Merge "vPing.py : changed #cloud-config to inject an sh script functest.yaml : vPing...
[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 # Directories
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")
74
75
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")
81
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
88
89 credentials = None
90 neutron_client = None
91
92 def config_functest_start():
93     """
94     Start the functest environment installation
95     """
96
97     if config_functest_check():
98         logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
99         exit(0)
100
101     if not check_internet_connectivity():
102         logger.error("There is no Internet connectivity. Please check the network configuration.")
103         exit(-1)
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
107         exit(-1)
108
109     else:
110         # Clean in case there are left overs
111
112         config_functest_clean()
113
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.")
118             exit(-1)
119
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()
124             exit(-1)
125
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()
130             exit(-1)
131
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()
136             exit(-1)
137
138         credentials = get_credentials()
139         neutron_client = client.Client(**credentials)
140
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)
146         else:
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()
151                 exit(-1)
152
153
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()
158             exit(-1)
159
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()
164             exit(-1)
165
166         exit(0)
167
168
169
170 def config_functest_check():
171     """
172     Check if the functest environment is properly installed
173     """
174     errors_all = False
175
176     logger.info("Checking current functest configuration...")
177     credentials = get_credentials()
178     neutron_client = client.Client(**credentials)
179
180     logger.debug("Checking directories...")
181     errors = False
182     dirs = [FUNCTEST_BASE_DIR, RALLY_INSTALLATION_DIR, RALLY_REPO_DIR, RALLY_TEST_DIR, BENCH_TESTS_DIR, VPING_DIR, ODL_DIR]
183     for dir in dirs:
184         if not os.path.exists(dir):
185             logger.debug("The directory '%s' does NOT exist." % dir)
186             errors = True
187             errors_all = True
188         else:
189             logger.debug("   %s found" % dir)
190     if not errors:
191         logger.debug("...OK")
192     else:
193         logger.debug("...FAIL")
194
195
196     logger.debug("Checking Rally deployment...")
197     if not check_rally():
198         logger.debug("   Rally deployment NOT found.")
199         errors_all = True
200         logger.debug("...FAIL")
201     else:
202         logger.debug("...OK")
203
204
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")
209         errors_all = True
210     else:
211         logger.debug("   Private network '%s' found." % NEUTRON_PRIVATE_NET_NAME)
212         logger.debug("...OK")
213
214
215     logger.debug("Checking Image...")
216     errors = False
217     if not os.path.isfile(IMAGE_DOWNLOAD_PATH):
218         logger.debug("   Image file '%s' NOT found." % IMAGE_DOWNLOAD_PATH)
219         errors = True
220         errors_all = True
221     else:
222         logger.debug("   Image file found in %s" % IMAGE_DOWNLOAD_PATH)
223
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()
230     if line == "":
231         logger.debug("   Glance image NOT found.")
232         errors = True
233         errors_all = True
234     else:
235         logger.debug("   Glance image found.")
236
237     if not errors:
238         logger.debug("...OK")
239     else:
240         logger.debug("...FAIL")
241
242     #TODO: check OLD environment setup
243     if errors_all:
244         return False
245     else:
246         return True
247
248
249
250
251 def config_functest_clean():
252     """
253     Clean the existing functest environment
254     """
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)
259
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
263         execute_command(cmd)
264
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.")
268
269     logger.debug("Deleting glance images")
270     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
271     p = os.popen(cmd,"r")
272
273     #while image_id = p.readline()
274     for image_id in p.readlines():
275         cmd = "glance image-delete " + image_id
276         execute_command(cmd)
277
278     return True
279
280
281
282
283
284 def install_rally():
285     if check_rally():
286         logger.info("Rally is already installed.")
287     else:
288         logger.debug("Cloning repository...")
289         url = "https://git.openstack.org/openstack/rally"
290         Repo.clone_from(url, RALLY_REPO_DIR)
291
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
295         execute_command(cmd)
296         #subprocess.call(['sudo', install_script])
297
298         logger.debug("Creating Rally environment...")
299         cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
300         execute_command(cmd)
301
302         logger.debug("Installing tempest...")
303         cmd = "rally-manage tempest install"
304         execute_command(cmd)
305
306         cmd = "rally deployment check"
307         execute_command(cmd)
308         #TODO: check that everything is 'Available' and warn if not
309
310         cmd = "rally show images"
311         execute_command(cmd)
312
313         cmd = "rally show flavors"
314         execute_command(cmd)
315
316     return True
317
318
319
320 def check_rally():
321     """
322     Check if Rally is installed and properly configured
323     """
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()
332         if line == "":
333             logger.debug("   Rally deployment not found")
334             return False
335         logger.debug("   Rally deployment found")
336         return True
337     else:
338         logger.debug("   Rally installation directory not found")
339         return False
340
341
342 def install_odl():
343     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
344     execute_command(cmd)
345     cmd = ODL_DIR + "create_venv.sh"
346     execute_command(cmd)
347     return True
348
349
350 def check_credentials():
351     """
352     Check if the OpenStack credentials (openrc) are sourced
353     """
354     #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
355     try:
356        os.environ['OS_AUTH_URL']
357     except KeyError:
358         return False
359     try:
360        os.environ['OS_USERNAME']
361     except KeyError:
362         return False
363     try:
364        os.environ['OS_PASSWORD']
365     except KeyError:
366         return False
367     try:
368        os.environ['OS_TENANT_NAME']
369     except KeyError:
370         return False
371     try:
372        os.environ['OS_REGION_NAME']
373     except KeyError:
374         return False
375     return True
376
377
378 def get_credentials():
379     d = {}
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']
384     return d
385
386 def get_nova_credentials():
387     d = {}
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']
392     return d
393
394
395 def download_tests():
396     os.makedirs(VPING_DIR)
397     os.makedirs(ODL_DIR)
398     os.makedirs(BENCH_TESTS_DIR)
399
400     logger.info("Copying functest.yaml to functest environment...")
401     try:
402         shutil.copy("./functest.yaml", FUNCTEST_BASE_DIR+"functest.yaml")
403     except:
404         print "Error copying the file:", sys.exc_info()[0]
405         return False
406
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):
410         return False
411
412
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):
416         return False
417
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):
424             return False
425
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']
429     for i in odl_tests:
430         odl_url = odl_base_url + i
431         logger.debug("Downloading %s" %odl_url)
432         if not download_url(odl_url,ODL_DIR):
433             return False
434
435     return True
436
437
438
439 def create_private_neutron_net(neutron):
440     try:
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)
449
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)
455
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']
461
462         logger.debug('Creating Port')
463         json_body = {'port': {
464          'admin_state_up': True,
465          'device_id': router_id,
466          'name': 'port1',
467          'network_id': network_id,
468         }}
469         response = neutron.create_port(body=json_body)
470         logger.debug("Port created successfully.")
471
472         """
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)
479         """
480     except:
481         print "Error:", sys.exc_info()[0]
482         return False
483
484     logger.info("Private Neutron network created successfully.")
485     return True
486
487 def get_network_id(neutron, network_name):
488     networks = neutron.list_networks()['networks']
489     id  = ''
490     for n in networks:
491         if n['name'] == network_name:
492             id = n['id']
493             break
494     return id
495
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']:
500                 return True
501     return False
502
503 def delete_neutron_net(neutron):
504     #TODO: remove router, ports
505     try:
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'])
514     finally:
515         return True
516     return False
517
518
519
520
521
522 def create_glance_image(path,name,disk_format):
523     """
524     Create a glance image given the absolute path of the image, its name and the disk format
525     """
526     cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
527     execute_command(cmd)
528     return True
529
530
531
532
533
534 def download_url(url, dest_path):
535     """
536     Download a file to a destination path given a URL
537     """
538     name = url.rsplit('/')[-1]
539     dest = dest_path + name
540     try:
541         response = urllib2.urlopen(url)
542     except (urllib2.HTTPError, urllib2.URLError):
543         logger.error("Error in fetching %s" %url)
544         return False
545
546     with open(dest, 'wb') as f:
547         f.write(response.read())
548     return True
549
550
551 def download_url_with_progress(url, dest_path):
552     """
553     Download a file to a destination path given a URL showing the progress
554     """
555     name = url.rsplit('/')[-1]
556     dest = dest_path + name
557     try:
558         response = urllib2.urlopen(url)
559     except (urllib2.HTTPError, urllib2.URLError):
560         logger.error("Error in fetching %s" %url)
561         return False
562
563     f = open(dest, 'wb')
564     meta = response.info()
565     file_size = int(meta.getheaders("Content-Length")[0])
566     logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
567
568     file_size_dl = 0
569     block_sz = 8192
570     while True:
571         buffer = response.read(block_sz)
572         if not buffer:
573             break
574
575         file_size_dl += len(buffer)
576         f.write(buffer)
577         status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
578         status = status + chr(8)*(len(status)+1)
579         print status,
580
581     f.close()
582     print("\n")
583     return True
584
585
586 def check_internet_connectivity(url='http://www.google.com/'):
587     """
588     Check if there is access to the internet
589     """
590     try:
591         urllib2.urlopen(url, timeout=5)
592         return True
593     except urllib.request.URLError:
594         return False
595
596 def execute_command(cmd):
597     """
598     Execute Linux command
599     """
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)
606     f.close()
607     f = open(output_file, 'r')
608     logger.debug(f.read())
609     #p = subprocess.call(cmd,shell=True);
610     if p == 0 :
611         return True
612     else:
613         logger.error("Error when executing command %s" %cmd)
614         exit(-1)
615
616
617
618
619 def main():
620     if not (args.action in actions):
621         logger.error('argument not valid')
622         exit(-1)
623
624     if args.action == "start":
625         config_functest_start()
626
627     if args.action == "check":
628         if config_functest_check():
629             logger.info("Functest environment correctly installed")
630         else:
631             logger.info("Functest environment not found or faulty")
632
633     if args.action == "clean":
634         while True:
635             print("Are you sure? [y|n]")
636             answer = raw_input("")
637             if answer == "y":
638                 config_functest_clean()
639                 break
640             elif answer == "n":
641                 break
642             else:
643                 print("Invalid option.")
644     exit(0)
645
646
647 if __name__ == '__main__':
648     main()
649