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
35 CONFIG_FUNCTEST_PATH = CONST.CONFIG_FUNCTEST_YAML
36 CONFIG_PATCH_PATH = os.path.join(os.path.dirname(
37 CONFIG_FUNCTEST_PATH), "config_patch.yaml")
38 CONFIG_AARCH64_PATCH_PATH = os.path.join(os.path.dirname(
39 CONFIG_FUNCTEST_PATH), "config_aarch64_patch.yaml")
40 RALLY_CONF_PATH = os.path.join("/etc/rally/rally.conf")
41 RALLY_AARCH64_PATCH_PATH = os.path.join(os.path.dirname(
42 CONFIG_FUNCTEST_PATH), "rally_aarch64_patch.conf")
45 class PrepareEnvParser(object):
48 self.parser = argparse.ArgumentParser()
49 self.parser.add_argument("action", help="Possible actions are: "
50 "'{d[0]}|{d[1]}' ".format(d=actions),
52 self.parser.add_argument("-d", "--debug", help="Debug mode",
55 def parse_args(self, argv=[]):
56 return vars(self.parser.parse_args(argv))
59 def print_separator():
60 logger.info("==============================================")
63 def check_env_variables():
65 logger.info("Checking environment variables...")
67 if CONST.INSTALLER_TYPE is None:
68 logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
69 CONST.INSTALLER_TYPE = "undefined"
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"
79 logger.info(" INSTALLER_TYPE=%s"
80 % CONST.INSTALLER_TYPE)
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.")
89 logger.info(" INSTALLER_IP=%s" % CONST.INSTALLER_IP)
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"
96 logger.info(" DEPLOY_SCENARIO=%s" % CONST.DEPLOY_SCENARIO)
98 logger.info(" CI_DEBUG=%s" % CONST.CI_DEBUG)
101 logger.info(" NODE_NAME=%s" % CONST.NODE_NAME)
104 logger.info(" BUILD_TAG=%s" % CONST.BUILD_TAG)
107 logger.info(" IS_CI_RUN=%s" % CONST.IS_CI_RUN)
110 def get_deployment_handler():
114 installer_params_yaml = os.path.join(CONST.dir_repo_functest,
115 'functest/ci/installer_params.yaml')
116 if (CONST.INSTALLER_IP and CONST.INSTALLER_TYPE and
117 CONST.INSTALLER_TYPE in opnfv_constants.INSTALLERS):
118 installer_params = ft_utils.get_parameter_from_yaml(
119 CONST.INSTALLER_TYPE, installer_params_yaml)
121 user = installer_params.get('user', None)
122 password = installer_params.get('password', None)
123 pkey = installer_params.get('pkey', None)
126 handler = factory.Factory.get_handler(
127 installer=CONST.INSTALLER_TYPE,
128 installer_ip=CONST.INSTALLER_IP,
130 installer_pwd=password,
133 pod_arch = handler.get_arch()
134 except Exception as e:
135 logger.debug("Cannot get deployment information. %s" % e)
138 def create_directories():
140 logger.info("Creating needed directories...")
141 if not os.path.exists(CONST.dir_functest_conf):
142 os.makedirs(CONST.dir_functest_conf)
143 logger.info(" %s created." % CONST.dir_functest_conf)
145 logger.debug(" %s already exists."
146 % CONST.dir_functest_conf)
148 if not os.path.exists(CONST.dir_functest_data):
149 os.makedirs(CONST.dir_functest_data)
150 logger.info(" %s created." % CONST.dir_functest_data)
152 logger.debug(" %s already exists."
153 % CONST.dir_functest_data)
156 def source_rc_file():
158 logger.info("Fetching RC file...")
160 if CONST.openstack_creds is None:
161 logger.warning("The environment variable 'creds' must be set and"
162 "pointing to the local RC file. Using default: "
163 "/home/opnfv/functest/conf/openstack.creds ...")
164 os.path.join(CONST.dir_functest_conf, 'openstack.creds')
166 if not os.path.isfile(CONST.openstack_creds):
167 logger.info("RC file not provided. "
168 "Fetching it from the installer...")
169 if CONST.INSTALLER_IP is None:
170 logger.error("The env variable CI_INSTALLER_IP must be provided in"
171 " order to fetch the credentials from the installer.")
172 raise Exception("Missing CI_INSTALLER_IP.")
173 if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
174 logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
175 "not a valid OPNFV installer. Available "
176 "installers are : %s." %
177 (CONST.INSTALLER_TYPE,
178 opnfv_constants.INSTALLERS))
179 raise Exception("Wrong INSTALLER_TYPE.")
181 cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
183 % (CONST.openstack_creds,
184 CONST.INSTALLER_TYPE,
186 logger.debug("Executing command: %s" % cmd)
187 p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
188 output = p.communicate()[0]
189 logger.debug("\n%s" % output)
190 if p.returncode != 0:
191 raise Exception("Failed to fetch credentials from installer.")
193 logger.info("RC file provided in %s."
194 % CONST.openstack_creds)
195 if os.path.getsize(CONST.openstack_creds) == 0:
196 raise Exception("The file %s is empty." % CONST.openstack_creds)
198 logger.info("Sourcing the OpenStack RC file...")
199 os_utils.source_credentials(
200 CONST.openstack_creds)
201 for key, value in os.environ.iteritems():
202 if re.search("OS_", key):
203 if key == 'OS_AUTH_URL':
204 CONST.OS_AUTH_URL = value
205 elif key == 'OS_USERNAME':
206 CONST.OS_USERNAME = value
207 elif key == 'OS_TENANT_NAME':
208 CONST.OS_TENANT_NAME = value
209 elif key == 'OS_PASSWORD':
210 CONST.OS_PASSWORD = value
213 def patch_config_file(patch_file_path, arch_filter=None):
214 if arch_filter and pod_arch not in arch_filter:
217 with open(patch_file_path) as f:
218 patch_file = yaml.safe_load(f)
221 for key in patch_file:
222 if key in CONST.DEPLOY_SCENARIO:
223 new_functest_yaml = dict(ft_utils.merge_dicts(
224 ft_utils.get_functest_yaml(), patch_file[key]))
228 os.remove(CONFIG_FUNCTEST_PATH)
229 with open(CONFIG_FUNCTEST_PATH, "w") as f:
230 f.write(yaml.dump(new_functest_yaml, default_style='"'))
234 def verify_deployment():
236 logger.info("Verifying OpenStack services...")
237 cmd = ("%s/functest/ci/check_os.sh" % CONST.dir_repo_functest)
239 logger.debug("Executing command: %s" % cmd)
240 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
242 while p.poll() is None:
243 line = p.stdout.readline().rstrip()
246 raise Exception("Problem while running 'check_os.sh'.")
253 if 'aarch64' in pod_arch:
254 logger.info("Apply aarch64 specific to rally config...")
255 with open(RALLY_AARCH64_PATCH_PATH, "r") as f:
256 rally_patch_conf = f.read()
258 for line in fileinput.input(RALLY_CONF_PATH, inplace=1):
260 if "cirros|testvm" in line:
261 print rally_patch_conf
263 logger.info("Creating Rally environment...")
265 cmd = "rally deployment destroy opnfv-rally"
266 ft_utils.execute_command(cmd, error_msg=(
267 "Deployment %s does not exist."
268 % CONST.rally_deployment_name),
271 rally_conf = os_utils.get_credentials_for_rally()
272 with open('rally_conf.json', 'w') as fp:
273 json.dump(rally_conf, fp)
274 cmd = ("rally deployment create "
275 "--file=rally_conf.json --name={0}"
276 .format(CONST.rally_deployment_name))
277 error_msg = "Problem while creating Rally deployment"
278 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
280 cmd = "rally deployment check"
281 error_msg = "OpenStack not responding or faulty Rally deployment."
282 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
284 cmd = "rally deployment list"
285 ft_utils.execute_command(cmd,
286 error_msg=("Problem while listing "
287 "Rally deployment."))
289 cmd = "rally plugin list | head -5"
290 ft_utils.execute_command(cmd,
291 error_msg=("Problem while showing "
295 def install_tempest():
296 logger.info("Installing tempest from existing repo...")
297 cmd = ("rally verify list-verifiers | "
298 "grep '{0}' | wc -l".format(CONST.tempest_deployment_name))
299 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
300 while p.poll() is None:
301 line = p.stdout.readline().rstrip()
303 logger.debug("Tempest %s does not exist" %
304 CONST.tempest_deployment_name)
305 cmd = ("rally verify create-verifier --source {0} "
306 "--name {1} --type tempest"
307 .format(CONST.dir_repo_tempest,
308 CONST.tempest_deployment_name))
309 error_msg = "Problem while installing Tempest."
310 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
314 _, flavor_id = os_utils.get_or_create_flavor('m1.tiny',
319 if flavor_id is None:
320 raise Exception('Failed to create flavor')
323 def check_environment():
324 msg_not_active = "The Functest environment is not installed."
325 if not os.path.isfile(CONST.env_active):
326 raise Exception(msg_not_active)
328 with open(CONST.env_active, "r") as env_file:
330 if not re.search("1", s):
331 raise Exception(msg_not_active)
333 logger.info("Functest environment is installed.")
336 def print_deployment_info():
338 logger.info('\n\nDeployment information:\n%s' %
339 handler.get_deployment_info())
344 if not (kwargs['action'] in actions):
345 logger.error('Argument not valid.')
347 elif kwargs['action'] == "start":
348 logger.info("######### Preparing Functest environment #########\n")
349 check_env_variables()
350 get_deployment_handler()
353 patch_config_file(CONFIG_PATCH_PATH)
354 patch_config_file(CONFIG_AARCH64_PATCH_PATH, 'aarch64')
359 with open(CONST.env_active, "w") as env_file:
362 print_deployment_info()
363 elif kwargs['action'] == "check":
365 except Exception as e:
371 if __name__ == '__main__':
372 parser = PrepareEnvParser()
373 args = parser.parse_args(sys.argv[1:])
374 sys.exit(main(**args))