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