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