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 from neutronclient.v2_0 import client
16 actions = ['start', 'check', 'clean']
17 parser = argparse.ArgumentParser()
18 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
19 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
20 parser.add_argument("-f", "--force", help="Force", action="store_true")
21 args = parser.parse_args()
24 """ logging configuration """
25 logger = logging.getLogger('config_functest')
26 logger.setLevel(logging.DEBUG)
28 ch = logging.StreamHandler()
30 ch.setLevel(logging.DEBUG)
32 ch.setLevel(logging.INFO)
35 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
36 ch.setFormatter(formatter)
41 yaml_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/functest.yaml'
42 name = yaml_url.rsplit('/')[-1]
44 if not os.path.exists(dest):
45 logger.info("Downloading functest.yaml...")
47 response = urllib2.urlopen(yaml_url)
48 except (urllib2.HTTPError, urllib2.URLError):
49 logger.error("Error in fetching %s" %yaml_url)
51 with open(dest, 'wb') as f:
52 f.write(response.read())
53 logger.info("functest.yaml stored in %s" % dest)
55 logger.info("functest.yaml found in %s" % dest)
58 with open('./functest.yaml') as f:
59 functest_yaml = yaml.safe_load(f)
63 """ global variables """
65 HOME = os.environ['HOME']+"/"
66 FUNCTEST_BASE_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_functest")
67 RALLY_REPO_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_repo")
68 RALLY_TEST_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally")
69 RALLY_INSTALLATION_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_inst")
70 BENCH_TESTS_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_scn")
71 VPING_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_vping")
72 ODL_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_odl")
75 # NEUTRON Private Network parameters
76 NEUTRON_PRIVATE_NET_NAME = functest_yaml.get("general").get("openstack").get("neutron_private_net_name")
77 NEUTRON_PRIVATE_SUBNET_NAME = functest_yaml.get("general").get("openstack").get("neutron_private_subnet_name")
78 NEUTRON_PRIVATE_SUBNET_CIDR = functest_yaml.get("general").get("openstack").get("neutron_private_subnet_cidr")
79 ROUTER_NAME = functest_yaml.get("general").get("openstack").get("neutron_router_name")
81 #GLANCE image parameters
82 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
83 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
84 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
85 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
86 IMAGE_DOWNLOAD_PATH = FUNCTEST_BASE_DIR + IMAGE_FILE_NAME
91 def config_functest_start():
93 Start the functest environment installation
95 if not check_internet_connectivity():
96 logger.error("There is no Internet connectivity. Please check the network configuration.")
99 if config_functest_check():
100 logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
104 # Clean in case there are left overs
105 logger.debug("Functest environment not found or faulty. Cleaning in case of leftovers.")
106 config_functest_clean()
108 logger.info("Starting installation of functest environment in %s" % FUNCTEST_BASE_DIR)
109 os.makedirs(FUNCTEST_BASE_DIR)
110 if not os.path.exists(FUNCTEST_BASE_DIR):
111 logger.error("There has been a problem while creating the environment directory.")
114 logger.info("Downloading test scripts and scenarios...")
115 if not download_tests():
116 logger.error("There has been a problem while downloading the test scripts and scenarios.")
117 config_functest_clean()
120 logger.info("Installing Rally...")
121 if not install_rally():
122 logger.error("There has been a problem while installing Rally.")
123 config_functest_clean()
126 logger.info("Installing ODL environment...")
127 if not install_odl():
128 logger.error("There has been a problem while installing Robot.")
129 config_functest_clean()
132 credentials = get_credentials()
133 neutron_client = client.Client(**credentials)
135 logger.info("Configuring Neutron...")
136 logger.info("Checking if private network '%s' exists..." % NEUTRON_PRIVATE_NET_NAME)
137 #Now: if exists we don't create it again (the clean command does not clean the neutron networks yet)
138 if check_neutron_net(neutron_client, NEUTRON_PRIVATE_NET_NAME):
139 logger.info("Private network '%s' found. No need to create another one." % NEUTRON_PRIVATE_NET_NAME)
141 logger.info("Private network '%s' not found. Creating..." % NEUTRON_PRIVATE_NET_NAME)
142 if not create_private_neutron_net(neutron_client):
143 logger.error("There has been a problem while creating the Neutron network.")
144 #config_functest_clean()
148 logger.info("Donwloading image...")
149 if not download_url_with_progress(IMAGE_URL, FUNCTEST_BASE_DIR):
150 logger.error("There has been a problem while downloading the image.")
151 config_functest_clean()
154 logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
155 if not create_glance_image(IMAGE_DOWNLOAD_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
156 logger.error("There has been a problem while creating the Glance image.")
157 config_functest_clean()
164 def config_functest_check():
166 Check if the functest environment is properly installed
170 logger.info("Checking current functest configuration...")
171 credentials = get_credentials()
172 neutron_client = client.Client(**credentials)
174 logger.debug("Checking directories...")
176 dirs = [FUNCTEST_BASE_DIR, RALLY_INSTALLATION_DIR, RALLY_REPO_DIR, RALLY_TEST_DIR, BENCH_TESTS_DIR, VPING_DIR, ODL_DIR]
178 if not os.path.exists(dir):
179 logger.debug("The directory '%s' does NOT exist." % dir)
183 logger.debug(" %s found" % dir)
185 logger.debug("...OK")
187 logger.debug("...FAIL")
190 logger.debug("Checking Rally deployment...")
191 if not check_rally():
192 logger.debug(" Rally deployment NOT found.")
194 logger.debug("...FAIL")
196 logger.debug("...OK")
199 logger.debug("Checking Neutron...")
200 if not check_neutron_net(neutron_client, NEUTRON_PRIVATE_NET_NAME):
201 logger.debug(" Private network '%s' NOT found." % NEUTRON_PRIVATE_NET_NAME)
202 logger.debug("...FAIL")
205 logger.debug(" Private network '%s' found." % NEUTRON_PRIVATE_NET_NAME)
206 logger.debug("...OK")
209 logger.debug("Checking Image...")
211 if not os.path.isfile(IMAGE_DOWNLOAD_PATH):
212 logger.debug(" Image file '%s' NOT found." % IMAGE_DOWNLOAD_PATH)
216 logger.debug(" Image file found in %s" % IMAGE_DOWNLOAD_PATH)
218 cmd="glance image-list | grep " + IMAGE_NAME
219 FNULL = open(os.devnull, 'w');
220 logger.debug(' Executing command : {}'.format(cmd))
221 p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
222 #if the command does not exist or there is no glance image
223 line = p.stdout.readline()
225 logger.debug(" Glance image NOT found.")
229 logger.debug(" Glance image found.")
232 logger.debug("...OK")
234 logger.debug("...FAIL")
236 #TODO: check OLD environment setup
245 def config_functest_clean():
247 Clean the existing functest environment
249 logger.info("Removing current functest environment...")
250 if os.path.exists(RALLY_INSTALLATION_DIR):
251 logger.debug("Removing rally installation directory %s" % RALLY_INSTALLATION_DIR)
252 shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
254 if os.path.exists(FUNCTEST_BASE_DIR):
255 logger.debug("Removing functest directory %s" % FUNCTEST_BASE_DIR)
256 cmd = "sudo rm -rf " + FUNCTEST_BASE_DIR #need to be sudo, not possible with rmtree
259 #logger.debug("Deleting Neutron network %s" % NEUTRON_PRIVATE_NET_NAME)
260 #if not delete_neutron_net() :
261 # logger.error("Error deleting the network. Remove it manually.")
263 logger.debug("Deleting glance images")
264 cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
265 p = os.popen(cmd,"r")
267 #while image_id = p.readline()
268 for image_id in p.readlines():
269 cmd = "glance image-delete " + image_id
280 logger.info("Rally is already installed.")
282 logger.debug("Cloning repository...")
283 url = "https://git.openstack.org/openstack/rally"
284 Repo.clone_from(url, RALLY_REPO_DIR)
286 logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
287 install_script = RALLY_REPO_DIR + "install_rally.sh"
288 cmd = 'sudo ' + install_script
290 #subprocess.call(['sudo', install_script])
292 logger.debug("Creating Rally environment...")
293 cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
296 logger.debug("Installing tempest...")
297 cmd = "rally-manage tempest install"
300 cmd = "rally deployment check"
302 #TODO: check that everything is 'Available' and warn if not
304 cmd = "rally show images"
307 cmd = "rally show flavors"
316 Check if Rally is installed and properly configured
318 if os.path.exists(RALLY_INSTALLATION_DIR):
319 logger.debug(" Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
320 FNULL = open(os.devnull, 'w');
321 cmd="rally deployment list | grep opnfv";
322 logger.debug(' Executing command : {}'.format(cmd))
323 p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
324 #if the command does not exist or there is no deployment
325 line = p.stdout.readline()
327 logger.debug(" Rally deployment not found")
329 logger.debug(" Rally deployment found")
332 logger.debug(" Rally installation directory not found")
337 cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
339 cmd = ODL_DIR + "create_venv.sh"
344 def check_credentials():
346 Check if the OpenStack credentials (openrc) are sourced
348 #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
350 os.environ['OS_AUTH_URL']
354 os.environ['OS_USERNAME']
358 os.environ['OS_PASSWORD']
362 os.environ['OS_TENANT_NAME']
366 os.environ['OS_REGION_NAME']
372 def get_credentials():
374 d['username'] = os.environ['OS_USERNAME']
375 d['password'] = os.environ['OS_PASSWORD']
376 d['auth_url'] = os.environ['OS_AUTH_URL']
377 d['tenant_name'] = os.environ['OS_TENANT_NAME']
380 def get_nova_credentials():
382 d['username'] = os.environ['OS_USERNAME']
383 d['api_key'] = os.environ['OS_PASSWORD']
384 d['auth_url'] = os.environ['OS_AUTH_URL']
385 d['project_id'] = os.environ['OS_TENANT_NAME']
389 def download_tests():
390 os.makedirs(VPING_DIR)
392 os.makedirs(BENCH_TESTS_DIR)
394 logger.info("Copying functest.yaml to functest environment...")
396 shutil.copy("./functest.yaml", FUNCTEST_BASE_DIR+"functest.yaml")
398 print "Error copying the file:", sys.exc_info()[0]
401 logger.info("Downloading vPing test...")
402 vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
403 if not download_url(vPing_url,VPING_DIR):
407 logger.info("Downloading Rally bench tests...")
408 run_rally_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/libraries/run_rally.py'
409 if not download_url(run_rally_url,RALLY_TEST_DIR):
412 rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
413 bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
414 for i in bench_tests:
415 rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
416 logger.debug("Downloading %s" %rally_bench_url)
417 if not download_url(rally_bench_url,BENCH_TESTS_DIR):
420 logger.info("Downloading OLD tests...")
421 odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
422 odl_tests = ['create_venv.sh', 'requirements.pip', 'start_tests.sh', 'test_list.txt']
424 odl_url = odl_base_url + i
425 logger.debug("Downloading %s" %odl_url)
426 if not download_url(odl_url,ODL_DIR):
433 def create_private_neutron_net(neutron):
435 neutron.format = 'json'
436 logger.debug('Creating Neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
437 json_body = {'network': {'name': NEUTRON_PRIVATE_NET_NAME,
438 'admin_state_up': True}}
439 netw = neutron.create_network(body=json_body)
440 net_dict = netw['network']
441 network_id = net_dict['id']
442 logger.debug("Network '%s' created successfully" % network_id)
444 logger.debug('Creating Subnet....')
445 json_body = {'subnets': [{'name': NEUTRON_PRIVATE_SUBNET_NAME, 'cidr': NEUTRON_PRIVATE_SUBNET_CIDR,
446 'ip_version': 4, 'network_id': network_id}]}
448 subnet = neutron.create_subnet(body=json_body)
449 subnet_id = subnet['subnets'][0]['id']
450 logger.debug("Subnet '%s' created successfully" % subnet_id)
453 logger.debug('Creating Router...')
454 json_body = {'router': {'name': ROUTER_NAME, 'admin_state_up': True}}
455 router = neutron.create_router(json_body)
456 router_id = router['router']['id']
457 logger.debug("Router '%s' created successfully" % router_id)
459 logger.debug('Adding router to subnet...')
460 json_body = {"subnet_id": subnet_id}
461 neutron.add_interface_router(router=router_id, body=json_body)
462 logger.debug("Interface added successfully.")
465 print "Error:", sys.exc_info()[0]
468 logger.info("Private Neutron network created successfully.")
471 def get_network_id(neutron, network_name):
472 networks = neutron.list_networks()['networks']
475 if n['name'] == network_name:
480 def check_neutron_net(neutron, net_name):
481 for network in neutron.list_networks()['networks']:
482 if network['name'] == net_name :
483 for subnet in network['subnets']:
487 def delete_neutron_net(neutron):
488 #TODO: remove router, ports
490 #https://github.com/isginf/openstack_tools/blob/master/openstack_remove_tenant.py
491 for network in neutron.list_networks()['networks']:
492 if network['name'] == NEUTRON_PRIVATE_NET_NAME :
493 for subnet in network['subnets']:
494 print "Deleting subnet " + subnet
495 neutron.delete_subnet(subnet)
496 print "Deleting network " + network['name']
497 neutron.delete_neutron_net(network['id'])
506 def create_glance_image(path,name,disk_format):
508 Create a glance image given the absolute path of the image, its name and the disk format
510 cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
518 def download_url(url, dest_path):
520 Download a file to a destination path given a URL
522 name = url.rsplit('/')[-1]
523 dest = dest_path + name
525 response = urllib2.urlopen(url)
526 except (urllib2.HTTPError, urllib2.URLError):
527 logger.error("Error in fetching %s" %url)
530 with open(dest, 'wb') as f:
531 f.write(response.read())
535 def download_url_with_progress(url, dest_path):
537 Download a file to a destination path given a URL showing the progress
539 name = url.rsplit('/')[-1]
540 dest = dest_path + name
542 response = urllib2.urlopen(url)
543 except (urllib2.HTTPError, urllib2.URLError):
544 logger.error("Error in fetching %s" %url)
548 meta = response.info()
549 file_size = int(meta.getheaders("Content-Length")[0])
550 logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
555 buffer = response.read(block_sz)
559 file_size_dl += len(buffer)
561 status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
562 status = status + chr(8)*(len(status)+1)
570 def check_internet_connectivity(url='http://www.google.com/'):
572 Check if there is access to the internet
575 urllib2.urlopen(url, timeout=5)
577 except urllib.request.URLError:
580 def execute_command(cmd):
582 Execute Linux command
584 logger.debug('Executing command : {}'.format(cmd))
585 #p = os.popen(cmd,"r")
586 #logger.debug(p.read())
587 output_file = "output.txt"
588 f = open(output_file, 'w+')
589 p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
591 f = open(output_file, 'r')
592 logger.debug(f.read())
593 #p = subprocess.call(cmd,shell=True);
597 logger.error("Error when executing command %s" %cmd)
604 if not (args.action in actions):
605 logger.error('argument not valid')
608 if not check_credentials():
609 logger.error("Please source the openrc credentials and run the script again.")
610 #TODO: source the credentials in this script
613 if args.action == "start":
614 config_functest_start()
616 if args.action == "check":
617 if config_functest_check():
618 logger.info("Functest environment correctly installed")
620 logger.info("Functest environment not found or faulty")
622 if args.action == "clean":
624 config_functest_clean()
627 print("Are you sure? [y|n]")
628 answer = raw_input("")
630 config_functest_clean()
635 print("Invalid option.")
639 if __name__ == '__main__':