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 = 'http://mirror.us.leaseweb.net/ubuntu-releases/14.04.2/ubuntu-14.04.2-server-amd64.iso'
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_installation_dir = os.environ['HOME'] + "/.rally"
26 parser = argparse.ArgumentParser()
27 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
28 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
29 args = parser.parse_args()
32 """ logging configuration """
33 logger = logging.getLogger('config_functest')
34 logger.setLevel(logging.DEBUG)
36 ch = logging.StreamHandler()
38 ch.setLevel(logging.DEBUG)
40 ch.setLevel(logging.INFO)
42 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
43 ch.setFormatter(formatter)
48 def config_functest_start():
50 Start the functest environment installation
52 if config_functest_check():
53 logger.info("Functest environment already installed in %s. Nothing to do." %functest_dir)
55 elif not check_internet_connectivity():
56 logger.error("There is no Internet connectivity. Please check the network configuration.")
58 elif not check_credentials():
59 logger.error("Please source the openrc credentials and run the script again.")
60 #TODO: source the credentials in this script
63 config_functest_clean()
65 logger.info("Starting installationg of functest environment in %s" %functest_dir)
66 os.makedirs(functest_dir)
67 if not os.path.exists(functest_dir):
68 logger.error("There has been a problem while creating the environment directory")
72 logger.info("Installing Rally...")
73 if not install_rally():
74 logger.error("There has been a problem while installing Rally")
77 logger.info("Installing Robot...")
78 if not install_robot():
79 logger.error("There has been a problem while installing Robot")
82 logger.info("Donwloading test scripts and scenarios...")
85 logger.info("Donwloading image...")
86 download_url_with_progress(image_url, functest_dir)
88 logger.info("Creating Glance image: %s ..." %image_name)
89 create_glance_image(image_path,image_name,image_disk_format)
95 def config_functest_check():
97 Check if the functest environment is installed
99 logger.info("Checking current functest configuration...")
100 if os.path.exists(functest_dir) and os.path.exists(rally_installation_dir):
101 logger.info("Functest environment directory found in %s" %functest_dir)
104 logger.info("Functest environment directory not found")
109 def config_functest_clean():
111 Clean the existing functest environment
113 logger.info("Removing current functest environment...")
114 if os.path.exists(rally_installation_dir):
115 shutil.rmtree(rally_installation_dir,ignore_errors=True)
117 if os.path.exists(functest_dir):
118 cmd = "sudo rm -rf " + functest_dir #need to be sudo
126 logger.info("Rally is already installed.")
128 logger.debug("Cloning repository...")
129 url = "https://git.openstack.org/openstack/rally"
130 Repo.clone_from(url, rally_repo_dir)
132 logger.debug("Executing %s./install_rally.sh..." %rally_repo_dir)
133 install_script = rally_repo_dir + "./install_rally.sh"
134 subprocess.call(['sudo', install_script])
136 logger.debug("Creating Rally environment...")
137 cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
140 logger.debug("Installing tempest...")
141 cmd = "rally-manage tempest install"
144 cmd = "rally deployment check"
146 #TODO: check that everything is 'Available' and warn if not
148 cmd = "rally show images"
151 cmd = "rally show flavors"
160 Check if Rally is installed and properly configured
162 if os.path.exists(os.environ['HOME']+"/.rally/"):
163 #TODO: do a more consistent check, for example running the comand rally deployment check
170 cmd = "sudo pip install requests"
172 cmd = "sudo pip install robotframework"
174 cmd = "sudo pip install robotframework-sshlibrary"
176 cmd = "sudo pip install robotframework-requests"
178 cmd = "mkvirtualenv robot"
183 def check_credentials():
185 Check if the OpenStack credentials (openrc) are sourced
187 #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
189 os.environ['OS_AUTH_URL']
193 os.environ['OS_USERNAME']
197 os.environ['OS_PASSWORD']
201 os.environ['OS_TENANT_NAME']
205 os.environ['OS_REGION_NAME']
211 def download_tests():
212 vPing_dir = functest_dir + "vPing/"
213 odl_dir = functest_dir + "ODL/"
214 bench_tests_dir = functest_dir + "scenarios/"
216 os.makedirs(vPing_dir)
218 os.makedirs(bench_tests_dir)
220 logger.info("Downloading vPing test...")
221 vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
222 download_url(vPing_url,vPing_dir)
224 logger.info("Downloading Rally bench tests...")
225 rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
226 bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
227 for i in bench_tests:
228 rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
229 logger.debug("Downloading %s" %rally_bench_url)
230 download_url(rally_bench_url,bench_tests_dir)
232 logger.info("Downloading OLD tests...")
233 odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
234 odl_tests = ['start_tests.sh', 'test_list.txt']
236 odl_url = odl_base_url + i
237 logger.debug("Downloading %s" %odl_url)
238 download_url(odl_url,odl_dir)
243 def create_glance_image(path,name,disk_format):
245 Create a glance image given the absolute path of the image, its name and the disk format
247 cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
251 def download_url(url, dest_path):
253 Download a file to a destination path given a URL
255 name = url.rsplit('/')[-1]
256 dest = dest_path + name
258 response = urllib2.urlopen(url)
259 except (urllib2.HTTPError, urllib2.URLError):
260 logger.error("Error in fetching %s" %url)
263 with open(dest, 'wb') as f:
264 f.write(response.read())
268 def download_url_with_progress(url, dest_path):
270 Download a file to a destination path given a URL showing the progress
272 name = url.rsplit('/')[-1]
273 dest = dest_path + name
275 response = urllib2.urlopen(url)
276 except (urllib2.HTTPError, urllib2.URLError):
277 logger.error("Error in fetching %s" %url)
281 meta = response.info()
282 file_size = int(meta.getheaders("Content-Length")[0])
283 logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
288 buffer = response.read(block_sz)
292 file_size_dl += len(buffer)
294 status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
295 status = status + chr(8)*(len(status)+1)
302 def check_internet_connectivity(url='http://www.google.com/'):
304 Check if there is access to the internet
307 urllib2.urlopen(url, timeout=5)
309 except urllib.request.URLError:
312 def execute_command(cmd):
314 Execute Linux command
316 logger.debug('Executing command : {}'.format(cmd))
317 p = os.popen(cmd,"r")
318 logger.debug(p.read())
323 if not (args.action in actions):
324 logger.error('argument not valid')
327 if args.action == "start":
328 config_functest_start()
330 if args.action == "check":
331 config_functest_check()
333 if args.action == "clean":
335 print("Are you sure? [y|n]")
336 answer = raw_input("")
338 config_functest_clean()
343 print("Invalid option.")
347 if __name__ == '__main__':