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