Fix Pep8 issues related to \
[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         os.path.join(ft_constants.FUNCTEST_CONF_DIR, 'openstack.creds')
128
129     if not os.path.isfile(ft_constants.OPENSTACK_CREDS):
130         logger.info("RC file not provided. "
131                     "Fetching it from the installer...")
132         if ft_constants.CI_INSTALLER_IP is None:
133             logger.error("The env variable CI_INSTALLER_IP must be provided in"
134                          " order to fetch the credentials from the installer.")
135             sys.exit("Missing CI_INSTALLER_IP.")
136         if ft_constants.CI_INSTALLER_TYPE not in ft_constants.INSTALLERS:
137             logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
138                          "not a valid OPNFV installer. Available "
139                          "installers are : %s." % ft_constants.INSTALLERS)
140             sys.exit("Wrong INSTALLER_TYPE.")
141
142         cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
143                "-d %s -i %s -a %s"
144                % (ft_constants.OPENSTACK_CREDS,
145                   ft_constants.CI_INSTALLER_TYPE,
146                   ft_constants.CI_INSTALLER_IP))
147         logger.debug("Executing command: %s" % cmd)
148         p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
149         output = p.communicate()[0]
150         logger.debug("\n%s" % output)
151         if p.returncode != 0:
152             logger.error("Failed to fetch credentials from installer.")
153             sys.exit(1)
154     else:
155         logger.info("RC file provided in %s."
156                     % ft_constants.OPENSTACK_CREDS)
157         if os.path.getsize(ft_constants.OPENSTACK_CREDS) == 0:
158             logger.error("The file %s is empty."
159                          % ft_constants.OPENSTACK_CREDS)
160             sys.exit(1)
161
162     logger.info("Sourcing the OpenStack RC file...")
163     creds = os_utils.source_credentials(
164         ft_constants.OPENSTACK_CREDS)
165     str = ""
166     for key, value in creds.iteritems():
167         if re.search("OS_", key):
168             str += "\n\t\t\t\t\t\t   " + key + "=" + value
169             if key == 'OS_AUTH_URL':
170                 ft_constants.OS_AUTH_URL = value
171             elif key == 'OS_USERNAME':
172                 ft_constants.OS_USERNAME = value
173             elif key == 'OS_TENANT_NAME':
174                 ft_constants.OS_TENANT_NAME = value
175             elif key == 'OS_PASSWORD':
176                 ft_constants.OS_PASSWORD = value
177     logger.debug("Used credentials: %s" % str)
178     logger.debug("OS_AUTH_URL:%s" % ft_constants.OS_AUTH_URL)
179     logger.debug("OS_USERNAME:%s" % ft_constants.OS_USERNAME)
180     logger.debug("OS_TENANT_NAME:%s" % ft_constants.OS_TENANT_NAME)
181     logger.debug("OS_PASSWORD:%s" % ft_constants.OS_PASSWORD)
182
183
184 def patch_config_file():
185     updated = False
186     for key in functest_patch_yaml:
187         if key in ft_constants.CI_SCENARIO:
188             new_functest_yaml = dict(ft_utils.merge_dicts(
189                 ft_utils.get_functest_yaml(), functest_patch_yaml[key]))
190             updated = True
191
192     if updated:
193         os.remove(CONFIG_FUNCTEST_PATH)
194         with open(CONFIG_FUNCTEST_PATH, "w") as f:
195             f.write(yaml.dump(new_functest_yaml, default_style='"'))
196         f.close()
197
198
199 def verify_deployment():
200     print_separator()
201     logger.info("Verifying OpenStack services...")
202     cmd = ("%s/functest/ci/check_os.sh" % ft_constants.FUNCTEST_REPO_DIR)
203
204     logger.debug("Executing command: %s" % cmd)
205     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
206
207     while p.poll() is None:
208         line = p.stdout.readline().rstrip()
209         if "ERROR" in line:
210             logger.error(line)
211             sys.exit("Problem while running 'check_os.sh'.")
212         logger.info(line)
213
214
215 def install_rally():
216     print_separator()
217     logger.info("Creating Rally environment...")
218
219     cmd = "rally deployment destroy opnfv-rally"
220     ft_utils.execute_command(cmd, error_msg=(
221         "Deployment %s does not exist."
222         % ft_constants.RALLY_DEPLOYMENT_NAME),
223         verbose=False)
224     rally_conf = os_utils.get_credentials_for_rally()
225     with open('rally_conf.json', 'w') as fp:
226         json.dump(rally_conf, fp)
227     cmd = "rally deployment create --file=rally_conf.json --name="
228     cmd += ft_constants.RALLY_DEPLOYMENT_NAME
229     ft_utils.execute_command(cmd,
230                              error_msg="Problem creating Rally deployment")
231
232     logger.info("Installing tempest from existing repo...")
233     cmd = ("rally verify install --source " +
234            ft_constants.TEMPEST_REPO_DIR +
235            " --system-wide")
236     ft_utils.execute_command(cmd,
237                              error_msg="Problem installing Tempest.")
238
239     cmd = "rally deployment check"
240     ft_utils.execute_command(cmd,
241                              error_msg=("OpenStack not responding or "
242                                         "faulty Rally deployment."))
243
244     cmd = "rally show images"
245     ft_utils.execute_command(cmd,
246                              error_msg=("Problem while listing "
247                                         "OpenStack images."))
248
249     cmd = "rally show flavors"
250     ft_utils.execute_command(cmd,
251                              error_msg=("Problem while showing "
252                                         "OpenStack flavors."))
253
254
255 def check_environment():
256     msg_not_active = "The Functest environment is not installed."
257     if not os.path.isfile(ft_constants.ENV_FILE):
258         logger.error(msg_not_active)
259         sys.exit(1)
260
261     with open(ft_constants.ENV_FILE, "r") as env_file:
262         s = env_file.read()
263         if not re.search("1", s):
264             logger.error(msg_not_active)
265             sys.exit(1)
266
267     logger.info("Functest environment installed.")
268
269
270 def main():
271     if not (args.action in actions):
272         logger.error('Argument not valid.')
273         sys.exit()
274
275     if args.action == "start":
276         logger.info("######### Preparing Functest environment #########\n")
277         check_env_variables()
278         create_directories()
279         source_rc_file()
280         patch_config_file()
281         verify_deployment()
282         install_rally()
283
284         with open(ft_constants.ENV_FILE, "w") as env_file:
285             env_file.write("1")
286
287         check_environment()
288
289     if args.action == "check":
290         check_environment()
291
292     exit(0)
293
294
295 if __name__ == '__main__':
296     main()