Merge "Fixed error in ansible_utils_tests.py and added ansible helper method to the...
[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 re
16
17 from snaps import file_utils
18 from snaps.openstack.utils import glance_utils
19 from snaps.openstack.create_network import NetworkSettings, SubnetSettings
20 from snaps.openstack.create_router import RouterSettings
21 from snaps.openstack.os_credentials import OSCreds, ProxySettings
22 from snaps.openstack.create_image import ImageSettings
23 import logging
24
25 __author__ = 'spisarski'
26
27
28 logger = logging.getLogger('openstack_tests')
29
30 CIRROS_DEFAULT_IMAGE_URL = 'http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-x86_64-disk.img'
31 CIRROS_DEFAULT_KERNEL_IMAGE_URL = 'http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-x86_64-kernel'
32 CIRROS_DEFAULT_RAMDISK_IMAGE_URL = 'http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-x86_64-initramfs'
33 CIRROS_USER = 'cirros'
34
35 CENTOS_DEFAULT_IMAGE_URL = 'http://cloud.centos.org/centos/7/images/CentOS-7-x86_64-GenericCloud.qcow2'
36 CENTOS_USER = 'centos'
37
38 UBUNTU_DEFAULT_IMAGE_URL =\
39     'http://uec-images.ubuntu.com/releases/trusty/14.04/ubuntu-14.04-server-cloudimg-amd64-disk1.img'
40 UBUNTU_USER = 'ubuntu'
41
42 DEFAULT_IMAGE_FORMAT = 'qcow2'
43
44
45 def get_credentials(os_env_file=None, proxy_settings_str=None, ssh_proxy_cmd=None, dev_os_env_file=None):
46     """
47     Returns the OpenStack credentials object. It first attempts to retrieve them from a standard OpenStack source file.
48     If that file is None, it will attempt to retrieve them with a YAML file.
49     it will retrieve them from a
50     :param os_env_file: the OpenStack source file
51     :param proxy_settings_str: proxy settings string <host>:<port> (optional)
52     :param ssh_proxy_cmd: the SSH proxy command for your environment (optional)
53     :param dev_os_env_file: the YAML file to retrieve both the OS credentials and proxy settings
54     :return: the SNAPS credentials object
55     """
56     if os_env_file:
57         logger.debug('Reading RC file - ' + os_env_file)
58         config = file_utils.read_os_env_file(os_env_file)
59         proj_name = config.get('OS_PROJECT_NAME')
60         if not proj_name:
61             proj_name = config.get('OS_TENANT_NAME')
62
63         proj_domain_id = 'default'
64         user_domain_id = 'default'
65
66         if config.get('OS_PROJECT_DOMAIN_ID'):
67             proj_domain_id = config['OS_PROJECT_DOMAIN_ID']
68         if config.get('OS_USER_DOMAIN_ID'):
69             user_domain_id = config['OS_USER_DOMAIN_ID']
70         if config.get('OS_IDENTITY_API_VERSION'):
71             version = int(config['OS_IDENTITY_API_VERSION'])
72         else:
73             version = 2
74
75         proxy_settings = None
76         if proxy_settings_str:
77             tokens = re.split(':', proxy_settings_str)
78             proxy_settings = ProxySettings(tokens[0], tokens[1], ssh_proxy_cmd)
79
80         os_creds = OSCreds(username=config['OS_USERNAME'],
81                            password=config['OS_PASSWORD'],
82                            auth_url=config['OS_AUTH_URL'],
83                            project_name=proj_name,
84                            identity_api_version=version,
85                            user_domain_id=user_domain_id,
86                            project_domain_id=proj_domain_id,
87                            proxy_settings=proxy_settings)
88     else:
89         logger.info('Reading development os_env file - ' + dev_os_env_file)
90         config = file_utils.read_yaml(dev_os_env_file)
91         identity_api_version = config.get('identity_api_version')
92         if not identity_api_version:
93             identity_api_version = 2
94
95         image_api_version = config.get('image_api_version')
96         if not image_api_version:
97             image_api_version = glance_utils.VERSION_2
98
99         proxy_settings = None
100         proxy_str = config.get('http_proxy')
101         if proxy_str:
102             tokens = re.split(':', proxy_str)
103             proxy_settings = ProxySettings(tokens[0], tokens[1], config.get('ssh_proxy_cmd'))
104
105         os_creds = OSCreds(username=config['username'], password=config['password'],
106                            auth_url=config['os_auth_url'], project_name=config['project_name'],
107                            identity_api_version=identity_api_version, image_api_version=image_api_version,
108                            proxy_settings=proxy_settings)
109
110     logger.info('OS Credentials = ' + str(os_creds))
111     return os_creds
112
113
114 def create_image_settings(image_name, image_user, image_format, metadata, disk_url=None, default_url=None,
115                           kernel_settings=None, ramdisk_settings=None, public=False):
116     """
117     Returns the image settings object
118     :param image_name: the name of the image
119     :param image_user: the image's sudo user
120     :param image_format: the image's format string
121     :param metadata: custom metadata for overriding default behavior for test image settings
122     :param disk_url: the disk image's URL
123     :param default_url: the default URL for the disk image
124     :param kernel_settings: override to the kernel settings from the image_metadata
125     :param ramdisk_settings: override to the ramdisk settings from the image_metadata
126     :param public: True denotes image can be used by other projects where False indicates the converse (default: False)
127     :return:
128     """
129
130     logger.debug('Image metadata - ' + str(metadata))
131
132     if metadata and 'config' in metadata:
133         return ImageSettings(config=metadata['config'])
134
135     disk_file = None
136     if metadata:
137         disk_url = metadata.get('disk_url')
138         disk_file = metadata.get('disk_file')
139     elif not disk_url:
140         disk_url = default_url
141     else:
142         disk_url = disk_url
143
144     if metadata and ('kernel_file' in metadata or 'kernel_url' in metadata) and kernel_settings is None:
145         kernel_image_settings = ImageSettings(
146             name=image_name + '-kernel', image_user=image_user, img_format=image_format,
147             image_file=metadata.get('kernel_file'), url=metadata.get('kernel_url'), public=public)
148     else:
149         kernel_image_settings = kernel_settings
150
151     if metadata and ('ramdisk_file' in metadata or 'ramdisk_url' in metadata) and ramdisk_settings is None:
152         ramdisk_image_settings = ImageSettings(
153             name=image_name + '-ramdisk', image_user=image_user, img_format=image_format,
154             image_file=metadata.get('ramdisk_file'), url=metadata.get('ramdisk_url'), public=public)
155     else:
156         ramdisk_image_settings = ramdisk_settings
157
158     extra_properties = None
159     if metadata and 'extra_properties' in metadata:
160         extra_properties = metadata['extra_properties']
161
162     return ImageSettings(name=image_name, image_user=image_user, img_format=image_format, image_file=disk_file,
163                          url=disk_url, extra_properties=extra_properties, kernel_image_settings=kernel_image_settings,
164                          ramdisk_image_settings=ramdisk_image_settings, public=public)
165
166
167 def cirros_image_settings(name=None, url=None, image_metadata=None, kernel_settings=None, ramdisk_settings=None,
168                           public=False):
169     """
170     Returns the image settings for a Cirros QCOW2 image
171     :param name: the name of the image
172     :param url: the image's URL
173     :param image_metadata: dict() values to override URLs for disk, kernel, and ramdisk
174     :param kernel_settings: override to the kernel settings from the image_metadata
175     :param ramdisk_settings: override to the ramdisk settings from the image_metadata
176     :param public: True denotes image can be used by other projects where False indicates the converse
177     :return:
178     """
179     if image_metadata and 'cirros' in image_metadata:
180         metadata = image_metadata['cirros']
181     else:
182         metadata = image_metadata
183
184     return create_image_settings(
185         image_name=name, image_user=CIRROS_USER, image_format=DEFAULT_IMAGE_FORMAT, metadata=metadata, disk_url=url,
186         default_url=CIRROS_DEFAULT_IMAGE_URL,
187         kernel_settings=kernel_settings, ramdisk_settings=ramdisk_settings, public=public)
188
189
190 def file_image_test_settings(name, file_path, image_user=CIRROS_USER):
191     return ImageSettings(name=name, image_user=image_user, img_format=DEFAULT_IMAGE_FORMAT, image_file=file_path)
192
193
194 def centos_image_settings(name, url=None, image_metadata=None, kernel_settings=None, ramdisk_settings=None,
195                           public=False):
196     """
197     Returns the image settings for a Centos QCOW2 image
198     :param name: the name of the image
199     :param url: the image's URL
200     :param image_metadata: dict() values to override URLs for disk, kernel, and ramdisk
201     :param kernel_settings: override to the kernel settings from the image_metadata
202     :param ramdisk_settings: override to the ramdisk settings from the image_metadata
203     :param public: True denotes image can be used by other projects where False indicates the converse
204     :return:
205     """
206     if image_metadata and 'centos' in image_metadata:
207         metadata = image_metadata['centos']
208     else:
209         metadata = image_metadata
210
211     return create_image_settings(
212         image_name=name, image_user=CENTOS_USER, image_format=DEFAULT_IMAGE_FORMAT, metadata=metadata, disk_url=url,
213         default_url=CENTOS_DEFAULT_IMAGE_URL,
214         kernel_settings=kernel_settings, ramdisk_settings=ramdisk_settings, public=public)
215
216
217 def ubuntu_image_settings(name, url=None, image_metadata=None, kernel_settings=None, ramdisk_settings=None,
218                           public=False):
219     """
220     Returns the image settings for a Ubuntu 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 ramdisk
224     :param kernel_settings: override to the kernel settings from the image_metadata
225     :param ramdisk_settings: override to the ramdisk settings from the image_metadata
226     :param public: True denotes image can be used by other projects where False indicates the converse
227     :return:
228     """
229     if image_metadata and 'ubuntu' in image_metadata:
230         metadata = image_metadata['ubuntu']
231     else:
232         metadata = image_metadata
233
234     return create_image_settings(
235         image_name=name, image_user=UBUNTU_USER, image_format=DEFAULT_IMAGE_FORMAT, metadata=metadata, disk_url=url,
236         default_url=UBUNTU_DEFAULT_IMAGE_URL,
237         kernel_settings=kernel_settings, ramdisk_settings=ramdisk_settings, public=public)
238
239
240 def get_priv_net_config(net_name, subnet_name, router_name=None, cidr='10.55.0.0/24', external_net=None):
241     return OSNetworkConfig(net_name, subnet_name, cidr, router_name, external_gateway=external_net)
242
243
244 def get_pub_net_config(net_name, subnet_name=None, router_name=None, cidr='10.55.1.0/24', external_net=None):
245     return OSNetworkConfig(net_name, subnet_name, cidr, router_name, external_gateway=external_net)
246
247
248 class OSNetworkConfig:
249     """
250     Represents the settings required for the creation of a network in OpenStack
251     """
252
253     def __init__(self, net_name, subnet_name=None, subnet_cidr=None, router_name=None, external_gateway=None):
254
255         if subnet_name and subnet_cidr:
256             self.network_settings = NetworkSettings(
257                 name=net_name, subnet_settings=[SubnetSettings(cidr=subnet_cidr, name=subnet_name)])
258         else:
259             self.network_settings = NetworkSettings(name=net_name)
260
261         if router_name:
262             if subnet_name:
263                 self.router_settings = RouterSettings(name=router_name, external_gateway=external_gateway,
264                                                       internal_subnets=[subnet_name])
265             else:
266                 self.router_settings = RouterSettings(name=router_name, external_gateway=external_gateway)