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