Fix the config of fixed_network_name in tempest
[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
11 """Tempest configuration utilities."""
12
13 import ConfigParser
14 import logging
15 import fileinput
16 import os
17 import pkg_resources
18 import shutil
19 import subprocess
20
21 import yaml
22
23 from functest.utils.constants import CONST
24 import functest.utils.functest_utils as ft_utils
25
26
27 IMAGE_ID_ALT = None
28 FLAVOR_ID_ALT = None
29 RALLY_CONF_PATH = "/etc/rally/rally.conf"
30 RALLY_AARCH64_PATCH_PATH = pkg_resources.resource_filename(
31     'functest', 'ci/rally_aarch64_patch.conf')
32 GLANCE_IMAGE_PATH = os.path.join(
33     CONST.__getattribute__('dir_functest_images'),
34     CONST.__getattribute__('openstack_image_file_name'))
35 TEMPEST_RESULTS_DIR = os.path.join(CONST.__getattribute__('dir_results'),
36                                    'tempest')
37 TEMPEST_CUSTOM = pkg_resources.resource_filename(
38     'functest', 'opnfv_tests/openstack/tempest/custom_tests/test_list.txt')
39 TEMPEST_BLACKLIST = pkg_resources.resource_filename(
40     'functest', 'opnfv_tests/openstack/tempest/custom_tests/blacklist.txt')
41 TEMPEST_DEFCORE = pkg_resources.resource_filename(
42     'functest',
43     'opnfv_tests/openstack/tempest/custom_tests/defcore_req.txt')
44 TEMPEST_RAW_LIST = os.path.join(TEMPEST_RESULTS_DIR, 'test_raw_list.txt')
45 TEMPEST_LIST = os.path.join(TEMPEST_RESULTS_DIR, 'test_list.txt')
46 REFSTACK_RESULTS_DIR = os.path.join(CONST.__getattribute__('dir_results'),
47                                     'refstack')
48 TEMPEST_CONF_YAML = pkg_resources.resource_filename(
49     'functest', 'opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml')
50 TEST_ACCOUNTS_FILE = pkg_resources.resource_filename(
51     'functest',
52     'opnfv_tests/openstack/tempest/custom_tests/test_accounts.yaml')
53
54 CI_INSTALLER_TYPE = CONST.__getattribute__('INSTALLER_TYPE')
55 CI_INSTALLER_IP = CONST.__getattribute__('INSTALLER_IP')
56
57 """ logging configuration """
58 LOGGER = logging.getLogger(__name__)
59
60
61 def create_rally_deployment():
62     """Create new rally deployment"""
63     # set the architecture to default
64     pod_arch = os.getenv("POD_ARCH", None)
65     arch_filter = ['aarch64']
66
67     if pod_arch and pod_arch in arch_filter:
68         LOGGER.info("Apply aarch64 specific to rally config...")
69         with open(RALLY_AARCH64_PATCH_PATH, "r") as pfile:
70             rally_patch_conf = pfile.read()
71
72         for line in fileinput.input(RALLY_CONF_PATH, inplace=1):
73             print line,
74             if "cirros|testvm" in line:
75                 print rally_patch_conf
76
77     LOGGER.info("Creating Rally environment...")
78
79     cmd = "rally deployment destroy opnfv-rally"
80     ft_utils.execute_command(cmd, error_msg=(
81         "Deployment %s does not exist."
82         % CONST.__getattribute__('rally_deployment_name')),
83                              verbose=False)
84
85     cmd = ("rally deployment create --fromenv --name={0}"
86            .format(CONST.__getattribute__('rally_deployment_name')))
87     error_msg = "Problem while creating Rally deployment"
88     ft_utils.execute_command_raise(cmd, error_msg=error_msg)
89
90     cmd = "rally deployment check"
91     error_msg = "OpenStack not responding or faulty Rally deployment."
92     ft_utils.execute_command_raise(cmd, error_msg=error_msg)
93
94
95 def create_verifier():
96     """Create new verifier"""
97     LOGGER.info("Create verifier from existing repo...")
98     cmd = ("rally verify delete-verifier --id '{0}' --force").format(
99         CONST.__getattribute__('tempest_verifier_name'))
100     ft_utils.execute_command(cmd, error_msg=(
101         "Verifier %s does not exist."
102         % CONST.__getattribute__('tempest_verifier_name')),
103                              verbose=False)
104     cmd = ("rally verify create-verifier --source {0} "
105            "--name {1} --type tempest --system-wide"
106            .format(CONST.__getattribute__('dir_repo_tempest'),
107                    CONST.__getattribute__('tempest_verifier_name')))
108     ft_utils.execute_command_raise(cmd,
109                                    error_msg='Problem while creating verifier')
110
111
112 def get_verifier_id():
113     """
114     Returns verifier id for current Tempest
115     """
116     create_rally_deployment()
117     create_verifier()
118     cmd = ("rally verify list-verifiers | awk '/" +
119            CONST.__getattribute__('tempest_verifier_name') +
120            "/ {print $2}'")
121     proc = subprocess.Popen(cmd, shell=True,
122                             stdout=subprocess.PIPE,
123                             stderr=subprocess.STDOUT)
124     deployment_uuid = proc.stdout.readline().rstrip()
125     if deployment_uuid == "":
126         LOGGER.error("Tempest verifier not found.")
127         raise Exception('Error with command:%s' % cmd)
128     return deployment_uuid
129
130
131 def get_verifier_deployment_id():
132     """
133     Returns deployment id for active Rally deployment
134     """
135     cmd = ("rally deployment list | awk '/" +
136            CONST.__getattribute__('rally_deployment_name') +
137            "/ {print $2}'")
138     proc = subprocess.Popen(cmd, shell=True,
139                             stdout=subprocess.PIPE,
140                             stderr=subprocess.STDOUT)
141     deployment_uuid = proc.stdout.readline().rstrip()
142     if deployment_uuid == "":
143         LOGGER.error("Rally deployment not found.")
144         raise Exception('Error with command:%s' % cmd)
145     return deployment_uuid
146
147
148 def get_verifier_repo_dir(verifier_id):
149     """
150     Returns installed verifier repo directory for Tempest
151     """
152     if not verifier_id:
153         verifier_id = get_verifier_id()
154
155     return os.path.join(CONST.__getattribute__('dir_rally_inst'),
156                         'verification',
157                         'verifier-{}'.format(verifier_id),
158                         'repo')
159
160
161 def get_verifier_deployment_dir(verifier_id, deployment_id):
162     """
163     Returns Rally deployment directory for current verifier
164     """
165     if not verifier_id:
166         verifier_id = get_verifier_id()
167
168     if not deployment_id:
169         deployment_id = get_verifier_deployment_id()
170
171     return os.path.join(CONST.__getattribute__('dir_rally_inst'),
172                         'verification',
173                         'verifier-{}'.format(verifier_id),
174                         'for-deployment-{}'.format(deployment_id))
175
176
177 def backup_tempest_config(conf_file):
178     """
179     Copy config file to tempest results directory
180     """
181     if not os.path.exists(TEMPEST_RESULTS_DIR):
182         os.makedirs(TEMPEST_RESULTS_DIR)
183     shutil.copyfile(conf_file,
184                     os.path.join(TEMPEST_RESULTS_DIR, 'tempest.conf'))
185
186
187 def configure_tempest(deployment_dir, network_name=None, image_id=None,
188                       flavor_id=None, compute_cnt=None):
189     """
190     Calls rally verify and updates the generated tempest.conf with
191     given parameters
192     """
193     conf_file = configure_verifier(deployment_dir)
194     configure_tempest_update_params(conf_file, network_name, image_id,
195                                     flavor_id, compute_cnt)
196
197
198 def configure_tempest_defcore(deployment_dir, network_name, image_id,
199                               flavor_id, image_id_alt, flavor_id_alt,
200                               tenant_id):
201     # pylint: disable=too-many-arguments
202     """
203     Add/update needed parameters into tempest.conf file
204     """
205     conf_file = configure_verifier(deployment_dir)
206     configure_tempest_update_params(conf_file, network_name, image_id,
207                                     flavor_id)
208
209     LOGGER.debug("Updating selected tempest.conf parameters for defcore...")
210     config = ConfigParser.RawConfigParser()
211     config.read(conf_file)
212     config.set('DEFAULT', 'log_file', '{}/tempest.log'.format(deployment_dir))
213     config.set('oslo_concurrency', 'lock_path',
214                '{}/lock_files'.format(deployment_dir))
215     generate_test_accounts_file(tenant_id=tenant_id)
216     config.set('auth', 'test_accounts_file', TEST_ACCOUNTS_FILE)
217     config.set('scenario', 'img_dir', '{}'.format(deployment_dir))
218     config.set('scenario', 'img_file', 'tempest-image')
219     config.set('compute', 'image_ref', image_id)
220     config.set('compute', 'image_ref_alt', image_id_alt)
221     config.set('compute', 'flavor_ref', flavor_id)
222     config.set('compute', 'flavor_ref_alt', flavor_id_alt)
223
224     with open(conf_file, 'wb') as config_file:
225         config.write(config_file)
226
227     confpath = pkg_resources.resource_filename(
228         'functest',
229         'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
230     shutil.copyfile(conf_file, confpath)
231
232
233 def generate_test_accounts_file(tenant_id):
234     """
235     Add needed tenant and user params into test_accounts.yaml
236     """
237
238     LOGGER.debug("Add needed params into test_accounts.yaml...")
239     accounts_list = [
240         {
241             'tenant_name':
242                 CONST.__getattribute__('tempest_identity_tenant_name'),
243             'tenant_id': str(tenant_id),
244             'username': CONST.__getattribute__('tempest_identity_user_name'),
245             'password':
246                 CONST.__getattribute__('tempest_identity_user_password')
247         }
248     ]
249
250     with open(TEST_ACCOUNTS_FILE, "w") as tfile:
251         yaml.dump(accounts_list, tfile, default_flow_style=False)
252
253
254 def update_tempest_conf_file(conf_file, config):
255     """Update defined paramters into tempest config file"""
256     with open(TEMPEST_CONF_YAML) as yfile:
257         conf_yaml = yaml.safe_load(yfile)
258     if conf_yaml:
259         sections = config.sections()
260         for section in conf_yaml:
261             if section not in sections:
262                 config.add_section(section)
263             sub_conf = conf_yaml.get(section)
264             for key, value in sub_conf.items():
265                 config.set(section, key, value)
266
267     with open(conf_file, 'wb') as config_file:
268         config.write(config_file)
269
270
271 def configure_tempest_update_params(tempest_conf_file, network_name=None,
272                                     image_id=None, flavor_id=None,
273                                     compute_cnt=1):
274     """
275     Add/update needed parameters into tempest.conf file
276     """
277     LOGGER.debug("Updating selected tempest.conf parameters...")
278     config = ConfigParser.RawConfigParser()
279     config.read(tempest_conf_file)
280     config.set('compute', 'fixed_network_name', network_name)
281     config.set('compute', 'volume_device_name',
282                CONST.__getattribute__('tempest_volume_device_name'))
283
284     if image_id is not None:
285         config.set('compute', 'image_ref', image_id)
286     if IMAGE_ID_ALT is not None:
287         config.set('compute', 'image_ref_alt', IMAGE_ID_ALT)
288     if CONST.__getattribute__('tempest_use_custom_flavors'):
289         if flavor_id is not None:
290             config.set('compute', 'flavor_ref', flavor_id)
291         if FLAVOR_ID_ALT is not None:
292             config.set('compute', 'flavor_ref_alt', FLAVOR_ID_ALT)
293     if compute_cnt > 1:
294         # enable multinode tests
295         config.set('compute', 'min_compute_nodes', compute_cnt)
296         config.set('compute-feature-enabled', 'live_migration', True)
297
298     config.set('identity', 'region',
299                CONST.__getattribute__('OS_REGION_NAME'))
300     identity_api_version = os.getenv(
301         "OS_IDENTITY_API_VERSION", os.getenv("IDENTITY_API_VERSION"))
302     if identity_api_version == '3':
303         auth_version = 'v3'
304         config.set('identity-feature-enabled', 'api_v2', False)
305     else:
306         auth_version = 'v2'
307     config.set('identity', 'auth_version', auth_version)
308     config.set(
309         'validation', 'ssh_timeout',
310         CONST.__getattribute__('tempest_validation_ssh_timeout'))
311     config.set('object-storage', 'operator_role',
312                CONST.__getattribute__('tempest_object_storage_operator_role'))
313
314     if CONST.__getattribute__('OS_ENDPOINT_TYPE') is not None:
315         config.set('identity', 'v3_endpoint_type',
316                    CONST.__getattribute__('OS_ENDPOINT_TYPE'))
317
318     if CONST.__getattribute__('OS_ENDPOINT_TYPE') is not None:
319         sections = config.sections()
320         services_list = ['compute',
321                          'volume',
322                          'image',
323                          'network',
324                          'data-processing',
325                          'object-storage',
326                          'orchestration']
327         for service in services_list:
328             if service not in sections:
329                 config.add_section(service)
330             config.set(service, 'endpoint_type',
331                        CONST.__getattribute__('OS_ENDPOINT_TYPE'))
332
333     LOGGER.debug('Add/Update required params defined in tempest_conf.yaml '
334                  'into tempest.conf file')
335     update_tempest_conf_file(tempest_conf_file, config)
336
337     backup_tempest_config(tempest_conf_file)
338
339
340 def configure_verifier(deployment_dir):
341     """
342     Execute rally verify configure-verifier, which generates tempest.conf
343     """
344     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
345     if os.path.isfile(tempest_conf_file):
346         LOGGER.debug("Verifier is already configured.")
347         LOGGER.debug("Reconfiguring the current verifier...")
348         cmd = "rally verify configure-verifier --reconfigure"
349     else:
350         LOGGER.info("Configuring the verifier...")
351         cmd = "rally verify configure-verifier"
352     ft_utils.execute_command(cmd)
353
354     LOGGER.debug("Looking for tempest.conf file...")
355     if not os.path.isfile(tempest_conf_file):
356         LOGGER.error("Tempest configuration file %s NOT found.",
357                      tempest_conf_file)
358         raise Exception("Tempest configuration file %s NOT found."
359                         % tempest_conf_file)
360     else:
361         return tempest_conf_file