FIX: Add SRIOV cleanup
[csit.git] / resources / tools / scripts / topo_reservation.py
index a04709b..e7e1ff6 100755 (executable)
@@ -28,6 +28,7 @@ from resources.libraries.python.ssh import exec_cmd
 
 
 RESERVATION_DIR = "/tmp/reservation_dir"
+RESERVATION_NODE = "TG"
 
 
 def diag_cmd(node, cmd):
@@ -38,9 +39,9 @@ def diag_cmd(node, cmd):
     :type ssh: dict
     :type cmd: str
     """
-    print "+", cmd
+    print('+ {cmd}'.format(cmd=cmd))
     _, stdout, _ = exec_cmd(node, cmd)
-    print stdout
+    print(stdout)
 
 
 def main():
@@ -53,27 +54,24 @@ def main():
     2. List contents of test.url file in the dir.
     3. Create reservation dir.
     4. Touch file according to -r option.
-    5. Put -u option string to file test.url
-    From these 5 steps, 1 and 2 are performed always, their RC ignored.
+    From these 4 steps, 1 and 2 are performed always, their RC ignored.
     RC of step 3 gives the overall result.
-    If the result is success, steps 4-5 are executed without any output,
+    If the result is success, step 4 is executed without any output,
     their RC is ignored.
 
-    The two files in reservation dir are there for reporting
-    which test run holds the reservation, so people can manually fix the testbed
-    if the rest run has been aborted, or otherwise failed to unregister.
-
-    The two files have different audiences.
-
-    The URL content is useful for people scheduling their test runs
-    and wondering why the reservation takes so long.
-    For them, a URL (if available) to copy and paste into browser
-    to see which test runs are blocking testbeds is the most convenient.
-
     The "run tag" as a filename is useful for admins accessing the testbed
     via a graphical terminal, which does not allow copying of text,
     as they need less keypresses to identify the test run holding the testbed.
     Also, the listing shows timestamps, which is useful for both audiences.
+
+    This all assumes the target system accepts ssh connections.
+    If it does not, the caller probably wants to stop trying
+    to reserve this system. Therefore this script can return 3 different codes.
+    Return code 0 means the reservation was successful.
+    Return code 1 means the system is inaccessible (or similarly unsuitable).
+    Return code 2 means the system is accessible, but already reserved.
+    The reason unsuitable systems return 1 is because that is also the value
+    Python returns on encountering and unexcepted exception.
     """
     parser = argparse.ArgumentParser()
     parser.add_argument("-t", "--topo", required=True,
@@ -82,8 +80,6 @@ def main():
                         action="store_true")
     parser.add_argument("-r", "--runtag", required=False, default="Unknown",
                         help="Identifier for test run suitable as filename")
-    parser.add_argument("-u", "--url", required=False, default="Unknown",
-                        help="Identifier for test run suitable as URL")
     args = parser.parse_args()
 
     with open(args.topo, "r") as topo_file:
@@ -93,43 +89,40 @@ def main():
     # we are using it, because testing shows SSH access to DUT
     # during test affects its performance (bursts of lost packets).
     try:
-        tgn = topology["TG"]
+        node = topology[RESERVATION_NODE]
     except KeyError:
-        print "Topology file does not contain 'TG' node"
+        print("Topology file does not contain '{node}' node".
+              format(node=RESERVATION_NODE))
         return 1
 
     # For system reservation we use mkdir it is an atomic operation and we can
     # store additional data (time, client_ID, ..) within reservation directory.
     if args.cancel:
-        ret, _, err = exec_cmd(tgn, "rm -r {}".format(RESERVATION_DIR))
+        ret, _, err = exec_cmd(node, "rm -r {dir}".format(dir=RESERVATION_DIR))
         if ret:
-            print "Cancellation unsuccessful:\n{}".format(err)
+            print("Cancellation unsuccessful:\n{err}".format(err=err))
         return ret
     # Before critical section, output can be outdated already.
-    print "Diagnostic commands:"
+    print("Diagnostic commands:")
     # -d and * are to supress "total <size>", see https://askubuntu.com/a/61190
-    diag_cmd(tgn, "ls --full-time -cd '{dir}'/*".format(dir=RESERVATION_DIR))
-    diag_cmd(tgn, "head -1 '{dir}/run.url'".format(dir=RESERVATION_DIR))
-    print "Attempting reservation."
+    diag_cmd(node, "ls --full-time -cd '{dir}'/*".format(dir=RESERVATION_DIR))
+    print("Attempting testbed reservation.")
     # Entering critical section.
-    # TODO: Add optional argument to exec_cmd_no_error to make it
-    # sys.exit(ret) instead raising? We do not want to deal with stacktrace.
-    ret, _, err = exec_cmd(tgn, "mkdir '{dir}'".format(dir=RESERVATION_DIR))
+    ret, _, _ = exec_cmd(node, "mkdir '{dir}'".format(dir=RESERVATION_DIR))
     # Critical section is over.
     if ret:
-        print "Reservation unsuccessful:\n{}".format(err)
-        return ret
+        _, stdo, _ = exec_cmd(node, "ls '{dir}'/*".format(dir=RESERVATION_DIR))
+        print("Testbed already reserved by:\n{stdo}".format(stdo=stdo))
+        return 2
     # Here the script knows it is the only owner of the testbed.
-    print "Success, writing test run info to reservation dir."
-    # TODO: Add optional argument to exec_cmd_no_error to print message
-    # to console instead raising? We do not want to deal with stacktrace.
-    ret2, _, err = exec_cmd(
-        tgn, "touch '{dir}/{runtag}' && ( echo '{url}' > '{dir}/run.url' )"\
-        .format(dir=RESERVATION_DIR, runtag=args.runtag, url=args.url))
-    if ret2:
-        print "Writing test run info failed, but continuing anyway:\n{}".format(
-            err)
-    return ret
+    print("Reservation success, writing additional info to reservation dir.")
+    ret, _, err = exec_cmd(
+        node, "touch '{dir}/{runtag}'"\
+        .format(dir=RESERVATION_DIR, runtag=args.runtag))
+    if ret:
+        print("Writing test run info failed, but continuing anyway:\n{err}".
+              format(err=err))
+    return 0
 
 
 if __name__ == "__main__":