Added the ability to give the tests the ability to add in flavor metadata.
[snaps.git] / snaps / provisioning / tests / ansible_utils_tests.py
1 # Copyright (c) 2016 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import os
17 import uuid
18
19 from snaps.openstack import create_instance
20 from snaps.openstack import create_keypairs
21 from snaps.openstack import create_network
22 from snaps.openstack import create_router
23 from snaps.openstack import create_image
24 from snaps.openstack import create_flavor
25 from scp import SCPClient
26
27 from snaps.provisioning import ansible_utils
28 from snaps.openstack.tests import openstack_tests
29 from snaps.openstack.tests.os_source_file_test import OSIntegrationTestCase
30
31 VM_BOOT_TIMEOUT = 600
32
33 ip_1 = '10.0.1.100'
34 ip_2 = '10.0.1.200'
35
36
37 class AnsibleProvisioningTests(OSIntegrationTestCase):
38     """
39     Test for the CreateInstance class with two NIC/Ports, eth0 with floating IP and eth1 w/o
40     """
41
42     def setUp(self):
43         """
44         Instantiates the CreateImage object that is responsible for downloading and creating an OS image file
45         within OpenStack
46         """
47         super(self.__class__, self).__start__()
48
49         guid = self.__class__.__name__ + '-' + str(uuid.uuid4())
50         self.keypair_priv_filepath = 'tmp/' + guid
51         self.keypair_pub_filepath = self.keypair_priv_filepath + '.pub'
52         self.keypair_name = guid + '-kp'
53         self.vm_inst_name = guid + '-inst'
54         self.test_file_local_path = 'tmp/' + guid + '-hello.txt'
55         self.port_1_name = guid + '-port-1'
56         self.port_2_name = guid + '-port-2'
57         self.floating_ip_name = guid + 'fip1'
58
59         # Setup members to cleanup just in case they don't get created
60         self.inst_creator = None
61         self.keypair_creator = None
62         self.flavor_creator = None
63         self.router_creator = None
64         self.network_creator = None
65         self.image_creator = None
66
67         try:
68             # Create Image
69             os_image_settings = openstack_tests.ubuntu_url_image(name=guid + '-' + '-image')
70             self.image_creator = create_image.OpenStackImage(self.os_creds, os_image_settings)
71             self.image_creator.create()
72
73             # First network is public
74             self.pub_net_config = openstack_tests.get_pub_net_config(
75                 net_name=guid + '-pub-net', subnet_name=guid + '-pub-subnet',
76                 router_name=guid + '-pub-router', external_net=self.ext_net_name)
77
78             self.network_creator = create_network.OpenStackNetwork(self.os_creds, self.pub_net_config.network_settings)
79             self.network_creator.create()
80
81             # Create routers
82             self.router_creator = create_router.OpenStackRouter(self.os_creds, self.pub_net_config.router_settings)
83             self.router_creator.create()
84
85             # Create Flavor
86             self.flavor_creator = create_flavor.OpenStackFlavor(
87                 self.admin_os_creds,
88                 create_flavor.FlavorSettings(name=guid + '-flavor-name', ram=2048, disk=10, vcpus=2,
89                                              metadata=self.flavor_metadata))
90             self.flavor_creator.create()
91
92             # Create Key/Pair
93             self.keypair_creator = create_keypairs.OpenStackKeypair(
94                 self.os_creds, create_keypairs.KeypairSettings(
95                     name=self.keypair_name, public_filepath=self.keypair_pub_filepath,
96                     private_filepath=self.keypair_priv_filepath))
97             self.keypair_creator.create()
98
99             # Create instance
100             ports_settings = list()
101             ports_settings.append(
102                 create_network.PortSettings(name=self.port_1_name,
103                                             network_name=self.pub_net_config.network_settings.name))
104
105             instance_settings = create_instance.VmInstanceSettings(
106                 name=self.vm_inst_name, flavor=self.flavor_creator.flavor_settings.name, port_settings=ports_settings,
107                 floating_ip_settings=[create_instance.FloatingIpSettings(
108                     name=self.floating_ip_name, port_name=self.port_1_name,
109                     router_name=self.pub_net_config.router_settings.name)])
110
111             self.inst_creator = create_instance.OpenStackVmInstance(
112                 self.os_creds, instance_settings, self.image_creator.image_settings,
113                 keypair_settings=self.keypair_creator.keypair_settings)
114         except Exception as e:
115             self.tearDown()
116             raise Exception(e.message)
117
118     def tearDown(self):
119         """
120         Cleans the created objects
121         """
122         if self.inst_creator:
123             self.inst_creator.clean()
124
125         if self.keypair_creator:
126             self.keypair_creator.clean()
127
128         if self.flavor_creator:
129             self.flavor_creator.clean()
130
131         if os.path.isfile(self.keypair_pub_filepath):
132             os.remove(self.keypair_pub_filepath)
133
134         if os.path.isfile(self.keypair_priv_filepath):
135             os.remove(self.keypair_priv_filepath)
136
137         if self.router_creator:
138             self.router_creator.clean()
139
140         if self.network_creator:
141             self.network_creator.clean()
142
143         if self.image_creator:
144             self.image_creator.clean()
145
146         if os.path.isfile(self.test_file_local_path):
147             os.remove(self.test_file_local_path)
148
149         super(self.__class__, self).__clean__()
150
151     def test_apply_simple_playbook(self):
152         """
153         Tests application of an Ansible playbook that simply copies over a file:
154         1. Have a ~/.ansible.cfg (or alternate means) to set host_key_checking = False
155         2. Set the following environment variable in your executing shell: ANSIBLE_HOST_KEY_CHECKING=False
156         Should this not be performed, the creation of the host ssh key will cause your ansible calls to fail.
157         """
158         self.inst_creator.create(block=True)
159
160         # Block until VM's ssh port has been opened
161         self.assertTrue(self.inst_creator.vm_ssh_active(block=True))
162
163         ssh_client = self.inst_creator.ssh_client()
164         self.assertIsNotNone(ssh_client)
165         out = ssh_client.exec_command('pwd')[1].channel.in_buffer.read(1024)
166         self.assertIsNotNone(out)
167         self.assertGreater(len(out), 1)
168
169         # Need to use the first floating IP as subsequent ones are currently broken with Apex CO
170         ip = self.inst_creator.get_floating_ip().ip
171         user = self.inst_creator.get_image_user()
172         priv_key = self.inst_creator.keypair_settings.private_filepath
173
174         retval = ansible_utils.apply_playbook('provisioning/tests/playbooks/simple_playbook.yml', [ip], user, priv_key,
175                                               proxy_setting=self.os_creds.proxy_settings)
176         self.assertEquals(0, retval)
177
178         ssh = ansible_utils.ssh_client(ip, user, priv_key, self.os_creds.proxy_settings)
179         self.assertIsNotNone(ssh)
180         scp = SCPClient(ssh.get_transport())
181         scp.get('~/hello.txt', self.test_file_local_path)
182
183         self.assertTrue(os.path.isfile(self.test_file_local_path))
184
185         with open(self.test_file_local_path) as f:
186             file_contents = f.readline()
187             self.assertEquals('Hello World!', file_contents)
188
189     def test_apply_template_playbook(self):
190         """
191         Tests application of an Ansible playbook that applies a template to a file:
192         1. Have a ~/.ansible.cfg (or alternate means) to set host_key_checking = False
193         2. Set the following environment variable in your executing shell: ANSIBLE_HOST_KEY_CHECKING=False
194         Should this not be performed, the creation of the host ssh key will cause your ansible calls to fail.
195         """
196         self.inst_creator.create(block=True)
197
198         # Block until VM's ssh port has been opened
199         self.assertTrue(self.inst_creator.vm_ssh_active(block=True))
200
201         # Need to use the first floating IP as subsequent ones are currently broken with Apex CO
202         ip = self.inst_creator.get_floating_ip().ip
203         user = self.inst_creator.get_image_user()
204         priv_key = self.inst_creator.keypair_settings.private_filepath
205
206         ansible_utils.apply_playbook('provisioning/tests/playbooks/template_playbook.yml', [ip], user, priv_key,
207                                      variables={'name': 'Foo'}, proxy_setting=self.os_creds.proxy_settings)
208
209         ssh = ansible_utils.ssh_client(ip, user, priv_key, self.os_creds.proxy_settings)
210         self.assertIsNotNone(ssh)
211         scp = SCPClient(ssh.get_transport())
212         scp.get('/tmp/hello.txt', self.test_file_local_path)
213
214         self.assertTrue(os.path.isfile(self.test_file_local_path))
215
216         with open(self.test_file_local_path) as f:
217             file_contents = f.readline()
218             self.assertEquals('Hello Foo!', file_contents)