3 # Copyright (c) 2021 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 as _exec_cmd
30 RESERVATION_DIR = u"/tmp/reservation_dir"
31 RESERVATION_NODE = u"TG"
34 def exec_cmd(node, cmd):
35 """A wrapper around ssh.exec_cmd with disabled JSON export.
37 Using this, maintainers can use "exec_cmd" without worrying
38 about interaction with json export.
40 TODO: Instead this, divide ssh module into reusable and robot-bound parts.
42 :param node: Node object as parsed from topology file to execute cmd on.
43 :param cmd: Command to execute.
46 :returns: RC, Stdout, Stderr.
47 :rtype: Tuple[int, str, str]
49 return _exec_cmd(node, cmd, export=False)
51 def diag_cmd(node, cmd):
52 """Execute cmd, print cmd and stdout, ignore stderr and rc; return None.
54 :param node: Node object as parsed from topology file to execute cmd on.
55 :param cmd: Command to execute.
60 _, stdout, _ = exec_cmd(node, cmd)
65 """Parse arguments, perform the action, write useful output, propagate RC.
67 If the intended action is cancellation, reservation dir is deleted.
69 If the intended action is reservation, the list is longer:
70 1. List contents of reservation dir.
71 2. List contents of test.url file in the dir.
72 3. Create reservation dir.
73 4. Touch file according to -r option.
74 From these 4 steps, 1 and 2 are performed always, their RC ignored.
75 RC of step 3 gives the overall result.
76 If the result is success, step 4 is executed without any output,
79 The "run tag" as a filename is useful for admins accessing the testbed
80 via a graphical terminal, which does not allow copying of text,
81 as they need less keypresses to identify the test run holding the testbed.
82 Also, the listing shows timestamps, which is useful for both audiences.
84 This all assumes the target system accepts ssh connections.
85 If it does not, the caller probably wants to stop trying
86 to reserve this system. Therefore this script can return 3 different codes.
87 Return code 0 means the reservation was successful.
88 Return code 1 means the system is inaccessible (or similarly unsuitable).
89 Return code 2 means the system is accessible, but already reserved.
90 The reason unsuitable systems return 1 is because that is also the value
91 Python returns on encountering and unexcepted exception.
93 parser = argparse.ArgumentParser()
94 parser.add_argument(u"-t", u"--topo", required=True, help=u"Topology file")
96 u"-c", u"--cancel", help=u"Cancel reservation", action=u"store_true"
99 u"-r", u"--runtag", required=False, default=u"Unknown",
100 help=u"Identifier for test run suitable as filename"
102 args = parser.parse_args()
104 with open(args.topo, u"rt") as topo_file:
105 topology = yaml.safe_load(topo_file.read())[u"nodes"]
107 # Even if TG is not guaranteed to be a Linux host,
108 # we are using it, because testing shows SSH access to DUT
109 # during test affects its performance (bursts of lost packets).
111 node = topology[RESERVATION_NODE]
113 print(f"Topology file does not contain '{RESERVATION_NODE}' node")
116 # For system reservation we use mkdir it is an atomic operation and we can
117 # store additional data (time, client_ID, ..) within reservation directory.
119 ret, _, err = exec_cmd(node, f"rm -r {RESERVATION_DIR}")
120 # If connection is refused, ret==None.
122 print(f"Cancellation unsuccessful:\n{err!r}")
125 # Before critical section, output can be outdated already.
126 print(u"Diagnostic commands:")
127 # -d and * are to suppress "total <size>", see https://askubuntu.com/a/61190
128 diag_cmd(node, f"ls --full-time -cd '{RESERVATION_DIR}'/*")
129 print(u"Attempting testbed reservation.")
130 # Entering critical section.
131 ret, _, _ = exec_cmd(node, f"mkdir '{RESERVATION_DIR}'")
132 # Critical section is over.
134 print(u"Failed to connect to testbed.")
137 _, stdo, _ = exec_cmd(node, f"ls '{RESERVATION_DIR}'/*")
138 print(f"Testbed already reserved by:\n{stdo}")
140 # Here the script knows it is the only owner of the testbed.
141 print(u"Reservation success, writing additional info to reservation dir.")
142 ret, _, err = exec_cmd(
143 node, f"touch '{RESERVATION_DIR}/{args.runtag}'")
145 print(f"Writing test run info failed, but continuing anyway:\n{err!r}")
149 if __name__ == u"__main__":