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