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']
20 parser = argparse.ArgumentParser()
21 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
22 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
23 args = parser.parse_args()
26 """ logging configuration """
27 logger = logging.getLogger('config_functest')
28 logger.setLevel(logging.DEBUG)
30 ch = logging.StreamHandler()
32 ch.setLevel(logging.DEBUG)
34 ch.setLevel(logging.INFO)
36 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
37 ch.setFormatter(formatter)
42 yaml_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/functest.yaml'
43 name = yaml_url.rsplit('/')[-1]
45 if not os.path.exists(dest):
46 logger.info("Downloading functest.yaml...")
48 response = urllib2.urlopen(yaml_url)
49 except (urllib2.HTTPError, urllib2.URLError):
50 logger.error("Error in fetching %s" %yaml_url)
52 with open(dest, 'wb') as f:
53 f.write(response.read())
54 logger.info("functest.yaml stored in %s" % dest)
56 logger.info("functest.yaml found in %s" % dest)
59 with open('./functest.yaml') as f:
60 functest_yaml = yaml.safe_load(f)
64 """ 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")
73 NEUTRON_PUBLIC_NAME = functest_yaml.get("general").get("openstack").get("neutron_public_net_name")
74 NEUTRON_NET_NAME = functest_yaml.get("general").get("openstack").get("neutron_net_name")
75 NEUTRON_SUBNET_NAME = functest_yaml.get("general").get("openstack").get("neutron_subnet_name")
76 NEUTRON_RANGE = functest_yaml.get("general").get("openstack").get("neutron_subnet_range")
77 ROUTER_NAME = functest_yaml.get("general").get("openstack").get("neutron_router_name")
79 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
80 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
81 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
82 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
83 IMAGE_DOWNLOAD_PATH = FUNCTEST_BASE_DIR + IMAGE_FILE_NAME
86 def config_functest_start():
88 Start the functest environment installation
90 #if config_functest_check():
91 # logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
93 if not check_internet_connectivity():
94 logger.error("There is no Internet connectivity. Please check the network configuration.")
96 elif not check_credentials():
97 logger.error("Please source the openrc credentials and run the script again.")
98 #TODO: source the credentials in this script
100 elif not check_neutron_net(NEUTRON_PUBLIC_NAME):
101 #The public network is normally created by default, no need to create a new one
102 logger.debug("Public network '%s' not found." % NEUTRON_PUBLIC_NAME)
103 logger.error("A public Neutron network is needed for the environment. Please create one.")
104 #TODO: source the credentials in this script
107 # Clean in case there are left overs
108 config_functest_clean()
110 logger.info("Starting installationg of functest environment in %s" % FUNCTEST_BASE_DIR)
111 os.makedirs(FUNCTEST_BASE_DIR)
112 if not os.path.exists(FUNCTEST_BASE_DIR):
113 logger.error("There has been a problem while creating the environment directory.")
116 logger.info("Donwloading test scripts and scenarios...")
117 if not download_tests():
118 logger.error("There has been a problem while downloading the test scripts and scenarios.")
119 config_functest_clean()
122 logger.info("Installing Rally...")
123 if not install_rally():
124 logger.error("There has been a problem while installing Rally.")
125 config_functest_clean()
128 logger.info("Installing ODL environment...")
129 if not install_odl():
130 logger.error("There has been a problem while installing Robot.")
131 config_functest_clean()
134 logger.info("Creating a private Neutron network...")
135 logger.debug("Checking if private network '%s' exists..." % NEUTRON_NET_NAME)
136 #Now: if exists we don't create it again (the clean command does not clean the neutron network)
137 #TODO: this check will not be needed when cleaning the neutron is implemented
138 if check_neutron_net(NEUTRON_NET_NAME):
139 logger.info("Private network '%s' found. No need to create another one." % NEUTRON_NET_NAME)
141 logger.info("Private network '%s' not found. Creating..." % NEUTRON_NET_NAME)
142 if not create_neutron_net():
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...")
173 logger.debug("Checking directories...")
175 dirs = [FUNCTEST_BASE_DIR, RALLY_INSTALLATION_DIR, RALLY_REPO_DIR, RALLY_TEST_DIR, BENCH_TESTS_DIR, VPING_DIR, ODL_DIR]
177 if not os.path.exists(dir):
178 logger.debug("The directory '%s' does NOT exist." % dir)
182 logger.debug(" %s found" % dir)
184 logger.debug("...OK")
186 logger.debug("...FAIL")
189 logger.debug("Checking Rally deployment...")
190 if not check_rally():
191 logger.debug("Rally deployment NOT found.")
193 logger.debug("...FAIL")
195 logger.debug("...OK")
198 logger.debug("Checking Neutron...")
200 if not check_neutron_net(NEUTRON_NET_NAME):
201 logger.debug(" Private network '%s' NOT found." % NEUTRON_NET_NAME)
205 logger.debug(" Private network '%s' found." % NEUTRON_NET_NAME)
207 if not check_neutron_net(NEUTRON_PUBLIC_NAME):
208 logger.debug(" Public network '%s' NOT found." % NEUTRON_PUBLIC_NAME)
212 logger.debug(" Public network '%s' found." % NEUTRON_PUBLIC_NAME)
215 logger.debug("...OK")
217 logger.debug("...FAIL")
220 logger.debug("Checking Image...")
222 if not os.path.isfile(IMAGE_DOWNLOAD_PATH):
223 logger.debug(" Image file '%s' NOT found." % IMAGE_DOWNLOAD_PATH)
227 logger.debug(" Image file found in %s" % IMAGE_DOWNLOAD_PATH)
229 cmd="glance image-list | grep " + IMAGE_NAME
230 FNULL = open(os.devnull, 'w');
231 logger.debug(' Executing command : {}'.format(cmd))
232 p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
233 #if the command does not exist or there is no glance image
234 line = p.stdout.readline()
236 logger.debug(" Glance image NOT found.")
240 logger.debug(" Glance image found.")
243 logger.debug("...OK")
245 logger.debug("...FAIL")
247 #TODO: check OLD environment setup
256 def config_functest_clean():
258 Clean the existing functest environment
260 logger.info("Removing current functest environment...")
261 if os.path.exists(RALLY_INSTALLATION_DIR):
262 logger.debug("Removing rally installation directory %s" % RALLY_INSTALLATION_DIR)
263 shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
265 if os.path.exists(FUNCTEST_BASE_DIR):
266 logger.debug("Removing functest directory %s" % FUNCTEST_BASE_DIR)
267 cmd = "sudo rm -rf " + FUNCTEST_BASE_DIR #need to be sudo, not possible with rmtree
270 #logger.debug("Deleting Neutron network %s" % NEUTRON_NET_NAME)
271 #if not delete_neutron_net() :
272 # logger.error("Error deleting the network. Remove it manually.")
274 logger.debug("Deleting glance images")
275 cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
276 p = os.popen(cmd,"r")
278 #while image_id = p.readline()
279 for image_id in p.readlines():
280 cmd = "glance image-delete " + image_id
291 logger.info("Rally is already installed.")
293 logger.debug("Cloning repository...")
294 url = "https://git.openstack.org/openstack/rally"
295 Repo.clone_from(url, RALLY_REPO_DIR)
297 logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
298 install_script = RALLY_REPO_DIR + "install_rally.sh"
299 cmd = 'sudo ' + install_script
301 #subprocess.call(['sudo', install_script])
303 logger.debug("Creating Rally environment...")
304 cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
307 logger.debug("Installing tempest...")
308 cmd = "rally-manage tempest install"
311 cmd = "rally deployment check"
313 #TODO: check that everything is 'Available' and warn if not
315 cmd = "rally show images"
318 cmd = "rally show flavors"
327 Check if Rally is installed and properly configured
329 if os.path.exists(RALLY_INSTALLATION_DIR):
330 logger.debug(" Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
331 FNULL = open(os.devnull, 'w');
332 cmd="rally deployment list | grep opnfv";
333 logger.debug(' Executing command : {}'.format(cmd))
334 p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
335 #if the command does not exist or there is no deployment
336 line = p.stdout.readline()
338 logger.debug(" Rally deployment not found")
340 logger.debug(" Rally deployment found")
343 logger.debug(" Rally installation directory not found")
348 cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
350 cmd = ODL_DIR + "create_venv.sh"
355 def check_credentials():
357 Check if the OpenStack credentials (openrc) are sourced
359 #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
361 os.environ['OS_AUTH_URL']
365 os.environ['OS_USERNAME']
369 os.environ['OS_PASSWORD']
373 os.environ['OS_TENANT_NAME']
377 os.environ['OS_REGION_NAME']
383 def get_credentials():
385 d['username'] = os.environ['OS_USERNAME']
386 d['password'] = os.environ['OS_PASSWORD']
387 d['auth_url'] = os.environ['OS_AUTH_URL']
388 d['tenant_name'] = os.environ['OS_TENANT_NAME']
391 def get_nova_credentials():
393 d['username'] = os.environ['OS_USERNAME']
394 d['api_key'] = os.environ['OS_PASSWORD']
395 d['auth_url'] = os.environ['OS_AUTH_URL']
396 d['project_id'] = os.environ['OS_TENANT_NAME']
400 def download_tests():
401 os.makedirs(VPING_DIR)
403 os.makedirs(BENCH_TESTS_DIR)
405 logger.info("Downloading functest.yaml...")
406 yaml_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/functest.yaml'
407 if not download_url(yaml_url,FUNCTEST_BASE_DIR):
408 logger.error("Unable to download the configuration file functest.yaml")
411 logger.info("Downloading vPing test...")
412 vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
413 if not download_url(vPing_url,VPING_DIR):
417 logger.info("Downloading Rally bench tests...")
418 run_rally_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/libraries/run_rally.py'
419 if not download_url(run_rally_url,RALLY_TEST_DIR):
422 rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
423 bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
424 for i in bench_tests:
425 rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
426 logger.debug("Downloading %s" %rally_bench_url)
427 if not download_url(rally_bench_url,BENCH_TESTS_DIR):
430 logger.info("Downloading OLD tests...")
431 odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
432 odl_tests = ['create_venv.sh', 'requirements.pip', 'start_tests.sh', 'test_list.txt']
434 odl_url = odl_base_url + i
435 logger.debug("Downloading %s" %odl_url)
436 if not download_url(odl_url,ODL_DIR):
442 def create_neutron_net():
443 credentials = get_credentials()
444 neutron = client.Client(**credentials)
446 neutron.format = 'json'
447 logger.debug('Creating Neutron network %s...' % NEUTRON_NET_NAME)
448 json_body = {'network': {'name': NEUTRON_NET_NAME,
449 'admin_state_up': True}}
450 netw = neutron.create_network(body=json_body)
451 net_dict = netw['network']
452 network_id = net_dict['id']
453 logger.debug("Network '%s' created successfully" % network_id)
455 logger.debug('Creating Subnet....')
456 json_body = {'subnets': [{'cidr': NEUTRON_RANGE,
457 'ip_version': 4, 'network_id': network_id}]}
458 subnet = neutron.create_subnet(body=json_body)
459 logger.debug("Subnet '%s' created successfully" % subnet)
461 logger.debug('Creating Router...')
462 json_body = {'router': {'name': ROUTER_NAME, 'admin_state_up': True}}
463 router = neutron.create_router(json_body)
464 logger.debug("Router '%s' created successfully" % router)
465 router_id = router['router']['id']
467 logger.debug('Creating Port')
468 json_body = {'port': {
469 'admin_state_up': True,
470 'device_id': router_id,
472 'network_id': network_id,
474 response = neutron.create_port(body=json_body)
475 logger.debug("Port created successfully.")
477 logger.debug('Setting up gateway...')
478 public_network_id = get_network_id(neutron,NEUTRON_PUBLIC_NAME)
479 json_body = {'network_id': public_network_id, 'enable_snat' : True}
480 gateway = neutron.add_gateway_router(router_id,body=json_body)
481 logger.debug("Gateway '%s' added successfully" % gateway)
483 logger.error("There has been a problem when creating the Neutron network.")
486 logger.info("Neutron network created successfully.")
491 def get_network_id(neutron_client, network_name):
492 networks = neutron_client.list_networks()['networks']
495 if n['name'] == network_name:
500 def check_neutron_net(net_name):
501 credentials = get_credentials()
502 neutron = client.Client(**credentials)
503 for network in neutron.list_networks()['networks']:
504 if network['name'] == net_name :
505 for subnet in network['subnets']:
509 def delete_neutron_net():
510 #TODO: remove router, ports
511 credentials = get_credentials()
512 neutron = client.Client(**credentials)
514 #https://github.com/isginf/openstack_tools/blob/master/openstack_remove_tenant.py
515 for network in neutron.list_networks()['networks']:
516 if network['name'] == NEUTRON_NET_NAME :
517 for subnet in network['subnets']:
518 print "Deleting subnet " + subnet
519 neutron.delete_subnet(subnet)
520 print "Deleting network " + network['name']
521 neutron.delete_neutron_net(network['id'])
530 def create_glance_image(path,name,disk_format):
532 Create a glance image given the absolute path of the image, its name and the disk format
534 cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
542 def download_url(url, dest_path):
544 Download a file to a destination path given a URL
546 name = url.rsplit('/')[-1]
547 dest = dest_path + name
549 response = urllib2.urlopen(url)
550 except (urllib2.HTTPError, urllib2.URLError):
551 logger.error("Error in fetching %s" %url)
554 with open(dest, 'wb') as f:
555 f.write(response.read())
559 def download_url_with_progress(url, dest_path):
561 Download a file to a destination path given a URL showing the progress
563 name = url.rsplit('/')[-1]
564 dest = dest_path + name
566 response = urllib2.urlopen(url)
567 except (urllib2.HTTPError, urllib2.URLError):
568 logger.error("Error in fetching %s" %url)
572 meta = response.info()
573 file_size = int(meta.getheaders("Content-Length")[0])
574 logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
579 buffer = response.read(block_sz)
583 file_size_dl += len(buffer)
585 status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
586 status = status + chr(8)*(len(status)+1)
594 def check_internet_connectivity(url='http://www.google.com/'):
596 Check if there is access to the internet
599 urllib2.urlopen(url, timeout=5)
601 except urllib.request.URLError:
604 def execute_command(cmd):
606 Execute Linux command
608 logger.debug('Executing command : {}'.format(cmd))
609 #p = os.popen(cmd,"r")
610 #logger.debug(p.read())
611 output_file = "/tmp/output.txt"
612 f = open(output_file, 'w+')
613 p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
615 f = open(output_file, 'r')
616 logger.debug(f.read())
617 #p = subprocess.call(cmd,shell=True);
621 logger.error("Error when executing command %s" %cmd)
628 if not (args.action in actions):
629 logger.error('argument not valid')
632 if args.action == "start":
633 config_functest_start()
635 if args.action == "check":
636 if config_functest_check():
637 logger.info("Functest environment correctly installed")
639 logger.info("Functest environment not found or faulty")
641 if args.action == "clean":
643 print("Are you sure? [y|n]")
644 answer = raw_input("")
646 config_functest_clean()
651 print("Invalid option.")
655 if __name__ == '__main__':