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