# http://www.apache.org/licenses/LICENSE-2.0
#
-import re, json, os, urllib2, argparse, logging, shutil
+import re, json, os, urllib2, argparse, logging, shutil, subprocess, yaml, sys, getpass
+import functest_utils
+from git import Repo
+from os import stat
+from pwd import getpwuid
actions = ['start', 'check', 'clean']
-
-""" global variables """
-functest_dir = os.environ['HOME'] + '/.functest/'
-#image_url = 'http://mirror.us.leaseweb.net/ubuntu-releases/14.04.2/ubuntu-14.04.2-server-amd64.iso'
-image_url = 'http://download.cirros-cloud.net/0.3.0/cirros-0.3.0-i386-disk.img'
-image_disk_format = 'raw'
-image_name = image_url.rsplit('/')[-1]
-image_path = functest_dir + image_name
-
parser = argparse.ArgumentParser()
+parser.add_argument("repo_path", help="Path to the repository")
parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
+parser.add_argument("-f", "--force", help="Force", action="store_true")
args = parser.parse_args()
ch.setFormatter(formatter)
logger.addHandler(ch)
+if not os.path.exists(args.repo_path):
+ logger.error("Repo directory not found '%s'" % args.repo_path)
+ exit(-1)
+
+with open(args.repo_path+"testcases/config_functest.yaml") as f:
+ functest_yaml = yaml.safe_load(f)
+f.close()
+
+
-def config_functest_start():
+""" global variables """
+# Directories
+HOME = os.environ['HOME']+"/"
+REPO_PATH = args.repo_path
+RALLY_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_rally")
+RALLY_REPO_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_repo")
+RALLY_INSTALLATION_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_inst")
+RALLY_RESULT_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_res")
+VPING_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_vping")
+ODL_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_odl")
+
+
+#GLANCE image parameters
+IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
+IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
+IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
+IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
+IMAGE_DIR = HOME + functest_yaml.get("general").get("openstack").get("image_download_path")
+IMAGE_PATH = IMAGE_DIR + IMAGE_FILE_NAME
+
+
+def action_start():
"""
Start the functest environment installation
"""
- if config_functest_check():
- logger.info("Functest environment already installed in %s. Nothing to do." %functest_dir)
- exit(0)
- elif not check_internet_connectivity():
- logger.error("There is no Internet connectivity. Please check the network configuration.")
- exit(-1)
- elif not check_credentials():
- logger.error("Please source the openrc credentials and run the script again.")
- #TODO: source the credentials in this script
+ if not check_permissions():
+ logger.error("Bad Python cache directory ownership.")
exit(-1)
- elif not check_rally():
- logger.error("Rally is not installed. Please follow the instructions to prepare the Rally environment.")
+
+ if not functest_utils.check_internet_connectivity():
+ logger.error("There is no Internet connectivity. Please check the network configuration.")
exit(-1)
+
+ if action_check():
+ logger.info("Functest environment already installed. Nothing to do.")
+ exit(0)
+
else:
- logger.info("Starting installationg of functest environment in %s" %functest_dir)
- os.makedirs(functest_dir)
- if not os.path.exists(functest_dir):
- logger.error("There has been a problem why creating the environment directory")
+ # Clean in case there are left overs
+ logger.debug("Cleaning possible functest environment leftovers.")
+ action_clean()
+
+ logger.info("Installing ODL environment...")
+ if not install_odl():
+ logger.error("There has been a problem while installing Robot.")
+ action_clean()
exit(-1)
- logger.info("Donwloading test scripts and scenarios...")
- download_tests()
+ logger.info("Starting installation of functest environment")
+ logger.info("Installing Rally...")
+ if not install_rally():
+ logger.error("There has been a problem while installing Rally.")
+ action_clean()
+ exit(-1)
- logger.info("Donwloading image...")
- download_url_with_progress(image_url, functest_dir)
+ # Create result folder under functest if necessary
+ if not os.path.exists(RALLY_RESULT_DIR):
+ os.makedirs(RALLY_RESULT_DIR)
- logger.info("Creating Glance image: %s ..." %image_name)
- create_glance_image(image_path,image_name,image_disk_format)
- exit(0)
+ logger.info("Downloading image...")
+ if not functest_utils.download_url(IMAGE_URL, IMAGE_DIR):
+ logger.error("There has been a problem downloading the image '%s'." %IMAGE_URL)
+ action_clean()
+ exit(-1)
+
+ logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
+ if not create_glance_image(IMAGE_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
+ logger.error("There has been a problem while creating the Glance image.")
+ action_clean()
+ exit(-1)
+ exit(0)
-def config_functest_check():
+def action_check():
"""
- Check if the functest environment is installed
+ Check if the functest environment is properly installed
"""
+ errors_all = False
+
logger.info("Checking current functest configuration...")
- if not os.path.exists(functest_dir):
- logger.info("Functest environment directory not found")
+
+ logger.debug("Checking script directories...")
+ errors = False
+ dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
+ for dir in dirs:
+ if not os.path.exists(dir):
+ logger.debug("The directory '%s' does NOT exist." % dir)
+ errors = True
+ errors_all = True
+ else:
+ logger.debug(" %s found" % dir)
+ if not errors:
+ logger.debug("...OK")
+ else:
+ logger.debug("...FAIL")
+
+
+ logger.debug("Checking Rally deployment...")
+ if not check_rally():
+ logger.debug(" Rally deployment NOT installed.")
+ errors_all = True
+ logger.debug("...FAIL")
+ else:
+ logger.debug("...OK")
+
+ logger.debug("Checking Image...")
+ errors = False
+ if not os.path.isfile(IMAGE_PATH):
+ logger.debug(" Image file '%s' NOT found." % IMAGE_PATH)
+ errors = True
+ errors_all = True
+ else:
+ logger.debug(" Image file found in %s" % IMAGE_PATH)
+
+ cmd="glance image-list | grep " + IMAGE_NAME
+ FNULL = open(os.devnull, 'w');
+ logger.debug(' Executing command : {}'.format(cmd))
+ p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
+ #if the command does not exist or there is no glance image
+ line = p.stdout.readline()
+ if line == "":
+ logger.debug(" Glance image NOT found.")
+ errors = True
+ errors_all = True
+ else:
+ logger.debug(" Glance image found.")
+
+ if not errors:
+ logger.debug("...OK")
+ else:
+ logger.debug("...FAIL")
+
+ #TODO: check OLD environment setup
+ if errors_all:
return False
else:
- logger.info("Functest environment directory found in %s" %functest_dir)
- #TODO: more verifications here
return True
-def config_functest_clean():
+
+def action_clean():
"""
Clean the existing functest environment
"""
- if not config_functest_check():
- logger.info("There is no functest environment installed. Nothing to clean.")
- return 0
- else:
- while True:
- print("Are you sure? [y|n]")
- answer = raw_input("")
- if answer == "y":
- logger.info("Removing current functest environment...")
- shutil.rmtree(functest_dir,ignore_errors=True)
- exit(0)
- elif answer == "n":
- exit(0)
- else:
- print("Invalid option.")
+ logger.info("Removing current functest environment...")
+ if os.path.exists(RALLY_INSTALLATION_DIR):
+ logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
+ shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
+ if os.path.exists(RALLY_REPO_DIR):
+ logger.debug("Removing Rally repository %s" % RALLY_REPO_DIR)
+ cmd = "sudo rm -rf " + RALLY_REPO_DIR #need to be sudo, not possible with rmtree
+ functest_utils.execute_command(cmd,logger)
+ if os.path.exists(IMAGE_PATH):
+ logger.debug("Deleting image")
+ os.remove(IMAGE_PATH)
+ cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
+ p = os.popen(cmd,"r")
-def check_rally():
- """
- Check if Rally is installed and properly configured
- """
- if os.path.exists(os.environ['HOME']+"/.rally/"):
- #TODO: do a more consistent check, for example running the comand rally deployment check
- return True
- else:
- return False
+ #while image_id = p.readline()
+ for image_id in p.readlines():
+ cmd = "glance image-delete " + image_id
+ functest_utils.execute_command(cmd,logger)
+ if os.path.exists(RALLY_RESULT_DIR):
+ logger.debug("Removing Result directory")
+ shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
-def check_credentials():
- """
- Check if the OpenStack credentials (openrc) are sourced
- """
- #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
- try:
- os.environ['OS_AUTH_URL']
- except KeyError:
- return False
- try:
- os.environ['OS_USERNAME']
- except KeyError:
- return False
- try:
- os.environ['OS_PASSWORD']
- except KeyError:
- return False
- try:
- os.environ['OS_TENANT_NAME']
- except KeyError:
- return False
- try:
- os.environ['OS_REGION_NAME']
- except KeyError:
- return False
- return True
+
+ logger.info("Functest environment clean!")
-def download_tests():
- vPing_dir = functest_dir + "vPing/"
- odl_dir = functest_dir + "ODL/"
- bench_tests_dir = functest_dir + "scenarios/"
- os.makedirs(vPing_dir)
- os.makedirs(odl_dir)
- os.makedirs(bench_tests_dir)
+def check_permissions():
+ current_user = getpass.getuser()
+ cache_dir = HOME+".cache/pip"
+ logger.info("Checking permissions of '%s'..." %cache_dir)
+ logger.debug("Current user is '%s'" %current_user)
+ cache_user = getpwuid(stat(cache_dir).st_uid).pw_name
+ logger.debug("Cache directory owner is '%s'" %cache_user)
+ if cache_user != current_user:
+ logger.info("The owner of '%s' is '%s'. Please run 'sudo chown -R %s %s'." %(cache_dir, cache_user, current_user, cache_dir))
+ return False
+
+ return True
- logger.info("Downloading vPing test...")
- vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
- download_url(vPing_url,vPing_dir)
- logger.info("Downloading Rally bench tests...")
- rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
- bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
- for i in bench_tests:
- rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
- logger.debug("Downloading %s" %rally_bench_url)
- download_url(rally_bench_url,bench_tests_dir)
+def install_rally():
+ if check_rally():
+ logger.info("Rally is already installed.")
+ else:
+ logger.debug("Cloning repository...")
+ url = "https://git.openstack.org/openstack/rally"
+ Repo.clone_from(url, RALLY_REPO_DIR)
- logger.info("Downloading OLD tests...")
- odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
- odl_tests = ['start_tests.sh', 'test_list.txt']
- for i in odl_tests:
- odl_url = odl_base_url + i
- logger.debug("Downloading %s" %odl_url)
- download_url(odl_url,odl_dir)
- #TODO: complete
+ logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
+ install_script = RALLY_REPO_DIR + "install_rally.sh"
+ cmd = 'sudo ' + install_script
+ functest_utils.execute_command(cmd,logger)
+ logger.debug("Creating Rally environment...")
+ cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
+ functest_utils.execute_command(cmd,logger)
+ logger.debug("Installing tempest...")
+ cmd = "rally-manage tempest install"
+ functest_utils.execute_command(cmd,logger)
-def create_glance_image(path,name,disk_format):
- """
- Create a glance image given the absolute path of the image, its name and the disk format
- """
- cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
- execute_command(cmd)
+ cmd = "rally deployment check"
+ functest_utils.execute_command(cmd,logger)
+ #TODO: check that everything is 'Available' and warn if not
+ cmd = "rally show images"
+ functest_utils.execute_command(cmd,logger)
-def download_url(url, dest_path):
- """
- Download a file to a destination path given a URL
- """
- name = url.rsplit('/')[-1]
- dest = dest_path + name
- try:
- response = urllib2.urlopen(url)
- except (urllib2.HTTPError, urllib2.URLError):
- logger.error("Error in fetching %s" %url)
- return False
+ cmd = "rally show flavors"
+ functest_utils.execute_command(cmd,logger)
- with open(dest, 'wb') as f:
- f.write(response.read())
return True
-def download_url_with_progress(url, dest_path):
+
+def check_rally():
"""
- Download a file to a destination path given a URL showing the progress
+ Check if Rally is installed and properly configured
"""
- name = url.rsplit('/')[-1]
- dest = dest_path + name
- try:
- response = urllib2.urlopen(url)
- except (urllib2.HTTPError, urllib2.URLError):
- logger.error("Error in fetching %s" %url)
+ if os.path.exists(RALLY_INSTALLATION_DIR):
+ logger.debug(" Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
+ FNULL = open(os.devnull, 'w');
+ cmd="rally deployment list | grep opnfv";
+ logger.debug(' Executing command : {}'.format(cmd))
+ p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
+ #if the command does not exist or there is no deployment
+ line = p.stdout.readline()
+ if line == "":
+ logger.debug(" Rally deployment NOT found")
+ return False
+ logger.debug(" Rally deployment found")
+ return True
+ else:
return False
- f = open(dest, 'wb')
- meta = response.info()
- file_size = int(meta.getheaders("Content-Length")[0])
- logger.info("Downloading: %s Bytes: %s" %(dest, file_size))
-
- file_size_dl = 0
- block_sz = 8192
- while True:
- buffer = response.read(block_sz)
- if not buffer:
- break
- file_size_dl += len(buffer)
- f.write(buffer)
- status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
- status = status + chr(8)*(len(status)+1)
- print status,
+def install_odl():
+ cmd = "chmod +x " + ODL_DIR + "start_tests.sh"
+ functest_utils.execute_command(cmd,logger)
+ cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
+ functest_utils.execute_command(cmd,logger)
+ cmd = ODL_DIR + "create_venv.sh"
+ functest_utils.execute_command(cmd,logger)
+ return True
- f.close()
- print("\n")
-def check_internet_connectivity(url='http://www.google.com/'):
+def create_glance_image(path,name,disk_format):
"""
- Check if there is access to the internet
+ Create a glance image given the absolute path of the image, its name and the disk format
"""
- try:
- urllib2.urlopen(url, timeout=5)
- return True
- except urllib.request.URLError:
- return False
+ cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
+ functest_utils.execute_command(cmd,logger)
+ return True
-def execute_command(cmd):
- """
- Execute Linux command
- """
- logger.debug('Executing command : {}'.format(cmd))
- p = os.popen(cmd,"r")
- print (p.read())
logger.error('argument not valid')
exit(-1)
+
+ if not functest_utils.check_credentials():
+ logger.error("Please source the openrc credentials and run the script again.")
+ #TODO: source the credentials in this script
+ exit(-1)
+
if args.action == "start":
- config_functest_start()
+ action_start()
if args.action == "check":
- config_functest_check()
+ if action_check():
+ logger.info("Functest environment correctly installed")
+ else:
+ logger.info("Functest environment not found or faulty")
if args.action == "clean":
- config_functest_clean()
+ if args.force :
+ action_clean()
+ else :
+ while True:
+ print("Are you sure? [y|n]")
+ answer = raw_input("")
+ if answer == "y":
+ action_clean()
+ break
+ elif answer == "n":
+ break
+ else:
+ print("Invalid option.")
+ exit(0)
+
if __name__ == '__main__':
main()