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
22 from functest.ci import check_deployment
23 import functest.utils.functest_utils as ft_utils
24 import functest.utils.openstack_utils as os_utils
25 from functest.utils.constants import CONST
27 from opnfv.utils import constants as opnfv_constants
28 from opnfv.deployment import factory
30 actions = ['start', 'check']
32 """ logging configuration """
33 logger = logging.getLogger('functest.ci.prepare_env')
35 # set the architecture to default
36 pod_arch = os.getenv("POD_ARCH", None)
37 arch_filter = ['aarch64']
39 CONFIG_FUNCTEST_PATH = pkg_resources.resource_filename(
40 'functest', 'ci/config_functest.yaml')
41 CONFIG_PATCH_PATH = pkg_resources.resource_filename(
42 'functest', 'ci/config_patch.yaml')
43 CONFIG_AARCH64_PATCH_PATH = pkg_resources.resource_filename(
44 'functest', 'ci/config_aarch64_patch.yaml')
45 RALLY_CONF_PATH = "/etc/rally/rally.conf"
46 RALLY_AARCH64_PATCH_PATH = pkg_resources.resource_filename(
47 'functest', 'ci/rally_aarch64_patch.conf')
50 class PrepareEnvParser(object):
53 self.parser = argparse.ArgumentParser()
54 self.parser.add_argument("action", help="Possible actions are: "
55 "'{d[0]}|{d[1]}' ".format(d=actions),
57 self.parser.add_argument("-d", "--debug", help="Debug mode",
60 def parse_args(self, argv=[]):
61 return vars(self.parser.parse_args(argv))
64 def print_separator():
65 logger.info("==============================================")
68 def check_env_variables():
70 logger.info("Checking environment variables...")
72 if CONST.__getattribute__('INSTALLER_TYPE') is None:
73 logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
74 CONST.__setattr__('INSTALLER_TYPE', 'undefined')
76 if (CONST.__getattribute__('INSTALLER_TYPE') not in
77 opnfv_constants.INSTALLERS):
78 logger.warning("INSTALLER_TYPE=%s is not a valid OPNFV installer. "
79 "Available OPNFV Installers are : %s. "
80 "Setting INSTALLER_TYPE=undefined."
81 % (CONST.__getattribute__('INSTALLER_TYPE'),
82 opnfv_constants.INSTALLERS))
83 CONST.__setattr__('INSTALLER_TYPE', 'undefined')
85 logger.info(" INSTALLER_TYPE=%s"
86 % CONST.__getattribute__('INSTALLER_TYPE'))
88 if CONST.__getattribute__('INSTALLER_IP') is None:
90 "The env variable 'INSTALLER_IP' is not defined. It is recommended"
91 " to extract some information from the deployment")
93 logger.info(" INSTALLER_IP=%s" %
94 CONST.__getattribute__('INSTALLER_IP'))
96 if CONST.__getattribute__('DEPLOY_SCENARIO') is None:
97 logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
98 "Setting CI_SCENARIO=undefined.")
99 CONST.__setattr__('DEPLOY_SCENARIO', 'undefined')
101 logger.info(" DEPLOY_SCENARIO=%s"
102 % CONST.__getattribute__('DEPLOY_SCENARIO'))
103 if CONST.__getattribute__('CI_DEBUG'):
104 logger.info(" CI_DEBUG=%s" % CONST.__getattribute__('CI_DEBUG'))
106 if CONST.__getattribute__('NODE_NAME'):
107 logger.info(" NODE_NAME=%s" % CONST.__getattribute__('NODE_NAME'))
109 if CONST.__getattribute__('BUILD_TAG'):
110 logger.info(" BUILD_TAG=%s" % CONST.__getattribute__('BUILD_TAG'))
112 if CONST.__getattribute__('IS_CI_RUN'):
113 logger.info(" IS_CI_RUN=%s" % CONST.__getattribute__('IS_CI_RUN'))
116 def get_deployment_handler():
120 installer_params_yaml = pkg_resources.resource_filename(
121 'functest', 'ci/installer_params.yaml')
122 if (CONST.__getattribute__('INSTALLER_IP') and
123 CONST.__getattribute__('INSTALLER_TYPE') and
124 CONST.__getattribute__('INSTALLER_TYPE') in
125 opnfv_constants.INSTALLERS):
127 installer_params = ft_utils.get_parameter_from_yaml(
128 CONST.__getattribute__('INSTALLER_TYPE'),
129 installer_params_yaml)
130 except ValueError as e:
131 logger.debug('Printing deployment info is not supported for %s' %
132 CONST.__getattribute__('INSTALLER_TYPE'))
135 user = installer_params.get('user', None)
136 password = installer_params.get('password', None)
137 pkey = installer_params.get('pkey', None)
139 handler = factory.Factory.get_handler(
140 installer=CONST.__getattribute__('INSTALLER_TYPE'),
141 installer_ip=CONST.__getattribute__('INSTALLER_IP'),
143 installer_pwd=password,
146 pod_arch = handler.get_arch()
147 except Exception as e:
148 logger.debug("Cannot get deployment information. %s" % e)
151 def create_directories():
153 logger.info("Creating needed directories...")
154 if not os.path.exists(CONST.__getattribute__('dir_functest_conf')):
155 os.makedirs(CONST.__getattribute__('dir_functest_conf'))
156 logger.info(" %s created." %
157 CONST.__getattribute__('dir_functest_conf'))
159 logger.debug(" %s already exists." %
160 CONST.__getattribute__('dir_functest_conf'))
162 if not os.path.exists(CONST.__getattribute__('dir_functest_data')):
163 os.makedirs(CONST.__getattribute__('dir_functest_data'))
164 logger.info(" %s created." %
165 CONST.__getattribute__('dir_functest_data'))
167 logger.debug(" %s already exists." %
168 CONST.__getattribute__('dir_functest_data'))
169 if not os.path.exists(CONST.__getattribute__('dir_functest_images')):
170 os.makedirs(CONST.__getattribute__('dir_functest_images'))
171 logger.info(" %s created." %
172 CONST.__getattribute__('dir_functest_images'))
174 logger.debug(" %s already exists." %
175 CONST.__getattribute__('dir_functest_images'))
178 def source_rc_file():
181 logger.info("Sourcing the OpenStack RC file...")
182 os_utils.source_credentials(CONST.__getattribute__('openstack_creds'))
183 for key, value in os.environ.iteritems():
184 if re.search("OS_", key):
185 if key == 'OS_AUTH_URL':
186 CONST.__setattr__('OS_AUTH_URL', value)
187 elif key == 'OS_USERNAME':
188 CONST.__setattr__('OS_USERNAME', value)
189 elif key == 'OS_TENANT_NAME':
190 CONST.__setattr__('OS_TENANT_NAME', value)
191 elif key == 'OS_PASSWORD':
192 CONST.__setattr__('OS_PASSWORD', value)
195 def update_config_file():
196 patch_file(CONFIG_PATCH_PATH)
198 if pod_arch and pod_arch in arch_filter:
199 patch_file(CONFIG_AARCH64_PATCH_PATH)
201 if "TEST_DB_URL" in os.environ:
205 def patch_file(patch_file_path):
206 logger.debug('Updating file: %s', patch_file_path)
207 with open(patch_file_path) as f:
208 patch_file = yaml.safe_load(f)
211 for key in patch_file:
212 if key in CONST.__getattribute__('DEPLOY_SCENARIO'):
213 new_functest_yaml = dict(ft_utils.merge_dicts(
214 ft_utils.get_functest_yaml(), patch_file[key]))
218 os.remove(CONFIG_FUNCTEST_PATH)
219 with open(CONFIG_FUNCTEST_PATH, "w") as f:
220 f.write(yaml.dump(new_functest_yaml, default_style='"'))
224 with open(CONFIG_FUNCTEST_PATH) as f:
225 functest_yaml = yaml.safe_load(f)
227 with open(CONFIG_FUNCTEST_PATH, "w") as f:
228 functest_yaml["results"]["test_db_url"] = os.environ.get('TEST_DB_URL')
229 f.write(yaml.dump(functest_yaml, default_style='"'))
232 def verify_deployment():
234 logger.info("Verifying OpenStack deployment...")
235 deployment = check_deployment.CheckDeployment()
236 deployment.check_all()
242 if pod_arch and pod_arch in arch_filter:
243 logger.info("Apply aarch64 specific to rally config...")
244 with open(RALLY_AARCH64_PATCH_PATH, "r") as f:
245 rally_patch_conf = f.read()
247 for line in fileinput.input(RALLY_CONF_PATH, inplace=1):
249 if "cirros|testvm" in line:
250 print rally_patch_conf
252 logger.info("Creating Rally environment...")
254 cmd = "rally deployment destroy opnfv-rally"
255 ft_utils.execute_command(cmd, error_msg=(
256 "Deployment %s does not exist."
257 % CONST.__getattribute__('rally_deployment_name')),
260 rally_conf = os_utils.get_credentials_for_rally()
261 with open('rally_conf.json', 'w') as fp:
262 json.dump(rally_conf, fp)
263 cmd = ("rally deployment create "
264 "--file=rally_conf.json --name={0}"
265 .format(CONST.__getattribute__('rally_deployment_name')))
266 error_msg = "Problem while creating Rally deployment"
267 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
269 cmd = "rally deployment check"
270 error_msg = "OpenStack not responding or faulty Rally deployment."
271 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
273 cmd = "rally deployment list"
274 ft_utils.execute_command(cmd,
275 error_msg=("Problem while listing "
276 "Rally deployment."))
278 cmd = "rally plugin list | head -5"
279 ft_utils.execute_command(cmd,
280 error_msg=("Problem while showing "
284 def install_tempest():
285 logger.info("Installing tempest from existing repo...")
286 cmd = ("rally verify list-verifiers | "
287 "grep '{0}' | wc -l".format(
288 CONST.__getattribute__('tempest_deployment_name')))
289 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
290 while p.poll() is None:
291 line = p.stdout.readline().rstrip()
293 logger.debug("Tempest %s does not exist" %
294 CONST.__getattribute__('tempest_deployment_name'))
295 cmd = ("rally verify create-verifier --source {0} "
296 "--name {1} --type tempest --system-wide"
297 .format(CONST.__getattribute__('dir_repo_tempest'),
298 CONST.__getattribute__('tempest_deployment_name')))
299 error_msg = "Problem while installing Tempest."
300 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
304 _, flavor_id = os_utils.get_or_create_flavor('m1.tiny',
309 if flavor_id is None:
310 raise Exception('Failed to create flavor')
313 def check_environment():
314 msg_not_active = "The Functest environment is not installed."
315 if not os.path.isfile(CONST.__getattribute__('env_active')):
316 raise Exception(msg_not_active)
318 with open(CONST.__getattribute__('env_active'), "r") as env_file:
320 if not re.search("1", s):
321 raise Exception(msg_not_active)
323 logger.info("Functest environment is installed.")
326 def print_deployment_info():
328 logger.info('\n\nDeployment information:\n%s' %
329 handler.get_deployment_info())
332 def prepare_env(**kwargs):
334 if not (kwargs['action'] in actions):
335 logger.error('Argument not valid.')
337 elif kwargs['action'] == "start":
338 logger.info("######### Preparing Functest environment #########\n")
340 check_env_variables()
347 with open(CONST.__getattribute__('env_active'), "w") as env_file:
350 elif kwargs['action'] == "check":
352 except Exception as e:
359 logging.config.fileConfig(pkg_resources.resource_filename(
360 'functest', 'ci/logging.ini'))
361 parser = PrepareEnvParser()
362 args = parser.parse_args(sys.argv[1:])
363 return prepare_env(**args)