ganeti-watcher 12.7 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
2
3
#!/usr/bin/python
#

4
# Copyright (C) 2006, 2007, 2008 Google Inc.
Iustin Pop's avatar
Iustin Pop committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#
# 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.


"""Tool to restart erronously downed virtual machines.

This program and set of classes implement a watchdog to restart
virtual machines in a Ganeti cluster that have crashed or been killed
by a node reboot.  Run from cron or similar.

28
"""
Iustin Pop's avatar
Iustin Pop committed
29
30
31

import os
import sys
32
import re
Iustin Pop's avatar
Iustin Pop committed
33
34
35
import time
import fcntl
import errno
36
import logging
Iustin Pop's avatar
Iustin Pop committed
37
38
39
40
from optparse import OptionParser

from ganeti import utils
from ganeti import constants
41
from ganeti import serializer
42
from ganeti import ssconf
43
from ganeti import errors
Iustin Pop's avatar
Iustin Pop committed
44
45


46
47
48
49
50
MAXTRIES = 5
BAD_STATES = ['stopped']
HELPLESS_STATES = ['(node down)']
NOTICE = 'NOTICE'
ERROR = 'ERROR'
51
52
53
KEY_RESTART_COUNT = "restart_count"
KEY_RESTART_WHEN = "restart_when"
KEY_BOOT_ID = "bootid"
54
55


Iustin Pop's avatar
Iustin Pop committed
56
57
class Error(Exception):
  """Generic custom error class."""
58
59
60
61


class NotMasterError(Error):
  """Exception raised when this host is not the master."""
Iustin Pop's avatar
Iustin Pop committed
62
63
64
65
66
67
68
69


def Indent(s, prefix='| '):
  """Indent a piece of text with a given prefix before each line.

  Args:
    s: The string to indent
    prefix: The string to prepend each line.
70

Iustin Pop's avatar
Iustin Pop committed
71
72
73
74
75
76
77
78
79
80
81
  """
  return "%s%s\n" % (prefix, ('\n' + prefix).join(s.splitlines()))


def DoCmd(cmd):
  """Run a shell command.

  Args:
    cmd: the command to run.

  Raises CommandError with verbose commentary on error.
82

Iustin Pop's avatar
Iustin Pop committed
83
84
85
86
87
88
89
90
91
92
93
94
95
  """
  res = utils.RunCmd(cmd)

  if res.failed:
    raise Error("Command %s failed:\n%s\nstdout:\n%sstderr:\n%s" %
                (repr(cmd),
                 Indent(res.fail_reason),
                 Indent(res.stdout),
                 Indent(res.stderr)))

  return res


96
97
98
99
100
101
102
103
104
105
106
107
def LockFile(fd):
  """Locks a file using POSIX locks.

  """
  try:
    fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  except IOError, err:
    if err.errno == errno.EAGAIN:
      raise StandardError("File already locked")
    raise


108
class WatcherState(object):
Iustin Pop's avatar
Iustin Pop committed
109
110
111
112
  """Interface to a state file recording restart attempts.

  """
  def __init__(self):
113
114
115
116
117
    """Open, lock, read and parse the file.

    Raises StandardError on lock contention.

    """
Iustin Pop's avatar
Iustin Pop committed
118
119
120
    # The two-step dance below is necessary to allow both opening existing
    # file read/write and creating if not existing.  Vanilla open will truncate
    # an existing file -or- allow creating if not existing.
121
122
    fd = os.open(constants.WATCHER_STATEFILE, os.O_RDWR | os.O_CREAT)
    self.statefile = os.fdopen(fd, 'w+')
Iustin Pop's avatar
Iustin Pop committed
123

124
    LockFile(self.statefile.fileno())
Iustin Pop's avatar
Iustin Pop committed
125

126
    try:
127
      self.data = serializer.Load(self.statefile.read())
128
129
130
    except Exception, msg:
      # Ignore errors while loading the file and treat it as empty
      self.data = {}
131
132
      logging.warning(("Empty or invalid state file. Using defaults."
                       " Error message: %s"), msg)
133
134
135
136
137
138

    if "instance" not in self.data:
      self.data["instance"] = {}
    if "node" not in self.data:
      self.data["node"] = {}

139
140
  def Save(self):
    """Save state to file, then unlock and close it.
141
142

    """
143
144
145
146
147
148
149
150
    assert self.statefile

    # We need to make sure the file is locked before renaming it, otherwise
    # starting ganeti-watcher again at the same time will create a conflict.
    fd = utils.WriteFile(constants.WATCHER_STATEFILE,
                         data=serializer.Dump(self.data),
                         prewrite=LockFile, close=False)
    self.statefile = os.fdopen(fd, 'w+')
151

152
  def Close(self):
153
154
155
156
157
    """Unlock configuration file and close it.

    """
    assert self.statefile

158
    # Files are automatically unlocked when closing them
159
160
161
162
163
    self.statefile.close()
    self.statefile = None

  def GetNodeBootID(self, name):
    """Returns the last boot ID of a node or None.
Iustin Pop's avatar
Iustin Pop committed
164

165
166
167
    """
    ndata = self.data["node"]

168
169
    if name in ndata and KEY_BOOT_ID in ndata[name]:
      return ndata[name][KEY_BOOT_ID]
170
171
172
173
174
175
176
    return None

  def SetNodeBootID(self, name, bootid):
    """Sets the boot ID of a node.

    """
    assert bootid
Iustin Pop's avatar
Iustin Pop committed
177

178
    ndata = self.data["node"]
Iustin Pop's avatar
Iustin Pop committed
179

180
181
182
    if name not in ndata:
      ndata[name] = {}

183
    ndata[name][KEY_BOOT_ID] = bootid
184
185

  def NumberOfRestartAttempts(self, instance):
Iustin Pop's avatar
Iustin Pop committed
186
187
188
189
    """Returns number of previous restart attempts.

    Args:
      instance - the instance to look up.
190

Iustin Pop's avatar
Iustin Pop committed
191
    """
192
    idata = self.data["instance"]
Iustin Pop's avatar
Iustin Pop committed
193

194
    if instance.name in idata:
195
      return idata[instance.name][KEY_RESTART_COUNT]
Iustin Pop's avatar
Iustin Pop committed
196
197
198

    return 0

199
  def RecordRestartAttempt(self, instance):
Iustin Pop's avatar
Iustin Pop committed
200
201
202
203
    """Record a restart attempt.

    Args:
      instance - the instance being restarted
204

Iustin Pop's avatar
Iustin Pop committed
205
    """
206
    idata = self.data["instance"]
Iustin Pop's avatar
Iustin Pop committed
207

208
209
210
211
    if instance.name not in idata:
      inst = idata[instance.name] = {}
    else:
      inst = idata[instance.name]
Iustin Pop's avatar
Iustin Pop committed
212

213
214
    inst[KEY_RESTART_WHEN] = time.time()
    inst[KEY_RESTART_COUNT] = inst.get(KEY_RESTART_COUNT, 0) + 1
Iustin Pop's avatar
Iustin Pop committed
215

216
  def RemoveInstance(self, instance):
217
    """Update state to reflect that a machine is running, i.e. remove record.
Iustin Pop's avatar
Iustin Pop committed
218
219
220
221

    Args:
      instance - the instance to remove from books

222
223
    This method removes the record for a named instance.

Iustin Pop's avatar
Iustin Pop committed
224
    """
225
    idata = self.data["instance"]
Iustin Pop's avatar
Iustin Pop committed
226

227
228
    if instance.name in idata:
      del idata[instance.name]
Iustin Pop's avatar
Iustin Pop committed
229
230
231
232
233
234
235


class Instance(object):
  """Abstraction for a Virtual Machine instance.

  Methods:
    Restart(): issue a command to restart the represented machine.
236

Iustin Pop's avatar
Iustin Pop committed
237
  """
238
  def __init__(self, name, state, autostart):
Iustin Pop's avatar
Iustin Pop committed
239
240
    self.name = name
    self.state = state
241
    self.autostart = autostart
Iustin Pop's avatar
Iustin Pop committed
242
243

  def Restart(self):
244
245
246
    """Encapsulates the start of an instance.

    """
Iustin Pop's avatar
Iustin Pop committed
247
248
    DoCmd(['gnt-instance', 'startup', '--lock-retries=15', self.name])

249
250
251
252
253
254
  def ActivateDisks(self):
    """Encapsulates the activation of all disks of an instance.

    """
    DoCmd(['gnt-instance', 'activate-disks', '--lock-retries=15', self.name])

Iustin Pop's avatar
Iustin Pop committed
255

256
257
def _RunListCmd(cmd):
  """Runs a command and parses its output into lists.
258

Iustin Pop's avatar
Iustin Pop committed
259
  """
260
261
  for line in DoCmd(cmd).stdout.splitlines():
    yield line.split(':')
Iustin Pop's avatar
Iustin Pop committed
262
263


264
265
266
267
268
269
270
271
def GetInstanceList(with_secondaries=None):
  """Get a list of instances on this cluster.

  """
  cmd = ['gnt-instance', 'list', '--lock-retries=15', '--no-headers',
         '--separator=:']

  fields = 'name,oper_state,admin_state'
Iustin Pop's avatar
Iustin Pop committed
272

273
274
  if with_secondaries is not None:
    fields += ',snodes'
Iustin Pop's avatar
Iustin Pop committed
275

276
277
278
279
280
281
282
283
284
  cmd.append('-o')
  cmd.append(fields)

  instances = []
  for fields in _RunListCmd(cmd):
    if with_secondaries is not None:
      (name, status, autostart, snodes) = fields

      if snodes == "-":
Iustin Pop's avatar
Iustin Pop committed
285
        continue
286
287
288
289
290

      for node in with_secondaries:
        if node in snodes.split(','):
          break
      else:
Iustin Pop's avatar
Iustin Pop committed
291
292
        continue

293
294
295
296
    else:
      (name, status, autostart) = fields

    instances.append(Instance(name, status, autostart != "no"))
Iustin Pop's avatar
Iustin Pop committed
297

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
  return instances


def GetNodeBootIDs():
  """Get a dict mapping nodes to boot IDs.

  """
  cmd = ['gnt-node', 'list', '--lock-retries=15', '--no-headers',
         '--separator=:', '-o', 'name,bootid']

  ids = {}
  for fields in _RunListCmd(cmd):
    (name, bootid) = fields
    ids[name] = bootid

  return ids
Iustin Pop's avatar
Iustin Pop committed
314
315


316
class Watcher(object):
Iustin Pop's avatar
Iustin Pop committed
317
318
319
320
321
  """Encapsulate the logic for restarting erronously halted virtual machines.

  The calling program should periodically instantiate me and call Run().
  This will traverse the list of instances, and make up to MAXTRIES attempts
  to restart machines that are down.
322

Iustin Pop's avatar
Iustin Pop committed
323
324
  """
  def __init__(self):
325
326
    sstore = ssconf.SimpleStore()
    master = sstore.GetMasterNode()
327
    if master != utils.HostInfo().name:
328
      raise NotMasterError("This is not the master node")
329
330
    self.instances = GetInstanceList()
    self.bootids = GetNodeBootIDs()
331
    self.started_instances = set()
Iustin Pop's avatar
Iustin Pop committed
332
333

  def Run(self):
334
    notepad = WatcherState()
335
336
337
338
339
340
    try:
      self.CheckInstances(notepad)
      self.CheckDisks(notepad)
      self.VerifyDisks()
    finally:
      notepad.Save()
341
342
343

  def CheckDisks(self, notepad):
    """Check all nodes for restarted ones.
344

Iustin Pop's avatar
Iustin Pop committed
345
    """
346
347
348
349
350
351
352
353
354
355
356
    check_nodes = []
    for name, id in self.bootids.iteritems():
      old = notepad.GetNodeBootID(name)
      if old != id:
        # Node's boot ID has changed, proably through a reboot.
        check_nodes.append(name)

    if check_nodes:
      # Activate disks for all instances with any of the checked nodes as a
      # secondary node.
      for instance in GetInstanceList(with_secondaries=check_nodes):
357
        if not instance.autostart:
358
359
          logging.info(("Skipping disk activation for non-autostart"
                        " instance %s"), instance.name)
360
          continue
361
362
363
364
        if instance.name in self.started_instances:
          # we already tried to start the instance, which should have
          # activated its drives (if they can be at all)
          continue
365
        try:
366
          logging.info("Activating disks for instance %s", instance.name)
367
          instance.ActivateDisks()
368
369
        except Error, err:
          logging.error(str(err), exc_info=True)
370
371
372
373

      # Keep changed boot IDs
      for name in check_nodes:
        notepad.SetNodeBootID(name, self.bootids[name])
Iustin Pop's avatar
Iustin Pop committed
374

375
376
377
378
  def CheckInstances(self, notepad):
    """Make a pass over the list of instances, restarting downed ones.

    """
Iustin Pop's avatar
Iustin Pop committed
379
    for instance in self.instances:
380
381
382
383
      # Don't care about manually stopped instances
      if not instance.autostart:
        continue

Iustin Pop's avatar
Iustin Pop committed
384
      if instance.state in BAD_STATES:
385
        n = notepad.NumberOfRestartAttempts(instance)
Iustin Pop's avatar
Iustin Pop committed
386
387
388
389
390
391
392

        if n > MAXTRIES:
          # stay quiet.
          continue
        elif n < MAXTRIES:
          last = " (Attempt #%d)" % (n + 1)
        else:
393
          notepad.RecordRestartAttempt(instance)
394
395
          logging.error("Could not restart %s after %d attempts, giving up",
                        instance.name, MAXTRIES)
Iustin Pop's avatar
Iustin Pop committed
396
397
          continue
        try:
398
399
          logging.info("Restarting %s%s",
                        instance.name, last)
Iustin Pop's avatar
Iustin Pop committed
400
          instance.Restart()
401
          self.started_instances.add(instance.name)
402
403
        except Error, err:
          logging.error(str(err), exc_info=True)
Iustin Pop's avatar
Iustin Pop committed
404

405
        notepad.RecordRestartAttempt(instance)
Iustin Pop's avatar
Iustin Pop committed
406
      elif instance.state in HELPLESS_STATES:
407
408
        if notepad.NumberOfRestartAttempts(instance):
          notepad.RemoveInstance(instance)
Iustin Pop's avatar
Iustin Pop committed
409
      else:
410
411
        if notepad.NumberOfRestartAttempts(instance):
          notepad.RemoveInstance(instance)
412
          logging.info("Restart of %s succeeded", instance.name)
Iustin Pop's avatar
Iustin Pop committed
413

414
415
416
417
418
419
  def VerifyDisks(self):
    """Run gnt-cluster verify-disks.

    """
    result = DoCmd(['gnt-cluster', 'verify-disks', '--lock-retries=15'])
    if result.output:
420
      logging.info(result.output)
Iustin Pop's avatar
Iustin Pop committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435


def ParseOptions():
  """Parse the command line options.

  Returns:
    (options, args) as from OptionParser.parse_args()

  """
  parser = OptionParser(description="Ganeti cluster watcher",
                        usage="%prog [-d]",
                        version="%%prog (ganeti) %s" %
                        constants.RELEASE_VERSION)

  parser.add_option("-d", "--debug", dest="debug",
436
                    help="Write all messages to stderr",
Iustin Pop's avatar
Iustin Pop committed
437
438
439
440
441
                    default=False, action="store_true")
  options, args = parser.parse_args()
  return options, args


442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
def SetupLogging(debug):
  """Configures the logging module.

  """
  formatter = logging.Formatter("%(asctime)s: %(message)s")

  logfile_handler = logging.FileHandler(constants.LOG_WATCHER)
  logfile_handler.setFormatter(formatter)
  logfile_handler.setLevel(logging.INFO)

  stderr_handler = logging.StreamHandler()
  stderr_handler.setFormatter(formatter)
  if debug:
    stderr_handler.setLevel(logging.NOTSET)
  else:
    stderr_handler.setLevel(logging.CRITICAL)

  root_logger = logging.getLogger("")
  root_logger.setLevel(logging.NOTSET)
  root_logger.addHandler(logfile_handler)
  root_logger.addHandler(stderr_handler)


Iustin Pop's avatar
Iustin Pop committed
465
466
467
468
469
470
def main():
  """Main function.

  """
  options, args = ParseOptions()

471
  SetupLogging(options.debug)
Iustin Pop's avatar
Iustin Pop committed
472
473

  try:
474
475
476
477
478
    try:
      watcher = Watcher()
    except errors.ConfigurationError:
      # Just exit if there's no configuration
      sys.exit(constants.EXIT_SUCCESS)
479
    watcher.Run()
480
481
  except SystemExit:
    raise
482
  except NotMasterError:
483
    logging.debug("Not master, exiting")
484
    sys.exit(constants.EXIT_NOTMASTER)
485
  except errors.ResolverError, err:
486
    logging.error("Cannot resolve hostname '%s', exiting.", err.args[0])
487
    sys.exit(constants.EXIT_NODESETUP_ERROR)
488
489
490
  except Exception, err:
    logging.error(str(err), exc_info=True)
    sys.exit(constants.EXIT_FAILURE)
Iustin Pop's avatar
Iustin Pop committed
491

492

Iustin Pop's avatar
Iustin Pop committed
493
494
if __name__ == '__main__':
  main()