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