Merge "[FUNCTEST] Correct right ip is used for public endpoint"
[functest.git] / functest / ci / prepare_env.py
1 #!/usr/bin/env python
2 #
3 # Author: Jose Lausuch (jose.lausuch@ericsson.com)
4 #
5 # Installs the Functest framework within the Docker container
6 # and run the tests automatically
7 #
8 #
9 # All rights reserved. This program and the accompanying materials
10 # are made available under the terms of the Apache License, Version 2.0
11 # which accompanies this distribution, and is available at
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14
15
16 import argparse
17 import json
18 import os
19 import re
20 import subprocess
21 import sys
22
23 import yaml
24 from opnfv.utils import constants as opnfv_constants
25
26 import functest.utils.functest_logger as ft_logger
27 import functest.utils.functest_utils as ft_utils
28 import functest.utils.openstack_utils as os_utils
29 from functest.utils.constants import CONST
30
31 actions = ['start', 'check']
32 parser = argparse.ArgumentParser()
33 parser.add_argument("action", help="Possible actions are: "
34                     "'{d[0]}|{d[1]}' ".format(d=actions))
35 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
36 args = parser.parse_args()
37
38
39 """ logging configuration """
40 logger = ft_logger.Logger("prepare_env").getLogger()
41
42
43 CONFIG_FUNCTEST_PATH = CONST.CONFIG_FUNCTEST_YAML
44 CONFIG_PATCH_PATH = os.path.join(os.path.dirname(
45     CONFIG_FUNCTEST_PATH), "config_patch.yaml")
46
47 with open(CONFIG_PATCH_PATH) as f:
48     functest_patch_yaml = yaml.safe_load(f)
49
50
51 def print_separator():
52     logger.info("==============================================")
53
54
55 def check_env_variables():
56     print_separator()
57     logger.info("Checking environment variables...")
58
59     if CONST.INSTALLER_TYPE is None:
60         logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
61         CONST.INSTALLER_TYPE = "undefined"
62     else:
63         if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
64             logger.warning("INSTALLER_TYPE=%s is not a valid OPNFV installer. "
65                            "Available OPNFV Installers are : %s. "
66                            "Setting INSTALLER_TYPE=undefined."
67                            % (CONST.INSTALLER_TYPE,
68                               opnfv_constants.INSTALLERS))
69             CONST.INSTALLER_TYPE = "undefined"
70         else:
71             logger.info("    INSTALLER_TYPE=%s"
72                         % CONST.INSTALLER_TYPE)
73
74     if CONST.INSTALLER_IP is None:
75         logger.warning("The env variable 'INSTALLER_IP' is not defined. "
76                        "It is needed to fetch the OpenStack credentials. "
77                        "If the credentials are not provided to the "
78                        "container as a volume, please add this env variable "
79                        "to the 'docker run' command.")
80     else:
81         logger.info("    INSTALLER_IP=%s" % CONST.INSTALLER_IP)
82
83     if CONST.DEPLOY_SCENARIO is None:
84         logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
85                        "Setting CI_SCENARIO=undefined.")
86         CONST.DEPLOY_SCENARIO = "undefined"
87     else:
88         logger.info("    DEPLOY_SCENARIO=%s" % CONST.DEPLOY_SCENARIO)
89     if CONST.CI_DEBUG:
90         logger.info("    CI_DEBUG=%s" % CONST.CI_DEBUG)
91
92     if CONST.NODE_NAME:
93         logger.info("    NODE_NAME=%s" % CONST.NODE_NAME)
94
95     if CONST.BUILD_TAG:
96         logger.info("    BUILD_TAG=%s" % CONST.BUILD_TAG)
97
98     if CONST.IS_CI_RUN:
99         logger.info("    IS_CI_RUN=%s" % CONST.IS_CI_RUN)
100
101
102 def create_directories():
103     print_separator()
104     logger.info("Creating needed directories...")
105     if not os.path.exists(CONST.dir_functest_conf):
106         os.makedirs(CONST.dir_functest_conf)
107         logger.info("    %s created." % CONST.dir_functest_conf)
108     else:
109         logger.debug("   %s already exists."
110                      % CONST.dir_functest_conf)
111
112     if not os.path.exists(CONST.dir_functest_data):
113         os.makedirs(CONST.dir_functest_data)
114         logger.info("    %s created." % CONST.dir_functest_data)
115     else:
116         logger.debug("   %s already exists."
117                      % CONST.dir_functest_data)
118
119
120 def source_rc_file():
121     print_separator()
122     logger.info("Fetching RC file...")
123
124     if CONST.openstack_creds is None:
125         logger.warning("The environment variable 'creds' must be set and"
126                        "pointing to the local RC file. Using default: "
127                        "/home/opnfv/functest/conf/openstack.creds ...")
128         os.path.join(CONST.dir_functest_conf, 'openstack.creds')
129
130     if not os.path.isfile(CONST.openstack_creds):
131         logger.info("RC file not provided. "
132                     "Fetching it from the installer...")
133         if CONST.INSTALLER_IP is None:
134             logger.error("The env variable CI_INSTALLER_IP must be provided in"
135                          " order to fetch the credentials from the installer.")
136             sys.exit("Missing CI_INSTALLER_IP.")
137         if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
138             logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
139                          "not a valid OPNFV installer. Available "
140                          "installers are : %s." %
141                          (CONST.INSTALLER_TYPE,
142                           opnfv_constants.INSTALLERS))
143             sys.exit("Wrong INSTALLER_TYPE.")
144
145         cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
146                "-d %s -i %s -a %s"
147                % (CONST.openstack_creds,
148                   CONST.INSTALLER_TYPE,
149                   CONST.INSTALLER_IP))
150         logger.debug("Executing command: %s" % cmd)
151         p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
152         output = p.communicate()[0]
153         logger.debug("\n%s" % output)
154         if p.returncode != 0:
155             logger.error("Failed to fetch credentials from installer.")
156             sys.exit(1)
157     else:
158         logger.info("RC file provided in %s."
159                     % CONST.openstack_creds)
160         if os.path.getsize(CONST.openstack_creds) == 0:
161             logger.error("The file %s is empty."
162                          % CONST.openstack_creds)
163             sys.exit(1)
164
165     logger.info("Sourcing the OpenStack RC file...")
166     creds = os_utils.source_credentials(
167         CONST.openstack_creds)
168     str = ""
169     for key, value in creds.iteritems():
170         if re.search("OS_", key):
171             str += "\n\t\t\t\t\t\t   " + key + "=" + value
172             if key == 'OS_AUTH_URL':
173                 CONST.OS_AUTH_URL = value
174             elif key == 'OS_USERNAME':
175                 CONST.OS_USERNAME = value
176             elif key == 'OS_TENANT_NAME':
177                 CONST.OS_TENANT_NAME = value
178             elif key == 'OS_PASSWORD':
179                 CONST.OS_PASSWORD = value
180     logger.debug("Used credentials: %s" % str)
181     logger.debug("OS_AUTH_URL:%s" % CONST.OS_AUTH_URL)
182     logger.debug("OS_USERNAME:%s" % CONST.OS_USERNAME)
183     logger.debug("OS_TENANT_NAME:%s" % CONST.OS_TENANT_NAME)
184     logger.debug("OS_PASSWORD:%s" % CONST.OS_PASSWORD)
185
186
187 def patch_config_file():
188     updated = False
189     for key in functest_patch_yaml:
190         if key in CONST.DEPLOY_SCENARIO:
191             new_functest_yaml = dict(ft_utils.merge_dicts(
192                 ft_utils.get_functest_yaml(), functest_patch_yaml[key]))
193             updated = True
194
195     if updated:
196         os.remove(CONFIG_FUNCTEST_PATH)
197         with open(CONFIG_FUNCTEST_PATH, "w") as f:
198             f.write(yaml.dump(new_functest_yaml, default_style='"'))
199         f.close()
200
201
202 def verify_deployment():
203     print_separator()
204     logger.info("Verifying OpenStack services...")
205     cmd = ("%s/functest/ci/check_os.sh" % CONST.dir_repo_functest)
206
207     logger.debug("Executing command: %s" % cmd)
208     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
209
210     while p.poll() is None:
211         line = p.stdout.readline().rstrip()
212         if "ERROR" in line:
213             logger.error(line)
214             sys.exit("Problem while running 'check_os.sh'.")
215         logger.info(line)
216
217
218 def install_rally():
219     print_separator()
220     logger.info("Creating Rally environment...")
221
222     cmd = "rally deployment destroy opnfv-rally"
223     ft_utils.execute_command(cmd, error_msg=(
224         "Deployment %s does not exist."
225         % CONST.rally_deployment_name),
226         verbose=False)
227     rally_conf = os_utils.get_credentials_for_rally()
228     with open('rally_conf.json', 'w') as fp:
229         json.dump(rally_conf, fp)
230     cmd = "rally deployment create --file=rally_conf.json --name="
231     cmd += CONST.rally_deployment_name
232     ft_utils.execute_command(cmd,
233                              error_msg="Problem creating Rally deployment")
234
235     logger.info("Installing tempest from existing repo...")
236     cmd = ("rally verify install --source " +
237            CONST.dir_repo_tempest +
238            " --system-wide")
239     ft_utils.execute_command(cmd,
240                              error_msg="Problem installing Tempest.")
241
242     cmd = "rally deployment check"
243     ft_utils.execute_command(cmd,
244                              error_msg=("OpenStack not responding or "
245                                         "faulty Rally deployment."))
246
247     cmd = "rally show images"
248     ft_utils.execute_command(cmd,
249                              error_msg=("Problem while listing "
250                                         "OpenStack images."))
251
252     cmd = "rally show flavors"
253     ft_utils.execute_command(cmd,
254                              error_msg=("Problem while showing "
255                                         "OpenStack flavors."))
256
257
258 def check_environment():
259     msg_not_active = "The Functest environment is not installed."
260     if not os.path.isfile(CONST.env_active):
261         logger.error(msg_not_active)
262         sys.exit(1)
263
264     with open(CONST.env_active, "r") as env_file:
265         s = env_file.read()
266         if not re.search("1", s):
267             logger.error(msg_not_active)
268             sys.exit(1)
269
270     logger.info("Functest environment installed.")
271
272
273 def main():
274     if not (args.action in actions):
275         logger.error('Argument not valid.')
276         sys.exit()
277
278     if args.action == "start":
279         logger.info("######### Preparing Functest environment #########\n")
280         check_env_variables()
281         create_directories()
282         source_rc_file()
283         patch_config_file()
284         verify_deployment()
285         install_rally()
286
287         with open(CONST.env_active, "w") as env_file:
288             env_file.write("1")
289
290         check_environment()
291
292     if args.action == "check":
293         check_environment()
294
295     exit(0)
296
297
298 if __name__ == '__main__':
299     main()