Debian Codegraph @

doc/examples/check_nodes.py

raw symbols SCIP
1 #!/usr/bin/python3
2 # check_nodes.py: ClusterShell simple example script.
3 #
4 # This script runs a simple command on remote nodes and reports node
5 # availability (basic health check) and also min/max boot dates.
6 # It shows an example of use of Task, NodeSet and EventHandler objects.
7 # Feel free to copy and modify it to fit your needs.
8 #
9 # Usage example: ./check_nodes.py -n node[1-99]
10
11 import optparse
12 from datetime import date, datetime
13
14 from ClusterShell.Event import EventHandler
15 from ClusterShell.NodeSet import NodeSet
16 from ClusterShell.Task import task_self
17
18
19 class CheckNodesResult(object):
20 """Our result class"""
21 def __init__(self):
22 """Initialize result class"""
23 self.nodes_ok = NodeSet()
24 self.nodes_ko = NodeSet()
25 self.min_boot_date = None
26 self.max_boot_date = None
27
28 def show(self):
29 """Display results"""
30 if self.nodes_ok:
31 print("%s: OK (boot date: min %s, max %s)" %
32 (self.nodes_ok, self.min_boot_date, self.max_boot_date))
33 if self.nodes_ko:
34 print("%s: FAILED" % self.nodes_ko)
35
36 class CheckNodesHandler(EventHandler):
37 """Our ClusterShell EventHandler"""
38
39 def __init__(self, result):
40 """Initialize our event handler with a ref to our result object."""
41 EventHandler.__init__(self)
42 self.result = result
43
44 def ev_read(self, worker, node, sname, msg):
45 """Read event from remote nodes"""
46 # this is an example to demonstrate remote result parsing
47 bootime = " ".join(msg.decode().strip().split()[2:])
48 # 'who -b' prints the boot date with or without the year
49 try:
50 date_boot = datetime.strptime(bootime, "%Y-%m-%d %H:%M")
51 except ValueError:
52 try:
53 # no year: prepend the current one before parsing
54 # (yearless dates are deprecated as of Python 3.13)
55 date_boot = datetime.strptime(
56 "%d %s" % (date.today().year, bootime), "%Y %b %d %H:%M")
57 except ValueError:
58 date_boot = None
59 if date_boot:
60 if not self.result.min_boot_date or \
61 self.result.min_boot_date > date_boot:
62 self.result.min_boot_date = date_boot
63 if not self.result.max_boot_date or \
64 self.result.max_boot_date < date_boot:
65 self.result.max_boot_date = date_boot
66 self.result.nodes_ok.add(node)
67 else:
68 self.result.nodes_ko.add(node)
69
70 def ev_close(self, worker, timedout):
71 """Worker has finished (command done on all nodes)"""
72 if timedout:
73 nodeset = NodeSet.fromlist(worker.iter_keys_timeout())
74 self.result.nodes_ko.add(nodeset)
75 self.result.show()
76
77 def main():
78 """ Main script function """
79 # Initialize option parser
80 parser = optparse.OptionParser()
81 parser.add_option("-d", "--debug", action="store_true", dest="debug",
82 default=False, help="Enable debug mode")
83 parser.add_option("-n", "--nodes", action="store", dest="nodes",
84 default="@all", help="Target nodes (default @all group)")
85 parser.add_option("-f", "--fanout", action="store", dest="fanout",
86 default="128", help="Fanout window size (default 128)",
87 type=int)
88 parser.add_option("-t", "--timeout", action="store", dest="timeout",
89 default="5", help="Timeout in seconds (default 5)",
90 type=float)
91 options, _ = parser.parse_args()
92
93 # Get current task (associated to main thread)
94 task = task_self()
95 nodes_target = NodeSet(options.nodes)
96 task.set_info("fanout", options.fanout)
97 if options.debug:
98 print("nodeset : %s" % nodes_target)
99 task.set_info("debug", True)
100
101 # Create ClusterShell event handler
102 handler = CheckNodesHandler(CheckNodesResult())
103
104 # Schedule remote command and run task (blocking call)
105 task.run("who -b", nodes=nodes_target, handler=handler, \
106 timeout=options.timeout)
107
108
109 if __name__ == '__main__':
110 main()