Reduce the number of iterations to ten in rally scenarios
[functest.git] / testcases / VIM / OpenStack / CI / libraries / run_rally-cert.py
index a52e7f0..0fb6ce7 100755 (executable)
@@ -21,11 +21,13 @@ import argparse
 import logging
 import yaml
 import requests
+import subprocess
 import sys
-import novaclient.v2.client as novaclient
+from novaclient import client as novaclient
 from glanceclient import client as glanceclient
 from keystoneclient.v2_0 import client as keystoneclient
 from neutronclient.v2_0 import client as neutronclient
+from cinderclient import client as cinderclient
 
 """ tests configuration """
 tests = ['authenticate', 'glance', 'cinder', 'heat', 'keystone',
@@ -48,11 +50,19 @@ parser.add_argument("-r", "--report",
 parser.add_argument("-s", "--smoke",
                     help="Smoke test mode",
                     action="store_true")
+parser.add_argument("-v", "--verbose",
+                    help="Print verbose info about the progress",
+                    action="store_true")
 
 args = parser.parse_args()
 
 client_dict = {}
 
+if args.verbose:
+    RALLY_STDERR = subprocess.STDOUT
+else:
+    RALLY_STDERR = open(os.devnull, 'w')
+
 """ logging configuration """
 logger = logging.getLogger("run_rally")
 logger.setLevel(logging.DEBUG)
@@ -91,15 +101,15 @@ SUPPORT_DIR = SCENARIOS_DIR + "scenario/support"
 FLAVOR_NAME = "m1.tiny"
 USERS_AMOUNT = 2
 TENANTS_AMOUNT = 3
-CONTROLLERS_AMOUNT = 2
+ITERATIONS_AMOUNT = 10
+CONCURRENCY = 4
+
 ###
 RESULTS_DIR = functest_yaml.get("general").get("directories"). \
     get("dir_rally_res")
 TEST_DB = functest_yaml.get("results").get("test_db_url")
 FLOATING_NETWORK = functest_yaml.get("general"). \
     get("openstack").get("neutron_public_net_name")
-FLOATING_SUBNET_CIDR = functest_yaml.get("general"). \
-    get("openstack").get("neutron_public_subnet_cidr")
 PRIVATE_NETWORK = functest_yaml.get("general"). \
     get("openstack").get("neutron_private_net_name")
 
@@ -112,17 +122,19 @@ GLANCE_IMAGE_FORMAT = functest_yaml.get("general"). \
 GLANCE_IMAGE_PATH = functest_yaml.get("general"). \
     get("directories").get("dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
 
+CINDER_VOLUME_TYPE_NAME = "volume_test"
+
 
 def push_results_to_db(payload):
 
     url = TEST_DB + "/results"
     installer = functest_utils.get_installer_type(logger)
-    git_version = functest_utils.get_git_branch(REPO_PATH)
+    scenario = functest_utils.get_scenario(logger)
     pod_name = functest_utils.get_pod_name(logger)
     # TODO pod_name hardcoded, info shall come from Jenkins
     params = {"project_name": "functest", "case_name": "Rally",
               "pod_name": pod_name, "installer": installer,
-              "version": git_version, "details": payload}
+              "version": scenario, "details": payload}
 
     headers = {'Content-Type': 'application/json'}
     r = requests.post(url, data=json.dumps(params), headers=headers)
@@ -151,16 +163,14 @@ def task_succeed(json_raw):
     :return: Bool
     """
     rally_report = json.loads(json_raw)
-    rally_report = rally_report[0]
-    if rally_report is None:
-        return False
-    if rally_report.get('result') is None:
-        return False
-
-    for result in rally_report.get('result'):
-        if len(result.get('error')) > 0:
+    for report in rally_report:
+        if report is None or report.get('result') is None:
             return False
 
+        for result in report.get('result'):
+            if result is None or len(result.get('error')) > 0:
+                return False
+
     return True
 
 
@@ -171,18 +181,44 @@ def build_task_args(test_file_name):
     task_args['flavor_name'] = FLAVOR_NAME
     task_args['glance_image_location'] = GLANCE_IMAGE_PATH
     task_args['floating_network'] = FLOATING_NETWORK
-    task_args['floating_subnet_cidr'] = FLOATING_SUBNET_CIDR
     task_args['netid'] = functest_utils.get_network_id(client_dict['neutron'],
                                     PRIVATE_NETWORK).encode('ascii', 'ignore')
     task_args['tmpl_dir'] = TEMPLATE_DIR
     task_args['sup_dir'] = SUPPORT_DIR
     task_args['users_amount'] = USERS_AMOUNT
     task_args['tenants_amount'] = TENANTS_AMOUNT
-    task_args['controllers_amount'] = CONTROLLERS_AMOUNT
+    task_args['iterations'] = ITERATIONS_AMOUNT
+    task_args['concurrency'] = CONCURRENCY
 
     return task_args
 
 
+def get_output(proc):
+    result = ""
+    if args.verbose:
+        while proc.poll() is None:
+            line = proc.stdout.readline()
+            print line.replace('\n', '')
+            result += line
+    else:
+        while proc.poll() is None:
+            line = proc.stdout.readline()
+            if "Load duration" in line or \
+               "started" in line or \
+               "finished" in line or \
+               " Preparing" in line or \
+               "+-" in line or \
+               "|" in line:
+                result += line
+            elif "test scenario" in line:
+                result += "\n" + line
+            elif "Full duration" in line:
+                result += line + "\n\n"
+        logger.info("\n" + result)
+
+    return result
+
+
 def run_task(test_name):
     #
     # the "main" function of the script who launch rally for a task
@@ -190,7 +226,7 @@ def run_task(test_name):
     # :return: void
     #
 
-    logger.info('starting {} test ...'.format(test_name))
+    logger.info('Starting test scenario "{}" ...'.format(test_name))
 
     task_file = '{}task.yaml'.format(SCENARIOS_DIR)
     if not os.path.exists(task_file):
@@ -208,8 +244,10 @@ def run_task(test_name):
                "--task {} ".format(task_file) + \
                "--task-args \"{}\" ".format(build_task_args(test_name))
     logger.debug('running command line : {}'.format(cmd_line))
-    cmd = os.popen(cmd_line)
-    task_id = get_task_id(cmd.read())
+
+    p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE, stderr=RALLY_STDERR, shell=True)
+    output = get_output(p)
+    task_id = get_task_id(output)
     logger.debug('task_id : {}'.format(task_id))
 
     if task_id is None:
@@ -249,9 +287,9 @@ def run_task(test_name):
 
     """ parse JSON operation result """
     if task_succeed(json_results):
-        print 'Test OK'
+        logger.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
     else:
-        print 'Test KO'
+        logger.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
 
 
 def main():
@@ -261,7 +299,7 @@ def main():
         exit(-1)
 
     creds_nova = functest_utils.get_credentials("nova")
-    nova_client = novaclient.Client(**creds_nova)
+    nova_client = novaclient.Client('2',**creds_nova)
     creds_neutron = functest_utils.get_credentials("neutron")
     neutron_client = neutronclient.Client(**creds_neutron)
     creds_keystone = functest_utils.get_credentials("keystone")
@@ -270,37 +308,65 @@ def main():
                                                    endpoint_type='publicURL')
     glance_client = glanceclient.Client(1, glance_endpoint,
                                         token=keystone_client.auth_token)
+    creds_cinder = functest_utils.get_credentials("cinder")
+    cinder_client = cinderclient.Client('2',creds_cinder['username'],
+                                        creds_cinder['api_key'],
+                                        creds_cinder['project_id'],
+                                        creds_cinder['auth_url'],
+                                        service_type="volume")
 
     client_dict['neutron'] = neutron_client
 
-    logger.debug("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME, GLANCE_IMAGE_PATH))
-    image_id = functest_utils.create_glance_image(glance_client,
-                                            GLANCE_IMAGE_NAME,GLANCE_IMAGE_PATH)
-    if not image_id:
-        logger.error("Failed to create a Glance image...")
-        exit(-1)
-    # Check if the given image exists
-    try:
-        nova_client.images.find(name=GLANCE_IMAGE_NAME)
-        logger.info("Glance image found '%s'" % GLANCE_IMAGE_NAME)
-    except:
-        logger.error("ERROR: Glance image '%s' not found." % GLANCE_IMAGE_NAME)
-        logger.info("Available images are: ")
-        exit(-1)
+    volume_types = functest_utils.list_volume_types(cinder_client, private=False)
+    if not volume_types:
+        volume_type = functest_utils.create_volume_type(cinder_client, \
+                                                        CINDER_VOLUME_TYPE_NAME)
+        if not volume_type:
+            logger.error("Failed to create volume type...")
+            exit(-1)
+        else:
+            logger.debug("Volume type '%s' created succesfully..." \
+                         % CINDER_VOLUME_TYPE_NAME)
+    else:
+        logger.debug("Using existing volume type(s)...")
+
+    image_id = functest_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
+
+    if image_id == '':
+        logger.debug("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME, \
+                                                           GLANCE_IMAGE_PATH))
+        image_id = functest_utils.create_glance_image(glance_client,\
+                                                GLANCE_IMAGE_NAME,GLANCE_IMAGE_PATH)
+        if not image_id:
+            logger.error("Failed to create the Glance image...")
+            exit(-1)
+        else:
+            logger.debug("Image '%s' with ID '%s' created succesfully ." \
+                         % (GLANCE_IMAGE_NAME, image_id))
+    else:
+        logger.debug("Using existing image '%s' with ID '%s'..." \
+                     % (GLANCE_IMAGE_NAME,image_id))
 
     if args.test_name == "all":
         for test_name in tests:
             if not (test_name == 'all' or
                     test_name == 'vm'):
-                print(test_name)
                 run_task(test_name)
     else:
         print(args.test_name)
         run_task(args.test_name)
 
-    logger.debug("Deleting image...")
+    logger.debug("Deleting image '%s' with ID '%s'..." \
+                         % (GLANCE_IMAGE_NAME, image_id))
     if not functest_utils.delete_glance_image(nova_client, image_id):
         logger.error("Error deleting the glance image")
 
+    if not volume_types:
+        logger.debug("Deleting volume type '%s'..." \
+                             % CINDER_VOLUME_TYPE_NAME)
+        if not functest_utils.delete_volume_type(cinder_client, volume_type):
+            logger.error("Error in deleting volume type...")
+
+
 if __name__ == '__main__':
     main()