daemon.py 8.06 KB
Newer Older
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
#
#

# Copyright (C) 2006, 2007, 2008 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Module with helper classes and functions for daemons"""


import select
import signal
import errno
28
import time
29
30
31
32

from ganeti import utils


33
34
35
36
37
38
39
40
41
class Timer(object):
  def __init__(self, owner, timer_id, start, interval, repeat):
    self.owner = owner
    self.timer_id = timer_id
    self.start = start
    self.interval = interval
    self.repeat = repeat


42
43
44
45
46
class Mainloop(object):
  """Generic mainloop for daemons

  """
  def __init__(self):
47
48
49
50
51
52
    """Constructs a new Mainloop instance.

    """
    self._io_wait = {}
    self._io_wait_add = []
    self._io_wait_remove = []
53
    self._signal_wait = []
54
55
56
57
    self._timer_id_last = 0
    self._timer = {}
    self._timer_add = []
    self._timer_remove = []
58

59
60
61
62
63
64
65
66
67
68
69
70
  def Run(self, handle_sigchld=True, handle_sigterm=True, stop_on_empty=False):
    """Runs the mainloop.

    @type handle_sigchld: bool
    @param handle_sigchld: Whether to install handler for SIGCHLD
    @type handle_sigterm: bool
    @param handle_sigterm: Whether to install handler for SIGTERM
    @type stop_on_empty: bool
    @param stop_on_empty: Whether to stop mainloop once all I/O waiters
                          unregistered

    """
71
72
    poller = select.poll()

73
74
75
76
77
    # Setup signal handlers
    if handle_sigchld:
      sigchld_handler = utils.SignalHandler([signal.SIGCHLD])
    else:
      sigchld_handler = None
78
    try:
79
80
81
82
83
84
85
      if handle_sigterm:
        sigterm_handler = utils.SignalHandler([signal.SIGTERM])
      else:
        sigterm_handler = None

      try:
        running = True
86
87
        timeout = None
        timeout_needs_update = True
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

        # Start actual main loop
        while running:
          # Entries could be added again afterwards, hence removing first
          if self._io_wait_remove:
            for fd in self._io_wait_remove:
              try:
                poller.unregister(fd)
              except KeyError:
                pass
              try:
                del self._io_wait[fd]
              except KeyError:
                pass
            self._io_wait_remove = []

          # Add new entries
          if self._io_wait_add:
            for (owner, fd, conditions) in self._io_wait_add:
              self._io_wait[fd] = owner
              poller.register(fd, conditions)
            self._io_wait_add = []

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
          # Add new timers
          if self._timer_add:
            timeout_needs_update = True
            for timer in self._timer_add:
              self._timer[timer.timer_id] = timer
            del self._timer_add[:]

          # Remove timers
          if self._timer_remove:
            timeout_needs_update = True
            for timer_id in self._timer_remove:
              try:
                del self._timer[timer_id]
              except KeyError:
                pass
            del self._timer_remove[:]

128
          # Stop if nothing is listening anymore
129
          if stop_on_empty and not (self._io_wait or self._timer):
130
131
            break

132
133
134
          # Calculate timeout again if required
          if timeout_needs_update:
            timeout = self._CalcTimeout(time.time())
135
            timeout_needs_update = False
136

137
138
          # Wait for I/O events
          try:
139
            io_events = poller.poll(timeout)
140
141
142
143
144
145
146
          except select.error, err:
            # EINTR can happen when signals are sent
            if err.args and err.args[0] in (errno.EINTR,):
              io_events = None
            else:
              raise

147
148
          after_poll = time.time()

149
150
151
152
153
154
155
          if io_events:
            # Check for I/O events
            for (evfd, evcond) in io_events:
              owner = self._io_wait.get(evfd, None)
              if owner:
                owner.OnIO(evfd, evcond)

156
157
158
          if self._timer:
            self._CheckTimers(after_poll)

159
160
161
162
163
164
165
166
167
168
169
170
171
          # Check whether signal was raised
          if sigchld_handler and sigchld_handler.called:
            self._CallSignalWaiters(signal.SIGCHLD)
            sigchld_handler.Clear()

          if sigterm_handler and sigterm_handler.called:
            self._CallSignalWaiters(signal.SIGTERM)
            running = False
            sigterm_handler.Clear()
      finally:
        # Restore signal handlers
        if sigterm_handler:
          sigterm_handler.Reset()
172
    finally:
173
174
      if sigchld_handler:
        sigchld_handler.Reset()
Guido Trotter's avatar
Guido Trotter committed
175

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
  def _CalcTimeout(self, now):
    if not self._timer:
      return None

    timeout = None

    # TODO: Repeating timers

    min_timeout = 0.001

    for timer in self._timer.itervalues():
      time_left = (timer.start + timer.interval) - now
      if timeout is None or time_left < timeout:
        timeout = time_left
      if timeout < 0:
        timeout = 0
        break
      elif timeout < min_timeout:
        timeout = min_timeout
        break

    return timeout * 1000.0

  def _CheckTimers(self, now):
    # TODO: Repeating timers
    for timer in self._timer.itervalues():
      if now < (timer.start + timer.interval):
        continue

      timer.owner.OnTimer(timer.timer_id)

      # TODO: Repeating timers should not be removed
      self._timer_remove.append(timer.timer_id)

210
211
212
213
214
215
216
217
218
  def _CallSignalWaiters(self, signum):
    """Calls all signal waiters for a certain signal.

    @type signum: int
    @param signum: Signal number

    """
    for owner in self._signal_wait:
      owner.OnSignal(signal.SIGCHLD)
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

  def RegisterIO(self, owner, fd, condition):
    """Registers a receiver for I/O notifications

    The receiver must support a "OnIO(self, fd, conditions)" function.

    @type owner: instance
    @param owner: Receiver
    @type fd: int
    @param fd: File descriptor
    @type condition: int
    @param condition: ORed field of conditions to be notified
                      (see select module)

    """
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    # select.Poller also supports file() like objects, but we don't.
    assert isinstance(fd, (int, long)), \
      "Only integers are supported for file descriptors"

    self._io_wait_add.append((owner, fd, condition))

  def UnregisterIO(self, fd):
    """Unregister a file descriptor.

    It'll be unregistered the next time the mainloop checks for it.

    @type fd: int
    @param fd: File descriptor

    """
    # select.Poller also supports file() like objects, but we don't.
    assert isinstance(fd, (int, long)), \
      "Only integers are supported for file descriptors"

    self._io_wait_remove.append(fd)
254
255
256
257
258
259
260
261
262
263
264

  def RegisterSignal(self, owner):
    """Registers a receiver for signal notifications

    The receiver must support a "OnSignal(self, signum)" function.

    @type owner: instance
    @param owner: Receiver

    """
    self._signal_wait.append(owner)
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299

  def AddTimer(self, owner, interval, repeat):
    """Add a new timer.

    The receiver must support a "OnTimer(self, timer_id)" function.

    @type owner: instance
    @param owner: Receiver
    @type interval: int or float
    @param interval: Timer interval in seconds
    @type repeat: bool
    @param repeat: Whether this is a repeating timer or one-off

    """
    # TODO: Implement repeating timers
    assert not repeat, "Repeating timers are not yet supported"

    # Get new ID
    self._timer_id_last += 1

    timer_id = self._timer_id_last

    self._timer_add.append(Timer(owner, timer_id, time.time(),
                                 float(interval), repeat))

    return timer_id

  def RemoveTimer(self, timer_id):
    """Removes a timer.

    @type timer_id: int
    @param timer_id: Timer ID

    """
    self._timer_remove.append(timer_id)