3 # Author: Jose Lausuch (jose.lausuch@ericsson.com)
5 # Installs the Functest framework within the Docker container
6 # and run the tests automatically
9 # All rights reserved. This program and the accompanying materials
10 # are made available under the terms of the Apache License, Version 2.0
11 # which accompanies this distribution, and is available at
12 # http://www.apache.org/licenses/LICENSE-2.0
24 from opnfv.utils import constants as opnfv_constants
26 import functest.utils.functest_logger as ft_logger
27 import functest.utils.functest_utils as ft_utils
28 import functest.utils.openstack_utils as os_utils
29 from functest.utils.constants import CONST
31 actions = ['start', 'check']
33 """ logging configuration """
34 logger = ft_logger.Logger("prepare_env").getLogger()
37 CONFIG_FUNCTEST_PATH = CONST.CONFIG_FUNCTEST_YAML
38 CONFIG_PATCH_PATH = os.path.join(os.path.dirname(
39 CONFIG_FUNCTEST_PATH), "config_patch.yaml")
41 with open(CONFIG_PATCH_PATH) as f:
42 functest_patch_yaml = yaml.safe_load(f)
45 class PrepareEnvParser():
48 self.parser = argparse.ArgumentParser()
49 self.parser.add_argument("action", help="Possible actions are: "
50 "'{d[0]}|{d[1]}' ".format(d=actions))
51 self.parser.add_argument("-d", "--debug", help="Debug mode",
54 def parse_args(self, argv=[]):
55 return vars(self.parser.parse_args(argv))
58 def print_separator():
59 logger.info("==============================================")
62 def check_env_variables():
64 logger.info("Checking environment variables...")
66 if CONST.INSTALLER_TYPE is None:
67 logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
68 CONST.INSTALLER_TYPE = "undefined"
70 if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
71 logger.warning("INSTALLER_TYPE=%s is not a valid OPNFV installer. "
72 "Available OPNFV Installers are : %s. "
73 "Setting INSTALLER_TYPE=undefined."
74 % (CONST.INSTALLER_TYPE,
75 opnfv_constants.INSTALLERS))
76 CONST.INSTALLER_TYPE = "undefined"
78 logger.info(" INSTALLER_TYPE=%s"
79 % CONST.INSTALLER_TYPE)
81 if CONST.INSTALLER_IP is None:
82 logger.warning("The env variable 'INSTALLER_IP' is not defined. "
83 "It is needed to fetch the OpenStack credentials. "
84 "If the credentials are not provided to the "
85 "container as a volume, please add this env variable "
86 "to the 'docker run' command.")
88 logger.info(" INSTALLER_IP=%s" % CONST.INSTALLER_IP)
90 if CONST.DEPLOY_SCENARIO is None:
91 logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
92 "Setting CI_SCENARIO=undefined.")
93 CONST.DEPLOY_SCENARIO = "undefined"
95 logger.info(" DEPLOY_SCENARIO=%s" % CONST.DEPLOY_SCENARIO)
97 logger.info(" CI_DEBUG=%s" % CONST.CI_DEBUG)
100 logger.info(" NODE_NAME=%s" % CONST.NODE_NAME)
103 logger.info(" BUILD_TAG=%s" % CONST.BUILD_TAG)
106 logger.info(" IS_CI_RUN=%s" % CONST.IS_CI_RUN)
109 def create_directories():
111 logger.info("Creating needed directories...")
112 if not os.path.exists(CONST.dir_functest_conf):
113 os.makedirs(CONST.dir_functest_conf)
114 logger.info(" %s created." % CONST.dir_functest_conf)
116 logger.debug(" %s already exists."
117 % CONST.dir_functest_conf)
119 if not os.path.exists(CONST.dir_functest_data):
120 os.makedirs(CONST.dir_functest_data)
121 logger.info(" %s created." % CONST.dir_functest_data)
123 logger.debug(" %s already exists."
124 % CONST.dir_functest_data)
127 def source_rc_file():
129 logger.info("Fetching RC file...")
131 if CONST.openstack_creds is None:
132 logger.warning("The environment variable 'creds' must be set and"
133 "pointing to the local RC file. Using default: "
134 "/home/opnfv/functest/conf/openstack.creds ...")
135 os.path.join(CONST.dir_functest_conf, 'openstack.creds')
137 if not os.path.isfile(CONST.openstack_creds):
138 logger.info("RC file not provided. "
139 "Fetching it from the installer...")
140 if CONST.INSTALLER_IP is None:
141 logger.error("The env variable CI_INSTALLER_IP must be provided in"
142 " order to fetch the credentials from the installer.")
143 sys.exit("Missing CI_INSTALLER_IP.")
144 if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
145 logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
146 "not a valid OPNFV installer. Available "
147 "installers are : %s." %
148 (CONST.INSTALLER_TYPE,
149 opnfv_constants.INSTALLERS))
150 sys.exit("Wrong INSTALLER_TYPE.")
152 cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
154 % (CONST.openstack_creds,
155 CONST.INSTALLER_TYPE,
157 logger.debug("Executing command: %s" % cmd)
158 p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
159 output = p.communicate()[0]
160 logger.debug("\n%s" % output)
161 if p.returncode != 0:
162 logger.error("Failed to fetch credentials from installer.")
165 logger.info("RC file provided in %s."
166 % CONST.openstack_creds)
167 if os.path.getsize(CONST.openstack_creds) == 0:
168 logger.error("The file %s is empty."
169 % CONST.openstack_creds)
172 logger.info("Sourcing the OpenStack RC file...")
173 creds = os_utils.source_credentials(
174 CONST.openstack_creds)
176 for key, value in creds.iteritems():
177 if re.search("OS_", key):
178 str += "\n\t\t\t\t\t\t " + key + "=" + value
179 if key == 'OS_AUTH_URL':
180 CONST.OS_AUTH_URL = value
181 elif key == 'OS_USERNAME':
182 CONST.OS_USERNAME = value
183 elif key == 'OS_TENANT_NAME':
184 CONST.OS_TENANT_NAME = value
185 elif key == 'OS_PASSWORD':
186 CONST.OS_PASSWORD = value
187 logger.debug("Used credentials: %s" % str)
188 logger.debug("OS_AUTH_URL:%s" % CONST.OS_AUTH_URL)
189 logger.debug("OS_USERNAME:%s" % CONST.OS_USERNAME)
190 logger.debug("OS_TENANT_NAME:%s" % CONST.OS_TENANT_NAME)
191 logger.debug("OS_PASSWORD:%s" % CONST.OS_PASSWORD)
194 def patch_config_file():
196 for key in functest_patch_yaml:
197 if key in CONST.DEPLOY_SCENARIO:
198 new_functest_yaml = dict(ft_utils.merge_dicts(
199 ft_utils.get_functest_yaml(), functest_patch_yaml[key]))
203 os.remove(CONFIG_FUNCTEST_PATH)
204 with open(CONFIG_FUNCTEST_PATH, "w") as f:
205 f.write(yaml.dump(new_functest_yaml, default_style='"'))
209 def verify_deployment():
211 logger.info("Verifying OpenStack services...")
212 cmd = ("%s/functest/ci/check_os.sh" % CONST.dir_repo_functest)
214 logger.debug("Executing command: %s" % cmd)
215 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
217 while p.poll() is None:
218 line = p.stdout.readline().rstrip()
221 sys.exit("Problem while running 'check_os.sh'.")
227 logger.info("Creating Rally environment...")
229 cmd = "rally deployment destroy opnfv-rally"
230 ft_utils.execute_command(cmd, error_msg=(
231 "Deployment %s does not exist."
232 % CONST.rally_deployment_name),
234 rally_conf = os_utils.get_credentials_for_rally()
235 with open('rally_conf.json', 'w') as fp:
236 json.dump(rally_conf, fp)
237 cmd = ("rally deployment create "
238 "--file=rally_conf.json --name={}"
239 .format(CONST.rally_deployment_name))
240 ft_utils.execute_command(cmd,
241 error_msg=("Problem while creating "
244 cmd = "rally deployment check"
245 ft_utils.execute_command(cmd,
246 error_msg=("OpenStack not responding or "
247 "faulty Rally deployment."))
249 cmd = "rally deployment list"
250 ft_utils.execute_command(cmd,
251 error_msg=("Problem while listing "
252 "Rally deployment."))
254 cmd = "rally plugin list | head -5"
255 ft_utils.execute_command(cmd,
256 error_msg=("Problem while showing "
260 def install_tempest():
261 logger.info("Installing tempest from existing repo...")
262 cmd = ("rally verify create-verifier --source {0} "
263 "--name {1} --type tempest"
264 .format(CONST.dir_repo_tempest, CONST.tempest_deployment_name))
265 ft_utils.execute_command(cmd,
266 error_msg="Problem while installing Tempest.")
269 def check_environment():
270 msg_not_active = "The Functest environment is not installed."
271 if not os.path.isfile(CONST.env_active):
272 logger.error(msg_not_active)
275 with open(CONST.env_active, "r") as env_file:
277 if not re.search("1", s):
278 logger.error(msg_not_active)
281 logger.info("Functest environment is installed.")
285 if not (kwargs['action'] in actions):
286 logger.error('Argument not valid.')
289 if kwargs['action'] == "start":
290 logger.info("######### Preparing Functest environment #########\n")
291 check_env_variables()
299 with open(CONST.env_active, "w") as env_file:
304 if kwargs['action'] == "check":
310 if __name__ == '__main__':
311 parser = PrepareEnvParser()
312 args = parser.parse_args(sys.argv[1:])