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
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
24 from opnfv.utils import constants as opnfv_constants
25 from opnfv.deployment import factory
27 actions = ['start', 'check']
29 """ logging configuration """
30 logger = ft_logger.Logger("prepare_env").getLogger()
32 # set the architecture to default
34 arch_filter = ['aarch64']
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")
46 class PrepareEnvParser(object):
49 self.parser = argparse.ArgumentParser()
50 self.parser.add_argument("action", help="Possible actions are: "
51 "'{d[0]}|{d[1]}' ".format(d=actions),
53 self.parser.add_argument("-d", "--debug", help="Debug mode",
56 def parse_args(self, argv=[]):
57 return vars(self.parser.parse_args(argv))
60 def print_separator():
61 logger.info("==============================================")
64 def check_env_variables():
66 logger.info("Checking environment variables...")
68 if CONST.INSTALLER_TYPE is None:
69 logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
70 CONST.INSTALLER_TYPE = "undefined"
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"
80 logger.info(" INSTALLER_TYPE=%s"
81 % CONST.INSTALLER_TYPE)
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.")
90 logger.info(" INSTALLER_IP=%s" % CONST.INSTALLER_IP)
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"
97 logger.info(" DEPLOY_SCENARIO=%s" % CONST.DEPLOY_SCENARIO)
99 logger.info(" CI_DEBUG=%s" % CONST.CI_DEBUG)
102 logger.info(" NODE_NAME=%s" % CONST.NODE_NAME)
105 logger.info(" BUILD_TAG=%s" % CONST.BUILD_TAG)
108 logger.info(" IS_CI_RUN=%s" % CONST.IS_CI_RUN)
111 def get_deployment_handler():
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):
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)
127 user = installer_params.get('user', None)
128 password = installer_params.get('password', None)
129 pkey = installer_params.get('pkey', None)
131 handler = factory.Factory.get_handler(
132 installer=CONST.INSTALLER_TYPE,
133 installer_ip=CONST.INSTALLER_IP,
135 installer_pwd=password,
138 pod_arch = handler.get_arch()
139 except Exception as e:
140 logger.debug("Cannot get deployment information. %s" % e)
143 def create_directories():
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)
150 logger.debug(" %s already exists."
151 % CONST.dir_functest_conf)
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)
157 logger.debug(" %s already exists."
158 % CONST.dir_functest_data)
161 def source_rc_file():
163 logger.info("Fetching RC file...")
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')
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.")
186 cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
188 % (CONST.openstack_creds,
189 CONST.INSTALLER_TYPE,
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.")
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)
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
217 def patch_config_file():
218 patch_file(CONFIG_PATCH_PATH)
220 if pod_arch and pod_arch in arch_filter:
221 patch_file(CONFIG_AARCH64_PATCH_PATH)
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)
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]))
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='"'))
243 def verify_deployment():
245 logger.info("Verifying OpenStack services...")
246 cmd = ("%s/functest/ci/check_os.sh" % CONST.dir_repo_functest)
248 logger.debug("Executing command: %s" % cmd)
249 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
251 while p.poll() is None:
252 line = p.stdout.readline().rstrip()
255 raise Exception("Problem while running 'check_os.sh'.")
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()
267 for line in fileinput.input(RALLY_CONF_PATH, inplace=1):
269 if "cirros|testvm" in line:
270 print rally_patch_conf
272 logger.info("Creating Rally environment...")
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),
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)
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)
293 cmd = "rally deployment list"
294 ft_utils.execute_command(cmd,
295 error_msg=("Problem while listing "
296 "Rally deployment."))
298 cmd = "rally plugin list | head -5"
299 ft_utils.execute_command(cmd,
300 error_msg=("Problem while showing "
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()
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)
323 _, flavor_id = os_utils.get_or_create_flavor('m1.tiny',
328 if flavor_id is None:
329 raise Exception('Failed to create flavor')
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)
337 with open(CONST.env_active, "r") as env_file:
339 if not re.search("1", s):
340 raise Exception(msg_not_active)
342 logger.info("Functest environment is installed.")
345 def print_deployment_info():
347 logger.info('\n\nDeployment information:\n%s' %
348 handler.get_deployment_info())
353 if not (kwargs['action'] in actions):
354 logger.error('Argument not valid.')
356 elif kwargs['action'] == "start":
357 logger.info("######### Preparing Functest environment #########\n")
358 check_env_variables()
359 get_deployment_handler()
367 with open(CONST.env_active, "w") as env_file:
370 print_deployment_info()
371 elif kwargs['action'] == "check":
373 except Exception as e:
379 if __name__ == '__main__':
380 parser = PrepareEnvParser()
381 args = parser.parse_args(sys.argv[1:])
382 sys.exit(main(**args))