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
14 actions = ['start', 'check', 'clean']
16 """ global variables """
17 functest_dir = os.environ['HOME'] + '/.functest/'
18 image_url = 'https://cloud-images.ubuntu.com/trusty/current/trusty-server-cloudimg-amd64-disk1.img'
19 #image_url = 'http://download.cirros-cloud.net/0.3.0/cirros-0.3.0-i386-disk.img'
20 image_disk_format = 'raw'
21 image_name = image_url.rsplit('/')[-1]
22 image_path = functest_dir + image_name
23 rally_repo_dir = functest_dir + "Rally_repo/"
24 rally_test_dir = functest_dir + "Rally_test/"
25 rally_installation_dir = os.environ['HOME'] + "/.rally"
29 parser = argparse.ArgumentParser()
30 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
31 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
32 args = parser.parse_args()
35 """ logging configuration """
36 logger = logging.getLogger('config_functest')
37 logger.setLevel(logging.DEBUG)
39 ch = logging.StreamHandler()
41 ch.setLevel(logging.DEBUG)
43 ch.setLevel(logging.INFO)
45 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
46 ch.setFormatter(formatter)
51 def config_functest_start():
53 Start the functest environment installation
55 if config_functest_check():
56 logger.info("Functest environment already installed in %s. Nothing to do." %functest_dir)
58 elif not check_internet_connectivity():
59 logger.error("There is no Internet connectivity. Please check the network configuration.")
61 elif not check_credentials():
62 logger.error("Please source the openrc credentials and run the script again.")
63 #TODO: source the credentials in this script
66 config_functest_clean()
68 logger.info("Starting installationg of functest environment in %s" %functest_dir)
69 os.makedirs(functest_dir)
70 if not os.path.exists(functest_dir):
71 logger.error("There has been a problem while creating the environment directory.")
75 logger.info("Installing Rally...")
76 if not install_rally():
77 logger.error("There has been a problem while installing Rally.")
78 config_functest_clean()
81 logger.info("Installing Robot...")
82 if not install_robot():
83 logger.error("There has been a problem while installing Robot.")
84 config_functest_clean()
87 logger.info("Donwloading test scripts and scenarios...")
88 if not download_tests():
89 logger.error("There has been a problem while downloading the test scripts and scenarios.")
90 config_functest_clean()
93 logger.info("Donwloading image...")
94 if not download_url_with_progress(image_url, functest_dir):
95 logger.error("There has been a problem while downloading the image.")
96 config_functest_clean()
99 logger.info("Creating Glance image: %s ..." %image_name)
100 if not create_glance_image(image_path,image_name,image_disk_format):
101 logger.error("There has been a problem while creating the Glance image.")
102 config_functest_clean()
109 def config_functest_check():
111 Check if the functest environment is installed
113 logger.info("Checking current functest configuration...")
114 if os.path.exists(functest_dir) and os.path.exists(rally_installation_dir):
115 logger.info("Functest environment directory found in %s" %functest_dir)
118 logger.info("Functest environment directory not found")
123 def config_functest_clean():
125 Clean the existing functest environment
127 logger.info("Removing current functest environment...")
128 if os.path.exists(rally_installation_dir):
129 logger.debug("Removing rally installation directory %s" % rally_installation_dir)
130 shutil.rmtree(rally_installation_dir,ignore_errors=True)
132 if os.path.exists(functest_dir):
133 logger.debug("Removing functest directory %s" % functest_dir)
134 cmd = "sudo rm -rf " + functest_dir #need to be sudo, not possible with rmtree
137 logger.debug("Deleting glance images")
138 cmd = "glance image-list | grep "+image_name+" | cut -c3-38"
139 p = os.popen(cmd,"r")
141 #while image_id = p.readline()
142 for image_id in p.readlines():
143 cmd = "glance image-delete " + image_id
151 logger.info("Rally is already installed.")
153 logger.debug("Cloning repository...")
154 url = "https://git.openstack.org/openstack/rally"
155 Repo.clone_from(url, rally_repo_dir)
157 logger.debug("Executing %s./install_rally.sh..." %rally_repo_dir)
158 install_script = rally_repo_dir + "install_rally.sh"
159 cmd = 'sudo ' + install_script
161 #subprocess.call(['sudo', install_script])
163 logger.debug("Creating Rally environment...")
164 cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
167 logger.debug("Installing tempest...")
168 cmd = "rally-manage tempest install"
171 cmd = "rally deployment check"
173 #TODO: check that everything is 'Available' and warn if not
175 cmd = "rally show images"
178 cmd = "rally show flavors"
187 Check if Rally is installed and properly configured
189 if os.path.exists(os.environ['HOME']+"/.rally/"):
190 #TODO: do a more consistent check, for example running the comand rally deployment check
197 cmd = "sudo pip install requests"
199 cmd = "sudo pip install robotframework"
201 cmd = "sudo pip install robotframework-sshlibrary"
203 cmd = "sudo pip install robotframework-requests"
205 #cmd = "mkvirtualenv robot"
206 #execute_command(cmd)
210 def check_credentials():
212 Check if the OpenStack credentials (openrc) are sourced
214 #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
216 os.environ['OS_AUTH_URL']
220 os.environ['OS_USERNAME']
224 os.environ['OS_PASSWORD']
228 os.environ['OS_TENANT_NAME']
232 os.environ['OS_REGION_NAME']
238 def download_tests():
239 vPing_dir = functest_dir + "vPing/"
240 odl_dir = functest_dir + "ODL/"
241 bench_tests_dir = rally_test_dir + "scenarios/"
243 os.makedirs(vPing_dir)
245 os.makedirs(bench_tests_dir)
247 logger.info("Downloading vPing test...")
248 vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
249 if not download_url(vPing_url,vPing_dir):
252 vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
253 if not download_url(vPing_url,vPing_dir):
256 logger.info("Downloading Rally bench tests...")
257 run_rally_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/libraries/run_rally.py'
258 if not download_url(run_rally_url,rally_test_dir ):
261 rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
262 bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
263 for i in bench_tests:
264 rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
265 logger.debug("Downloading %s" %rally_bench_url)
266 if not download_url(rally_bench_url,bench_tests_dir):
269 logger.info("Downloading OLD tests...")
270 odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
271 odl_tests = ['start_tests.sh', 'test_list.txt']
273 odl_url = odl_base_url + i
274 logger.debug("Downloading %s" %odl_url)
275 if not download_url(odl_url,odl_dir):
283 def create_glance_image(path,name,disk_format):
285 Create a glance image given the absolute path of the image, its name and the disk format
287 cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
292 def download_url(url, dest_path):
294 Download a file to a destination path given a URL
296 name = url.rsplit('/')[-1]
297 dest = dest_path + name
299 response = urllib2.urlopen(url)
300 except (urllib2.HTTPError, urllib2.URLError):
301 logger.error("Error in fetching %s" %url)
304 with open(dest, 'wb') as f:
305 f.write(response.read())
309 def download_url_with_progress(url, dest_path):
311 Download a file to a destination path given a URL showing the progress
313 name = url.rsplit('/')[-1]
314 dest = dest_path + name
316 response = urllib2.urlopen(url)
317 except (urllib2.HTTPError, urllib2.URLError):
318 logger.error("Error in fetching %s" %url)
322 meta = response.info()
323 file_size = int(meta.getheaders("Content-Length")[0])
324 logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
329 buffer = response.read(block_sz)
333 file_size_dl += len(buffer)
335 status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
336 status = status + chr(8)*(len(status)+1)
344 def check_internet_connectivity(url='http://www.google.com/'):
346 Check if there is access to the internet
349 urllib2.urlopen(url, timeout=5)
351 except urllib.request.URLError:
354 def execute_command(cmd):
356 Execute Linux command
358 logger.debug('Executing command : {}'.format(cmd))
359 #p = os.popen(cmd,"r")
360 #logger.debug(p.read())
361 output_file = "/tmp/output.txt"
362 f = open(output_file, 'w+')
363 p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
365 f = open(output_file, 'r')
366 logger.debug(f.read())
367 #p = subprocess.call(cmd,shell=True);
371 logger.error("Error when executing command %s" %cmd)
378 if not (args.action in actions):
379 logger.error('argument not valid')
382 if args.action == "start":
383 config_functest_start()
385 if args.action == "check":
386 config_functest_check()
388 if args.action == "clean":
390 print("Are you sure? [y|n]")
391 answer = raw_input("")
393 config_functest_clean()
398 print("Invalid option.")
402 if __name__ == '__main__':