Remove parser tests from fuel onos
[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 with open(CONFIG_FUNCTEST_PATH) as f:
54     functest_yaml = yaml.safe_load(f)
55
56 with open(CONFIG_PATCH_PATH) as f:
57     functest_patch_yaml = yaml.safe_load(f)
58
59 FUNCTEST_CONF_DIR = functest_yaml.get("general").get(
60     "directories").get("dir_functest_conf")
61
62 FUNCTEST_DATA_DIR = functest_yaml.get("general").get(
63     "directories").get("dir_functest_data")
64 FUNCTEST_RESULTS_DIR = functest_yaml.get("general").get(
65     "directories").get("dir_results")
66 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
67 TEMPEST_REPO_DIR = functest_yaml.get("general").get(
68     "directories").get("dir_repo_tempest")
69
70 ENV_FILE = FUNCTEST_CONF_DIR + "/env_active"
71
72
73 def print_separator():
74     logger.info("==============================================")
75
76
77 def check_env_variables():
78     print_separator()
79     logger.info("Checking environment variables...")
80     global CI_INSTALLER_TYPE
81     global CI_INSTALLER_IP
82     global CI_DEBUG
83     global CI_SCENARIO
84     CI_INSTALLER_TYPE = os.getenv('INSTALLER_TYPE')
85     CI_INSTALLER_IP = os.getenv('INSTALLER_IP')
86     CI_SCENARIO = os.getenv('DEPLOY_SCENARIO')
87     CI_NODE = os.getenv('NODE_NAME')
88     CI_BUILD_TAG = os.getenv('BUILD_TAG')
89     CI_DEBUG = os.getenv('CI_DEBUG')
90
91     if CI_INSTALLER_TYPE is None:
92         logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
93         CI_INSTALLER_TYPE = "undefined"
94     else:
95         if os.getenv('INSTALLER_TYPE') not in INSTALLERS:
96             logger.warning("INSTALLER_TYPE=%s is not a valid OPNFV installer. "
97                            "Available OPNFV Installers are : %s."
98                            "Setting INSTALLER_TYPE=undefined." % INSTALLERS)
99             CI_INSTALLER_TYPE = "undefined"
100         else:
101             logger.info("    INSTALLER_TYPE=%s" % CI_INSTALLER_TYPE)
102
103     if CI_INSTALLER_IP is None:
104         logger.warning("The env variable 'INSTALLER_IP' is not defined. "
105                        "It is needed to fetch the OpenStack credentials. "
106                        "If the credentials are not provided to the "
107                        "container as a volume, please add this env variable "
108                        "to the 'docker run' command.")
109     else:
110         logger.info("    INSTALLER_IP=%s" % CI_INSTALLER_IP)
111
112     if CI_SCENARIO is None:
113         logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
114                        "Setting CE_SCENARIO=undefined.")
115         CI_SCENARIO = "undefined"
116     else:
117         logger.info("    DEPLOY_SCENARIO=%s" % CI_SCENARIO)
118     if CI_DEBUG:
119         logger.info("    CI_DEBUG=%s" % CI_DEBUG)
120
121     if CI_NODE:
122         logger.info("    NODE_NAME=%s" % CI_NODE)
123
124     if CI_BUILD_TAG:
125         logger.info("    BUILD_TAG=%s" % CI_BUILD_TAG)
126
127
128 def create_directories():
129     print_separator()
130     logger.info("Creating needed directories...")
131     if not os.path.exists(FUNCTEST_CONF_DIR):
132         os.makedirs(FUNCTEST_CONF_DIR)
133         logger.info("    %s created." % FUNCTEST_CONF_DIR)
134     else:
135         logger.debug("   %s already exists." % FUNCTEST_CONF_DIR)
136
137     if not os.path.exists(FUNCTEST_DATA_DIR):
138         os.makedirs(FUNCTEST_DATA_DIR)
139         logger.info("    %s created." % FUNCTEST_DATA_DIR)
140     else:
141         logger.debug("   %s already exists." % FUNCTEST_DATA_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 patch_config_file():
193     updated = False
194     for key in functest_patch_yaml:
195         if key in CI_SCENARIO:
196             new_functest_yaml = dict(ft_utils.merge_dicts(
197                 functest_yaml, functest_patch_yaml[key]))
198             updated = True
199
200     if updated:
201         os.remove(CONFIG_FUNCTEST_PATH)
202         with open(CONFIG_FUNCTEST_PATH, "w") as f:
203             f.write(yaml.dump(new_functest_yaml, default_style='"'))
204         f.close()
205
206
207 def verify_deployment():
208     print_separator()
209     logger.info("Verifying OpenStack services...")
210     cmd = ("%s/ci/check_os.sh" % FUNCTEST_REPO)
211
212     logger.debug("Executing command: %s" % cmd)
213     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
214
215     while p.poll() is None:
216         line = p.stdout.readline().rstrip()
217         if "ERROR" in line:
218             logger.error(line)
219             sys.exit("Problem while running 'check_os.sh'.")
220         logger.info(line)
221
222
223 def install_rally():
224     print_separator()
225     logger.info("Creating Rally environment...")
226
227     cmd = "rally deployment destroy opnfv-rally"
228     ft_utils.execute_command(cmd, logger=logger, exit_on_error=False,
229                              error_msg=("Deployment %s does not exist."
230                                         % DEPLOYMENT_MAME), verbose=False)
231     rally_conf = os_utils.get_credentials_for_rally()
232     with open('rally_conf.json', 'w') as fp:
233         json.dump(rally_conf, fp)
234     cmd = "rally deployment create --file=rally_conf.json --name="
235     cmd += DEPLOYMENT_MAME
236     ft_utils.execute_command(cmd, logger,
237                              error_msg="Problem creating Rally deployment")
238
239     logger.info("Installing tempest from existing repo...")
240     cmd = ("rally verify install --source " + TEMPEST_REPO_DIR +
241            " --system-wide")
242     ft_utils.execute_command(cmd, logger,
243                              error_msg="Problem installing Tempest.")
244
245     cmd = "rally deployment check"
246     ft_utils.execute_command(cmd, logger,
247                              error_msg=("OpenStack not responding or "
248                                         "faulty Rally deployment."))
249
250     cmd = "rally show images"
251     ft_utils.execute_command(cmd, logger,
252                              error_msg=("Problem while listing "
253                                         "OpenStack images."))
254
255     cmd = "rally show flavors"
256     ft_utils.execute_command(cmd, logger,
257                              error_msg=("Problem while showing "
258                                         "OpenStack flavors."))
259
260
261 def check_environment():
262     msg_not_active = "The Functest environment is not installed."
263     if not os.path.isfile(ENV_FILE):
264         logger.error(msg_not_active)
265         sys.exit(1)
266
267     with open(ENV_FILE, "r") as env_file:
268         s = env_file.read()
269         if not re.search("1", s):
270             logger.error(msg_not_active)
271             sys.exit(1)
272
273     logger.info("Functest environment installed.")
274
275
276 def main():
277     if not (args.action in actions):
278         logger.error('Argument not valid.')
279         sys.exit()
280
281     if args.action == "start":
282         logger.info("######### Preparing Functest environment #########\n")
283         check_env_variables()
284         create_directories()
285         source_rc_file()
286         patch_config_file()
287         verify_deployment()
288         install_rally()
289
290         with open(ENV_FILE, "w") as env_file:
291             env_file.write("1")
292
293         check_environment()
294
295     if args.action == "check":
296         check_environment()
297
298     exit(0)
299
300 if __name__ == '__main__':
301     main()