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"""
36 from ganeti import utils
37 from ganeti import constants
38 from ganeti import errors
41 class SchedulerBreakout(Exception):
42 """Exception used to get out of the scheduler loop
47 def AsyncoreDelayFunction(timeout):
48 """Asyncore-compatible scheduler delay function.
50 This is a delay function for sched that, rather than actually sleeping,
51 executes asyncore events happening in the meantime.
53 After an event has occurred, rather than returning, it raises a
54 SchedulerBreakout exception, which will force the current scheduler.run()
55 invocation to terminate, so that we can also check for signals. The main loop
56 will then call the scheduler run again, which will allow it to actually
57 process any due events.
59 This is needed because scheduler.run() doesn't support a count=..., as
60 asyncore loop, and the scheduler module documents throwing exceptions from
61 inside the delay function as an allowed usage model.
64 asyncore.loop(timeout=timeout, count=1, use_poll=True)
65 raise SchedulerBreakout()
68 class AsyncoreScheduler(sched.scheduler):
69 """Event scheduler integrated with asyncore
72 def __init__(self, timefunc):
73 sched.scheduler.__init__(self, timefunc, AsyncoreDelayFunction)
76 class AsyncUDPSocket(asyncore.dispatcher):
77 """An improved asyncore udp socket.
81 """Constructor for AsyncUDPSocket
84 asyncore.dispatcher.__init__(self)
86 self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
88 # this method is overriding an asyncore.dispatcher method
89 def handle_connect(self):
90 # Python thinks that the first udp message from a source qualifies as a
91 # "connect" and further ones are part of the same connection. We beg to
92 # differ and treat all messages equally.
97 payload, address = self.recvfrom(constants.MAX_UDP_DATA_SIZE)
98 except socket.error, err:
99 if err.errno == errno.EINTR:
100 # we got a signal while trying to read. no need to do anything,
101 # handle_read will be called again if there is data on the socket.
106 self.handle_datagram(payload, ip, port)
108 # this method is overriding an asyncore.dispatcher method
109 def handle_read(self):
112 except: # pylint: disable-msg=W0702
113 # we need to catch any exception here, log it, but proceed, because even
114 # if we failed handling a single request, we still want to continue.
115 logging.error("Unexpected exception", exc_info=True)
117 def handle_datagram(self, payload, ip, port):
118 """Handle an already read udp datagram
121 raise NotImplementedError
123 # this method is overriding an asyncore.dispatcher method
125 # We should check whether we can write to the socket only if we have
126 # something scheduled to be written
127 return bool(self._out_queue)
129 def handle_write(self):
131 if not self._out_queue:
132 logging.error("handle_write called with empty output queue")
134 (ip, port, payload) = self._out_queue[0]
136 self.sendto(payload, 0, (ip, port))
137 except socket.error, err:
138 if err.errno == errno.EINTR:
139 # we got a signal while trying to write. no need to do anything,
140 # handle_write will be called again because we haven't emptied the
141 # _out_queue, and we'll try again
145 self._out_queue.pop(0)
146 except: # pylint: disable-msg=W0702
147 # we need to catch any exception here, log it, but proceed, because even
148 # if we failed sending a single datagram we still want to continue.
149 logging.error("Unexpected exception", exc_info=True)
151 def enqueue_send(self, ip, port, payload):
152 """Enqueue a datagram to be sent when possible
155 if len(payload) > constants.MAX_UDP_DATA_SIZE:
156 raise errors.UdpDataSizeError('Packet too big: %s > %s' % (len(payload),
157 constants.MAX_UDP_DATA_SIZE))
158 self._out_queue.append((ip, port, payload))
160 def process_next_packet(self, timeout=0):
161 """Process the next datagram, waiting for it if necessary.
164 @param timeout: how long to wait for data
166 @return: True if some data has been handled, False otherwise
169 if utils.WaitForFdCondition(self, select.POLLIN, timeout) & select.POLLIN:
176 class Mainloop(object):
177 """Generic mainloop for daemons
179 @ivar scheduler: A sched.scheduler object, which can be used to register
184 """Constructs a new Mainloop instance.
187 self._signal_wait = []
188 self.scheduler = AsyncoreScheduler(time.time)
190 @utils.SignalHandled([signal.SIGCHLD])
191 @utils.SignalHandled([signal.SIGTERM])
192 def Run(self, signal_handlers=None):
193 """Runs the mainloop.
195 @type signal_handlers: dict
196 @param signal_handlers: signal->L{utils.SignalHandler} passed by decorator
199 assert isinstance(signal_handlers, dict) and \
200 len(signal_handlers) > 0, \
201 "Broken SignalHandled decorator"
203 # Start actual main loop
205 if not self.scheduler.empty():
208 except SchedulerBreakout:
211 asyncore.loop(count=1, use_poll=True)
213 # Check whether a signal was raised
214 for sig in signal_handlers:
215 handler = signal_handlers[sig]
217 self._CallSignalWaiters(sig)
218 running = (sig != signal.SIGTERM)
221 def _CallSignalWaiters(self, signum):
222 """Calls all signal waiters for a certain signal.
225 @param signum: Signal number
228 for owner in self._signal_wait:
229 owner.OnSignal(signum)
231 def RegisterSignal(self, owner):
232 """Registers a receiver for signal notifications
234 The receiver must support a "OnSignal(self, signum)" function.
236 @type owner: instance
237 @param owner: Receiver
240 self._signal_wait.append(owner)
243 def GenericMain(daemon_name, optionparser, dirs, check_fn, exec_fn):
244 """Shared main function for daemons.
246 @type daemon_name: string
247 @param daemon_name: daemon name
248 @type optionparser: optparse.OptionParser
249 @param optionparser: initialized optionparser with daemon-specific options
250 (common -f -d options will be handled by this module)
251 @type dirs: list of strings
252 @param dirs: list of directories that must exist for this daemon to work
253 @type check_fn: function which accepts (options, args)
254 @param check_fn: function that checks start conditions and exits if they're
256 @type exec_fn: function which accepts (options, args)
257 @param exec_fn: function that's executed with the daemon's pid file held, and
258 runs the daemon itself.
261 optionparser.add_option("-f", "--foreground", dest="fork",
262 help="Don't detach from the current terminal",
263 default=True, action="store_false")
264 optionparser.add_option("-d", "--debug", dest="debug",
265 help="Enable some debug messages",
266 default=False, action="store_true")
267 optionparser.add_option("--syslog", dest="syslog",
268 help="Enable logging to syslog (except debug"
269 " messages); one of 'no', 'yes' or 'only' [%s]" %
270 constants.SYSLOG_USAGE,
271 default=constants.SYSLOG_USAGE,
272 choices=["no", "yes", "only"])
273 if daemon_name in constants.DAEMONS_PORTS:
274 # for networked daemons we also allow choosing the bind port and address.
275 # by default we use the port provided by utils.GetDaemonPort, and bind to
276 # 0.0.0.0 (which is represented by and empty bind address.
277 port = utils.GetDaemonPort(daemon_name)
278 optionparser.add_option("-p", "--port", dest="port",
279 help="Network port (%s default)." % port,
280 default=port, type="int")
281 optionparser.add_option("-b", "--bind", dest="bind_address",
283 default="", metavar="ADDRESS")
285 if daemon_name in constants.DAEMONS_SSL:
286 default_cert, default_key = constants.DAEMONS_SSL[daemon_name]
287 optionparser.add_option("--no-ssl", dest="ssl",
288 help="Do not secure HTTP protocol with SSL",
289 default=True, action="store_false")
290 optionparser.add_option("-K", "--ssl-key", dest="ssl_key",
292 default=default_key, type="string")
293 optionparser.add_option("-C", "--ssl-cert", dest="ssl_cert",
294 help="SSL certificate",
295 default=default_cert, type="string")
297 multithread = utils.no_fork = daemon_name in constants.MULTITHREADED_DAEMONS
299 options, args = optionparser.parse_args()
301 if hasattr(options, 'ssl') and options.ssl:
302 if not (options.ssl_cert and options.ssl_key):
303 print >> sys.stderr, "Need key and certificate to use ssl"
304 sys.exit(constants.EXIT_FAILURE)
305 for fname in (options.ssl_cert, options.ssl_key):
306 if not os.path.isfile(fname):
307 print >> sys.stderr, "Need ssl file %s to run" % fname
308 sys.exit(constants.EXIT_FAILURE)
310 if check_fn is not None:
311 check_fn(options, args)
313 utils.EnsureDirs(dirs)
317 utils.Daemonize(logfile=constants.DAEMONS_LOGFILES[daemon_name])
319 utils.WritePidFile(daemon_name)
321 utils.SetupLogging(logfile=constants.DAEMONS_LOGFILES[daemon_name],
323 stderr_logging=not options.fork,
324 multithreaded=multithread,
326 syslog=options.syslog)
327 logging.info("%s daemon startup", daemon_name)
328 exec_fn(options, args)
330 utils.RemovePidFile(daemon_name)