Added functest.yaml to centralize the common parameters for all scripts of functest
[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 actions = ['start', 'check', 'clean']
15
16 with open('functest.yaml') as f:
17     functest_yaml = yaml.safe_load(f)
18 f.close()
19
20 logger.info("Downloading functest.yaml...")
21 yaml_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/functest.yaml'
22 if not download_url(yaml_url,"./"):
23     logger.error("Unable to download the configuration file functest.yaml")
24     exit(-1)
25
26 """ global variables """
27 HOME = os.environ['HOME']+"/"
28 FUNCTEST_BASE_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_functest")
29 RALLY_REPO_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_repo")
30 RALLY_TEST_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally")
31 RALLY_INSTALLATION_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_inst")
32 BENCH_TESTS_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_scn")
33 VPING_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_vping")
34 ODL_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_odl")
35 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
36 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
37 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
38 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
39 IMAGE_DOWNLOAD_PATH = FUNCTEST_BASE_DIR + IMAGE_FILE_NAME
40
41 parser = argparse.ArgumentParser()
42 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
43 parser.add_argument("-d", "--debug", help="Debug mode",  action="store_true")
44 args = parser.parse_args()
45
46
47 """ logging configuration """
48 logger = logging.getLogger('config_functest')
49 logger.setLevel(logging.DEBUG)
50
51 ch = logging.StreamHandler()
52 if args.debug:
53     ch.setLevel(logging.DEBUG)
54 else:
55     ch.setLevel(logging.INFO)
56
57 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
58 ch.setFormatter(formatter)
59 logger.addHandler(ch)
60
61
62
63 def config_functest_start():
64     """
65     Start the functest environment installation
66     """
67     if config_functest_check():
68         logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
69         exit(0)
70     elif not check_internet_connectivity():
71         logger.error("There is no Internet connectivity. Please check the network configuration.")
72         exit(-1)
73     elif not check_credentials():
74         logger.error("Please source the openrc credentials and run the script again.")
75         #TODO: source the credentials in this script
76         exit(-1)
77     else:
78         config_functest_clean()
79
80         logger.info("Starting installationg of functest environment in %s" %FUNCTEST_BASE_DIR)
81         os.makedirs(FUNCTEST_BASE_DIR)
82         if not os.path.exists(FUNCTEST_BASE_DIR):
83             logger.error("There has been a problem while creating the environment directory.")
84             exit(-1)
85
86         logger.info("Donwloading test scripts and scenarios...")
87         if not download_tests():
88             logger.error("There has been a problem while downloading the test scripts and scenarios.")
89             config_functest_clean()
90             exit(-1)
91
92         logger.info("Installing Rally...")
93         if not install_rally():
94             logger.error("There has been a problem while installing Rally.")
95             config_functest_clean()
96             exit(-1)
97
98         logger.info("Installing ODL environment...")
99         if not install_odl():
100             logger.error("There has been a problem while installing Robot.")
101             config_functest_clean()
102             exit(-1)
103
104         logger.info("Donwloading image...")
105         if not download_url_with_progress(IMAGE_URL, FUNCTEST_BASE_DIR):
106             logger.error("There has been a problem while downloading the image.")
107             config_functest_clean()
108             exit(-1)
109
110         logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
111         if not create_glance_image(IMAGE_DOWNLOAD_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
112             logger.error("There has been a problem while creating the Glance image.")
113             config_functest_clean()
114             exit(-1)
115
116         exit(0)
117
118
119
120 def config_functest_check():
121     """
122     Check if the functest environment is properly installed
123     """
124     logger.info("Checking current functest configuration...")
125
126     logger.debug("Checking directories...")
127     dirs = [FUNCTEST_BASE_DIR, RALLY_INSTALLATION_DIR, RALLY_REPO_DIR, RALLY_TEST_DIR, BENCH_TESTS_DIR, VPING_DIR, ODL_DIR]
128     for dir in dirs:
129         if not os.path.exists(dir):
130             logger.debug("The directory %s does not exist." %dir)
131             return False
132         logger.debug("   %s found" % dir)
133
134     logger.debug("...OK")
135     logger.debug("Checking Rally deployment...")
136     if not check_rally():
137         logger.debug("Rally deployment not found.")
138         return False
139     logger.debug("...OK")
140
141     logger.debug("Checking Image...")
142     if not os.path.isfile(IMAGE_DOWNLOAD_PATH):
143         return False
144     logger.debug("   Image file found in %s" %IMAGE_DOWNLOAD_PATH)
145
146     cmd="glance image-list | grep " + IMAGE_NAME
147     FNULL = open(os.devnull, 'w');
148     logger.debug('   Executing command : {}'.format(cmd))
149     p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
150     #if the command does not exist or there is no glance image
151     line = p.stdout.readline()
152     if line == "":
153         logger.debug("   Glance image not found")
154         return False
155     logger.debug("   Glance image found")
156     logger.debug("...OK")
157
158     #TODO: check OLD environment setup
159
160     return True
161
162
163
164
165 def config_functest_clean():
166     """
167     Clean the existing functest environment
168     """
169     logger.info("Removing current functest environment...")
170     if os.path.exists(RALLY_INSTALLATION_DIR):
171         logger.debug("Removing rally installation directory %s" % RALLY_INSTALLATION_DIR)
172         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
173
174     if os.path.exists(FUNCTEST_BASE_DIR):
175         logger.debug("Removing functest directory %s" % FUNCTEST_BASE_DIR)
176         cmd = "sudo rm -rf " + FUNCTEST_BASE_DIR #need to be sudo, not possible with rmtree
177         execute_command(cmd)
178
179     logger.debug("Deleting glance images")
180     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
181     p = os.popen(cmd,"r")
182
183     #while image_id = p.readline()
184     for image_id in p.readlines():
185         cmd = "glance image-delete " + image_id
186         execute_command(cmd)
187
188     return True
189
190
191 def install_rally():
192     if check_rally():
193         logger.info("Rally is already installed.")
194     else:
195         logger.debug("Cloning repository...")
196         url = "https://git.openstack.org/openstack/rally"
197         Repo.clone_from(url, RALLY_REPO_DIR)
198
199         logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
200         install_script = RALLY_REPO_DIR + "install_rally.sh"
201         cmd = 'sudo ' + install_script
202         execute_command(cmd)
203         #subprocess.call(['sudo', install_script])
204
205         logger.debug("Creating Rally environment...")
206         cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
207         execute_command(cmd)
208
209         logger.debug("Installing tempest...")
210         cmd = "rally-manage tempest install"
211         execute_command(cmd)
212
213         cmd = "rally deployment check"
214         execute_command(cmd)
215         #TODO: check that everything is 'Available' and warn if not
216
217         cmd = "rally show images"
218         execute_command(cmd)
219
220         cmd = "rally show flavors"
221         execute_command(cmd)
222
223     return True
224
225
226
227 def check_rally():
228     """
229     Check if Rally is installed and properly configured
230     """
231     if os.path.exists(RALLY_INSTALLATION_DIR):
232         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
233         FNULL = open(os.devnull, 'w');
234         cmd="rally deployment list | grep opnfv";
235         logger.debug('   Executing command : {}'.format(cmd))
236         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
237         #if the command does not exist or there is no deployment
238         line = p.stdout.readline()
239         if line == "":
240             logger.debug("   Rally deployment not found")
241             return False
242         logger.debug("   Rally deployment found")
243         return True
244     else:
245         logger.debug("   Rally installation directory not found")
246         return False
247
248
249 def install_odl():
250     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
251     execute_command(cmd)
252     cmd = ODL_DIR + "create_venv.sh"
253     execute_command(cmd)
254     return True
255
256
257 def check_credentials():
258     """
259     Check if the OpenStack credentials (openrc) are sourced
260     """
261     #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
262     try:
263        os.environ['OS_AUTH_URL']
264     except KeyError:
265         return False
266     try:
267        os.environ['OS_USERNAME']
268     except KeyError:
269         return False
270     try:
271        os.environ['OS_PASSWORD']
272     except KeyError:
273         return False
274     try:
275        os.environ['OS_TENANT_NAME']
276     except KeyError:
277         return False
278     try:
279        os.environ['OS_REGION_NAME']
280     except KeyError:
281         return False
282     return True
283
284
285 def download_tests():
286     os.makedirs(VPING_DIR)
287     os.makedirs(ODL_DIR)
288     os.makedirs(BENCH_TESTS_DIR)
289
290     logger.info("Downloading functest.yaml...")
291     yaml_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/functest.yaml'
292     if not download_url(yaml_url,FUNCTEST_BASE_DIR):
293         logger.error("Unable to download the configuration file functest.yaml")
294         return False
295
296     logger.info("Downloading vPing test...")
297     vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
298     if not download_url(vPing_url,VPING_DIR):
299         return False
300
301
302     logger.info("Downloading Rally bench tests...")
303     run_rally_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/libraries/run_rally.py'
304     if not download_url(run_rally_url,RALLY_TEST_DIR):
305         return False
306
307     rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
308     bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
309     for i in bench_tests:
310         rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
311         logger.debug("Downloading %s" %rally_bench_url)
312         if not download_url(rally_bench_url,BENCH_TESTS_DIR):
313             return False
314
315     logger.info("Downloading OLD tests...")
316     odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
317     odl_tests = ['create_venv.sh', 'requirements.pip', 'start_tests.sh', 'test_list.txt']
318     for i in odl_tests:
319         odl_url = odl_base_url + i
320         logger.debug("Downloading %s" %odl_url)
321         if not download_url(odl_url,ODL_DIR):
322             return False
323
324     return True
325
326
327
328 def create_glance_image(path,name,disk_format):
329     """
330     Create a glance image given the absolute path of the image, its name and the disk format
331     """
332     cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
333     execute_command(cmd)
334     return True
335
336
337 def download_url(url, dest_path):
338     """
339     Download a file to a destination path given a URL
340     """
341     name = url.rsplit('/')[-1]
342     dest = dest_path + name
343     try:
344         response = urllib2.urlopen(url)
345     except (urllib2.HTTPError, urllib2.URLError):
346         logger.error("Error in fetching %s" %url)
347         return False
348
349     with open(dest, 'wb') as f:
350         f.write(response.read())
351     return True
352
353
354 def download_url_with_progress(url, dest_path):
355     """
356     Download a file to a destination path given a URL showing the progress
357     """
358     name = url.rsplit('/')[-1]
359     dest = dest_path + name
360     try:
361         response = urllib2.urlopen(url)
362     except (urllib2.HTTPError, urllib2.URLError):
363         logger.error("Error in fetching %s" %url)
364         return False
365
366     f = open(dest, 'wb')
367     meta = response.info()
368     file_size = int(meta.getheaders("Content-Length")[0])
369     logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
370
371     file_size_dl = 0
372     block_sz = 8192
373     while True:
374         buffer = response.read(block_sz)
375         if not buffer:
376             break
377
378         file_size_dl += len(buffer)
379         f.write(buffer)
380         status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
381         status = status + chr(8)*(len(status)+1)
382         print status,
383
384     f.close()
385     print("\n")
386     return True
387
388
389 def check_internet_connectivity(url='http://www.google.com/'):
390     """
391     Check if there is access to the internet
392     """
393     try:
394         urllib2.urlopen(url, timeout=5)
395         return True
396     except urllib.request.URLError:
397         return False
398
399 def execute_command(cmd):
400     """
401     Execute Linux command
402     """
403     logger.debug('Executing command : {}'.format(cmd))
404     #p = os.popen(cmd,"r")
405     #logger.debug(p.read())
406     output_file = "/tmp/output.txt"
407     f = open(output_file, 'w+')
408     p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
409     f.close()
410     f = open(output_file, 'r')
411     logger.debug(f.read())
412     #p = subprocess.call(cmd,shell=True);
413     if p == 0 :
414         return True
415     else:
416         logger.error("Error when executing command %s" %cmd)
417         exit(-1)
418
419
420
421
422 def main():
423     if not (args.action in actions):
424         logger.error('argument not valid')
425         exit(-1)
426
427     if args.action == "start":
428         config_functest_start()
429
430     if args.action == "check":
431         if config_functest_check():
432             logger.info("Functest environment correctly installed")
433         else:
434             logger.info("Functest environment not found or faulty")
435
436     if args.action == "clean":
437         while True:
438             print("Are you sure? [y|n]")
439             answer = raw_input("")
440             if answer == "y":
441                 config_functest_clean()
442                 break
443             elif answer == "n":
444                 break
445             else:
446                 print("Invalid option.")
447     exit(0)
448
449
450 if __name__ == '__main__':
451     main()
452