ganeti-confd 12 KB
Newer Older
Guido Trotter's avatar
Guido Trotter committed
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
28
#!/usr/bin/python
#

# Copyright (C) 2009, 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.


"""Ganeti configuration daemon

Ganeti-confd is a daemon to query master candidates for configuration values.
It uses UDP+HMAC for authentication with a global cluster key.

"""

Iustin Pop's avatar
Iustin Pop committed
29
30
31
# pylint: disable-msg=C0103
# C0103: Invalid name ganeti-confd

Guido Trotter's avatar
Guido Trotter committed
32
33
34
import os
import sys
import logging
Guido Trotter's avatar
Guido Trotter committed
35
import time
Guido Trotter's avatar
Guido Trotter committed
36

37
try:
Iustin Pop's avatar
Iustin Pop committed
38
  # pylint: disable-msg=E0611
39
40
41
42
  from pyinotify import pyinotify
except ImportError:
  import pyinotify

Guido Trotter's avatar
Guido Trotter committed
43
44
from optparse import OptionParser

45
46
47
from ganeti import asyncnotifier
from ganeti import confd
from ganeti.confd import server as confd_server
Guido Trotter's avatar
Guido Trotter committed
48
49
50
51
52
53
from ganeti import constants
from ganeti import errors
from ganeti import daemon
from ganeti import ssconf


54
class ConfdAsyncUDPServer(daemon.AsyncUDPSocket):
Guido Trotter's avatar
Guido Trotter committed
55
56
57
58
59
60
61
62
63
64
65
  """The confd udp server, suitable for use with asyncore.

  """
  def __init__(self, bind_address, port, processor):
    """Constructor for ConfdAsyncUDPServer

    @type bind_address: string
    @param bind_address: socket bind address ('' for all)
    @type port: int
    @param port: udp port
    @type processor: L{confd.server.ConfdProcessor}
66
    @param processor: ConfdProcessor to use to handle queries
Guido Trotter's avatar
Guido Trotter committed
67
68

    """
69
    daemon.AsyncUDPSocket.__init__(self)
Guido Trotter's avatar
Guido Trotter committed
70
71
72
73
    self.bind_address = bind_address
    self.port = port
    self.processor = processor
    self.bind((bind_address, port))
Iustin Pop's avatar
Iustin Pop committed
74
    logging.debug("listening on ('%s':%d)", bind_address, port)
Guido Trotter's avatar
Guido Trotter committed
75

76
77
  # this method is overriding a daemon.AsyncUDPSocket method
  def handle_datagram(self, payload_in, ip, port):
78
    try:
79
      query = confd.UnpackMagic(payload_in)
80
81
    except errors.ConfdMagicError, err:
      logging.debug(err)
82
83
84
85
      return

    answer =  self.processor.ExecQuery(query, ip, port)
    if answer is not None:
86
      try:
87
        self.enqueue_send(ip, port, confd.PackMagic(answer))
88
89
      except errors.UdpDataSizeError:
        logging.error("Reply too big to fit in an udp packet.")
Guido Trotter's avatar
Guido Trotter committed
90
91
92
93


class ConfdInotifyEventHandler(pyinotify.ProcessEvent):

94
  def __init__(self, watch_manager, callback,
95
               filename=constants.CLUSTER_CONF_FILE):
Guido Trotter's avatar
Guido Trotter committed
96
97
98
99
    """Constructor for ConfdInotifyEventHandler

    @type watch_manager: L{pyinotify.WatchManager}
    @param watch_manager: ganeti-confd inotify watch manager
100
101
    @type callback: function accepting a boolean
    @param callback: function to call when an inotify event happens
102
103
    @type filename: string
    @param filename: config file to watch
Guido Trotter's avatar
Guido Trotter committed
104
105
106
107

    """
    # no need to call the parent's constructor
    self.watch_manager = watch_manager
108
    self.callback = callback
Iustin Pop's avatar
Iustin Pop committed
109
110
    # pylint: disable-msg=E1103
    # pylint for some reason doesn't see the below constants
Guido Trotter's avatar
Guido Trotter committed
111
112
    self.mask = pyinotify.EventsCodes.IN_IGNORED | \
                pyinotify.EventsCodes.IN_MODIFY
113
    self.file = filename
114
    self.watch_handle = None
Guido Trotter's avatar
Guido Trotter committed
115

116
117
  def enable(self):
    """Watch the given file
Guido Trotter's avatar
Guido Trotter committed
118
119

    """
120
121
122
    if self.watch_handle is None:
      result = self.watch_manager.add_watch(self.file, self.mask)
      if not self.file in result or result[self.file] <= 0:
123
        raise errors.InotifyError("Could not add inotify watcher")
124
125
126
127
128
129
130
131
132
133
134
      else:
        self.watch_handle = result[self.file]

  def disable(self):
    """Stop watching the given file

    """
    if self.watch_handle is not None:
      result = self.watch_manager.rm_watch(self.watch_handle)
      if result[self.watch_handle]:
        self.watch_handle = None
Guido Trotter's avatar
Guido Trotter committed
135
136
137
138
139
140
141
142

  def process_IN_IGNORED(self, event):
    # Due to the fact that we monitor just for the cluster config file (rather
    # than for the whole data dir) when the file is replaced with another one
    # (which is what happens normally in ganeti) we're going to receive an
    # IN_IGNORED event from inotify, because of the file removal (which is
    # contextual with the replacement). In such a case we need to create
    # another watcher for the "new" file.
Iustin Pop's avatar
Iustin Pop committed
143
    logging.debug("Received 'ignored' inotify event for %s", event.path)
144
    self.watch_handle = None
Guido Trotter's avatar
Guido Trotter committed
145
146
147
148
149
150

    try:
      # Since the kernel believes the file we were interested in is gone, it's
      # not going to notify us of any other events, until we set up, here, the
      # new watch. This is not a race condition, though, since we're anyway
      # going to realod the file after setting up the new watch.
151
      self.callback(False)
Guido Trotter's avatar
Guido Trotter committed
152
    except errors.ConfdFatalError, err:
Iustin Pop's avatar
Iustin Pop committed
153
      logging.critical("Critical error, shutting down: %s", err)
Guido Trotter's avatar
Guido Trotter committed
154
155
156
157
158
159
160
161
162
163
164
165
      sys.exit(constants.EXIT_FAILURE)
    except:
      # we need to catch any exception here, log it, but proceed, because even
      # if we failed handling a single request, we still want the confd to
      # continue working.
      logging.error("Unexpected exception", exc_info=True)

  def process_IN_MODIFY(self, event):
    # This gets called when the config file is modified. Note that this doesn't
    # usually happen in Ganeti, as the config file is normally replaced by a
    # new one, at filesystem level, rather than actually modified (see
    # utils.WriteFile)
Iustin Pop's avatar
Iustin Pop committed
166
    logging.debug("Received 'modify' inotify event for %s", event.path)
Guido Trotter's avatar
Guido Trotter committed
167
168

    try:
169
      self.callback(True)
Guido Trotter's avatar
Guido Trotter committed
170
    except errors.ConfdFatalError, err:
Iustin Pop's avatar
Iustin Pop committed
171
      logging.critical("Critical error, shutting down: %s", err)
Guido Trotter's avatar
Guido Trotter committed
172
173
174
175
176
177
178
179
      sys.exit(constants.EXIT_FAILURE)
    except:
      # we need to catch any exception here, log it, but proceed, because even
      # if we failed handling a single request, we still want the confd to
      # continue working.
      logging.error("Unexpected exception", exc_info=True)

  def process_default(self, event):
Iustin Pop's avatar
Iustin Pop committed
180
    logging.error("Received unhandled inotify event: %s", event)
Guido Trotter's avatar
Guido Trotter committed
181
182


183
184
185
186
187
188
189
190
class ConfdConfigurationReloader(object):
  """Logic to control when to reload the ganeti configuration

  This class is able to alter between inotify and polling, to rate-limit the
  number of reloads. When using inotify it also supports a fallback timed
  check, to verify that the reload hasn't failed.

  """
191
  def __init__(self, processor, mainloop):
192
193
    """Constructor for ConfdConfigurationReloader

194
195
    @type processor: L{confd.server.ConfdProcessor}
    @param processor: ganeti-confd ConfdProcessor
Guido Trotter's avatar
Guido Trotter committed
196
197
    @type mainloop: L{daemon.Mainloop}
    @param mainloop: ganeti-confd mainloop
198
199

    """
200
    self.processor = processor
Guido Trotter's avatar
Guido Trotter committed
201
202
    self.mainloop = mainloop

Guido Trotter's avatar
Guido Trotter committed
203
    self.polling = True
Guido Trotter's avatar
Guido Trotter committed
204
    self.last_notification = 0
205
206
207

    # Asyncronous inotify handler for config changes
    self.wm = pyinotify.WatchManager()
208
    self.inotify_handler = ConfdInotifyEventHandler(self.wm, self.OnInotify)
209
    self.notifier = asyncnotifier.AsyncNotifier(self.wm, self.inotify_handler)
210

Guido Trotter's avatar
Guido Trotter committed
211
212
213
    self.timer_handle = None
    self._EnableTimer()

214
215
216
217
218
219
220
  def OnInotify(self, notifier_enabled):
    """Receive an inotify notification.

    @type notifier_enabled: boolean
    @param notifier_enabled: whether the notifier is still enabled

    """
Guido Trotter's avatar
Guido Trotter committed
221
222
223
224
225
226
227
228
    current_time = time.time()
    time_delta = current_time - self.last_notification
    self.last_notification = current_time

    if time_delta < constants.CONFD_CONFIG_RELOAD_RATELIMIT:
      logging.debug("Moving from inotify mode to polling mode")
      self.polling = True
      if notifier_enabled:
229
        self.inotify_handler.disable()
Guido Trotter's avatar
Guido Trotter committed
230
231

    if not self.polling and not notifier_enabled:
232
233
234
      try:
        self.inotify_handler.enable()
      except errors.InotifyError:
235
        self.polling = True
236
237

    try:
238
      reloaded = self.processor.reader.Reload()
239
240
241
242
243
      if reloaded:
        logging.info("Reloaded ganeti config")
      else:
        logging.debug("Skipped double config reload")
    except errors.ConfigurationError:
244
245
246
      self.DisableConfd()
      self.inotify_handler.disable()
      return
247

Guido Trotter's avatar
Guido Trotter committed
248
249
    # Reset the timer. If we're polling it will go to the polling rate, if
    # we're not it will delay it again to its base safe timeout.
250
    self._ResetTimer()
Guido Trotter's avatar
Guido Trotter committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266

  def _DisableTimer(self):
    if self.timer_handle is not None:
      self.mainloop.scheduler.cancel(self.timer_handle)
      self.timer_handle = None

  def _EnableTimer(self):
    if self.polling:
      timeout = constants.CONFD_CONFIG_RELOAD_RATELIMIT
    else:
      timeout = constants.CONFD_CONFIG_RELOAD_TIMEOUT

    if self.timer_handle is None:
      self.timer_handle = self.mainloop.scheduler.enter(
        timeout, 1, self.OnTimer, [])

267
268
269
270
  def _ResetTimer(self):
    self._DisableTimer()
    self._EnableTimer()

Guido Trotter's avatar
Guido Trotter committed
271
272
273
274
275
  def OnTimer(self):
    """Function called when the timer fires

    """
    self.timer_handle = None
276
277
    reloaded = False
    was_disabled = False
Guido Trotter's avatar
Guido Trotter committed
278
    try:
279
280
281
282
283
284
      if self.processor.reader is None:
        was_disabled = True
        self.EnableConfd()
        reloaded = True
      else:
        reloaded = self.processor.reader.Reload()
Guido Trotter's avatar
Guido Trotter committed
285
    except errors.ConfigurationError:
286
      self.DisableConfd(silent=was_disabled)
287
      return
Guido Trotter's avatar
Guido Trotter committed
288
289
290
291
292
293
294

    if self.polling and reloaded:
      logging.info("Reloaded ganeti config")
    elif reloaded:
      # We have reloaded the config files, but received no inotify event.  If
      # an event is pending though, we just happen to have timed out before
      # receiving it, so this is not a problem, and we shouldn't alert
295
      if not self.notifier.check_events() and not was_disabled:
Guido Trotter's avatar
Guido Trotter committed
296
297
298
299
300
301
        logging.warning("Config file reload at timeout (inotify failure)")
    elif self.polling:
      # We're polling, but we haven't reloaded the config:
      # Going back to inotify mode
      logging.debug("Moving from polling mode to inotify mode")
      self.polling = False
302
303
304
305
      try:
        self.inotify_handler.enable()
      except errors.InotifyError:
        self.polling = True
Guido Trotter's avatar
Guido Trotter committed
306
307
308
309
    else:
      logging.debug("Performed configuration check")

    self._EnableTimer()
310

311
  def DisableConfd(self, silent=False):
312
313
314
    """Puts confd in non-serving mode

    """
315
316
    if not silent:
      logging.warning("Confd is being disabled")
317
318
319
320
321
322
323
324
325
326
    self.processor.Disable()
    self.polling = False
    self._ResetTimer()

  def EnableConfd(self):
    self.processor.Enable()
    logging.warning("Confd is being enabled")
    self.polling = True
    self._ResetTimer()

327

328
def CheckConfd(_, args):
Michael Hanselmann's avatar
Michael Hanselmann committed
329
  """Initial checks whether to run exit with a failure.
Guido Trotter's avatar
Guido Trotter committed
330
331

  """
332
333
334
335
  if args: # confd doesn't take any arguments
    print >> sys.stderr, ("Usage: %s [-f] [-d] [-b ADDRESS]" % sys.argv[0])
    sys.exit(constants.EXIT_FAILURE)

Guido Trotter's avatar
Guido Trotter committed
336
337
338
339
340
341
342
  # TODO: collapse HMAC daemons handling in daemons GenericMain, when we'll
  # have more than one.
  if not os.path.isfile(constants.HMAC_CLUSTER_KEY):
    print >> sys.stderr, "Need HMAC key %s to run" % constants.HMAC_CLUSTER_KEY
    sys.exit(constants.EXIT_FAILURE)


343
def ExecConfd(options, _):
Michael Hanselmann's avatar
Michael Hanselmann committed
344
  """Main confd function, executed with PID file held
Guido Trotter's avatar
Guido Trotter committed
345
346

  """
347
348
  mainloop = daemon.Mainloop()

Guido Trotter's avatar
Guido Trotter committed
349
  # Asyncronous confd UDP server
350
  processor = confd_server.ConfdProcessor()
351
352
353
  try:
    processor.Enable()
  except errors.ConfigurationError:
354
355
    # If enabling the processor has failed, we can still go on, but confd will
    # be disabled
356
    logging.warning("Confd is starting in disabled mode")
357

Guido Trotter's avatar
Guido Trotter committed
358
359
  server = ConfdAsyncUDPServer(options.bind_address, options.port, processor)

360
  # Configuration reloader
361
  reloader = ConfdConfigurationReloader(processor, mainloop)
362
363

  mainloop.Run()
Guido Trotter's avatar
Guido Trotter committed
364
365
366
367
368
369
370
371
372
373
374
375
376


def main():
  """Main function for the confd daemon.

  """
  parser = OptionParser(description="Ganeti configuration daemon",
                        usage="%prog [-f] [-d] [-b ADDRESS]",
                        version="%%prog (ganeti) %s" %
                        constants.RELEASE_VERSION)

  dirs = [(val, constants.RUN_DIRS_MODE) for val in constants.SUB_RUN_DIRS]
  dirs.append((constants.LOCK_DIR, 1777))
Michael Hanselmann's avatar
Michael Hanselmann committed
377
  daemon.GenericMain(constants.CONFD, parser, dirs, CheckConfd, ExecConfd)
Guido Trotter's avatar
Guido Trotter committed
378
379


Michael Hanselmann's avatar
Michael Hanselmann committed
380
if __name__ == "__main__":
Guido Trotter's avatar
Guido Trotter committed
381
  main()