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
42 from ganeti import compat
49 class LockAcquireTimeout(Exception):
50 """Exception to report timeouts on acquiring locks.
55 def _CalculateLockAttemptTimeouts():
56 """Calculate timeouts for lock attempts.
59 result = [constants.LOCK_ATTEMPTS_MINWAIT]
60 running_sum = result[0]
62 # Wait for a total of at least LOCK_ATTEMPTS_TIMEOUT before doing a
64 while running_sum < constants.LOCK_ATTEMPTS_TIMEOUT:
65 timeout = (result[-1] * 1.05) ** 1.25
67 # Cap max timeout. This gives other jobs a chance to run even if
68 # we're still trying to get our locks, before finally moving to a
70 timeout = min(timeout, constants.LOCK_ATTEMPTS_MAXWAIT)
71 # And also cap the lower boundary for safety
72 timeout = max(timeout, constants.LOCK_ATTEMPTS_MINWAIT)
74 result.append(timeout)
75 running_sum += timeout
80 class LockAttemptTimeoutStrategy(object):
81 """Class with lock acquire timeout strategy.
90 _TIMEOUT_PER_ATTEMPT = _CalculateLockAttemptTimeouts()
92 def __init__(self, _time_fn=time.time, _random_fn=random.random):
93 """Initializes this class.
95 @param _time_fn: Time function for unittests
96 @param _random_fn: Random number generator for unittests
101 self._timeouts = iter(self._TIMEOUT_PER_ATTEMPT)
102 self._time_fn = _time_fn
103 self._random_fn = _random_fn
105 def NextAttempt(self):
106 """Returns the timeout for the next attempt.
110 timeout = self._timeouts.next()
111 except StopIteration:
112 # No more timeouts, do blocking acquire
115 if timeout is not None:
116 # Add a small variation (-/+ 5%) to timeout. This helps in situations
117 # where two or more jobs are fighting for the same lock(s).
118 variation_range = timeout * 0.1
119 timeout += ((self._random_fn() * variation_range) -
120 (variation_range * 0.5))
125 class OpExecCbBase: # pylint: disable=W0232
126 """Base class for OpCode execution callbacks.
129 def NotifyStart(self):
130 """Called when we are about to execute the LU.
132 This function is called when we're about to start the lu's Exec() method,
133 that is, after we have acquired all locks.
137 def Feedback(self, *args):
138 """Sends feedback from the LU code to the end-user.
142 def CheckCancel(self):
143 """Check whether job has been cancelled.
147 def SubmitManyJobs(self, jobs):
148 """Submits jobs for processing.
150 See L{jqueue.JobQueue.SubmitManyJobs}.
153 raise NotImplementedError
156 def _LUNameForOpName(opname):
157 """Computes the LU name for a given OpCode name.
160 assert opname.startswith(_OP_PREFIX), \
161 "Invalid OpCode name, doesn't start with %s: %s" % (_OP_PREFIX, opname)
163 return _LU_PREFIX + opname[len(_OP_PREFIX):]
166 def _ComputeDispatchTable():
167 """Computes the opcode-to-lu dispatch table.
170 return dict((op, getattr(cmdlib, _LUNameForOpName(op.__name__)))
171 for op in opcodes.OP_MAPPING.values()
175 def _RpcResultsToHooksResults(rpc_results):
176 """Function to convert RPC results to the format expected by HooksMaster.
178 @type rpc_results: dict(node: L{rpc.RpcResult})
179 @param rpc_results: RPC results
180 @rtype: dict(node: (fail_msg, offline, hooks_results))
181 @return: RPC results unpacked according to the format expected by
185 return dict((node, (rpc_res.fail_msg, rpc_res.offline, rpc_res.payload))
186 for (node, rpc_res) in rpc_results.items())
189 class Processor(object):
190 """Object which runs OpCodes"""
191 DISPATCH_TABLE = _ComputeDispatchTable()
193 def __init__(self, context, ec_id):
194 """Constructor for Processor
196 @type context: GanetiContext
197 @param context: global Ganeti context
199 @param ec_id: execution context identifier
202 self.context = context
205 self.rpc = rpc.RpcRunner(context.cfg)
206 self.hmclass = HooksMaster
208 def _AcquireLocks(self, level, names, shared, timeout, priority):
209 """Acquires locks via the Ganeti lock manager.
212 @param level: Lock level
213 @type names: list or string
214 @param names: Lock names
216 @param shared: Whether the locks should be acquired in shared mode
217 @type timeout: None or float
218 @param timeout: Timeout for acquiring the locks
219 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
224 self._cbs.CheckCancel()
226 acquired = self.context.glm.acquire(level, names, shared=shared,
227 timeout=timeout, priority=priority)
230 raise LockAcquireTimeout()
234 def _ProcessResult(self, result):
235 """Examines opcode result.
237 If necessary, additional processing on the result is done.
240 if isinstance(result, cmdlib.ResultWithJobs):
242 job_submission = self._cbs.SubmitManyJobs(result.jobs)
245 result = result.other
247 assert constants.JOB_IDS_KEY not in result, \
248 "Key '%s' found in additional return values" % constants.JOB_IDS_KEY
250 result[constants.JOB_IDS_KEY] = job_submission
254 def _ExecLU(self, lu):
255 """Logical Unit execution sequence.
258 write_count = self.context.cfg.write_count
261 hm = self.BuildHooksManager(lu)
262 h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
263 lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
266 if getattr(lu.op, "dry_run", False):
267 # in this mode, no post-hooks are run, and the config is not
268 # written (as it might have been modified by another LU, and we
269 # shouldn't do writeout on behalf of other threads
270 self.LogInfo("dry-run mode requested, not actually executing"
272 return lu.dry_run_result
275 result = self._ProcessResult(lu.Exec(self.Log))
276 h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
277 result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
280 # FIXME: This needs locks if not lu_class.REQ_BGL
281 if write_count != self.context.cfg.write_count:
286 def BuildHooksManager(self, lu):
287 return self.hmclass.BuildFromLu(lu.rpc.call_hooks_runner, lu)
289 def _LockAndExecLU(self, lu, level, calc_timeout, priority):
290 """Execute a Logical Unit, with the needed locks.
292 This is a recursive function that starts locking the given level, and
293 proceeds up, till there are no more locks to acquire. Then it executes the
294 given LU and its opcodes.
297 adding_locks = level in lu.add_locks
298 acquiring_locks = level in lu.needed_locks
299 if level not in locking.LEVELS:
301 self._cbs.NotifyStart()
303 result = self._ExecLU(lu)
305 elif adding_locks and acquiring_locks:
306 # We could both acquire and add locks at the same level, but for now we
307 # don't need this, so we'll avoid the complicated code needed.
308 raise NotImplementedError("Can't declare locks to acquire when adding"
311 elif adding_locks or acquiring_locks:
312 lu.DeclareLocks(level)
313 share = lu.share_locks[level]
316 assert adding_locks ^ acquiring_locks, \
317 "Locks must be either added or acquired"
321 needed_locks = lu.needed_locks[level]
323 self._AcquireLocks(level, needed_locks, share,
324 calc_timeout(), priority)
327 add_locks = lu.add_locks[level]
328 lu.remove_locks[level] = add_locks
331 self.context.glm.add(level, add_locks, acquired=1, shared=share)
332 except errors.LockError:
333 raise errors.OpPrereqError(
334 "Couldn't add locks (%s), probably because of a race condition"
335 " with another job, who added them first" % add_locks,
339 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
341 if level in lu.remove_locks:
342 self.context.glm.remove(level, lu.remove_locks[level])
344 if self.context.glm.is_owned(level):
345 self.context.glm.release(level)
348 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
352 def ExecOpCode(self, op, cbs, timeout=None, priority=None):
353 """Execute an opcode.
355 @type op: an OpCode instance
356 @param op: the opcode to be executed
357 @type cbs: L{OpExecCbBase}
358 @param cbs: Runtime callbacks
359 @type timeout: float or None
360 @param timeout: Maximum time to acquire all locks, None for no timeout
361 @type priority: number or None
362 @param priority: Priority for acquiring lock(s)
363 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
367 if not isinstance(op, opcodes.OpCode):
368 raise errors.ProgrammerError("Non-opcode instance passed"
369 " to ExecOpcode (%s)" % type(op))
371 lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
373 raise errors.OpCodeUnknown("Unknown opcode")
376 calc_timeout = lambda: None
378 calc_timeout = utils.RunningTimeout(timeout, False).Remaining
382 # Acquire the Big Ganeti Lock exclusively if this LU requires it,
383 # and in a shared fashion otherwise (to prevent concurrent run with
385 self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL,
386 not lu_class.REQ_BGL, calc_timeout(),
389 lu = lu_class(self, op, self.context, self.rpc)
391 assert lu.needed_locks is not None, "needed_locks not set by LU"
394 result = self._LockAndExecLU(lu, locking.LEVEL_INSTANCE, calc_timeout,
398 self.context.cfg.DropECReservations(self._ec_id)
400 self.context.glm.release(locking.LEVEL_CLUSTER)
404 resultcheck_fn = op.OP_RESULT
405 if not (resultcheck_fn is None or resultcheck_fn(result)):
406 logging.error("Expected opcode result matching %s, got %s",
407 resultcheck_fn, result)
408 raise errors.OpResultError("Opcode result does not match %s" %
413 def Log(self, *args):
414 """Forward call to feedback callback function.
418 self._cbs.Feedback(*args)
420 def LogStep(self, current, total, message):
421 """Log a change in LU execution progress.
424 logging.debug("Step %d/%d %s", current, total, message)
425 self.Log("STEP %d/%d %s" % (current, total, message))
427 def LogWarning(self, message, *args, **kwargs):
428 """Log a warning to the logs and the user.
430 The optional keyword argument is 'hint' and can be used to show a
431 hint to the user (presumably related to the warning). If the
432 message is empty, it will not be printed at all, allowing one to
436 assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
437 "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
439 message = message % tuple(args)
441 logging.warning(message)
442 self.Log(" - WARNING: %s" % message)
444 self.Log(" Hint: %s" % kwargs["hint"])
446 def LogInfo(self, message, *args):
447 """Log an informational message to the logs and the user.
451 message = message % tuple(args)
452 logging.info(message)
453 self.Log(" - INFO: %s" % message)
456 """Returns the current execution context ID.
460 raise errors.ProgrammerError("Tried to use execution context id when"
465 class HooksMaster(object):
466 def __init__(self, opcode, hooks_path, nodes, hooks_execution_fn,
467 hooks_results_adapt_fn, build_env_fn, log_fn, htype=None, cluster_name=None,
469 """Base class for hooks masters.
471 This class invokes the execution of hooks according to the behaviour
472 specified by its parameters.
475 @param opcode: opcode of the operation to which the hooks are tied
476 @type hooks_path: string
477 @param hooks_path: prefix of the hooks directories
478 @type nodes: 2-tuple of lists
479 @param nodes: 2-tuple of lists containing nodes on which pre-hooks must be
480 run and nodes on which post-hooks must be run
481 @type hooks_execution_fn: function that accepts the following parameters:
482 (node_list, hooks_path, phase, environment)
483 @param hooks_execution_fn: function that will execute the hooks; can be
484 None, indicating that no conversion is necessary.
485 @type hooks_results_adapt_fn: function
486 @param hooks_results_adapt_fn: function that will adapt the return value of
487 hooks_execution_fn to the format expected by RunPhase
488 @type build_env_fn: function that returns a dictionary having strings as
490 @param build_env_fn: function that builds the environment for the hooks
491 @type log_fn: function that accepts a string
492 @param log_fn: logging function
493 @type htype: string or None
494 @param htype: None or one of L{constants.HTYPE_CLUSTER},
495 L{constants.HTYPE_NODE}, L{constants.HTYPE_INSTANCE}
496 @type cluster_name: string
497 @param cluster_name: name of the cluster
498 @type master_name: string
499 @param master_name: name of the master
503 self.hooks_path = hooks_path
504 self.hooks_execution_fn = hooks_execution_fn
505 self.hooks_results_adapt_fn = hooks_results_adapt_fn
506 self.build_env_fn = build_env_fn
509 self.cluster_name = cluster_name
510 self.master_name = master_name
512 self.pre_env = self._BuildEnv(constants.HOOKS_PHASE_PRE)
513 (self.pre_nodes, self.post_nodes) = nodes
515 def _BuildEnv(self, phase):
516 """Compute the environment and the target nodes.
518 Based on the opcode and the current node list, this builds the
519 environment for the hooks and the target node list for the run.
522 if phase == constants.HOOKS_PHASE_PRE:
524 elif phase == constants.HOOKS_PHASE_POST:
525 prefix = "GANETI_POST_"
527 raise AssertionError("Unknown phase '%s'" % phase)
531 if self.hooks_path is not None:
532 phase_env = self.build_env_fn()
534 assert not compat.any(key.upper().startswith(prefix)
535 for key in phase_env)
536 env.update(("%s%s" % (prefix, key), value)
537 for (key, value) in phase_env.items())
539 if phase == constants.HOOKS_PHASE_PRE:
540 assert compat.all((key.startswith("GANETI_") and
541 not key.startswith("GANETI_POST_"))
544 elif phase == constants.HOOKS_PHASE_POST:
545 assert compat.all(key.startswith("GANETI_POST_") for key in env)
546 assert isinstance(self.pre_env, dict)
548 # Merge with pre-phase environment
549 assert not compat.any(key.startswith("GANETI_POST_")
550 for key in self.pre_env)
551 env.update(self.pre_env)
553 raise AssertionError("Unknown phase '%s'" % phase)
557 def _RunWrapper(self, node_list, hpath, phase, phase_env):
558 """Simple wrapper over self.callfn.
560 This method fixes the environment before executing the hooks.
564 "PATH": constants.HOOKS_PATH,
565 "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
566 "GANETI_OP_CODE": self.opcode,
567 "GANETI_DATA_DIR": constants.DATA_DIR,
568 "GANETI_HOOKS_PHASE": phase,
569 "GANETI_HOOKS_PATH": hpath,
573 env["GANETI_OBJECT_TYPE"] = self.htype
575 if self.cluster_name is not None:
576 env["GANETI_CLUSTER"] = self.cluster_name
578 if self.master_name is not None:
579 env["GANETI_MASTER"] = self.master_name
582 env = utils.algo.JoinDisjointDicts(env, phase_env)
584 # Convert everything to strings
585 env = dict([(str(key), str(val)) for key, val in env.iteritems()])
587 assert compat.all(key == "PATH" or key.startswith("GANETI_")
590 return self.hooks_execution_fn(node_list, hpath, phase, env)
592 def RunPhase(self, phase, nodes=None):
593 """Run all the scripts for a phase.
595 This is the main function of the HookMaster.
596 It executes self.hooks_execution_fn, and after running
597 self.hooks_results_adapt_fn on its results it expects them to be in the form
598 {node_name: (fail_msg, [(script, result, output), ...]}).
600 @param phase: one of L{constants.HOOKS_PHASE_POST} or
601 L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
602 @param nodes: overrides the predefined list of nodes for the given phase
603 @return: the processed results of the hooks multi-node rpc call
604 @raise errors.HooksFailure: on communication failure to the nodes
605 @raise errors.HooksAbort: on failure of one of the hooks
608 if phase == constants.HOOKS_PHASE_PRE:
610 nodes = self.pre_nodes
612 elif phase == constants.HOOKS_PHASE_POST:
614 nodes = self.post_nodes
615 env = self._BuildEnv(phase)
617 raise AssertionError("Unknown phase '%s'" % phase)
620 # empty node list, we should not attempt to run this as either
621 # we're in the cluster init phase and the rpc client part can't
622 # even attempt to run, or this LU doesn't do hooks at all
625 results = self._RunWrapper(nodes, self.hooks_path, phase, env)
627 msg = "Communication Failure"
628 if phase == constants.HOOKS_PHASE_PRE:
629 raise errors.HooksFailure(msg)
634 converted_res = results
635 if self.hooks_results_adapt_fn:
636 converted_res = self.hooks_results_adapt_fn(results)
639 for node_name, (fail_msg, offline, hooks_results) in converted_res.items():
644 self.log_fn("Communication failure to node %s: %s", node_name, fail_msg)
647 for script, hkr, output in hooks_results:
648 if hkr == constants.HKR_FAIL:
649 if phase == constants.HOOKS_PHASE_PRE:
650 errs.append((node_name, script, output))
653 output = "(no output)"
654 self.log_fn("On %s script %s failed, output: %s" %
655 (node_name, script, output))
657 if errs and phase == constants.HOOKS_PHASE_PRE:
658 raise errors.HooksAbort(errs)
662 def RunConfigUpdate(self):
663 """Run the special configuration update hook
665 This is a special hook that runs only on the master after each
666 top-level LI if the configuration has been updated.
669 phase = constants.HOOKS_PHASE_POST
670 hpath = constants.HOOKS_NAME_CFGUPDATE
671 nodes = [self.master_name]
672 self._RunWrapper(nodes, hpath, phase, self.pre_env)
675 def BuildFromLu(hooks_execution_fn, lu):
679 nodes = map(frozenset, lu.BuildHooksNodes())
681 master_name = cluster_name = None
683 master_name = lu.cfg.GetMasterNode()
684 cluster_name = lu.cfg.GetClusterName()
686 return HooksMaster(lu.op.OP_ID, lu.HPATH, nodes, hooks_execution_fn,
687 _RpcResultsToHooksResults, lu.BuildHooksEnv,
688 lu.LogWarning, lu.HTYPE, cluster_name, master_name)