Debian Codegraph @

lib/ClusterShell/Task.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 Task module.
23
24 Simple example of use:
25
26 >>> from ClusterShell.Task import task_self, NodeSet
27 >>>
28 >>> # get task associated with calling thread
29 ... task = task_self()
30 >>>
31 >>> # add a command to execute on distant nodes
32 ... task.shell("/bin/uname -r", nodes="tiger[1-30,35]")
33 <ClusterShell.Worker.Ssh.WorkerSsh object at 0x7f41da71b890>
34 >>>
35 >>> # run task in calling thread
36 ... task.run()
37 >>>
38 >>> # get results
39 ... for output, nodelist in task.iter_buffers():
40 ... print('%s: %s' % (NodeSet.fromlist(nodelist), output.message().decode()))
41 ...
42
43 """
44
45 from __future__ import print_function
46 import logging
47 from operator import itemgetter
48 import os
49 import socket
50 import sys
51 import threading
52 from time import sleep
53 import traceback
54
55 try:
56 basestring
57 except NameError: # Python 3 compat
58 basestring = str
59
60 from ClusterShell.Defaults import config_paths, DEFAULTS
61 from ClusterShell.Defaults import _local_workerclass, _distant_workerclass, _load_workerclass
62 from ClusterShell.Engine.Engine import EngineAbortException
63 from ClusterShell.Engine.Engine import EngineTimeoutException
64 from ClusterShell.Engine.Engine import EngineAlreadyRunningError
65 from ClusterShell.Engine.Engine import EngineTimer
66 from ClusterShell.Engine.Factory import PreferredEngine
67 from ClusterShell.Worker.EngineClient import EnginePort, EngineClientError
68 from ClusterShell.Worker.Popen import WorkerPopen
69 from ClusterShell.Worker.Tree import TreeWorker
70 from ClusterShell.Worker.Worker import FANOUT_UNLIMITED
71
72 from ClusterShell.Event import EventHandler
73 from ClusterShell.MsgTree import MsgTree
74 from ClusterShell.NodeSet import NodeSet
75
76 from ClusterShell.Topology import TopologyParser, TopologyError
77 from ClusterShell.Propagation import PropagationTreeRouter, PropagationChannel
78
79
80 class TaskException(Exception):
81 """Base task exception."""
82
83 class TaskError(TaskException):
84 """Base task error exception."""
85
86 class TimeoutError(TaskError):
87 """Raised when the task timed out."""
88
89 class AlreadyRunningError(TaskError):
90 """Raised when trying to resume an already running task."""
91
92 class TaskMsgTreeError(TaskError):
93 """Raised when trying to access disabled MsgTree."""
94
95
96 def _getshorthostname():
97 """Get short hostname (host name cut at the first dot)"""
98 return socket.gethostname().split('.')[0]
99
100
101 class Task(object):
102 """
103 The Task class defines an essential ClusterShell object which aims to
104 execute commands in parallel and easily get their results.
105
106 More precisely, a Task object manages a coordinated (ie. with respect of
107 its current parameters) collection of independent parallel Worker objects.
108 See ClusterShell.Worker.Worker for further details on ClusterShell Workers.
109
110 Always bound to a specific thread, a Task object acts like a "thread
111 singleton". So most of the time, and even more for single-threaded
112 applications, you can get the current task object with the following
113 top-level Task module function:
114
115 >>> task = task_self()
116
117 However, if you want to create a task in a new thread, use:
118
119 >>> task = Task()
120
121 To create or get the instance of the task associated with the thread
122 object thr (threading.Thread):
123
124 >>> task = Task(thread=thr)
125
126 To submit a command to execute locally within task, use:
127
128 >>> task.shell("/bin/hostname")
129
130 To submit a command to execute to some distant nodes in parallel, use:
131
132 >>> task.shell("/bin/hostname", nodes="tiger[1-20]")
133
134 The previous examples submit commands to execute but do not allow result
135 interaction during their execution. For your program to interact during
136 command execution, it has to define event handlers that will listen for
137 local or remote events. These handlers are based on the EventHandler
138 class, defined in ClusterShell.Event. The following example shows how to
139 submit a command on a cluster with a registered event handler:
140
141 >>> task.shell("uname -r", nodes="node[1-9]", handler=MyEventHandler())
142
143 Run task in its associated thread (will block only if the calling thread is
144 the task associated thread):
145
146 >>> task.resume()
147
148 or:
149
150 >>> task.run()
151
152 You can also pass arguments to task.run() to schedule a command exactly
153 like in task.shell(), and run it:
154
155 >>> task.run("hostname", nodes="tiger[1-20]", handler=MyEventHandler())
156
157 A common need is to set a maximum delay for command execution, especially
158 when the command time is not known. Doing this with ClusterShell Task is
159 very straightforward. To limit the execution time on each node, use the
160 timeout parameter of shell() or run() methods to set a delay in seconds,
161 like:
162
163 >>> task.run("check_network.sh", nodes="tiger[1-20]", timeout=30)
164
165 You can then either use Task's iter_keys_timeout() method after execution
166 to see on what nodes the command has timed out, or listen for ev_close()
167 events in your event handler and check the timedout boolean.
168
169 To get command result, you can either use Task's iter_buffers() method for
170 standard output, iter_errors() for standard error after command execution
171 (common output contents are automatically gathered), or you can listen for
172 ev_read() events in your event handler and get live command output.
173
174 To get command return codes, you can either use Task's iter_retcodes(),
175 node_retcode() and max_retcode() methods after command execution, or
176 listen for ev_hup() events in your event handler.
177 """
178
179 # topology.conf file path list
180 TOPOLOGY_CONFIGS = config_paths('topology.conf')
181
182 _tasks = {}
183 _taskid_max = 0
184 _task_lock = threading.Lock()
185
186 class _SyncMsgHandler(EventHandler):
187 """Special task control port event handler.
188 When a message is received on the port, call appropriate
189 task method."""
190 def __init__(self, task):
191 EventHandler.__init__(self)
192 self.task = task
193
194 def ev_msg(self, port, msg):
195 """Message received: call appropriate task method."""
196 # pull out function and its arguments from message
197 func, (args, kwargs) = msg[0], msg[1:]
198 # call task method
199 func(self.task, *args, **kwargs)
200
201 class tasksyncmethod(object):
202 """Class encapsulating a function that checks if the calling
203 task is running or is the current task, and allowing it to be
204 used as a decorator making the wrapped task method thread-safe."""
205 def __call__(self, f):
206 def taskfunc(*args, **kwargs):
207 # pull out the class instance
208 task, fargs = args[0], args[1:]
209 # check if the calling task is the current thread task
210 if task._is_task_self():
211 return f(task, *fargs, **kwargs)
212 elif task._dispatch_port:
213 # no, safely call the task method by message
214 # through the task special dispatch port
215 task._dispatch_port.msg_send((f, fargs, kwargs))
216 else:
217 task.info("print_debug")(task, "%s: dropped call: %s" % \
218 (task, str(fargs)))
219 # modify the decorator meta-data for pydoc
220 # Note: should be later replaced by @wraps (functools)
221 # as of Python 2.5
222 taskfunc.__name__ = f.__name__
223 taskfunc.__doc__ = f.__doc__
224 taskfunc.__dict__ = f.__dict__
225 taskfunc.__module__ = f.__module__
226 return taskfunc
227
228 class _SuspendCondition(object):
229 """Special class to manage task suspend condition."""
230 def __init__(self, lock=threading.RLock(), initial=0):
231 self._cond = threading.Condition(lock)
232 self.suspend_count = initial
233
234 def atomic_inc(self):
235 """Increase suspend count."""
236 self._cond.acquire()
237 self.suspend_count += 1
238 self._cond.release()
239
240 def atomic_dec(self):
241 """Decrease suspend count."""
242 self._cond.acquire()
243 self.suspend_count -= 1
244 self._cond.release()
245
246 def wait_check(self, release_lock=None):
247 """Wait for condition if needed."""
248 self._cond.acquire()
249 try:
250 if self.suspend_count > 0:
251 if release_lock:
252 release_lock.release()
253 self._cond.wait()
254 finally:
255 self._cond.release()
256
257 def notify_all(self):
258 """Signal all threads waiting for condition."""
259 self._cond.acquire()
260 try:
261 self.suspend_count = min(self.suspend_count, 0)
262 self._cond.notify_all()
263 finally:
264 self._cond.release()
265
266
267 def __new__(cls, thread=None, defaults=None):
268 """
269 For task bound to a specific thread, this class acts like a
270 "thread singleton", so new style class is used and new object
271 are only instantiated if needed.
272 """
273 if thread:
274 if thread not in cls._tasks:
275 cls._tasks[thread] = object.__new__(cls)
276 return cls._tasks[thread]
277
278 return object.__new__(cls)
279
280 def __init__(self, thread=None, defaults=None):
281 """Initialize a Task, creating a new non-daemonic thread if
282 needed."""
283 if not getattr(self, "_engine", None):
284 # first time called
285 self._default_lock = threading.Lock()
286 if defaults is None:
287 defaults = DEFAULTS
288 self._default = defaults._task_default.copy()
289 self._default.update(
290 {"local_worker": _local_workerclass(defaults),
291 "distant_worker": _distant_workerclass(defaults)})
292 self._info = defaults._task_info.copy()
293
294 # use factory class PreferredEngine that gives the proper
295 # engine instance
296 self._engine = PreferredEngine(self.default("engine"), self._info)
297 self.timeout = None
298
299 # task synchronization objects
300 self._run_lock = threading.Lock() # primitive lock
301 self._suspend_lock = threading.RLock() # reentrant lock
302 # both join and suspend conditions share the same underlying lock
303 self._suspend_cond = Task._SuspendCondition(self._suspend_lock, 1)
304 self._join_cond = threading.Condition(self._suspend_lock)
305 self._suspended = False
306 self._quit = False
307 self._terminated = False
308
309 # Default router
310 self.topology = None
311 self.router = None
312 self.gateways = {}
313
314 # dict of MsgTree by sname
315 self._msgtrees = {}
316 # dict of sources to return codes
317 self._d_source_rc = {}
318 # dict of return codes to sources
319 self._d_rc_sources = {}
320 # keep max rc
321 self._max_rc = None
322 # keep timeout'd sources
323 self._timeout_sources = set()
324 # allow no-op call to getters before resume()
325 self._reset()
326
327 # special engine port for task method dispatching
328 self._dispatch_port = EnginePort(handler=Task._SyncMsgHandler(self),
329 autoclose=True)
330 self._engine.add(self._dispatch_port)
331
332 # set taskid used as Thread name
333 Task._task_lock.acquire()
334 Task._taskid_max += 1
335 self._taskid = Task._taskid_max
336 Task._task_lock.release()
337
338 # create new thread if needed
339 self._thread_foreign = bool(thread)
340 if self._thread_foreign:
341 self.thread = thread
342 else:
343 self.thread = thread = \
344 threading.Thread(None,
345 Task._thread_start,
346 "Task-%d" % self._taskid,
347 args=(self,))
348 Task._tasks[thread] = self
349 thread.start()
350
351 def _is_task_self(self):
352 """Private method used by the library to check if the task is
353 task_self(), but do not create any task_self() instance."""
354 return self.thread == threading.current_thread()
355
356 def default_excepthook(self, exc_type, exc_value, tb):
357 """Default excepthook for a newly Task. When an exception is
358 raised and uncaught on Task thread, excepthook is called, which
359 is default_excepthook by default. Once excepthook overridden,
360 you can still call default_excepthook if needed."""
361 print('Exception in thread %s:' % self.thread, file=sys.stderr)
362 traceback.print_exception(exc_type, exc_value, tb, file=sys.stderr)
363
364 _excepthook = default_excepthook
365
366 def _getexcepthook(self):
367 return self._excepthook
368
369 def _setexcepthook(self, hook):
370 self._excepthook = hook
371 # If thread has not been created by us, install sys.excepthook which
372 # might handle uncaught exception.
373 if self._thread_foreign:
374 sys.excepthook = self._excepthook
375
376 # When an exception is raised and uncaught on Task's thread,
377 # excepthook is called. You may want to override this three
378 # arguments method (very similar of what you can do with
379 # sys.excepthook)."""
380 excepthook = property(_getexcepthook, _setexcepthook)
381
382 def _thread_start(self):
383 """Task-managed thread entry point"""
384 while not self._quit:
385 self._suspend_cond.wait_check()
386 if self._quit: # may be set by abort()
387 break
388 try:
389 self._resume()
390 except:
391 self.excepthook(*sys.exc_info())
392 self._quit = True
393
394 self._terminate(kill=True)
395
396 def _run(self, timeout):
397 """Run task (always called from its self thread)."""
398 # check if task is already running
399 if self._run_lock.locked():
400 raise AlreadyRunningError("task is already running")
401 # use with statement later
402 try:
403 self._run_lock.acquire()
404 self._engine.run(timeout)
405 finally:
406 self._run_lock.release()
407
408 def _default_tree_is_enabled(self):
409 """Return whether default tree is enabled (load topology_file btw)"""
410 if self.topology is None:
411 for topology_file in self.TOPOLOGY_CONFIGS[::-1]:
412 if os.path.exists(topology_file):
413 self.load_topology(topology_file)
414 break
415 return (self.topology is not None) and self.default("auto_tree")
416
417 def load_topology(self, topology_file):
418 """Load propagation topology from provided file.
419
420 On success, task.topology is set to a corresponding TopologyTree
421 instance.
422
423 On failure, task.topology is left untouched and a TopologyError
424 exception is raised.
425 """
426 self.topology = TopologyParser(topology_file).tree(_getshorthostname())
427
428 def _default_router(self, router=None):
429 """
430 Helper to instantiate or bind a default PropagationTreeRouter
431 for the task which can then be shared by multiple workers.
432 Called by a TreeWorker when it is scheduled with this task.
433 """
434 if router is None:
435 if self.router is None:
436 # Init router with the task's topology (e.g. root node)
437 self.router = \
438 PropagationTreeRouter(str(self.topology.root.nodeset),
439 self.topology)
440 else:
441 if self.router is not None:
442 # Update default router if a different one is used by a worker.
443 logger = logging.getLogger(__name__)
444 logger.debug("_default_router: overriding previous default " \
445 "router %s with %s", self.router, router)
446 self.router = router
447 return self.router
448
449 def default(self, default_key, def_val=None):
450 """
451 Return per-task value for key from the "default" dictionary.
452 See set_default() for a list of reserved task default_keys.
453 """
454 self._default_lock.acquire()
455 try:
456 return self._default.get(default_key, def_val)
457 finally:
458 self._default_lock.release()
459
460 def set_default(self, default_key, value):
461 """
462 Set task value for specified key in the dictionary "default".
463 Users may store their own task-specific key, value pairs
464 using this method and retrieve them with default().
465
466 Task default_keys are:
467
468 - "stderr": Boolean value indicating whether to enable
469 stdout/stderr separation when using task.shell(), if not
470 specified explicitly (default: False).
471 - "stdin": Boolean value indicating whether to enable stdin when
472 using task.shell(), if not explicitly specified (default: True)
473 - "stdout_msgtree": Whether to instantiate standard output
474 MsgTree for automatic internal gathering of result messages
475 coming from Workers (default: True).
476 - "stderr_msgtree": Same for stderr (default: True).
477 - "engine": Used to specify an underlying Engine explicitly
478 (default: "auto").
479 - "port_qlimit": Size of port messages queue (default: 100).
480 - "local_workername": Worker name used when spawning workers
481 for local commands (default: "exec").
482 - "distant_workername": Worker name used when spawning workers
483 for distant commands (default: "ssh").
484
485 Threading considerations:
486
487 Unlike set_info(), when called from the task's thread or
488 not, set_default() immediately updates the underlying
489 dictionary in a thread-safe manner. This method doesn't
490 wake up the engine when called.
491 """
492 self._default_lock.acquire()
493 try:
494 self._default[default_key] = value
495 if default_key == 'local_workername':
496 self._default['local_worker'] = _load_workerclass(value)
497 elif default_key == 'distant_workername':
498 self._default['distant_worker'] = _load_workerclass(value)
499 finally:
500 self._default_lock.release()
501
502 def info(self, info_key, def_val=None):
503 """
504 Return per-task information. See set_info() for a list of
505 reserved task info_keys.
506 """
507 return self._info.get(info_key, def_val)
508
509 @tasksyncmethod()
510 def set_info(self, info_key, value):
511 """
512 Set task value for a specific key information. Key, value
513 pairs can be passed to the engine and/or workers.
514 Users may store their own task-specific info key, value pairs
515 using this method and retrieve them with info().
516
517 The following example changes the fanout value to 128:
518 >>> task.set_info('fanout', 128)
519
520 The following example enables debug messages:
521 >>> task.set_info('debug', True)
522
523 Task info_keys are:
524
525 - "debug": Boolean value indicating whether to enable library
526 debugging messages (default: False).
527 - "print_debug": Debug messages processing function. This
528 function takes 2 arguments: the task instance and the
529 message string (default: an internal function doing standard
530 print).
531 - "fanout": Max number of registered clients in Engine at a
532 time (default: 64).
533 - "grooming_delay": Message maximum end-to-end delay requirement
534 used for traffic grooming, in seconds as float (default: 0.25).
535 - "connect_timeout": Time in seconds to wait for connecting to
536 remote host before aborting (default: 10).
537 - "command_timeout": Time in seconds to wait for a command to
538 complete before aborting (default: 0, which means
539 unlimited).
540 - "tree_default:<key>": In tree mode, overrides the key <key>
541 in Defaults (settings normally set in defaults.conf)
542
543 Threading considerations:
544
545 Unlike set_default(), the underlying info dictionary is only
546 modified from the task's thread. So calling set_info() from
547 another thread leads to queueing the request for late apply
548 (at run time) using the task dispatch port. When received,
549 the request wakes up the engine when the task is running and
550 the info dictionary is then updated.
551 """
552 self._info[info_key] = value
553
554 def shell(self, command, **kwargs):
555 """
556 Schedule a shell command for local or distant parallel execution. This
557 essential method creates a local or remote Worker (depending on the
558 presence of the nodes parameter) and immediately schedules it for
559 execution in task's runloop. So, if the task is already running
560 (ie. called from an event handler), the command is started immediately,
561 assuming current execution constraints are met (eg. fanout value). If
562 the task is not running, the command is not started but scheduled for
563 late execution. See resume() to start task runloop.
564
565 The following optional parameters are passed to the underlying local
566 or remote Worker constructor:
567
568 - handler: EventHandler instance to notify (on event) -- default is
569 no handler (None)
570 - timeout: command timeout delay expressed in second using a floating
571 point value -- default is unlimited (None)
572 - autoclose: if set to True, the underlying Worker is automatically
573 aborted as soon as all other non-autoclosing task objects (workers,
574 ports, timers) have finished -- default is False
575 - stderr: separate stdout/stderr if set to True -- default is False.
576 - stdin: enable stdin if set to True or prevent its use otherwise --
577 default is True.
578
579 Local usage:
580 task.shell(command [, key=key] [, handler=handler]
581 [, timeout=secs] [, autoclose=enable_autoclose]
582 [, stderr=enable_stderr][, stdin=enable_stdin]))
583
584 Distant usage:
585 task.shell(command, nodes=nodeset [, handler=handler]
586 [, timeout=secs], [, autoclose=enable_autoclose]
587 [, tree=None|False|True] [, remote=False|True]
588 [, stderr=enable_stderr][, stdin=enable_stdin]))
589
590 Example:
591
592 >>> task = task_self()
593 >>> task.shell("/bin/date", nodes="node[1-2345]")
594 >>> task.resume()
595 """
596
597 handler = kwargs.get("handler", None)
598 timeo = kwargs.get("timeout", None)
599 autoclose = kwargs.get("autoclose", False)
600 stderr = kwargs.get("stderr", self.default("stderr"))
601 stdin = kwargs.get("stdin", self.default("stdin"))
602 remote = kwargs.get("remote", True)
603
604 if kwargs.get("nodes", None):
605 assert kwargs.get("key", None) is None, \
606 "'key' argument not supported for distant command"
607
608 tree = kwargs.get("tree")
609
610 # tree == None means auto
611 if tree != False and self._default_tree_is_enabled():
612 # fail if tree is forced without any topology
613 if tree and self.topology is None:
614 raise TaskError("tree mode required for distant shell "
615 "command with unknown topology!")
616 # create tree worker
617 wrkcls = TreeWorker
618 elif not remote:
619 # create local worker
620 wrkcls = self.default('local_worker')
621 else:
622 # create distant worker
623 wrkcls = self.default('distant_worker')
624
625 worker = wrkcls(NodeSet(kwargs["nodes"]), command=command,
626 handler=handler, stderr=stderr,
627 timeout=timeo, autoclose=autoclose, remote=remote)
628 else:
629 # create old fashioned local worker
630 worker = WorkerPopen(command, key=kwargs.get("key", None),
631 handler=handler, stderr=stderr,
632 timeout=timeo, autoclose=autoclose)
633
634 if not stdin:
635 try:
636 worker.set_write_eof() # prevent reading from stdin
637 except EngineClientError: # not all workers support writing
638 pass
639
640 # schedule worker for execution in this task
641 self.schedule(worker)
642
643 return worker
644
645 def copy(self, source, dest, nodes, **kwargs):
646 """
647 Copy local file to distant nodes.
648
649 Note: in tree mode, copy and rcopy always separate stderr so that
650 the internal tar/scp error messages are not merged into stdout; an
651 explicit stderr=False is then ignored.
652 """
653 assert nodes != None, "local copy not supported"
654
655 handler = kwargs.get("handler", None)
656 stderr = kwargs.get("stderr", self.default("stderr"))
657 timeo = kwargs.get("timeout", None)
658 preserve = kwargs.get("preserve", None)
659 reverse = kwargs.get("reverse", False)
660
661 tree = kwargs.get("tree")
662
663 # tree == None means auto
664 if tree != False and self._default_tree_is_enabled():
665 # fail if tree is forced without any topology
666 if tree and self.topology is None:
667 raise TaskError("tree mode required for distant shell "
668 "command with unknown topology!")
669
670 # create tree worker
671 wrkcls = TreeWorker
672 else:
673 # create a new copy worker
674 wrkcls = self.default('distant_worker')
675
676 worker = wrkcls(nodes, source=source, dest=dest, handler=handler,
677 stderr=stderr, timeout=timeo, preserve=preserve,
678 reverse=reverse)
679
680 self.schedule(worker)
681 return worker
682
683 def rcopy(self, source, dest, nodes, **kwargs):
684 """
685 Copy distant file or directory to local node.
686 """
687 kwargs['reverse'] = True
688 return self.copy(source, dest, nodes, **kwargs)
689
690 @tasksyncmethod()
691 def _add_port(self, port):
692 """Add an EnginePort instance to Engine (private method)."""
693 self._engine.add(port)
694
695 @tasksyncmethod()
696 def remove_port(self, port):
697 """Close and remove a port from task previously created with port()."""
698 self._engine.remove(port)
699
700 def port(self, handler=None, autoclose=False):
701 """
702 Create a new task port. A task port is an abstraction object to
703 deliver messages reliably between tasks.
704
705 Basic rules:
706 - A task can send messages to another task port (thread safe).
707 - A task can receive messages from an acquired port either by
708 setting up a notification mechanism or using a polling
709 mechanism that may block the task waiting for a message
710 sent on the port.
711 - A port can be acquired by one task only.
712
713 If handler is set to a valid EventHandler object, the port is
714 a send-once port, ie. a message sent to this port generates an
715 ev_msg event notification issued the port's task. If handler
716 is not set, the task can only receive messages on the port by
717 calling port.msg_recv().
718 """
719 port = EnginePort(handler, autoclose)
720 self._add_port(port)
721 return port
722
723 def timer(self, fire, handler, interval=-1.0, autoclose=False):
724 """
725 Create a timer bound to this task that fires at a preset time
726 in the future by invoking the ev_timer() method of *handler*
727 (provided EventHandler object). Timers can fire either only
728 once or repeatedly at fixed time intervals. Repeating timers
729 can also have their next firing time manually adjusted.
730
731 The mandatory parameter *fire* sets the firing delay in seconds.
732
733 The optional parameter *interval* sets the firing interval of
734 the timer. If not specified, the timer fires once and then is
735 automatically invalidated.
736
737 Time values are expressed in second using floating point
738 values. Precision is implementation (and system) dependent.
739
740 The optional parameter *autoclose*, if set to True, creates
741 an "autoclosing" timer: it will be automatically invalidated
742 as soon as all other non-autoclosing task's objects (workers,
743 ports, timers) have finished. Default value is False, which
744 means the timer will retain task's runloop until it is
745 invalidated.
746
747 Return a new EngineTimer instance.
748
749 See ClusterShell.Engine.Engine.EngineTimer for more details.
750 """
751 assert fire >= 0.0, \
752 "timer's relative fire time must be a positive floating number"
753
754 timer = EngineTimer(fire, interval, autoclose, handler)
755 # The following method may be sent through msg port (async
756 # call) if called from another task.
757 self._add_timer(timer)
758 # always return new timer (sync)
759 return timer
760
761 @tasksyncmethod()
762 def _add_timer(self, timer):
763 """Add a timer to task engine (thread-safe)."""
764 self._engine.add_timer(timer)
765
766 @tasksyncmethod()
767 def schedule(self, worker):
768 """
769 Schedule a worker for execution, ie. add worker in task running
770 loop. Worker will start processing immediately if the task is
771 running (eg. called from an event handler) or as soon as the
772 task is started otherwise. Only useful for manually instantiated
773 workers, for example:
774
775 >>> task = task_self()
776 >>> worker = WorkerSsh("node[2-3]", None, 10, command="/bin/ls")
777 >>> task.schedule(worker)
778 >>> task.resume()
779 """
780 assert self in Task._tasks.values(), \
781 "deleted task instance, call task_self() again!"
782
783 # bind worker to task self
784 worker._set_task(self)
785
786 # add worker clients to engine
787 for client in worker._engine_clients():
788 self._engine.add(client)
789
790 def _resume_thread(self):
791 """Resume task - called from another thread."""
792 self._suspend_cond.notify_all()
793
794 def _resume(self):
795 """Resume task - called from self thread."""
796 assert self.thread == threading.current_thread()
797 try:
798 try:
799 self._reset()
800 self._run(self.timeout)
801 except EngineTimeoutException:
802 raise TimeoutError()
803 except EngineAbortException as exc:
804 self._terminate(exc.kill)
805 except EngineAlreadyRunningError:
806 raise AlreadyRunningError("task engine is already running")
807 finally:
808 # task becomes joinable
809 self._join_cond.acquire()
810 self._suspend_cond.atomic_inc()
811 self._join_cond.notify_all()
812 self._join_cond.release()
813
814 def resume(self, timeout=None):
815 """
816 Resume task. If task is task_self(), workers are executed in the
817 calling thread so this method will block until all (non-autoclosing)
818 workers have finished. This is always the case for a single-threaded
819 application (eg. which doesn't create other Task() instance than
820 task_self()). Otherwise, the current thread doesn't block. In that
821 case, you may then want to call task_wait() to wait for completion.
822
823 Warning: the timeout parameter can be used to set an hard limit of
824 task execution time (in seconds). In that case, a TimeoutError
825 exception is raised if this delay is reached. Its value is 0 by
826 default, which means no task time limit (TimeoutError is never
827 raised). In order to set a maximum delay for individual command
828 execution, you should use Task.shell()'s timeout parameter instead.
829 """
830 # If you change options here, check Task.run() compatibility.
831
832 self.timeout = timeout
833
834 self._suspend_cond.atomic_dec()
835
836 if self._is_task_self():
837 self._resume()
838 else:
839 self._resume_thread()
840
841 def run(self, command=None, **kwargs):
842 """
843 With arguments, it will schedule a command exactly like a Task.shell()
844 would have done it and run it.
845 This is the easiest way to simply run a command.
846
847 >>> task.run("hostname", nodes="foo")
848
849 Without argument, it starts all outstanding actions.
850 It behaves like Task.resume().
851
852 >>> task.shell("hostname", nodes="foo")
853 >>> task.shell("hostname", nodes="bar")
854 >>> task.run()
855
856 When used with a command, you can set a maximum delay of individual
857 command execution with the help of the timeout parameter (see
858 Task.shell's parameters). You can then listen for ev_close() events
859 and check the timedout boolean in your Worker event handlers, or use
860 num_timeout() or iter_keys_timeout() afterwards.
861 But, when used as an alias to Task.resume(), the timeout parameter
862 sets an hard limit of task execution time. In that case, a TimeoutError
863 exception is raised if this delay is reached.
864 """
865 worker = None
866 timeout = None
867
868 # Both resume() and shell() support a 'timeout' parameter. We need a
869 # trick to behave correctly for both cases.
870 #
871 # Here, we mock: task.resume(10)
872 if type(command) in (int, float):
873 timeout = command
874 command = None
875 # Here, we mock: task.resume(timeout=10)
876 elif 'timeout' in kwargs and command is None:
877 timeout = kwargs.pop('timeout')
878 # All other cases mean a classical: shell(...)
879 # we mock: task.shell("mycommand", [timeout=..., ...])
880 elif command is not None:
881 worker = self.shell(command, **kwargs)
882
883 self.resume(timeout)
884
885 return worker
886
887 @tasksyncmethod()
888 def _suspend_wait(self):
889 """Suspend request received."""
890 assert task_self() == self
891 # atomically set suspend state
892 self._suspend_lock.acquire()
893 self._suspended = True
894 self._suspend_lock.release()
895
896 # wait for special suspend condition, while releasing l_run
897 self._suspend_cond.wait_check(self._run_lock)
898
899 # waking up, atomically unset suspend state
900 self._suspend_lock.acquire()
901 self._suspended = False
902 self._suspend_lock.release()
903
904 def suspend(self):
905 """
906 Suspend task execution. This method may be called from another
907 task (thread-safe). The function returns False if the task
908 cannot be suspended (eg. it's not running), or returns True if
909 the task has been successfully suspended.
910 To resume a suspended task, use task.resume().
911 """
912 # first of all, increase suspend count
913 self._suspend_cond.atomic_inc()
914
915 # call synchronized suspend method
916 self._suspend_wait()
917
918 # wait for stopped task
919 self._run_lock.acquire() # run_lock ownership transfer
920
921 # get result: are we really suspended or just stopped?
922 result = True
923 self._suspend_lock.acquire()
924 if not self._suspended:
925 # not acknowledging suspend state, task is stopped
926 result = False
927 self._run_lock.release()
928 self._suspend_lock.release()
929 return result
930
931 @tasksyncmethod()
932 def _abort(self, kill=False):
933 """Abort request received."""
934 assert task_self() == self
935 # raise an EngineAbortException when task is running
936 self._quit = True
937 self._engine.abort(kill)
938
939 def abort(self, kill=False):
940 """
941 Abort a task. Aborting a task removes (and stops when needed)
942 all workers. If optional parameter kill is True, the task
943 object is unbound from the current thread, so calling
944 task_self() creates a new Task object.
945 """
946 if not self._run_lock.acquire(0):
947 # self._run_lock is locked, try to call synchronized method
948 self._abort(kill)
949 # but there is no guarantee that it has really been called, as the
950 # task could have aborted during the same time, so we use polling
951 while not self._run_lock.acquire(0):
952 sleep(0.001)
953 # in any case, once _run_lock has been acquired, confirm abort
954 self._quit = True
955 self._run_lock.release()
956 if self._is_task_self():
957 self._terminate(kill)
958 else:
959 # abort on stopped/suspended task
960 self._suspend_cond.notify_all()
961
962 def _terminate(self, kill):
963 """
964 Abort completion subroutine.
965 """
966 assert self._quit == True
967
968 # already fully terminated by a prior abort pass (#110)
969 if self._engine is None:
970 return
971
972 self._terminated = True
973
974 if kill:
975 # invalidate dispatch port
976 self._dispatch_port = None
977 # clear engine
978 self._engine.clear(clear_ports=kill)
979 if kill:
980 self._engine.release()
981 self._engine = None
982
983 # clear result objects
984 self._reset()
985
986 # unlock any remaining threads that are waiting for our
987 # termination (late join()s)
988 # must be called after _terminated is set to True
989 self._join_cond.acquire()
990 self._join_cond.notify_all()
991 self._join_cond.release()
992
993 # destroy task if needed
994 if kill:
995 Task._task_lock.acquire()
996 try:
997 del Task._tasks[threading.current_thread()]
998 finally:
999 Task._task_lock.release()
1000
1001 def join(self):
1002 """
1003 Suspend execution of the calling thread until the target task
1004 terminates, unless the target task has already terminated.
1005 """
1006 self._join_cond.acquire()
1007 try:
1008 if self._suspend_cond.suspend_count > 0 and not self._suspended:
1009 # ignore stopped task
1010 return
1011 if self._terminated:
1012 # ignore join() on dead task
1013 return
1014 self._join_cond.wait()
1015 finally:
1016 self._join_cond.release()
1017
1018 def running(self):
1019 """
1020 Return True if the task is running.
1021 """
1022 return self._engine and self._engine.running
1023
1024 def _reset(self):
1025 """
1026 Reset buffers and retcodes management variables.
1027 """
1028 # reinit MsgTree dict
1029 self._msgtrees = {}
1030 # other re-init's
1031 self._d_source_rc = {}
1032 self._d_rc_sources = {}
1033 self._max_rc = None
1034 self._timeout_sources.clear()
1035
1036 def _msgtree(self, sname, strict=True):
1037 """Helper method to return msgtree instance by sname if allowed."""
1038 if self.default("%s_msgtree" % sname):
1039 if sname not in self._msgtrees:
1040 self._msgtrees[sname] = MsgTree()
1041 return self._msgtrees[sname]
1042 elif strict:
1043 raise TaskMsgTreeError("%s_msgtree not set" % sname)
1044
1045 def _msg_add(self, worker, node, sname, msg):
1046 """
1047 Process a new message into Task's MsgTree that is coming from:
1048 - a worker instance of this task
1049 - a node
1050 - a stream name sname (string identifier)
1051 """
1052 assert worker.task == self, "better to add messages from my workers"
1053 msgtree = self._msgtree(sname, strict=False)
1054 # As strict=False, if msgtree is None, this means task is set to NOT
1055 # record messages... in that case we ignore this request, still
1056 # keeping possible existing MsgTree, thus allowing temporarily
1057 # disabled ones.
1058 if msgtree is not None:
1059 msgtree.add((worker, node), msg)
1060
1061 def _rc_set(self, worker, node, rc):
1062 """
1063 Add a worker return code (rc) that is coming from a node of a
1064 worker instance.
1065 """
1066 assert rc is not None
1067
1068 source = (worker, node)
1069
1070 # store rc by source
1071 self._d_source_rc[source] = rc
1072
1073 # store source by rc
1074 self._d_rc_sources.setdefault(rc, set()).add(source)
1075
1076 # update max rc
1077 if self._max_rc is None or rc > self._max_rc:
1078 self._max_rc = rc
1079
1080 def _timeout_add(self, worker, node):
1081 """
1082 Add a timeout indicator that is coming from a node of a worker
1083 instance.
1084 """
1085 # store source in timeout set
1086 self._timeout_sources.add((worker, node))
1087
1088 def _msg_by_source(self, worker, node, sname):
1089 """Get a message by its worker instance, node and stream name."""
1090 msg = self._msgtree(sname).get((worker, node))
1091 if msg is None:
1092 return None
1093 return bytes(msg)
1094
1095 def _call_tree_matcher(self, tree_match_func, match_keys=None, worker=None):
1096 """Call identified tree matcher (items, walk) method with options."""
1097 if isinstance(match_keys, basestring): # change to str for Python 3
1098 raise TypeError("Sequence of keys/nodes expected for 'match_keys'.")
1099 # filter by worker and optionally by matching keys
1100 if worker and match_keys is None:
1101 match = lambda k: k[0] is worker
1102 elif worker and match_keys is not None:
1103 match = lambda k: k[0] is worker and k[1] in match_keys
1104 elif match_keys:
1105 match = lambda k: k[1] in match_keys
1106 else:
1107 match = None
1108 # Call tree matcher function (items or walk)
1109 return tree_match_func(match, itemgetter(1))
1110
1111 def _rc_by_source(self, worker, node):
1112 """Get a return code by worker instance and node."""
1113 return self._d_source_rc[(worker, node)]
1114
1115 def _rc_iter_by_key(self, key):
1116 """
1117 Return an iterator over return codes for the given key.
1118 """
1119 for (w, k), rc in self._d_source_rc.items():
1120 if k == key:
1121 yield rc
1122
1123 def _rc_iter_by_worker(self, worker, match_keys=None):
1124 """
1125 Return an iterator over return codes and keys list for a
1126 specific worker and optional matching keys.
1127 """
1128 if match_keys:
1129 # Use the items iterator for the underlying dict.
1130 for rc, src in self._d_rc_sources.items():
1131 keys = [t[1] for t in src if t[0] is worker and \
1132 t[1] in match_keys]
1133 if len(keys) > 0:
1134 yield rc, keys
1135 else:
1136 for rc, src in self._d_rc_sources.items():
1137 keys = [t[1] for t in src if t[0] is worker]
1138 if len(keys) > 0:
1139 yield rc, keys
1140
1141 def _krc_iter_by_worker(self, worker):
1142 """
1143 Return an iterator over key, rc for a specific worker.
1144 """
1145 for rc, src in self._d_rc_sources.items():
1146 for w, k in src:
1147 if w is worker:
1148 yield k, rc
1149
1150 def _num_timeout_by_worker(self, worker):
1151 """
1152 Return the number of timed out "keys" for a specific worker.
1153 """
1154 cnt = 0
1155 for (w, k) in self._timeout_sources:
1156 if w is worker:
1157 cnt += 1
1158 return cnt
1159
1160 def _iter_keys_timeout_by_worker(self, worker):
1161 """
1162 Iterate over timed out keys (ie. nodes) for a specific worker.
1163 """
1164 for (w, k) in self._timeout_sources:
1165 if w is worker:
1166 yield k
1167
1168 def _flush_buffers_by_worker(self, worker):
1169 """
1170 Remove any messages from specified worker.
1171 """
1172 msgtree = self._msgtree('stdout', strict=False)
1173 if msgtree is not None:
1174 msgtree.remove(lambda k: k[0] == worker)
1175
1176 def _flush_errors_by_worker(self, worker):
1177 """
1178 Remove any error messages from specified worker.
1179 """
1180 errtree = self._msgtree('stderr', strict=False)
1181 if errtree is not None:
1182 errtree.remove(lambda k: k[0] == worker)
1183
1184 def key_buffer(self, key):
1185 """
1186 Get buffer for a specific key. When the key is associated
1187 to multiple workers, the resulting buffer will contain
1188 all workers content that may overlap. This method returns an
1189 empty buffer if key is not found in any workers.
1190 """
1191 msgtree = self._msgtree('stdout')
1192 select_key = lambda k: k[1] == key
1193 return b''.join(bytes(msg) for msg in msgtree.messages(select_key))
1194
1195 node_buffer = key_buffer
1196
1197 def key_error(self, key):
1198 """
1199 Get error buffer for a specific key. When the key is associated
1200 to multiple workers, the resulting buffer will contain all
1201 workers content that may overlap. This method returns an empty
1202 error buffer if key is not found in any workers.
1203 """
1204 errtree = self._msgtree('stderr')
1205 select_key = lambda k: k[1] == key
1206 return b''.join(bytes(msg) for msg in errtree.messages(select_key))
1207
1208 node_error = key_error
1209
1210 def key_retcode(self, key):
1211 """
1212 Return return code for a specific key. When the key is
1213 associated to multiple workers, return the max return
1214 code from these workers. Raises a KeyError if key is not found
1215 in any finished workers.
1216 """
1217 codes = list(self._rc_iter_by_key(key))
1218 if not codes:
1219 raise KeyError(key)
1220 return max(codes)
1221
1222 node_retcode = key_retcode
1223
1224 def max_retcode(self):
1225 """
1226 Get max return code encountered during last run or None in the
1227 following cases:
1228
1229 - all commands timed out
1230 - no command-based worker was executed
1231
1232 How do retcodes work? If the process exits normally, the return
1233 code is its exit status. If the process is terminated by a
1234 signal, the return code is 128 + signal number.
1235 """
1236 return self._max_rc
1237
1238 def _iter_msgtree(self, sname, match_keys=None):
1239 """Helper method to iterate over recorded buffers by sname."""
1240 try:
1241 msgtree = self._msgtrees[sname]
1242 return self._call_tree_matcher(msgtree.walk, match_keys)
1243 except KeyError:
1244 if not self.default("%s_msgtree" % sname):
1245 raise TaskMsgTreeError("%s_msgtree not set" % sname)
1246 return iter([])
1247
1248 def iter_buffers(self, match_keys=None):
1249 """
1250 Iterate over buffers, returns a tuple (buffer, keys). For remote
1251 workers (Ssh), keys are list of nodes. In that case, you should use
1252 NodeSet.fromlist(keys) to get a NodeSet instance (which is more
1253 convenient and efficient):
1254
1255 Optional parameter match_keys add filtering on these keys.
1256
1257 Usage example:
1258
1259 >>> for buffer, nodelist in task.iter_buffers():
1260 ... print(NodeSet.fromlist(nodelist))
1261 ... print(buffer.message().decode())
1262 """
1263 return self._iter_msgtree('stdout', match_keys)
1264
1265 def iter_errors(self, match_keys=None):
1266 """
1267 Iterate over error buffers, returns a tuple (buffer, keys).
1268
1269 See iter_buffers().
1270 """
1271 return self._iter_msgtree('stderr', match_keys)
1272
1273 def iter_retcodes(self, match_keys=None):
1274 """
1275 Iterate over return codes of command-based workers, returns a
1276 tuple (rc, keys).
1277
1278 Optional parameter *match_keys* add filtering on these keys.
1279
1280 How do retcodes work? If the process exits normally, the return
1281 code is its exit status. If the process is terminated by a
1282 signal, the return code is 128 + signal number.
1283 """
1284 if match_keys:
1285 # Use the items iterator for the underlying dict.
1286 for rc, src in self._d_rc_sources.items():
1287 keys = [t[1] for t in src if t[1] in match_keys]
1288 yield rc, keys
1289 else:
1290 for rc, src in self._d_rc_sources.items():
1291 yield rc, [t[1] for t in src]
1292
1293 def num_timeout(self):
1294 """
1295 Return the number of timed out "keys" (ie. nodes).
1296 """
1297 return len(self._timeout_sources)
1298
1299 def iter_keys_timeout(self):
1300 """
1301 Iterate over timed out keys (ie. nodes).
1302 """
1303 for (w, k) in self._timeout_sources:
1304 yield k
1305
1306 def flush_buffers(self):
1307 """
1308 Flush all task messages (from all task workers).
1309 """
1310 msgtree = self._msgtree('stdout', strict=False)
1311 if msgtree is not None:
1312 msgtree.clear()
1313
1314 def flush_errors(self):
1315 """
1316 Flush all task error messages (from all task workers).
1317 """
1318 errtree = self._msgtree('stderr', strict=False)
1319 if errtree is not None:
1320 errtree.clear()
1321
1322 @classmethod
1323 def wait(cls, from_thread):
1324 """
1325 Class method that blocks calling thread until all tasks have
1326 finished (from a ClusterShell point of view, for instance,
1327 their task.resume() return). It doesn't necessarily mean that
1328 associated threads have finished.
1329 """
1330 Task._task_lock.acquire()
1331 try:
1332 tasks = Task._tasks.copy()
1333 finally:
1334 Task._task_lock.release()
1335 for thread, task in tasks.items():
1336 if thread != from_thread:
1337 task.join()
1338
1339 def _pchannel(self, gateway, metaworker):
1340 """Get propagation channel for gateway (create one if needed).
1341
1342 Use self.gateways dictionary that allows lookup like:
1343 gateway (string) => (worker channel, set of metaworkers)
1344 """
1345 gwstr = str(gateway)
1346
1347 # create gateway channel if needed
1348 if gwstr not in self.gateways:
1349 chan = PropagationChannel(self, gateway)
1350 logger = logging.getLogger(__name__)
1351 logger.debug("pchannel: creating new channel %s", chan)
1352 # invoke gateway
1353 timeout = None # FIXME: handle timeout for gateway channels
1354 wrkcls = self.default('distant_worker')
1355 chanworker = wrkcls(gateway, command=metaworker.invoke_gateway,
1356 handler=chan, stderr=True, timeout=timeout)
1357 chanworker._update_task_rc = False
1358 # gateway is special! define worker._fanout to not rely on the
1359 # engine's fanout, and use the special value FANOUT_UNLIMITED to
1360 # always allow registration of gateways
1361 chanworker._fanout = FANOUT_UNLIMITED
1362 # change default stream names to avoid internal task buffering
1363 # and conform with channel stream names
1364 chanworker.SNAME_STDIN = chan.SNAME_WRITER
1365 chanworker.SNAME_STDOUT = chan.SNAME_READER
1366 chanworker.SNAME_STDERR = chan.SNAME_ERROR
1367 self.schedule(chanworker)
1368 # update gateways dict
1369 self.gateways[gwstr] = (chanworker, set([metaworker]))
1370 else:
1371 # TODO: assert chanworker is running (need Worker.running())
1372 chanworker, metaworkers = self.gateways[gwstr]
1373 metaworkers.add(metaworker)
1374 return chanworker.eh
1375
1376 def _pchannel_release(self, gateway, metaworker):
1377 """Release propagation channel associated to gateway.
1378
1379 Lookup by gateway, decref associated metaworker set and abort channel
1380 worker if not used anymore.
1381
1382 Called by TreeWorker._check_fini()
1383 """
1384 logger = logging.getLogger(__name__)
1385 logger.debug("pchannel_release %s %s", gateway, metaworker)
1386
1387 gwstr = str(gateway)
1388
1389 if gwstr not in self.gateways:
1390 logger.error("pchannel_release: no pchannel found for gateway %s",
1391 gwstr)
1392 else:
1393 # TODO: delay gateway closing when other gateways are running
1394 chanworker, metaworkers = self.gateways[gwstr]
1395 metaworkers.remove(metaworker)
1396 if len(metaworkers) == 0:
1397 logger.debug("pchannel_release: closing channel %s",
1398 chanworker.eh)
1399 # Call PropagationChannel._close() that will close the channel
1400 # properly, update the opened/setup flags and abort the worker.
1401 # We might be in an event handler and we want to make sure we
1402 # ignore any pending messages from this gateway from now on.
1403 chanworker.eh._close(abort=True)
1404
1405 def _pchannel_close(self, gateway, chanworker):
1406 """A propagation channel is closing.
1407
1408 Perform necessary cleanup actions when a gateway channel is closing.
1409
1410 Called by PropagationChannel.ev_close().
1411 """
1412 logger = logging.getLogger(__name__)
1413 logger.debug("pchannel_closing: %s", gateway)
1414 chwrk, metaworkers = self.gateways[gateway]
1415 assert chwrk is chanworker, (chwrk, chanworker)
1416 metaworkers_copy = list(metaworkers)
1417 for mw in metaworkers_copy:
1418 mw._gateway_abort(gateway)
1419 del self.gateways[gateway]
1420
1421
1422 def task_self(defaults=None):
1423 """
1424 Return the current Task object, corresponding to the caller's thread of
1425 control (a Task object is always bound to a specific thread). This function
1426 provided as a convenience is available in the top-level ClusterShell.Task
1427 package namespace.
1428 """
1429 return Task(thread=threading.current_thread(), defaults=defaults)
1430
1431 def task_wait():
1432 """
1433 Suspend execution of the calling thread until all tasks terminate, unless
1434 all tasks have already terminated. This function is provided as a
1435 convenience and is available in the top-level ClusterShell.Task package
1436 namespace.
1437 """
1438 Task.wait(threading.current_thread())
1439
1440 def task_terminate():
1441 """
1442 Destroy the Task instance bound to the current thread. A next call to
1443 task_self() will create a new Task object. Not to be called from a signal
1444 handler. This function provided as a convenience is available in the
1445 top-level ClusterShell.Task package namespace.
1446 """
1447 task_self().abort(kill=True)
1448
1449 def task_cleanup():
1450 """
1451 Cleanup routine to destroy all created tasks. This function provided as a
1452 convenience is available in the top-level ClusterShell.Task package
1453 namespace. This is mainly used for testing purposes and should be avoided
1454 otherwise. task_cleanup() may be called from any threads but not from a
1455 signal handler.
1456 """
1457 # be sure to return to a clean state (no task at all)
1458 while True:
1459 Task._task_lock.acquire()
1460 try:
1461 tasks = Task._tasks.copy()
1462 if len(tasks) == 0:
1463 break
1464 finally:
1465 Task._task_lock.release()
1466 # send abort to all known tasks (it's needed to retry as we may have
1467 # missed the engine notification window (it was just exiting, which is
1468 # quite a common case if we didn't task_join() previously), or we may
1469 # have lost some task's dispatcher port messages.
1470 for task in tasks.values():
1471 task.abort(kill=True)
1472 # also, for other task than self, task.abort() is async and performed
1473 # through an EngineAbortException, so tell the Python scheduler to give
1474 # up control to raise this exception (handled by task._terminate())...
1475 sleep(0.001)