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