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 = {}
42 # TODO: Does not yet support adding new event sources while running
43 poller = select.poll()
44 for (owner, fd, conditions) in self._io_wait:
45 poller.register(fd, conditions)
47 self.sigchld_handler = utils.SignalHandler([signal.SIGCHLD])
51 io_events = poller.poll(1000)
52 except select.error, err:
53 # EINTR can happen when signals are sent
54 if err.args and err.args[0] in (errno.EINTR,):
60 # Check for I/O events
61 for (evfd, evcond) in io_events:
62 for (owner, fd, conditions) in self._io_wait:
63 if fd == evfd and evcond & conditions:
64 owner.OnIO(fd, evcond)
66 # Check whether signal was raised
67 if self.sigchld_handler.called:
68 for owner in self._signal_wait:
69 owner.OnSignal(signal.SIGCHLD)
70 self.sigchld_handler.Clear()
72 self.sigchld_handler.Reset()
73 self.sigchld_handler = None
75 def RegisterIO(self, owner, fd, condition):
76 """Registers a receiver for I/O notifications
78 The receiver must support a "OnIO(self, fd, conditions)" function.
81 @param owner: Receiver
83 @param fd: File descriptor
85 @param condition: ORed field of conditions to be notified
89 self._io_wait.append((owner, fd, condition))
91 def RegisterSignal(self, owner):
92 """Registers a receiver for signal notifications
94 The receiver must support a "OnSignal(self, signum)" function.
97 @param owner: Receiver
100 self._signal_wait.append(owner)