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 """
66 HOME = os.environ['HOME']+"/"
67 FUNCTEST_BASE_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_functest")
68 RALLY_REPO_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_repo")
69 RALLY_TEST_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally")
70 RALLY_INSTALLATION_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_inst")
71 BENCH_TESTS_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_scn")
72 VPING_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_vping")
73 ODL_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_odl")
76 # NEUTRON Private Network parameters
77 NEUTRON_PRIVATE_NET_NAME = functest_yaml.get("general").get("openstack").get("neutron_private_net_name")
78 NEUTRON_PRIVATE_SUBNET_NAME = functest_yaml.get("general").get("openstack").get("neutron_private_subnet_name")
79 NEUTRON_PRIVATE_SUBNET_CIDR = functest_yaml.get("general").get("openstack").get("neutron_private_subnet_cidr")
80 ROUTER_NAME = functest_yaml.get("general").get("openstack").get("neutron_router_name")
82 #GLANCE image parameters
83 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
84 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
85 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
86 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
87 IMAGE_DOWNLOAD_PATH = FUNCTEST_BASE_DIR + IMAGE_FILE_NAME
92 def config_functest_start():
94 Start the functest environment installation
97 if config_functest_check():
98 logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
101 if not check_internet_connectivity():
102 logger.error("There is no Internet connectivity. Please check the network configuration.")
104 elif not check_credentials():
105 logger.error("Please source the openrc credentials and run the script again.")
106 #TODO: source the credentials in this script
110 # Clean in case there are left overs
112 config_functest_clean()
114 logger.info("Starting installationg of functest environment in %s" % FUNCTEST_BASE_DIR)
115 os.makedirs(FUNCTEST_BASE_DIR)
116 if not os.path.exists(FUNCTEST_BASE_DIR):
117 logger.error("There has been a problem while creating the environment directory.")
120 logger.info("Donwloading test scripts and scenarios...")
121 if not download_tests():
122 logger.error("There has been a problem while downloading the test scripts and scenarios.")
123 config_functest_clean()
126 logger.info("Installing Rally...")
127 if not install_rally():
128 logger.error("There has been a problem while installing Rally.")
129 config_functest_clean()
132 logger.info("Installing ODL environment...")
133 if not install_odl():
134 logger.error("There has been a problem while installing Robot.")
135 config_functest_clean()
138 credentials = get_credentials()
139 neutron_client = client.Client(**credentials)
141 logger.info("Configuring Neutron...")
142 logger.info("Checking if private network '%s' exists..." % NEUTRON_PRIVATE_NET_NAME)
143 #Now: if exists we don't create it again (the clean command does not clean the neutron networks yet)
144 if check_neutron_net(neutron_client, NEUTRON_PRIVATE_NET_NAME):
145 logger.info("Private network '%s' found. No need to create another one." % NEUTRON_PRIVATE_NET_NAME)
147 logger.info("Private network '%s' not found. Creating..." % NEUTRON_PRIVATE_NET_NAME)
148 if not create_private_neutron_net(neutron_client):
149 logger.error("There has been a problem while creating the Neutron network.")
150 #config_functest_clean()
154 logger.info("Donwloading image...")
155 if not download_url_with_progress(IMAGE_URL, FUNCTEST_BASE_DIR):
156 logger.error("There has been a problem while downloading the image.")
157 config_functest_clean()
160 logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
161 if not create_glance_image(IMAGE_DOWNLOAD_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
162 logger.error("There has been a problem while creating the Glance image.")
163 config_functest_clean()
170 def config_functest_check():
172 Check if the functest environment is properly installed
176 logger.info("Checking current functest configuration...")
177 credentials = get_credentials()
178 neutron_client = client.Client(**credentials)
180 logger.debug("Checking directories...")
182 dirs = [FUNCTEST_BASE_DIR, RALLY_INSTALLATION_DIR, RALLY_REPO_DIR, RALLY_TEST_DIR, BENCH_TESTS_DIR, VPING_DIR, ODL_DIR]
184 if not os.path.exists(dir):
185 logger.debug("The directory '%s' does NOT exist." % dir)
189 logger.debug(" %s found" % dir)
191 logger.debug("...OK")
193 logger.debug("...FAIL")
196 logger.debug("Checking Rally deployment...")
197 if not check_rally():
198 logger.debug(" Rally deployment NOT found.")
200 logger.debug("...FAIL")
202 logger.debug("...OK")
205 logger.debug("Checking Neutron...")
206 if not check_neutron_net(neutron_client, NEUTRON_PRIVATE_NET_NAME):
207 logger.debug(" Private network '%s' NOT found." % NEUTRON_PRIVATE_NET_NAME)
208 logger.debug("...FAIL")
211 logger.debug(" Private network '%s' found." % NEUTRON_PRIVATE_NET_NAME)
212 logger.debug("...OK")
215 logger.debug("Checking Image...")
217 if not os.path.isfile(IMAGE_DOWNLOAD_PATH):
218 logger.debug(" Image file '%s' NOT found." % IMAGE_DOWNLOAD_PATH)
222 logger.debug(" Image file found in %s" % IMAGE_DOWNLOAD_PATH)
224 cmd="glance image-list | grep " + IMAGE_NAME
225 FNULL = open(os.devnull, 'w');
226 logger.debug(' Executing command : {}'.format(cmd))
227 p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
228 #if the command does not exist or there is no glance image
229 line = p.stdout.readline()
231 logger.debug(" Glance image NOT found.")
235 logger.debug(" Glance image found.")
238 logger.debug("...OK")
240 logger.debug("...FAIL")
242 #TODO: check OLD environment setup
251 def config_functest_clean():
253 Clean the existing functest environment
255 logger.info("Removing current functest environment...")
256 if os.path.exists(RALLY_INSTALLATION_DIR):
257 logger.debug("Removing rally installation directory %s" % RALLY_INSTALLATION_DIR)
258 shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
260 if os.path.exists(FUNCTEST_BASE_DIR):
261 logger.debug("Removing functest directory %s" % FUNCTEST_BASE_DIR)
262 cmd = "sudo rm -rf " + FUNCTEST_BASE_DIR #need to be sudo, not possible with rmtree
265 #logger.debug("Deleting Neutron network %s" % NEUTRON_PRIVATE_NET_NAME)
266 #if not delete_neutron_net() :
267 # logger.error("Error deleting the network. Remove it manually.")
269 logger.debug("Deleting glance images")
270 cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
271 p = os.popen(cmd,"r")
273 #while image_id = p.readline()
274 for image_id in p.readlines():
275 cmd = "glance image-delete " + image_id
286 logger.info("Rally is already installed.")
288 logger.debug("Cloning repository...")
289 url = "https://git.openstack.org/openstack/rally"
290 Repo.clone_from(url, RALLY_REPO_DIR)
292 logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
293 install_script = RALLY_REPO_DIR + "install_rally.sh"
294 cmd = 'sudo ' + install_script
296 #subprocess.call(['sudo', install_script])
298 logger.debug("Creating Rally environment...")
299 cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
302 logger.debug("Installing tempest...")
303 cmd = "rally-manage tempest install"
306 cmd = "rally deployment check"
308 #TODO: check that everything is 'Available' and warn if not
310 cmd = "rally show images"
313 cmd = "rally show flavors"
322 Check if Rally is installed and properly configured
324 if os.path.exists(RALLY_INSTALLATION_DIR):
325 logger.debug(" Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
326 FNULL = open(os.devnull, 'w');
327 cmd="rally deployment list | grep opnfv";
328 logger.debug(' Executing command : {}'.format(cmd))
329 p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
330 #if the command does not exist or there is no deployment
331 line = p.stdout.readline()
333 logger.debug(" Rally deployment not found")
335 logger.debug(" Rally deployment found")
338 logger.debug(" Rally installation directory not found")
343 cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
345 cmd = ODL_DIR + "create_venv.sh"
350 def check_credentials():
352 Check if the OpenStack credentials (openrc) are sourced
354 #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
356 os.environ['OS_AUTH_URL']
360 os.environ['OS_USERNAME']
364 os.environ['OS_PASSWORD']
368 os.environ['OS_TENANT_NAME']
372 os.environ['OS_REGION_NAME']
378 def get_credentials():
380 d['username'] = os.environ['OS_USERNAME']
381 d['password'] = os.environ['OS_PASSWORD']
382 d['auth_url'] = os.environ['OS_AUTH_URL']
383 d['tenant_name'] = os.environ['OS_TENANT_NAME']
386 def get_nova_credentials():
388 d['username'] = os.environ['OS_USERNAME']
389 d['api_key'] = os.environ['OS_PASSWORD']
390 d['auth_url'] = os.environ['OS_AUTH_URL']
391 d['project_id'] = os.environ['OS_TENANT_NAME']
395 def download_tests():
396 os.makedirs(VPING_DIR)
398 os.makedirs(BENCH_TESTS_DIR)
400 logger.info("Copying functest.yaml to functest environment...")
402 shutil.copy("./functest.yaml", FUNCTEST_BASE_DIR+"functest.yaml")
404 print "Error copying the file:", sys.exc_info()[0]
407 logger.info("Downloading vPing test...")
408 vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
409 if not download_url(vPing_url,VPING_DIR):
413 logger.info("Downloading Rally bench tests...")
414 run_rally_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/libraries/run_rally.py'
415 if not download_url(run_rally_url,RALLY_TEST_DIR):
418 rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
419 bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
420 for i in bench_tests:
421 rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
422 logger.debug("Downloading %s" %rally_bench_url)
423 if not download_url(rally_bench_url,BENCH_TESTS_DIR):
426 logger.info("Downloading OLD tests...")
427 odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
428 odl_tests = ['create_venv.sh', 'requirements.pip', 'start_tests.sh', 'test_list.txt']
430 odl_url = odl_base_url + i
431 logger.debug("Downloading %s" %odl_url)
432 if not download_url(odl_url,ODL_DIR):
439 def create_private_neutron_net(neutron):
441 neutron.format = 'json'
442 logger.debug('Creating Neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
443 json_body = {'network': {'name': NEUTRON_PRIVATE_NET_NAME,
444 'admin_state_up': True}}
445 netw = neutron.create_network(body=json_body)
446 net_dict = netw['network']
447 network_id = net_dict['id']
448 logger.debug("Network '%s' created successfully" % network_id)
450 logger.debug('Creating Subnet....')
451 json_body = {'subnets': [{'cidr': NEUTRON_PRIVATE_SUBNET_CIDR,
452 'ip_version': 4, 'network_id': network_id}]}
453 subnet = neutron.create_subnet(body=json_body)
454 logger.debug("Subnet '%s' created successfully" % subnet)
456 logger.debug('Creating Router...')
457 json_body = {'router': {'name': ROUTER_NAME, 'admin_state_up': True}}
458 router = neutron.create_router(json_body)
459 logger.debug("Router '%s' created successfully" % router)
460 router_id = router['router']['id']
462 logger.debug('Creating Port')
463 json_body = {'port': {
464 'admin_state_up': True,
465 'device_id': router_id,
467 'network_id': network_id,
469 response = neutron.create_port(body=json_body)
470 logger.debug("Port created successfully.")
473 #No need to set up a gateway if there is no public network
474 logger.debug('Setting up gateway...')
475 public_network_id = get_network_id(neutron,NEUTRON_PUBLIC_NET_NAME)
476 json_body = {'network_id': public_network_id, 'enable_snat' : True}
477 gateway = neutron.add_gateway_router(router_id,body=json_body)
478 logger.debug("Gateway '%s' added successfully" % gateway)
481 print "Error:", sys.exc_info()[0]
484 logger.info("Private Neutron network created successfully.")
487 def get_network_id(neutron, network_name):
488 networks = neutron.list_networks()['networks']
491 if n['name'] == network_name:
496 def check_neutron_net(neutron, net_name):
497 for network in neutron.list_networks()['networks']:
498 if network['name'] == net_name :
499 for subnet in network['subnets']:
503 def delete_neutron_net(neutron):
504 #TODO: remove router, ports
506 #https://github.com/isginf/openstack_tools/blob/master/openstack_remove_tenant.py
507 for network in neutron.list_networks()['networks']:
508 if network['name'] == NEUTRON_PRIVATE_NET_NAME :
509 for subnet in network['subnets']:
510 print "Deleting subnet " + subnet
511 neutron.delete_subnet(subnet)
512 print "Deleting network " + network['name']
513 neutron.delete_neutron_net(network['id'])
522 def create_glance_image(path,name,disk_format):
524 Create a glance image given the absolute path of the image, its name and the disk format
526 cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
534 def download_url(url, dest_path):
536 Download a file to a destination path given a URL
538 name = url.rsplit('/')[-1]
539 dest = dest_path + name
541 response = urllib2.urlopen(url)
542 except (urllib2.HTTPError, urllib2.URLError):
543 logger.error("Error in fetching %s" %url)
546 with open(dest, 'wb') as f:
547 f.write(response.read())
551 def download_url_with_progress(url, dest_path):
553 Download a file to a destination path given a URL showing the progress
555 name = url.rsplit('/')[-1]
556 dest = dest_path + name
558 response = urllib2.urlopen(url)
559 except (urllib2.HTTPError, urllib2.URLError):
560 logger.error("Error in fetching %s" %url)
564 meta = response.info()
565 file_size = int(meta.getheaders("Content-Length")[0])
566 logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
571 buffer = response.read(block_sz)
575 file_size_dl += len(buffer)
577 status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
578 status = status + chr(8)*(len(status)+1)
586 def check_internet_connectivity(url='http://www.google.com/'):
588 Check if there is access to the internet
591 urllib2.urlopen(url, timeout=5)
593 except urllib.request.URLError:
596 def execute_command(cmd):
598 Execute Linux command
600 logger.debug('Executing command : {}'.format(cmd))
601 #p = os.popen(cmd,"r")
602 #logger.debug(p.read())
603 output_file = "/tmp/output.txt"
604 f = open(output_file, 'w+')
605 p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
607 f = open(output_file, 'r')
608 logger.debug(f.read())
609 #p = subprocess.call(cmd,shell=True);
613 logger.error("Error when executing command %s" %cmd)
620 if not (args.action in actions):
621 logger.error('argument not valid')
624 if args.action == "start":
625 config_functest_start()
627 if args.action == "check":
628 if config_functest_check():
629 logger.info("Functest environment correctly installed")
631 logger.info("Functest environment not found or faulty")
633 if args.action == "clean":
635 print("Are you sure? [y|n]")
636 answer = raw_input("")
638 config_functest_clean()
643 print("Invalid option.")
647 if __name__ == '__main__':