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