Add Kubernetes tests to userguide
[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     try:
92         output = subprocess.check_output(cmd)
93         LOGGER.info("%s\n%s", " ".join(cmd), output)
94     except subprocess.CalledProcessError:
95         pass
96
97     cmd = ['rally', 'verify', 'create-verifier',
98            '--source', str(getattr(config.CONF, 'dir_repo_tempest')),
99            '--name', str(getattr(config.CONF, 'tempest_verifier_name')),
100            '--type', 'tempest', '--system-wide']
101     output = subprocess.check_output(cmd)
102     LOGGER.info("%s\n%s", " ".join(cmd), output)
103
104
105 def get_verifier_id():
106     """
107     Returns verifier id for current Tempest
108     """
109     create_rally_deployment()
110     create_verifier()
111     cmd = ("rally verify list-verifiers | awk '/" +
112            getattr(config.CONF, 'tempest_verifier_name') +
113            "/ {print $2}'")
114     proc = subprocess.Popen(cmd, shell=True,
115                             stdout=subprocess.PIPE,
116                             stderr=subprocess.STDOUT)
117     deployment_uuid = proc.stdout.readline().rstrip()
118     if deployment_uuid == "":
119         LOGGER.error("Tempest verifier not found.")
120         raise Exception('Error with command:%s' % cmd)
121     return deployment_uuid
122
123
124 def get_verifier_deployment_id():
125     """
126     Returns deployment id for active Rally deployment
127     """
128     cmd = ("rally deployment list | awk '/" +
129            getattr(config.CONF, 'rally_deployment_name') +
130            "/ {print $2}'")
131     proc = subprocess.Popen(cmd, shell=True,
132                             stdout=subprocess.PIPE,
133                             stderr=subprocess.STDOUT)
134     deployment_uuid = proc.stdout.readline().rstrip()
135     if deployment_uuid == "":
136         LOGGER.error("Rally deployment not found.")
137         raise Exception('Error with command:%s' % cmd)
138     return deployment_uuid
139
140
141 def get_verifier_repo_dir(verifier_id):
142     """
143     Returns installed verifier repo directory for Tempest
144     """
145     if not verifier_id:
146         verifier_id = get_verifier_id()
147
148     return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
149                         'verification',
150                         'verifier-{}'.format(verifier_id),
151                         'repo')
152
153
154 def get_verifier_deployment_dir(verifier_id, deployment_id):
155     """
156     Returns Rally deployment directory for current verifier
157     """
158     if not verifier_id:
159         verifier_id = get_verifier_id()
160
161     if not deployment_id:
162         deployment_id = get_verifier_deployment_id()
163
164     return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
165                         'verification',
166                         'verifier-{}'.format(verifier_id),
167                         'for-deployment-{}'.format(deployment_id))
168
169
170 def backup_tempest_config(conf_file, res_dir):
171     """
172     Copy config file to tempest results directory
173     """
174     if not os.path.exists(res_dir):
175         os.makedirs(res_dir)
176     shutil.copyfile(conf_file,
177                     os.path.join(res_dir, 'tempest.conf'))
178
179
180 def update_tempest_conf_file(conf_file, rconfig):
181     """Update defined paramters into tempest config file"""
182     with open(TEMPEST_CONF_YAML) as yfile:
183         conf_yaml = yaml.safe_load(yfile)
184     if conf_yaml:
185         sections = rconfig.sections()
186         for section in conf_yaml:
187             if section not in sections:
188                 rconfig.add_section(section)
189             sub_conf = conf_yaml.get(section)
190             for key, value in sub_conf.items():
191                 rconfig.set(section, key, value)
192
193     with open(conf_file, 'wb') as config_file:
194         rconfig.write(config_file)
195
196
197 def configure_tempest_update_params(tempest_conf_file, res_dir,
198                                     network_name=None, image_id=None,
199                                     flavor_id=None, compute_cnt=1):
200     # pylint: disable=too-many-branches, too-many-arguments
201     """
202     Add/update needed parameters into tempest.conf file
203     """
204     LOGGER.debug("Updating selected tempest.conf parameters...")
205     rconfig = ConfigParser.RawConfigParser()
206     rconfig.read(tempest_conf_file)
207     rconfig.set('compute', 'fixed_network_name', network_name)
208     rconfig.set('compute', 'volume_device_name', env.get('VOLUME_DEVICE_NAME'))
209     if image_id is not None:
210         rconfig.set('compute', 'image_ref', image_id)
211     if IMAGE_ID_ALT is not None:
212         rconfig.set('compute', 'image_ref_alt', IMAGE_ID_ALT)
213     if getattr(config.CONF, 'tempest_use_custom_flavors'):
214         if flavor_id is not None:
215             rconfig.set('compute', 'flavor_ref', flavor_id)
216         if FLAVOR_ID_ALT is not None:
217             rconfig.set('compute', 'flavor_ref_alt', FLAVOR_ID_ALT)
218     if compute_cnt > 1:
219         # enable multinode tests
220         rconfig.set('compute', 'min_compute_nodes', compute_cnt)
221         rconfig.set('compute-feature-enabled', 'live_migration', True)
222
223     rconfig.set('identity', 'region', os.environ.get('OS_REGION_NAME'))
224     identity_api_version = os.environ.get("OS_IDENTITY_API_VERSION", '3')
225     if identity_api_version == '3':
226         auth_version = 'v3'
227         rconfig.set('identity-feature-enabled', 'api_v2', False)
228     else:
229         auth_version = 'v2'
230     rconfig.set('identity', 'auth_version', auth_version)
231     rconfig.set(
232         'validation', 'ssh_timeout',
233         getattr(config.CONF, 'tempest_validation_ssh_timeout'))
234     rconfig.set('object-storage', 'operator_role',
235                 getattr(config.CONF, 'tempest_object_storage_operator_role'))
236
237     if os.environ.get('OS_ENDPOINT_TYPE') is not None:
238         rconfig.set('identity', 'v3_endpoint_type',
239                     os.environ.get('OS_ENDPOINT_TYPE'))
240
241     if os.environ.get('OS_ENDPOINT_TYPE') is not None:
242         sections = rconfig.sections()
243         services_list = [
244             'compute', 'volume', 'image', 'network', 'data-processing',
245             'object-storage', 'orchestration']
246         for service in services_list:
247             if service not in sections:
248                 rconfig.add_section(service)
249             rconfig.set(service, 'endpoint_type',
250                         os.environ.get('OS_ENDPOINT_TYPE'))
251
252     LOGGER.debug('Add/Update required params defined in tempest_conf.yaml '
253                  'into tempest.conf file')
254     update_tempest_conf_file(tempest_conf_file, rconfig)
255
256     backup_tempest_config(tempest_conf_file, res_dir)
257
258
259 def configure_verifier(deployment_dir):
260     """
261     Execute rally verify configure-verifier, which generates tempest.conf
262     """
263     cmd = ['rally', 'verify', 'configure-verifier', '--reconfigure',
264            '--id', str(getattr(config.CONF, 'tempest_verifier_name'))]
265     output = subprocess.check_output(cmd)
266     LOGGER.info("%s\n%s", " ".join(cmd), output)
267
268     LOGGER.debug("Looking for tempest.conf file...")
269     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
270     if not os.path.isfile(tempest_conf_file):
271         LOGGER.error("Tempest configuration file %s NOT found.",
272                      tempest_conf_file)
273         raise Exception("Tempest configuration file %s NOT found."
274                         % tempest_conf_file)
275     else:
276         return tempest_conf_file