Merge "Switch to blocking: false for ODL in functest-smoke"
[functest.git] / functest / opnfv_tests / openstack / tempest / conf_utils.py
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2015 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 import ConfigParser
11 import logging
12 import os
13 import pkg_resources
14 import shutil
15 import subprocess
16
17 import yaml
18
19 from functest.utils.constants import CONST
20 import functest.utils.functest_utils as ft_utils
21 import functest.utils.openstack_utils as os_utils
22
23
24 IMAGE_ID_ALT = None
25 FLAVOR_ID_ALT = None
26 GLANCE_IMAGE_PATH = os.path.join(
27     CONST.__getattribute__('dir_functest_images'),
28     CONST.__getattribute__('openstack_image_file_name'))
29 TEMPEST_RESULTS_DIR = os.path.join(CONST.__getattribute__('dir_results'),
30                                    'tempest')
31 TEMPEST_CUSTOM = pkg_resources.resource_filename(
32     'functest', 'opnfv_tests/openstack/tempest/custom_tests/test_list.txt')
33 TEMPEST_BLACKLIST = pkg_resources.resource_filename(
34     'functest', 'opnfv_tests/openstack/tempest/custom_tests/blacklist.txt')
35 TEMPEST_DEFCORE = pkg_resources.resource_filename(
36     'functest',
37     'opnfv_tests/openstack/tempest/custom_tests/defcore_req.txt')
38 TEMPEST_RAW_LIST = os.path.join(TEMPEST_RESULTS_DIR, 'test_raw_list.txt')
39 TEMPEST_LIST = os.path.join(TEMPEST_RESULTS_DIR, 'test_list.txt')
40 REFSTACK_RESULTS_DIR = os.path.join(CONST.__getattribute__('dir_results'),
41                                     'refstack')
42 TEMPEST_CONF_YAML = pkg_resources.resource_filename(
43     'functest', 'opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml')
44
45 CI_INSTALLER_TYPE = CONST.__getattribute__('INSTALLER_TYPE')
46 CI_INSTALLER_IP = CONST.__getattribute__('INSTALLER_IP')
47
48 """ logging configuration """
49 logger = logging.getLogger(__name__)
50
51
52 def create_tempest_resources(use_custom_images=False,
53                              use_custom_flavors=False):
54     keystone_client = os_utils.get_keystone_client()
55
56     logger.debug("Creating tenant and user for Tempest suite")
57     tenant_id = os_utils.create_tenant(
58         keystone_client,
59         CONST.__getattribute__('tempest_identity_tenant_name'),
60         CONST.__getattribute__('tempest_identity_tenant_description'))
61     if not tenant_id:
62         logger.error("Failed to create %s tenant"
63                      % CONST.__getattribute__('tempest_identity_tenant_name'))
64
65     user_id = os_utils.create_user(
66         keystone_client,
67         CONST.__getattribute__('tempest_identity_user_name'),
68         CONST.__getattribute__('tempest_identity_user_password'),
69         None, tenant_id)
70     if not user_id:
71         logger.error("Failed to create %s user" %
72                      CONST.__getattribute__('tempest_identity_user_name'))
73
74     logger.debug("Creating private network for Tempest suite")
75     network_dic = os_utils.create_shared_network_full(
76         CONST.__getattribute__('tempest_private_net_name'),
77         CONST.__getattribute__('tempest_private_subnet_name'),
78         CONST.__getattribute__('tempest_router_name'),
79         CONST.__getattribute__('tempest_private_subnet_cidr'))
80     if network_dic is None:
81         raise Exception('Failed to create private network')
82
83     image_id = ""
84     image_id_alt = ""
85     flavor_id = ""
86     flavor_id_alt = ""
87
88     if (CONST.__getattribute__('tempest_use_custom_images') or
89        use_custom_images):
90         # adding alternative image should be trivial should we need it
91         logger.debug("Creating image for Tempest suite")
92         _, image_id = os_utils.get_or_create_image(
93             CONST.__getattribute__('openstack_image_name'),
94             GLANCE_IMAGE_PATH,
95             CONST.__getattribute__('openstack_image_disk_format'))
96         if image_id is None:
97             raise Exception('Failed to create image')
98
99     if use_custom_images:
100         logger.debug("Creating 2nd image for Tempest suite")
101         _, image_id_alt = os_utils.get_or_create_image(
102             CONST.__getattribute__('openstack_image_name_alt'),
103             GLANCE_IMAGE_PATH,
104             CONST.__getattribute__('openstack_image_disk_format'))
105         if image_id_alt is None:
106             raise Exception('Failed to create image')
107
108     if (CONST.__getattribute__('tempest_use_custom_flavors') or
109        use_custom_flavors):
110         # adding alternative flavor should be trivial should we need it
111         logger.debug("Creating flavor for Tempest suite")
112         _, flavor_id = os_utils.get_or_create_flavor(
113             CONST.__getattribute__('openstack_flavor_name'),
114             CONST.__getattribute__('openstack_flavor_ram'),
115             CONST.__getattribute__('openstack_flavor_disk'),
116             CONST.__getattribute__('openstack_flavor_vcpus'))
117         if flavor_id is None:
118             raise Exception('Failed to create flavor')
119
120     if use_custom_flavors:
121         logger.debug("Creating 2nd flavor for tempest_defcore")
122         _, flavor_id_alt = os_utils.get_or_create_flavor(
123             CONST.__getattribute__('openstack_flavor_name_alt'),
124             CONST.__getattribute__('openstack_flavor_ram'),
125             CONST.__getattribute__('openstack_flavor_disk'),
126             CONST.__getattribute__('openstack_flavor_vcpus'))
127         if flavor_id_alt is None:
128             raise Exception('Failed to create flavor')
129
130     img_flavor_dict = {}
131     img_flavor_dict['image_id'] = image_id
132     img_flavor_dict['image_id_alt'] = image_id_alt
133     img_flavor_dict['flavor_id'] = flavor_id
134     img_flavor_dict['flavor_id_alt'] = flavor_id_alt
135
136     return img_flavor_dict
137
138
139 def get_verifier_id():
140     """
141     Returns verifer id for current Tempest
142     """
143     cmd = ("rally verify list-verifiers | awk '/" +
144            CONST.__getattribute__('tempest_deployment_name') +
145            "/ {print $2}'")
146     p = subprocess.Popen(cmd, shell=True,
147                          stdout=subprocess.PIPE,
148                          stderr=subprocess.STDOUT)
149     deployment_uuid = p.stdout.readline().rstrip()
150     if deployment_uuid == "":
151         logger.error("Tempest verifier not found.")
152         raise Exception('Error with command:%s' % cmd)
153     return deployment_uuid
154
155
156 def get_verifier_deployment_id():
157     """
158     Returns deployment id for active Rally deployment
159     """
160     cmd = ("rally deployment list | awk '/" +
161            CONST.__getattribute__('rally_deployment_name') +
162            "/ {print $2}'")
163     p = subprocess.Popen(cmd, shell=True,
164                          stdout=subprocess.PIPE,
165                          stderr=subprocess.STDOUT)
166     deployment_uuid = p.stdout.readline().rstrip()
167     if deployment_uuid == "":
168         logger.error("Rally deployment not found.")
169         raise Exception('Error with command:%s' % cmd)
170     return deployment_uuid
171
172
173 def get_verifier_repo_dir(verifier_id):
174     """
175     Returns installed verfier repo directory for Tempest
176     """
177     if not verifier_id:
178         verifier_id = get_verifier_id()
179
180     return os.path.join(CONST.__getattribute__('dir_rally_inst'),
181                         'verification',
182                         'verifier-{}'.format(verifier_id),
183                         'repo')
184
185
186 def get_verifier_deployment_dir(verifier_id, deployment_id):
187     """
188     Returns Rally deployment directory for current verifier
189     """
190     if not verifier_id:
191         verifier_id = get_verifier_id()
192
193     if not deployment_id:
194         deployment_id = get_verifier_deployment_id()
195
196     return os.path.join(CONST.__getattribute__('dir_rally_inst'),
197                         'verification',
198                         'verifier-{}'.format(verifier_id),
199                         'for-deployment-{}'.format(deployment_id))
200
201
202 def get_repo_tag(repo):
203     """
204     Returns last tag of current branch
205     """
206     cmd = ("git -C {0} describe --abbrev=0 HEAD".format(repo))
207     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
208     tag = p.stdout.readline().rstrip()
209
210     return str(tag)
211
212
213 def backup_tempest_config(conf_file):
214     """
215     Copy config file to tempest results directory
216     """
217     if not os.path.exists(TEMPEST_RESULTS_DIR):
218         os.makedirs(TEMPEST_RESULTS_DIR)
219
220     shutil.copyfile(conf_file,
221                     os.path.join(TEMPEST_RESULTS_DIR, 'tempest.conf'))
222
223
224 def configure_tempest(deployment_dir, IMAGE_ID=None, FLAVOR_ID=None,
225                       MODE=None):
226     """
227     Calls rally verify and updates the generated tempest.conf with
228     given parameters
229     """
230     conf_file = configure_verifier(deployment_dir)
231     configure_tempest_update_params(conf_file,
232                                     IMAGE_ID, FLAVOR_ID)
233
234
235 def configure_tempest_defcore(deployment_dir, img_flavor_dict):
236     """
237     Add/update needed parameters into tempest.conf file
238     """
239     conf_file = configure_verifier(deployment_dir)
240     configure_tempest_update_params(conf_file,
241                                     img_flavor_dict.get("image_id"),
242                                     img_flavor_dict.get("flavor_id"))
243
244     logger.debug("Updating selected tempest.conf parameters for defcore...")
245     config = ConfigParser.RawConfigParser()
246     config.read(conf_file)
247     config.set('DEFAULT', 'log_file', '{}/tempest.log'.format(deployment_dir))
248     config.set('oslo_concurrency', 'lock_path',
249                '{}/lock_files'.format(deployment_dir))
250     config.set('scenario', 'img_dir', '{}'.format(deployment_dir))
251     config.set('scenario', 'img_file', 'tempest-image')
252     config.set('compute', 'image_ref', img_flavor_dict.get("image_id"))
253     config.set('compute', 'image_ref_alt',
254                img_flavor_dict['image_id_alt'])
255     config.set('compute', 'flavor_ref', img_flavor_dict.get("flavor_id"))
256     config.set('compute', 'flavor_ref_alt',
257                img_flavor_dict['flavor_id_alt'])
258
259     with open(conf_file, 'wb') as config_file:
260         config.write(config_file)
261
262     confpath = pkg_resources.resource_filename(
263         'functest',
264         'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
265     shutil.copyfile(conf_file, confpath)
266
267
268 def configure_tempest_update_params(tempest_conf_file,
269                                     IMAGE_ID=None, FLAVOR_ID=None):
270     """
271     Add/update needed parameters into tempest.conf file
272     """
273     logger.debug("Updating selected tempest.conf parameters...")
274     config = ConfigParser.RawConfigParser()
275     config.read(tempest_conf_file)
276     config.set(
277         'compute',
278         'fixed_network_name',
279         CONST.__getattribute__('tempest_private_net_name'))
280     config.set('compute', 'volume_device_name',
281                CONST.__getattribute__('tempest_volume_device_name'))
282     if CONST.__getattribute__('tempest_use_custom_images'):
283         if IMAGE_ID is not None:
284             config.set('compute', 'image_ref', IMAGE_ID)
285         if IMAGE_ID_ALT is not None:
286             config.set('compute', 'image_ref_alt', IMAGE_ID_ALT)
287     if CONST.__getattribute__('tempest_use_custom_flavors'):
288         if FLAVOR_ID is not None:
289             config.set('compute', 'flavor_ref', FLAVOR_ID)
290         if FLAVOR_ID_ALT is not None:
291             config.set('compute', 'flavor_ref_alt', FLAVOR_ID_ALT)
292     config.set('identity', 'tenant_name',
293                CONST.__getattribute__('tempest_identity_tenant_name'))
294     config.set('identity', 'username',
295                CONST.__getattribute__('tempest_identity_user_name'))
296     config.set('identity', 'password',
297                CONST.__getattribute__('tempest_identity_user_password'))
298     config.set('identity', 'region', 'RegionOne')
299     if os_utils.is_keystone_v3():
300         auth_version = 'v3'
301     else:
302         auth_version = 'v2'
303     config.set('identity', 'auth_version', auth_version)
304     config.set(
305         'validation', 'ssh_timeout',
306         CONST.__getattribute__('tempest_validation_ssh_timeout'))
307     config.set('object-storage', 'operator_role',
308                CONST.__getattribute__('tempest_object_storage_operator_role'))
309
310     if CONST.__getattribute__('OS_ENDPOINT_TYPE') is not None:
311         sections = config.sections()
312         if os_utils.is_keystone_v3():
313             config.set('identity', 'v3_endpoint_type',
314                        CONST.__getattribute__('OS_ENDPOINT_TYPE'))
315             if 'identity-feature-enabled' not in sections:
316                 config.add_section('identity-feature-enabled')
317                 config.set('identity-feature-enabled', 'api_v2', False)
318                 config.set('identity-feature-enabled', 'api_v2_admin', False)
319         services_list = ['compute',
320                          'volume',
321                          'image',
322                          'network',
323                          'data-processing',
324                          'object-storage',
325                          'orchestration']
326         for service in services_list:
327             if service not in sections:
328                 config.add_section(service)
329             config.set(service, 'endpoint_type',
330                        CONST.__getattribute__('OS_ENDPOINT_TYPE'))
331
332     logger.debug('Add/Update required params defined in tempest_conf.yaml '
333                  'into tempest.conf file')
334     with open(TEMPEST_CONF_YAML) as f:
335         conf_yaml = yaml.safe_load(f)
336     if conf_yaml:
337         sections = config.sections()
338         for section in conf_yaml:
339             if section not in sections:
340                 config.add_section(section)
341             sub_conf = conf_yaml.get(section)
342             for key, value in sub_conf.items():
343                 config.set(section, key, value)
344
345     with open(tempest_conf_file, 'wb') as config_file:
346         config.write(config_file)
347
348     backup_tempest_config(tempest_conf_file)
349
350
351 def configure_verifier(deployment_dir):
352     """
353     Execute rally verify configure-verifier, which generates tempest.conf
354     """
355     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
356     if os.path.isfile(tempest_conf_file):
357         logger.debug("Verifier is already configured.")
358         logger.debug("Reconfiguring the current verifier...")
359         cmd = "rally verify configure-verifier --reconfigure"
360     else:
361         logger.info("Configuring the verifier...")
362         cmd = "rally verify configure-verifier"
363     ft_utils.execute_command(cmd)
364
365     logger.debug("Looking for tempest.conf file...")
366     if not os.path.isfile(tempest_conf_file):
367         logger.error("Tempest configuration file %s NOT found."
368                      % tempest_conf_file)
369         raise Exception("Tempest configuration file %s NOT found."
370                         % tempest_conf_file)
371     else:
372         return tempest_conf_file