Merge "Releng environment in unit testing."
[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                                  choices=actions)
52         self.parser.add_argument("-d", "--debug", help="Debug mode",
53                                  action="store_true")
54
55     def parse_args(self, argv=[]):
56         return vars(self.parser.parse_args(argv))
57
58
59 def print_separator():
60     logger.info("==============================================")
61
62
63 def check_env_variables():
64     print_separator()
65     logger.info("Checking environment variables...")
66
67     if CONST.INSTALLER_TYPE is None:
68         logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
69         CONST.INSTALLER_TYPE = "undefined"
70     else:
71         if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
72             logger.warning("INSTALLER_TYPE=%s is not a valid OPNFV installer. "
73                            "Available OPNFV Installers are : %s. "
74                            "Setting INSTALLER_TYPE=undefined."
75                            % (CONST.INSTALLER_TYPE,
76                               opnfv_constants.INSTALLERS))
77             CONST.INSTALLER_TYPE = "undefined"
78         else:
79             logger.info("    INSTALLER_TYPE=%s"
80                         % CONST.INSTALLER_TYPE)
81
82     if CONST.INSTALLER_IP is None:
83         logger.warning("The env variable 'INSTALLER_IP' is not defined. "
84                        "It is needed to fetch the OpenStack credentials. "
85                        "If the credentials are not provided to the "
86                        "container as a volume, please add this env variable "
87                        "to the 'docker run' command.")
88     else:
89         logger.info("    INSTALLER_IP=%s" % CONST.INSTALLER_IP)
90
91     if CONST.DEPLOY_SCENARIO is None:
92         logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
93                        "Setting CI_SCENARIO=undefined.")
94         CONST.DEPLOY_SCENARIO = "undefined"
95     else:
96         logger.info("    DEPLOY_SCENARIO=%s" % CONST.DEPLOY_SCENARIO)
97     if CONST.CI_DEBUG:
98         logger.info("    CI_DEBUG=%s" % CONST.CI_DEBUG)
99
100     if CONST.NODE_NAME:
101         logger.info("    NODE_NAME=%s" % CONST.NODE_NAME)
102
103     if CONST.BUILD_TAG:
104         logger.info("    BUILD_TAG=%s" % CONST.BUILD_TAG)
105
106     if CONST.IS_CI_RUN:
107         logger.info("    IS_CI_RUN=%s" % CONST.IS_CI_RUN)
108
109
110 def create_directories():
111     print_separator()
112     logger.info("Creating needed directories...")
113     if not os.path.exists(CONST.dir_functest_conf):
114         os.makedirs(CONST.dir_functest_conf)
115         logger.info("    %s created." % CONST.dir_functest_conf)
116     else:
117         logger.debug("   %s already exists."
118                      % CONST.dir_functest_conf)
119
120     if not os.path.exists(CONST.dir_functest_data):
121         os.makedirs(CONST.dir_functest_data)
122         logger.info("    %s created." % CONST.dir_functest_data)
123     else:
124         logger.debug("   %s already exists."
125                      % CONST.dir_functest_data)
126
127
128 def source_rc_file():
129     print_separator()
130     logger.info("Fetching RC file...")
131
132     if CONST.openstack_creds is None:
133         logger.warning("The environment variable 'creds' must be set and"
134                        "pointing to the local RC file. Using default: "
135                        "/home/opnfv/functest/conf/openstack.creds ...")
136         os.path.join(CONST.dir_functest_conf, 'openstack.creds')
137
138     if not os.path.isfile(CONST.openstack_creds):
139         logger.info("RC file not provided. "
140                     "Fetching it from the installer...")
141         if CONST.INSTALLER_IP is None:
142             logger.error("The env variable CI_INSTALLER_IP must be provided in"
143                          " order to fetch the credentials from the installer.")
144             raise Exception("Missing CI_INSTALLER_IP.")
145         if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
146             logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
147                          "not a valid OPNFV installer. Available "
148                          "installers are : %s." %
149                          (CONST.INSTALLER_TYPE,
150                           opnfv_constants.INSTALLERS))
151             raise Exception("Wrong INSTALLER_TYPE.")
152
153         cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
154                "-d %s -i %s -a %s"
155                % (CONST.openstack_creds,
156                   CONST.INSTALLER_TYPE,
157                   CONST.INSTALLER_IP))
158         logger.debug("Executing command: %s" % cmd)
159         p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
160         output = p.communicate()[0]
161         logger.debug("\n%s" % output)
162         if p.returncode != 0:
163             raise Exception("Failed to fetch credentials from installer.")
164     else:
165         logger.info("RC file provided in %s."
166                     % CONST.openstack_creds)
167         if os.path.getsize(CONST.openstack_creds) == 0:
168             raise Exception("The file %s is empty." % CONST.openstack_creds)
169
170     logger.info("Sourcing the OpenStack RC file...")
171     os_utils.source_credentials(
172         CONST.openstack_creds)
173     for key, value in os.environ.iteritems():
174         if re.search("OS_", key):
175             if key == 'OS_AUTH_URL':
176                 CONST.OS_AUTH_URL = value
177             elif key == 'OS_USERNAME':
178                 CONST.OS_USERNAME = value
179             elif key == 'OS_TENANT_NAME':
180                 CONST.OS_TENANT_NAME = value
181             elif key == 'OS_PASSWORD':
182                 CONST.OS_PASSWORD = value
183
184
185 def patch_config_file():
186     updated = False
187     for key in functest_patch_yaml:
188         if key in CONST.DEPLOY_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" % CONST.dir_repo_functest)
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             raise Exception("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         % CONST.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 "
229            "--file=rally_conf.json --name={}"
230            .format(CONST.rally_deployment_name))
231     ft_utils.execute_command(cmd,
232                              error_msg=("Problem while creating "
233                                         "Rally deployment"))
234
235     cmd = "rally deployment check"
236     ft_utils.execute_command(cmd,
237                              error_msg=("OpenStack not responding or "
238                                         "faulty Rally deployment."))
239
240     cmd = "rally deployment list"
241     ft_utils.execute_command(cmd,
242                              error_msg=("Problem while listing "
243                                         "Rally deployment."))
244
245     cmd = "rally plugin list | head -5"
246     ft_utils.execute_command(cmd,
247                              error_msg=("Problem while showing "
248                                         "Rally plugins."))
249
250
251 def install_tempest():
252     logger.info("Installing tempest from existing repo...")
253     cmd = ("rally verify create-verifier --source {0} "
254            "--name {1} --type tempest"
255            .format(CONST.dir_repo_tempest, CONST.tempest_deployment_name))
256     ft_utils.execute_command(cmd,
257                              error_msg="Problem while installing Tempest.")
258
259
260 def create_flavor():
261     os_utils.get_or_create_flavor('m1.tiny',
262                                   '512',
263                                   '1',
264                                   '1',
265                                   public=True)
266
267
268 def check_environment():
269     msg_not_active = "The Functest environment is not installed."
270     if not os.path.isfile(CONST.env_active):
271         raise Exception(msg_not_active)
272
273     with open(CONST.env_active, "r") as env_file:
274         s = env_file.read()
275         if not re.search("1", s):
276             raise Exception(msg_not_active)
277
278     logger.info("Functest environment is installed.")
279
280
281 def main(**kwargs):
282     try:
283         if not (kwargs['action'] in actions):
284             logger.error('Argument not valid.')
285             return -1
286         elif kwargs['action'] == "start":
287             logger.info("######### Preparing Functest environment #########\n")
288             check_env_variables()
289             create_directories()
290             source_rc_file()
291             patch_config_file()
292             verify_deployment()
293             install_rally()
294             install_tempest()
295             create_flavor()
296             with open(CONST.env_active, "w") as env_file:
297                 env_file.write("1")
298             check_environment()
299         elif kwargs['action'] == "check":
300             check_environment()
301     except Exception as e:
302         logger.error(e)
303         return -1
304     return 0
305
306
307 if __name__ == '__main__':
308     parser = PrepareEnvParser()
309     args = parser.parse_args(sys.argv[1:])
310     sys.exit(main(**args))