Extract util functions from tempest.py to conf_utils
[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
154     if CONST.OS_ENDPOINT_TYPE is not None:
155         services_list = ['compute',
156                          'volume',
157                          'image',
158                          'network',
159                          'data-processing',
160                          'object-storage',
161                          'orchestration']
162         sections = config.sections()
163         for service in services_list:
164             if service not in sections:
165                 config.add_section(service)
166             config.set(service, 'endpoint_type',
167                        CONST.OS_ENDPOINT_TYPE)
168
169     with open(tempest_conf_file, 'wb') as config_file:
170         config.write(config_file)
171
172     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
173     shutil.copyfile(tempest_conf_file,
174                     os.path.join(TEMPEST_RESULTS_DIR, 'tempest.conf'))
175
176     return releng_constants.EXIT_OK
177
178
179 def configure_tempest_multisite(deployment_dir):
180     """
181     Add/update needed parameters into tempest.conf file generated by Rally
182     """
183     logger.debug("configure the tempest")
184     configure_tempest(deployment_dir)
185
186     logger.debug("Finding tempest.conf file...")
187     tempest_conf_old = os.path.join(deployment_dir, 'tempest.conf')
188     if not os.path.isfile(tempest_conf_old):
189         logger.error("Tempest configuration file %s NOT found."
190                      % tempest_conf_old)
191         return releng_constants.EXIT_RUN_ERROR
192
193     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
194     cur_path = os.path.split(os.path.realpath(__file__))[0]
195     tempest_conf_file = os.path.join(cur_path, 'tempest_multisite.conf')
196     shutil.copyfile(tempest_conf_old, tempest_conf_file)
197
198     logger.debug("Updating selected tempest.conf parameters...")
199     config = ConfigParser.RawConfigParser()
200     config.read(tempest_conf_file)
201
202     config.set('service_available', 'kingbird', 'true')
203     # cmd = ("openstack endpoint show kingbird | grep publicurl |"
204     #       "awk '{print $4}' | awk -F '/' '{print $4}'")
205     # kingbird_api_version = os.popen(cmd).read()
206     kingbird_api_version = os_utils.get_endpoint(service_type='kingbird')
207
208     if CI_INSTALLER_TYPE == 'fuel':
209         # For MOS based setup, the service is accessible
210         # via bind host
211         kingbird_conf_path = "/etc/kingbird/kingbird.conf"
212         installer_type = CI_INSTALLER_TYPE
213         installer_ip = CI_INSTALLER_IP
214         installer_username = CONST.__getattribute__(
215             'multisite_{}_installer_username'.format(installer_type))
216         installer_password = CONST.__getattribute__(
217             'multisite_{}_installer_password'.format(installer_type))
218
219         ssh_options = ("-o UserKnownHostsFile=/dev/null -o "
220                        "StrictHostKeyChecking=no")
221
222         # Get the controller IP from the fuel node
223         cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
224                 \'fuel node --env 1| grep controller | grep "True\|  1" \
225                 | awk -F\| "{print \$5}"\'' % (installer_password,
226                                                ssh_options,
227                                                installer_username,
228                                                installer_ip)
229         multisite_controller_ip = "".join(os.popen(cmd).read().split())
230
231         # Login to controller and get bind host details
232         cmd = 'sshpass -p %s ssh 2>/dev/null  %s %s@%s "ssh %s \\" \
233             grep -e "^bind_" %s  \\""' % (installer_password,
234                                           ssh_options,
235                                           installer_username,
236                                           installer_ip,
237                                           multisite_controller_ip,
238                                           kingbird_conf_path)
239         bind_details = os.popen(cmd).read()
240         bind_details = "".join(bind_details.split())
241         # Extract port number from the bind details
242         bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
243         # Extract ip address from the bind details
244         bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
245                                bind_details)[0]
246         kingbird_endpoint_url = "http://%s:%s/" % (bind_host, bind_port)
247     else:
248         # cmd = "openstack endpoint show kingbird | grep publicurl |\
249         #       awk '{print $4}' | awk -F '/' '{print $3}'"
250         # kingbird_endpoint_url = os.popen(cmd).read()
251         kingbird_endpoint_url = os_utils.get_endpoint(service_type='kingbird')
252
253     try:
254         config.add_section("kingbird")
255     except Exception:
256         logger.info('kingbird section exist')
257     config.set('kingbird', 'endpoint_type', 'publicURL')
258     config.set('kingbird', 'TIME_TO_SYNC', '20')
259     config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
260     config.set('kingbird', 'api_version', kingbird_api_version)
261     with open(tempest_conf_file, 'wb') as config_file:
262         config.write(config_file)
263
264     return releng_constants.EXIT_OK