1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
|
"""
Utilities for event-driven programming.
$Id$
Copyright (C) 2009 Internet Systems Consortium ("ISC")
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
"""
import asyncore
import rpki.log, rpki.sundial
class iterator(object):
"""Iteration construct for event-driven code. Takes three
arguments:
- Some kind of iterable object
- A callback to call on each item in the iteration
- A callback to call after the iteration terminates.
The item callback receives two arguments: the callable iterator
object and the current value of the iteration. It should call the
iterator (or arrange for the iterator to be called) when it is time
to continue to the next item in the iteration.
The termination callback receives no arguments.
"""
def __init__(self, iterable, item_callback, done_callback):
self.item_callback = item_callback
self.done_callback = done_callback
try:
self.iterator = iter(iterable)
except:
rpki.log.debug("Problem constructing iterator for %s" % repr(iterable))
raise
self()
def __call__(self, *ignored):
try:
self.item_callback(self, self.iterator.next())
except StopIteration:
if self.done_callback is not None:
self.done_callback()
class timer(object):
"""Timer construct for event-driven code. It can be used in either of two ways:
- As a virtual class, in which case the subclass should provide a
handler() method to receive the wakup event when the timer expires; or
- By setting an explicit handler callback, either via the
constructor or the set_handler() method.
Subclassing is probably more Pythonic, but setting an explict
handler turns out to be very convenient when combined with bound
methods to other objects.
"""
## @var queue
# Timer queue, shared by all timer instances (there can be only one queue).
queue = []
def __init__(self, handler = None):
if handler is not None:
self.set_handler(handler)
def set(self, when):
"""Set a timer. Argument can be a datetime, to specify an
absolute time, a timedelta, to specify an offset time, or None, to
indicate that the timer should expire immediately, which can be
useful in avoiding an excessively deep call stack.
"""
if when is None:
self.when = rpki.sundial.now()
elif isinstance(when, rpki.sundial.timedelta):
self.when = rpki.sundial.now() + when
else:
self.when = when
assert isinstance(self.when, rpki.sundial.datetime)
if self not in self.queue:
self.queue.append(self)
self.queue.sort()
def __cmp__(self, other):
return cmp(self.when, other.when)
def cancel(self):
"""Cancel a timer, if it was set."""
try:
self.queue.remove(self)
except ValueError:
pass
def is_set(self):
"""Test whether this timer is currently set."""
return self in self.queue
def handler(self):
"""Handle a timer that has expired. This must either be overriden
by a subclass or set dynamically by set_handler().
"""
raise NotImplementedError
def set_handler(self, handler):
"""Set timer's expiration handler. This is an alternative to
subclassing the timer class, and may be easier to use when
integrating timers into other classes (eg, the handler can be a
bound method to an object in a class representing a network
connection).
"""
self.handler = handler
@classmethod
def runq(cls):
"""Run the timer queue: for each timer whose call time has passed,
pull the timer off the queue and call its handler() method.
"""
while cls.queue and rpki.sundial.now() >= cls.queue[0].when:
cls.queue.pop(0).handler()
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, repr(self.when))
@classmethod
def seconds_until_wakeup(cls):
"""Calculate delay until next timer expires, or None if no timers
are set and we should wait indefinitely. Rounds up to avoid
spinning in select() or poll(). We could calculate fractional
seconds in the right units instead, but select() and poll() don't
even take the same units (argh!), and we're not doing anything
that hair-triggered, so rounding up is simplest.
"""
if not cls.queue:
return None
now = rpki.sundial.now()
if now >= cls.queue[0].when:
return 0
else:
delay = cls.queue[0].when - now
seconds = delay.convert_to_seconds()
if delay.microseconds:
seconds += 1
return seconds
@classmethod
def clear(cls):
"""Cancel every timer on the queue. We could just throw away the
queue content, but this way we can notify subclasses that provide
their own cancel() method.
"""
while cls.queue:
cls.queue.pop(0).cancel()
def event_loop():
"""Replacement for asyncore.loop(), adding timer support."""
while asyncore.socket_map:
asyncore.poll(timer.seconds_until_wakeup(), asyncore.socket_map)
timer.runq()
|