Merge "Forbid calling generate_report from cmdline"
[functest.git] / functest / opnfv_tests / openstack / tempest / conf_utils.py
1 #!/usr/bin/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 re
14 import shutil
15 import subprocess
16
17 from functest.utils.constants import CONST
18 import functest.utils.functest_utils as ft_utils
19 import functest.utils.openstack_utils as os_utils
20
21
22 IMAGE_ID_ALT = None
23 FLAVOR_ID_ALT = None
24 REPO_PATH = CONST.dir_repo_functest
25 GLANCE_IMAGE_PATH = os.path.join(CONST.dir_functest_data,
26                                  CONST.openstack_image_file_name)
27 TEMPEST_TEST_LIST_DIR = CONST.dir_tempest_cases
28 TEMPEST_RESULTS_DIR = os.path.join(CONST.dir_results,
29                                    'tempest')
30 TEMPEST_CUSTOM = os.path.join(REPO_PATH, TEMPEST_TEST_LIST_DIR,
31                               'test_list.txt')
32 TEMPEST_BLACKLIST = os.path.join(REPO_PATH, TEMPEST_TEST_LIST_DIR,
33                                  'blacklist.txt')
34 TEMPEST_DEFCORE = os.path.join(REPO_PATH, TEMPEST_TEST_LIST_DIR,
35                                'defcore_req.txt')
36 TEMPEST_RAW_LIST = os.path.join(TEMPEST_RESULTS_DIR, 'test_raw_list.txt')
37 TEMPEST_LIST = os.path.join(TEMPEST_RESULTS_DIR, 'test_list.txt')
38 REFSTACK_RESULTS_DIR = os.path.join(CONST.dir_results,
39                                     'refstack')
40
41 CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
42 CI_INSTALLER_IP = CONST.INSTALLER_IP
43
44 """ logging configuration """
45 logger = logging.getLogger(__name__)
46
47
48 def create_tempest_resources(use_custom_images=False,
49                              use_custom_flavors=False):
50     keystone_client = os_utils.get_keystone_client()
51
52     logger.debug("Creating tenant and user for Tempest suite")
53     tenant_id = os_utils.create_tenant(
54         keystone_client,
55         CONST.tempest_identity_tenant_name,
56         CONST.tempest_identity_tenant_description)
57     if not tenant_id:
58         logger.error("Failed to create %s tenant"
59                      % CONST.tempest_identity_tenant_name)
60
61     user_id = os_utils.create_user(keystone_client,
62                                    CONST.tempest_identity_user_name,
63                                    CONST.tempest_identity_user_password,
64                                    None, tenant_id)
65     if not user_id:
66         logger.error("Failed to create %s user" %
67                      CONST.tempest_identity_user_name)
68
69     logger.debug("Creating private network for Tempest suite")
70     network_dic = os_utils.create_shared_network_full(
71         CONST.tempest_private_net_name,
72         CONST.tempest_private_subnet_name,
73         CONST.tempest_router_name,
74         CONST.tempest_private_subnet_cidr)
75     if network_dic is None:
76         raise Exception('Failed to create private network')
77
78     image_id = ""
79     image_id_alt = ""
80     flavor_id = ""
81     flavor_id_alt = ""
82
83     if CONST.tempest_use_custom_images or use_custom_images:
84         # adding alternative image should be trivial should we need it
85         logger.debug("Creating image for Tempest suite")
86         _, image_id = os_utils.get_or_create_image(
87             CONST.openstack_image_name, GLANCE_IMAGE_PATH,
88             CONST.openstack_image_disk_format)
89         if image_id is None:
90             raise Exception('Failed to create image')
91
92     if use_custom_images:
93         logger.debug("Creating 2nd image for Tempest suite")
94         _, image_id_alt = os_utils.get_or_create_image(
95             CONST.openstack_image_name_alt, GLANCE_IMAGE_PATH,
96             CONST.openstack_image_disk_format)
97         if image_id_alt is None:
98             raise Exception('Failed to create image')
99
100     if CONST.tempest_use_custom_flavors or use_custom_flavors:
101         # adding alternative flavor should be trivial should we need it
102         logger.debug("Creating flavor for Tempest suite")
103         _, flavor_id = os_utils.get_or_create_flavor(
104             CONST.openstack_flavor_name,
105             CONST.openstack_flavor_ram,
106             CONST.openstack_flavor_disk,
107             CONST.openstack_flavor_vcpus)
108         if flavor_id is None:
109             raise Exception('Failed to create flavor')
110
111     if use_custom_flavors:
112         logger.debug("Creating 2nd flavor for tempest_defcore")
113         _, flavor_id_alt = os_utils.get_or_create_flavor(
114             CONST.openstack_flavor_name_alt,
115             CONST.openstack_flavor_ram,
116             CONST.openstack_flavor_disk,
117             CONST.openstack_flavor_vcpus)
118         if flavor_id_alt is None:
119             raise Exception('Failed to create flavor')
120
121     img_flavor_dict = {}
122     img_flavor_dict['image_id'] = image_id
123     img_flavor_dict['image_id_alt'] = image_id_alt
124     img_flavor_dict['flavor_id'] = flavor_id
125     img_flavor_dict['flavor_id_alt'] = flavor_id_alt
126
127     return img_flavor_dict
128
129
130 def get_verifier_id():
131     """
132     Returns verifer id for current Tempest
133     """
134     cmd = ("rally verify list-verifiers | awk '/" +
135            CONST.tempest_deployment_name +
136            "/ {print $2}'")
137     p = subprocess.Popen(cmd, shell=True,
138                          stdout=subprocess.PIPE,
139                          stderr=subprocess.STDOUT)
140     deployment_uuid = p.stdout.readline().rstrip()
141     if deployment_uuid == "":
142         logger.error("Tempest verifier not found.")
143         raise Exception('Error with command:%s' % cmd)
144     return deployment_uuid
145
146
147 def get_verifier_deployment_id():
148     """
149     Returns deployment id for active Rally deployment
150     """
151     cmd = ("rally deployment list | awk '/" +
152            CONST.rally_deployment_name +
153            "/ {print $2}'")
154     p = subprocess.Popen(cmd, shell=True,
155                          stdout=subprocess.PIPE,
156                          stderr=subprocess.STDOUT)
157     deployment_uuid = p.stdout.readline().rstrip()
158     if deployment_uuid == "":
159         logger.error("Rally deployment not found.")
160         raise Exception('Error with command:%s' % cmd)
161     return deployment_uuid
162
163
164 def get_verifier_repo_dir(verifier_id):
165     """
166     Returns installed verfier repo directory for Tempest
167     """
168     if not verifier_id:
169         verifier_id = get_verifier_id()
170
171     return os.path.join(CONST.dir_rally_inst,
172                         'verification',
173                         'verifier-{}'.format(verifier_id),
174                         'repo')
175
176
177 def get_verifier_deployment_dir(verifier_id, deployment_id):
178     """
179     Returns Rally deployment directory for current verifier
180     """
181     if not verifier_id:
182         verifier_id = get_verifier_id()
183
184     if not deployment_id:
185         deployment_id = get_verifier_deployment_id()
186
187     return os.path.join(CONST.dir_rally_inst,
188                         'verification',
189                         'verifier-{}'.format(verifier_id),
190                         'for-deployment-{}'.format(deployment_id))
191
192
193 def get_repo_tag(repo):
194     """
195     Returns last tag of current branch
196     """
197     cmd = ("git -C {0} describe --abbrev=0 HEAD".format(repo))
198     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
199     tag = p.stdout.readline().rstrip()
200
201     return str(tag)
202
203
204 def backup_tempest_config(conf_file):
205     """
206     Copy config file to tempest results directory
207     """
208     if not os.path.exists(TEMPEST_RESULTS_DIR):
209         os.makedirs(TEMPEST_RESULTS_DIR)
210
211     shutil.copyfile(conf_file,
212                     os.path.join(TEMPEST_RESULTS_DIR, 'tempest.conf'))
213
214
215 def configure_tempest(deployment_dir, IMAGE_ID=None, FLAVOR_ID=None,
216                       MODE=None):
217     """
218     Calls rally verify and updates the generated tempest.conf with
219     given parameters
220     """
221     conf_file = configure_verifier(deployment_dir)
222     configure_tempest_update_params(conf_file,
223                                     IMAGE_ID, FLAVOR_ID)
224     if MODE == 'feature_multisite':
225         configure_tempest_multisite_params(conf_file)
226
227
228 def configure_tempest_defcore(deployment_dir, img_flavor_dict):
229     """
230     Add/update needed parameters into tempest.conf file
231     """
232     conf_file = configure_verifier(deployment_dir)
233     configure_tempest_update_params(conf_file,
234                                     img_flavor_dict.get("image_id"),
235                                     img_flavor_dict.get("flavor_id"))
236
237     logger.debug("Updating selected tempest.conf parameters for defcore...")
238     config = ConfigParser.RawConfigParser()
239     config.read(conf_file)
240     config.set('compute', 'image_ref', img_flavor_dict.get("image_id"))
241     config.set('compute', 'image_ref_alt',
242                img_flavor_dict['image_id_alt'])
243     config.set('compute', 'flavor_ref', img_flavor_dict.get("flavor_id"))
244     config.set('compute', 'flavor_ref_alt',
245                img_flavor_dict['flavor_id_alt'])
246
247     with open(conf_file, 'wb') as config_file:
248         config.write(config_file)
249
250     confpath = os.path.join(CONST.dir_functest_test,
251                             CONST.refstack_tempest_conf_path)
252     shutil.copyfile(conf_file, confpath)
253
254
255 def configure_tempest_update_params(tempest_conf_file,
256                                     IMAGE_ID=None, FLAVOR_ID=None):
257     """
258     Add/update needed parameters into tempest.conf file
259     """
260     logger.debug("Updating selected tempest.conf parameters...")
261     config = ConfigParser.RawConfigParser()
262     config.read(tempest_conf_file)
263     config.set(
264         'compute',
265         'fixed_network_name',
266         CONST.tempest_private_net_name)
267     config.set('compute', 'volume_device_name',
268                CONST.tempest_volume_device_name)
269     if CONST.tempest_use_custom_images:
270         if IMAGE_ID is not None:
271             config.set('compute', 'image_ref', IMAGE_ID)
272         if IMAGE_ID_ALT is not None:
273             config.set('compute', 'image_ref_alt', IMAGE_ID_ALT)
274     if CONST.tempest_use_custom_flavors:
275         if FLAVOR_ID is not None:
276             config.set('compute', 'flavor_ref', FLAVOR_ID)
277         if FLAVOR_ID_ALT is not None:
278             config.set('compute', 'flavor_ref_alt', FLAVOR_ID_ALT)
279     config.set('identity', 'tenant_name', CONST.tempest_identity_tenant_name)
280     config.set('identity', 'username', CONST.tempest_identity_user_name)
281     config.set('identity', 'password', CONST.tempest_identity_user_password)
282     config.set('identity', 'region', 'RegionOne')
283     config.set(
284         'validation', 'ssh_timeout', CONST.tempest_validation_ssh_timeout)
285     config.set('object-storage', 'operator_role',
286                CONST.tempest_object_storage_operator_role)
287
288     if CONST.OS_ENDPOINT_TYPE is not None:
289         sections = config.sections()
290         if os_utils.is_keystone_v3():
291             config.set('identity', 'v3_endpoint_type', CONST.OS_ENDPOINT_TYPE)
292             if 'identity-feature-enabled' not in sections:
293                 config.add_section('identity-feature-enabled')
294                 config.set('identity-feature-enabled', 'api_v2', False)
295                 config.set('identity-feature-enabled', 'api_v2_admin', False)
296         services_list = ['compute',
297                          'volume',
298                          'image',
299                          'network',
300                          'data-processing',
301                          'object-storage',
302                          'orchestration']
303         for service in services_list:
304             if service not in sections:
305                 config.add_section(service)
306             config.set(service, 'endpoint_type',
307                        CONST.OS_ENDPOINT_TYPE)
308
309     with open(tempest_conf_file, 'wb') as config_file:
310         config.write(config_file)
311
312     backup_tempest_config(tempest_conf_file)
313
314
315 def configure_verifier(deployment_dir):
316     """
317     Execute rally verify configure-verifier, which generates tempest.conf
318     """
319     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
320     if os.path.isfile(tempest_conf_file):
321         logger.debug("Verifier is already configured.")
322         logger.debug("Reconfiguring the current verifier...")
323         cmd = "rally verify configure-verifier --reconfigure"
324     else:
325         logger.info("Configuring the verifier...")
326         cmd = "rally verify configure-verifier"
327     ft_utils.execute_command(cmd)
328
329     logger.debug("Looking for tempest.conf file...")
330     if not os.path.isfile(tempest_conf_file):
331         logger.error("Tempest configuration file %s NOT found."
332                      % tempest_conf_file)
333         raise Exception("Tempest configuration file %s NOT found."
334                         % tempest_conf_file)
335     else:
336         return tempest_conf_file
337
338
339 def configure_tempest_multisite_params(tempest_conf_file):
340     """
341     Add/update multisite parameters into tempest.conf file generated by Rally
342     """
343     logger.debug("Updating multisite tempest.conf parameters...")
344     config = ConfigParser.RawConfigParser()
345     config.read(tempest_conf_file)
346
347     config.set('service_available', 'kingbird', 'true')
348     # cmd = ("openstack endpoint show kingbird | grep publicurl |"
349     #       "awk '{print $4}' | awk -F '/' '{print $4}'")
350     # kingbird_api_version = os.popen(cmd).read()
351     # kingbird_api_version = os_utils.get_endpoint(service_type='multisite')
352
353     if CI_INSTALLER_TYPE == 'fuel':
354         # For MOS based setup, the service is accessible
355         # via bind host
356         kingbird_conf_path = "/etc/kingbird/kingbird.conf"
357         installer_type = CI_INSTALLER_TYPE
358         installer_ip = CI_INSTALLER_IP
359         installer_username = CONST.__getattribute__(
360             'multisite_{}_installer_username'.format(installer_type))
361         installer_password = CONST.__getattribute__(
362             'multisite_{}_installer_password'.format(installer_type))
363
364         ssh_options = ("-o UserKnownHostsFile=/dev/null -o "
365                        "StrictHostKeyChecking=no")
366
367         # Get the controller IP from the fuel node
368         cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
369                 \'fuel node --env 1| grep controller | grep "True\|  1" \
370                 | awk -F\| "{print \$5}"\'' % (installer_password,
371                                                ssh_options,
372                                                installer_username,
373                                                installer_ip)
374         multisite_controller_ip = "".join(os.popen(cmd).read().split())
375
376         # Login to controller and get bind host details
377         cmd = 'sshpass -p %s ssh 2>/dev/null  %s %s@%s "ssh %s \\" \
378             grep -e "^bind_" %s  \\""' % (installer_password,
379                                           ssh_options,
380                                           installer_username,
381                                           installer_ip,
382                                           multisite_controller_ip,
383                                           kingbird_conf_path)
384         bind_details = os.popen(cmd).read()
385         bind_details = "".join(bind_details.split())
386         # Extract port number from the bind details
387         bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
388         # Extract ip address from the bind details
389         bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
390                                bind_details)[0]
391         kingbird_endpoint_url = "http://%s:%s/" % (bind_host, bind_port)
392     else:
393         # cmd = "openstack endpoint show kingbird | grep publicurl |\
394         #       awk '{print $4}' | awk -F '/' '{print $3}'"
395         # kingbird_endpoint_url = os.popen(cmd).read()
396         kingbird_endpoint_url = os_utils.get_endpoint(service_type='kingbird')
397
398     try:
399         config.add_section("kingbird")
400     except Exception:
401         logger.info('kingbird section exist')
402
403     # set the domain id
404     config.set('auth', 'admin_domain_name', 'default')
405
406     config.set('kingbird', 'endpoint_type', 'publicURL')
407     config.set('kingbird', 'TIME_TO_SYNC', '120')
408     config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
409     config.set('kingbird', 'api_version', 'v1.0')
410     with open(tempest_conf_file, 'wb') as config_file:
411         config.write(config_file)
412
413     backup_tempest_config(tempest_conf_file)
414
415
416 def install_verifier_ext(path):
417     """
418     Install extension to active verifier
419     """
420     logger.info("Installing verifier from existing repo...")
421     tag = get_repo_tag(path)
422     cmd = ("rally verify add-verifier-ext --source {0} "
423            "--version {1}"
424            .format(path, tag))
425     error_msg = ("Problem while adding verifier extension from %s" % path)
426     ft_utils.execute_command_raise(cmd, error_msg=error_msg)