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