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