3 # Copyright (c) 2019 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 = "/tmp/reservation_dir"
33 def diag_cmd(node, cmd):
34 """Execute cmd, print cmd and stdout, ignore stderr and rc; return None.
36 :param node: Node object as parsed from topology file to execute cmd on.
37 :param cmd: Command to execute.
42 _, stdout, _ = exec_cmd(node, cmd)
47 """Parse arguments, perform the action, write useful output, propagate RC.
49 If the intended action is cancellation, reservation dir is deleted.
51 If the intended action is reservation, the list is longer:
52 1. List contents of reservation dir.
53 2. List contents of test.url file in the dir.
54 3. Create reservation dir.
55 4. Touch file according to -r option.
56 5. Put -u option string to file test.url
57 From these 5 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, steps 4-5 are executed without any output,
62 The two files in reservation dir are there for reporting
63 which test run holds the reservation, so people can manually fix the testbed
64 if the rest run has been aborted, or otherwise failed to unregister.
66 The two files have different audiences.
68 The URL content is useful for people scheduling their test runs
69 and wondering why the reservation takes so long.
70 For them, a URL (if available) to copy and paste into browser
71 to see which test runs are blocking testbeds is the most convenient.
73 The "run tag" as a filename is useful for admins accessing the testbed
74 via a graphical terminal, which does not allow copying of text,
75 as they need less keypresses to identify the test run holding the testbed.
76 Also, the listing shows timestamps, which is useful for both audiences.
78 This all assumes the target system accepts ssh connections.
79 If it does not, the caller probably wants to stop trying
80 to reserve this system. Therefore this script can return 3 different codes.
81 Return code 0 means the reservation was successful.
82 Return code 1 means the system is inaccessible (or similarly unsuitable).
83 Return code 2 means the system is accessible, but already reserved.
84 The reason unsuitable systems return 1 is because that is also the value
85 Python returns on encountering and unexcepted exception.
87 parser = argparse.ArgumentParser()
88 parser.add_argument("-t", "--topo", required=True,
90 parser.add_argument("-c", "--cancel", help="Cancel reservation",
92 parser.add_argument("-r", "--runtag", required=False, default="Unknown",
93 help="Identifier for test run suitable as filename")
94 parser.add_argument("-u", "--url", required=False, default="Unknown",
95 help="Identifier for test run suitable as URL")
96 args = parser.parse_args()
98 with open(args.topo, "r") as topo_file:
99 topology = yaml.load(topo_file.read())['nodes']
101 # Even if TG is not guaranteed to be a Linux host,
102 # we are using it, because testing shows SSH access to DUT
103 # during test affects its performance (bursts of lost packets).
107 print "Topology file does not contain 'TG' node"
110 # For system reservation we use mkdir it is an atomic operation and we can
111 # store additional data (time, client_ID, ..) within reservation directory.
113 ret, _, err = exec_cmd(tgn, "rm -r {}".format(RESERVATION_DIR))
115 print "Cancellation unsuccessful:\n{}".format(err)
117 # Before critical section, output can be outdated already.
118 print "Diagnostic commands:"
119 # -d and * are to supress "total <size>", see https://askubuntu.com/a/61190
120 diag_cmd(tgn, "ls --full-time -cd '{dir}'/*".format(dir=RESERVATION_DIR))
121 diag_cmd(tgn, "head -1 '{dir}/run.url'".format(dir=RESERVATION_DIR))
122 print "Attempting reservation."
123 # Entering critical section.
124 # TODO: Add optional argument to exec_cmd_no_error to make it
125 # sys.exit(ret) instead raising? We do not want to deal with stacktrace.
126 ret, _, err = exec_cmd(tgn, "mkdir '{dir}'".format(dir=RESERVATION_DIR))
127 # Critical section is over.
129 print "Already reserved by another job:\n{}".format(err)
131 # Here the script knows it is the only owner of the testbed.
132 print "Success, writing test run info to reservation dir."
133 # TODO: Add optional argument to exec_cmd_no_error to print message
134 # to console instead raising? We do not want to deal with stacktrace.
135 ret2, _, err = exec_cmd(
136 tgn, "touch '{dir}/{runtag}' && ( echo '{url}' > '{dir}/run.url' )"\
137 .format(dir=RESERVATION_DIR, runtag=args.runtag, url=args.url))
139 print "Writing test run info failed, but continuing anyway:\n{}".format(
144 if __name__ == "__main__":