3 # Copyright (c) 2015 Ericsson
4 # jose.lausuch@ericsson.com
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
11 import re, json, os, urllib2, argparse, logging, shutil, subprocess, yaml
14 actions = ['start', 'check', 'clean']
16 with open('functest.yaml') as f:
17 functest_yaml = yaml.safe_load(f)
20 logger.info("Downloading functest.yaml...")
21 yaml_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/functest.yaml'
22 if not download_url(yaml_url,"./"):
23 logger.error("Unable to download the configuration file functest.yaml")
26 """ global variables """
27 HOME = os.environ['HOME']+"/"
28 FUNCTEST_BASE_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_functest")
29 RALLY_REPO_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_repo")
30 RALLY_TEST_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally")
31 RALLY_INSTALLATION_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_inst")
32 BENCH_TESTS_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_scn")
33 VPING_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_vping")
34 ODL_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_odl")
35 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
36 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
37 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
38 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
39 IMAGE_DOWNLOAD_PATH = FUNCTEST_BASE_DIR + IMAGE_FILE_NAME
41 parser = argparse.ArgumentParser()
42 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
43 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
44 args = parser.parse_args()
47 """ logging configuration """
48 logger = logging.getLogger('config_functest')
49 logger.setLevel(logging.DEBUG)
51 ch = logging.StreamHandler()
53 ch.setLevel(logging.DEBUG)
55 ch.setLevel(logging.INFO)
57 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
58 ch.setFormatter(formatter)
63 def config_functest_start():
65 Start the functest environment installation
67 if config_functest_check():
68 logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
70 elif not check_internet_connectivity():
71 logger.error("There is no Internet connectivity. Please check the network configuration.")
73 elif not check_credentials():
74 logger.error("Please source the openrc credentials and run the script again.")
75 #TODO: source the credentials in this script
78 config_functest_clean()
80 logger.info("Starting installationg of functest environment in %s" %FUNCTEST_BASE_DIR)
81 os.makedirs(FUNCTEST_BASE_DIR)
82 if not os.path.exists(FUNCTEST_BASE_DIR):
83 logger.error("There has been a problem while creating the environment directory.")
86 logger.info("Donwloading test scripts and scenarios...")
87 if not download_tests():
88 logger.error("There has been a problem while downloading the test scripts and scenarios.")
89 config_functest_clean()
92 logger.info("Installing Rally...")
93 if not install_rally():
94 logger.error("There has been a problem while installing Rally.")
95 config_functest_clean()
98 logger.info("Installing ODL environment...")
100 logger.error("There has been a problem while installing Robot.")
101 config_functest_clean()
104 logger.info("Donwloading image...")
105 if not download_url_with_progress(IMAGE_URL, FUNCTEST_BASE_DIR):
106 logger.error("There has been a problem while downloading the image.")
107 config_functest_clean()
110 logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
111 if not create_glance_image(IMAGE_DOWNLOAD_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
112 logger.error("There has been a problem while creating the Glance image.")
113 config_functest_clean()
120 def config_functest_check():
122 Check if the functest environment is properly installed
124 logger.info("Checking current functest configuration...")
126 logger.debug("Checking directories...")
127 dirs = [FUNCTEST_BASE_DIR, RALLY_INSTALLATION_DIR, RALLY_REPO_DIR, RALLY_TEST_DIR, BENCH_TESTS_DIR, VPING_DIR, ODL_DIR]
129 if not os.path.exists(dir):
130 logger.debug("The directory %s does not exist." %dir)
132 logger.debug(" %s found" % dir)
134 logger.debug("...OK")
135 logger.debug("Checking Rally deployment...")
136 if not check_rally():
137 logger.debug("Rally deployment not found.")
139 logger.debug("...OK")
141 logger.debug("Checking Image...")
142 if not os.path.isfile(IMAGE_DOWNLOAD_PATH):
144 logger.debug(" Image file found in %s" %IMAGE_DOWNLOAD_PATH)
146 cmd="glance image-list | grep " + IMAGE_NAME
147 FNULL = open(os.devnull, 'w');
148 logger.debug(' Executing command : {}'.format(cmd))
149 p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
150 #if the command does not exist or there is no glance image
151 line = p.stdout.readline()
153 logger.debug(" Glance image not found")
155 logger.debug(" Glance image found")
156 logger.debug("...OK")
158 #TODO: check OLD environment setup
165 def config_functest_clean():
167 Clean the existing functest environment
169 logger.info("Removing current functest environment...")
170 if os.path.exists(RALLY_INSTALLATION_DIR):
171 logger.debug("Removing rally installation directory %s" % RALLY_INSTALLATION_DIR)
172 shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
174 if os.path.exists(FUNCTEST_BASE_DIR):
175 logger.debug("Removing functest directory %s" % FUNCTEST_BASE_DIR)
176 cmd = "sudo rm -rf " + FUNCTEST_BASE_DIR #need to be sudo, not possible with rmtree
179 logger.debug("Deleting glance images")
180 cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
181 p = os.popen(cmd,"r")
183 #while image_id = p.readline()
184 for image_id in p.readlines():
185 cmd = "glance image-delete " + image_id
193 logger.info("Rally is already installed.")
195 logger.debug("Cloning repository...")
196 url = "https://git.openstack.org/openstack/rally"
197 Repo.clone_from(url, RALLY_REPO_DIR)
199 logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
200 install_script = RALLY_REPO_DIR + "install_rally.sh"
201 cmd = 'sudo ' + install_script
203 #subprocess.call(['sudo', install_script])
205 logger.debug("Creating Rally environment...")
206 cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
209 logger.debug("Installing tempest...")
210 cmd = "rally-manage tempest install"
213 cmd = "rally deployment check"
215 #TODO: check that everything is 'Available' and warn if not
217 cmd = "rally show images"
220 cmd = "rally show flavors"
229 Check if Rally is installed and properly configured
231 if os.path.exists(RALLY_INSTALLATION_DIR):
232 logger.debug(" Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
233 FNULL = open(os.devnull, 'w');
234 cmd="rally deployment list | grep opnfv";
235 logger.debug(' Executing command : {}'.format(cmd))
236 p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
237 #if the command does not exist or there is no deployment
238 line = p.stdout.readline()
240 logger.debug(" Rally deployment not found")
242 logger.debug(" Rally deployment found")
245 logger.debug(" Rally installation directory not found")
250 cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
252 cmd = ODL_DIR + "create_venv.sh"
257 def check_credentials():
259 Check if the OpenStack credentials (openrc) are sourced
261 #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
263 os.environ['OS_AUTH_URL']
267 os.environ['OS_USERNAME']
271 os.environ['OS_PASSWORD']
275 os.environ['OS_TENANT_NAME']
279 os.environ['OS_REGION_NAME']
285 def download_tests():
286 os.makedirs(VPING_DIR)
288 os.makedirs(BENCH_TESTS_DIR)
290 logger.info("Downloading functest.yaml...")
291 yaml_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/functest.yaml'
292 if not download_url(yaml_url,FUNCTEST_BASE_DIR):
293 logger.error("Unable to download the configuration file functest.yaml")
296 logger.info("Downloading vPing test...")
297 vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
298 if not download_url(vPing_url,VPING_DIR):
302 logger.info("Downloading Rally bench tests...")
303 run_rally_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/libraries/run_rally.py'
304 if not download_url(run_rally_url,RALLY_TEST_DIR):
307 rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
308 bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
309 for i in bench_tests:
310 rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
311 logger.debug("Downloading %s" %rally_bench_url)
312 if not download_url(rally_bench_url,BENCH_TESTS_DIR):
315 logger.info("Downloading OLD tests...")
316 odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
317 odl_tests = ['create_venv.sh', 'requirements.pip', 'start_tests.sh', 'test_list.txt']
319 odl_url = odl_base_url + i
320 logger.debug("Downloading %s" %odl_url)
321 if not download_url(odl_url,ODL_DIR):
328 def create_glance_image(path,name,disk_format):
330 Create a glance image given the absolute path of the image, its name and the disk format
332 cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
337 def download_url(url, dest_path):
339 Download a file to a destination path given a URL
341 name = url.rsplit('/')[-1]
342 dest = dest_path + name
344 response = urllib2.urlopen(url)
345 except (urllib2.HTTPError, urllib2.URLError):
346 logger.error("Error in fetching %s" %url)
349 with open(dest, 'wb') as f:
350 f.write(response.read())
354 def download_url_with_progress(url, dest_path):
356 Download a file to a destination path given a URL showing the progress
358 name = url.rsplit('/')[-1]
359 dest = dest_path + name
361 response = urllib2.urlopen(url)
362 except (urllib2.HTTPError, urllib2.URLError):
363 logger.error("Error in fetching %s" %url)
367 meta = response.info()
368 file_size = int(meta.getheaders("Content-Length")[0])
369 logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
374 buffer = response.read(block_sz)
378 file_size_dl += len(buffer)
380 status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
381 status = status + chr(8)*(len(status)+1)
389 def check_internet_connectivity(url='http://www.google.com/'):
391 Check if there is access to the internet
394 urllib2.urlopen(url, timeout=5)
396 except urllib.request.URLError:
399 def execute_command(cmd):
401 Execute Linux command
403 logger.debug('Executing command : {}'.format(cmd))
404 #p = os.popen(cmd,"r")
405 #logger.debug(p.read())
406 output_file = "/tmp/output.txt"
407 f = open(output_file, 'w+')
408 p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
410 f = open(output_file, 'r')
411 logger.debug(f.read())
412 #p = subprocess.call(cmd,shell=True);
416 logger.error("Error when executing command %s" %cmd)
423 if not (args.action in actions):
424 logger.error('argument not valid')
427 if args.action == "start":
428 config_functest_start()
430 if args.action == "check":
431 if config_functest_check():
432 logger.info("Functest environment correctly installed")
434 logger.info("Functest environment not found or faulty")
436 if args.action == "clean":
438 print("Are you sure? [y|n]")
439 answer = raw_input("")
441 config_functest_clean()
446 print("Invalid option.")
450 if __name__ == '__main__':