Debian Codegraph @

lib/ClusterShell/Worker/Worker.py

raw symbols SCIP
1 #
2 # Copyright (C) 2007-2016 CEA/DAM
3 # Copyright (C) 2015-2017 Stephane Thiell <[email protected]>
4 #
5 # This file is part of ClusterShell.
6 #
7 # ClusterShell is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # ClusterShell is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with ClusterShell; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
21 """
22 ClusterShell worker interface.
23
24 A worker is a generic object which provides "grouped" work in a specific task.
25 """
26
27 try:
28 from inspect import getfullargspec # py3
29 except ImportError:
30 from inspect import getargspec as getfullargspec # py2
31
32 import warnings
33
34 from ClusterShell.Worker.EngineClient import EngineClient
35 from ClusterShell.NodeSet import NodeSet
36 from ClusterShell.Engine.Engine import FANOUT_UNLIMITED, FANOUT_DEFAULT
37
38
39 def _eh_sigspec_invoke_compat(method, argc_legacy, *args):
40 """
41 Helper function to invoke an event handler method, with legacy
42 signature compatibility if actual argc does match argc_legacy.
43 This should be removed when old signatures (< 1.8) aren't supported
44 anymore (in 2.x).
45 """
46 argc_actual = len(getfullargspec(method)[0])
47 if argc_actual == argc_legacy:
48 # Use legacy signature (1.x) deprecated as of 1.9
49 warnings.warn("%s should use new %s() signature" % (method.__self__,
50 method.__name__),
51 DeprecationWarning)
52 return method(*args[0:argc_legacy - 1])
53 else:
54 # Assume new signature (2.x)
55 return method(*args)
56
57 def _eh_sigspec_ev_read_17(ev_read):
58 """Helper function to check whether ev_read has the old 1.7 signature."""
59 if len(getfullargspec(ev_read)[0]) == 2:
60 warnings.warn("%s should use new ev_read() signature" % \
61 ev_read.__self__, DeprecationWarning)
62 return True
63 return False
64
65
66 class WorkerException(Exception):
67 """Generic worker exception."""
68
69 class WorkerError(WorkerException):
70 """Generic worker error."""
71
72 # DEPRECATED: WorkerBadArgumentError exception is deprecated as of 1.4,
73 # use ValueError instead.
74 WorkerBadArgumentError = ValueError
75
76 class Worker(object):
77 """
78 Worker is an essential base class for the ClusterShell library. The goal
79 of a worker object is to execute a common work on a single or several
80 targets (abstract notion) in parallel. Concrete targets and also the
81 notion of local or distant targets are managed by Worker's subclasses
82 (for example, see the DistantWorker base class).
83
84 A configured Worker object is associated to a specific ClusterShell Task,
85 which can be seen as a single-threaded Worker supervisor. Indeed, the work
86 to be done is executed in parallel depending on other Workers and Task's
87 current parameters, like current fanout value.
88
89 ClusterShell is designed to write event-driven applications, and the Worker
90 class is key here as Worker objects are passed as parameter of most event
91 handlers (see the ClusterShell.Event.EventHandler class).
92
93 Example of use:
94
95 >>> from ClusterShell.Event import EventHandler
96 >>> class MyOutputHandler(EventHandler):
97 ... def ev_read(self, worker, node, sname, msg):
98 ... print("%s: %s" % (node, msg.decode()))
99 ...
100 """
101
102 # The following common stream names are recognized by the Task class.
103 # They can be changed per Worker, thus avoiding any Task buffering.
104 SNAME_STDIN = 'stdin' #: stream name usually used for stdin
105 SNAME_STDOUT = 'stdout' #: stream name usually used for stdout
106 SNAME_STDERR = 'stderr' #: stream name usually used for stderr
107
108 def __init__(self, handler):
109 """Initializer. Should be called from derived classes."""
110 # Associated EventHandler object
111 self.eh = handler #: associated :class:`.EventHandler`
112
113 # Per Worker fanout value (positive integer).
114 # Default is FANOUT_DEFAULT to use the fanout set at the Task level.
115 # Change to FANOUT_UNLIMITED to always schedule this worker.
116 # NOTE: the fanout value must be set before the Worker starts and
117 # cannot currently be changed afterwards.
118 self._fanout = FANOUT_DEFAULT
119
120 # Update task rc? [private]
121 # TODO: to be replaced with Task Event Handlers
122 self._update_task_rc = True
123
124 # Parent task (once bound)
125 self.task = None #: worker's task when scheduled or None
126 self.started = False #: set to True when worker has started
127 self.metaworker = None
128 self.metarefcnt = 0
129
130 # current_x public variables (updated at each event accordingly)
131
132 #: set to node in event handler; DEPRECATED: use :class:`.EventHandler` method argument **node**
133 self.current_node = None
134 #: set to stdout in event handler; DEPRECATED: use :class:`.EventHandler` method argument **msg** if ``sname==SNAME_STDOUT``
135 self.current_msg = None
136 #: set to stderr message in event handler; DEPRECATED: use :class:`.EventHandler` method argument **msg** if ``sname==SNAME_STDERR``
137 self.current_errmsg = None
138 #: set to return code in event handler; DEPRECATED: use :class:`.EventHandler` method argument **rc**
139 self.current_rc = 0
140 #: set to stream name in event handler; DEPRECATED: use :class:`.EventHandler` method argument **sname**
141 self.current_sname = None
142
143 def _set_task(self, task):
144 """Bind worker to task. Called by task.schedule()."""
145 if self.task is not None:
146 # one-shot-only schedule supported for now
147 raise WorkerError("worker has already been scheduled")
148 self.task = task
149
150 def _task_bound_check(self):
151 """Helper method to check that worker is bound to a task."""
152 if not self.task:
153 raise WorkerError("worker is not task bound")
154
155 def _engine_clients(self):
156 """Return a list of underlying engine clients."""
157 raise NotImplementedError("Derived classes must implement.")
158
159 # Event generators
160
161 def _on_start(self, key):
162 """Called on command start."""
163 self.current_node = key
164
165 if not self.started:
166 self.started = True
167 if self.eh is not None:
168 self.eh.ev_start(self)
169
170 if self.eh is not None:
171 _eh_sigspec_invoke_compat(self.eh.ev_pickup, 2, self, key)
172
173 def _on_close(self, key, rc=None):
174 """Called to generate events when the Worker is closing."""
175 if self._update_task_rc:
176 # rc may be None here for example when called from StreamClient
177 # Only update task if rc is not None.
178 if rc is not None:
179 self.task._rc_set(self, key, rc)
180
181 self.current_node = key
182 self.current_rc = rc
183
184 if self.eh is not None:
185 _eh_sigspec_invoke_compat(self.eh.ev_hup, 2, self, key, rc)
186
187 def _on_written(self, key, bytes_count, sname):
188 """Notification of bytes written."""
189 # set node and stream name (compat only)
190 self.current_node = key
191 self.current_sname = sname
192
193 if self.eh is not None:
194 self.eh.ev_written(self, key, sname, bytes_count)
195
196 # Base getters
197
198 def did_timeout(self):
199 """Return whether this worker has aborted due to timeout."""
200 self._task_bound_check()
201 return self.task._num_timeout_by_worker(self) > 0
202
203 def read(self, node=None, sname='stdout'):
204 """Read worker stream buffer.
205
206 Return stream read buffer of current worker.
207
208 Arguments:
209 :param node: node name, can also be set to None for simple worker
210 having worker.key defined (default is None)
211 :param sname: stream name (default is 'stdout')
212 """
213 self._task_bound_check()
214 return self.task._msg_by_source(self, node, sname)
215
216 # Base actions
217
218 def abort(self):
219 """Abort processing any action by this worker.
220
221 Safe to call on an already closing or aborting worker.
222 """
223 raise NotImplementedError("Derived classes must implement.")
224
225 def flush_buffers(self):
226 """Flush any messages associated to this worker."""
227 self._task_bound_check()
228 self.task._flush_buffers_by_worker(self)
229
230 def flush_errors(self):
231 """Flush any error messages associated to this worker."""
232 self._task_bound_check()
233 self.task._flush_errors_by_worker(self)
234
235
236 class DistantWorker(Worker):
237 """Base class DistantWorker.
238
239 DistantWorker provides a useful set of setters/getters to use with
240 distant workers like ssh or pdsh.
241 """
242
243 # Event generators
244
245 def _on_node_msgline(self, node, msg, sname):
246 """Message received from node, update last* stuffs."""
247 # Maxoptimize this method as it might be called very often.
248 task = self.task
249 assert not isinstance(node, NodeSet) # for testing
250 # update task msgtree
251 task._msg_add(self, node, sname, msg)
252
253 ### LEGACY (1.x) ###
254 # set stream name
255 self.current_sname = sname
256
257 # generate event
258 self.current_node = node
259 if sname == self.SNAME_STDERR:
260 self.current_errmsg = msg
261 if self.eh is not None:
262 # call old ev_error for compat (default is no-op)
263 if hasattr(self.eh, 'ev_error'): # missing in 1.8.0!
264 self.eh.ev_error(self)
265 # /!\ NOT elif
266 if not _eh_sigspec_ev_read_17(self.eh.ev_read):
267 ### FUTURE (2.x) ###
268 self.eh.ev_read(self, node, sname, msg)
269 else:
270 self.current_msg = msg
271 if self.eh is not None:
272 # ev_read: check for old signature first (< 1.8)
273 if _eh_sigspec_ev_read_17(self.eh.ev_read):
274 self.eh.ev_read(self)
275 else:
276 ### FUTURE (2.x) ###
277 self.eh.ev_read(self, node, sname, msg)
278
279 def _on_node_close(self, node, rc):
280 """Command return code received."""
281 Worker._on_close(self, node, rc)
282
283 def _on_node_timeout(self, node):
284 """Update on node timeout."""
285 # Update current_node to allow node resolution after ev_timeout.
286 self.current_node = node
287
288 self.task._timeout_add(self, node)
289
290 def node_buffer(self, node):
291 """Get specific node buffer."""
292 return self.read(node, self.SNAME_STDOUT)
293
294 def node_error(self, node):
295 """Get specific node error buffer."""
296 return self.read(node, self.SNAME_STDERR)
297
298 node_error_buffer = node_error
299
300 def node_retcode(self, node):
301 """
302 Get specific node return code.
303
304 :raises KeyError: command on node has not yet finished (no return code
305 available), or this node is not known by this worker
306 """
307 self._task_bound_check()
308 try:
309 rc = self.task._rc_by_source(self, node)
310 except KeyError:
311 raise KeyError(node)
312 return rc
313
314 node_rc = node_retcode
315
316 def iter_buffers(self, match_keys=None):
317 """
318 Returns an iterator over available buffers and associated
319 NodeSet. If the optional parameter match_keys is defined, only
320 keys found in match_keys are returned.
321 """
322 self._task_bound_check()
323 for msg, keys in self.task._call_tree_matcher(
324 self.task._msgtree(self.SNAME_STDOUT).walk, match_keys, self):
325 yield msg, NodeSet.fromlist(keys)
326
327 def iter_errors(self, match_keys=None):
328 """
329 Returns an iterator over available error buffers and associated
330 NodeSet. If the optional parameter match_keys is defined, only
331 keys found in match_keys are returned.
332 """
333 self._task_bound_check()
334 for msg, keys in self.task._call_tree_matcher(
335 self.task._msgtree(self.SNAME_STDERR).walk, match_keys, self):
336 yield msg, NodeSet.fromlist(keys)
337
338 def iter_node_buffers(self, match_keys=None):
339 """
340 Returns an iterator over each node and associated buffer.
341 """
342 self._task_bound_check()
343 return self.task._call_tree_matcher(
344 self.task._msgtree(self.SNAME_STDOUT).items, match_keys, self)
345
346 def iter_node_errors(self, match_keys=None):
347 """
348 Returns an iterator over each node and associated error buffer.
349 """
350 self._task_bound_check()
351 return self.task._call_tree_matcher(
352 self.task._msgtree(self.SNAME_STDERR).items, match_keys, self)
353
354 def iter_retcodes(self, match_keys=None):
355 """
356 Returns an iterator over return codes and associated NodeSet.
357 If the optional parameter match_keys is defined, only keys
358 found in match_keys are returned.
359 """
360 self._task_bound_check()
361 for rc, keys in self.task._rc_iter_by_worker(self, match_keys):
362 yield rc, NodeSet.fromlist(keys)
363
364 def iter_node_retcodes(self):
365 """
366 Returns an iterator over each node and associated return code.
367 """
368 self._task_bound_check()
369 return self.task._krc_iter_by_worker(self)
370
371 def num_timeout(self):
372 """
373 Return the number of timed out "keys" (ie. nodes) for this worker.
374 """
375 self._task_bound_check()
376 return self.task._num_timeout_by_worker(self)
377
378 def iter_keys_timeout(self):
379 """
380 Iterate over timed out keys (ie. nodes) for a specific worker.
381 """
382 self._task_bound_check()
383 return self.task._iter_keys_timeout_by_worker(self)
384
385 class StreamClient(EngineClient):
386 """StreamWorker's default EngineClient.
387
388 StreamClient is the EngineClient subclass used by default by
389 StreamWorker. It handles some generic methods to pass data to the
390 StreamWorker.
391 """
392
393 def _start(self):
394 """Called on EngineClient start."""
395 assert not self.worker.started
396 self.worker._on_start(self.key)
397 return self
398
399 def _read(self, sname, size=65536):
400 """Read data from process."""
401 return EngineClient._read(self, sname, size)
402
403 def _close(self, abort, timeout):
404 """Close client. See EngineClient._close()."""
405 EngineClient._close(self, abort, timeout)
406 if timeout:
407 assert abort, "abort flag not set on timeout"
408 self.worker._on_timeout(self.key)
409
410 # return code not available
411 self.worker._on_close(self.key)
412
413 if self.worker.eh:
414 _eh_sigspec_invoke_compat(self.worker.eh.ev_close, 2, self, timeout)
415
416 def _handle_read(self, sname):
417 """Engine is telling us there is data available for reading."""
418 # Local variables optimization
419 task = self.worker.task
420 msgline = self.worker._on_msgline
421
422 debug = task.info("debug", False)
423 if debug:
424 print_debug = task.info("print_debug")
425 for msg in self._readlines(sname):
426 print_debug(task, "LINE %s" % msg)
427 msgline(self.key, msg, sname)
428 else:
429 for msg in self._readlines(sname):
430 msgline(self.key, msg, sname)
431
432 def _flush_read(self, sname):
433 """Called at close time to flush stream read buffer."""
434 stream = self.streams[sname]
435 if stream.readable() and stream.rbuf:
436 # We still have some read data available in buffer, but no
437 # EOL. Generate a final message before closing.
438 self.worker._on_msgline(self.key, stream.rbuf, sname)
439
440 def write(self, buf, sname=None):
441 """Write to writable stream(s)."""
442 if sname is not None:
443 self._write(sname, buf)
444 return
445 # sname not specified: "broadcast" to all writable streams...
446 for writer in self.streams.writers():
447 self._write(writer.name, buf)
448
449 def set_write_eof(self, sname=None):
450 """Set EOF flag to writable stream(s)."""
451 if sname is not None:
452 self._set_write_eof(sname)
453 return
454 # sname not specified: set eof flag on all writable streams...
455 for writer in self.streams.writers():
456 self._set_write_eof(writer.name)
457
458 class StreamWorker(Worker):
459 """StreamWorker base class [v1.7+]
460
461 The StreamWorker class implements a base (but concrete) Worker that
462 can read and write to multiple streams. Unlike most other Workers,
463 it does not execute any external commands by itself. Rather, it
464 should be pre-bound to "streams", ie. file(s) or file descriptor(s),
465 using the two following methods:
466
467 >>> worker.set_reader('stream1', fd1)
468 >>> worker.set_writer('stream2', fd2)
469
470 Like other Workers, the StreamWorker instance should be associated
471 with a Task using task.schedule(worker). When the task engine is
472 ready to process the StreamWorker, all of its streams are being
473 processed together. For that reason, it is not possible to add new
474 readers or writers to a running StreamWorker (ie. task is running
475 and worker is already scheduled).
476
477 Configured readers will generate ev_read() events when data is
478 available for reading, with the stream name passed as one of its
479 argument.
480
481 Configured writers will allow the use of the method write(), eg.
482 worker.write(data, 'stream2'), to write to the stream.
483 """
484
485 def __init__(self, handler, key=None, stderr=False, timeout=-1,
486 autoclose=False, client_class=StreamClient):
487 Worker.__init__(self, handler)
488 if key is None: # allow key=0
489 key = self
490 self.clients = [client_class(self, key, stderr, timeout, autoclose)]
491
492 def set_reader(self, sname, sfile, retain=True, closefd=True):
493 """Add a readable stream to StreamWorker.
494
495 Arguments:
496 :param sname: the name of the stream (string)
497 :param sfile: the stream file or file descriptor
498 :param retain: whether the stream retains engine client
499 (default is True)
500 :param closefd: whether to close fd when the stream is closed
501 (default is True)
502 """
503 if not self.clients[0].registered:
504 self.clients[0].streams.set_reader(sname, sfile, retain, closefd)
505 else:
506 raise WorkerError("cannot add new stream at runtime")
507
508 def set_writer(self, sname, sfile, retain=True, closefd=True):
509 """Set a writable stream to StreamWorker.
510
511 Arguments:
512 :param sname: the name of the stream (string)
513 :param sfile: the stream file or file descriptor
514 :param retain: whether the stream retains engine client
515 (default is True)
516 :param closefd: whether to close fd when the stream is closed
517 (default is True)
518 """
519 if not self.clients[0].registered:
520 self.clients[0].streams.set_writer(sname, sfile, retain, closefd)
521 else:
522 raise WorkerError("cannot add new stream at runtime")
523
524 def _engine_clients(self):
525 """Return a list of underlying engine clients."""
526 return self.clients
527
528 def set_key(self, key):
529 """Source key for this worker is free for use.
530
531 Use this method to set the custom source key for this worker.
532 """
533 self.clients[0].key = key
534
535 def _on_msgline(self, key, msg, sname):
536 """Add a message."""
537 # update task msgtree
538 self.task._msg_add(self, key, sname, msg)
539
540 ### LEGACY (1.x) ###
541 # set stream name
542 self.current_sname = sname
543
544 # generate event
545 if sname == 'stderr':
546 self.current_errmsg = msg
547 if self.eh is not None:
548 # call old ev_error for compat (default is no-op)
549 if hasattr(self.eh, 'ev_error'): # missing in 1.8.0!
550 self.eh.ev_error(self)
551 # /!\ NOT elif
552 if not _eh_sigspec_ev_read_17(self.eh.ev_read):
553 ### FUTURE (2.x) ###
554 self.eh.ev_read(self, key, sname, msg)
555 else:
556 self.current_msg = msg
557 if self.eh is not None:
558 # ev_read: check for old signature first (< 1.8)
559 if _eh_sigspec_ev_read_17(self.eh.ev_read):
560 self.eh.ev_read(self)
561 else:
562 ### FUTURE (2.x) ###
563 self.eh.ev_read(self, key, sname, msg)
564
565 def _on_timeout(self, key):
566 """Update on timeout."""
567 self.task._timeout_add(self, key)
568
569 # trigger timeout event (deprecated in 1.8+)
570 # also use hasattr check because ev_timeout was missing in 1.8.0
571 if self.eh and hasattr(self.eh, 'ev_timeout'):
572 warnings.warn("%s should use new ev_close() instead of " \
573 "ev_timeout()" % self.eh, DeprecationWarning)
574 self.eh.ev_timeout(self)
575
576 def abort(self):
577 """Abort processing any action by this worker.
578
579 Safe to call on an already closing or aborting worker.
580 """
581 self.clients[0].abort()
582
583 def read(self, node=None, sname='stdout'):
584 """Read worker stream buffer.
585
586 Return stream read buffer of current worker.
587
588 Arguments:
589 :param node: node name, can also be set to None for simple worker
590 having worker.key defined (default is None)
591 :param sname: stream name (default is 'stdout')
592 """
593 return Worker.read(self, node or self.clients[0].key, sname)
594
595 def write(self, buf, sname=None):
596 """Write to worker.
597
598 If sname is specified, write to the associated stream,
599 otherwise write to all writable streams.
600 """
601 self.clients[0].write(buf, sname)
602
603 def set_write_eof(self, sname=None):
604 """
605 Tell worker to close its writer file descriptor once flushed.
606
607 Do not perform writes after this call. Like write(), sname can
608 be optionally specified to target a specific writable stream,
609 otherwise all writable streams are marked as EOF.
610 """
611 self.clients[0].set_write_eof(sname)
612
613 class WorkerSimple(StreamWorker):
614 """WorkerSimple base class [DEPRECATED]
615
616 Implements a simple Worker to manage common process
617 stdin/stdout/stderr streams.
618
619 [DEPRECATED] use StreamWorker.
620 """
621
622 def __init__(self, file_reader, file_writer, file_error, key, handler,
623 stderr=False, timeout=-1, autoclose=False, closefd=True,
624 client_class=StreamClient):
625 """Initialize WorkerSimple worker."""
626 StreamWorker.__init__(self, handler, key, stderr, timeout, autoclose,
627 client_class=client_class)
628 if file_reader:
629 self.set_reader('stdout', file_reader, closefd=closefd)
630 if file_error:
631 self.set_reader('stderr', file_error, closefd=closefd)
632 if file_writer:
633 self.set_writer('stdin', file_writer, closefd=closefd)
634 # keep reference of provided file objects during worker lifetime
635 self._filerefs = (file_reader, file_writer, file_error)
636
637 def error_fileno(self):
638 """Return the standard error reader file descriptor (integer)."""
639 return self.clients[0].streams['stderr'].fd
640
641 def reader_fileno(self):
642 """Return the reader file descriptor (integer)."""
643 return self.clients[0].streams['stdout'].fd
644
645 def writer_fileno(self):
646 """Return the writer file descriptor as an integer."""
647 return self.clients[0].streams['stdin'].fd
648
649 def error(self):
650 """Read worker error buffer."""
651 return self.read(sname='stderr')
652
653 def _on_start(self, key):
654 """Called on command start."""
655 if not self.started:
656 self.started = True
657 if self.eh is not None:
658 self.eh.ev_start(self)
659
660 if self.eh is not None:
661 # generate ev_pickup
662 _eh_sigspec_invoke_compat(self.eh.ev_pickup, 2, self, key)
663
664 def _on_close(self, key, rc=None):
665 """Called to generate events when the Worker is closing."""
666 self.current_rc = rc
667
668 # rc may be None here for example when called from StreamClient
669 # Only update task if rc is not None.
670 if rc is not None:
671 self.task._rc_set(self, key, rc)
672
673 if self.eh is not None:
674 # generate ev_hup
675 _eh_sigspec_invoke_compat(self.eh.ev_hup, 2, self, key, rc)
676
677 def _on_written(self, key, bytes_count, sname):
678 """Notification of bytes written."""
679 # set node and stream name (compat only)
680 self.current_sname = sname
681
682 if self.eh is not None:
683 # generate ev_written
684 self.eh.ev_written(self, key, sname, bytes_count)