2dab75cf4e6f3f4c58f2eb07b73f17f6a2f5341f
[snaps.git] / snaps / openstack / tests / openstack_tests.py
1 # Copyright (c) 2017 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 import logging
16 import re
17
18 import pkg_resources
19 from snaps import file_utils
20 from snaps.openstack.create_image import ImageSettings
21 from snaps.openstack.create_network import NetworkSettings, SubnetSettings
22 from snaps.openstack.create_router import RouterSettings
23 from snaps.openstack.os_credentials import OSCreds, ProxySettings
24
25 __author__ = 'spisarski'
26
27 logger = logging.getLogger('openstack_tests')
28
29 CIRROS_DEFAULT_IMAGE_URL =\
30     'http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-x86_64-disk.img'
31 CIRROS_DEFAULT_KERNEL_IMAGE_URL =\
32     'http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-x86_64-kernel'
33 CIRROS_DEFAULT_RAMDISK_IMAGE_URL =\
34     'http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-x86_64-initramfs'
35 CIRROS_USER = 'cirros'
36
37 CENTOS_DEFAULT_IMAGE_URL =\
38     'http://cloud.centos.org/centos/7/images/' \
39     'CentOS-7-x86_64-GenericCloud.qcow2'
40 CENTOS_USER = 'centos'
41
42 UBUNTU_DEFAULT_IMAGE_URL = \
43     'http://uec-images.ubuntu.com/releases/trusty/14.04/' \
44     'ubuntu-14.04-server-cloudimg-amd64-disk1.img'
45 UBUNTU_USER = 'ubuntu'
46
47 DEFAULT_IMAGE_FORMAT = 'qcow2'
48
49
50 def get_credentials(os_env_file=None, proxy_settings_str=None,
51                     ssh_proxy_cmd=None, dev_os_env_file=None, overrides=None):
52     """
53     Returns the OpenStack credentials object. It first attempts to retrieve
54     them from a standard OpenStack source file. If that file is None, it will
55     attempt to retrieve them with a YAML file.
56     :param os_env_file: the OpenStack source file
57     :param proxy_settings_str: proxy settings string <host>:<port> (optional)
58     :param ssh_proxy_cmd: the SSH proxy command for your environment (optional)
59     :param dev_os_env_file: the YAML file to retrieve both the OS credentials
60                             and proxy settings
61     :param overrides: dict() containing values to override the credentials
62                       found and passed in.
63     :return: the SNAPS credentials object
64     """
65     if os_env_file:
66         logger.debug('Reading RC file - ' + os_env_file)
67         config = file_utils.read_os_env_file(os_env_file)
68         proj_name = config.get('OS_PROJECT_NAME')
69         if not proj_name:
70             proj_name = config.get('OS_TENANT_NAME')
71
72         proxy_settings = None
73         if proxy_settings_str:
74             tokens = re.split(':', proxy_settings_str)
75             proxy_settings = ProxySettings(host=tokens[0], port=tokens[1],
76                                            ssh_proxy_cmd=ssh_proxy_cmd)
77
78         https_cacert = None
79         if config.get('OS_CACERT'):
80             https_cacert = config.get('OS_CACERT')
81         elif config.get('OS_INSECURE'):
82             https_cacert = False
83
84         interface = 'admin'
85         if config.get('OS_INTERFACE'):
86             interface = config.get('OS_INTERFACE')
87
88         creds_dict = {
89             'username': config['OS_USERNAME'],
90             'password': config['OS_PASSWORD'],
91             'auth_url': config['OS_AUTH_URL'],
92             'project_name': proj_name,
93             'identity_api_version': config.get('OS_IDENTITY_API_VERSION'),
94             'image_api_version': config.get('OS_IMAGE_API_VERSION'),
95             'network_api_version': config.get('OS_NETWORK_API_VERSION'),
96             'compute_api_version': config.get('OS_COMPUTE_API_VERSION'),
97             'heat_api_version': config.get('OS_HEAT_API_VERSION'),
98             'user_domain_id': config.get('OS_USER_DOMAIN_ID'),
99             'user_domain_name': config.get('OS_USER_DOMAIN_NAME'),
100             'project_domain_id': config.get('OS_PROJECT_DOMAIN_ID'),
101             'project_domain_name': config.get('OS_PROJECT_DOMAIN_NAME'),
102             'interface': interface,
103             'proxy_settings': proxy_settings,
104             'cacert': https_cacert,
105             'region_name': config.get('OS_REGION_NAME')}
106     else:
107         logger.info('Reading development os_env file - ' + dev_os_env_file)
108         config = file_utils.read_yaml(dev_os_env_file)
109
110         proxy_settings = None
111         proxy_str = config.get('http_proxy')
112         if proxy_str:
113             tokens = re.split(':', proxy_str)
114             proxy_settings = ProxySettings(
115                 host=tokens[0], port=tokens[1],
116                 ssh_proxy_cmd=config.get('ssh_proxy_cmd'))
117
118         creds_dict = {
119             'username': config['username'],
120             'password': config['password'],
121             'auth_url': config['os_auth_url'],
122             'project_name': config['project_name'],
123             'identity_api_version': config.get('identity_api_version'),
124             'image_api_version': config.get('image_api_version'),
125             'network_api_version': config.get('network_api_version'),
126             'compute_api_version': config.get('compute_api_version'),
127             'heat_api_version': config.get('heat_api_version'),
128             'user_domain_id': config.get('user_domain_id'),
129             'project_domain_id': config.get('project_domain_id'),
130             'interface': config.get('interface'),
131             'proxy_settings': proxy_settings,
132             'cacert': config.get('cacert'),
133             'region_name': config.get('region_name')}
134
135     if overrides and isinstance(overrides, dict):
136         creds_dict.update(overrides)
137
138     os_creds = OSCreds(**creds_dict)
139     logger.info('OS Credentials = %s', os_creds)
140     return os_creds
141
142
143 def create_image_settings(image_name, image_user, image_format, metadata,
144                           disk_url=None, default_url=None,
145                           kernel_settings=None, ramdisk_settings=None,
146                           public=False, nic_config_pb_loc=None):
147     """
148     Returns the image settings object
149     :param image_name: the name of the image
150     :param image_user: the image's sudo user
151     :param image_format: the image's format string
152     :param metadata: custom metadata for overriding default behavior for test
153                      image settings
154     :param disk_url: the disk image's URL
155     :param default_url: the default URL for the disk image
156     :param kernel_settings: override to the kernel settings from the
157                             image_metadata
158     :param ramdisk_settings: override to the ramdisk settings from the
159                              image_metadata
160     :param public: True denotes image can be used by other projects where False
161                    indicates the converse (default: False)
162     :param nic_config_pb_loc: The location of the playbook used for configuring
163                               multiple NICs
164     :return:
165     """
166
167     logger.debug('Image metadata - ' + str(metadata))
168
169     if metadata and 'config' in metadata:
170         return ImageSettings(**metadata['config'])
171
172     disk_file = None
173     if metadata:
174         disk_url = metadata.get('disk_url')
175         disk_file = metadata.get('disk_file')
176     elif not disk_url:
177         disk_url = default_url
178     else:
179         disk_url = disk_url
180
181     if metadata and \
182             ('kernel_file' in metadata or 'kernel_url' in metadata) and \
183             kernel_settings is None:
184         kernel_image_settings = ImageSettings(
185             name=image_name + '-kernel', image_user=image_user,
186             img_format=image_format,
187             image_file=metadata.get('kernel_file'),
188             url=metadata.get('kernel_url'), public=public)
189     else:
190         kernel_image_settings = kernel_settings
191
192     if metadata and \
193             ('ramdisk_file' in metadata or 'ramdisk_url' in metadata) and \
194             ramdisk_settings is None:
195         ramdisk_image_settings = ImageSettings(
196             name=image_name + '-ramdisk', image_user=image_user,
197             img_format=image_format,
198             image_file=metadata.get('ramdisk_file'),
199             url=metadata.get('ramdisk_url'), public=public)
200     else:
201         ramdisk_image_settings = ramdisk_settings
202
203     extra_properties = None
204     if metadata and 'extra_properties' in metadata:
205         extra_properties = metadata['extra_properties']
206
207     return ImageSettings(name=image_name, image_user=image_user,
208                          img_format=image_format, image_file=disk_file,
209                          url=disk_url, extra_properties=extra_properties,
210                          kernel_image_settings=kernel_image_settings,
211                          ramdisk_image_settings=ramdisk_image_settings,
212                          public=public,
213                          nic_config_pb_loc=nic_config_pb_loc)
214
215
216 def cirros_image_settings(name=None, url=None, image_metadata=None,
217                           kernel_settings=None, ramdisk_settings=None,
218                           public=False):
219     """
220     Returns the image settings for a Cirros QCOW2 image
221     :param name: the name of the image
222     :param url: the image's URL
223     :param image_metadata: dict() values to override URLs for disk, kernel, and
224                            ramdisk
225     :param kernel_settings: override to the kernel settings from the
226                             image_metadata
227     :param ramdisk_settings: override to the ramdisk settings from the
228                              image_metadata
229     :param public: True denotes image can be used by other projects where False
230                    indicates the converse
231     :return:
232     """
233     if image_metadata and 'cirros' in image_metadata:
234         metadata = image_metadata['cirros']
235     else:
236         metadata = image_metadata
237
238     return create_image_settings(
239         image_name=name, image_user=CIRROS_USER,
240         image_format=DEFAULT_IMAGE_FORMAT, metadata=metadata, disk_url=url,
241         default_url=CIRROS_DEFAULT_IMAGE_URL,
242         kernel_settings=kernel_settings, ramdisk_settings=ramdisk_settings,
243         public=public)
244
245
246 def file_image_test_settings(name, file_path, image_user=CIRROS_USER):
247     return ImageSettings(name=name, image_user=image_user,
248                          img_format=DEFAULT_IMAGE_FORMAT, image_file=file_path)
249
250
251 def centos_image_settings(name, url=None, image_metadata=None,
252                           kernel_settings=None, ramdisk_settings=None,
253                           public=False):
254     """
255     Returns the image settings for a Centos QCOW2 image
256     :param name: the name of the image
257     :param url: the image's URL
258     :param image_metadata: dict() values to override URLs for disk, kernel, and
259                            ramdisk
260     :param kernel_settings: override to the kernel settings from the
261                             image_metadata
262     :param ramdisk_settings: override to the ramdisk settings from the
263                              image_metadata
264     :param public: True denotes image can be used by other projects where False
265                    indicates the converse
266     :return:
267     """
268     if image_metadata and 'centos' in image_metadata:
269         metadata = image_metadata['centos']
270     else:
271         metadata = image_metadata
272
273     pb_path = pkg_resources.resource_filename(
274         'snaps.provisioning.ansible_pb.centos-network-setup.playbooks',
275         'configure_host.yml')
276     return create_image_settings(
277         image_name=name, image_user=CENTOS_USER,
278         image_format=DEFAULT_IMAGE_FORMAT, metadata=metadata, disk_url=url,
279         default_url=CENTOS_DEFAULT_IMAGE_URL,
280         kernel_settings=kernel_settings, ramdisk_settings=ramdisk_settings,
281         public=public, nic_config_pb_loc=pb_path)
282
283
284 def ubuntu_image_settings(name, url=None, image_metadata=None,
285                           kernel_settings=None, ramdisk_settings=None,
286                           public=False):
287     """
288     Returns the image settings for a Ubuntu QCOW2 image
289     :param name: the name of the image
290     :param url: the image's URL
291     :param image_metadata: dict() values to override URLs for disk, kernel, and
292                            ramdisk
293     :param kernel_settings: override to the kernel settings from the
294                             image_metadata
295     :param ramdisk_settings: override to the ramdisk settings from the
296                              image_metadata
297     :param public: True denotes image can be used by other projects where False
298                    indicates the converse
299     :return:
300     """
301     if image_metadata and 'ubuntu' in image_metadata:
302         metadata = image_metadata['ubuntu']
303     else:
304         metadata = image_metadata
305
306     pb_path = pkg_resources.resource_filename(
307         'snaps.provisioning.ansible_pb.ubuntu-network-setup.playbooks',
308         'configure_host.yml')
309     return create_image_settings(
310         image_name=name, image_user=UBUNTU_USER,
311         image_format=DEFAULT_IMAGE_FORMAT, metadata=metadata, disk_url=url,
312         default_url=UBUNTU_DEFAULT_IMAGE_URL,
313         kernel_settings=kernel_settings, ramdisk_settings=ramdisk_settings,
314         public=public, nic_config_pb_loc=pb_path)
315
316
317 def get_priv_net_config(net_name, subnet_name, router_name=None,
318                         cidr='10.55.0.0/24', external_net=None):
319     return OSNetworkConfig(net_name, subnet_name, cidr, router_name,
320                            external_gateway=external_net)
321
322
323 def get_pub_net_config(net_name, subnet_name=None, router_name=None,
324                        cidr='10.55.1.0/24', external_net=None):
325     return OSNetworkConfig(net_name, subnet_name, cidr, router_name,
326                            external_gateway=external_net)
327
328
329 class OSNetworkConfig:
330     """
331     Represents the settings required for the creation of a network in OpenStack
332     """
333
334     def __init__(self, net_name, subnet_name=None, subnet_cidr=None,
335                  router_name=None, external_gateway=None):
336
337         if subnet_name and subnet_cidr:
338             self.network_settings = NetworkSettings(
339                 name=net_name, subnet_settings=[
340                     SubnetSettings(cidr=subnet_cidr, name=subnet_name)])
341         else:
342             self.network_settings = NetworkSettings(name=net_name)
343
344         if router_name:
345             if subnet_name:
346                 self.router_settings = RouterSettings(
347                     name=router_name, external_gateway=external_gateway,
348                     internal_subnets=[subnet_name])
349             else:
350                 self.router_settings = RouterSettings(
351                     name=router_name, external_gateway=external_gateway)