Debian Codegraph @

lib/ClusterShell/Engine/Engine.py

raw symbols SCIP
1 #
2 # Copyright (C) 2007-2016 CEA/DAM
3 # Copyright (C) 2015-2016 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 Interface of underlying Task's Engine.
23
24 An Engine implements a loop your thread enters and uses to call event handlers
25 in response to incoming events (from workers, timers, etc.).
26 """
27
28 import errno
29 import heapq
30 import logging
31 import sys
32 import time
33 import traceback
34
35
36 LOGGER = logging.getLogger(__name__)
37
38 # Engine client fd I/O event interest bits
39 E_READ = 0x1
40 E_WRITE = 0x2
41
42 # Define epsilon value for time float arithmetic operations
43 EPSILON = 1.0e-3
44
45 # Special fanout value for unlimited
46 FANOUT_UNLIMITED = -1
47 # Special fanout value to use default Engine fanout
48 FANOUT_DEFAULT = None
49
50
51 class EngineException(Exception):
52 """
53 Base engine exception.
54 """
55
56 class EngineAbortException(EngineException):
57 """
58 Raised on user abort.
59 """
60 def __init__(self, kill):
61 EngineException.__init__(self)
62 self.kill = kill
63
64 class EngineTimeoutException(EngineException):
65 """
66 Raised when a timeout is encountered.
67 """
68
69 class EngineIllegalOperationError(EngineException):
70 """
71 Error raised when an illegal operation has been performed.
72 """
73
74 class EngineAlreadyRunningError(EngineIllegalOperationError):
75 """
76 Error raised when the engine is already running.
77 """
78
79 class EngineNotSupportedError(EngineException):
80 """
81 Error raised when the engine mechanism is not supported.
82 """
83 def __init__(self, engineid):
84 EngineException.__init__(self)
85 self.engineid = engineid
86
87
88 class EngineBaseTimer(object):
89 """
90 Abstract class for ClusterShell's engine timer. Such a timer
91 requires a relative fire time (delay) in seconds (as float), and
92 supports an optional repeating interval in seconds (as float too).
93
94 See EngineTimer for more information about ClusterShell timers.
95 """
96
97 def __init__(self, fire_delay, interval=-1.0, autoclose=False):
98 """
99 Create a base timer.
100 """
101 # fire_delay is used for comparison between timers and MUST NOT be
102 # None in Python 3 as comparison with float is not possible and could
103 # lead to confusion anyway. If None is passed, fire_delay is now set
104 # to -1 to avoid the timer to be armed in _EngineTimerQ.schedule().
105 if fire_delay is None:
106 self.fire_delay = -1.0
107 else:
108 self.fire_delay = fire_delay
109 self.interval = interval
110 self.autoclose = autoclose
111 self._engine = None
112 self._timercase = None
113
114 def _set_engine(self, engine):
115 """
116 Bind to engine, called by Engine.
117 """
118 if self._engine:
119 # A timer can be registered to only one engine at a time.
120 raise EngineIllegalOperationError("Already bound to engine.")
121
122 self._engine = engine
123
124 def invalidate(self):
125 """
126 Invalidates a timer object, stopping it from ever firing again.
127 """
128 if self._engine:
129 self._engine.timerq.invalidate(self)
130 self._engine = None
131
132 def is_valid(self):
133 """
134 Returns a boolean value that indicates whether an EngineTimer
135 object is valid and able to fire.
136 """
137 return self._engine is not None
138
139 def set_nextfire(self, fire_delay, interval=-1):
140 """
141 Set the next firing delay in seconds for an EngineTimer object.
142
143 The optional parameter *interval* sets the firing interval
144 of the timer. If not specified, the timer fires once and then
145 is automatically invalidated.
146
147 Time values are expressed in second using floating point
148 values. Precision is implementation (and system) dependent.
149
150 It is safe to call this method from the task owning this
151 timer object, in any event handlers, anywhere.
152
153 However, resetting a timer's next firing time may be a
154 relatively expensive operation. It is more efficient to let
155 timers autorepeat or to use this method from the timer's own
156 event handler callback (ie. from its ev_timer).
157 """
158 if not self.is_valid():
159 raise EngineIllegalOperationError("Operation on invalid timer.")
160
161 self.fire_delay = fire_delay
162 self.interval = interval
163 self._engine.timerq.reschedule(self)
164
165 def _fire(self):
166 raise NotImplementedError("Derived classes must implement.")
167
168
169 class EngineTimer(EngineBaseTimer):
170 """
171 Concrete class EngineTimer
172
173 An EngineTimer object represents a timer bound to an engine that
174 fires at a preset time in the future. Timers can fire either only
175 once or repeatedly at fixed time intervals. Repeating timers can
176 also have their next firing time manually adjusted.
177
178 A timer is not a real-time mechanism; it fires when the task's
179 underlying engine to which the timer has been added is running and
180 able to check if the timer's firing time has passed.
181 """
182
183 def __init__(self, fire_delay, interval, autoclose, handler):
184 EngineBaseTimer.__init__(self, fire_delay, interval, autoclose)
185 self.eh = handler
186 assert self.eh is not None, "An event handler is needed for timer."
187
188 def _fire(self):
189 self.eh.ev_timer(self)
190
191 class _EngineTimerQ(object):
192
193 class _EngineTimerCase(object):
194 """
195 Helper class that allows comparisons of fire times, to be easily used
196 in an heapq.
197 """
198 def __init__(self, client):
199 self.client = client
200 self.client._timercase = self
201 # arm timer (first time)
202 assert self.client.fire_delay > -EPSILON
203 self.fire_date = self.client.fire_delay + time.time()
204
205 def __lt__(self, other):
206 # NOTE: add @total_ordering decorator in Python 2.7+
207 return self.fire_date < other.fire_date
208
209 def __cmp__(self, other):
210 # DEPRECATED: no longer used in Python 3
211 return cmp(self.fire_date, other.fire_date)
212
213 def arm(self, client):
214 assert client is not None
215 self.client = client
216 self.client._timercase = self
217 # setup next firing date
218 time_current = time.time()
219 if self.client.fire_delay > -EPSILON:
220 self.fire_date = self.client.fire_delay + time_current
221 else:
222 interval = float(self.client.interval)
223 assert interval > 0
224 # Keep it simple: increase fire_date by interval even if
225 # fire_date stays in the past, as in that case it's going to
226 # fire again at next runloop anyway.
227 self.fire_date += interval
228 # Just print a debug message that could help detect issues
229 # coming from a long-running timer handler.
230 if self.fire_date < time_current:
231 LOGGER.debug("Warning: passed interval time for %r "
232 "(long running event handler?)", self.client)
233
234 def disarm(self):
235 client = self.client
236 client._timercase = None
237 self.client = None
238 return client
239
240 def armed(self):
241 return self.client is not None
242
243
244 def __init__(self, engine):
245 """
246 Initializer.
247 """
248 self._engine = engine
249 self.timers = []
250 self.armed_count = 0
251
252 def __len__(self):
253 """
254 Return the number of active timers.
255 """
256 return self.armed_count
257
258 def schedule(self, client):
259 """
260 Insert and arm a client's timer.
261 """
262 # arm only if fire is set
263 if client.fire_delay > -EPSILON:
264 heapq.heappush(self.timers, _EngineTimerQ._EngineTimerCase(client))
265 self.armed_count += 1
266 if not client.autoclose:
267 self._engine.evlooprefcnt += 1
268
269 def reschedule(self, client):
270 """
271 Re-insert client's timer.
272 """
273 if client._timercase:
274 self.invalidate(client)
275 self._dequeue_disarmed()
276 self.schedule(client)
277
278 def invalidate(self, client):
279 """
280 Invalidate client's timer. Current implementation doesn't really remove
281 the timer, but simply flags it as disarmed.
282 """
283 if not client._timercase:
284 # if timer is being fire, invalidate its values
285 client.fire_delay = -1.0
286 client.interval = -1.0
287 return
288
289 if self.armed_count <= 0:
290 raise ValueError("Engine client timer not found in timer queue")
291
292 client._timercase.disarm()
293 self.armed_count -= 1
294 if not client.autoclose:
295 self._engine.evlooprefcnt -= 1
296
297 def _dequeue_disarmed(self):
298 """
299 Dequeue disarmed timers (sort of garbage collection).
300 """
301 while len(self.timers) > 0 and not self.timers[0].armed():
302 heapq.heappop(self.timers)
303
304 def fire_expired(self):
305 """
306 Remove expired timers from the queue and fire associated clients.
307 """
308 self._dequeue_disarmed()
309
310 # Build a queue of expired timercases. Any expired (and still armed)
311 # timer is fired, but only once per call.
312 expired_timercases = []
313 now = time.time()
314 while self.timers and self.timers[0].fire_date <= now:
315 expired_timercases.append(heapq.heappop(self.timers))
316 self._dequeue_disarmed()
317
318 for timercase in expired_timercases:
319 # Be careful to recheck and skip any disarmed timers (eg. timer
320 # could be invalidated from another timer's event handler)
321 if not timercase.armed():
322 continue
323
324 # Disarm timer
325 client = timercase.disarm()
326
327 # Fire timer
328 client.fire_delay = -1.0
329 client._fire()
330
331 # Rearm it if needed - Note: fire=0 is valid, interval=0 is not
332 if client.fire_delay >= -EPSILON or client.interval > EPSILON:
333 timercase.arm(client)
334 heapq.heappush(self.timers, timercase)
335 else:
336 self.armed_count -= 1
337 if not client.autoclose:
338 self._engine.evlooprefcnt -= 1
339
340 def nextfire_delay(self):
341 """
342 Return next timer fire delay (relative time).
343 """
344 self._dequeue_disarmed()
345 if len(self.timers) > 0:
346 return max(0., self.timers[0].fire_date - time.time())
347
348 return -1
349
350 def clear(self):
351 """
352 Stop and clear all timers.
353 """
354 for timer in self.timers:
355 if timer.armed():
356 timer.client.invalidate()
357
358 self.timers = []
359 self.armed_count = 0
360
361
362 class Engine(object):
363 """
364 Base class for ClusterShell Engines.
365
366 Subclasses have to implement a runloop listening for client events.
367 Subclasses that override other than "pure virtual methods" should call
368 corresponding base class methods.
369 """
370
371 identifier = "(none)"
372
373 def __init__(self, info):
374 """Initialize base class."""
375 # take a reference on info dict
376 self.info = info
377
378 # and update engine id
379 self.info['engine'] = self.identifier
380
381 # keep track of all clients
382 self._clients = set()
383 self._ports = set()
384
385 # keep track of the number of registered clients per worker
386 # (this does not include ports)
387 self._reg_stats = {}
388
389 # keep track of registered file descriptors in a dict where keys
390 # are fileno and values are (EngineClient, EngineClientStream) tuples
391 self.reg_clifds = {}
392
393 # fanout cache used to speed up client launch when fanout changed
394 self._prev_fanout = 0 # fanout_diff != 0 the first time
395
396 # Current loop iteration counter. It is the number of performed engine
397 # loops in order to keep track of client registration epoch, so we can
398 # safely process FDs by chunk and re-use FDs (see Engine._fd2client).
399 self._current_loopcnt = 0
400
401 # Current stream being processed
402 self._current_stream = None
403
404 # timer queue to handle both timers and clients timeout
405 self.timerq = _EngineTimerQ(self)
406
407 # reference count to the event loop (must include registered
408 # clients and timers configured WITHOUT autoclose)
409 self.evlooprefcnt = 0
410
411 # running state
412 self.running = False
413 # runloop-has-exited flag
414 self._exited = False
415
416 def release(self):
417 """Release engine-specific resources."""
418 pass
419
420 def clients(self):
421 """Get a copy of clients set."""
422 return self._clients.copy()
423
424 def ports(self):
425 """
426 Get a copy of ports set.
427 """
428 return self._ports.copy()
429
430 def _fd2client(self, fd):
431 client, stream = self.reg_clifds.get(fd, (None, None))
432 if client:
433 if client._reg_epoch < self._current_loopcnt:
434 return client, stream
435 else:
436 LOGGER.debug("_fd2client: ignoring just re-used FD %d",
437 stream.fd)
438 return (None, None)
439
440 def _can_register(self, client):
441 assert not client.registered
442
443 if not client.delayable or client.worker._fanout == FANOUT_UNLIMITED:
444 return True
445 elif client.worker._fanout is FANOUT_DEFAULT:
446 return self._reg_stats.get('default', 0) < self.info['fanout']
447 else:
448 worker = client.worker
449 return self._reg_stats.get(worker, 0) < worker._fanout
450
451 def _update_reg_stats(self, client, offset):
452 if client.worker._fanout is FANOUT_DEFAULT:
453 key = 'default'
454 else:
455 key = client.worker
456 self._reg_stats.setdefault(key, 0)
457 self._reg_stats[key] += offset
458
459 def add(self, client):
460 """Add a client to engine."""
461 # bind to engine
462 client._set_engine(self)
463
464 if client.delayable:
465 # add to regular client set
466 self._clients.add(client)
467 else:
468 # add to port set (non-delayable)
469 self._ports.add(client)
470
471 if self.running and self._can_register(client):
472 # in-fly add if running
473 self.register(client._start())
474
475
476 def _remove(self, client, abort, did_timeout=False):
477 """Remove a client from engine (subroutine)."""
478 # be careful to also remove ports when engine has not started yet
479 if client.registered or not client.delayable:
480 if client.registered:
481 self.unregister(client)
482 # care should be taken to ensure correct closing flags
483 client._close(abort=abort, timeout=did_timeout)
484
485 def remove(self, client, abort=False, did_timeout=False):
486 """
487 Remove a client from engine. Does NOT aim to flush individual stream
488 read buffers.
489 """
490 self._debug("REMOVE %s" % client)
491 if client.delayable:
492 self._clients.remove(client)
493 else:
494 self._ports.remove(client)
495 self._remove(client, abort, did_timeout)
496 # we just removed a client, so start pending client(s)
497 self.start_clients()
498
499 def remove_stream(self, client, stream):
500 """
501 Regular way to remove a client stream from engine, performing
502 needed read flush as needed. If no more retainable stream
503 remains for this client, this method automatically removes the
504 entire client from engine.
505
506 This function does nothing if the stream is not registered.
507 """
508 if stream.fd not in self.reg_clifds:
509 LOGGER.debug("remove_stream: %s not registered", stream)
510 return
511
512 self.unregister_stream(client, stream)
513
514 # _close_stream() will flush pending read buffers so may generate events
515 client._close_stream(stream.name)
516
517 # client may have been removed by previous events, if not check whether
518 # some retained streams still remain
519 if client in self._clients and not client.streams.retained():
520 self.remove(client)
521
522 def clear(self, did_timeout=False, clear_ports=False):
523 """
524 Remove all clients. Does not flush read buffers.
525 Subclasses that override this method should call base class method.
526 """
527 all_clients = [self._clients]
528 if clear_ports:
529 all_clients.append(self._ports)
530
531 for clients in all_clients:
532 while len(clients) > 0:
533 client = clients.pop()
534 self._remove(client, True, did_timeout)
535
536 def register(self, client):
537 """
538 Register an engine client. Subclasses that override this method
539 should call base class method.
540 """
541 assert client in self._clients or client in self._ports
542 assert not client.registered
543
544 self._debug("REG %s (%s)(autoclose=%s)" % \
545 (client.__class__.__name__, client.streams,
546 client.autoclose))
547
548 client.registered = True
549 client._reg_epoch = self._current_loopcnt
550
551 if client.delayable:
552 self._update_reg_stats(client, 1)
553
554 # set interest event bits...
555 for streams, ievent in ((client.streams.active_readers, E_READ),
556 (client.streams.active_writers, E_WRITE)):
557 for stream in streams():
558 self.reg_clifds[stream.fd] = client, stream
559 stream.events |= ievent
560 if not client.autoclose:
561 self.evlooprefcnt += 1
562 self._register_specific(stream.fd, ievent)
563
564 # start timeout timer
565 self.timerq.schedule(client)
566
567 def unregister_stream(self, client, stream):
568 """Unregister a stream from a client."""
569 self._debug("UNREG_STREAM stream=%s" % stream)
570 assert stream is not None and stream.fd is not None
571 assert stream.fd in self.reg_clifds, \
572 "stream fd %d not registered" % stream.fd
573 assert client.registered
574 self._unregister_specific(stream.fd, stream.events & stream.evmask)
575 self._debug("UNREG_STREAM unregistering stream fd %d (%d)" % \
576 (stream.fd, len(client.streams)))
577 stream.events &= ~stream.evmask
578 del self.reg_clifds[stream.fd]
579 if not client.autoclose:
580 self.evlooprefcnt -= 1
581
582 def unregister(self, client):
583 """Unregister a client"""
584 # sanity check
585 assert client.registered
586 self._debug("UNREG %s (%s)" % (client.__class__.__name__, \
587 client.streams))
588
589 # remove timeout timer
590 self.timerq.invalidate(client)
591
592 # clear interest events...
593 for streams, ievent in ((client.streams.active_readers, E_READ),
594 (client.streams.active_writers, E_WRITE)):
595 for stream in streams():
596 if stream.fd in self.reg_clifds:
597 self._unregister_specific(stream.fd, stream.events & ievent)
598 stream.events &= ~ievent
599 del self.reg_clifds[stream.fd]
600 if not client.autoclose:
601 self.evlooprefcnt -= 1
602
603 client.registered = False
604 if client.delayable:
605 self._update_reg_stats(client, -1)
606
607 def modify(self, client, sname, setmask, clearmask):
608 """Modify the next loop interest events bitset for a client stream."""
609 self._debug("MODEV set:0x%x clear:0x%x %s (%s)" % (setmask, clearmask,
610 client, sname))
611 stream = client.streams[sname]
612 stream.new_events &= ~clearmask
613 stream.new_events |= setmask
614
615 if self._current_stream is not stream:
616 # modifying a non processing stream, apply new_events now
617 self.set_events(client, stream)
618
619 def _register_specific(self, fd, event):
620 """Engine-specific register fd for event method."""
621 raise NotImplementedError("Derived classes must implement.")
622
623 def _unregister_specific(self, fd, ev_is_set):
624 """Engine-specific unregister fd method."""
625 raise NotImplementedError("Derived classes must implement.")
626
627 def _modify_specific(self, fd, event, setvalue):
628 """Engine-specific modify fd for event method."""
629 raise NotImplementedError("Derived classes must implement.")
630
631 def set_events(self, client, stream):
632 """Set the active interest events bitset for a client stream."""
633 self._debug("SETEV new_events:0x%x events:0x%x for %s[%s]" % \
634 (stream.new_events, stream.events, client, stream.name))
635
636 if not client.registered:
637 LOGGER.debug("set_events: client %s[%s] not registered",
638 client, stream.name)
639 return
640
641 chgbits = stream.new_events ^ stream.events
642 if chgbits == 0:
643 return
644
645 # configure interest events as appropriate
646 for interest in (E_READ, E_WRITE):
647 if chgbits & interest:
648 assert stream.evmask & interest
649 status = stream.new_events & interest
650 self._modify_specific(stream.fd, interest, status)
651 if status:
652 stream.events |= interest
653 else:
654 stream.events &= ~interest
655
656 stream.new_events = stream.events
657
658 def set_reading(self, client, sname):
659 """Set client reading state."""
660 # listen for readable events
661 self.modify(client, sname, E_READ, 0)
662
663 def set_writing(self, client, sname):
664 """Set client writing state."""
665 # listen for writable events
666 self.modify(client, sname, E_WRITE, 0)
667
668 def add_timer(self, timer):
669 """Add a timer instance to engine."""
670 timer._set_engine(self)
671 self.timerq.schedule(timer)
672
673 def remove_timer(self, timer):
674 """Remove engine timer from engine."""
675 self.timerq.invalidate(timer)
676
677 def fire_timers(self):
678 """Fire expired timers for processing."""
679 # Only fire timers if runloop is still retained
680 if self.evlooprefcnt > 0:
681 # Fire once any expired timers
682 self.timerq.fire_expired()
683
684 def start_ports(self):
685 """Start and register all port clients."""
686 # Ports are special, non-delayable engine clients
687 for port in self._ports:
688 if not port.registered:
689 self._debug("START PORT %s" % port)
690 self.register(port._start())
691
692 def start_clients(self):
693 """Start and register regular engine clients in respect of fanout."""
694 # check if engine fanout has changed
695 # NOTE: worker._fanout live changes not supported (see #323)
696 fanout_diff = self.info['fanout'] - self._prev_fanout
697 if fanout_diff:
698 self._prev_fanout = self.info['fanout']
699
700 for client in self._clients:
701 if not client.registered and self._can_register(client):
702 self._debug("START CLIENT %s" % client.__class__.__name__)
703 self.register(client._start())
704 # if first time or engine fanout has changed, we do a full scan
705 if fanout_diff == 0:
706 # if engine fanout has not changed, we only start 1 client
707 break
708
709 def run(self, timeout):
710 """Run engine in calling thread."""
711 # change to running state
712 if self.running:
713 raise EngineAlreadyRunningError()
714
715 try:
716 self.running = True
717 # start port clients
718 self.start_ports()
719 # peek in ports for early pending messages
720 self.snoop_ports()
721 # start all other clients
722 self.start_clients()
723 # run loop until all clients and timers are removed
724 self.runloop(timeout)
725 except EngineTimeoutException:
726 self.clear(did_timeout=True)
727 raise
728 except: # MUST use BaseException as soon as possible (py2.5+)
729 # The game is over.
730 exc_t, exc_val, exc_tb = sys.exc_info()
731 try:
732 # Close Engine clients
733 self.clear()
734 except:
735 # self.clear() may still generate termination events that
736 # may raises exceptions, overriding the other one above.
737 # In the future, we should block new user events to avoid
738 # that. Also, such cases could be better handled with
739 # BaseException. For now, print a backtrace in debug to
740 # help detect the problem.
741 tbexc = traceback.format_exception(exc_t, exc_val, exc_tb)
742 LOGGER.debug(''.join(tbexc))
743 raise
744 raise
745 finally:
746 # cleanup
747 self.timerq.clear()
748 self.running = False
749 self._prev_fanout = 0
750
751 def snoop_ports(self):
752 """
753 Peek in ports for possible early pending messages.
754 This method simply tries to read port pipes in non-blocking mode.
755 """
756 # make a copy so that early messages on installed ports may
757 # lead to new ports
758 ports = self._ports.copy()
759 for port in ports:
760 try:
761 port._handle_read('in')
762 except (IOError, OSError) as ex:
763 if ex.errno in (errno.EAGAIN, errno.EWOULDBLOCK):
764 # no pending message
765 return
766 # raise any other error
767 raise
768
769 def runloop(self, timeout):
770 """Engine specific run loop. Derived classes must implement."""
771 raise NotImplementedError("Derived classes must implement.")
772
773 def abort(self, kill):
774 """Abort runloop."""
775 if self.running:
776 raise EngineAbortException(kill)
777
778 self.clear(clear_ports=kill)
779
780 def exited(self):
781 """Returns True if the engine has exited the runloop once."""
782 return not self.running and self._exited
783
784 def _debug(self, s):
785 """library engine verbose debugging hook"""
786 #LOGGER.debug(s)
787 pass