Fix role processing in Patrole
[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 subprocess
18
19 import pkg_resources
20 import yaml
21
22 from functest.utils import config
23 from functest.utils import env
24
25
26 IMAGE_ID_ALT = None
27 FLAVOR_ID_ALT = None
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,
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(tempest_conf_file,
187                                     network_name=None, image_id=None,
188                                     flavor_id=None, compute_cnt=1):
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_ID_ALT is not None:
201         rconfig.set('compute', 'image_ref_alt', IMAGE_ID_ALT)
202     if getattr(config.CONF, 'tempest_use_custom_flavors'):
203         if flavor_id is not None:
204             rconfig.set('compute', 'flavor_ref', flavor_id)
205         if FLAVOR_ID_ALT is not None:
206             rconfig.set('compute', 'flavor_ref_alt', FLAVOR_ID_ALT)
207     if compute_cnt > 1:
208         # enable multinode tests
209         rconfig.set('compute', 'min_compute_nodes', compute_cnt)
210         rconfig.set('compute-feature-enabled', 'live_migration', True)
211
212     rconfig.set('identity', 'region', os.environ.get('OS_REGION_NAME'))
213     identity_api_version = os.environ.get("OS_IDENTITY_API_VERSION", '3')
214     if identity_api_version == '3':
215         auth_version = 'v3'
216         rconfig.set('identity-feature-enabled', 'api_v2', False)
217     else:
218         auth_version = 'v2'
219     rconfig.set('identity', 'auth_version', auth_version)
220     rconfig.set(
221         'validation', 'ssh_timeout',
222         getattr(config.CONF, 'tempest_validation_ssh_timeout'))
223     rconfig.set('object-storage', 'operator_role',
224                 getattr(config.CONF, 'tempest_object_storage_operator_role'))
225
226     if os.environ.get('OS_ENDPOINT_TYPE') is not None:
227         rconfig.set('identity', 'v3_endpoint_type',
228                     os.environ.get('OS_ENDPOINT_TYPE'))
229
230     if os.environ.get('OS_ENDPOINT_TYPE') is not None:
231         sections = rconfig.sections()
232         services_list = [
233             'compute', 'volume', 'image', 'network', 'data-processing',
234             'object-storage', 'orchestration']
235         for service in services_list:
236             if service not in sections:
237                 rconfig.add_section(service)
238             rconfig.set(service, 'endpoint_type',
239                         os.environ.get('OS_ENDPOINT_TYPE'))
240
241     LOGGER.debug('Add/Update required params defined in tempest_conf.yaml '
242                  'into tempest.conf file')
243     update_tempest_conf_file(tempest_conf_file, rconfig)
244
245
246 def configure_verifier(deployment_dir):
247     """
248     Execute rally verify configure-verifier, which generates tempest.conf
249     """
250     cmd = ['rally', 'verify', 'configure-verifier', '--reconfigure',
251            '--id', str(getattr(config.CONF, 'tempest_verifier_name'))]
252     output = subprocess.check_output(cmd)
253     LOGGER.info("%s\n%s", " ".join(cmd), output)
254
255     LOGGER.debug("Looking for tempest.conf file...")
256     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
257     if not os.path.isfile(tempest_conf_file):
258         LOGGER.error("Tempest configuration file %s NOT found.",
259                      tempest_conf_file)
260         raise Exception("Tempest configuration file %s NOT found."
261                         % tempest_conf_file)
262     else:
263         return tempest_conf_file