FIX: Topology reservation
[csit.git] / resources / tools / scripts / topo_reservation.py
1 #!/usr/bin/env python2
2
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:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
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.
15
16 """Script managing reservation and un-reservation of testbeds.
17
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.
21 """
22
23 import sys
24 import argparse
25 import yaml
26
27 from resources.libraries.python.ssh import exec_cmd
28
29
30 RESERVATION_DIR = "/tmp/reservation_dir"
31 RESERVATION_NODE = "TG"
32
33
34 def diag_cmd(node, cmd):
35     """Execute cmd, print cmd and stdout, ignore stderr and rc; return None.
36
37     :param node: Node object as parsed from topology file to execute cmd on.
38     :param cmd: Command to execute.
39     :type ssh: dict
40     :type cmd: str
41     """
42     print('+ {cmd}'.format(cmd=cmd))
43     _, stdout, _ = exec_cmd(node, cmd)
44     print(stdout)
45
46
47 def main():
48     """Parse arguments, perform the action, write useful output, propagate RC.
49
50     If the intended action is cancellation, reservation dir is deleted.
51
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,
60     their RC is ignored.
61
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.
66
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.
75     """
76     parser = argparse.ArgumentParser()
77     parser.add_argument("-t", "--topo", required=True,
78                         help="Topology file")
79     parser.add_argument("-c", "--cancel", help="Cancel reservation",
80                         action="store_true")
81     parser.add_argument("-r", "--runtag", required=False, default="Unknown",
82                         help="Identifier for test run suitable as filename")
83     args = parser.parse_args()
84
85     with open(args.topo, "r") as topo_file:
86         topology = yaml.load(topo_file.read())['nodes']
87
88     # Even if TG is not guaranteed to be a Linux host,
89     # we are using it, because testing shows SSH access to DUT
90     # during test affects its performance (bursts of lost packets).
91     try:
92         node = topology[RESERVATION_NODE]
93     except KeyError:
94         print("Topology file does not contain '{node}' node".
95               format(node=RESERVATION_NODE))
96         return 1
97
98     # For system reservation we use mkdir it is an atomic operation and we can
99     # store additional data (time, client_ID, ..) within reservation directory.
100     if args.cancel:
101         ret, _, err = exec_cmd(node, "rm -r {dir}".format(dir=RESERVATION_DIR))
102         if ret:
103             print("Cancellation unsuccessful:\n{err}".format(err=err))
104         return ret
105     # Before critical section, output can be outdated already.
106     print("Diagnostic commands:")
107     # -d and * are to supress "total <size>", see https://askubuntu.com/a/61190
108     diag_cmd(node, "ls --full-time -cd '{dir}'/*".format(dir=RESERVATION_DIR))
109     print("Attempting testbed reservation.")
110     # Entering critical section.
111     ret, _, _ = exec_cmd(node, "mkdir '{dir}'".format(dir=RESERVATION_DIR))
112     # Critical section is over.
113     if ret:
114         _, stdo, _ = exec_cmd(node, "ls '{dir}'/*".format(dir=RESERVATION_DIR))
115         print("Testbed already reserved by:\n{stdo}".format(stdo=stdo))
116         return 2
117     # Here the script knows it is the only owner of the testbed.
118     print("Reservation success, writing additional info to reservation dir.")
119     ret, _, err = exec_cmd(
120         node, "touch '{dir}/{runtag}'"\
121         .format(dir=RESERVATION_DIR, runtag=args.runtag))
122     if ret:
123         print("Writing test run info failed, but continuing anyway:\n{err}".
124               format(err=err))
125     return 0
126
127
128 if __name__ == "__main__":
129     sys.exit(main())