Add a fundamental rubbos test case with minimum resources
[bottlenecks.git] / testsuites / rubbos / run_rubbos.py
index c17f0d3..97b5357 100755 (executable)
@@ -8,10 +8,10 @@
 # http://www.apache.org/licenses/LICENSE-2.0
 ##############################################################################
 
-
 import os
 import argparse
 import time
+import subprocess
 import logging
 import urllib2
 import shutil
@@ -26,7 +26,7 @@ from novaclient.client import Client as NovaClient
 parser = argparse.ArgumentParser()
 parser.add_argument("-c", "--conf",
                     help="configuration files for the testcase, in yaml format",
-                    default="/tmp/rubbos_1-1-1.yaml")
+                    default="/home/opnfv/bottlenecks/testsuites/rubbos/testcase_cfg/rubbos_basic.yaml")
 args = parser.parse_args()
 
 #--------------------------------------------------
@@ -81,10 +81,10 @@ def rubbos_stack_satisfy(name="bottlenecks_rubbos_stack", status="CREATE_COMPLET
     for stack in heat.stacks.list():
         if status == None and stack.stack_name == name:
             # Found target stack
-            print "Found stack, name=" + stack.stack_name
+            print "Found stack, name=" + str(stack.stack_name)
             return True
         elif stack.stack_name == name and stack.stack_status==status:
-            print "Found stack, name=" + stack.stack_name + ", status=" + stack.stack_status
+            print "Found stack, name=" + str(stack.stack_name) + ", status=" + str(stack.stack_status)
             return True
     return False
 
@@ -105,17 +105,17 @@ def rubbos_env_cleanup():
 
     for keypair in nova.keypairs.list():
         if keypair.name.find("bottlenecks_rubbos") >= 0:
-            print "Delete keypair, id:" + keypair.id + ", name:" + keypair.name
+            print "Delete keypair, id:" + str(keypair.id) + ", name:" + str(keypair.name)
             nova.keypairs.delete(keypair.id)
 
     for flavor in nova.flavors.list():
         if flavor.name.find("bottlenecks_rubbos") >= 0:
-            print "Delete flavor, id:" + str(flavor.id) + ", name:" + flavor.name
+            print "Delete flavor, id:" + str(flavor.id) + ", name:" + str(flavor.name)
             nova.flavors.delete(flavor.id)
 
     for stack in heat.stacks.list():
         if stack.stack_name.find("bottlenecks_rubbos") >= 0:
-            print "Delete stack, id: " + str(stack.id) + ", name:" + str(stack.stack_name
+            print "Delete stack, id: " + str(stack.id) + ", name:" + str(stack.stack_name)
             heat.stacks.delete(stack.id)
 
     timeInProgress = 0
@@ -165,7 +165,7 @@ def rubbos_create_flavors(name="bottlenecks_rubbos_flavor", ram=4096, vcpus=2, d
     nova = _get_nova_client()
     nova.flavors.create(name=name, ram=ram, vcpus=vcpus, disk=disk)
 
-def rubbos_create_instance(template_file, rubbos_parameters=None, stack_name="bottlenecks_rubbos_stack"):
+def rubbos_create_instances(template_file, rubbos_parameters=None, stack_name="bottlenecks_rubbos_stack"):
     print "========== Create rubbos instances =========="
     heat = _get_heat_client()
 
@@ -175,7 +175,7 @@ def rubbos_create_instance(template_file, rubbos_parameters=None, stack_name="bo
     stack_id = stack['stack']['id']
     stack_status = heat.stacks.get(stack_id).stack_status
 
-    print "Created stack, id=" + stack_id + ", status=" + stack_status
+    print "Created stack, id=" + str(stack_id) + ", status=" + str(stack_status)
 
     timeInProgress= 0
     while stack_status == "CREATE_IN_PROGRESS" and timeInProgress < 150:
@@ -187,17 +187,147 @@ def rubbos_create_instance(template_file, rubbos_parameters=None, stack_name="bo
     print "After %d seconds, the stack's status is [%s]" %(timeInProgress, stack_status)
     return True if stack_status == "CREATE_COMPLETE" else False
 
+def get_instances(nova_client):
+    try:
+        instances = nova_client.servers.list(search_opts={'all_tenants': 1})
+        return instances
+    except Exception, e:
+        print "Error [get_instances(nova_client)]:", e
+        return None
+
+def reboot_instances():
+    print("========== reboot instances ==========")
+    nova = _get_nova_client()
+    print("nova servers list:")
+    print(nova.servers.list())
+    for instance in nova.servers.list():
+        name = getattr(instance, 'name')
+        if name.find("rubbos") >= 0:
+            print("reboot %s" % name)
+            instance.reboot()
+    print("Finish reboot all rubbos servers.")
+
 def rubbos_run():
-    pass
+    print "========== run rubbos ==========="
+
+    nova = _get_nova_client()
+    instances = get_instances(nova)
+    if instances == None:
+        print "Found *None* instances, exit rubbos_run()!"
+        return False
+
+    control_public_ip = ""
+    control_server = ""
+    client_servers = ""
+    web_servers = ""
+    app_servers = ""
+    cjdbc_controller = ""
+    database_servers = ""
+    for instance in instances:
+        name = getattr(instance, 'name')
+        private_ip = [ x['addr'] for x in getattr(instance, 'addresses').itervalues().next() if x['OS-EXT-IPS:type'] == 'fixed']
+        public_ip =  [ x['addr'] for x in getattr(instance, 'addresses').itervalues().next() if x['OS-EXT-IPS:type'] == 'floating']
+
+        if name.find("rubbos-control") >= 0:
+            control_public_ip = public_ip[0]
+            control_server = str(name) + ':' + public_ip[0] + ':' + private_ip[0]
+        if name.find("rubbos-client") >= 0:
+            client_servers = client_servers + str(name)+':'+private_ip[0] + ","
+        if name.find("rubbos-httpd") >= 0:
+            web_servers = web_servers + str(name)+':'+private_ip[0] + ","
+        if name.find("rubbos-tomcat") >= 0:
+            app_servers = app_servers + str(name) + ':' + private_ip[0] + ","
+        if name.find("rubbos-cjdbc") >= 0:
+            cjdbc_controller = str(name) + ':' + private_ip[0]
+        if name.find("rubbos-mysql") >= 0:
+            database_servers = database_servers + str(name) + ':' + private_ip[0] + ","
+
+    client_servers = client_servers[0:len(client_servers)-1]
+    web_servers = web_servers[0:len(web_servers)-1]
+    app_servers = app_servers[0:len(app_servers)-1]
+    database_servers = database_servers[0:len(database_servers)-1]
+    print "control_server:    %s" % control_server
+    print "client_servers:    %s" % client_servers
+    print "web_servers:       %s" % web_servers
+    print "app_servers:       %s" % app_servers
+    print "cjdbc_controller:  %s" % cjdbc_controller
+    print "database_servers:  %s" % database_servers
+    with open(Bottlenecks_repo_dir+"/testsuites/rubbos/puppet_manifests/internal/rubbos.conf") as temp_f, open('rubbos.conf', 'w') as new_f:
+        for line in temp_f.readlines():
+            if line.find("REPLACED_CONTROLLER") >= 0 :
+                new_f.write( line.replace("REPLACED_CONTROLLER", control_server) )
+            elif line.find("REPLACED_CLIENT_SERVERS") >= 0:
+                new_f.write( line.replace("REPLACED_CLIENT_SERVERS", client_servers) )
+            elif line.find("REPLACED_WEB_SERVERS") >= 0:
+                new_f.write( line.replace("REPLACED_WEB_SERVERS", web_servers) )
+            elif line.find("REPLACED_APP_SERVERS") >= 0:
+                new_f.write( line.replace("REPLACED_APP_SERVERS", app_servers) )
+            elif line.find("REPLACED_CJDBC_CONTROLLER") >= 0:
+                new_f.write( line.replace("REPLACED_CJDBC_CONTROLLER", cjdbc_controller) )
+            elif line.find("REPLACED_DB_SERVERS") >= 0:
+                new_f.write( line.replace("REPLACED_DB_SERVERS", database_servers) )
+            elif line.find("REPLACED_CLIENTS_PER_NODE") >= 0:
+                new_f.write( line.replace("REPLACED_CLIENTS_PER_NODE", "200 400 800 1600 3200") )
+            else:
+                new_f.write(line)
+    if os.path.exists("rubbos.conf") == False:
+        return False
+
+    cmd = "sudo chmod 0600 " + Bottlenecks_repo_dir + "/utils/infra_setup/bottlenecks_key/bottlenecks_key"
+    subprocess.call(cmd, shell=True)
+    ssh_args = "-o StrictHostKeyChecking=no -o BatchMode=yes -i " + Bottlenecks_repo_dir + "/utils/infra_setup/bottlenecks_key/bottlenecks_key "
+
+    print "############### Test #################"
+    cmd = 'ssh-keygen -f "/root/.ssh/known_hosts" -R ' + control_public_ip
+    subprocess.call(cmd, shell=True)
+    print "## Ping test:"
+    cmd = "ping -c 5 " + control_public_ip
+    print cmd
+    subprocess.call(cmd, shell=True)
+    print "## ssh date test:"
+    cmd = "ssh " + ssh_args + " ubuntu@" + control_public_ip + ' "date"'
+    print cmd
+    subprocess.call(cmd, shell=True)
+    print "## neutruon net-list:"
+    subprocess.call("neutron net-list", shell=True)
+    print "## nova list:"
+    subprocess.call("nova list", shell=True)
+    print "############### Test #################"
+
+    cmd = "scp " + ssh_args + "rubbos.conf ubuntu@" + control_public_ip + ":/home/ubuntu/"
+    print "Exec shell: " + cmd
+    subprocess.call(cmd, shell=True)
+
+    cmd = "scp " + ssh_args + Bottlenecks_repo_dir + "/testsuites/rubbos/puppet_manifests/internal/run_rubbos_internal.sh ubuntu@" + control_public_ip + ":/home/ubuntu/"
+    print "Exec shell: " + cmd
+    subprocess.call(cmd, shell=True)
+
+    # call remote run_rubbos_internal.sh
+    cmd = "ssh " + ssh_args + " ubuntu@" + control_public_ip + ' "sudo /home/ubuntu/run_rubbos_internal.sh /home/ubuntu/rubbos.conf /home/ubuntu/btnks-results" '
+    print "Exec shell: " + cmd
+    subprocess.call(cmd, shell=True)
+    cmd = "scp " + ssh_args + " ubuntu@" + control_public_ip + ":/home/ubuntu/btnks-results/rubbos.out ./rubbos.out"
+    print "Exec shell: " + cmd
+    subprocess.call(cmd, shell=True)
+    if os.path.exists("rubbos.out") == False:
+        print "Failed to fetch results from the rubbos_control node!"
+        return False
+
+    with open("rubbos.out") as f:
+        lines = f.readlines()
+        print "Rubbos results:"
+        for line in lines:
+            print line
+    return True
 
 def main():
     global Heat_template
     global Bottlenecks_repo_dir
     global image_url
-    Bottlenecks_repo_dir = "/tmp/opnfvrepo/bottlenecks"
-    #Bottlenecks_repo_dir = "/root/wyg/bottlenecks"       # Test dir in local env
-    image_url = 'http://artifacts.opnfv.org/bottlenecks/rubbos/bottlenecks-trusty-server.img'
+    Bottlenecks_repo_dir = "/home/opnfv/bottlenecks"      # same in Dockerfile, docker directory
+
+    image_url = 'http://artifacts.opnfv.org/bottlenecks/rubbos/trusty-server-cloudimg-amd64-btnks.img'
+    #image_url = 'http://artifacts.opnfv.org/bottlenecks/rubbos/bottlenecks-trusty-server.img'
 
     if not (args.conf):
        logger.error("Configuration files are not set for testcase")
@@ -205,10 +335,21 @@ def main():
     else:
        Heat_template = args.conf
 
+    master_user_data=""
+    agent_user_data=""
+    with open(Bottlenecks_repo_dir+"/utils/infra_setup/user_data/p-master-user-data") as f:
+        master_user_data=f.read()
+    master_user_data = master_user_data.replace('REPLACED_PUPPET_MASTER_SERVER','rubbos-control')
+    with open(Bottlenecks_repo_dir+"/utils/infra_setup/user_data/p-agent-user-data") as f:
+        agent_user_data=f.read()
+    agent_user_data = agent_user_data.replace('REPLACED_PUPPET_MASTER_SERVER','rubbos-control')
+
     parameters={'image': 'bottlenecks_rubbos_image',
                 'key_name': 'bottlenecks_rubbos_keypair',
-                'flavor': 'm1.small',
-                'public_net': 'ext-net'}
+                'flavor': 'bottlenecks_rubbos_flavor',
+                'public_net': os.environ.get('EXTERNAL_NET'),
+                'master_user_data': master_user_data,
+                'agent_user_data': agent_user_data }
 
     print "Heat_template_file: " + Heat_template
     print "parameters:\n" + str(parameters)
@@ -230,6 +371,12 @@ def main():
         print "Cannot create instances, as Failed to create image(s)."
         exit (-1)
 
+    print "Wait 150 seconds after stack creation........."
+    time.sleep(150)
+
+    reboot_instances()
+    time.sleep(30)
+
     rubbos_run()
     rubbos_env_cleanup()