Move tempest logics in tempest_conf.yaml
[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 from six.moves import configparser
23 import yaml
24
25 from functest.utils import config
26 from functest.utils import env
27 from functest.utils import functest_utils
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, image_id=None, flavor_id=None,
175         compute_cnt=1, image_alt_id=None, flavor_alt_id=None,
176         admin_role_name='admin', cidr='192.168.120.0/24',
177         domain_id='default'):
178     # pylint: disable=too-many-branches,too-many-arguments,too-many-statements
179     """
180     Add/update needed parameters into tempest.conf file
181     """
182     LOGGER.debug("Updating selected tempest.conf parameters...")
183     rconfig = configparser.RawConfigParser()
184     rconfig.read(tempest_conf_file)
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     filters = ['RetryFilter', 'AvailabilityZoneFilter', 'ComputeFilter',
199                'ComputeCapabilitiesFilter', 'ImagePropertiesFilter',
200                'ServerGroupAntiAffinityFilter', 'ServerGroupAffinityFilter']
201     rconfig.set(
202         'compute-feature-enabled', 'scheduler_available_filters',
203         functest_utils.convert_list_to_ini(filters))
204     if os.environ.get('OS_REGION_NAME'):
205         rconfig.set('identity', 'region', os.environ.get('OS_REGION_NAME'))
206     if env.get("NEW_USER_ROLE").lower() != "member":
207         rconfig.set(
208             'auth', 'tempest_roles',
209             functest_utils.convert_list_to_ini([env.get("NEW_USER_ROLE")]))
210     if not json.loads(env.get("USE_DYNAMIC_CREDENTIALS").lower()):
211         rconfig.set('auth', 'use_dynamic_credentials', False)
212         account_file = os.path.join(
213             getattr(config.CONF, 'dir_functest_data'), 'accounts.yaml')
214         assert os.path.exists(
215             account_file), "{} doesn't exist".format(account_file)
216         rconfig.set('auth', 'test_accounts_file', account_file)
217     rconfig.set('identity', 'auth_version', 'v3')
218     rconfig.set('identity', 'admin_role', admin_role_name)
219     rconfig.set('identity', 'admin_domain_scope', True)
220     rconfig.set('identity', 'default_domain_id', domain_id)
221     if not rconfig.has_section('network'):
222         rconfig.add_section('network')
223     rconfig.set('network', 'default_network', cidr)
224     rconfig.set('network', 'project_network_cidr', cidr)
225     rconfig.set('network', 'project_networks_reachable', False)
226     rconfig.set(
227         'validation', 'ssh_timeout',
228         getattr(config.CONF, 'tempest_validation_ssh_timeout'))
229     rconfig.set('object-storage', 'operator_role',
230                 getattr(config.CONF, 'tempest_object_storage_operator_role'))
231     rconfig.set(
232         'identity', 'v3_endpoint_type',
233         os.environ.get('OS_INTERFACE', 'public'))
234
235     sections = rconfig.sections()
236     services_list = [
237         'compute', 'volume', 'image', 'network', 'data-processing',
238         'object-storage', 'orchestration']
239     for service in services_list:
240         if service not in sections:
241             rconfig.add_section(service)
242         rconfig.set(
243             service, 'endpoint_type', os.environ.get('OS_INTERFACE', 'public'))
244
245     LOGGER.debug('Add/Update required params defined in tempest_conf.yaml '
246                  'into tempest.conf file')
247     update_tempest_conf_file(tempest_conf_file, rconfig)
248
249
250 def configure_verifier(deployment_dir):
251     """
252     Execute rally verify configure-verifier, which generates tempest.conf
253     """
254     cmd = ['rally', 'verify', 'configure-verifier', '--reconfigure',
255            '--id', str(getattr(config.CONF, 'tempest_verifier_name'))]
256     output = subprocess.check_output(cmd)
257     LOGGER.info("%s\n%s", " ".join(cmd), output)
258
259     LOGGER.debug("Looking for tempest.conf file...")
260     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
261     if not os.path.isfile(tempest_conf_file):
262         LOGGER.error("Tempest configuration file %s NOT found.",
263                      tempest_conf_file)
264         return None
265     return tempest_conf_file