Merge "Fix dict conversion in tempest.conf"
[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 from __future__ import print_function
14
15 import json
16 import logging
17 import fileinput
18 import os
19 import subprocess
20
21 import pkg_resources
22 import six
23 from six.moves import configparser
24 import yaml
25
26 from functest.utils import config
27 from functest.utils import env
28
29
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
43 CI_INSTALLER_TYPE = env.get('INSTALLER_TYPE')
44
45 """ logging configuration """
46 LOGGER = logging.getLogger(__name__)
47
48
49 def create_rally_deployment(environ=None):
50     """Create new rally deployment"""
51     # set the architecture to default
52     pod_arch = env.get("POD_ARCH")
53     arch_filter = ['aarch64']
54
55     if pod_arch and pod_arch in arch_filter:
56         LOGGER.info("Apply aarch64 specific to rally config...")
57         with open(RALLY_AARCH64_PATCH_PATH, "r") as pfile:
58             rally_patch_conf = pfile.read()
59
60         for line in fileinput.input(RALLY_CONF_PATH):
61             print(line, end=' ')
62             if "cirros|testvm" in line:
63                 print(rally_patch_conf)
64
65     LOGGER.info("Creating Rally environment...")
66
67     try:
68         cmd = ['rally', 'deployment', 'destroy',
69                '--deployment',
70                str(getattr(config.CONF, 'rally_deployment_name'))]
71         output = subprocess.check_output(cmd)
72         LOGGER.info("%s\n%s", " ".join(cmd), output)
73     except subprocess.CalledProcessError:
74         pass
75
76     cmd = ['rally', 'deployment', 'create', '--fromenv',
77            '--name', str(getattr(config.CONF, 'rally_deployment_name'))]
78     output = subprocess.check_output(cmd, env=environ)
79     LOGGER.info("%s\n%s", " ".join(cmd), output)
80
81     cmd = ['rally', 'deployment', 'check']
82     output = subprocess.check_output(cmd)
83     LOGGER.info("%s\n%s", " ".join(cmd), output)
84     return get_verifier_deployment_id()
85
86
87 def create_verifier():
88     """Create new verifier"""
89     LOGGER.info("Create verifier from existing repo...")
90     cmd = ['rally', 'verify', 'delete-verifier',
91            '--id', str(getattr(config.CONF, 'tempest_verifier_name')),
92            '--force']
93     try:
94         output = subprocess.check_output(cmd)
95         LOGGER.info("%s\n%s", " ".join(cmd), output)
96     except subprocess.CalledProcessError:
97         pass
98
99     cmd = ['rally', 'verify', 'create-verifier',
100            '--source', str(getattr(config.CONF, 'dir_repo_tempest')),
101            '--name', str(getattr(config.CONF, 'tempest_verifier_name')),
102            '--type', 'tempest', '--system-wide']
103     output = subprocess.check_output(cmd)
104     LOGGER.info("%s\n%s", " ".join(cmd), output)
105     return get_verifier_id()
106
107
108 def get_verifier_id():
109     """
110     Returns verifier id for current Tempest
111     """
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     verifier_uuid = proc.stdout.readline().rstrip()
119     return verifier_uuid
120
121
122 def get_verifier_deployment_id():
123     """
124     Returns deployment id for active Rally deployment
125     """
126     cmd = ("rally deployment list | awk '/" +
127            getattr(config.CONF, 'rally_deployment_name') +
128            "/ {print $2}'")
129     proc = subprocess.Popen(cmd, shell=True,
130                             stdout=subprocess.PIPE,
131                             stderr=subprocess.STDOUT)
132     deployment_uuid = proc.stdout.readline().rstrip()
133     return deployment_uuid
134
135
136 def get_verifier_repo_dir(verifier_id):
137     """
138     Returns installed verifier repo directory for Tempest
139     """
140     return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
141                         'verification',
142                         'verifier-{}'.format(verifier_id),
143                         'repo')
144
145
146 def get_verifier_deployment_dir(verifier_id, deployment_id):
147     """
148     Returns Rally deployment directory for current verifier
149     """
150     return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
151                         'verification',
152                         'verifier-{}'.format(verifier_id),
153                         'for-deployment-{}'.format(deployment_id))
154
155
156 def update_tempest_conf_file(conf_file, rconfig):
157     """Update defined paramters into tempest config file"""
158     with open(TEMPEST_CONF_YAML) as yfile:
159         conf_yaml = yaml.safe_load(yfile)
160     if conf_yaml:
161         sections = rconfig.sections()
162         for section in conf_yaml:
163             if section not in sections:
164                 rconfig.add_section(section)
165             sub_conf = conf_yaml.get(section)
166             for key, value in sub_conf.items():
167                 rconfig.set(section, key, value)
168
169     with open(conf_file, 'wb') as config_file:
170         rconfig.write(config_file)
171
172
173 def configure_tempest_update_params(
174         tempest_conf_file, network_name=None, image_id=None, flavor_id=None,
175         compute_cnt=1, image_alt_id=None, flavor_alt_id=None,
176         domain_name="Default"):
177     # pylint: disable=too-many-branches, too-many-arguments
178     """
179     Add/update needed parameters into tempest.conf file
180     """
181     LOGGER.debug("Updating selected tempest.conf parameters...")
182     rconfig = configparser.RawConfigParser()
183     rconfig.read(tempest_conf_file)
184     rconfig.set('compute', 'fixed_network_name', network_name)
185     rconfig.set('compute', 'volume_device_name', env.get('VOLUME_DEVICE_NAME'))
186     if image_id is not None:
187         rconfig.set('compute', 'image_ref', image_id)
188     if image_alt_id is not None:
189         rconfig.set('compute', 'image_ref_alt', image_alt_id)
190     if flavor_id is not None:
191         rconfig.set('compute', 'flavor_ref', flavor_id)
192     if flavor_alt_id is not None:
193         rconfig.set('compute', 'flavor_ref_alt', flavor_alt_id)
194     if compute_cnt > 1:
195         # enable multinode tests
196         rconfig.set('compute', 'min_compute_nodes', compute_cnt)
197         rconfig.set('compute-feature-enabled', 'live_migration', True)
198     rconfig.set('compute-feature-enabled', 'shelve', False)
199     if os.environ.get('OS_REGION_NAME'):
200         rconfig.set('identity', 'region', os.environ.get('OS_REGION_NAME'))
201     identity_api_version = os.environ.get("OS_IDENTITY_API_VERSION", '3')
202     rconfig.set('auth', 'admin_domain_scope', True)
203     rconfig.set('auth', 'default_credentials_domain_name', domain_name)
204     if identity_api_version == '3':
205         auth_version = 'v3'
206         rconfig.set('identity-feature-enabled', 'api_v2', False)
207     else:
208         auth_version = 'v2'
209     if env.get("NEW_USER_ROLE").lower() != "member":
210         rconfig.set(
211             'auth', 'tempest_roles',
212             convert_list_to_ini([env.get("NEW_USER_ROLE")]))
213     if not json.loads(env.get("USE_DYNAMIC_CREDENTIALS").lower()):
214         rconfig.set('auth', 'use_dynamic_credentials', False)
215         account_file = os.path.join(
216             getattr(config.CONF, 'dir_functest_data'), 'accounts.yaml')
217         assert os.path.exists(
218             account_file), "{} doesn't exist".format(account_file)
219         rconfig.set('auth', 'test_accounts_file', account_file)
220     rconfig.set('identity', 'auth_version', auth_version)
221     rconfig.set(
222         'validation', 'ssh_timeout',
223         getattr(config.CONF, 'tempest_validation_ssh_timeout'))
224     rconfig.set('object-storage', 'operator_role',
225                 getattr(config.CONF, 'tempest_object_storage_operator_role'))
226
227     rconfig.set(
228         'identity', 'v3_endpoint_type',
229         os.environ.get('OS_INTERFACE', 'public'))
230
231     sections = rconfig.sections()
232     services_list = [
233         'compute', 'volume', 'image', 'network', 'data-processing',
234         'object-storage', 'orchestration']
235     for service in services_list:
236         if service not in sections:
237             rconfig.add_section(service)
238         rconfig.set(
239             service, 'endpoint_type', os.environ.get('OS_INTERFACE', 'public'))
240
241     LOGGER.debug('Add/Update required params defined in tempest_conf.yaml '
242                  'into tempest.conf file')
243     update_tempest_conf_file(tempest_conf_file, rconfig)
244
245
246 def configure_verifier(deployment_dir):
247     """
248     Execute rally verify configure-verifier, which generates tempest.conf
249     """
250     cmd = ['rally', 'verify', 'configure-verifier', '--reconfigure',
251            '--id', str(getattr(config.CONF, 'tempest_verifier_name'))]
252     output = subprocess.check_output(cmd)
253     LOGGER.info("%s\n%s", " ".join(cmd), output)
254
255     LOGGER.debug("Looking for tempest.conf file...")
256     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
257     if not os.path.isfile(tempest_conf_file):
258         LOGGER.error("Tempest configuration file %s NOT found.",
259                      tempest_conf_file)
260         return None
261     return tempest_conf_file
262
263
264 def convert_dict_to_ini(value):
265     "Convert dict to oslo.conf input"
266     assert isinstance(value, dict)
267     return ",".join("{}:{}".format(
268         key, val) for (key, val) in six.iteritems(value))
269
270
271 def convert_list_to_ini(value):
272     "Convert list to oslo.conf input"
273     assert isinstance(value, list)
274     return ",".join("{}".format(val) for val in value)