Merge "[cloudify_ims] Change VNF flavor value"
[functest.git] / functest / ci / prepare_env.py
1 #!/usr/bin/env python
2 #
3 # All rights reserved. This program and the accompanying materials
4 # are made available under the terms of the Apache License, Version 2.0
5 # which accompanies this distribution, and is available at
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8
9 import argparse
10 import json
11 import os
12 import re
13 import subprocess
14 import sys
15 import fileinput
16
17 import yaml
18
19 import functest.utils.functest_logger as ft_logger
20 import functest.utils.functest_utils as ft_utils
21 import functest.utils.openstack_utils as os_utils
22 from functest.utils.constants import CONST
23
24 from opnfv.utils import constants as opnfv_constants
25 from opnfv.deployment import factory
26
27 actions = ['start', 'check']
28
29 """ logging configuration """
30 logger = ft_logger.Logger("prepare_env").getLogger()
31 handler = None
32 # set the architecture to default
33 pod_arch = None
34 arch_filter = ['aarch64']
35
36 CONFIG_FUNCTEST_PATH = CONST.CONFIG_FUNCTEST_YAML
37 CONFIG_PATCH_PATH = os.path.join(os.path.dirname(
38     CONFIG_FUNCTEST_PATH), "config_patch.yaml")
39 CONFIG_AARCH64_PATCH_PATH = os.path.join(os.path.dirname(
40     CONFIG_FUNCTEST_PATH), "config_aarch64_patch.yaml")
41 RALLY_CONF_PATH = os.path.join("/etc/rally/rally.conf")
42 RALLY_AARCH64_PATCH_PATH = os.path.join(os.path.dirname(
43     CONFIG_FUNCTEST_PATH), "rally_aarch64_patch.conf")
44
45
46 class PrepareEnvParser(object):
47
48     def __init__(self):
49         self.parser = argparse.ArgumentParser()
50         self.parser.add_argument("action", help="Possible actions are: "
51                                  "'{d[0]}|{d[1]}' ".format(d=actions),
52                                  choices=actions)
53         self.parser.add_argument("-d", "--debug", help="Debug mode",
54                                  action="store_true")
55
56     def parse_args(self, argv=[]):
57         return vars(self.parser.parse_args(argv))
58
59
60 def print_separator():
61     logger.info("==============================================")
62
63
64 def check_env_variables():
65     print_separator()
66     logger.info("Checking environment variables...")
67
68     if CONST.INSTALLER_TYPE is None:
69         logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
70         CONST.INSTALLER_TYPE = "undefined"
71     else:
72         if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
73             logger.warning("INSTALLER_TYPE=%s is not a valid OPNFV installer. "
74                            "Available OPNFV Installers are : %s. "
75                            "Setting INSTALLER_TYPE=undefined."
76                            % (CONST.INSTALLER_TYPE,
77                               opnfv_constants.INSTALLERS))
78             CONST.INSTALLER_TYPE = "undefined"
79         else:
80             logger.info("    INSTALLER_TYPE=%s"
81                         % CONST.INSTALLER_TYPE)
82
83     if CONST.INSTALLER_IP is None:
84         logger.warning("The env variable 'INSTALLER_IP' is not defined. "
85                        "It is needed to fetch the OpenStack credentials. "
86                        "If the credentials are not provided to the "
87                        "container as a volume, please add this env variable "
88                        "to the 'docker run' command.")
89     else:
90         logger.info("    INSTALLER_IP=%s" % CONST.INSTALLER_IP)
91
92     if CONST.DEPLOY_SCENARIO is None:
93         logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
94                        "Setting CI_SCENARIO=undefined.")
95         CONST.DEPLOY_SCENARIO = "undefined"
96     else:
97         logger.info("    DEPLOY_SCENARIO=%s" % CONST.DEPLOY_SCENARIO)
98     if CONST.CI_DEBUG:
99         logger.info("    CI_DEBUG=%s" % CONST.CI_DEBUG)
100
101     if CONST.NODE_NAME:
102         logger.info("    NODE_NAME=%s" % CONST.NODE_NAME)
103
104     if CONST.BUILD_TAG:
105         logger.info("    BUILD_TAG=%s" % CONST.BUILD_TAG)
106
107     if CONST.IS_CI_RUN:
108         logger.info("    IS_CI_RUN=%s" % CONST.IS_CI_RUN)
109
110
111 def get_deployment_handler():
112     global handler
113     global pod_arch
114
115     installer_params_yaml = os.path.join(CONST.dir_repo_functest,
116                                          'functest/ci/installer_params.yaml')
117     if (CONST.INSTALLER_IP and CONST.INSTALLER_TYPE and
118             CONST.INSTALLER_TYPE in opnfv_constants.INSTALLERS):
119         try:
120             installer_params = ft_utils.get_parameter_from_yaml(
121                 CONST.INSTALLER_TYPE, installer_params_yaml)
122         except ValueError as e:
123             logger.debug('Printing deployment info is not supported for %s' %
124                          CONST.INSTALLER_TYPE)
125             logger.debug(e)
126         else:
127             user = installer_params.get('user', None)
128             password = installer_params.get('password', None)
129             pkey = installer_params.get('pkey', None)
130             try:
131                 handler = factory.Factory.get_handler(
132                     installer=CONST.INSTALLER_TYPE,
133                     installer_ip=CONST.INSTALLER_IP,
134                     installer_user=user,
135                     installer_pwd=password,
136                     pkey_file=pkey)
137                 if handler:
138                     pod_arch = handler.get_arch()
139             except Exception as e:
140                 logger.debug("Cannot get deployment information. %s" % e)
141
142
143 def create_directories():
144     print_separator()
145     logger.info("Creating needed directories...")
146     if not os.path.exists(CONST.dir_functest_conf):
147         os.makedirs(CONST.dir_functest_conf)
148         logger.info("    %s created." % CONST.dir_functest_conf)
149     else:
150         logger.debug("   %s already exists."
151                      % CONST.dir_functest_conf)
152
153     if not os.path.exists(CONST.dir_functest_data):
154         os.makedirs(CONST.dir_functest_data)
155         logger.info("    %s created." % CONST.dir_functest_data)
156     else:
157         logger.debug("   %s already exists."
158                      % CONST.dir_functest_data)
159
160
161 def source_rc_file():
162     print_separator()
163     logger.info("Fetching RC file...")
164
165     if CONST.openstack_creds is None:
166         logger.warning("The environment variable 'creds' must be set and"
167                        "pointing to the local RC file. Using default: "
168                        "/home/opnfv/functest/conf/openstack.creds ...")
169         os.path.join(CONST.dir_functest_conf, 'openstack.creds')
170
171     if not os.path.isfile(CONST.openstack_creds):
172         logger.info("RC file not provided. "
173                     "Fetching it from the installer...")
174         if CONST.INSTALLER_IP is None:
175             logger.error("The env variable CI_INSTALLER_IP must be provided in"
176                          " order to fetch the credentials from the installer.")
177             raise Exception("Missing CI_INSTALLER_IP.")
178         if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
179             logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
180                          "not a valid OPNFV installer. Available "
181                          "installers are : %s." %
182                          (CONST.INSTALLER_TYPE,
183                           opnfv_constants.INSTALLERS))
184             raise Exception("Wrong INSTALLER_TYPE.")
185
186         cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
187                "-d %s -i %s -a %s"
188                % (CONST.openstack_creds,
189                   CONST.INSTALLER_TYPE,
190                   CONST.INSTALLER_IP))
191         logger.debug("Executing command: %s" % cmd)
192         p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
193         output = p.communicate()[0]
194         logger.debug("\n%s" % output)
195         if p.returncode != 0:
196             raise Exception("Failed to fetch credentials from installer.")
197     else:
198         logger.info("RC file provided in %s."
199                     % CONST.openstack_creds)
200         if os.path.getsize(CONST.openstack_creds) == 0:
201             raise Exception("The file %s is empty." % CONST.openstack_creds)
202
203     logger.info("Sourcing the OpenStack RC file...")
204     os_utils.source_credentials(CONST.openstack_creds)
205     for key, value in os.environ.iteritems():
206         if re.search("OS_", key):
207             if key == 'OS_AUTH_URL':
208                 CONST.OS_AUTH_URL = value
209             elif key == 'OS_USERNAME':
210                 CONST.OS_USERNAME = value
211             elif key == 'OS_TENANT_NAME':
212                 CONST.OS_TENANT_NAME = value
213             elif key == 'OS_PASSWORD':
214                 CONST.OS_PASSWORD = value
215
216
217 def patch_config_file():
218     patch_file(CONFIG_PATCH_PATH)
219
220     if pod_arch and pod_arch in arch_filter:
221         patch_file(CONFIG_AARCH64_PATCH_PATH)
222
223
224 def patch_file(patch_file_path):
225     logger.debug('Updating file: %s', patch_file_path)
226     with open(patch_file_path) as f:
227         patch_file = yaml.safe_load(f)
228
229     updated = False
230     for key in patch_file:
231         if key in CONST.DEPLOY_SCENARIO:
232             new_functest_yaml = dict(ft_utils.merge_dicts(
233                 ft_utils.get_functest_yaml(), patch_file[key]))
234             updated = True
235
236     if updated:
237         os.remove(CONFIG_FUNCTEST_PATH)
238         with open(CONFIG_FUNCTEST_PATH, "w") as f:
239             f.write(yaml.dump(new_functest_yaml, default_style='"'))
240         f.close()
241
242
243 def verify_deployment():
244     print_separator()
245     logger.info("Verifying OpenStack services...")
246     cmd = ("%s/functest/ci/check_os.sh" % CONST.dir_repo_functest)
247
248     logger.debug("Executing command: %s" % cmd)
249     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
250
251     while p.poll() is None:
252         line = p.stdout.readline().rstrip()
253         if "ERROR" in line:
254             logger.error(line)
255             raise Exception("Problem while running 'check_os.sh'.")
256         logger.info(line)
257
258
259 def install_rally():
260     print_separator()
261
262     if pod_arch and pod_arch in arch_filter:
263         logger.info("Apply aarch64 specific to rally config...")
264         with open(RALLY_AARCH64_PATCH_PATH, "r") as f:
265             rally_patch_conf = f.read()
266
267         for line in fileinput.input(RALLY_CONF_PATH, inplace=1):
268             print line,
269             if "cirros|testvm" in line:
270                 print rally_patch_conf
271
272     logger.info("Creating Rally environment...")
273
274     cmd = "rally deployment destroy opnfv-rally"
275     ft_utils.execute_command(cmd, error_msg=(
276         "Deployment %s does not exist."
277         % CONST.rally_deployment_name),
278         verbose=False)
279
280     rally_conf = os_utils.get_credentials_for_rally()
281     with open('rally_conf.json', 'w') as fp:
282         json.dump(rally_conf, fp)
283     cmd = ("rally deployment create "
284            "--file=rally_conf.json --name={0}"
285            .format(CONST.rally_deployment_name))
286     error_msg = "Problem while creating Rally deployment"
287     ft_utils.execute_command_raise(cmd, error_msg=error_msg)
288
289     cmd = "rally deployment check"
290     error_msg = "OpenStack not responding or faulty Rally deployment."
291     ft_utils.execute_command_raise(cmd, error_msg=error_msg)
292
293     cmd = "rally deployment list"
294     ft_utils.execute_command(cmd,
295                              error_msg=("Problem while listing "
296                                         "Rally deployment."))
297
298     cmd = "rally plugin list | head -5"
299     ft_utils.execute_command(cmd,
300                              error_msg=("Problem while showing "
301                                         "Rally plugins."))
302
303
304 def install_tempest():
305     logger.info("Installing tempest from existing repo...")
306     cmd = ("rally verify list-verifiers | "
307            "grep '{0}' | wc -l".format(CONST.tempest_deployment_name))
308     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
309     while p.poll() is None:
310         line = p.stdout.readline().rstrip()
311         if str(line) == '0':
312             logger.debug("Tempest %s does not exist" %
313                          CONST.tempest_deployment_name)
314             cmd = ("rally verify create-verifier --source {0} "
315                    "--name {1} --type tempest"
316                    .format(CONST.dir_repo_tempest,
317                            CONST.tempest_deployment_name))
318             error_msg = "Problem while installing Tempest."
319             ft_utils.execute_command_raise(cmd, error_msg=error_msg)
320
321
322 def create_flavor():
323     _, flavor_id = os_utils.get_or_create_flavor('m1.tiny',
324                                                  '512',
325                                                  '1',
326                                                  '1',
327                                                  public=True)
328     if flavor_id is None:
329         raise Exception('Failed to create flavor')
330
331
332 def check_environment():
333     msg_not_active = "The Functest environment is not installed."
334     if not os.path.isfile(CONST.env_active):
335         raise Exception(msg_not_active)
336
337     with open(CONST.env_active, "r") as env_file:
338         s = env_file.read()
339         if not re.search("1", s):
340             raise Exception(msg_not_active)
341
342     logger.info("Functest environment is installed.")
343
344
345 def print_deployment_info():
346     if handler:
347         logger.info('\n\nDeployment information:\n%s' %
348                     handler.get_deployment_info())
349
350
351 def main(**kwargs):
352     try:
353         if not (kwargs['action'] in actions):
354             logger.error('Argument not valid.')
355             return -1
356         elif kwargs['action'] == "start":
357             logger.info("######### Preparing Functest environment #########\n")
358             check_env_variables()
359             get_deployment_handler()
360             create_directories()
361             source_rc_file()
362             patch_config_file()
363             verify_deployment()
364             install_rally()
365             install_tempest()
366             create_flavor()
367             with open(CONST.env_active, "w") as env_file:
368                 env_file.write("1")
369             check_environment()
370             print_deployment_info()
371         elif kwargs['action'] == "check":
372             check_environment()
373     except Exception as e:
374         logger.error(e)
375         return -1
376     return 0
377
378
379 if __name__ == '__main__':
380     parser = PrepareEnvParser()
381     args = parser.parse_args(sys.argv[1:])
382     sys.exit(main(**args))