root / daemons / ganeti-confd @ e22af31d
History | View | Annotate | Download (11.8 kB)
1 |
#!/usr/bin/python |
---|---|
2 |
# |
3 |
|
4 |
# Copyright (C) 2009, Google Inc. |
5 |
# |
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. |
10 |
# |
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. |
15 |
# |
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 |
19 |
# 02110-1301, USA. |
20 |
|
21 |
|
22 |
"""Ganeti configuration daemon |
23 |
|
24 |
Ganeti-confd is a daemon to query master candidates for configuration values. |
25 |
It uses UDP+HMAC for authentication with a global cluster key. |
26 |
|
27 |
""" |
28 |
|
29 |
# pylint: disable-msg=C0103 |
30 |
# C0103: Invalid name ganeti-confd |
31 |
|
32 |
import os |
33 |
import sys |
34 |
import logging |
35 |
import time |
36 |
|
37 |
try: |
38 |
# pylint: disable-msg=E0611 |
39 |
from pyinotify import pyinotify |
40 |
except ImportError: |
41 |
import pyinotify |
42 |
|
43 |
from optparse import OptionParser |
44 |
|
45 |
from ganeti import asyncnotifier |
46 |
from ganeti import confd |
47 |
from ganeti.confd import server as confd_server |
48 |
from ganeti import constants |
49 |
from ganeti import errors |
50 |
from ganeti import daemon |
51 |
|
52 |
|
53 |
class ConfdAsyncUDPServer(daemon.AsyncUDPSocket): |
54 |
"""The confd udp server, suitable for use with asyncore. |
55 |
|
56 |
""" |
57 |
def __init__(self, bind_address, port, processor): |
58 |
"""Constructor for ConfdAsyncUDPServer |
59 |
|
60 |
@type bind_address: string |
61 |
@param bind_address: socket bind address ('' for all) |
62 |
@type port: int |
63 |
@param port: udp port |
64 |
@type processor: L{confd.server.ConfdProcessor} |
65 |
@param processor: ConfdProcessor to use to handle queries |
66 |
|
67 |
""" |
68 |
daemon.AsyncUDPSocket.__init__(self) |
69 |
self.bind_address = bind_address |
70 |
self.port = port |
71 |
self.processor = processor |
72 |
self.bind((bind_address, port)) |
73 |
logging.debug("listening on ('%s':%d)", bind_address, port) |
74 |
|
75 |
# this method is overriding a daemon.AsyncUDPSocket method |
76 |
def handle_datagram(self, payload_in, ip, port): |
77 |
try: |
78 |
query = confd.UnpackMagic(payload_in) |
79 |
except errors.ConfdMagicError, err: |
80 |
logging.debug(err) |
81 |
return |
82 |
|
83 |
answer = self.processor.ExecQuery(query, ip, port) |
84 |
if answer is not None: |
85 |
try: |
86 |
self.enqueue_send(ip, port, confd.PackMagic(answer)) |
87 |
except errors.UdpDataSizeError: |
88 |
logging.error("Reply too big to fit in an udp packet.") |
89 |
|
90 |
|
91 |
class ConfdInotifyEventHandler(pyinotify.ProcessEvent): |
92 |
|
93 |
def __init__(self, watch_manager, callback, |
94 |
filename=constants.CLUSTER_CONF_FILE): |
95 |
"""Constructor for ConfdInotifyEventHandler |
96 |
|
97 |
@type watch_manager: pyinotify.WatchManager |
98 |
@param watch_manager: ganeti-confd inotify watch manager |
99 |
@type callback: function accepting a boolean |
100 |
@param callback: function to call when an inotify event happens |
101 |
@type filename: string |
102 |
@param filename: config file to watch |
103 |
|
104 |
""" |
105 |
# pylint: disable-msg=W0231 |
106 |
# no need to call the parent's constructor |
107 |
self.watch_manager = watch_manager |
108 |
self.callback = callback |
109 |
self.mask = pyinotify.EventsCodes.ALL_FLAGS["IN_IGNORED"] | \ |
110 |
pyinotify.EventsCodes.ALL_FLAGS["IN_MODIFY"] |
111 |
self.file = filename |
112 |
self.watch_handle = None |
113 |
|
114 |
def enable(self): |
115 |
"""Watch the given file |
116 |
|
117 |
""" |
118 |
if self.watch_handle is None: |
119 |
result = self.watch_manager.add_watch(self.file, self.mask) |
120 |
if not self.file in result or result[self.file] <= 0: |
121 |
raise errors.InotifyError("Could not add inotify watcher") |
122 |
else: |
123 |
self.watch_handle = result[self.file] |
124 |
|
125 |
def disable(self): |
126 |
"""Stop watching the given file |
127 |
|
128 |
""" |
129 |
if self.watch_handle is not None: |
130 |
result = self.watch_manager.rm_watch(self.watch_handle) |
131 |
if result[self.watch_handle]: |
132 |
self.watch_handle = None |
133 |
|
134 |
def process_IN_IGNORED(self, event): |
135 |
# Due to the fact that we monitor just for the cluster config file (rather |
136 |
# than for the whole data dir) when the file is replaced with another one |
137 |
# (which is what happens normally in ganeti) we're going to receive an |
138 |
# IN_IGNORED event from inotify, because of the file removal (which is |
139 |
# contextual with the replacement). In such a case we need to create |
140 |
# another watcher for the "new" file. |
141 |
logging.debug("Received 'ignored' inotify event for %s", event.path) |
142 |
self.watch_handle = None |
143 |
|
144 |
try: |
145 |
# Since the kernel believes the file we were interested in is gone, it's |
146 |
# not going to notify us of any other events, until we set up, here, the |
147 |
# new watch. This is not a race condition, though, since we're anyway |
148 |
# going to realod the file after setting up the new watch. |
149 |
self.callback(False) |
150 |
except: |
151 |
# we need to catch any exception here, log it, but proceed, because even |
152 |
# if we failed handling a single request, we still want the confd to |
153 |
# continue working. |
154 |
logging.error("Unexpected exception", exc_info=True) |
155 |
|
156 |
def process_IN_MODIFY(self, event): |
157 |
# This gets called when the config file is modified. Note that this doesn't |
158 |
# usually happen in Ganeti, as the config file is normally replaced by a |
159 |
# new one, at filesystem level, rather than actually modified (see |
160 |
# utils.WriteFile) |
161 |
logging.debug("Received 'modify' inotify event for %s", event.path) |
162 |
|
163 |
try: |
164 |
self.callback(True) |
165 |
except: |
166 |
# we need to catch any exception here, log it, but proceed, because even |
167 |
# if we failed handling a single request, we still want the confd to |
168 |
# continue working. |
169 |
logging.error("Unexpected exception", exc_info=True) |
170 |
|
171 |
def process_default(self, event): |
172 |
logging.error("Received unhandled inotify event: %s", event) |
173 |
|
174 |
|
175 |
class ConfdConfigurationReloader(object): |
176 |
"""Logic to control when to reload the ganeti configuration |
177 |
|
178 |
This class is able to alter between inotify and polling, to rate-limit the |
179 |
number of reloads. When using inotify it also supports a fallback timed |
180 |
check, to verify that the reload hasn't failed. |
181 |
|
182 |
""" |
183 |
def __init__(self, processor, mainloop): |
184 |
"""Constructor for ConfdConfigurationReloader |
185 |
|
186 |
@type processor: L{confd.server.ConfdProcessor} |
187 |
@param processor: ganeti-confd ConfdProcessor |
188 |
@type mainloop: L{daemon.Mainloop} |
189 |
@param mainloop: ganeti-confd mainloop |
190 |
|
191 |
""" |
192 |
self.processor = processor |
193 |
self.mainloop = mainloop |
194 |
|
195 |
self.polling = True |
196 |
self.last_notification = 0 |
197 |
|
198 |
# Asyncronous inotify handler for config changes |
199 |
self.wm = pyinotify.WatchManager() |
200 |
self.inotify_handler = ConfdInotifyEventHandler(self.wm, self.OnInotify) |
201 |
self.notifier = asyncnotifier.AsyncNotifier(self.wm, self.inotify_handler) |
202 |
|
203 |
self.timer_handle = None |
204 |
self._EnableTimer() |
205 |
|
206 |
def OnInotify(self, notifier_enabled): |
207 |
"""Receive an inotify notification. |
208 |
|
209 |
@type notifier_enabled: boolean |
210 |
@param notifier_enabled: whether the notifier is still enabled |
211 |
|
212 |
""" |
213 |
current_time = time.time() |
214 |
time_delta = current_time - self.last_notification |
215 |
self.last_notification = current_time |
216 |
|
217 |
if time_delta < constants.CONFD_CONFIG_RELOAD_RATELIMIT: |
218 |
logging.debug("Moving from inotify mode to polling mode") |
219 |
self.polling = True |
220 |
if notifier_enabled: |
221 |
self.inotify_handler.disable() |
222 |
|
223 |
if not self.polling and not notifier_enabled: |
224 |
try: |
225 |
self.inotify_handler.enable() |
226 |
except errors.InotifyError: |
227 |
self.polling = True |
228 |
|
229 |
try: |
230 |
reloaded = self.processor.reader.Reload() |
231 |
if reloaded: |
232 |
logging.info("Reloaded ganeti config") |
233 |
else: |
234 |
logging.debug("Skipped double config reload") |
235 |
except errors.ConfigurationError: |
236 |
self.DisableConfd() |
237 |
self.inotify_handler.disable() |
238 |
return |
239 |
|
240 |
# Reset the timer. If we're polling it will go to the polling rate, if |
241 |
# we're not it will delay it again to its base safe timeout. |
242 |
self._ResetTimer() |
243 |
|
244 |
def _DisableTimer(self): |
245 |
if self.timer_handle is not None: |
246 |
self.mainloop.scheduler.cancel(self.timer_handle) |
247 |
self.timer_handle = None |
248 |
|
249 |
def _EnableTimer(self): |
250 |
if self.polling: |
251 |
timeout = constants.CONFD_CONFIG_RELOAD_RATELIMIT |
252 |
else: |
253 |
timeout = constants.CONFD_CONFIG_RELOAD_TIMEOUT |
254 |
|
255 |
if self.timer_handle is None: |
256 |
self.timer_handle = self.mainloop.scheduler.enter( |
257 |
timeout, 1, self.OnTimer, []) |
258 |
|
259 |
def _ResetTimer(self): |
260 |
self._DisableTimer() |
261 |
self._EnableTimer() |
262 |
|
263 |
def OnTimer(self): |
264 |
"""Function called when the timer fires |
265 |
|
266 |
""" |
267 |
self.timer_handle = None |
268 |
reloaded = False |
269 |
was_disabled = False |
270 |
try: |
271 |
if self.processor.reader is None: |
272 |
was_disabled = True |
273 |
self.EnableConfd() |
274 |
reloaded = True |
275 |
else: |
276 |
reloaded = self.processor.reader.Reload() |
277 |
except errors.ConfigurationError: |
278 |
self.DisableConfd(silent=was_disabled) |
279 |
return |
280 |
|
281 |
if self.polling and reloaded: |
282 |
logging.info("Reloaded ganeti config") |
283 |
elif reloaded: |
284 |
# We have reloaded the config files, but received no inotify event. If |
285 |
# an event is pending though, we just happen to have timed out before |
286 |
# receiving it, so this is not a problem, and we shouldn't alert |
287 |
if not self.notifier.check_events() and not was_disabled: |
288 |
logging.warning("Config file reload at timeout (inotify failure)") |
289 |
elif self.polling: |
290 |
# We're polling, but we haven't reloaded the config: |
291 |
# Going back to inotify mode |
292 |
logging.debug("Moving from polling mode to inotify mode") |
293 |
self.polling = False |
294 |
try: |
295 |
self.inotify_handler.enable() |
296 |
except errors.InotifyError: |
297 |
self.polling = True |
298 |
else: |
299 |
logging.debug("Performed configuration check") |
300 |
|
301 |
self._EnableTimer() |
302 |
|
303 |
def DisableConfd(self, silent=False): |
304 |
"""Puts confd in non-serving mode |
305 |
|
306 |
""" |
307 |
if not silent: |
308 |
logging.warning("Confd is being disabled") |
309 |
self.processor.Disable() |
310 |
self.polling = False |
311 |
self._ResetTimer() |
312 |
|
313 |
def EnableConfd(self): |
314 |
self.processor.Enable() |
315 |
logging.warning("Confd is being enabled") |
316 |
self.polling = True |
317 |
self._ResetTimer() |
318 |
|
319 |
|
320 |
def CheckConfd(_, args): |
321 |
"""Initial checks whether to run exit with a failure. |
322 |
|
323 |
""" |
324 |
if args: # confd doesn't take any arguments |
325 |
print >> sys.stderr, ("Usage: %s [-f] [-d] [-b ADDRESS]" % sys.argv[0]) |
326 |
sys.exit(constants.EXIT_FAILURE) |
327 |
|
328 |
# TODO: collapse HMAC daemons handling in daemons GenericMain, when we'll |
329 |
# have more than one. |
330 |
if not os.path.isfile(constants.CONFD_HMAC_KEY): |
331 |
print >> sys.stderr, "Need HMAC key %s to run" % constants.CONFD_HMAC_KEY |
332 |
sys.exit(constants.EXIT_FAILURE) |
333 |
|
334 |
|
335 |
def ExecConfd(options, _): |
336 |
"""Main confd function, executed with PID file held |
337 |
|
338 |
""" |
339 |
# TODO: clarify how the server and reloader variables work (they are |
340 |
# not used) |
341 |
# pylint: disable-msg=W0612 |
342 |
mainloop = daemon.Mainloop() |
343 |
|
344 |
# Asyncronous confd UDP server |
345 |
processor = confd_server.ConfdProcessor() |
346 |
try: |
347 |
processor.Enable() |
348 |
except errors.ConfigurationError: |
349 |
# If enabling the processor has failed, we can still go on, but confd will |
350 |
# be disabled |
351 |
logging.warning("Confd is starting in disabled mode") |
352 |
|
353 |
server = ConfdAsyncUDPServer(options.bind_address, options.port, processor) |
354 |
|
355 |
# Configuration reloader |
356 |
reloader = ConfdConfigurationReloader(processor, mainloop) |
357 |
|
358 |
mainloop.Run() |
359 |
|
360 |
|
361 |
def main(): |
362 |
"""Main function for the confd daemon. |
363 |
|
364 |
""" |
365 |
parser = OptionParser(description="Ganeti configuration daemon", |
366 |
usage="%prog [-f] [-d] [-b ADDRESS]", |
367 |
version="%%prog (ganeti) %s" % |
368 |
constants.RELEASE_VERSION) |
369 |
|
370 |
dirs = [(val, constants.RUN_DIRS_MODE) for val in constants.SUB_RUN_DIRS] |
371 |
dirs.append((constants.LOCK_DIR, 1777)) |
372 |
daemon.GenericMain(constants.CONFD, parser, dirs, CheckConfd, ExecConfd) |
373 |
|
374 |
|
375 |
if __name__ == "__main__": |
376 |
main() |