Wrap call to the rest api with try-except while generating report
[functest.git] / 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 os
18 import re
19 import subprocess
20 import sys
21 import json
22
23 import functest.utils.functest_logger as ft_logger
24 import functest.utils.functest_utils as ft_utils
25 import functest.utils.openstack_utils as os_utils
26 import yaml
27
28
29 actions = ['start', 'check']
30 parser = argparse.ArgumentParser()
31 parser.add_argument("action", help="Possible actions are: "
32                     "'{d[0]}|{d[1]}' ".format(d=actions))
33 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
34 args = parser.parse_args()
35
36
37 """ logging configuration """
38 logger = ft_logger.Logger("prepare_env").getLogger()
39
40
41 """ global variables """
42 INSTALLERS = ['fuel', 'compass', 'apex', 'joid']
43 CI_INSTALLER_TYPE = ""
44 CI_INSTALLER_IP = ""
45 CI_SCENARIO = ""
46 CI_DEBUG = False
47 REPOS_DIR = os.getenv('repos_dir')
48 FUNCTEST_REPO = REPOS_DIR + '/functest/'
49
50 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
51     functest_yaml = yaml.safe_load(f)
52
53 FUNCTEST_CONF_DIR = functest_yaml.get("general").get(
54     "directories").get("dir_functest_conf")
55
56 FUNCTEST_DATA_DIR = functest_yaml.get("general").get(
57     "directories").get("dir_functest_data")
58 FUNCTEST_RESULTS_DIR = functest_yaml.get("general").get(
59     "directories").get("dir_results")
60 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
61 TEMPEST_REPO_DIR = functest_yaml.get("general").get(
62     "directories").get("dir_repo_tempest")
63
64 ENV_FILE = FUNCTEST_CONF_DIR + "/env_active"
65
66
67 def print_separator():
68     logger.info("==============================================")
69
70
71 def check_env_variables():
72     print_separator()
73     logger.info("Checking environment variables...")
74     global CI_INSTALLER_TYPE
75     global CI_INSTALLER_IP
76     global CI_DEBUG
77     global CI_SCENARIO
78     CI_INSTALLER_TYPE = os.getenv('INSTALLER_TYPE')
79     CI_INSTALLER_IP = os.getenv('INSTALLER_IP')
80     CI_SCENARIO = os.getenv('DEPLOY_SCENARIO')
81     CI_NODE = os.getenv('NODE_NAME')
82     CI_BUILD_TAG = os.getenv('BUILD_TAG')
83     CI_DEBUG = os.getenv('CI_DEBUG')
84
85     if CI_INSTALLER_TYPE is None:
86         logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
87         CI_INSTALLER_TYPE = "undefined"
88     else:
89         if os.getenv('INSTALLER_TYPE') not in INSTALLERS:
90             logger.warning("INSTALLER_TYPE=%s is not a valid OPNFV installer. "
91                            "Available OPNFV Installers are : %s."
92                            "Setting INSTALLER_TYPE=undefined." % INSTALLERS)
93             CI_INSTALLER_TYPE = "undefined"
94         else:
95             logger.info("    INSTALLER_TYPE=%s" % CI_INSTALLER_TYPE)
96
97     if CI_INSTALLER_IP is None:
98         logger.warning("The env variable 'INSTALLER_IP' is not defined. "
99                        "It is needed to fetch the OpenStack credentials. "
100                        "If the credentials are not provided to the "
101                        "container as a volume, please add this env variable "
102                        "to the 'docker run' command.")
103     else:
104         logger.info("    INSTALLER_IP=%s" % CI_INSTALLER_IP)
105
106     if CI_SCENARIO is None:
107         logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
108                        "Setting CE_SCENARIO=undefined.")
109         CI_SCENARIO = "undefined"
110     else:
111         logger.info("    DEPLOY_SCENARIO=%s" % CI_SCENARIO)
112     if CI_DEBUG:
113         logger.info("    CI_DEBUG=%s" % CI_DEBUG)
114
115     if CI_NODE:
116         logger.info("    NODE_NAME=%s" % CI_NODE)
117
118     if CI_BUILD_TAG:
119         logger.info("    BUILD_TAG=%s" % CI_BUILD_TAG)
120
121
122 def create_directories():
123     print_separator()
124     logger.info("Creating needed directories...")
125     if not os.path.exists(FUNCTEST_CONF_DIR):
126         os.makedirs(FUNCTEST_CONF_DIR)
127         logger.info("    %s created." % FUNCTEST_CONF_DIR)
128     else:
129         logger.debug("   %s already exists." % FUNCTEST_CONF_DIR)
130
131     if not os.path.exists(FUNCTEST_DATA_DIR):
132         os.makedirs(FUNCTEST_DATA_DIR)
133         logger.info("    %s created." % FUNCTEST_DATA_DIR)
134     else:
135         logger.debug("   %s already exists." % FUNCTEST_DATA_DIR)
136
137
138 def source_rc_file():
139     print_separator()
140     logger.info("Fetching RC file...")
141     rc_file = os.getenv('creds')
142     if rc_file is None:
143         logger.warning("The environment variable 'creds' must be set and"
144                        "pointing to the local RC file. Using default: "
145                        "/home/opnfv/functest/conf/openstack.creds ...")
146         rc_file = "/home/opnfv/functest/conf/openstack.creds"
147
148     if not os.path.isfile(rc_file):
149         logger.info("RC file not provided. "
150                     "Fetching it from the installer...")
151         if CI_INSTALLER_IP is None:
152             logger.error("The env variable CI_INSTALLER_IP must be provided in"
153                          " order to fetch the credentials from the installer.")
154             sys.exit("Missing CI_INSTALLER_IP.")
155         if CI_INSTALLER_TYPE not in INSTALLERS:
156             logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
157                          "not a valid OPNFV installer. Available "
158                          "installers are : %s." % INSTALLERS)
159             sys.exit("Wrong INSTALLER_TYPE.")
160
161         cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
162                "-d %s -i %s -a %s"
163                % (rc_file, CI_INSTALLER_TYPE, CI_INSTALLER_IP))
164         logger.debug("Executing command: %s" % cmd)
165         p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
166         output = p.communicate()[0]
167         logger.debug("\n%s" % output)
168         if p.returncode != 0:
169             logger.error("Failed to fetch credentials from installer.")
170             sys.exit(1)
171     else:
172         logger.info("RC file provided in %s." % rc_file)
173         if os.path.getsize(rc_file) == 0:
174             logger.error("The file %s is empty." % rc_file)
175             sys.exit(1)
176
177     logger.info("Sourcing the OpenStack RC file...")
178     creds = os_utils.source_credentials(rc_file)
179     str = ""
180     for key, value in creds.iteritems():
181         if re.search("OS_", key):
182             str += "\n\t\t\t\t\t\t   " + key + "=" + value
183     logger.debug("Used credentials: %s" % str)
184
185
186 def verify_deployment():
187     print_separator()
188     logger.info("Verifying OpenStack services...")
189     cmd = ("%s/ci/check_os.sh" % FUNCTEST_REPO)
190
191     logger.debug("Executing command: %s" % cmd)
192     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
193
194     while p.poll() is None:
195         line = p.stdout.readline().rstrip()
196         if "ERROR" in line:
197             logger.error(line)
198             sys.exit("Problem while running 'check_os.sh'.")
199         logger.info(line)
200
201
202 def install_rally():
203     print_separator()
204     logger.info("Creating Rally environment...")
205
206     cmd = "rally deployment destroy opnfv-rally"
207     ft_utils.execute_command(cmd, logger=logger, exit_on_error=False,
208                              error_msg=("Deployment %s does not exist."
209                                         % DEPLOYMENT_MAME), verbose=False)
210     rally_conf = os_utils.get_credentials_for_rally()
211     with open('rally_conf.json', 'w') as fp:
212         json.dump(rally_conf, fp)
213     cmd = "rally deployment create --file=rally_conf.json --name="
214     cmd += DEPLOYMENT_MAME
215     ft_utils.execute_command(cmd, logger,
216                              error_msg="Problem creating Rally deployment")
217
218     logger.info("Installing tempest from existing repo...")
219     cmd = ("rally verify install --source " + TEMPEST_REPO_DIR +
220            " --system-wide")
221     ft_utils.execute_command(cmd, logger,
222                              error_msg="Problem installing Tempest.")
223
224     cmd = "rally deployment check"
225     ft_utils.execute_command(cmd, logger,
226                              error_msg=("OpenStack not responding or "
227                                         "faulty Rally deployment."))
228
229     cmd = "rally show images"
230     ft_utils.execute_command(cmd, logger,
231                              error_msg=("Problem while listing "
232                                         "OpenStack images."))
233
234     cmd = "rally show flavors"
235     ft_utils.execute_command(cmd, logger,
236                              error_msg=("Problem while showing "
237                                         "OpenStack flavors."))
238
239
240 def check_environment():
241     msg_not_active = "The Functest environment is not installed."
242     if not os.path.isfile(ENV_FILE):
243         logger.error(msg_not_active)
244         sys.exit(1)
245
246     with open(ENV_FILE, "r") as env_file:
247         s = env_file.read()
248         if not re.search("1", s):
249             logger.error(msg_not_active)
250             sys.exit(1)
251
252     logger.info("Functest environment installed.")
253
254
255 def main():
256     if not (args.action in actions):
257         logger.error('Argument not valid.')
258         sys.exit()
259
260     if args.action == "start":
261         logger.info("######### Preparing Functest environment #########\n")
262         check_env_variables()
263         create_directories()
264         source_rc_file()
265         verify_deployment()
266         install_rally()
267
268         with open(ENV_FILE, "w") as env_file:
269             env_file.write("1")
270
271         check_environment()
272
273     if args.action == "check":
274         check_environment()
275
276     exit(0)
277
278 if __name__ == '__main__':
279     main()