4 # Copyright (C) 2006, 2007, 2008 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 """Module with helper classes and functions for daemons"""
29 from ganeti import utils
32 class Mainloop(object):
33 """Generic mainloop for daemons
38 self._signal_wait = []
39 self.sigchld_handler = None
40 self.sigterm_handler = None
44 # TODO: Does not yet support adding new event sources while running
45 poller = select.poll()
46 for (owner, fd, conditions) in self._io_wait:
47 poller.register(fd, conditions)
49 self.sigchld_handler = utils.SignalHandler([signal.SIGCHLD])
50 self.sigterm_handler = utils.SignalHandler([signal.SIGTERM])
54 io_events = poller.poll(1000)
55 except select.error, err:
56 # EINTR can happen when signals are sent
57 if err.args and err.args[0] in (errno.EINTR,):
63 # Check for I/O events
64 for (evfd, evcond) in io_events:
65 for (owner, fd, conditions) in self._io_wait:
66 if fd == evfd and evcond & conditions:
67 owner.OnIO(fd, evcond)
69 # Check whether signal was raised
70 if self.sigchld_handler.called:
71 for owner in self._signal_wait:
72 owner.OnSignal(signal.SIGCHLD)
73 self.sigchld_handler.Clear()
75 if self.sigterm_handler.called:
77 self.sigterm_handler.Clear()
79 self.sigchld_handler.Reset()
80 self.sigchld_handler = None
81 self.sigterm_handler.Reset()
82 self.sigterm_handler = None
85 def RegisterIO(self, owner, fd, condition):
86 """Registers a receiver for I/O notifications
88 The receiver must support a "OnIO(self, fd, conditions)" function.
91 @param owner: Receiver
93 @param fd: File descriptor
95 @param condition: ORed field of conditions to be notified
99 self._io_wait.append((owner, fd, condition))
101 def RegisterSignal(self, owner):
102 """Registers a receiver for signal notifications
104 The receiver must support a "OnSignal(self, signum)" function.
106 @type owner: instance
107 @param owner: Receiver
110 self._signal_wait.append(owner)