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