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