[tempest/defcore] Configure volume device name
[functest.git] / functest / opnfv_tests / openstack / tempest / conf_utils.py
1 #!/usr/bin/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 import ConfigParser
11 import os
12 import re
13 import shutil
14 import subprocess
15
16 from functest.utils.constants import CONST
17 import functest.utils.functest_logger as ft_logger
18 import functest.utils.functest_utils as ft_utils
19 import functest.utils.openstack_utils as os_utils
20
21
22 IMAGE_ID_ALT = None
23 FLAVOR_ID_ALT = None
24 REPO_PATH = CONST.dir_repo_functest
25 GLANCE_IMAGE_PATH = os.path.join(CONST.dir_functest_data,
26                                  CONST.openstack_image_file_name)
27 TEMPEST_TEST_LIST_DIR = CONST.dir_tempest_cases
28 TEMPEST_RESULTS_DIR = os.path.join(CONST.dir_results,
29                                    'tempest')
30 TEMPEST_CUSTOM = os.path.join(REPO_PATH, TEMPEST_TEST_LIST_DIR,
31                               'test_list.txt')
32 TEMPEST_BLACKLIST = os.path.join(REPO_PATH, TEMPEST_TEST_LIST_DIR,
33                                  'blacklist.txt')
34 TEMPEST_DEFCORE = os.path.join(REPO_PATH, TEMPEST_TEST_LIST_DIR,
35                                'defcore_req.txt')
36 TEMPEST_RAW_LIST = os.path.join(TEMPEST_RESULTS_DIR, 'test_raw_list.txt')
37 TEMPEST_LIST = os.path.join(TEMPEST_RESULTS_DIR, 'test_list.txt')
38
39 CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
40 CI_INSTALLER_IP = CONST.INSTALLER_IP
41
42 """ logging configuration """
43 logger = ft_logger.Logger("Tempest").getLogger()
44
45
46 def get_verifier_id():
47     """
48     Returns verifer id for current Tempest
49     """
50     cmd = ("rally verify list-verifiers | awk '/" +
51            CONST.tempest_deployment_name +
52            "/ {print $2}'")
53     p = subprocess.Popen(cmd, shell=True,
54                          stdout=subprocess.PIPE,
55                          stderr=subprocess.STDOUT)
56     deployment_uuid = p.stdout.readline().rstrip()
57     if deployment_uuid == "":
58         logger.error("Tempest verifier not found.")
59         raise Exception('Error with command:%s' % cmd)
60     return deployment_uuid
61
62
63 def get_verifier_deployment_id():
64     """
65     Returns deployment id for active Rally deployment
66     """
67     cmd = ("rally deployment list | awk '/" +
68            CONST.rally_deployment_name +
69            "/ {print $2}'")
70     p = subprocess.Popen(cmd, shell=True,
71                          stdout=subprocess.PIPE,
72                          stderr=subprocess.STDOUT)
73     deployment_uuid = p.stdout.readline().rstrip()
74     if deployment_uuid == "":
75         logger.error("Rally deployment not found.")
76         raise Exception('Error with command:%s' % cmd)
77     return deployment_uuid
78
79
80 def get_verifier_repo_dir(verifier_id):
81     """
82     Returns installed verfier repo directory for Tempest
83     """
84     if not verifier_id:
85         verifier_id = get_verifier_id()
86
87     return os.path.join(CONST.dir_rally_inst,
88                         'verification',
89                         'verifier-{}'.format(verifier_id),
90                         'repo')
91
92
93 def get_verifier_deployment_dir(verifier_id, deployment_id):
94     """
95     Returns Rally deployment directory for current verifier
96     """
97     if not verifier_id:
98         verifier_id = get_verifier_id()
99
100     if not deployment_id:
101         deployment_id = get_verifier_deployment_id()
102
103     return os.path.join(CONST.dir_rally_inst,
104                         'verification',
105                         'verifier-{}'.format(verifier_id),
106                         'for-deployment-{}'.format(deployment_id))
107
108
109 def get_repo_tag(repo):
110     """
111     Returns last tag of current branch
112     """
113     cmd = ("git -C {0} describe --abbrev=0 HEAD".format(repo))
114     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
115     tag = p.stdout.readline().rstrip()
116
117     return str(tag)
118
119
120 def backup_tempest_config(conf_file):
121     """
122     Copy config file to tempest results directory
123     """
124     if not os.path.exists(TEMPEST_RESULTS_DIR):
125         os.makedirs(TEMPEST_RESULTS_DIR)
126
127     shutil.copyfile(conf_file,
128                     os.path.join(TEMPEST_RESULTS_DIR, 'tempest.conf'))
129
130
131 def configure_tempest(deployment_dir, IMAGE_ID=None, FLAVOR_ID=None,
132                       MODE=None):
133     """
134     Calls rally verify and updates the generated tempest.conf with
135     given parameters
136     """
137     conf_file = configure_verifier(deployment_dir)
138     configure_tempest_update_params(conf_file,
139                                     IMAGE_ID, FLAVOR_ID)
140     if MODE == 'feature_multisite':
141         configure_tempest_multisite_params(conf_file)
142
143
144 def configure_tempest_update_params(tempest_conf_file,
145                                     IMAGE_ID=None, FLAVOR_ID=None):
146     """
147     Add/update needed parameters into tempest.conf file
148     """
149     logger.debug("Updating selected tempest.conf parameters...")
150     config = ConfigParser.RawConfigParser()
151     config.read(tempest_conf_file)
152     config.set(
153         'compute',
154         'fixed_network_name',
155         CONST.tempest_private_net_name)
156     config.set('compute', 'volume_device_name',
157                CONST.tempest_volume_device_name)
158     if CONST.tempest_use_custom_images:
159         if IMAGE_ID is not None:
160             config.set('compute', 'image_ref', IMAGE_ID)
161         if IMAGE_ID_ALT is not None:
162             config.set('compute', 'image_ref_alt', IMAGE_ID_ALT)
163     if CONST.tempest_use_custom_flavors:
164         if FLAVOR_ID is not None:
165             config.set('compute', 'flavor_ref', FLAVOR_ID)
166         if FLAVOR_ID_ALT is not None:
167             config.set('compute', 'flavor_ref_alt', FLAVOR_ID_ALT)
168     config.set('identity', 'tenant_name', CONST.tempest_identity_tenant_name)
169     config.set('identity', 'username', CONST.tempest_identity_user_name)
170     config.set('identity', 'password', CONST.tempest_identity_user_password)
171     config.set(
172         'validation', 'ssh_timeout', CONST.tempest_validation_ssh_timeout)
173     config.set('object-storage', 'operator_role',
174                CONST.tempest_object_storage_operator_role)
175
176     if CONST.OS_ENDPOINT_TYPE is not None:
177         services_list = ['compute',
178                          'volume',
179                          'image',
180                          'network',
181                          'data-processing',
182                          'object-storage',
183                          'orchestration']
184         sections = config.sections()
185         for service in services_list:
186             if service not in sections:
187                 config.add_section(service)
188             config.set(service, 'endpoint_type',
189                        CONST.OS_ENDPOINT_TYPE)
190
191     with open(tempest_conf_file, 'wb') as config_file:
192         config.write(config_file)
193
194     backup_tempest_config(tempest_conf_file)
195
196
197 def configure_verifier(deployment_dir):
198     """
199     Execute rally verify configure-verifier, which generates tempest.conf
200     """
201     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
202     if os.path.isfile(tempest_conf_file):
203         logger.debug("Verifier is already configured.")
204         logger.debug("Reconfiguring the current verifier...")
205         cmd = "rally verify configure-verifier --reconfigure"
206     else:
207         logger.info("Configuring the verifier...")
208         cmd = "rally verify configure-verifier"
209     ft_utils.execute_command(cmd)
210
211     logger.debug("Looking for tempest.conf file...")
212     if not os.path.isfile(tempest_conf_file):
213         logger.error("Tempest configuration file %s NOT found."
214                      % tempest_conf_file)
215         raise Exception("Tempest configuration file %s NOT found."
216                         % tempest_conf_file)
217     else:
218         return tempest_conf_file
219
220
221 def configure_tempest_multisite_params(tempest_conf_file):
222     """
223     Add/update multisite parameters into tempest.conf file generated by Rally
224     """
225     logger.debug("Updating multisite tempest.conf parameters...")
226     config = ConfigParser.RawConfigParser()
227     config.read(tempest_conf_file)
228
229     config.set('service_available', 'kingbird', 'true')
230     # cmd = ("openstack endpoint show kingbird | grep publicurl |"
231     #       "awk '{print $4}' | awk -F '/' '{print $4}'")
232     # kingbird_api_version = os.popen(cmd).read()
233     kingbird_api_version = os_utils.get_endpoint(service_type='multisite')
234
235     if CI_INSTALLER_TYPE == 'fuel':
236         # For MOS based setup, the service is accessible
237         # via bind host
238         kingbird_conf_path = "/etc/kingbird/kingbird.conf"
239         installer_type = CI_INSTALLER_TYPE
240         installer_ip = CI_INSTALLER_IP
241         installer_username = CONST.__getattribute__(
242             'multisite_{}_installer_username'.format(installer_type))
243         installer_password = CONST.__getattribute__(
244             'multisite_{}_installer_password'.format(installer_type))
245
246         ssh_options = ("-o UserKnownHostsFile=/dev/null -o "
247                        "StrictHostKeyChecking=no")
248
249         # Get the controller IP from the fuel node
250         cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
251                 \'fuel node --env 1| grep controller | grep "True\|  1" \
252                 | awk -F\| "{print \$5}"\'' % (installer_password,
253                                                ssh_options,
254                                                installer_username,
255                                                installer_ip)
256         multisite_controller_ip = "".join(os.popen(cmd).read().split())
257
258         # Login to controller and get bind host details
259         cmd = 'sshpass -p %s ssh 2>/dev/null  %s %s@%s "ssh %s \\" \
260             grep -e "^bind_" %s  \\""' % (installer_password,
261                                           ssh_options,
262                                           installer_username,
263                                           installer_ip,
264                                           multisite_controller_ip,
265                                           kingbird_conf_path)
266         bind_details = os.popen(cmd).read()
267         bind_details = "".join(bind_details.split())
268         # Extract port number from the bind details
269         bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
270         # Extract ip address from the bind details
271         bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
272                                bind_details)[0]
273         kingbird_endpoint_url = "http://%s:%s/" % (bind_host, bind_port)
274     else:
275         # cmd = "openstack endpoint show kingbird | grep publicurl |\
276         #       awk '{print $4}' | awk -F '/' '{print $3}'"
277         # kingbird_endpoint_url = os.popen(cmd).read()
278         kingbird_endpoint_url = os_utils.get_endpoint(service_type='kingbird')
279
280     try:
281         config.add_section("kingbird")
282     except Exception:
283         logger.info('kingbird section exist')
284     config.set('kingbird', 'endpoint_type', 'publicURL')
285     config.set('kingbird', 'TIME_TO_SYNC', '20')
286     config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
287     config.set('kingbird', 'api_version', kingbird_api_version)
288     with open(tempest_conf_file, 'wb') as config_file:
289         config.write(config_file)
290
291     backup_tempest_config(tempest_conf_file)
292
293
294 def install_verifier_ext(path):
295     """
296     Install extension to active verifier
297     """
298     logger.info("Installing verifier from existing repo...")
299     tag = get_repo_tag(path)
300     cmd = ("rally verify add-verifier-ext --source {0} "
301            "--version {1}"
302            .format(path, tag))
303     error_msg = ("Problem while adding verifier extension from %s" % path)
304     ft_utils.execute_command_raise(cmd, error_msg=error_msg)