config_functest.py : added --force flag to force clean functest without prompting.
[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 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()
22
23
24 """ logging configuration """
25 logger = logging.getLogger('config_functest')
26 logger.setLevel(logging.DEBUG)
27
28 ch = logging.StreamHandler()
29 if args.debug:
30     ch.setLevel(logging.DEBUG)
31 else:
32     ch.setLevel(logging.INFO)
33
34
35 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
36 ch.setFormatter(formatter)
37 logger.addHandler(ch)
38
39
40
41 yaml_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/functest.yaml'
42 name = yaml_url.rsplit('/')[-1]
43 dest = "./" + name
44 if not os.path.exists(dest):
45     logger.info("Downloading functest.yaml...")
46     try:
47         response = urllib2.urlopen(yaml_url)
48     except (urllib2.HTTPError, urllib2.URLError):
49         logger.error("Error in fetching %s" %yaml_url)
50         exit(-1)
51     with open(dest, 'wb') as f:
52         f.write(response.read())
53     logger.info("functest.yaml stored in %s" % dest)
54 else:
55     logger.info("functest.yaml found in %s" % dest)
56
57
58 with open('./functest.yaml') as f:
59     functest_yaml = yaml.safe_load(f)
60 f.close()
61
62
63 """ global variables """
64 # Directories
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
74
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")
80
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
87
88 credentials = None
89 neutron_client = None
90
91 def config_functest_start():
92     """
93     Start the functest environment installation
94     """
95     if not check_internet_connectivity():
96         logger.error("There is no Internet connectivity. Please check the network configuration.")
97         exit(-1)
98
99     if config_functest_check():
100         logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
101         exit(0)
102
103     else:
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()
107
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.")
112             exit(-1)
113
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()
118             exit(-1)
119
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()
124             exit(-1)
125
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()
130             exit(-1)
131
132         credentials = get_credentials()
133         neutron_client = client.Client(**credentials)
134
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)
140         else:
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()
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     credentials = get_credentials()
172     neutron_client = client.Client(**credentials)
173
174     logger.debug("Checking directories...")
175     errors = False
176     dirs = [FUNCTEST_BASE_DIR, RALLY_INSTALLATION_DIR, RALLY_REPO_DIR, RALLY_TEST_DIR, BENCH_TESTS_DIR, VPING_DIR, ODL_DIR]
177     for dir in dirs:
178         if not os.path.exists(dir):
179             logger.debug("The directory '%s' does NOT exist." % dir)
180             errors = True
181             errors_all = True
182         else:
183             logger.debug("   %s found" % dir)
184     if not errors:
185         logger.debug("...OK")
186     else:
187         logger.debug("...FAIL")
188
189
190     logger.debug("Checking Rally deployment...")
191     if not check_rally():
192         logger.debug("   Rally deployment NOT found.")
193         errors_all = True
194         logger.debug("...FAIL")
195     else:
196         logger.debug("...OK")
197
198
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")
203         errors_all = True
204     else:
205         logger.debug("   Private network '%s' found." % NEUTRON_PRIVATE_NET_NAME)
206         logger.debug("...OK")
207
208
209     logger.debug("Checking Image...")
210     errors = False
211     if not os.path.isfile(IMAGE_DOWNLOAD_PATH):
212         logger.debug("   Image file '%s' NOT found." % IMAGE_DOWNLOAD_PATH)
213         errors = True
214         errors_all = True
215     else:
216         logger.debug("   Image file found in %s" % IMAGE_DOWNLOAD_PATH)
217
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()
224     if line == "":
225         logger.debug("   Glance image NOT found.")
226         errors = True
227         errors_all = True
228     else:
229         logger.debug("   Glance image found.")
230
231     if not errors:
232         logger.debug("...OK")
233     else:
234         logger.debug("...FAIL")
235
236     #TODO: check OLD environment setup
237     if errors_all:
238         return False
239     else:
240         return True
241
242
243
244
245 def config_functest_clean():
246     """
247     Clean the existing functest environment
248     """
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)
253
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
257         execute_command(cmd)
258
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.")
262
263     logger.debug("Deleting glance images")
264     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
265     p = os.popen(cmd,"r")
266
267     #while image_id = p.readline()
268     for image_id in p.readlines():
269         cmd = "glance image-delete " + image_id
270         execute_command(cmd)
271
272     return True
273
274
275
276
277
278 def install_rally():
279     if check_rally():
280         logger.info("Rally is already installed.")
281     else:
282         logger.debug("Cloning repository...")
283         url = "https://git.openstack.org/openstack/rally"
284         Repo.clone_from(url, RALLY_REPO_DIR)
285
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
289         execute_command(cmd)
290         #subprocess.call(['sudo', install_script])
291
292         logger.debug("Creating Rally environment...")
293         cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
294         execute_command(cmd)
295
296         logger.debug("Installing tempest...")
297         cmd = "rally-manage tempest install"
298         execute_command(cmd)
299
300         cmd = "rally deployment check"
301         execute_command(cmd)
302         #TODO: check that everything is 'Available' and warn if not
303
304         cmd = "rally show images"
305         execute_command(cmd)
306
307         cmd = "rally show flavors"
308         execute_command(cmd)
309
310     return True
311
312
313
314 def check_rally():
315     """
316     Check if Rally is installed and properly configured
317     """
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()
326         if line == "":
327             logger.debug("   Rally deployment not found")
328             return False
329         logger.debug("   Rally deployment found")
330         return True
331     else:
332         logger.debug("   Rally installation directory not found")
333         return False
334
335
336 def install_odl():
337     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
338     execute_command(cmd)
339     cmd = ODL_DIR + "create_venv.sh"
340     execute_command(cmd)
341     return True
342
343
344 def check_credentials():
345     """
346     Check if the OpenStack credentials (openrc) are sourced
347     """
348     #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
349     try:
350        os.environ['OS_AUTH_URL']
351     except KeyError:
352         return False
353     try:
354        os.environ['OS_USERNAME']
355     except KeyError:
356         return False
357     try:
358        os.environ['OS_PASSWORD']
359     except KeyError:
360         return False
361     try:
362        os.environ['OS_TENANT_NAME']
363     except KeyError:
364         return False
365     try:
366        os.environ['OS_REGION_NAME']
367     except KeyError:
368         return False
369     return True
370
371
372 def get_credentials():
373     d = {}
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']
378     return d
379
380 def get_nova_credentials():
381     d = {}
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']
386     return d
387
388
389 def download_tests():
390     os.makedirs(VPING_DIR)
391     os.makedirs(ODL_DIR)
392     os.makedirs(BENCH_TESTS_DIR)
393
394     logger.info("Copying functest.yaml to functest environment...")
395     try:
396         shutil.copy("./functest.yaml", FUNCTEST_BASE_DIR+"functest.yaml")
397     except:
398         print "Error copying the file:", sys.exc_info()[0]
399         return False
400
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):
404         return False
405
406
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):
410         return False
411
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):
418             return False
419
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']
423     for i in odl_tests:
424         odl_url = odl_base_url + i
425         logger.debug("Downloading %s" %odl_url)
426         if not download_url(odl_url,ODL_DIR):
427             return False
428
429     return True
430
431
432
433 def create_private_neutron_net(neutron):
434     try:
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)
443
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}]}
447
448         subnet = neutron.create_subnet(body=json_body)
449         subnet_id = subnet['subnets'][0]['id']
450         logger.debug("Subnet '%s' created successfully" % subnet_id)
451
452
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)
458
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.")
463
464     except:
465         print "Error:", sys.exc_info()[0]
466         return False
467
468     logger.info("Private Neutron network created successfully.")
469     return True
470
471 def get_network_id(neutron, network_name):
472     networks = neutron.list_networks()['networks']
473     id  = ''
474     for n in networks:
475         if n['name'] == network_name:
476             id = n['id']
477             break
478     return id
479
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']:
484                 return True
485     return False
486
487 def delete_neutron_net(neutron):
488     #TODO: remove router, ports
489     try:
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'])
498     finally:
499         return True
500     return False
501
502
503
504
505
506 def create_glance_image(path,name,disk_format):
507     """
508     Create a glance image given the absolute path of the image, its name and the disk format
509     """
510     cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
511     execute_command(cmd)
512     return True
513
514
515
516
517
518 def download_url(url, dest_path):
519     """
520     Download a file to a destination path given a URL
521     """
522     name = url.rsplit('/')[-1]
523     dest = dest_path + name
524     try:
525         response = urllib2.urlopen(url)
526     except (urllib2.HTTPError, urllib2.URLError):
527         logger.error("Error in fetching %s" %url)
528         return False
529
530     with open(dest, 'wb') as f:
531         f.write(response.read())
532     return True
533
534
535 def download_url_with_progress(url, dest_path):
536     """
537     Download a file to a destination path given a URL showing the progress
538     """
539     name = url.rsplit('/')[-1]
540     dest = dest_path + name
541     try:
542         response = urllib2.urlopen(url)
543     except (urllib2.HTTPError, urllib2.URLError):
544         logger.error("Error in fetching %s" %url)
545         return False
546
547     f = open(dest, 'wb')
548     meta = response.info()
549     file_size = int(meta.getheaders("Content-Length")[0])
550     logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
551
552     file_size_dl = 0
553     block_sz = 8192
554     while True:
555         buffer = response.read(block_sz)
556         if not buffer:
557             break
558
559         file_size_dl += len(buffer)
560         f.write(buffer)
561         status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
562         status = status + chr(8)*(len(status)+1)
563         print status,
564
565     f.close()
566     print("\n")
567     return True
568
569
570 def check_internet_connectivity(url='http://www.google.com/'):
571     """
572     Check if there is access to the internet
573     """
574     try:
575         urllib2.urlopen(url, timeout=5)
576         return True
577     except urllib.request.URLError:
578         return False
579
580 def execute_command(cmd):
581     """
582     Execute Linux command
583     """
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)
590     f.close()
591     f = open(output_file, 'r')
592     logger.debug(f.read())
593     #p = subprocess.call(cmd,shell=True);
594     if p == 0 :
595         return True
596     else:
597         logger.error("Error when executing command %s" %cmd)
598         exit(-1)
599
600
601
602
603 def main():
604     if not (args.action in actions):
605         logger.error('argument not valid')
606         exit(-1)
607
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
611         exit(-1)
612
613     if args.action == "start":
614         config_functest_start()
615
616     if args.action == "check":
617         if config_functest_check():
618             logger.info("Functest environment correctly installed")
619         else:
620             logger.info("Functest environment not found or faulty")
621
622     if args.action == "clean":
623         if args.force :
624             config_functest_clean()
625         else :
626             while True:
627                 print("Are you sure? [y|n]")
628                 answer = raw_input("")
629                 if answer == "y":
630                     config_functest_clean()
631                     break
632                 elif answer == "n":
633                     break
634                 else:
635                     print("Invalid option.")
636     exit(0)
637
638
639 if __name__ == '__main__':
640     main()
641