Debian Codegraph @

doc/sphinx/guide/examples.rst

raw
1 .. _prog-examples:
2
3 Programming Examples
4 ====================
5
6 .. highlight:: python
7
8 .. _prog-example-seq:
9
10 Remote command example (sequential mode)
11 ----------------------------------------
12
13 The following example shows how to send a command on some nodes, how to get a
14 specific buffer and how to get gathered buffers::
15
16 from ClusterShell.Task import task_self
17 task = task_self()
18
19 task.run("/bin/uname -r", nodes="green[36-39,133]")
20
21 print(task.node_buffer("green37").decode())
22
23 for buf, nodes in task.iter_buffers():
24 print(nodes, buf.message().decode())
25
26 if task.max_retcode() != 0:
27 print("An error occurred (max rc = %s)" % task.max_retcode())
28
29
30 Result::
31
32 2.6.32-431.el6.x86_64
33 ['green37', 'green38', 'green36', 'green39'] 2.6.32-431.el6.x86_64
34 ['green133'] 3.10.0-123.20.1.el7.x86_64
35
36 .. _prog-example-ev:
37
38 Remote command example with live output (event-based mode)
39 ----------------------------------------------------------
40
41 The following example shows how to use the event-based programming model by
42 installing an EventHandler and listening for :meth:`.EventHandler.ev_read`
43 (we've got a line to read) and :meth:`.EventHandler.ev_hup` (one command has
44 just completed) events. The goal here is to print standard outputs of ``uname
45 -a`` commands during their execution and also to notify the user of any
46 erroneous return codes::
47
48 from ClusterShell.Task import task_self
49 from ClusterShell.Event import EventHandler
50
51 class MyHandler(EventHandler):
52
53 def ev_read(self, worker, node, sname, msg):
54 print("%s: %s" % (node, msg.decode()))
55
56 def ev_hup(self, worker, node, rc):
57 if rc != 0:
58 print("%s: returned with error code %s" % (node, rc))
59
60 task = task_self()
61
62 # Submit command, install event handler for this command and run task
63 task.run("/bin/uname -a", nodes="fortoy[32-159]", handler=MyHandler())
64
65 .. _prog-example-script:
66
67 *check_nodes.py* example script
68 -------------------------------
69
70 .. note:: The example scripts use ``#!/usr/bin/python3`` as ClusterShell is
71 usually installed for the system Python interpreter (distribution packages
72 or ``pip install --user``). If you installed ClusterShell in a virtual
73 environment, adjust the interpreter line accordingly (e.g.
74 ``#!/usr/bin/env python3``).
75
76 The following script is available as an example in the source repository and
77 is usually packaged with ClusterShell::
78
79 #!/usr/bin/python3
80 # check_nodes.py: ClusterShell simple example script.
81 #
82 # This script runs a simple command on remote nodes and reports node
83 # availability (basic health check) and also min/max boot dates.
84 # It shows an example of use of Task, NodeSet and EventHandler objects.
85 # Feel free to copy and modify it to fit your needs.
86 #
87 # Usage example: ./check_nodes.py -n node[1-99]
88
89 import optparse
90 from datetime import date, datetime
91
92 from ClusterShell.Event import EventHandler
93 from ClusterShell.NodeSet import NodeSet
94 from ClusterShell.Task import task_self
95
96
97 class CheckNodesResult(object):
98 """Our result class"""
99 def __init__(self):
100 """Initialize result class"""
101 self.nodes_ok = NodeSet()
102 self.nodes_ko = NodeSet()
103 self.min_boot_date = None
104 self.max_boot_date = None
105
106 def show(self):
107 """Display results"""
108 if self.nodes_ok:
109 print("%s: OK (boot date: min %s, max %s)" %
110 (self.nodes_ok, self.min_boot_date, self.max_boot_date))
111 if self.nodes_ko:
112 print("%s: FAILED" % self.nodes_ko)
113
114 class CheckNodesHandler(EventHandler):
115 """Our ClusterShell EventHandler"""
116
117 def __init__(self, result):
118 """Initialize our event handler with a ref to our result object."""
119 EventHandler.__init__(self)
120 self.result = result
121
122 def ev_read(self, worker, node, sname, msg):
123 """Read event from remote nodes"""
124 # this is an example to demonstrate remote result parsing
125 bootime = " ".join(msg.decode().strip().split()[2:])
126 # 'who -b' prints the boot date with or without the year
127 try:
128 date_boot = datetime.strptime(bootime, "%Y-%m-%d %H:%M")
129 except ValueError:
130 try:
131 # no year: prepend the current one before parsing
132 # (yearless dates are deprecated as of Python 3.13)
133 date_boot = datetime.strptime(
134 "%d %s" % (date.today().year, bootime), "%Y %b %d %H:%M")
135 except ValueError:
136 date_boot = None
137 if date_boot:
138 if not self.result.min_boot_date or \
139 self.result.min_boot_date > date_boot:
140 self.result.min_boot_date = date_boot
141 if not self.result.max_boot_date or \
142 self.result.max_boot_date < date_boot:
143 self.result.max_boot_date = date_boot
144 self.result.nodes_ok.add(node)
145 else:
146 self.result.nodes_ko.add(node)
147
148 def ev_close(self, worker, timedout):
149 """Worker has finished (command done on all nodes)"""
150 if timedout:
151 nodeset = NodeSet.fromlist(worker.iter_keys_timeout())
152 self.result.nodes_ko.add(nodeset)
153 self.result.show()
154
155 def main():
156 """ Main script function """
157 # Initialize option parser
158 parser = optparse.OptionParser()
159 parser.add_option("-d", "--debug", action="store_true", dest="debug",
160 default=False, help="Enable debug mode")
161 parser.add_option("-n", "--nodes", action="store", dest="nodes",
162 default="@all", help="Target nodes (default @all group)")
163 parser.add_option("-f", "--fanout", action="store", dest="fanout",
164 default="128", help="Fanout window size (default 128)",
165 type=int)
166 parser.add_option("-t", "--timeout", action="store", dest="timeout",
167 default="5", help="Timeout in seconds (default 5)",
168 type=float)
169 options, _ = parser.parse_args()
170
171 # Get current task (associated to main thread)
172 task = task_self()
173 nodes_target = NodeSet(options.nodes)
174 task.set_info("fanout", options.fanout)
175 if options.debug:
176 print("nodeset : %s" % nodes_target)
177 task.set_info("debug", True)
178
179 # Create ClusterShell event handler
180 handler = CheckNodesHandler(CheckNodesResult())
181
182 # Schedule remote command and run task (blocking call)
183 task.run("who -b", nodes=nodes_target, handler=handler, \
184 timeout=options.timeout)
185
186
187 if __name__ == '__main__':
188 main()
189
190 .. _prog-example-pp-sbatch:
191
192 Using NodeSet with Parallel Python Batch script using SLURM
193 -----------------------------------------------------------
194
195 The following example shows how to use the NodeSet class to expand
196 ``$SLURM_NODELIST`` environment variable in a Parallel Python batch script
197 launched by SLURM. This variable may contain folded node sets. If ClusterShell
198 is not available system-wide on your compute cluster, you need to follow
199 :ref:`install-pip-user` first. On Python 3, Parallel Python is available as
200 the ppft_ package.
201
202 .. highlight:: bash
203
204 Example of SLURM ``pp.sbatch`` to submit using ``sbatch pp.sbatch``::
205
206 #!/bin/bash
207
208 #SBATCH -N 2
209 #SBATCH --ntasks-per-node 1
210
211 # run the servers
212 srun ~/.local/bin/ppserver -w $SLURM_CPUS_PER_TASK -t 300 &
213 sleep 10
214
215 # launch the parallel processing
216 python3 -u ./pp_jobs.py
217
218 .. highlight:: python
219
220 Example of a ``pp_jobs.py`` script::
221
222 #!/usr/bin/python3
223
224 import os, time
225 import pp
226 from ClusterShell.NodeSet import NodeSet
227
228 # get the nodelist from Slurm
229 nodelist = NodeSet(os.environ['SLURM_NODELIST'])
230
231 # start the servers (ncpus=0 will make sure that none is started locally)
232 # casting nodelist to tuple/list will correctly expand $SLURM_NODELIST
233 job_server = pp.Server(ncpus=0, ppservers=tuple(nodelist))
234
235 # make sure the servers have enough time to start
236 time.sleep(5)
237
238 # test function to execute on the remote nodes
239 def test_func():
240 print(os.uname())
241
242 # start the jobs
243 job_1 = job_server.submit(test_func,(),(),("os",))
244 job_2 = job_server.submit(test_func,(),(),("os",))
245
246 # retrieve the results
247 print(job_1())
248 print(job_2())
249
250 # Cleanup
251 job_server.print_stats()
252 job_server.destroy()
253
254
255 .. _ppft: https://pypi.org/project/ppft/