Statistics
| Branch: | Tag: | Revision:

root / lib / watcher / __init__.py @ fb62843c

History | View | Annotate | Download (24.4 kB)

1 9f4bb951 Michael Hanselmann
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 9598b71f Michele Tartara
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 55c85950 Iustin Pop
"""Tool to restart erroneously downed virtual machines.
23 a8083063 Iustin Pop

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

28 5a3103e9 Michael Hanselmann
"""
29 a8083063 Iustin Pop
30 a8083063 Iustin Pop
import os
31 cfcc79c6 Michael Hanselmann
import os.path
32 a8083063 Iustin Pop
import sys
33 a8083063 Iustin Pop
import time
34 438b45d4 Michael Hanselmann
import logging
35 16e0b9c9 Michael Hanselmann
import operator
36 9bb69bb5 Michael Hanselmann
import errno
37 a8083063 Iustin Pop
from optparse import OptionParser
38 a8083063 Iustin Pop
39 a8083063 Iustin Pop
from ganeti import utils
40 a8083063 Iustin Pop
from ganeti import constants
41 83e5e26f René Nussbaumer
from ganeti import compat
42 89e1fc26 Iustin Pop
from ganeti import errors
43 e125c67c Michael Hanselmann
from ganeti import opcodes
44 e125c67c Michael Hanselmann
from ganeti import cli
45 7dfb83c2 Iustin Pop
from ganeti import luxi
46 db147305 Tom Limoncelli
from ganeti import rapi
47 a744b676 Manuel Franceschini
from ganeti import netutils
48 16e0b9c9 Michael Hanselmann
from ganeti import qlang
49 16e0b9c9 Michael Hanselmann
from ganeti import objects
50 16e0b9c9 Michael Hanselmann
from ganeti import ssconf
51 16e0b9c9 Michael Hanselmann
from ganeti import ht
52 57fe4a5b Michael Hanselmann
from ganeti import pathutils
53 a8083063 Iustin Pop
54 b459a848 Andrea Spadaccini
import ganeti.rapi.client # pylint: disable=W0611
55 fc3f75dd Iustin Pop
from ganeti.rapi.client import UsesRapiClient
56 adf6301e Michael Hanselmann
57 adf6301e Michael Hanselmann
from ganeti.watcher import nodemaint
58 adf6301e Michael Hanselmann
from ganeti.watcher import state
59 db147305 Tom Limoncelli
60 a8083063 Iustin Pop
61 5a3103e9 Michael Hanselmann
MAXTRIES = 5
62 b8028dcf Michael Hanselmann
BAD_STATES = compat.UniqueFrozenset([
63 0cc9e018 Michael Hanselmann
  constants.INSTST_ERRORDOWN,
64 0cc9e018 Michael Hanselmann
  ])
65 b8028dcf Michael Hanselmann
HELPLESS_STATES = compat.UniqueFrozenset([
66 0cc9e018 Michael Hanselmann
  constants.INSTST_NODEDOWN,
67 0cc9e018 Michael Hanselmann
  constants.INSTST_NODEOFFLINE,
68 0cc9e018 Michael Hanselmann
  ])
69 0cc9e018 Michael Hanselmann
NOTICE = "NOTICE"
70 0cc9e018 Michael Hanselmann
ERROR = "ERROR"
71 e125c67c Michael Hanselmann
72 16e0b9c9 Michael Hanselmann
#: Number of seconds to wait between starting child processes for node groups
73 16e0b9c9 Michael Hanselmann
CHILD_PROCESS_DELAY = 1.0
74 16e0b9c9 Michael Hanselmann
75 9bb69bb5 Michael Hanselmann
#: How many seconds to wait for instance status file lock
76 9bb69bb5 Michael Hanselmann
INSTANCE_STATUS_LOCK_TIMEOUT = 10.0
77 9bb69bb5 Michael Hanselmann
78 e125c67c Michael Hanselmann
79 7bca53e4 Michael Hanselmann
class NotMasterError(errors.GenericError):
80 38242904 Iustin Pop
  """Exception raised when this host is not the master."""
81 a8083063 Iustin Pop
82 a8083063 Iustin Pop
83 3753b2cb Michael Hanselmann
def ShouldPause():
84 3753b2cb Michael Hanselmann
  """Check whether we should pause.
85 3753b2cb Michael Hanselmann

86 3753b2cb Michael Hanselmann
  """
87 57fe4a5b Michael Hanselmann
  return bool(utils.ReadWatcherPauseFile(pathutils.WATCHER_PAUSEFILE))
88 3753b2cb Michael Hanselmann
89 3753b2cb Michael Hanselmann
90 f1115454 Guido Trotter
def StartNodeDaemons():
91 f1115454 Guido Trotter
  """Start all the daemons that should be running on all nodes.
92 f1115454 Guido Trotter

93 f1115454 Guido Trotter
  """
94 55c85950 Iustin Pop
  # on master or not, try to start the node daemon
95 2826b361 Guido Trotter
  utils.EnsureDaemon(constants.NODED)
96 f1115454 Guido Trotter
  # start confd as well. On non candidates it will be in disabled mode.
97 aa224134 Iustin Pop
  if constants.ENABLE_CONFD:
98 aa224134 Iustin Pop
    utils.EnsureDaemon(constants.CONFD)
99 c300dbe4 Michele Tartara
  # start mond as well: all nodes need monitoring
100 c300dbe4 Michele Tartara
  if constants.ENABLE_MOND:
101 c300dbe4 Michele Tartara
    utils.EnsureDaemon(constants.MOND)
102 c300dbe4 Michele Tartara
103 f1115454 Guido Trotter
104 9e289e36 Guido Trotter
def RunWatcherHooks():
105 9e289e36 Guido Trotter
  """Run the watcher hooks.
106 9e289e36 Guido Trotter

107 9e289e36 Guido Trotter
  """
108 57fe4a5b Michael Hanselmann
  hooks_dir = utils.PathJoin(pathutils.HOOKS_BASE_DIR,
109 c4feafe8 Iustin Pop
                             constants.HOOKS_NAME_WATCHER)
110 10e689d4 Iustin Pop
  if not os.path.isdir(hooks_dir):
111 10e689d4 Iustin Pop
    return
112 9e289e36 Guido Trotter
113 9e289e36 Guido Trotter
  try:
114 9e289e36 Guido Trotter
    results = utils.RunParts(hooks_dir)
115 17385bd2 Andrea Spadaccini
  except Exception, err: # pylint: disable=W0703
116 17385bd2 Andrea Spadaccini
    logging.exception("RunParts %s failed: %s", hooks_dir, err)
117 a0aa6b49 Michael Hanselmann
    return
118 9e289e36 Guido Trotter
119 9e289e36 Guido Trotter
  for (relname, status, runresult) in results:
120 9e289e36 Guido Trotter
    if status == constants.RUNPARTS_SKIP:
121 9e289e36 Guido Trotter
      logging.debug("Watcher hook %s: skipped", relname)
122 9e289e36 Guido Trotter
    elif status == constants.RUNPARTS_ERR:
123 9e289e36 Guido Trotter
      logging.warning("Watcher hook %s: error (%s)", relname, runresult)
124 9e289e36 Guido Trotter
    elif status == constants.RUNPARTS_RUN:
125 9e289e36 Guido Trotter
      if runresult.failed:
126 9e289e36 Guido Trotter
        logging.warning("Watcher hook %s: failed (exit: %d) (output: %s)",
127 9e289e36 Guido Trotter
                        relname, runresult.exit_code, runresult.output)
128 9e289e36 Guido Trotter
      else:
129 9e289e36 Guido Trotter
        logging.debug("Watcher hook %s: success (output: %s)", relname,
130 9e289e36 Guido Trotter
                      runresult.output)
131 013ce4ae Michael Hanselmann
    else:
132 013ce4ae Michael Hanselmann
      raise errors.ProgrammerError("Unknown status %s returned by RunParts",
133 013ce4ae Michael Hanselmann
                                   status)
134 9e289e36 Guido Trotter
135 001b3825 Michael Hanselmann
136 a8083063 Iustin Pop
class Instance(object):
137 a8083063 Iustin Pop
  """Abstraction for a Virtual Machine instance.
138 a8083063 Iustin Pop

139 a8083063 Iustin Pop
  """
140 d962dbf9 Thomas Thrainer
  def __init__(self, name, status, disks_active, snodes):
141 a8083063 Iustin Pop
    self.name = name
142 adf6301e Michael Hanselmann
    self.status = status
143 d962dbf9 Thomas Thrainer
    self.disks_active = disks_active
144 83e5e26f René Nussbaumer
    self.snodes = snodes
145 a8083063 Iustin Pop
146 16e0b9c9 Michael Hanselmann
  def Restart(self, cl):
147 3ecf6786 Iustin Pop
    """Encapsulates the start of an instance.
148 3ecf6786 Iustin Pop

149 3ecf6786 Iustin Pop
    """
150 c873d91c Iustin Pop
    op = opcodes.OpInstanceStartup(instance_name=self.name, force=False)
151 16e0b9c9 Michael Hanselmann
    cli.SubmitOpCode(op, cl=cl)
152 a8083063 Iustin Pop
153 16e0b9c9 Michael Hanselmann
  def ActivateDisks(self, cl):
154 5a3103e9 Michael Hanselmann
    """Encapsulates the activation of all disks of an instance.
155 5a3103e9 Michael Hanselmann

156 5a3103e9 Michael Hanselmann
    """
157 83f5d475 Iustin Pop
    op = opcodes.OpInstanceActivateDisks(instance_name=self.name)
158 16e0b9c9 Michael Hanselmann
    cli.SubmitOpCode(op, cl=cl)
159 a8083063 Iustin Pop
160 a8083063 Iustin Pop
161 16e0b9c9 Michael Hanselmann
class Node:
162 16e0b9c9 Michael Hanselmann
  """Data container representing cluster node.
163 5a3103e9 Michael Hanselmann

164 5a3103e9 Michael Hanselmann
  """
165 16e0b9c9 Michael Hanselmann
  def __init__(self, name, bootid, offline, secondaries):
166 16e0b9c9 Michael Hanselmann
    """Initializes this class.
167 a8083063 Iustin Pop

168 16e0b9c9 Michael Hanselmann
    """
169 16e0b9c9 Michael Hanselmann
    self.name = name
170 16e0b9c9 Michael Hanselmann
    self.bootid = bootid
171 16e0b9c9 Michael Hanselmann
    self.offline = offline
172 16e0b9c9 Michael Hanselmann
    self.secondaries = secondaries
173 5a3103e9 Michael Hanselmann
174 78f44650 Iustin Pop
175 16e0b9c9 Michael Hanselmann
def _CheckInstances(cl, notepad, instances):
176 16e0b9c9 Michael Hanselmann
  """Make a pass over the list of instances, restarting downed ones.
177 5a3103e9 Michael Hanselmann

178 16e0b9c9 Michael Hanselmann
  """
179 16e0b9c9 Michael Hanselmann
  notepad.MaintainInstanceList(instances.keys())
180 78f44650 Iustin Pop
181 16e0b9c9 Michael Hanselmann
  started = set()
182 78f44650 Iustin Pop
183 16e0b9c9 Michael Hanselmann
  for inst in instances.values():
184 16e0b9c9 Michael Hanselmann
    if inst.status in BAD_STATES:
185 16e0b9c9 Michael Hanselmann
      n = notepad.NumberOfRestartAttempts(inst.name)
186 5a3103e9 Michael Hanselmann
187 16e0b9c9 Michael Hanselmann
      if n > MAXTRIES:
188 16e0b9c9 Michael Hanselmann
        logging.warning("Not restarting instance '%s', retries exhausted",
189 16e0b9c9 Michael Hanselmann
                        inst.name)
190 16e0b9c9 Michael Hanselmann
        continue
191 a8083063 Iustin Pop
192 16e0b9c9 Michael Hanselmann
      if n == MAXTRIES:
193 16e0b9c9 Michael Hanselmann
        notepad.RecordRestartAttempt(inst.name)
194 16e0b9c9 Michael Hanselmann
        logging.error("Could not restart instance '%s' after %s attempts,"
195 16e0b9c9 Michael Hanselmann
                      " giving up", inst.name, MAXTRIES)
196 16e0b9c9 Michael Hanselmann
        continue
197 5a3103e9 Michael Hanselmann
198 16e0b9c9 Michael Hanselmann
      try:
199 16e0b9c9 Michael Hanselmann
        logging.info("Restarting instance '%s' (attempt #%s)",
200 16e0b9c9 Michael Hanselmann
                     inst.name, n + 1)
201 16e0b9c9 Michael Hanselmann
        inst.Restart(cl)
202 b459a848 Andrea Spadaccini
      except Exception: # pylint: disable=W0703
203 16e0b9c9 Michael Hanselmann
        logging.exception("Error while restarting instance '%s'", inst.name)
204 16e0b9c9 Michael Hanselmann
      else:
205 16e0b9c9 Michael Hanselmann
        started.add(inst.name)
206 5a3103e9 Michael Hanselmann
207 16e0b9c9 Michael Hanselmann
      notepad.RecordRestartAttempt(inst.name)
208 5a3103e9 Michael Hanselmann
209 16e0b9c9 Michael Hanselmann
    else:
210 16e0b9c9 Michael Hanselmann
      if notepad.NumberOfRestartAttempts(inst.name):
211 16e0b9c9 Michael Hanselmann
        notepad.RemoveInstance(inst.name)
212 16e0b9c9 Michael Hanselmann
        if inst.status not in HELPLESS_STATES:
213 16e0b9c9 Michael Hanselmann
          logging.info("Restart of instance '%s' succeeded", inst.name)
214 a8083063 Iustin Pop
215 16e0b9c9 Michael Hanselmann
  return started
216 a8083063 Iustin Pop
217 a8083063 Iustin Pop
218 16e0b9c9 Michael Hanselmann
def _CheckDisks(cl, notepad, nodes, instances, started):
219 16e0b9c9 Michael Hanselmann
  """Check all nodes for restarted ones.
220 38242904 Iustin Pop

221 a8083063 Iustin Pop
  """
222 16e0b9c9 Michael Hanselmann
  check_nodes = []
223 16e0b9c9 Michael Hanselmann
224 16e0b9c9 Michael Hanselmann
  for node in nodes.values():
225 16e0b9c9 Michael Hanselmann
    old = notepad.GetNodeBootID(node.name)
226 16e0b9c9 Michael Hanselmann
    if not node.bootid:
227 16e0b9c9 Michael Hanselmann
      # Bad node, not returning a boot id
228 16e0b9c9 Michael Hanselmann
      if not node.offline:
229 16e0b9c9 Michael Hanselmann
        logging.debug("Node '%s' missing boot ID, skipping secondary checks",
230 16e0b9c9 Michael Hanselmann
                      node.name)
231 16e0b9c9 Michael Hanselmann
      continue
232 16e0b9c9 Michael Hanselmann
233 16e0b9c9 Michael Hanselmann
    if old != node.bootid:
234 16e0b9c9 Michael Hanselmann
      # Node's boot ID has changed, probably through a reboot
235 16e0b9c9 Michael Hanselmann
      check_nodes.append(node)
236 16e0b9c9 Michael Hanselmann
237 16e0b9c9 Michael Hanselmann
  if check_nodes:
238 16e0b9c9 Michael Hanselmann
    # Activate disks for all instances with any of the checked nodes as a
239 16e0b9c9 Michael Hanselmann
    # secondary node.
240 16e0b9c9 Michael Hanselmann
    for node in check_nodes:
241 16e0b9c9 Michael Hanselmann
      for instance_name in node.secondaries:
242 16e0b9c9 Michael Hanselmann
        try:
243 16e0b9c9 Michael Hanselmann
          inst = instances[instance_name]
244 16e0b9c9 Michael Hanselmann
        except KeyError:
245 16e0b9c9 Michael Hanselmann
          logging.info("Can't find instance '%s', maybe it was ignored",
246 16e0b9c9 Michael Hanselmann
                       instance_name)
247 eee1fa2d Iustin Pop
          continue
248 a8083063 Iustin Pop
249 d962dbf9 Thomas Thrainer
        if not inst.disks_active:
250 d962dbf9 Thomas Thrainer
          logging.info("Skipping disk activation for instance with not"
251 d962dbf9 Thomas Thrainer
                       " activated disks '%s'", inst.name)
252 a8083063 Iustin Pop
          continue
253 16e0b9c9 Michael Hanselmann
254 16e0b9c9 Michael Hanselmann
        if inst.name in started:
255 16e0b9c9 Michael Hanselmann
          # we already tried to start the instance, which should have
256 16e0b9c9 Michael Hanselmann
          # activated its drives (if they can be at all)
257 16e0b9c9 Michael Hanselmann
          logging.debug("Skipping disk activation for instance '%s' as"
258 16e0b9c9 Michael Hanselmann
                        " it was already started", inst.name)
259 a8083063 Iustin Pop
          continue
260 16e0b9c9 Michael Hanselmann
261 a8083063 Iustin Pop
        try:
262 16e0b9c9 Michael Hanselmann
          logging.info("Activating disks for instance '%s'", inst.name)
263 16e0b9c9 Michael Hanselmann
          inst.ActivateDisks(cl)
264 b459a848 Andrea Spadaccini
        except Exception: # pylint: disable=W0703
265 16e0b9c9 Michael Hanselmann
          logging.exception("Error while activating disks for instance '%s'",
266 16e0b9c9 Michael Hanselmann
                            inst.name)
267 a8083063 Iustin Pop
268 16e0b9c9 Michael Hanselmann
    # Keep changed boot IDs
269 16e0b9c9 Michael Hanselmann
    for node in check_nodes:
270 16e0b9c9 Michael Hanselmann
      notepad.SetNodeBootID(node.name, node.bootid)
271 a8083063 Iustin Pop
272 83e5e26f René Nussbaumer
273 16e0b9c9 Michael Hanselmann
def _CheckForOfflineNodes(nodes, instance):
274 16e0b9c9 Michael Hanselmann
  """Checks if given instances has any secondary in offline status.
275 ae1a845c Michael Hanselmann

276 16e0b9c9 Michael Hanselmann
  @param instance: The instance object
277 16e0b9c9 Michael Hanselmann
  @return: True if any of the secondary is offline, False otherwise
278 ae1a845c Michael Hanselmann

279 16e0b9c9 Michael Hanselmann
  """
280 16e0b9c9 Michael Hanselmann
  return compat.any(nodes[node_name].offline for node_name in instance.snodes)
281 ae1a845c Michael Hanselmann
282 ae1a845c Michael Hanselmann
283 16e0b9c9 Michael Hanselmann
def _VerifyDisks(cl, uuid, nodes, instances):
284 16e0b9c9 Michael Hanselmann
  """Run a per-group "gnt-cluster verify-disks".
285 ae1a845c Michael Hanselmann

286 16e0b9c9 Michael Hanselmann
  """
287 16e0b9c9 Michael Hanselmann
  job_id = cl.SubmitJob([opcodes.OpGroupVerifyDisks(group_name=uuid)])
288 16e0b9c9 Michael Hanselmann
  ((_, offline_disk_instances, _), ) = \
289 16e0b9c9 Michael Hanselmann
    cli.PollJob(job_id, cl=cl, feedback_fn=logging.debug)
290 16e0b9c9 Michael Hanselmann
  cl.ArchiveJob(job_id)
291 ae1a845c Michael Hanselmann
292 16e0b9c9 Michael Hanselmann
  if not offline_disk_instances:
293 16e0b9c9 Michael Hanselmann
    # nothing to do
294 16e0b9c9 Michael Hanselmann
    logging.debug("Verify-disks reported no offline disks, nothing to do")
295 16e0b9c9 Michael Hanselmann
    return
296 ae1a845c Michael Hanselmann
297 16e0b9c9 Michael Hanselmann
  logging.debug("Will activate disks for instance(s) %s",
298 16e0b9c9 Michael Hanselmann
                utils.CommaJoin(offline_disk_instances))
299 ae1a845c Michael Hanselmann
300 16e0b9c9 Michael Hanselmann
  # We submit only one job, and wait for it. Not optimal, but this puts less
301 16e0b9c9 Michael Hanselmann
  # load on the job queue.
302 16e0b9c9 Michael Hanselmann
  job = []
303 16e0b9c9 Michael Hanselmann
  for name in offline_disk_instances:
304 16e0b9c9 Michael Hanselmann
    try:
305 16e0b9c9 Michael Hanselmann
      inst = instances[name]
306 16e0b9c9 Michael Hanselmann
    except KeyError:
307 16e0b9c9 Michael Hanselmann
      logging.info("Can't find instance '%s', maybe it was ignored", name)
308 16e0b9c9 Michael Hanselmann
      continue
309 ae1a845c Michael Hanselmann
310 16e0b9c9 Michael Hanselmann
    if inst.status in HELPLESS_STATES or _CheckForOfflineNodes(nodes, inst):
311 40b068e5 Iustin Pop
      logging.info("Skipping instance '%s' because it is in a helpless state"
312 40b068e5 Iustin Pop
                   " or has offline secondaries", name)
313 16e0b9c9 Michael Hanselmann
      continue
314 ae1a845c Michael Hanselmann
315 16e0b9c9 Michael Hanselmann
    job.append(opcodes.OpInstanceActivateDisks(instance_name=name))
316 5188ab37 Iustin Pop
317 16e0b9c9 Michael Hanselmann
  if job:
318 16e0b9c9 Michael Hanselmann
    job_id = cli.SendJob(job, cl=cl)
319 83e5e26f René Nussbaumer
320 16e0b9c9 Michael Hanselmann
    try:
321 16e0b9c9 Michael Hanselmann
      cli.PollJob(job_id, cl=cl, feedback_fn=logging.debug)
322 b459a848 Andrea Spadaccini
    except Exception: # pylint: disable=W0703
323 16e0b9c9 Michael Hanselmann
      logging.exception("Error while activating disks")
324 a8083063 Iustin Pop
325 a8083063 Iustin Pop
326 db147305 Tom Limoncelli
def IsRapiResponding(hostname):
327 db147305 Tom Limoncelli
  """Connects to RAPI port and does a simple test.
328 db147305 Tom Limoncelli

329 db147305 Tom Limoncelli
  Connects to RAPI port of hostname and does a simple test. At this time, the
330 db147305 Tom Limoncelli
  test is GetVersion.
331 db147305 Tom Limoncelli

332 db147305 Tom Limoncelli
  @type hostname: string
333 db147305 Tom Limoncelli
  @param hostname: hostname of the node to connect to.
334 db147305 Tom Limoncelli
  @rtype: bool
335 db147305 Tom Limoncelli
  @return: Whether RAPI is working properly
336 db147305 Tom Limoncelli

337 db147305 Tom Limoncelli
  """
338 34f06005 Iustin Pop
  curl_config = rapi.client.GenericCurlConfig()
339 2a7c3583 Michael Hanselmann
  rapi_client = rapi.client.GanetiRapiClient(hostname,
340 2a7c3583 Michael Hanselmann
                                             curl_config_fn=curl_config)
341 db147305 Tom Limoncelli
  try:
342 db147305 Tom Limoncelli
    master_version = rapi_client.GetVersion()
343 db147305 Tom Limoncelli
  except rapi.client.CertificateError, err:
344 d7c42723 Michael Hanselmann
    logging.warning("RAPI certificate error: %s", err)
345 db147305 Tom Limoncelli
    return False
346 db147305 Tom Limoncelli
  except rapi.client.GanetiApiError, err:
347 d7c42723 Michael Hanselmann
    logging.warning("RAPI error: %s", err)
348 db147305 Tom Limoncelli
    return False
349 d7c42723 Michael Hanselmann
  else:
350 d7c42723 Michael Hanselmann
    logging.debug("Reported RAPI version %s", master_version)
351 d7c42723 Michael Hanselmann
    return master_version == constants.RAPI_VERSION
352 db147305 Tom Limoncelli
353 db147305 Tom Limoncelli
354 a8083063 Iustin Pop
def ParseOptions():
355 a8083063 Iustin Pop
  """Parse the command line options.
356 a8083063 Iustin Pop

357 c41eea6e Iustin Pop
  @return: (options, args) as from OptionParser.parse_args()
358 a8083063 Iustin Pop

359 a8083063 Iustin Pop
  """
360 a8083063 Iustin Pop
  parser = OptionParser(description="Ganeti cluster watcher",
361 a8083063 Iustin Pop
                        usage="%prog [-d]",
362 a8083063 Iustin Pop
                        version="%%prog (ganeti) %s" %
363 a8083063 Iustin Pop
                        constants.RELEASE_VERSION)
364 a8083063 Iustin Pop
365 6d4e8ec0 Iustin Pop
  parser.add_option(cli.DEBUG_OPT)
366 16e0b9c9 Michael Hanselmann
  parser.add_option(cli.NODEGROUP_OPT)
367 f0a80b01 Michael Hanselmann
  parser.add_option("-A", "--job-age", dest="job_age", default=6 * 3600,
368 f07521e5 Iustin Pop
                    help="Autoarchive jobs older than this age (default"
369 f0a80b01 Michael Hanselmann
                          " 6 hours)")
370 46c8a6ab Iustin Pop
  parser.add_option("--ignore-pause", dest="ignore_pause", default=False,
371 46c8a6ab Iustin Pop
                    action="store_true", help="Ignore cluster pause setting")
372 5f01e6ad Michael Hanselmann
  parser.add_option("--wait-children", dest="wait_children",
373 16e0b9c9 Michael Hanselmann
                    action="store_true", help="Wait for child processes")
374 5f01e6ad Michael Hanselmann
  parser.add_option("--no-wait-children", dest="wait_children",
375 40b068e5 Iustin Pop
                    action="store_false",
376 40b068e5 Iustin Pop
                    help="Don't wait for child processes")
377 5f01e6ad Michael Hanselmann
  # See optparse documentation for why default values are not set by options
378 5f01e6ad Michael Hanselmann
  parser.set_defaults(wait_children=True)
379 a8083063 Iustin Pop
  options, args = parser.parse_args()
380 f07521e5 Iustin Pop
  options.job_age = cli.ParseTimespec(options.job_age)
381 f0a80b01 Michael Hanselmann
382 f0a80b01 Michael Hanselmann
  if args:
383 f0a80b01 Michael Hanselmann
    parser.error("No arguments expected")
384 f0a80b01 Michael Hanselmann
385 f0a80b01 Michael Hanselmann
  return (options, args)
386 a8083063 Iustin Pop
387 a8083063 Iustin Pop
388 9bb69bb5 Michael Hanselmann
def _WriteInstanceStatus(filename, data):
389 9bb69bb5 Michael Hanselmann
  """Writes the per-group instance status file.
390 9bb69bb5 Michael Hanselmann

391 9bb69bb5 Michael Hanselmann
  The entries are sorted.
392 8f07dc0d Michael Hanselmann

393 9bb69bb5 Michael Hanselmann
  @type filename: string
394 9bb69bb5 Michael Hanselmann
  @param filename: Path to instance status file
395 9bb69bb5 Michael Hanselmann
  @type data: list of tuple; (instance name as string, status as string)
396 9bb69bb5 Michael Hanselmann
  @param data: Instance name and status
397 8f07dc0d Michael Hanselmann

398 8f07dc0d Michael Hanselmann
  """
399 9bb69bb5 Michael Hanselmann
  logging.debug("Updating instance status file '%s' with %s instances",
400 9bb69bb5 Michael Hanselmann
                filename, len(data))
401 8f07dc0d Michael Hanselmann
402 9bb69bb5 Michael Hanselmann
  utils.WriteFile(filename,
403 9bb69bb5 Michael Hanselmann
                  data="".join(map(compat.partial(operator.mod, "%s %s\n"),
404 9bb69bb5 Michael Hanselmann
                                   sorted(data))))
405 9bb69bb5 Michael Hanselmann
406 9bb69bb5 Michael Hanselmann
407 9bb69bb5 Michael Hanselmann
def _UpdateInstanceStatus(filename, instances):
408 9bb69bb5 Michael Hanselmann
  """Writes an instance status file from L{Instance} objects.
409 9bb69bb5 Michael Hanselmann

410 9bb69bb5 Michael Hanselmann
  @type filename: string
411 9bb69bb5 Michael Hanselmann
  @param filename: Path to status file
412 9bb69bb5 Michael Hanselmann
  @type instances: list of L{Instance}
413 9bb69bb5 Michael Hanselmann

414 9bb69bb5 Michael Hanselmann
  """
415 9bb69bb5 Michael Hanselmann
  _WriteInstanceStatus(filename, [(inst.name, inst.status)
416 9bb69bb5 Michael Hanselmann
                                  for inst in instances])
417 9bb69bb5 Michael Hanselmann
418 9bb69bb5 Michael Hanselmann
419 9bb69bb5 Michael Hanselmann
def _ReadInstanceStatus(filename):
420 9bb69bb5 Michael Hanselmann
  """Reads an instance status file.
421 9bb69bb5 Michael Hanselmann

422 9bb69bb5 Michael Hanselmann
  @type filename: string
423 9bb69bb5 Michael Hanselmann
  @param filename: Path to status file
424 9bb69bb5 Michael Hanselmann
  @rtype: tuple; (None or number, list of lists containing instance name and
425 9bb69bb5 Michael Hanselmann
    status)
426 9bb69bb5 Michael Hanselmann
  @return: File's mtime and instance status contained in the file; mtime is
427 9bb69bb5 Michael Hanselmann
    C{None} if file can't be read
428 9bb69bb5 Michael Hanselmann

429 9bb69bb5 Michael Hanselmann
  """
430 9bb69bb5 Michael Hanselmann
  logging.debug("Reading per-group instance status from '%s'", filename)
431 9bb69bb5 Michael Hanselmann
432 2635bb04 Michael Hanselmann
  statcb = utils.FileStatHelper()
433 9bb69bb5 Michael Hanselmann
  try:
434 9bb69bb5 Michael Hanselmann
    content = utils.ReadFile(filename, preread=statcb)
435 9bb69bb5 Michael Hanselmann
  except EnvironmentError, err:
436 9bb69bb5 Michael Hanselmann
    if err.errno == errno.ENOENT:
437 9bb69bb5 Michael Hanselmann
      logging.error("Can't read '%s', does not exist (yet)", filename)
438 9bb69bb5 Michael Hanselmann
    else:
439 9bb69bb5 Michael Hanselmann
      logging.exception("Unable to read '%s', ignoring", filename)
440 9bb69bb5 Michael Hanselmann
    return (None, None)
441 9bb69bb5 Michael Hanselmann
  else:
442 6f9e71bb Michael Hanselmann
    return (statcb.st.st_mtime, [line.split(None, 1)
443 9bb69bb5 Michael Hanselmann
                                 for line in content.splitlines()])
444 9bb69bb5 Michael Hanselmann
445 9bb69bb5 Michael Hanselmann
446 9bb69bb5 Michael Hanselmann
def _MergeInstanceStatus(filename, pergroup_filename, groups):
447 9bb69bb5 Michael Hanselmann
  """Merges all per-group instance status files into a global one.
448 9bb69bb5 Michael Hanselmann

449 9bb69bb5 Michael Hanselmann
  @type filename: string
450 9bb69bb5 Michael Hanselmann
  @param filename: Path to global instance status file
451 9bb69bb5 Michael Hanselmann
  @type pergroup_filename: string
452 9bb69bb5 Michael Hanselmann
  @param pergroup_filename: Path to per-group status files, must contain "%s"
453 9bb69bb5 Michael Hanselmann
    to be replaced with group UUID
454 9bb69bb5 Michael Hanselmann
  @type groups: sequence
455 9bb69bb5 Michael Hanselmann
  @param groups: UUIDs of known groups
456 9bb69bb5 Michael Hanselmann

457 9bb69bb5 Michael Hanselmann
  """
458 9bb69bb5 Michael Hanselmann
  # Lock global status file in exclusive mode
459 9bb69bb5 Michael Hanselmann
  lock = utils.FileLock.Open(filename)
460 9bb69bb5 Michael Hanselmann
  try:
461 9bb69bb5 Michael Hanselmann
    lock.Exclusive(blocking=True, timeout=INSTANCE_STATUS_LOCK_TIMEOUT)
462 9bb69bb5 Michael Hanselmann
  except errors.LockError, err:
463 9bb69bb5 Michael Hanselmann
    # All per-group processes will lock and update the file. None of them
464 9bb69bb5 Michael Hanselmann
    # should take longer than 10 seconds (the value of
465 9bb69bb5 Michael Hanselmann
    # INSTANCE_STATUS_LOCK_TIMEOUT).
466 9bb69bb5 Michael Hanselmann
    logging.error("Can't acquire lock on instance status file '%s', not"
467 9bb69bb5 Michael Hanselmann
                  " updating: %s", filename, err)
468 9bb69bb5 Michael Hanselmann
    return
469 9bb69bb5 Michael Hanselmann
470 9bb69bb5 Michael Hanselmann
  logging.debug("Acquired exclusive lock on '%s'", filename)
471 9bb69bb5 Michael Hanselmann
472 9bb69bb5 Michael Hanselmann
  data = {}
473 9bb69bb5 Michael Hanselmann
474 9bb69bb5 Michael Hanselmann
  # Load instance status from all groups
475 9bb69bb5 Michael Hanselmann
  for group_uuid in groups:
476 9bb69bb5 Michael Hanselmann
    (mtime, instdata) = _ReadInstanceStatus(pergroup_filename % group_uuid)
477 9bb69bb5 Michael Hanselmann
478 9bb69bb5 Michael Hanselmann
    if mtime is not None:
479 9bb69bb5 Michael Hanselmann
      for (instance_name, status) in instdata:
480 9bb69bb5 Michael Hanselmann
        data.setdefault(instance_name, []).append((mtime, status))
481 9bb69bb5 Michael Hanselmann
482 9bb69bb5 Michael Hanselmann
  # Select last update based on file mtime
483 9bb69bb5 Michael Hanselmann
  inststatus = [(instance_name, sorted(status, reverse=True)[0][1])
484 9bb69bb5 Michael Hanselmann
                for (instance_name, status) in data.items()]
485 9bb69bb5 Michael Hanselmann
486 9bb69bb5 Michael Hanselmann
  # Write the global status file. Don't touch file after it's been
487 9bb69bb5 Michael Hanselmann
  # updated--there is no lock anymore.
488 9bb69bb5 Michael Hanselmann
  _WriteInstanceStatus(filename, inststatus)
489 8f07dc0d Michael Hanselmann
490 8f07dc0d Michael Hanselmann
491 16e0b9c9 Michael Hanselmann
def GetLuxiClient(try_restart):
492 16e0b9c9 Michael Hanselmann
  """Tries to connect to the master daemon.
493 16e0b9c9 Michael Hanselmann

494 16e0b9c9 Michael Hanselmann
  @type try_restart: bool
495 16e0b9c9 Michael Hanselmann
  @param try_restart: Whether to attempt to restart the master daemon
496 16e0b9c9 Michael Hanselmann

497 16e0b9c9 Michael Hanselmann
  """
498 16e0b9c9 Michael Hanselmann
  try:
499 16e0b9c9 Michael Hanselmann
    return cli.GetClient()
500 16e0b9c9 Michael Hanselmann
  except errors.OpPrereqError, err:
501 16e0b9c9 Michael Hanselmann
    # this is, from cli.GetClient, a not-master case
502 16e0b9c9 Michael Hanselmann
    raise NotMasterError("Not on master node (%s)" % err)
503 16e0b9c9 Michael Hanselmann
504 16e0b9c9 Michael Hanselmann
  except luxi.NoMasterError, err:
505 16e0b9c9 Michael Hanselmann
    if not try_restart:
506 16e0b9c9 Michael Hanselmann
      raise
507 16e0b9c9 Michael Hanselmann
508 16e0b9c9 Michael Hanselmann
    logging.warning("Master daemon seems to be down (%s), trying to restart",
509 16e0b9c9 Michael Hanselmann
                    err)
510 16e0b9c9 Michael Hanselmann
511 16e0b9c9 Michael Hanselmann
    if not utils.EnsureDaemon(constants.MASTERD):
512 16e0b9c9 Michael Hanselmann
      raise errors.GenericError("Can't start the master daemon")
513 16e0b9c9 Michael Hanselmann
514 16e0b9c9 Michael Hanselmann
    # Retry the connection
515 16e0b9c9 Michael Hanselmann
    return cli.GetClient()
516 16e0b9c9 Michael Hanselmann
517 16e0b9c9 Michael Hanselmann
518 16e0b9c9 Michael Hanselmann
def _StartGroupChildren(cl, wait):
519 16e0b9c9 Michael Hanselmann
  """Starts a new instance of the watcher for every node group.
520 16e0b9c9 Michael Hanselmann

521 16e0b9c9 Michael Hanselmann
  """
522 16e0b9c9 Michael Hanselmann
  assert not compat.any(arg.startswith(cli.NODEGROUP_OPT_NAME)
523 16e0b9c9 Michael Hanselmann
                        for arg in sys.argv)
524 16e0b9c9 Michael Hanselmann
525 16e0b9c9 Michael Hanselmann
  result = cl.QueryGroups([], ["name", "uuid"], False)
526 16e0b9c9 Michael Hanselmann
527 16e0b9c9 Michael Hanselmann
  children = []
528 16e0b9c9 Michael Hanselmann
529 16e0b9c9 Michael Hanselmann
  for (idx, (name, uuid)) in enumerate(result):
530 16e0b9c9 Michael Hanselmann
    args = sys.argv + [cli.NODEGROUP_OPT_NAME, uuid]
531 16e0b9c9 Michael Hanselmann
532 16e0b9c9 Michael Hanselmann
    if idx > 0:
533 16e0b9c9 Michael Hanselmann
      # Let's not kill the system
534 16e0b9c9 Michael Hanselmann
      time.sleep(CHILD_PROCESS_DELAY)
535 16e0b9c9 Michael Hanselmann
536 16e0b9c9 Michael Hanselmann
    logging.debug("Spawning child for group '%s' (%s), arguments %s",
537 16e0b9c9 Michael Hanselmann
                  name, uuid, args)
538 16e0b9c9 Michael Hanselmann
539 16e0b9c9 Michael Hanselmann
    try:
540 16e0b9c9 Michael Hanselmann
      # TODO: Should utils.StartDaemon be used instead?
541 16e0b9c9 Michael Hanselmann
      pid = os.spawnv(os.P_NOWAIT, args[0], args)
542 b459a848 Andrea Spadaccini
    except Exception: # pylint: disable=W0703
543 16e0b9c9 Michael Hanselmann
      logging.exception("Failed to start child for group '%s' (%s)",
544 16e0b9c9 Michael Hanselmann
                        name, uuid)
545 16e0b9c9 Michael Hanselmann
    else:
546 16e0b9c9 Michael Hanselmann
      logging.debug("Started with PID %s", pid)
547 16e0b9c9 Michael Hanselmann
      children.append(pid)
548 16e0b9c9 Michael Hanselmann
549 16e0b9c9 Michael Hanselmann
  if wait:
550 16e0b9c9 Michael Hanselmann
    for pid in children:
551 16e0b9c9 Michael Hanselmann
      logging.debug("Waiting for child PID %s", pid)
552 16e0b9c9 Michael Hanselmann
      try:
553 16e0b9c9 Michael Hanselmann
        result = utils.RetryOnSignal(os.waitpid, pid, 0)
554 16e0b9c9 Michael Hanselmann
      except EnvironmentError, err:
555 16e0b9c9 Michael Hanselmann
        result = str(err)
556 16e0b9c9 Michael Hanselmann
557 16e0b9c9 Michael Hanselmann
      logging.debug("Child PID %s exited with status %s", pid, result)
558 16e0b9c9 Michael Hanselmann
559 16e0b9c9 Michael Hanselmann
560 16e0b9c9 Michael Hanselmann
def _ArchiveJobs(cl, age):
561 16e0b9c9 Michael Hanselmann
  """Archives old jobs.
562 16e0b9c9 Michael Hanselmann

563 16e0b9c9 Michael Hanselmann
  """
564 16e0b9c9 Michael Hanselmann
  (arch_count, left_count) = cl.AutoArchiveJobs(age)
565 16e0b9c9 Michael Hanselmann
  logging.debug("Archived %s jobs, left %s", arch_count, left_count)
566 16e0b9c9 Michael Hanselmann
567 16e0b9c9 Michael Hanselmann
568 16e0b9c9 Michael Hanselmann
def _CheckMaster(cl):
569 16e0b9c9 Michael Hanselmann
  """Ensures current host is master node.
570 16e0b9c9 Michael Hanselmann

571 16e0b9c9 Michael Hanselmann
  """
572 16e0b9c9 Michael Hanselmann
  (master, ) = cl.QueryConfigValues(["master_node"])
573 16e0b9c9 Michael Hanselmann
  if master != netutils.Hostname.GetSysName():
574 16e0b9c9 Michael Hanselmann
    raise NotMasterError("This is not the master node")
575 16e0b9c9 Michael Hanselmann
576 16e0b9c9 Michael Hanselmann
577 fc3f75dd Iustin Pop
@UsesRapiClient
578 16e0b9c9 Michael Hanselmann
def _GlobalWatcher(opts):
579 16e0b9c9 Michael Hanselmann
  """Main function for global watcher.
580 16e0b9c9 Michael Hanselmann

581 16e0b9c9 Michael Hanselmann
  At the end child processes are spawned for every node group.
582 16e0b9c9 Michael Hanselmann

583 16e0b9c9 Michael Hanselmann
  """
584 16e0b9c9 Michael Hanselmann
  StartNodeDaemons()
585 16e0b9c9 Michael Hanselmann
  RunWatcherHooks()
586 16e0b9c9 Michael Hanselmann
587 16e0b9c9 Michael Hanselmann
  # Run node maintenance in all cases, even if master, so that old masters can
588 16e0b9c9 Michael Hanselmann
  # be properly cleaned up
589 b459a848 Andrea Spadaccini
  if nodemaint.NodeMaintenance.ShouldRun(): # pylint: disable=E0602
590 b459a848 Andrea Spadaccini
    nodemaint.NodeMaintenance().Exec() # pylint: disable=E0602
591 16e0b9c9 Michael Hanselmann
592 16e0b9c9 Michael Hanselmann
  try:
593 16e0b9c9 Michael Hanselmann
    client = GetLuxiClient(True)
594 16e0b9c9 Michael Hanselmann
  except NotMasterError:
595 16e0b9c9 Michael Hanselmann
    # Don't proceed on non-master nodes
596 16e0b9c9 Michael Hanselmann
    return constants.EXIT_SUCCESS
597 16e0b9c9 Michael Hanselmann
598 16e0b9c9 Michael Hanselmann
  # we are on master now
599 16e0b9c9 Michael Hanselmann
  utils.EnsureDaemon(constants.RAPI)
600 16e0b9c9 Michael Hanselmann
601 16e0b9c9 Michael Hanselmann
  # If RAPI isn't responding to queries, try one restart
602 16e0b9c9 Michael Hanselmann
  logging.debug("Attempting to talk to remote API on %s",
603 16e0b9c9 Michael Hanselmann
                constants.IP4_ADDRESS_LOCALHOST)
604 16e0b9c9 Michael Hanselmann
  if not IsRapiResponding(constants.IP4_ADDRESS_LOCALHOST):
605 16e0b9c9 Michael Hanselmann
    logging.warning("Couldn't get answer from remote API, restaring daemon")
606 16e0b9c9 Michael Hanselmann
    utils.StopDaemon(constants.RAPI)
607 16e0b9c9 Michael Hanselmann
    utils.EnsureDaemon(constants.RAPI)
608 16e0b9c9 Michael Hanselmann
    logging.debug("Second attempt to talk to remote API")
609 16e0b9c9 Michael Hanselmann
    if not IsRapiResponding(constants.IP4_ADDRESS_LOCALHOST):
610 16e0b9c9 Michael Hanselmann
      logging.fatal("RAPI is not responding")
611 16e0b9c9 Michael Hanselmann
  logging.debug("Successfully talked to remote API")
612 16e0b9c9 Michael Hanselmann
613 16e0b9c9 Michael Hanselmann
  _CheckMaster(client)
614 16e0b9c9 Michael Hanselmann
  _ArchiveJobs(client, opts.job_age)
615 16e0b9c9 Michael Hanselmann
616 16e0b9c9 Michael Hanselmann
  # Spawn child processes for all node groups
617 16e0b9c9 Michael Hanselmann
  _StartGroupChildren(client, opts.wait_children)
618 16e0b9c9 Michael Hanselmann
619 16e0b9c9 Michael Hanselmann
  return constants.EXIT_SUCCESS
620 16e0b9c9 Michael Hanselmann
621 16e0b9c9 Michael Hanselmann
622 16e0b9c9 Michael Hanselmann
def _GetGroupData(cl, uuid):
623 16e0b9c9 Michael Hanselmann
  """Retrieves instances and nodes per node group.
624 16e0b9c9 Michael Hanselmann

625 16e0b9c9 Michael Hanselmann
  """
626 16e0b9c9 Michael Hanselmann
  job = [
627 16e0b9c9 Michael Hanselmann
    # Get all primary instances in group
628 16e0b9c9 Michael Hanselmann
    opcodes.OpQuery(what=constants.QR_INSTANCE,
629 d962dbf9 Thomas Thrainer
                    fields=["name", "status", "disks_active", "snodes",
630 16e0b9c9 Michael Hanselmann
                            "pnode.group.uuid", "snodes.group.uuid"],
631 2e5c33db Iustin Pop
                    qfilter=[qlang.OP_EQUAL, "pnode.group.uuid", uuid],
632 5bfb1134 Michael Hanselmann
                    use_locking=True),
633 16e0b9c9 Michael Hanselmann
634 16e0b9c9 Michael Hanselmann
    # Get all nodes in group
635 16e0b9c9 Michael Hanselmann
    opcodes.OpQuery(what=constants.QR_NODE,
636 16e0b9c9 Michael Hanselmann
                    fields=["name", "bootid", "offline"],
637 2e5c33db Iustin Pop
                    qfilter=[qlang.OP_EQUAL, "group.uuid", uuid],
638 5bfb1134 Michael Hanselmann
                    use_locking=True),
639 16e0b9c9 Michael Hanselmann
    ]
640 16e0b9c9 Michael Hanselmann
641 16e0b9c9 Michael Hanselmann
  job_id = cl.SubmitJob(job)
642 16e0b9c9 Michael Hanselmann
  results = map(objects.QueryResponse.FromDict,
643 16e0b9c9 Michael Hanselmann
                cli.PollJob(job_id, cl=cl, feedback_fn=logging.debug))
644 16e0b9c9 Michael Hanselmann
  cl.ArchiveJob(job_id)
645 16e0b9c9 Michael Hanselmann
646 16e0b9c9 Michael Hanselmann
  results_data = map(operator.attrgetter("data"), results)
647 16e0b9c9 Michael Hanselmann
648 16e0b9c9 Michael Hanselmann
  # Ensure results are tuples with two values
649 16e0b9c9 Michael Hanselmann
  assert compat.all(map(ht.TListOf(ht.TListOf(ht.TIsLength(2))), results_data))
650 16e0b9c9 Michael Hanselmann
651 16e0b9c9 Michael Hanselmann
  # Extract values ignoring result status
652 16e0b9c9 Michael Hanselmann
  (raw_instances, raw_nodes) = [[map(compat.snd, values)
653 16e0b9c9 Michael Hanselmann
                                 for values in res]
654 16e0b9c9 Michael Hanselmann
                                for res in results_data]
655 16e0b9c9 Michael Hanselmann
656 16e0b9c9 Michael Hanselmann
  secondaries = {}
657 16e0b9c9 Michael Hanselmann
  instances = []
658 16e0b9c9 Michael Hanselmann
659 16e0b9c9 Michael Hanselmann
  # Load all instances
660 d962dbf9 Thomas Thrainer
  for (name, status, disks_active, snodes, pnode_group_uuid,
661 16e0b9c9 Michael Hanselmann
       snodes_group_uuid) in raw_instances:
662 16e0b9c9 Michael Hanselmann
    if snodes and set([pnode_group_uuid]) != set(snodes_group_uuid):
663 16e0b9c9 Michael Hanselmann
      logging.error("Ignoring split instance '%s', primary group %s, secondary"
664 16e0b9c9 Michael Hanselmann
                    " groups %s", name, pnode_group_uuid,
665 16e0b9c9 Michael Hanselmann
                    utils.CommaJoin(snodes_group_uuid))
666 16e0b9c9 Michael Hanselmann
    else:
667 d962dbf9 Thomas Thrainer
      instances.append(Instance(name, status, disks_active, snodes))
668 16e0b9c9 Michael Hanselmann
669 16e0b9c9 Michael Hanselmann
      for node in snodes:
670 16e0b9c9 Michael Hanselmann
        secondaries.setdefault(node, set()).add(name)
671 16e0b9c9 Michael Hanselmann
672 16e0b9c9 Michael Hanselmann
  # Load all nodes
673 16e0b9c9 Michael Hanselmann
  nodes = [Node(name, bootid, offline, secondaries.get(name, set()))
674 16e0b9c9 Michael Hanselmann
           for (name, bootid, offline) in raw_nodes]
675 16e0b9c9 Michael Hanselmann
676 16e0b9c9 Michael Hanselmann
  return (dict((node.name, node) for node in nodes),
677 16e0b9c9 Michael Hanselmann
          dict((inst.name, inst) for inst in instances))
678 16e0b9c9 Michael Hanselmann
679 16e0b9c9 Michael Hanselmann
680 9bb69bb5 Michael Hanselmann
def _LoadKnownGroups():
681 9bb69bb5 Michael Hanselmann
  """Returns a list of all node groups known by L{ssconf}.
682 16e0b9c9 Michael Hanselmann

683 16e0b9c9 Michael Hanselmann
  """
684 16e0b9c9 Michael Hanselmann
  groups = ssconf.SimpleStore().GetNodegroupList()
685 16e0b9c9 Michael Hanselmann
686 9bb69bb5 Michael Hanselmann
  result = list(line.split(None, 1)[0] for line in groups
687 9bb69bb5 Michael Hanselmann
                if line.strip())
688 9bb69bb5 Michael Hanselmann
689 9bb69bb5 Michael Hanselmann
  if not compat.all(map(utils.UUID_RE.match, result)):
690 9bb69bb5 Michael Hanselmann
    raise errors.GenericError("Ssconf contains invalid group UUID")
691 9bb69bb5 Michael Hanselmann
692 9bb69bb5 Michael Hanselmann
  return result
693 16e0b9c9 Michael Hanselmann
694 16e0b9c9 Michael Hanselmann
695 16e0b9c9 Michael Hanselmann
def _GroupWatcher(opts):
696 16e0b9c9 Michael Hanselmann
  """Main function for per-group watcher process.
697 16e0b9c9 Michael Hanselmann

698 16e0b9c9 Michael Hanselmann
  """
699 16e0b9c9 Michael Hanselmann
  group_uuid = opts.nodegroup.lower()
700 16e0b9c9 Michael Hanselmann
701 16e0b9c9 Michael Hanselmann
  if not utils.UUID_RE.match(group_uuid):
702 16e0b9c9 Michael Hanselmann
    raise errors.GenericError("Node group parameter (%s) must be given a UUID,"
703 16e0b9c9 Michael Hanselmann
                              " got '%s'" %
704 16e0b9c9 Michael Hanselmann
                              (cli.NODEGROUP_OPT_NAME, group_uuid))
705 16e0b9c9 Michael Hanselmann
706 16e0b9c9 Michael Hanselmann
  logging.info("Watcher for node group '%s'", group_uuid)
707 16e0b9c9 Michael Hanselmann
708 9bb69bb5 Michael Hanselmann
  known_groups = _LoadKnownGroups()
709 9bb69bb5 Michael Hanselmann
710 16e0b9c9 Michael Hanselmann
  # Check if node group is known
711 9bb69bb5 Michael Hanselmann
  if group_uuid not in known_groups:
712 16e0b9c9 Michael Hanselmann
    raise errors.GenericError("Node group '%s' is not known by ssconf" %
713 16e0b9c9 Michael Hanselmann
                              group_uuid)
714 16e0b9c9 Michael Hanselmann
715 40b068e5 Iustin Pop
  # Group UUID has been verified and should not contain any dangerous
716 40b068e5 Iustin Pop
  # characters
717 57fe4a5b Michael Hanselmann
  state_path = pathutils.WATCHER_GROUP_STATE_FILE % group_uuid
718 57fe4a5b Michael Hanselmann
  inst_status_path = pathutils.WATCHER_GROUP_INSTANCE_STATUS_FILE % group_uuid
719 16e0b9c9 Michael Hanselmann
720 16e0b9c9 Michael Hanselmann
  logging.debug("Using state file %s", state_path)
721 16e0b9c9 Michael Hanselmann
722 16e0b9c9 Michael Hanselmann
  # Global watcher
723 b459a848 Andrea Spadaccini
  statefile = state.OpenStateFile(state_path) # pylint: disable=E0602
724 16e0b9c9 Michael Hanselmann
  if not statefile:
725 16e0b9c9 Michael Hanselmann
    return constants.EXIT_FAILURE
726 16e0b9c9 Michael Hanselmann
727 b459a848 Andrea Spadaccini
  notepad = state.WatcherState(statefile) # pylint: disable=E0602
728 16e0b9c9 Michael Hanselmann
  try:
729 16e0b9c9 Michael Hanselmann
    # Connect to master daemon
730 16e0b9c9 Michael Hanselmann
    client = GetLuxiClient(False)
731 16e0b9c9 Michael Hanselmann
732 16e0b9c9 Michael Hanselmann
    _CheckMaster(client)
733 16e0b9c9 Michael Hanselmann
734 16e0b9c9 Michael Hanselmann
    (nodes, instances) = _GetGroupData(client, group_uuid)
735 16e0b9c9 Michael Hanselmann
736 9bb69bb5 Michael Hanselmann
    # Update per-group instance status file
737 9bb69bb5 Michael Hanselmann
    _UpdateInstanceStatus(inst_status_path, instances.values())
738 9bb69bb5 Michael Hanselmann
739 57fe4a5b Michael Hanselmann
    _MergeInstanceStatus(pathutils.INSTANCE_STATUS_FILE,
740 57fe4a5b Michael Hanselmann
                         pathutils.WATCHER_GROUP_INSTANCE_STATUS_FILE,
741 9bb69bb5 Michael Hanselmann
                         known_groups)
742 9bb69bb5 Michael Hanselmann
743 16e0b9c9 Michael Hanselmann
    started = _CheckInstances(client, notepad, instances)
744 16e0b9c9 Michael Hanselmann
    _CheckDisks(client, notepad, nodes, instances, started)
745 16e0b9c9 Michael Hanselmann
    _VerifyDisks(client, group_uuid, nodes, instances)
746 16e0b9c9 Michael Hanselmann
  except Exception, err:
747 16e0b9c9 Michael Hanselmann
    logging.info("Not updating status file due to failure: %s", err)
748 16e0b9c9 Michael Hanselmann
    raise
749 16e0b9c9 Michael Hanselmann
  else:
750 16e0b9c9 Michael Hanselmann
    # Save changes for next run
751 16e0b9c9 Michael Hanselmann
    notepad.Save(state_path)
752 16e0b9c9 Michael Hanselmann
753 16e0b9c9 Michael Hanselmann
  return constants.EXIT_SUCCESS
754 16e0b9c9 Michael Hanselmann
755 16e0b9c9 Michael Hanselmann
756 9f4bb951 Michael Hanselmann
def Main():
757 a8083063 Iustin Pop
  """Main function.
758 a8083063 Iustin Pop

759 a8083063 Iustin Pop
  """
760 f0a80b01 Michael Hanselmann
  (options, _) = ParseOptions()
761 a8083063 Iustin Pop
762 57fe4a5b Michael Hanselmann
  utils.SetupLogging(pathutils.LOG_WATCHER, sys.argv[0],
763 cfcc79c6 Michael Hanselmann
                     debug=options.debug, stderr_logging=options.debug)
764 a8083063 Iustin Pop
765 46c8a6ab Iustin Pop
  if ShouldPause() and not options.ignore_pause:
766 3753b2cb Michael Hanselmann
    logging.debug("Pause has been set, exiting")
767 9f4bb951 Michael Hanselmann
    return constants.EXIT_SUCCESS
768 3753b2cb Michael Hanselmann
769 16e0b9c9 Michael Hanselmann
  # Try to acquire global watcher lock in shared mode
770 57fe4a5b Michael Hanselmann
  lock = utils.FileLock.Open(pathutils.WATCHER_LOCK_FILE)
771 a8083063 Iustin Pop
  try:
772 16e0b9c9 Michael Hanselmann
    lock.Shared(blocking=False)
773 16e0b9c9 Michael Hanselmann
  except (EnvironmentError, errors.LockError), err:
774 16e0b9c9 Michael Hanselmann
    logging.error("Can't acquire lock on %s: %s",
775 57fe4a5b Michael Hanselmann
                  pathutils.WATCHER_LOCK_FILE, err)
776 16e0b9c9 Michael Hanselmann
    return constants.EXIT_SUCCESS
777 db147305 Tom Limoncelli
778 16e0b9c9 Michael Hanselmann
  if options.nodegroup is None:
779 16e0b9c9 Michael Hanselmann
    fn = _GlobalWatcher
780 16e0b9c9 Michael Hanselmann
  else:
781 16e0b9c9 Michael Hanselmann
    # Per-nodegroup watcher
782 16e0b9c9 Michael Hanselmann
    fn = _GroupWatcher
783 16e0b9c9 Michael Hanselmann
784 16e0b9c9 Michael Hanselmann
  try:
785 16e0b9c9 Michael Hanselmann
    return fn(options)
786 16e0b9c9 Michael Hanselmann
  except (SystemExit, KeyboardInterrupt):
787 1b052f42 Michael Hanselmann
    raise
788 38242904 Iustin Pop
  except NotMasterError:
789 438b45d4 Michael Hanselmann
    logging.debug("Not master, exiting")
790 9f4bb951 Michael Hanselmann
    return constants.EXIT_NOTMASTER
791 89e1fc26 Iustin Pop
  except errors.ResolverError, err:
792 013ce4ae Michael Hanselmann
    logging.error("Cannot resolve hostname '%s', exiting", err.args[0])
793 9f4bb951 Michael Hanselmann
    return constants.EXIT_NODESETUP_ERROR
794 24edc6d4 Iustin Pop
  except errors.JobQueueFull:
795 24edc6d4 Iustin Pop
    logging.error("Job queue is full, can't query cluster state")
796 24edc6d4 Iustin Pop
  except errors.JobQueueDrainError:
797 24edc6d4 Iustin Pop
    logging.error("Job queue is drained, can't maintain cluster state")
798 438b45d4 Michael Hanselmann
  except Exception, err:
799 001b3825 Michael Hanselmann
    logging.exception(str(err))
800 9f4bb951 Michael Hanselmann
    return constants.EXIT_FAILURE
801 5a3103e9 Michael Hanselmann
802 9f4bb951 Michael Hanselmann
  return constants.EXIT_SUCCESS