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