Implemented the ability to create Magnum Cluster Type objects.
[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.config.image import ImageConfig
21 from snaps.config.network import NetworkConfig, SubnetConfig
22 from snaps.config.router import RouterConfig
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 = 'public'
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             'volume_api_version': config.get('OS_VOLUME_API_VERSION'),
103             'interface': interface,
104             'proxy_settings': proxy_settings,
105             'cacert': https_cacert,
106             'region_name': config.get('OS_REGION_NAME')}
107     else:
108         logger.info('Reading development os_env file - ' + dev_os_env_file)
109         config = file_utils.read_yaml(dev_os_env_file)
110
111         proxy_settings = None
112         proxy_str = config.get('http_proxy')
113         if proxy_str:
114             tokens = re.split(':', proxy_str)
115             proxy_settings = ProxySettings(
116                 host=tokens[0], port=tokens[1],
117                 ssh_proxy_cmd=config.get('ssh_proxy_cmd'))
118
119         creds_dict = {
120             'username': config['username'],
121             'password': config['password'],
122             'auth_url': config['os_auth_url'],
123             'project_name': config['project_name'],
124             'identity_api_version': config.get('identity_api_version'),
125             'image_api_version': config.get('image_api_version'),
126             'network_api_version': config.get('network_api_version'),
127             'compute_api_version': config.get('compute_api_version'),
128             'heat_api_version': config.get('heat_api_version'),
129             'user_domain_id': config.get('user_domain_id'),
130             'user_domain_name': config.get('user_domain_name'),
131             'project_domain_id': config.get('project_domain_id'),
132             'project_domain_name': config.get('project_domain_name'),
133             'volume_api_version': config.get('volume_api_version'),
134             'interface': config.get('interface'),
135             'proxy_settings': proxy_settings,
136             'cacert': config.get('cacert'),
137             'region_name': config.get('region_name')}
138
139     if overrides and isinstance(overrides, dict):
140         creds_dict.update(overrides)
141
142     os_creds = OSCreds(**creds_dict)
143     logger.info('OS Credentials = %s', os_creds.__str__)
144     return os_creds
145
146
147 def create_image_settings(image_name, image_user, image_format, metadata,
148                           disk_url=None, default_url=None,
149                           kernel_settings=None, ramdisk_settings=None,
150                           public=False, nic_config_pb_loc=None):
151     """
152     Returns the image settings object
153     :param image_name: the name of the image
154     :param image_user: the image's sudo user
155     :param image_format: the image's format string
156     :param metadata: custom metadata for overriding default behavior for test
157                      image settings
158     :param disk_url: the disk image's URL
159     :param default_url: the default URL for the disk image
160     :param kernel_settings: override to the kernel settings from the
161                             image_metadata
162     :param ramdisk_settings: override to the ramdisk settings from the
163                              image_metadata
164     :param public: True denotes image can be used by other projects where False
165                    indicates the converse (default: False)
166     :param nic_config_pb_loc: The location of the playbook used for configuring
167                               multiple NICs
168     :return:
169     """
170
171     logger.debug('Image metadata - ' + str(metadata))
172
173     if metadata and 'config' in metadata:
174         return ImageConfig(**metadata['config'])
175
176     disk_file = None
177     if metadata and ('disk_url' in metadata or 'disk_file' in metadata):
178         disk_url = metadata.get('disk_url')
179         disk_file = metadata.get('disk_file')
180     elif not disk_url:
181         disk_url = default_url
182
183     if (metadata
184             and ('kernel_file' in metadata or 'kernel_url' in metadata)
185             and kernel_settings is None):
186         kernel_image_settings = ImageConfig(
187             name=image_name + '-kernel', image_user=image_user,
188             img_format=image_format, image_file=metadata.get('kernel_file'),
189             url=metadata.get('kernel_url'), public=public)
190     else:
191         kernel_image_settings = kernel_settings
192
193     if (metadata
194             and ('ramdisk_file' in metadata or 'ramdisk_url' in metadata)
195             and ramdisk_settings is None):
196         ramdisk_image_settings = ImageConfig(
197             name=image_name + '-ramdisk', image_user=image_user,
198             img_format=image_format,
199             image_file=metadata.get('ramdisk_file'),
200             url=metadata.get('ramdisk_url'), public=public)
201     else:
202         ramdisk_image_settings = ramdisk_settings
203
204     extra_properties = None
205     if metadata and 'extra_properties' in metadata:
206         extra_properties = metadata['extra_properties']
207
208     return ImageConfig(name=image_name, image_user=image_user,
209                        img_format=image_format, image_file=disk_file,
210                        url=disk_url, extra_properties=extra_properties,
211                        kernel_image_settings=kernel_image_settings,
212                        ramdisk_image_settings=ramdisk_image_settings,
213                        public=public,
214                        nic_config_pb_loc=nic_config_pb_loc)
215
216
217 def cirros_image_settings(name=None, url=None, image_metadata=None,
218                           kernel_settings=None, ramdisk_settings=None,
219                           public=False):
220     """
221     Returns the image settings for a Cirros QCOW2 image
222     :param name: the name of the image
223     :param url: the image's URL
224     :param image_metadata: dict() values to override URLs for disk, kernel, and
225                            ramdisk
226     :param kernel_settings: override to the kernel settings from the
227                             image_metadata
228     :param ramdisk_settings: override to the ramdisk settings from the
229                              image_metadata
230     :param public: True denotes image can be used by other projects where False
231                    indicates the converse
232     :return:
233     """
234     if image_metadata and 'cirros' in image_metadata:
235         metadata = image_metadata['cirros']
236     else:
237         metadata = image_metadata
238
239     return create_image_settings(
240         image_name=name, image_user=CIRROS_USER,
241         image_format=DEFAULT_IMAGE_FORMAT, metadata=metadata, disk_url=url,
242         default_url=CIRROS_DEFAULT_IMAGE_URL,
243         kernel_settings=kernel_settings, ramdisk_settings=ramdisk_settings,
244         public=public)
245
246
247 def file_image_test_settings(name, file_path, image_user=CIRROS_USER):
248     return ImageConfig(name=name, image_user=image_user,
249                        img_format=DEFAULT_IMAGE_FORMAT, image_file=file_path)
250
251
252 def centos_image_settings(name, url=None, image_metadata=None,
253                           kernel_settings=None, ramdisk_settings=None,
254                           public=False):
255     """
256     Returns the image settings for a Centos QCOW2 image
257     :param name: the name of the image
258     :param url: the image's URL
259     :param image_metadata: dict() values to override URLs for disk, kernel, and
260                            ramdisk
261     :param kernel_settings: override to the kernel settings from the
262                             image_metadata
263     :param ramdisk_settings: override to the ramdisk settings from the
264                              image_metadata
265     :param public: True denotes image can be used by other projects where False
266                    indicates the converse
267     :return:
268     """
269     if image_metadata and 'centos' in image_metadata:
270         metadata = image_metadata['centos']
271     else:
272         metadata = image_metadata
273
274     pb_path = pkg_resources.resource_filename(
275         'snaps.provisioning.ansible_pb.centos-network-setup.playbooks',
276         'configure_host.yml')
277     return create_image_settings(
278         image_name=name, image_user=CENTOS_USER,
279         image_format=DEFAULT_IMAGE_FORMAT, metadata=metadata, disk_url=url,
280         default_url=CENTOS_DEFAULT_IMAGE_URL,
281         kernel_settings=kernel_settings, ramdisk_settings=ramdisk_settings,
282         public=public, nic_config_pb_loc=pb_path)
283
284
285 def ubuntu_image_settings(name, url=None, image_metadata=None,
286                           kernel_settings=None, ramdisk_settings=None,
287                           public=False):
288     """
289     Returns the image settings for a Ubuntu QCOW2 image
290     :param name: the name of the image
291     :param url: the image's URL
292     :param image_metadata: dict() values to override URLs for disk, kernel, and
293                            ramdisk
294     :param kernel_settings: override to the kernel settings from the
295                             image_metadata
296     :param ramdisk_settings: override to the ramdisk settings from the
297                              image_metadata
298     :param public: True denotes image can be used by other projects where False
299                    indicates the converse
300     :return:
301     """
302     if image_metadata and 'ubuntu' in image_metadata:
303         metadata = image_metadata['ubuntu']
304     else:
305         metadata = image_metadata
306
307     pb_path = pkg_resources.resource_filename(
308         'snaps.provisioning.ansible_pb.ubuntu-network-setup.playbooks',
309         'configure_host.yml')
310     return create_image_settings(
311         image_name=name, image_user=UBUNTU_USER,
312         image_format=DEFAULT_IMAGE_FORMAT, metadata=metadata, disk_url=url,
313         default_url=UBUNTU_DEFAULT_IMAGE_URL,
314         kernel_settings=kernel_settings, ramdisk_settings=ramdisk_settings,
315         public=public, nic_config_pb_loc=pb_path)
316
317
318 def get_priv_net_config(net_name, subnet_name, router_name=None,
319                         cidr='10.55.0.0/24', external_net=None):
320     return OSNetworkConfig(net_name, subnet_name, cidr, router_name,
321                            external_gateway=external_net)
322
323
324 def get_pub_net_config(net_name, subnet_name=None, router_name=None,
325                        cidr='10.55.1.0/24', external_net=None):
326     return OSNetworkConfig(net_name, subnet_name, cidr, router_name,
327                            external_gateway=external_net)
328
329
330 class OSNetworkConfig:
331     """
332     Represents the settings required for the creation of a network in OpenStack
333     """
334
335     def __init__(self, net_name, subnet_name=None, subnet_cidr=None,
336                  router_name=None, external_gateway=None):
337
338         if subnet_name and subnet_cidr:
339             self.network_settings = NetworkConfig(
340                 name=net_name, subnet_settings=[
341                     SubnetConfig(cidr=subnet_cidr, name=subnet_name)])
342         else:
343             self.network_settings = NetworkConfig(name=net_name)
344
345         if router_name:
346             if subnet_name:
347                 self.router_settings = RouterConfig(
348                     name=router_name, external_gateway=external_gateway,
349                     internal_subnets=[subnet_name])
350             else:
351                 self.router_settings = RouterConfig(
352                     name=router_name, external_gateway=external_gateway)