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
17 from opnfv.utils import constants as opnfv_constants
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 actions = ['start', 'check']
26 """ logging configuration """
27 logger = ft_logger.Logger("prepare_env").getLogger()
30 CONFIG_FUNCTEST_PATH = CONST.CONFIG_FUNCTEST_YAML
31 CONFIG_PATCH_PATH = os.path.join(os.path.dirname(
32 CONFIG_FUNCTEST_PATH), "config_patch.yaml")
34 with open(CONFIG_PATCH_PATH) as f:
35 functest_patch_yaml = yaml.safe_load(f)
38 class PrepareEnvParser():
41 self.parser = argparse.ArgumentParser()
42 self.parser.add_argument("action", help="Possible actions are: "
43 "'{d[0]}|{d[1]}' ".format(d=actions),
45 self.parser.add_argument("-d", "--debug", help="Debug mode",
48 def parse_args(self, argv=[]):
49 return vars(self.parser.parse_args(argv))
52 def print_separator():
53 logger.info("==============================================")
56 def check_env_variables():
58 logger.info("Checking environment variables...")
60 if CONST.INSTALLER_TYPE is None:
61 logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
62 CONST.INSTALLER_TYPE = "undefined"
64 if CONST.INSTALLER_TYPE not in opnfv_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 % (CONST.INSTALLER_TYPE,
69 opnfv_constants.INSTALLERS))
70 CONST.INSTALLER_TYPE = "undefined"
72 logger.info(" INSTALLER_TYPE=%s"
73 % CONST.INSTALLER_TYPE)
75 if CONST.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.")
82 logger.info(" INSTALLER_IP=%s" % CONST.INSTALLER_IP)
84 if CONST.DEPLOY_SCENARIO is None:
85 logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
86 "Setting CI_SCENARIO=undefined.")
87 CONST.DEPLOY_SCENARIO = "undefined"
89 logger.info(" DEPLOY_SCENARIO=%s" % CONST.DEPLOY_SCENARIO)
91 logger.info(" CI_DEBUG=%s" % CONST.CI_DEBUG)
94 logger.info(" NODE_NAME=%s" % CONST.NODE_NAME)
97 logger.info(" BUILD_TAG=%s" % CONST.BUILD_TAG)
100 logger.info(" IS_CI_RUN=%s" % CONST.IS_CI_RUN)
103 def create_directories():
105 logger.info("Creating needed directories...")
106 if not os.path.exists(CONST.dir_functest_conf):
107 os.makedirs(CONST.dir_functest_conf)
108 logger.info(" %s created." % CONST.dir_functest_conf)
110 logger.debug(" %s already exists."
111 % CONST.dir_functest_conf)
113 if not os.path.exists(CONST.dir_functest_data):
114 os.makedirs(CONST.dir_functest_data)
115 logger.info(" %s created." % CONST.dir_functest_data)
117 logger.debug(" %s already exists."
118 % CONST.dir_functest_data)
121 def source_rc_file():
123 logger.info("Fetching RC file...")
125 if CONST.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(CONST.dir_functest_conf, 'openstack.creds')
131 if not os.path.isfile(CONST.openstack_creds):
132 logger.info("RC file not provided. "
133 "Fetching it from the installer...")
134 if CONST.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 raise Exception("Missing CI_INSTALLER_IP.")
138 if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
139 logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
140 "not a valid OPNFV installer. Available "
141 "installers are : %s." %
142 (CONST.INSTALLER_TYPE,
143 opnfv_constants.INSTALLERS))
144 raise Exception("Wrong INSTALLER_TYPE.")
146 cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
148 % (CONST.openstack_creds,
149 CONST.INSTALLER_TYPE,
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 raise Exception("Failed to fetch credentials from installer.")
158 logger.info("RC file provided in %s."
159 % CONST.openstack_creds)
160 if os.path.getsize(CONST.openstack_creds) == 0:
161 raise Exception("The file %s is empty." % CONST.openstack_creds)
163 logger.info("Sourcing the OpenStack RC file...")
164 os_utils.source_credentials(
165 CONST.openstack_creds)
166 for key, value in os.environ.iteritems():
167 if re.search("OS_", key):
168 if key == 'OS_AUTH_URL':
169 CONST.OS_AUTH_URL = value
170 elif key == 'OS_USERNAME':
171 CONST.OS_USERNAME = value
172 elif key == 'OS_TENANT_NAME':
173 CONST.OS_TENANT_NAME = value
174 elif key == 'OS_PASSWORD':
175 CONST.OS_PASSWORD = value
178 def patch_config_file():
180 for key in functest_patch_yaml:
181 if key in CONST.DEPLOY_SCENARIO:
182 new_functest_yaml = dict(ft_utils.merge_dicts(
183 ft_utils.get_functest_yaml(), functest_patch_yaml[key]))
187 os.remove(CONFIG_FUNCTEST_PATH)
188 with open(CONFIG_FUNCTEST_PATH, "w") as f:
189 f.write(yaml.dump(new_functest_yaml, default_style='"'))
193 def verify_deployment():
195 logger.info("Verifying OpenStack services...")
196 cmd = ("%s/functest/ci/check_os.sh" % CONST.dir_repo_functest)
198 logger.debug("Executing command: %s" % cmd)
199 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
201 while p.poll() is None:
202 line = p.stdout.readline().rstrip()
205 raise Exception("Problem while running 'check_os.sh'.")
211 logger.info("Creating Rally environment...")
213 cmd = "rally deployment destroy opnfv-rally"
214 ft_utils.execute_command(cmd, error_msg=(
215 "Deployment %s does not exist."
216 % CONST.rally_deployment_name),
219 rally_conf = os_utils.get_credentials_for_rally()
220 with open('rally_conf.json', 'w') as fp:
221 json.dump(rally_conf, fp)
222 cmd = ("rally deployment create "
223 "--file=rally_conf.json --name={0}"
224 .format(CONST.rally_deployment_name))
225 error_msg = "Problem while creating Rally deployment"
226 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
228 cmd = "rally deployment check"
229 error_msg = "OpenStack not responding or faulty Rally deployment."
230 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
232 cmd = "rally deployment list"
233 ft_utils.execute_command(cmd,
234 error_msg=("Problem while listing "
235 "Rally deployment."))
237 cmd = "rally plugin list | head -5"
238 ft_utils.execute_command(cmd,
239 error_msg=("Problem while showing "
243 def install_tempest():
244 logger.info("Installing tempest from existing repo...")
245 cmd = ("rally verify list-verifiers | "
246 "grep '{0}' | wc -l".format(CONST.tempest_deployment_name))
247 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
248 while p.poll() is None:
249 line = p.stdout.readline().rstrip()
251 logger.debug("Tempest %s does not exist" %
252 CONST.tempest_deployment_name)
253 cmd = ("rally verify create-verifier --source {0} "
254 "--name {1} --type tempest"
255 .format(CONST.dir_repo_tempest,
256 CONST.tempest_deployment_name))
257 error_msg = "Problem while installing Tempest."
258 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
262 _, flavor_id = os_utils.get_or_create_flavor('m1.tiny',
267 if flavor_id is None:
268 raise Exception('Failed to create flavor')
271 def check_environment():
272 msg_not_active = "The Functest environment is not installed."
273 if not os.path.isfile(CONST.env_active):
274 raise Exception(msg_not_active)
276 with open(CONST.env_active, "r") as env_file:
278 if not re.search("1", s):
279 raise Exception(msg_not_active)
281 logger.info("Functest environment is installed.")
286 if not (kwargs['action'] in actions):
287 logger.error('Argument not valid.')
289 elif kwargs['action'] == "start":
290 logger.info("######### Preparing Functest environment #########\n")
291 check_env_variables()
299 with open(CONST.env_active, "w") as env_file:
302 elif kwargs['action'] == "check":
304 except Exception as e:
310 if __name__ == '__main__':
311 parser = PrepareEnvParser()
312 args = parser.parse_args(sys.argv[1:])
313 sys.exit(main(**args))