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