config_functest.py: added create neutron network.
authorjose.lausuch <jose.lausuch@ericsson.com>
Sun, 10 May 2015 23:36:59 +0000 (01:36 +0200)
committerjose.lausuch <jose.lausuch@ericsson.com>
Sun, 10 May 2015 23:41:44 +0000 (01:41 +0200)
vPing.py: some adaptations and bug fixes
JIRA: FUNCTEST-1
JIRA: FUNCTEST-3

Change-Id: Ie8ee80c2ab61904bf4b5025d23034ef0265b509e
Signed-off-by: jose.lausuch <jose.lausuch@ericsson.com>
testcases/config_functest.py
testcases/functest.yaml
testcases/vPing/CI/libraries/vPing.py

index dd9af06..05376be 100644 (file)
@@ -11,6 +11,8 @@
 import re, json, os, urllib2, argparse, logging, shutil, subprocess, yaml
 from git import Repo
 
+from neutronclient.v2_0 import client
+
 actions = ['start', 'check', 'clean']
 
 
@@ -52,8 +54,9 @@ if not os.path.exists(dest):
     logger.info("functest.yaml stored in %s" % dest)
 else:
     logger.info("functest.yaml found in %s" % dest)
-    
-with open('functest.yaml') as f:
+
+
+with open('./functest.yaml') as f:
     functest_yaml = yaml.safe_load(f)
 f.close()
 
@@ -67,6 +70,12 @@ RALLY_INSTALLATION_DIR = HOME + functest_yaml.get("general").get("directories").
 BENCH_TESTS_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_scn")
 VPING_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_vping")
 ODL_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_odl")
+NEUTRON_PUBLIC_NAME = functest_yaml.get("general").get("openstack").get("neutron_public_net_name")
+NEUTRON_NET_NAME = functest_yaml.get("general").get("openstack").get("neutron_net_name")
+NEUTRON_SUBNET_NAME = functest_yaml.get("general").get("openstack").get("neutron_subnet_name")
+NEUTRON_RANGE = functest_yaml.get("general").get("openstack").get("neutron_subnet_range")
+ROUTER_NAME = functest_yaml.get("general").get("openstack").get("neutron_router_name")
+
 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")
@@ -74,26 +83,31 @@ IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
 IMAGE_DOWNLOAD_PATH = FUNCTEST_BASE_DIR + IMAGE_FILE_NAME
 
 
-
-
 def config_functest_start():
     """
     Start the functest environment installation
     """
-    if config_functest_check():
-        logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
-        exit(0)
-    elif not check_internet_connectivity():
+    #if config_functest_check():
+    #    logger.info("Functest environment already installed in %s. Nothing to do." %FUNCTEST_BASE_DIR)
+    #    exit(0)
+    if 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
         exit(-1)
+    elif not check_neutron_net(NEUTRON_PUBLIC_NAME):
+        #The public network is normally created by default, no need to create a new one
+        logger.debug("Public network '%s' not found." % NEUTRON_PUBLIC_NAME)
+        logger.error("A public Neutron network is needed for the environment. Please create one.")
+        #TODO: source the credentials in this script
+        exit(-1)
     else:
+        # Clean in case there are left overs
         config_functest_clean()
 
-        logger.info("Starting installationg of functest environment in %s" %FUNCTEST_BASE_DIR)
+        logger.info("Starting installationg of functest environment in %s" % FUNCTEST_BASE_DIR)
         os.makedirs(FUNCTEST_BASE_DIR)
         if not os.path.exists(FUNCTEST_BASE_DIR):
             logger.error("There has been a problem while creating the environment directory.")
@@ -117,6 +131,20 @@ def config_functest_start():
             config_functest_clean()
             exit(-1)
 
+        logger.info("Creating a private Neutron network...")
+        logger.debug("Checking if private network '%s' exists..." % NEUTRON_NET_NAME)
+        #Now: if exists we don't create it again (the clean command does not clean the neutron network)
+        #TODO: this check will not be needed when cleaning the neutron is implemented
+        if check_neutron_net(NEUTRON_NET_NAME):
+            logger.info("Private network '%s' found. No need to create another one." % NEUTRON_NET_NAME)
+        else:
+            logger.info("Private network '%s' not found. Creating..." % NEUTRON_NET_NAME)
+            if not create_neutron_net():
+                logger.error("There has been a problem while creating the Neutron network.")
+                #config_functest_clean()
+                exit(-1)
+
+
         logger.info("Donwloading image...")
         if not download_url_with_progress(IMAGE_URL, FUNCTEST_BASE_DIR):
             logger.error("There has been a problem while downloading the image.")
@@ -137,27 +165,66 @@ def config_functest_check():
     """
     Check if the functest environment is properly installed
     """
+    errors_all = False
+
     logger.info("Checking current functest configuration...")
 
+
     logger.debug("Checking directories...")
+    errors = False
     dirs = [FUNCTEST_BASE_DIR, RALLY_INSTALLATION_DIR, RALLY_REPO_DIR, RALLY_TEST_DIR, BENCH_TESTS_DIR, VPING_DIR, ODL_DIR]
     for dir in dirs:
         if not os.path.exists(dir):
-            logger.debug("The directory %s does not exist." %dir)
-            return False
-        logger.debug("   %s found" % 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("...OK")
     logger.debug("Checking Rally deployment...")
     if not check_rally():
-        logger.debug("Rally deployment not found.")
-        return False
-    logger.debug("...OK")
+        logger.debug("Rally deployment NOT found.")
+        errors_all = True
+        logger.debug("...FAIL")
+    else:
+        logger.debug("...OK")
+
+
+    logger.debug("Checking Neutron...")
+    errors = False
+    if not check_neutron_net(NEUTRON_NET_NAME):
+        logger.debug("   Private network '%s' NOT found." % NEUTRON_NET_NAME)
+        errors = True
+        errors_all = True
+    else:
+        logger.debug("   Private network '%s' found." % NEUTRON_NET_NAME)
+
+    if not check_neutron_net(NEUTRON_PUBLIC_NAME):
+        logger.debug("   Public network '%s' NOT found." % NEUTRON_PUBLIC_NAME)
+        errors = True
+        errors_all = True
+    else:
+        logger.debug("   Public network '%s' found." % NEUTRON_PUBLIC_NAME)
+
+    if not errors:
+        logger.debug("...OK")
+    else:
+        logger.debug("...FAIL")
+
 
     logger.debug("Checking Image...")
+    errors = False
     if not os.path.isfile(IMAGE_DOWNLOAD_PATH):
-        return False
-    logger.debug("   Image file found in %s" %IMAGE_DOWNLOAD_PATH)
+        logger.debug("   Image file '%s' NOT found." % IMAGE_DOWNLOAD_PATH)
+        errors = True
+        errors_all = True
+    else:
+        logger.debug("   Image file found in %s" % IMAGE_DOWNLOAD_PATH)
 
     cmd="glance image-list | grep " + IMAGE_NAME
     FNULL = open(os.devnull, 'w');
@@ -166,14 +233,22 @@ def config_functest_check():
     #if the command does not exist or there is no glance image
     line = p.stdout.readline()
     if line == "":
-        logger.debug("   Glance image not found")
-        return False
-    logger.debug("   Glance image found")
-    logger.debug("...OK")
+        logger.debug("   Glance image NOT found.")
+        errors = True
+        errors_all = True
+    else:
+        logger.debug("   Glance image found.")
 
-    #TODO: check OLD environment setup
+    if not errors:
+        logger.debug("...OK")
+    else:
+        logger.debug("...FAIL")
 
-    return True
+    #TODO: check OLD environment setup
+    if errors_all:
+        return False
+    else:
+        return True
 
 
 
@@ -192,6 +267,10 @@ def config_functest_clean():
         cmd = "sudo rm -rf " + FUNCTEST_BASE_DIR #need to be sudo, not possible with rmtree
         execute_command(cmd)
 
+    #logger.debug("Deleting Neutron network %s" % NEUTRON_NET_NAME)
+    #if not delete_neutron_net() :
+    #    logger.error("Error deleting the network. Remove it manually.")
+
     logger.debug("Deleting glance images")
     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
     p = os.popen(cmd,"r")
@@ -204,6 +283,9 @@ def config_functest_clean():
     return True
 
 
+
+
+
 def install_rally():
     if check_rally():
         logger.info("Rally is already installed.")
@@ -298,6 +380,23 @@ def check_credentials():
     return True
 
 
+def get_credentials():
+    d = {}
+    d['username'] = os.environ['OS_USERNAME']
+    d['password'] = os.environ['OS_PASSWORD']
+    d['auth_url'] = os.environ['OS_AUTH_URL']
+    d['tenant_name'] = os.environ['OS_TENANT_NAME']
+    return d
+
+def get_nova_credentials():
+    d = {}
+    d['username'] = os.environ['OS_USERNAME']
+    d['api_key'] = os.environ['OS_PASSWORD']
+    d['auth_url'] = os.environ['OS_AUTH_URL']
+    d['project_id'] = os.environ['OS_TENANT_NAME']
+    return d
+
+
 def download_tests():
     os.makedirs(VPING_DIR)
     os.makedirs(ODL_DIR)
@@ -340,6 +439,93 @@ def download_tests():
     return True
 
 
+def create_neutron_net():
+    credentials = get_credentials()
+    neutron = client.Client(**credentials)
+    try:
+        neutron.format = 'json'
+        logger.debug('Creating Neutron network %s...' % NEUTRON_NET_NAME)
+        json_body = {'network': {'name': NEUTRON_NET_NAME,
+                    'admin_state_up': True}}
+        netw = neutron.create_network(body=json_body)
+        net_dict = netw['network']
+        network_id = net_dict['id']
+        logger.debug("Network '%s' created successfully" % network_id)
+
+        logger.debug('Creating Subnet....')
+        json_body = {'subnets': [{'cidr': NEUTRON_RANGE,
+                           'ip_version': 4, 'network_id': network_id}]}
+        subnet = neutron.create_subnet(body=json_body)
+        logger.debug("Subnet '%s' created successfully" % subnet)
+
+        logger.debug('Creating Router...')
+        json_body = {'router': {'name': ROUTER_NAME, 'admin_state_up': True}}
+        router = neutron.create_router(json_body)
+        logger.debug("Router '%s' created successfully" % router)
+        router_id = router['router']['id']
+
+        logger.debug('Creating Port')
+        json_body = {'port': {
+         'admin_state_up': True,
+         'device_id': router_id,
+         'name': 'port1',
+         'network_id': network_id,
+        }}
+        response = neutron.create_port(body=json_body)
+        logger.debug("Port created successfully.")
+
+        logger.debug('Setting up gateway...')
+        public_network_id = get_network_id(neutron,NEUTRON_PUBLIC_NAME)
+        json_body = {'network_id': public_network_id, 'enable_snat' :  True}
+        gateway = neutron.add_gateway_router(router_id,body=json_body)
+        logger.debug("Gateway '%s' added successfully" % gateway)
+    except:
+        logger.error("There has been a problem when creating the Neutron network.")
+        return False
+    finally:
+        logger.info("Neutron network created successfully.")
+        return True
+
+    return False
+
+def get_network_id(neutron_client, network_name):
+    networks = neutron_client.list_networks()['networks']
+    id  = ''
+    for n in networks:
+        if n['name'] == network_name:
+            id = n['id']
+            break
+    return id
+
+def check_neutron_net(net_name):
+    credentials = get_credentials()
+    neutron = client.Client(**credentials)
+    for network in neutron.list_networks()['networks']:
+        if network['name'] == net_name :
+            for subnet in network['subnets']:
+                return True
+    return False
+
+def delete_neutron_net():
+    #TODO: remove router, ports
+    credentials = get_credentials()
+    neutron = client.Client(**credentials)
+    try:
+        #https://github.com/isginf/openstack_tools/blob/master/openstack_remove_tenant.py
+        for network in neutron.list_networks()['networks']:
+            if network['name'] == NEUTRON_NET_NAME :
+                for subnet in network['subnets']:
+                    print "Deleting subnet " + subnet
+                    neutron.delete_subnet(subnet)
+                print "Deleting network " + network['name']
+                neutron.delete_neutron_net(network['id'])
+    finally:
+        return True
+    return False
+
+
+
+
 
 def create_glance_image(path,name,disk_format):
     """
@@ -350,6 +536,9 @@ def create_glance_image(path,name,disk_format):
     return True
 
 
+
+
+
 def download_url(url, dest_path):
     """
     Download a file to a destination path given a URL
index c103834..2f34949 100644 (file)
@@ -1,7 +1,7 @@
 ---
 general:
     directories:
-        dir_functest:   .functest/
+        dir_functest:   .functest/ #DONT CHANGE
         dir_rally_repo: .functest/Rally_repo/
         dir_rally:      .functest/Rally_test/
         dir_rally_scn:  .functest/Rally_test/scenarios/
@@ -13,12 +13,16 @@ general:
         image_name: Ubuntu14.04
         image_url:  https://cloud-images.ubuntu.com/trusty/current/trusty-server-cloudimg-amd64-disk1.img
         image_disk_format:  raw
+        #Public network. Must exist already.
+        neutron_public_net_name: net04_ext
+        #Private network for functest. Will be created by config_functest.py
         neutron_net_name: functest-net
         neutron_subnet_name: functest-subnet
-        neutro_subnet_range: 192.168.120.0/24
+        neutron_subnet_range: 192.168.120.0/24
         neutron_subnet_start: 192.168.120.2
         neutron_subnet_end: 192.168.120.254
         neutron_subnet_gateway: 192.168.120.254
+        neutron_router_name: functest-router
 vping:
     ping_timeout:   200
     vm_flavor: m1.small #adapt to your environment
index d140eee..b81ebb8 100644 (file)
@@ -22,8 +22,8 @@ import cinderclient.v1.client as cinderclient
 pp = pprint.PrettyPrinter(indent=4)
 
 EXIT_CODE = -1
-
-with open('../functest.yaml') as f:
+HOME = os.environ['HOME']+"/"
+with open(HOME+'.functest/functest.yaml') as f:
     functest_yaml = yaml.safe_load(f)
 f.close()
 
@@ -145,7 +145,7 @@ def main():
             logger.info("Network found '%s'" %net.human_id)
             network_found = True
     if not network_found:
-        logger.error("ERROR: Neutron network %s not found." % NEUTRON_NET_NAME)
+        logger.error("Neutron network %s not found." % NEUTRON_NET_NAME)
         logger.info("Available networks are: ")
         pMsg(nova.networks.list())
         exit(-1)