Added more logs to track better errors
[functest.git] / testcases / features / sfc / sfc.py
index c84810e..122ed5d 100755 (executable)
@@ -27,7 +27,7 @@ HOME = os.environ['HOME'] + "/"
 
 VM_BOOT_TIMEOUT = 180
 INSTANCE_NAME = "client"
-FLAVOR = "m1.small"
+FLAVOR = "custom"
 IMAGE_NAME = "sf_nsh_colorado"
 IMAGE_FILENAME = "sf_nsh_colorado.qcow2"
 IMAGE_FORMAT = "qcow2"
@@ -52,13 +52,27 @@ TACKER_SCRIPT = 'sfc_tacker.bash'
 TEARDOWN_SCRIPT = "sfc_teardown.bash"
 TACKER_CHANGECLASSI = "sfc_change_classi.bash"
 
+ssh_options = '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
+
+
+def check_ssh(ip):
+    cmd = "sshpass -p opnfv ssh " + ssh_options + " -q " + ip + " exit"
+    success = subprocess.call(cmd, shell=True) == 0
+    if not success:
+        logger.debug("Wating for SSH connectivity in SF with IP: %s" % ip)
+    return success
+
 
 def main():
 
     # Allow any port so that tacker commands reaches the server.
     # This will be deleted when tacker is included in OPNFV installation
 
-    ssh_options = '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
+    status = "PASS"
+    failures = 0
+    start_time = time.time()
+    json_results = {}
+
     contr_cmd = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
                  " 'fuel node'|grep controller|awk '{print $10}'")
     logger.info("Executing script to get ip_server: '%s'" % contr_cmd)
@@ -68,19 +82,14 @@ def main():
                                stderr=subprocess.PIPE)
     ip_server = process.stdout.readline().rstrip()
 
-    contr_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
-                  " 'fuel node'|grep compute|awk '{print $10}'")
-    logger.info("Executing script to get ip_compute: '%s'" % contr_cmd2)
-    process = subprocess.Popen(contr_cmd2,
-                               shell=True,
-                               stdout=subprocess.PIPE,
-                               stderr=subprocess.PIPE)
-    ip_compute = process.stdout.readline().rstrip()
-
     iptable_cmd1 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
                     " ssh " + ip_server + " iptables -P INPUT ACCEPT ")
     iptable_cmd2 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
                     " ssh " + ip_server + " iptables -t nat -P INPUT ACCEPT ")
+    iptable_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
+                    " ssh " + ssh_options + " " + ip_server +
+                    " iptables -A INPUT -m state"
+                    " --state NEW,ESTABLISHED,RELATED -j ACCEPT")
 
     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd1)
     subprocess.call(iptable_cmd1, shell=True, stderr=subprocess.PIPE)
@@ -88,6 +97,9 @@ def main():
     logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd2)
     subprocess.call(iptable_cmd2, shell=True, stderr=subprocess.PIPE)
 
+    logger.info("Changing firewall policy in controller: '%s'" % iptable_cmd3)
+    subprocess.call(iptable_cmd3, shell=True, stderr=subprocess.PIPE)
+
 # Getting the different clients
 
     nova_client = os_utils.get_nova_client()
@@ -128,7 +140,33 @@ def main():
     sg_id = os_utils.create_security_group_full(neutron_client,
                                                 SECGROUP_NAME, SECGROUP_DESCR)
 
-    # boot INTANCE
+    secgroups = os_utils.get_security_groups(neutron_client)
+
+    for sg in secgroups:
+        os_utils.create_secgroup_rule(neutron_client, sg['id'],
+                                      'ingress', 'tcp',
+                                      port_range_min=22,
+                                      port_range_max=22)
+        os_utils.create_secgroup_rule(neutron_client, sg['id'],
+                                      'egress', 'tcp',
+                                      port_range_min=22,
+                                      port_range_max=22)
+        os_utils.create_secgroup_rule(neutron_client, sg['id'],
+                                      'ingress', 'tcp',
+                                      port_range_min=80,
+                                      port_range_max=80)
+        os_utils.create_secgroup_rule(neutron_client, sg['id'],
+                                      'egress', 'tcp',
+                                      port_range_min=80,
+                                      port_range_max=80)
+
+    _, custom_flv_id = os_utils.get_or_create_flavor(
+        'custom', 1500, 10, 1, public=True)
+    if not custom_flv_id:
+        logger.error("Failed to create custom flavor")
+        sys.exit(1)
+
+    # boot INSTANCE
     logger.info("Creating instance '%s'..." % INSTANCE_NAME)
     logger.debug(
         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
@@ -136,7 +174,8 @@ def main():
     instance = os_utils.create_instance_and_wait_for_active(FLAVOR,
                                                             image_id,
                                                             network_id,
-                                                            INSTANCE_NAME)
+                                                            INSTANCE_NAME,
+                                                            av_zone='nova')
 
     if instance is None:
         logger.error("Error while booting instance.")
@@ -169,14 +208,15 @@ def main():
 # STARTING SECOND VM (server) ###
 
     # boot INTANCE
-    logger.info("Creating instance '%s'..." % INSTANCE_NAME)
+    logger.info("Creating instance '%s'..." % INSTANCE_NAME_2)
     logger.debug(
         "Configuration:\n name=%s \n flavor=%s \n image=%s \n "
-        "network=%s \n" % (INSTANCE_NAME, FLAVOR, image_id, network_id))
+        "network=%s \n" % (INSTANCE_NAME_2, FLAVOR, image_id, network_id))
     instance_2 = os_utils.create_instance_and_wait_for_active(FLAVOR,
                                                               image_id,
                                                               network_id,
-                                                              INSTANCE_NAME_2)
+                                                              INSTANCE_NAME_2,
+                                                              av_zone='nova')
 
     if instance_2 is None:
         logger.error("Error while booting instance.")
@@ -253,6 +293,27 @@ def main():
 
     logger.debug("Floating IPs for SFs: %s..." % ips)
 
+    # Check SSH connectivity to VNFs
+    r = 0
+    retries = 100
+    check = [False, False]
+
+    logger.info("Checking SSH connectivity to the SFs with ips %s" % str(ips))
+    while r < retries and not all(check):
+        try:
+            check = [check_ssh(ips[0]), check_ssh(ips[1])]
+        except Exception:
+            logger.exception("SSH check failed")
+            check = [False, False]
+        time.sleep(3)
+        r += 1
+
+    if not all(check):
+        logger.error("Cannot establish SSH connection to the SFs")
+        sys.exit(1)
+
+    logger.info("SSH connectivity to the SFs established")
+
     # SSH TO START THE VXLAN_TOOL ON SF1
     logger.info("Configuring the SFs")
     try:
@@ -304,20 +365,6 @@ def main():
     except Exception:
         logger.exception("vxlan_tool not started in SF2")
 
-    # SSH to modify the classification flows in compute
-
-    contr_cmd3 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
-                  " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
-    logger.info("Executing script to modify the classi: '%s'" % contr_cmd3)
-    process = subprocess.Popen(contr_cmd3,
-                               shell=True,
-                               stdout=subprocess.PIPE)
-
-    logger.info("Waiting for 60 seconds before TEST")
-    for j in range(0, 6):
-        logger.info("Test starting in {0} seconds".format(str((6 - j)*10)))
-        time.sleep(10)
-
     i = 0
 
     # SSH TO EXECUTE cmd_client
@@ -333,10 +380,13 @@ def main():
             logger.info('\033[92m' + "TEST 1 [PASSED] "
                         "==> SSH BLOCKED" + '\033[0m')
             i = i + 1
+            json_results.update({"Test 1: SSH Blocked": "Passed"})
         else:
             logger.error('\033[91m' + "TEST 1 [FAILED] "
                          "==> SSH NOT BLOCKED" + '\033[0m')
-            return
+            status = "FAIL"
+            json_results.update({"Test 1: SSH Blocked": "Failed"})
+            failures += 1
     except:
         logger.debug("Waiting for %s..." % floatip_client)
         time.sleep(6)
@@ -353,10 +403,13 @@ def main():
             logger.info('\033[92m' + "TEST 2 [PASSED] "
                         "==> HTTP WORKS" + '\033[0m')
             i = i + 1
+            json_results.update({"Test 2: HTTP works": "Passed"})
         else:
             logger.error('\033[91m' + "TEST 2 [FAILED] "
                          "==> HTTP BLOCKED" + '\033[0m')
-            return
+            status = "FAIL"
+            json_results.update({"Test 2: HTTP works": "Failed"})
+            failures += 1
     except:
         logger.debug("Waiting for %s..." % floatip_client)
         time.sleep(6)
@@ -369,16 +422,7 @@ def main():
     subprocess.call(tacker_classi, shell=True)
 
     logger.info("Wait for ODL to update the classification rules in OVS")
-    time.sleep(10)
-
-    # SSH to modify the classification flows in compute
-
-    contr_cmd4 = ("sshpass -p r00tme ssh " + ssh_options + " root@10.20.0.2"
-                  " 'ssh " + ip_compute + " 'bash correct_classifier.bash''")
-    logger.info("Executing script to modify the classi: '%s'" % contr_cmd4)
-    process = subprocess.Popen(contr_cmd4,
-                               shell=True,
-                               stdout=subprocess.PIPE)
+    time.sleep(100)
 
     # SSH TO EXECUTE cmd_client
 
@@ -389,13 +433,16 @@ def main():
         (stdin, stdout, stderr) = ssh.exec_command(command)
 
         if "timed out" in stdout.readlines()[0]:
-            logger.info('\033[92m' + "TEST 3 [WORKS] "
+            logger.info('\033[92m' + "TEST 3 [PASSED] "
                         "==> HTTP BLOCKED" + '\033[0m')
             i = i + 1
+            json_results.update({"Test 3: HTTP Blocked": "Passed"})
         else:
             logger.error('\033[91m' + "TEST 3 [FAILED] "
                          "==> HTTP NOT BLOCKED" + '\033[0m')
-            return
+            status = "FAIL"
+            json_results.update({"Test 3: HTTP Blocked": "Failed"})
+            failures += 1
     except:
         logger.debug("Waiting for %s..." % floatip_client)
         time.sleep(6)
@@ -409,13 +456,16 @@ def main():
         (stdin, stdout, stderr) = ssh.exec_command(command)
 
         if "succeeded" in stdout.readlines()[0]:
-            logger.info('\033[92m' + "TEST 4 [WORKS] "
+            logger.info('\033[92m' + "TEST 4 [PASSED] "
                         "==> SSH WORKS" + '\033[0m')
             i = i + 1
+            json_results.update({"Test 4: SSH works": "Passed"})
         else:
             logger.error('\033[91m' + "TEST 4 [FAILED] "
                          "==> SSH BLOCKED" + '\033[0m')
-            return
+            status = "FAIL"
+            json_results.update({"Test 4: SSH works": "Failed"})
+            failures += 1
     except:
         logger.debug("Waiting for %s..." % floatip_client)
         time.sleep(6)
@@ -426,21 +476,20 @@ def main():
             logger.info('\033[92m' + "SFC TEST WORKED"
                         " :) \n" + '\033[0m')
 
-    # TODO report results to DB
-    # functest_utils.logger_test_results("SFC",
-    # "odl-sfc",
-    # status, details)
-    # see doctor, promise, domino, ...
-    # if args.report:
-        # logger.info("Pushing odl-SFC results")
-        # functest_utils.push_results_to_db("functest",
-        #                                  "odl-sfc",
-        #                                  start_time,
-        #                                  stop_time,
-        #                                  status,
-        #                                  details)
-
-    sys.exit(0)
+    if args.report:
+        stop_time = time.time()
+        json_results.update({"tests": "4", "failures": int(failures)})
+        logger.debug("Promise Results json: " + str(json_results))
+        ft_utils.push_results_to_db("sfc",
+                                    "functest-odl-sfc",
+                                    start_time,
+                                    stop_time,
+                                    status,
+                                    json_results)
+    if status == "PASS":
+        sys.exit(0)
+    else:
+        sys.exit(1)
 
 if __name__ == '__main__':
     main()