3 # Copyright (c) 2022 Cisco and/or its affiliates.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
16 """Script managing reservation and un-reservation of testbeds.
18 This script provides simple reservation mechanism to avoid
19 simultaneous use of nodes listed in topology file.
20 As source of truth, TG node from the topology file is used.
27 from resources.libraries.python.ssh import exec_cmd
30 RESERVATION_DIR = u"/tmp/reservation_dir"
31 RESERVATION_NODE = u"TG"
34 def diag_cmd(node, cmd):
35 """Execute cmd, print cmd and stdout, ignore stderr and rc; return None.
37 :param node: Node object as parsed from topology file to execute cmd on.
38 :param cmd: Command to execute.
43 _, stdout, _ = exec_cmd(node, cmd)
48 """Parse arguments, perform the action, write useful output, propagate RC.
50 If the intended action is cancellation, reservation dir is deleted.
52 If the intended action is reservation, the list is longer:
53 1. List contents of reservation dir.
54 2. List contents of test.url file in the dir.
55 3. Create reservation dir.
56 4. Touch file according to -r option.
57 From these 4 steps, 1 and 2 are performed always, their RC ignored.
58 RC of step 3 gives the overall result.
59 If the result is success, step 4 is executed without any output,
62 The "run tag" as a filename is useful for admins accessing the testbed
63 via a graphical terminal, which does not allow copying of text,
64 as they need less keypresses to identify the test run holding the testbed.
65 Also, the listing shows timestamps, which is useful for both audiences.
67 This all assumes the target system accepts ssh connections.
68 If it does not, the caller probably wants to stop trying
69 to reserve this system. Therefore this script can return 3 different codes.
70 Return code 0 means the reservation was successful.
71 Return code 1 means the system is inaccessible (or similarly unsuitable).
72 Return code 2 means the system is accessible, but already reserved.
73 The reason unsuitable systems return 1 is because that is also the value
74 Python returns on encountering and unexcepted exception.
76 parser = argparse.ArgumentParser()
77 parser.add_argument(u"-t", u"--topo", required=True, help=u"Topology file")
79 u"-c", u"--cancel", help=u"Cancel reservation", action=u"store_true"
82 u"-r", u"--runtag", required=False, default=u"Unknown",
83 help=u"Identifier for test run suitable as filename"
85 args = parser.parse_args()
87 with open(args.topo, u"rt") as topo_file:
88 topology = yaml.safe_load(topo_file.read())[u"nodes"]
90 # Even if TG is not guaranteed to be a Linux host,
91 # we are using it, because testing shows SSH access to DUT
92 # during test affects its performance (bursts of lost packets).
94 node = topology[RESERVATION_NODE]
96 print(f"Topology file does not contain '{RESERVATION_NODE}' node")
99 # For system reservation we use mkdir it is an atomic operation and we can
100 # store additional data (time, client_ID, ..) within reservation directory.
102 ret, _, err = exec_cmd(node, f"rm -r {RESERVATION_DIR}")
103 # If connection is refused, ret==None.
105 print(f"Cancellation unsuccessful:\n{err!r}")
108 # Before critical section, output can be outdated already.
109 print(u"Diagnostic commands:")
110 # -d and * are to suppress "total <size>", see https://askubuntu.com/a/61190
111 diag_cmd(node, f"ls --full-time -cd '{RESERVATION_DIR}'/*")
112 print(u"Attempting testbed reservation.")
113 # Entering critical section.
114 ret, _, _ = exec_cmd(node, f"mkdir '{RESERVATION_DIR}'")
115 # Critical section is over.
117 print(u"Failed to connect to testbed.")
120 _, stdo, _ = exec_cmd(node, f"ls '{RESERVATION_DIR}'/*")
121 print(f"Testbed already reserved by:\n{stdo}")
123 # Here the script knows it is the only owner of the testbed.
124 print(u"Reservation success, writing additional info to reservation dir.")
125 ret, _, err = exec_cmd(
126 node, f"touch '{RESERVATION_DIR}/{args.runtag}'")
128 print(f"Writing test run info failed, but continuing anyway:\n{err!r}")
132 if __name__ == u"__main__":