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),
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 create_directories():
112 logger.info("Creating needed directories...")
113 if not os.path.exists(CONST.dir_functest_conf):
114 os.makedirs(CONST.dir_functest_conf)
115 logger.info(" %s created." % CONST.dir_functest_conf)
117 logger.debug(" %s already exists."
118 % CONST.dir_functest_conf)
120 if not os.path.exists(CONST.dir_functest_data):
121 os.makedirs(CONST.dir_functest_data)
122 logger.info(" %s created." % CONST.dir_functest_data)
124 logger.debug(" %s already exists."
125 % CONST.dir_functest_data)
128 def source_rc_file():
130 logger.info("Fetching RC file...")
132 if CONST.openstack_creds is None:
133 logger.warning("The environment variable 'creds' must be set and"
134 "pointing to the local RC file. Using default: "
135 "/home/opnfv/functest/conf/openstack.creds ...")
136 os.path.join(CONST.dir_functest_conf, 'openstack.creds')
138 if not os.path.isfile(CONST.openstack_creds):
139 logger.info("RC file not provided. "
140 "Fetching it from the installer...")
141 if CONST.INSTALLER_IP is None:
142 logger.error("The env variable CI_INSTALLER_IP must be provided in"
143 " order to fetch the credentials from the installer.")
144 raise Exception("Missing CI_INSTALLER_IP.")
145 if CONST.INSTALLER_TYPE not in opnfv_constants.INSTALLERS:
146 logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
147 "not a valid OPNFV installer. Available "
148 "installers are : %s." %
149 (CONST.INSTALLER_TYPE,
150 opnfv_constants.INSTALLERS))
151 raise Exception("Wrong INSTALLER_TYPE.")
153 cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
155 % (CONST.openstack_creds,
156 CONST.INSTALLER_TYPE,
158 logger.debug("Executing command: %s" % cmd)
159 p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
160 output = p.communicate()[0]
161 logger.debug("\n%s" % output)
162 if p.returncode != 0:
163 raise Exception("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 raise Exception("The file %s is empty." % CONST.openstack_creds)
170 logger.info("Sourcing the OpenStack RC file...")
171 os_utils.source_credentials(
172 CONST.openstack_creds)
173 for key, value in os.environ.iteritems():
174 if re.search("OS_", key):
175 if key == 'OS_AUTH_URL':
176 CONST.OS_AUTH_URL = value
177 elif key == 'OS_USERNAME':
178 CONST.OS_USERNAME = value
179 elif key == 'OS_TENANT_NAME':
180 CONST.OS_TENANT_NAME = value
181 elif key == 'OS_PASSWORD':
182 CONST.OS_PASSWORD = value
185 def patch_config_file():
187 for key in functest_patch_yaml:
188 if key in CONST.DEPLOY_SCENARIO:
189 new_functest_yaml = dict(ft_utils.merge_dicts(
190 ft_utils.get_functest_yaml(), functest_patch_yaml[key]))
194 os.remove(CONFIG_FUNCTEST_PATH)
195 with open(CONFIG_FUNCTEST_PATH, "w") as f:
196 f.write(yaml.dump(new_functest_yaml, default_style='"'))
200 def verify_deployment():
202 logger.info("Verifying OpenStack services...")
203 cmd = ("%s/functest/ci/check_os.sh" % CONST.dir_repo_functest)
205 logger.debug("Executing command: %s" % cmd)
206 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
208 while p.poll() is None:
209 line = p.stdout.readline().rstrip()
212 raise Exception("Problem while running 'check_os.sh'.")
218 logger.info("Creating Rally environment...")
220 cmd = "rally deployment destroy opnfv-rally"
221 ft_utils.execute_command(cmd, error_msg=(
222 "Deployment %s does not exist."
223 % CONST.rally_deployment_name),
225 rally_conf = os_utils.get_credentials_for_rally()
226 with open('rally_conf.json', 'w') as fp:
227 json.dump(rally_conf, fp)
228 cmd = ("rally deployment create "
229 "--file=rally_conf.json --name={}"
230 .format(CONST.rally_deployment_name))
231 ft_utils.execute_command(cmd,
232 error_msg=("Problem while creating "
235 cmd = "rally deployment check"
236 ft_utils.execute_command(cmd,
237 error_msg=("OpenStack not responding or "
238 "faulty Rally deployment."))
240 cmd = "rally deployment list"
241 ft_utils.execute_command(cmd,
242 error_msg=("Problem while listing "
243 "Rally deployment."))
245 cmd = "rally plugin list | head -5"
246 ft_utils.execute_command(cmd,
247 error_msg=("Problem while showing "
251 def install_tempest():
252 logger.info("Installing tempest from existing repo...")
253 cmd = ("rally verify create-verifier --source {0} "
254 "--name {1} --type tempest"
255 .format(CONST.dir_repo_tempest, CONST.tempest_deployment_name))
256 ft_utils.execute_command(cmd,
257 error_msg="Problem while installing Tempest.")
261 os_utils.get_or_create_flavor('m1.tiny',
268 def check_environment():
269 msg_not_active = "The Functest environment is not installed."
270 if not os.path.isfile(CONST.env_active):
271 raise Exception(msg_not_active)
273 with open(CONST.env_active, "r") as env_file:
275 if not re.search("1", s):
276 raise Exception(msg_not_active)
278 logger.info("Functest environment is installed.")
283 if not (kwargs['action'] in actions):
284 logger.error('Argument not valid.')
286 elif kwargs['action'] == "start":
287 logger.info("######### Preparing Functest environment #########\n")
288 check_env_variables()
296 with open(CONST.env_active, "w") as env_file:
299 elif kwargs['action'] == "check":
301 except Exception as e:
307 if __name__ == '__main__':
308 parser = PrepareEnvParser()
309 args = parser.parse_args(sys.argv[1:])
310 sys.exit(main(**args))