4 # Copyright (C) 2006, 2007, 2011 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 """Module implementing the logic behind the cluster operations
24 This module implements the logic for doing operations in the cluster. There
25 are two kinds of classes defined:
26 - logical units, which know how to deal with their specific opcode only
27 - the processor, which dispatches the opcodes to their logical units
35 from ganeti import opcodes
36 from ganeti import constants
37 from ganeti import errors
38 from ganeti import rpc
39 from ganeti import cmdlib
40 from ganeti import locking
41 from ganeti import utils
48 class LockAcquireTimeout(Exception):
49 """Exception to report timeouts on acquiring locks.
54 def _CalculateLockAttemptTimeouts():
55 """Calculate timeouts for lock attempts.
60 # Wait for a total of at least 150s before doing a blocking acquire
61 while sum(result) < 150.0:
62 timeout = (result[-1] * 1.05) ** 1.25
64 # Cap timeout at 10 seconds. This gives other jobs a chance to run
65 # even if we're still trying to get our locks, before finally moving
66 # to a blocking acquire.
71 # Lower boundary for safety
74 result.append(timeout)
79 class LockAttemptTimeoutStrategy(object):
80 """Class with lock acquire timeout strategy.
89 _TIMEOUT_PER_ATTEMPT = _CalculateLockAttemptTimeouts()
91 def __init__(self, _time_fn=time.time, _random_fn=random.random):
92 """Initializes this class.
94 @param _time_fn: Time function for unittests
95 @param _random_fn: Random number generator for unittests
100 self._timeouts = iter(self._TIMEOUT_PER_ATTEMPT)
101 self._time_fn = _time_fn
102 self._random_fn = _random_fn
104 def NextAttempt(self):
105 """Returns the timeout for the next attempt.
109 timeout = self._timeouts.next()
110 except StopIteration:
111 # No more timeouts, do blocking acquire
114 if timeout is not None:
115 # Add a small variation (-/+ 5%) to timeout. This helps in situations
116 # where two or more jobs are fighting for the same lock(s).
117 variation_range = timeout * 0.1
118 timeout += ((self._random_fn() * variation_range) -
119 (variation_range * 0.5))
124 class OpExecCbBase: # pylint: disable-msg=W0232
125 """Base class for OpCode execution callbacks.
128 def NotifyStart(self):
129 """Called when we are about to execute the LU.
131 This function is called when we're about to start the lu's Exec() method,
132 that is, after we have acquired all locks.
136 def Feedback(self, *args):
137 """Sends feedback from the LU code to the end-user.
141 def CheckCancel(self):
142 """Check whether job has been cancelled.
147 def _LUNameForOpName(opname):
148 """Computes the LU name for a given OpCode name.
151 assert opname.startswith(_OP_PREFIX), \
152 "Invalid OpCode name, doesn't start with %s: %s" % (_OP_PREFIX, opname)
154 return _LU_PREFIX + opname[len(_OP_PREFIX):]
157 def _ComputeDispatchTable():
158 """Computes the opcode-to-lu dispatch table.
161 return dict((op, getattr(cmdlib, _LUNameForOpName(op.__name__)))
162 for op in opcodes.OP_MAPPING.values()
166 class Processor(object):
167 """Object which runs OpCodes"""
168 DISPATCH_TABLE = _ComputeDispatchTable()
170 def __init__(self, context, ec_id):
171 """Constructor for Processor
173 @type context: GanetiContext
174 @param context: global Ganeti context
176 @param ec_id: execution context identifier
179 self.context = context
182 self.rpc = rpc.RpcRunner(context.cfg)
183 self.hmclass = HooksMaster
185 def _AcquireLocks(self, level, names, shared, timeout, priority):
186 """Acquires locks via the Ganeti lock manager.
189 @param level: Lock level
190 @type names: list or string
191 @param names: Lock names
193 @param shared: Whether the locks should be acquired in shared mode
194 @type timeout: None or float
195 @param timeout: Timeout for acquiring the locks
196 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
201 self._cbs.CheckCancel()
203 acquired = self.context.glm.acquire(level, names, shared=shared,
204 timeout=timeout, priority=priority)
207 raise LockAcquireTimeout()
211 def _ExecLU(self, lu):
212 """Logical Unit execution sequence.
215 write_count = self.context.cfg.write_count
217 hm = HooksMaster(self.rpc.call_hooks_runner, lu)
218 h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
219 lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
222 if getattr(lu.op, "dry_run", False):
223 # in this mode, no post-hooks are run, and the config is not
224 # written (as it might have been modified by another LU, and we
225 # shouldn't do writeout on behalf of other threads
226 self.LogInfo("dry-run mode requested, not actually executing"
228 return lu.dry_run_result
231 result = lu.Exec(self.Log)
232 h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
233 result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
236 # FIXME: This needs locks if not lu_class.REQ_BGL
237 if write_count != self.context.cfg.write_count:
242 def _LockAndExecLU(self, lu, level, calc_timeout, priority):
243 """Execute a Logical Unit, with the needed locks.
245 This is a recursive function that starts locking the given level, and
246 proceeds up, till there are no more locks to acquire. Then it executes the
247 given LU and its opcodes.
250 adding_locks = level in lu.add_locks
251 acquiring_locks = level in lu.needed_locks
252 if level not in locking.LEVELS:
254 self._cbs.NotifyStart()
256 result = self._ExecLU(lu)
258 elif adding_locks and acquiring_locks:
259 # We could both acquire and add locks at the same level, but for now we
260 # don't need this, so we'll avoid the complicated code needed.
261 raise NotImplementedError("Can't declare locks to acquire when adding"
264 elif adding_locks or acquiring_locks:
265 lu.DeclareLocks(level)
266 share = lu.share_locks[level]
269 assert adding_locks ^ acquiring_locks, \
270 "Locks must be either added or acquired"
274 needed_locks = lu.needed_locks[level]
276 acquired = self._AcquireLocks(level, needed_locks, share,
277 calc_timeout(), priority)
280 add_locks = lu.add_locks[level]
281 lu.remove_locks[level] = add_locks
284 self.context.glm.add(level, add_locks, acquired=1, shared=share)
285 except errors.LockError:
286 raise errors.OpPrereqError(
287 "Couldn't add locks (%s), probably because of a race condition"
288 " with another job, who added them first" % add_locks,
294 lu.acquired_locks[level] = acquired
296 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
298 if level in lu.remove_locks:
299 self.context.glm.remove(level, lu.remove_locks[level])
301 if self.context.glm.is_owned(level):
302 self.context.glm.release(level)
305 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
309 def ExecOpCode(self, op, cbs, timeout=None, priority=None):
310 """Execute an opcode.
312 @type op: an OpCode instance
313 @param op: the opcode to be executed
314 @type cbs: L{OpExecCbBase}
315 @param cbs: Runtime callbacks
316 @type timeout: float or None
317 @param timeout: Maximum time to acquire all locks, None for no timeout
318 @type priority: number or None
319 @param priority: Priority for acquiring lock(s)
320 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
324 if not isinstance(op, opcodes.OpCode):
325 raise errors.ProgrammerError("Non-opcode instance passed"
328 lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
330 raise errors.OpCodeUnknown("Unknown opcode")
333 calc_timeout = lambda: None
335 calc_timeout = utils.RunningTimeout(timeout, False).Remaining
339 # Acquire the Big Ganeti Lock exclusively if this LU requires it,
340 # and in a shared fashion otherwise (to prevent concurrent run with
342 self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL,
343 not lu_class.REQ_BGL, calc_timeout(),
346 lu = lu_class(self, op, self.context, self.rpc)
348 assert lu.needed_locks is not None, "needed_locks not set by LU"
351 return self._LockAndExecLU(lu, locking.LEVEL_INSTANCE, calc_timeout,
355 self.context.cfg.DropECReservations(self._ec_id)
357 self.context.glm.release(locking.LEVEL_CLUSTER)
361 def Log(self, *args):
362 """Forward call to feedback callback function.
366 self._cbs.Feedback(*args)
368 def LogStep(self, current, total, message):
369 """Log a change in LU execution progress.
372 logging.debug("Step %d/%d %s", current, total, message)
373 self.Log("STEP %d/%d %s" % (current, total, message))
375 def LogWarning(self, message, *args, **kwargs):
376 """Log a warning to the logs and the user.
378 The optional keyword argument is 'hint' and can be used to show a
379 hint to the user (presumably related to the warning). If the
380 message is empty, it will not be printed at all, allowing one to
384 assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
385 "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
387 message = message % tuple(args)
389 logging.warning(message)
390 self.Log(" - WARNING: %s" % message)
392 self.Log(" Hint: %s" % kwargs["hint"])
394 def LogInfo(self, message, *args):
395 """Log an informational message to the logs and the user.
399 message = message % tuple(args)
400 logging.info(message)
401 self.Log(" - INFO: %s" % message)
404 """Returns the current execution context ID.
408 raise errors.ProgrammerError("Tried to use execution context id when"
413 class HooksMaster(object):
416 This class distributes the run commands to the nodes based on the
419 In order to remove the direct dependency on the rpc module, the
420 constructor needs a function which actually does the remote
421 call. This will usually be rpc.call_hooks_runner, but any function
422 which behaves the same works.
425 def __init__(self, callfn, lu):
429 self.env, node_list_pre, node_list_post = self._BuildEnv()
431 constants.HOOKS_PHASE_PRE: node_list_pre,
432 constants.HOOKS_PHASE_POST: node_list_post,
436 """Compute the environment and the target nodes.
438 Based on the opcode and the current node list, this builds the
439 environment for the hooks and the target node list for the run.
443 "PATH": "/sbin:/bin:/usr/sbin:/usr/bin",
444 "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
445 "GANETI_OP_CODE": self.op.OP_ID,
446 "GANETI_OBJECT_TYPE": self.lu.HTYPE,
447 "GANETI_DATA_DIR": constants.DATA_DIR,
450 if self.lu.HPATH is not None:
451 lu_env, lu_nodes_pre, lu_nodes_post = self.lu.BuildHooksEnv()
454 env["GANETI_" + key] = lu_env[key]
456 lu_nodes_pre = lu_nodes_post = []
458 return env, frozenset(lu_nodes_pre), frozenset(lu_nodes_post)
460 def _RunWrapper(self, node_list, hpath, phase):
461 """Simple wrapper over self.callfn.
463 This method fixes the environment before doing the rpc call.
466 env = self.env.copy()
467 env["GANETI_HOOKS_PHASE"] = phase
468 env["GANETI_HOOKS_PATH"] = hpath
469 if self.lu.cfg is not None:
470 env["GANETI_CLUSTER"] = self.lu.cfg.GetClusterName()
471 env["GANETI_MASTER"] = self.lu.cfg.GetMasterNode()
473 env = dict([(str(key), str(val)) for key, val in env.iteritems()])
475 return self.callfn(node_list, hpath, phase, env)
477 def RunPhase(self, phase, nodes=None):
478 """Run all the scripts for a phase.
480 This is the main function of the HookMaster.
482 @param phase: one of L{constants.HOOKS_PHASE_POST} or
483 L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
484 @param nodes: overrides the predefined list of nodes for the given phase
485 @return: the processed results of the hooks multi-node rpc call
486 @raise errors.HooksFailure: on communication failure to the nodes
487 @raise errors.HooksAbort: on failure of one of the hooks
491 nodes = self.node_list[phase]
494 # empty node list, we should not attempt to run this as either
495 # we're in the cluster init phase and the rpc client part can't
496 # even attempt to run, or this LU doesn't do hooks at all
499 results = self._RunWrapper(nodes, self.lu.HPATH, phase)
501 msg = "Communication Failure"
502 if phase == constants.HOOKS_PHASE_PRE:
503 raise errors.HooksFailure(msg)
505 self.lu.LogWarning(msg)
509 for node_name in results:
510 res = results[node_name]
516 self.lu.LogWarning("Communication failure to node %s: %s",
520 for script, hkr, output in res.payload:
521 if hkr == constants.HKR_FAIL:
522 if phase == constants.HOOKS_PHASE_PRE:
523 errs.append((node_name, script, output))
526 output = "(no output)"
527 self.lu.LogWarning("On %s script %s failed, output: %s" %
528 (node_name, script, output))
530 if errs and phase == constants.HOOKS_PHASE_PRE:
531 raise errors.HooksAbort(errs)
535 def RunConfigUpdate(self):
536 """Run the special configuration update hook
538 This is a special hook that runs only on the master after each
539 top-level LI if the configuration has been updated.
542 phase = constants.HOOKS_PHASE_POST
543 hpath = constants.HOOKS_NAME_CFGUPDATE
544 nodes = [self.lu.cfg.GetMasterNode()]
545 self._RunWrapper(nodes, hpath, phase)