config_functest.py: added create neutron network.
[functest.git] / testcases / config_functest.py
1 #!/usr/bin/env python
2 #
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
9 #
10
11 import re, json, os, urllib2, argparse, logging, shutil, subprocess, yaml
12 from git import Repo
13
14 from neutronclient.v2_0 import client
15
16 actions = ['start', 'check', 'clean']
17
18
19
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()
24
25
26 """ logging configuration """
27 logger = logging.getLogger('config_functest')
28 logger.setLevel(logging.DEBUG)
29
30 ch = logging.StreamHandler()
31 if args.debug:
32     ch.setLevel(logging.DEBUG)
33 else:
34     ch.setLevel(logging.INFO)
35
36 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
37 ch.setFormatter(formatter)
38 logger.addHandler(ch)
39
40
41
42 yaml_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/functest.yaml'
43 name = yaml_url.rsplit('/')[-1]
44 dest = "./" + name
45 if not os.path.exists(dest):
46     logger.info("Downloading functest.yaml...")
47     try:
48         response = urllib2.urlopen(yaml_url)
49     except (urllib2.HTTPError, urllib2.URLError):
50         logger.error("Error in fetching %s" %yaml_url)
51         exit(-1)
52     with open(dest, 'wb') as f:
53         f.write(response.read())
54     logger.info("functest.yaml stored in %s" % dest)
55 else:
56     logger.info("functest.yaml found in %s" % dest)
57
58
59 with open('./functest.yaml') as f:
60     functest_yaml = yaml.safe_load(f)
61 f.close()
62
63
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")
78
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
84
85
86 def config_functest_start():
87     """
88     Start the functest environment installation
89     """
90     #if config_functest_check():
91     #    logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
92     #    exit(0)
93     if not check_internet_connectivity():
94         logger.error("There is no Internet connectivity. Please check the network configuration.")
95         exit(-1)
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
99         exit(-1)
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
105         exit(-1)
106     else:
107         # Clean in case there are left overs
108         config_functest_clean()
109
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.")
114             exit(-1)
115
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()
120             exit(-1)
121
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()
126             exit(-1)
127
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()
132             exit(-1)
133
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)
140         else:
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()
145                 exit(-1)
146
147
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()
152             exit(-1)
153
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()
158             exit(-1)
159
160         exit(0)
161
162
163
164 def config_functest_check():
165     """
166     Check if the functest environment is properly installed
167     """
168     errors_all = False
169
170     logger.info("Checking current functest configuration...")
171
172
173     logger.debug("Checking directories...")
174     errors = False
175     dirs = [FUNCTEST_BASE_DIR, RALLY_INSTALLATION_DIR, RALLY_REPO_DIR, RALLY_TEST_DIR, BENCH_TESTS_DIR, VPING_DIR, ODL_DIR]
176     for dir in dirs:
177         if not os.path.exists(dir):
178             logger.debug("The directory '%s' does NOT exist." % dir)
179             errors = True
180             errors_all = True
181         else:
182             logger.debug("   %s found" % dir)
183     if not errors:
184         logger.debug("...OK")
185     else:
186         logger.debug("...FAIL")
187
188
189     logger.debug("Checking Rally deployment...")
190     if not check_rally():
191         logger.debug("Rally deployment NOT found.")
192         errors_all = True
193         logger.debug("...FAIL")
194     else:
195         logger.debug("...OK")
196
197
198     logger.debug("Checking Neutron...")
199     errors = False
200     if not check_neutron_net(NEUTRON_NET_NAME):
201         logger.debug("   Private network '%s' NOT found." % NEUTRON_NET_NAME)
202         errors = True
203         errors_all = True
204     else:
205         logger.debug("   Private network '%s' found." % NEUTRON_NET_NAME)
206
207     if not check_neutron_net(NEUTRON_PUBLIC_NAME):
208         logger.debug("   Public network '%s' NOT found." % NEUTRON_PUBLIC_NAME)
209         errors = True
210         errors_all = True
211     else:
212         logger.debug("   Public network '%s' found." % NEUTRON_PUBLIC_NAME)
213
214     if not errors:
215         logger.debug("...OK")
216     else:
217         logger.debug("...FAIL")
218
219
220     logger.debug("Checking Image...")
221     errors = False
222     if not os.path.isfile(IMAGE_DOWNLOAD_PATH):
223         logger.debug("   Image file '%s' NOT found." % IMAGE_DOWNLOAD_PATH)
224         errors = True
225         errors_all = True
226     else:
227         logger.debug("   Image file found in %s" % IMAGE_DOWNLOAD_PATH)
228
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()
235     if line == "":
236         logger.debug("   Glance image NOT found.")
237         errors = True
238         errors_all = True
239     else:
240         logger.debug("   Glance image found.")
241
242     if not errors:
243         logger.debug("...OK")
244     else:
245         logger.debug("...FAIL")
246
247     #TODO: check OLD environment setup
248     if errors_all:
249         return False
250     else:
251         return True
252
253
254
255
256 def config_functest_clean():
257     """
258     Clean the existing functest environment
259     """
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)
264
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
268         execute_command(cmd)
269
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.")
273
274     logger.debug("Deleting glance images")
275     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
276     p = os.popen(cmd,"r")
277
278     #while image_id = p.readline()
279     for image_id in p.readlines():
280         cmd = "glance image-delete " + image_id
281         execute_command(cmd)
282
283     return True
284
285
286
287
288
289 def install_rally():
290     if check_rally():
291         logger.info("Rally is already installed.")
292     else:
293         logger.debug("Cloning repository...")
294         url = "https://git.openstack.org/openstack/rally"
295         Repo.clone_from(url, RALLY_REPO_DIR)
296
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
300         execute_command(cmd)
301         #subprocess.call(['sudo', install_script])
302
303         logger.debug("Creating Rally environment...")
304         cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
305         execute_command(cmd)
306
307         logger.debug("Installing tempest...")
308         cmd = "rally-manage tempest install"
309         execute_command(cmd)
310
311         cmd = "rally deployment check"
312         execute_command(cmd)
313         #TODO: check that everything is 'Available' and warn if not
314
315         cmd = "rally show images"
316         execute_command(cmd)
317
318         cmd = "rally show flavors"
319         execute_command(cmd)
320
321     return True
322
323
324
325 def check_rally():
326     """
327     Check if Rally is installed and properly configured
328     """
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()
337         if line == "":
338             logger.debug("   Rally deployment not found")
339             return False
340         logger.debug("   Rally deployment found")
341         return True
342     else:
343         logger.debug("   Rally installation directory not found")
344         return False
345
346
347 def install_odl():
348     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
349     execute_command(cmd)
350     cmd = ODL_DIR + "create_venv.sh"
351     execute_command(cmd)
352     return True
353
354
355 def check_credentials():
356     """
357     Check if the OpenStack credentials (openrc) are sourced
358     """
359     #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
360     try:
361        os.environ['OS_AUTH_URL']
362     except KeyError:
363         return False
364     try:
365        os.environ['OS_USERNAME']
366     except KeyError:
367         return False
368     try:
369        os.environ['OS_PASSWORD']
370     except KeyError:
371         return False
372     try:
373        os.environ['OS_TENANT_NAME']
374     except KeyError:
375         return False
376     try:
377        os.environ['OS_REGION_NAME']
378     except KeyError:
379         return False
380     return True
381
382
383 def get_credentials():
384     d = {}
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']
389     return d
390
391 def get_nova_credentials():
392     d = {}
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']
397     return d
398
399
400 def download_tests():
401     os.makedirs(VPING_DIR)
402     os.makedirs(ODL_DIR)
403     os.makedirs(BENCH_TESTS_DIR)
404
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")
409         return False
410
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):
414         return False
415
416
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):
420         return False
421
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):
428             return False
429
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']
433     for i in odl_tests:
434         odl_url = odl_base_url + i
435         logger.debug("Downloading %s" %odl_url)
436         if not download_url(odl_url,ODL_DIR):
437             return False
438
439     return True
440
441
442 def create_neutron_net():
443     credentials = get_credentials()
444     neutron = client.Client(**credentials)
445     try:
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)
454
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)
460
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']
466
467         logger.debug('Creating Port')
468         json_body = {'port': {
469          'admin_state_up': True,
470          'device_id': router_id,
471          'name': 'port1',
472          'network_id': network_id,
473         }}
474         response = neutron.create_port(body=json_body)
475         logger.debug("Port created successfully.")
476
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)
482     except:
483         logger.error("There has been a problem when creating the Neutron network.")
484         return False
485     finally:
486         logger.info("Neutron network created successfully.")
487         return True
488
489     return False
490
491 def get_network_id(neutron_client, network_name):
492     networks = neutron_client.list_networks()['networks']
493     id  = ''
494     for n in networks:
495         if n['name'] == network_name:
496             id = n['id']
497             break
498     return id
499
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']:
506                 return True
507     return False
508
509 def delete_neutron_net():
510     #TODO: remove router, ports
511     credentials = get_credentials()
512     neutron = client.Client(**credentials)
513     try:
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'])
522     finally:
523         return True
524     return False
525
526
527
528
529
530 def create_glance_image(path,name,disk_format):
531     """
532     Create a glance image given the absolute path of the image, its name and the disk format
533     """
534     cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
535     execute_command(cmd)
536     return True
537
538
539
540
541
542 def download_url(url, dest_path):
543     """
544     Download a file to a destination path given a URL
545     """
546     name = url.rsplit('/')[-1]
547     dest = dest_path + name
548     try:
549         response = urllib2.urlopen(url)
550     except (urllib2.HTTPError, urllib2.URLError):
551         logger.error("Error in fetching %s" %url)
552         return False
553
554     with open(dest, 'wb') as f:
555         f.write(response.read())
556     return True
557
558
559 def download_url_with_progress(url, dest_path):
560     """
561     Download a file to a destination path given a URL showing the progress
562     """
563     name = url.rsplit('/')[-1]
564     dest = dest_path + name
565     try:
566         response = urllib2.urlopen(url)
567     except (urllib2.HTTPError, urllib2.URLError):
568         logger.error("Error in fetching %s" %url)
569         return False
570
571     f = open(dest, 'wb')
572     meta = response.info()
573     file_size = int(meta.getheaders("Content-Length")[0])
574     logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
575
576     file_size_dl = 0
577     block_sz = 8192
578     while True:
579         buffer = response.read(block_sz)
580         if not buffer:
581             break
582
583         file_size_dl += len(buffer)
584         f.write(buffer)
585         status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
586         status = status + chr(8)*(len(status)+1)
587         print status,
588
589     f.close()
590     print("\n")
591     return True
592
593
594 def check_internet_connectivity(url='http://www.google.com/'):
595     """
596     Check if there is access to the internet
597     """
598     try:
599         urllib2.urlopen(url, timeout=5)
600         return True
601     except urllib.request.URLError:
602         return False
603
604 def execute_command(cmd):
605     """
606     Execute Linux command
607     """
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)
614     f.close()
615     f = open(output_file, 'r')
616     logger.debug(f.read())
617     #p = subprocess.call(cmd,shell=True);
618     if p == 0 :
619         return True
620     else:
621         logger.error("Error when executing command %s" %cmd)
622         exit(-1)
623
624
625
626
627 def main():
628     if not (args.action in actions):
629         logger.error('argument not valid')
630         exit(-1)
631
632     if args.action == "start":
633         config_functest_start()
634
635     if args.action == "check":
636         if config_functest_check():
637             logger.info("Functest environment correctly installed")
638         else:
639             logger.info("Functest environment not found or faulty")
640
641     if args.action == "clean":
642         while True:
643             print("Are you sure? [y|n]")
644             answer = raw_input("")
645             if answer == "y":
646                 config_functest_clean()
647                 break
648             elif answer == "n":
649                 break
650             else:
651                 print("Invalid option.")
652     exit(0)
653
654
655 if __name__ == '__main__':
656     main()
657