Fix broken call to re.search()
[sdnvpn.git] / sdnvpn / lib / utils.py
index 00d0fa7..98a1e87 100644 (file)
@@ -7,12 +7,16 @@
 #
 # http://www.apache.org/licenses/LICENSE-2.0
 #
+import os
 import sys
 import time
+import requests
+import re
+import subprocess
 
 import functest.utils.functest_logger as ft_logger
 import functest.utils.openstack_utils as os_utils
-import re
+from opnfv.deployment.factory import Factory as DeploymentFactory
 
 from sdnvpn.lib import config as sdnvpn_config
 
@@ -20,6 +24,9 @@ logger = ft_logger.Logger("sndvpn_test_utils").getLogger()
 
 common_config = sdnvpn_config.CommonConfig()
 
+ODL_USER = 'admin'
+ODL_PASS = 'admin'
+
 
 def create_net(neutron_client, name):
     logger.debug("Creating network %s", name)
@@ -47,7 +54,7 @@ def create_subnet(neutron_client, name, cidr, net_id):
 
 def create_network(neutron_client, net, subnet1, cidr1,
                    router, subnet2=None, cidr2=None):
-    """Network assoc will not work for networks/subnets created by this function.
+    """Network assoc won't work for networks/subnets created by this function.
 
     It is an ODL limitation due to it handling routers as vpns.
     See https://bugs.opendaylight.org/show_bug.cgi?id=6962"""
@@ -195,6 +202,43 @@ def generate_userdata_with_ssh(ips_array):
     return (u1 + u2)
 
 
+def get_installerHandler():
+    installer_type = str(os.environ['INSTALLER_TYPE'].lower())
+    installer_ip = get_installer_ip()
+
+    if installer_type not in ["fuel", "apex"]:
+        raise ValueError("%s is not supported" % installer_type)
+    else:
+        if installer_type in ["apex"]:
+            developHandler = DeploymentFactory.get_handler(
+                installer_type,
+                installer_ip,
+                'root',
+                pkey_file="/root/.ssh/id_rsa")
+
+        if installer_type in ["fuel"]:
+            developHandler = DeploymentFactory.get_handler(
+                installer_type,
+                installer_ip,
+                'root',
+                'r00tme')
+        return developHandler
+
+
+def get_nodes():
+    developHandler = get_installerHandler()
+    return developHandler.get_nodes()
+
+
+def get_installer_ip():
+    return str(os.environ['INSTALLER_IP'])
+
+
+def get_instance_ip(instance):
+    instance_ip = instance.networks.itervalues().next()[0]
+    return instance_ip
+
+
 def wait_for_instance(instance):
     logger.info("Waiting for instance %s to get a DHCP lease..." % instance.id)
     # The sleep this function replaced waited for 80s
@@ -301,3 +345,88 @@ def open_icmp_ssh(neutron_client, security_group_id):
                                   security_group_id,
                                   'tcp',
                                   80, 80)
+
+
+def open_bgp_port(neutron_client, security_group_id):
+    os_utils.create_secgroup_rule(neutron_client,
+                                  security_group_id,
+                                  'tcp',
+                                  179, 179)
+
+
+def exec_cmd(cmd, verbose):
+    success = True
+    logger.debug("Executing '%s'" % cmd)
+    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
+                         stderr=subprocess.STDOUT)
+    output = ""
+    for line in iter(p.stdout.readline, b''):
+        output += line
+
+    if verbose:
+        logger.debug(output)
+
+    p.stdout.close()
+    returncode = p.wait()
+    if returncode != 0:
+        logger.error("Command %s failed to execute." % cmd)
+        success = False
+
+    return output, success
+
+
+def check_odl_fib(ip, controller_ip):
+    """Check that there is an entry in the ODL Fib for `ip`"""
+    url = "http://" + controller_ip + \
+          ":8181/restconf/config/odl-fib:fibEntries/"
+    logger.debug("Querring '%s' for FIB entries", url)
+    res = requests.get(url, auth=(ODL_USER, ODL_PASS))
+    if res.status_code != 200:
+        logger.error("OpenDaylight response status code: %s", res.status_code)
+        return False
+    logger.debug("Checking whether '%s' is in the OpenDaylight FIB"
+                 % controller_ip)
+    logger.debug("OpenDaylight FIB: \n%s" % res.text)
+    return ip in res.text
+
+
+def run_odl_cmd(odl_node, cmd):
+    '''Run a command in the OpenDaylight Karaf shell
+
+    This is a bit flimsy because of shell quote escaping, make sure that
+    the cmd passed does not have any top level double quotes or this
+    function will break.
+
+    The /dev/null is used because client works, but outputs something
+    that contains "ERROR" and run_cmd doesn't like that.
+
+    '''
+    karaf_cmd = '/opt/opendaylight/bin/client "%s" 2>/dev/null' % cmd
+    return odl_node.run_cmd(karaf_cmd)
+
+
+def wait_for_cloud_init(instance):
+    success = True
+    # ubuntu images take a long time to start
+    tries = 20
+    sleep_time = 30
+    while tries > 0:
+        instance_log = instance.get_console_output()
+        if "Failed to run module" in instance_log:
+            success = False
+            logger.error("Cloud init failed to run. Reason: %s",
+                         instance_log)
+            break
+        if re.search(r"Cloud-init v. .+ finished at", instance_log):
+            success = True
+            break
+        time.sleep(sleep_time)
+        tries = tries - 1
+
+    if tries == 0:
+        logger.error("Cloud init timed out"
+                     ". Reason: %s",
+                     instance_log)
+        success = False
+
+    return success