Infra: Fix AWS deployment
[csit.git] / resources / tools / scripts / topo_reservation.py
1 #!/usr/bin/env python3
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 argparse
24 import sys
25 import yaml
26
27 from resources.libraries.python.ssh import exec_cmd
28
29
30 RESERVATION_DIR = u"/tmp/reservation_dir"
31 RESERVATION_NODE = u"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 node: dict
40     :type cmd: str
41     """
42     print(f"+ {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(u"-t", u"--topo", required=True, help=u"Topology file")
78     parser.add_argument(
79         u"-c", u"--cancel", help=u"Cancel reservation", action=u"store_true"
80     )
81     parser.add_argument(
82         u"-r", u"--runtag", required=False, default=u"Unknown",
83         help=u"Identifier for test run suitable as filename"
84     )
85     args = parser.parse_args()
86
87     with open(args.topo, u"rt") as topo_file:
88         topology = yaml.safe_load(topo_file.read())[u"nodes"]
89
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).
93     try:
94         node = topology[RESERVATION_NODE]
95     except KeyError:
96         print(f"Topology file does not contain '{RESERVATION_NODE}' node")
97         return 1
98
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.
101     if args.cancel:
102         ret, _, err = exec_cmd(node, f"rm -r {RESERVATION_DIR}")
103         # If connection is refused, ret==None.
104         if ret != 0:
105             print(f"Cancellation unsuccessful:\n{err!r}")
106             return 1
107         return 0
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.
116     if ret is None:
117         print(u"Failed to connect to testbed.")
118         return 1
119     if ret != 0:
120         _, stdo, _ = exec_cmd(node, f"ls '{RESERVATION_DIR}'/*")
121         print(f"Testbed already reserved by:\n{stdo}")
122         return 2
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}'")
127     if ret != 0:
128         print(f"Writing test run info failed, but continuing anyway:\n{err!r}")
129     return 0
130
131
132 if __name__ == u"__main__":
133     sys.exit(main())