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"
28 parser = argparse.ArgumentParser()
29 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
30 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
31 args = parser.parse_args()
34 """ logging configuration """
35 logger = logging.getLogger('config_functest')
36 logger.setLevel(logging.DEBUG)
38 ch = logging.StreamHandler()
40 ch.setLevel(logging.DEBUG)
42 ch.setLevel(logging.INFO)
44 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
45 ch.setFormatter(formatter)
50 def config_functest_start():
52 Start the functest environment installation
54 if config_functest_check():
55 logger.info("Functest environment already installed in %s. Nothing to do." %functest_dir)
57 elif not check_internet_connectivity():
58 logger.error("There is no Internet connectivity. Please check the network configuration.")
60 elif not check_credentials():
61 logger.error("Please source the openrc credentials and run the script again.")
62 #TODO: source the credentials in this script
65 config_functest_clean()
67 logger.info("Starting installationg of functest environment in %s" %functest_dir)
68 os.makedirs(functest_dir)
69 if not os.path.exists(functest_dir):
70 logger.error("There has been a problem while creating the environment directory.")
74 logger.info("Installing Rally...")
75 if not install_rally():
76 logger.error("There has been a problem while installing Rally.")
77 config_functest_clean()
80 logger.info("Installing Robot...")
81 if not install_robot():
82 logger.error("There has been a problem while installing Robot.")
83 config_functest_clean()
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()
92 logger.info("Donwloading image...")
93 if not download_url_with_progress(image_url, functest_dir):
94 logger.error("There has been a problem while downloading the image.")
95 config_functest_clean()
98 logger.info("Creating Glance image: %s ..." %image_name)
99 if not create_glance_image(image_path,image_name,image_disk_format):
100 logger.error("There has been a problem while creating the Glance image.")
101 config_functest_clean()
108 def config_functest_check():
110 Check if the functest environment is installed
112 logger.info("Checking current functest configuration...")
113 if os.path.exists(functest_dir) and os.path.exists(rally_installation_dir):
114 logger.info("Functest environment directory found in %s" %functest_dir)
117 logger.info("Functest environment directory not found")
122 def config_functest_clean():
124 Clean the existing functest environment
126 logger.info("Removing current functest environment...")
127 if os.path.exists(rally_installation_dir):
128 logger.debug("Removing rally installation directory %s" % rally_installation_dir)
129 shutil.rmtree(rally_installation_dir,ignore_errors=True)
131 if os.path.exists(functest_dir):
132 logger.debug("Removing functest directory %s" % functest_dir)
133 cmd = "sudo rm -rf " + functest_dir #need to be sudo, not possible with rmtree
136 logger.debug("Deleting glance images")
137 cmd = "glance image-list | grep "+image_name+" | cut -c3-38"
138 p = os.popen(cmd,"r")
140 #while image_id = p.readline()
141 for image_id in p.readlines():
142 cmd = "glance image-delete " + image_id
150 logger.info("Rally is already installed.")
152 logger.debug("Cloning repository...")
153 url = "https://git.openstack.org/openstack/rally"
154 Repo.clone_from(url, rally_repo_dir)
156 logger.debug("Executing %s./install_rally.sh..." %rally_repo_dir)
157 install_script = rally_repo_dir + "install_rally.sh"
158 cmd = 'sudo ' + install_script
160 #subprocess.call(['sudo', install_script])
162 logger.debug("Creating Rally environment...")
163 cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
166 logger.debug("Installing tempest...")
167 cmd = "rally-manage tempest install"
170 cmd = "rally deployment check"
172 #TODO: check that everything is 'Available' and warn if not
174 cmd = "rally show images"
177 cmd = "rally show flavors"
186 Check if Rally is installed and properly configured
188 if os.path.exists(os.environ['HOME']+"/.rally/"):
189 #TODO: do a more consistent check, for example running the comand rally deployment check
196 cmd = "sudo pip install requests"
198 cmd = "sudo pip install robotframework"
200 cmd = "sudo pip install robotframework-sshlibrary"
202 cmd = "sudo pip install robotframework-requests"
204 #cmd = "mkvirtualenv robot"
205 #execute_command(cmd)
209 def check_credentials():
211 Check if the OpenStack credentials (openrc) are sourced
213 #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
215 os.environ['OS_AUTH_URL']
219 os.environ['OS_USERNAME']
223 os.environ['OS_PASSWORD']
227 os.environ['OS_TENANT_NAME']
231 os.environ['OS_REGION_NAME']
237 def download_tests():
238 vPing_dir = functest_dir + "vPing/"
239 odl_dir = functest_dir + "ODL/"
240 bench_tests_dir = functest_dir + "scenarios/"
242 os.makedirs(vPing_dir)
244 os.makedirs(bench_tests_dir)
246 logger.info("Downloading vPing test...")
247 vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
248 if not download_url(vPing_url,vPing_dir):
251 vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
252 if not download_url(vPing_url,vPing_dir):
255 logger.info("Downloading Rally bench tests...")
256 run_rally_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/libraries/run_rally.py'
257 if not download_url(run_rally_url,bench_tests_dir ):
260 rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
261 bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
262 for i in bench_tests:
263 rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
264 logger.debug("Downloading %s" %rally_bench_url)
265 if not download_url(rally_bench_url,bench_tests_dir):
268 logger.info("Downloading OLD tests...")
269 odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
270 odl_tests = ['start_tests.sh', 'test_list.txt']
272 odl_url = odl_base_url + i
273 logger.debug("Downloading %s" %odl_url)
274 if not download_url(odl_url,odl_dir):
282 def create_glance_image(path,name,disk_format):
284 Create a glance image given the absolute path of the image, its name and the disk format
286 cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
291 def download_url(url, dest_path):
293 Download a file to a destination path given a URL
295 name = url.rsplit('/')[-1]
296 dest = dest_path + name
298 response = urllib2.urlopen(url)
299 except (urllib2.HTTPError, urllib2.URLError):
300 logger.error("Error in fetching %s" %url)
303 with open(dest, 'wb') as f:
304 f.write(response.read())
308 def download_url_with_progress(url, dest_path):
310 Download a file to a destination path given a URL showing the progress
312 name = url.rsplit('/')[-1]
313 dest = dest_path + name
315 response = urllib2.urlopen(url)
316 except (urllib2.HTTPError, urllib2.URLError):
317 logger.error("Error in fetching %s" %url)
321 meta = response.info()
322 file_size = int(meta.getheaders("Content-Length")[0])
323 logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
328 buffer = response.read(block_sz)
332 file_size_dl += len(buffer)
334 status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
335 status = status + chr(8)*(len(status)+1)
343 def check_internet_connectivity(url='http://www.google.com/'):
345 Check if there is access to the internet
348 urllib2.urlopen(url, timeout=5)
350 except urllib.request.URLError:
353 def execute_command(cmd):
355 Execute Linux command
357 logger.debug('Executing command : {}'.format(cmd))
358 #p = os.popen(cmd,"r")
359 #logger.debug(p.read())
360 output_file = "/tmp/output.txt"
361 f = open(output_file, 'w+')
362 p = subprocess.call(cmd,shell=True, stdout=f, stderr=subprocess.STDOUT)
364 f = open(output_file, 'r')
365 logger.debug(f.read())
366 #p = subprocess.call(cmd,shell=True);
370 logger.error("Error when executing command %s" %cmd)
377 if not (args.action in actions):
378 logger.error('argument not valid')
381 if args.action == "start":
382 config_functest_start()
384 if args.action == "check":
385 config_functest_check()
387 if args.action == "clean":
389 print("Are you sure? [y|n]")
390 answer = raw_input("")
392 config_functest_clean()
397 print("Invalid option.")
401 if __name__ == '__main__':