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