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