Merge "bugfix for finding tempest failed testcase"
[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     Add/update needed parameters into tempest.conf file generated by Rally
114     """
115     tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
116     if os.path.isfile(tempest_conf_file):
117         logger.debug("Verifier is already configured.")
118         logger.debug("Reconfiguring the current verifier...")
119         cmd = "rally verify configure-verifier --reconfigure"
120     else:
121         logger.info("Configuring the verifier...")
122         cmd = "rally verify configure-verifier"
123     ft_utils.execute_command(cmd)
124
125     logger.debug("Looking for tempest.conf file...")
126     if not os.path.isfile(tempest_conf_file):
127         logger.error("Tempest configuration file %s NOT found."
128                      % tempest_conf_file)
129         return releng_constants.EXIT_RUN_ERROR
130
131     logger.debug("Updating selected tempest.conf parameters...")
132     config = ConfigParser.RawConfigParser()
133     config.read(tempest_conf_file)
134     config.set(
135         'compute',
136         'fixed_network_name',
137         CONST.tempest_private_net_name)
138     if CONST.tempest_use_custom_images:
139         if IMAGE_ID is not None:
140             config.set('compute', 'image_ref', IMAGE_ID)
141         if IMAGE_ID_ALT is not None:
142             config.set('compute', 'image_ref_alt', IMAGE_ID_ALT)
143     if CONST.tempest_use_custom_flavors:
144         if FLAVOR_ID is not None:
145             config.set('compute', 'flavor_ref', FLAVOR_ID)
146         if FLAVOR_ID_ALT is not None:
147             config.set('compute', 'flavor_ref_alt', FLAVOR_ID_ALT)
148     config.set('identity', 'tenant_name', CONST.tempest_identity_tenant_name)
149     config.set('identity', 'username', CONST.tempest_identity_user_name)
150     config.set('identity', 'password', CONST.tempest_identity_user_password)
151     config.set(
152         'validation', 'ssh_timeout', CONST.tempest_validation_ssh_timeout)
153     config.set('object-storage', 'operator_role',
154                CONST.tempest_object_storage_operator_role)
155
156     if CONST.OS_ENDPOINT_TYPE is not None:
157         services_list = ['compute',
158                          'volume',
159                          'image',
160                          'network',
161                          'data-processing',
162                          'object-storage',
163                          'orchestration']
164         sections = config.sections()
165         for service in services_list:
166             if service not in sections:
167                 config.add_section(service)
168             config.set(service, 'endpoint_type',
169                        CONST.OS_ENDPOINT_TYPE)
170
171     with open(tempest_conf_file, 'wb') as config_file:
172         config.write(config_file)
173
174     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
175     if not os.path.exists(TEMPEST_RESULTS_DIR):
176         os.makedirs(TEMPEST_RESULTS_DIR)
177
178     shutil.copyfile(tempest_conf_file,
179                     os.path.join(TEMPEST_RESULTS_DIR, 'tempest.conf'))
180
181     return releng_constants.EXIT_OK
182
183
184 def configure_tempest_multisite(deployment_dir):
185     """
186     Add/update needed parameters into tempest.conf file generated by Rally
187     """
188     logger.debug("configure the tempest")
189     configure_tempest(deployment_dir)
190
191     logger.debug("Finding tempest.conf file...")
192     tempest_conf_old = os.path.join(deployment_dir, 'tempest.conf')
193     if not os.path.isfile(tempest_conf_old):
194         logger.error("Tempest configuration file %s NOT found."
195                      % tempest_conf_old)
196         return releng_constants.EXIT_RUN_ERROR
197
198     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
199     cur_path = os.path.split(os.path.realpath(__file__))[0]
200     tempest_conf_file = os.path.join(cur_path, 'tempest_multisite.conf')
201     shutil.copyfile(tempest_conf_old, tempest_conf_file)
202
203     logger.debug("Updating selected tempest.conf parameters...")
204     config = ConfigParser.RawConfigParser()
205     config.read(tempest_conf_file)
206
207     config.set('service_available', 'kingbird', 'true')
208     # cmd = ("openstack endpoint show kingbird | grep publicurl |"
209     #       "awk '{print $4}' | awk -F '/' '{print $4}'")
210     # kingbird_api_version = os.popen(cmd).read()
211     kingbird_api_version = os_utils.get_endpoint(service_type='multisite')
212
213     if CI_INSTALLER_TYPE == 'fuel':
214         # For MOS based setup, the service is accessible
215         # via bind host
216         kingbird_conf_path = "/etc/kingbird/kingbird.conf"
217         installer_type = CI_INSTALLER_TYPE
218         installer_ip = CI_INSTALLER_IP
219         installer_username = CONST.__getattribute__(
220             'multisite_{}_installer_username'.format(installer_type))
221         installer_password = CONST.__getattribute__(
222             'multisite_{}_installer_password'.format(installer_type))
223
224         ssh_options = ("-o UserKnownHostsFile=/dev/null -o "
225                        "StrictHostKeyChecking=no")
226
227         # Get the controller IP from the fuel node
228         cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
229                 \'fuel node --env 1| grep controller | grep "True\|  1" \
230                 | awk -F\| "{print \$5}"\'' % (installer_password,
231                                                ssh_options,
232                                                installer_username,
233                                                installer_ip)
234         multisite_controller_ip = "".join(os.popen(cmd).read().split())
235
236         # Login to controller and get bind host details
237         cmd = 'sshpass -p %s ssh 2>/dev/null  %s %s@%s "ssh %s \\" \
238             grep -e "^bind_" %s  \\""' % (installer_password,
239                                           ssh_options,
240                                           installer_username,
241                                           installer_ip,
242                                           multisite_controller_ip,
243                                           kingbird_conf_path)
244         bind_details = os.popen(cmd).read()
245         bind_details = "".join(bind_details.split())
246         # Extract port number from the bind details
247         bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
248         # Extract ip address from the bind details
249         bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
250                                bind_details)[0]
251         kingbird_endpoint_url = "http://%s:%s/" % (bind_host, bind_port)
252     else:
253         # cmd = "openstack endpoint show kingbird | grep publicurl |\
254         #       awk '{print $4}' | awk -F '/' '{print $3}'"
255         # kingbird_endpoint_url = os.popen(cmd).read()
256         kingbird_endpoint_url = os_utils.get_endpoint(service_type='kingbird')
257
258     try:
259         config.add_section("kingbird")
260     except Exception:
261         logger.info('kingbird section exist')
262     config.set('kingbird', 'endpoint_type', 'publicURL')
263     config.set('kingbird', 'TIME_TO_SYNC', '20')
264     config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
265     config.set('kingbird', 'api_version', kingbird_api_version)
266     with open(tempest_conf_file, 'wb') as config_file:
267         config.write(config_file)
268
269     return releng_constants.EXIT_OK