Merge "Refactor TempestCommon to simplify subclasses"
[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_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_CONF_YAML = pkg_resources.resource_filename(
41     'functest', 'opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml')
42 TEST_ACCOUNTS_FILE = pkg_resources.resource_filename(
43     'functest',
44     'opnfv_tests/openstack/tempest/custom_tests/test_accounts.yaml')
45
46 CI_INSTALLER_TYPE = env.get('INSTALLER_TYPE')
47
48 """ logging configuration """
49 LOGGER = logging.getLogger(__name__)
50
51
52 def create_rally_deployment():
53     """Create new rally deployment"""
54     # set the architecture to default
55     pod_arch = env.get("POD_ARCH")
56     arch_filter = ['aarch64']
57
58     if pod_arch and pod_arch in arch_filter:
59         LOGGER.info("Apply aarch64 specific to rally config...")
60         with open(RALLY_AARCH64_PATCH_PATH, "r") as pfile:
61             rally_patch_conf = pfile.read()
62
63         for line in fileinput.input(RALLY_CONF_PATH, inplace=1):
64             print line,
65             if "cirros|testvm" in line:
66                 print rally_patch_conf
67
68     LOGGER.info("Creating Rally environment...")
69
70     cmd = "rally deployment destroy opnfv-rally"
71     ft_utils.execute_command(cmd, error_msg=(
72         "Deployment %s does not exist."
73         % getattr(config.CONF, 'rally_deployment_name')), verbose=False)
74
75     cmd = ("rally deployment create --fromenv --name={0}"
76            .format(getattr(config.CONF, 'rally_deployment_name')))
77     error_msg = "Problem while creating Rally deployment"
78     ft_utils.execute_command_raise(cmd, error_msg=error_msg)
79
80     cmd = "rally deployment check"
81     error_msg = "OpenStack not responding or faulty Rally deployment."
82     ft_utils.execute_command_raise(cmd, error_msg=error_msg)
83
84
85 def create_verifier():
86     """Create new verifier"""
87     LOGGER.info("Create verifier from existing repo...")
88     cmd = ("rally verify delete-verifier --id '{0}' --force").format(
89         getattr(config.CONF, 'tempest_verifier_name'))
90     ft_utils.execute_command(cmd, error_msg=(
91         "Verifier %s does not exist."
92         % getattr(config.CONF, 'tempest_verifier_name')), verbose=False)
93     cmd = ("rally verify create-verifier --source {0} "
94            "--name {1} --type tempest --system-wide"
95            .format(getattr(config.CONF, 'dir_repo_tempest'),
96                    getattr(config.CONF, 'tempest_verifier_name')))
97     ft_utils.execute_command_raise(cmd,
98                                    error_msg='Problem while creating verifier')
99
100
101 def get_verifier_id():
102     """
103     Returns verifier id for current Tempest
104     """
105     create_rally_deployment()
106     create_verifier()
107     cmd = ("rally verify list-verifiers | awk '/" +
108            getattr(config.CONF, 'tempest_verifier_name') +
109            "/ {print $2}'")
110     proc = subprocess.Popen(cmd, shell=True,
111                             stdout=subprocess.PIPE,
112                             stderr=subprocess.STDOUT)
113     deployment_uuid = proc.stdout.readline().rstrip()
114     if deployment_uuid == "":
115         LOGGER.error("Tempest verifier not found.")
116         raise Exception('Error with command:%s' % cmd)
117     return deployment_uuid
118
119
120 def get_verifier_deployment_id():
121     """
122     Returns deployment id for active Rally deployment
123     """
124     cmd = ("rally deployment list | awk '/" +
125            getattr(config.CONF, 'rally_deployment_name') +
126            "/ {print $2}'")
127     proc = subprocess.Popen(cmd, shell=True,
128                             stdout=subprocess.PIPE,
129                             stderr=subprocess.STDOUT)
130     deployment_uuid = proc.stdout.readline().rstrip()
131     if deployment_uuid == "":
132         LOGGER.error("Rally deployment not found.")
133         raise Exception('Error with command:%s' % cmd)
134     return deployment_uuid
135
136
137 def get_verifier_repo_dir(verifier_id):
138     """
139     Returns installed verifier repo directory for Tempest
140     """
141     if not verifier_id:
142         verifier_id = get_verifier_id()
143
144     return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
145                         'verification',
146                         'verifier-{}'.format(verifier_id),
147                         'repo')
148
149
150 def get_verifier_deployment_dir(verifier_id, deployment_id):
151     """
152     Returns Rally deployment directory for current verifier
153     """
154     if not verifier_id:
155         verifier_id = get_verifier_id()
156
157     if not deployment_id:
158         deployment_id = get_verifier_deployment_id()
159
160     return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
161                         'verification',
162                         'verifier-{}'.format(verifier_id),
163                         'for-deployment-{}'.format(deployment_id))
164
165
166 def backup_tempest_config(conf_file, res_dir):
167     """
168     Copy config file to tempest results directory
169     """
170     if not os.path.exists(res_dir):
171         os.makedirs(res_dir)
172     shutil.copyfile(conf_file,
173                     os.path.join(res_dir, 'tempest.conf'))
174
175
176 def generate_test_accounts_file(tenant_id):
177     """
178     Add needed tenant and user params into test_accounts.yaml
179     """
180
181     LOGGER.debug("Add needed params into test_accounts.yaml...")
182     accounts_list = [
183         {
184             'tenant_name': getattr(
185                 config.CONF, 'tempest_identity_tenant_name'),
186             'tenant_id': str(tenant_id),
187             'username': getattr(config.CONF, 'tempest_identity_user_name'),
188             'password': getattr(config.CONF, 'tempest_identity_user_password')
189         }
190     ]
191
192     with open(TEST_ACCOUNTS_FILE, "w") as tfile:
193         yaml.dump(accounts_list, tfile, default_flow_style=False)
194
195
196 def update_tempest_conf_file(conf_file, rconfig):
197     """Update defined paramters into tempest config file"""
198     with open(TEMPEST_CONF_YAML) as yfile:
199         conf_yaml = yaml.safe_load(yfile)
200     if conf_yaml:
201         sections = rconfig.sections()
202         for section in conf_yaml:
203             if section not in sections:
204                 rconfig.add_section(section)
205             sub_conf = conf_yaml.get(section)
206             for key, value in sub_conf.items():
207                 rconfig.set(section, key, value)
208
209     with open(conf_file, 'wb') as config_file:
210         rconfig.write(config_file)
211
212
213 def configure_tempest_update_params(tempest_conf_file, res_dir,
214                                     network_name=None, image_id=None,
215                                     flavor_id=None, compute_cnt=1):
216     # pylint: disable=too-many-branches, too-many-arguments
217     """
218     Add/update needed parameters into tempest.conf file
219     """
220     LOGGER.debug("Updating selected tempest.conf parameters...")
221     rconfig = ConfigParser.RawConfigParser()
222     rconfig.read(tempest_conf_file)
223     rconfig.set('compute', 'fixed_network_name', network_name)
224     rconfig.set('compute', 'volume_device_name', env.get('VOLUME_DEVICE_NAME'))
225     if image_id is not None:
226         rconfig.set('compute', 'image_ref', image_id)
227     if IMAGE_ID_ALT is not None:
228         rconfig.set('compute', 'image_ref_alt', IMAGE_ID_ALT)
229     if getattr(config.CONF, 'tempest_use_custom_flavors'):
230         if flavor_id is not None:
231             rconfig.set('compute', 'flavor_ref', flavor_id)
232         if FLAVOR_ID_ALT is not None:
233             rconfig.set('compute', 'flavor_ref_alt', FLAVOR_ID_ALT)
234     if compute_cnt > 1:
235         # enable multinode tests
236         rconfig.set('compute', 'min_compute_nodes', compute_cnt)
237         rconfig.set('compute-feature-enabled', 'live_migration', True)
238
239     rconfig.set('identity', 'region', os.environ.get('OS_REGION_NAME'))
240     identity_api_version = os.environ.get("OS_IDENTITY_API_VERSION", '3')
241     if identity_api_version == '3':
242         auth_version = 'v3'
243         rconfig.set('identity-feature-enabled', 'api_v2', False)
244     else:
245         auth_version = 'v2'
246     rconfig.set('identity', 'auth_version', auth_version)
247     rconfig.set(
248         'validation', 'ssh_timeout',
249         getattr(config.CONF, 'tempest_validation_ssh_timeout'))
250     rconfig.set('object-storage', 'operator_role',
251                 getattr(config.CONF, 'tempest_object_storage_operator_role'))
252
253     if os.environ.get('OS_ENDPOINT_TYPE') is not None:
254         rconfig.set('identity', 'v3_endpoint_type',
255                     os.environ.get('OS_ENDPOINT_TYPE'))
256
257     rconfig.set('network-feature-enabled', 'api_extensions', 'all')
258
259     if os.environ.get('OS_ENDPOINT_TYPE') is not None:
260         sections = rconfig.sections()
261         services_list = [
262             'compute', 'volume', 'image', 'network', 'data-processing',
263             'object-storage', 'orchestration']
264         for service in services_list:
265             if service not in sections:
266                 rconfig.add_section(service)
267             rconfig.set(service, 'endpoint_type',
268                         os.environ.get('OS_ENDPOINT_TYPE'))
269
270     LOGGER.debug('Add/Update required params defined in tempest_conf.yaml '
271                  'into tempest.conf file')
272     update_tempest_conf_file(tempest_conf_file, rconfig)
273
274     backup_tempest_config(tempest_conf_file, res_dir)
275
276
277 def configure_verifier(deployment_dir):
278     """
279     Execute rally verify configure-verifier, which generates tempest.conf
280     """
281     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
282     if os.path.isfile(tempest_conf_file):
283         LOGGER.debug("Verifier is already configured.")
284         LOGGER.debug("Reconfiguring the current verifier...")
285         cmd = "rally verify configure-verifier --reconfigure"
286     else:
287         LOGGER.info("Configuring the verifier...")
288         cmd = "rally verify configure-verifier"
289     ft_utils.execute_command(cmd)
290
291     LOGGER.debug("Looking for tempest.conf file...")
292     if not os.path.isfile(tempest_conf_file):
293         LOGGER.error("Tempest configuration file %s NOT found.",
294                      tempest_conf_file)
295         raise Exception("Tempest configuration file %s NOT found."
296                         % tempest_conf_file)
297     else:
298         return tempest_conf_file