4 # Copyright (C) 2006, 2007, 2011, 2012 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
38 from ganeti import opcodes
39 from ganeti import constants
40 from ganeti import errors
41 from ganeti import cmdlib
42 from ganeti import locking
43 from ganeti import utils
44 from ganeti import compat
45 from ganeti import pathutils
52 class LockAcquireTimeout(Exception):
53 """Exception to report timeouts on acquiring locks.
58 def _CalculateLockAttemptTimeouts():
59 """Calculate timeouts for lock attempts.
62 result = [constants.LOCK_ATTEMPTS_MINWAIT]
63 running_sum = result[0]
65 # Wait for a total of at least LOCK_ATTEMPTS_TIMEOUT before doing a
67 while running_sum < constants.LOCK_ATTEMPTS_TIMEOUT:
68 timeout = (result[-1] * 1.05) ** 1.25
70 # Cap max timeout. This gives other jobs a chance to run even if
71 # we're still trying to get our locks, before finally moving to a
73 timeout = min(timeout, constants.LOCK_ATTEMPTS_MAXWAIT)
74 # And also cap the lower boundary for safety
75 timeout = max(timeout, constants.LOCK_ATTEMPTS_MINWAIT)
77 result.append(timeout)
78 running_sum += timeout
83 class LockAttemptTimeoutStrategy(object):
84 """Class with lock acquire timeout strategy.
93 _TIMEOUT_PER_ATTEMPT = _CalculateLockAttemptTimeouts()
95 def __init__(self, _time_fn=time.time, _random_fn=random.random):
96 """Initializes this class.
98 @param _time_fn: Time function for unittests
99 @param _random_fn: Random number generator for unittests
102 object.__init__(self)
104 self._timeouts = iter(self._TIMEOUT_PER_ATTEMPT)
105 self._time_fn = _time_fn
106 self._random_fn = _random_fn
108 def NextAttempt(self):
109 """Returns the timeout for the next attempt.
113 timeout = self._timeouts.next()
114 except StopIteration:
115 # No more timeouts, do blocking acquire
118 if timeout is not None:
119 # Add a small variation (-/+ 5%) to timeout. This helps in situations
120 # where two or more jobs are fighting for the same lock(s).
121 variation_range = timeout * 0.1
122 timeout += ((self._random_fn() * variation_range) -
123 (variation_range * 0.5))
128 class OpExecCbBase: # pylint: disable=W0232
129 """Base class for OpCode execution callbacks.
132 def NotifyStart(self):
133 """Called when we are about to execute the LU.
135 This function is called when we're about to start the lu's Exec() method,
136 that is, after we have acquired all locks.
140 def Feedback(self, *args):
141 """Sends feedback from the LU code to the end-user.
145 def CurrentPriority(self): # pylint: disable=R0201
146 """Returns current priority or C{None}.
151 def SubmitManyJobs(self, jobs):
152 """Submits jobs for processing.
154 See L{jqueue.JobQueue.SubmitManyJobs}.
157 raise NotImplementedError
160 def _LUNameForOpName(opname):
161 """Computes the LU name for a given OpCode name.
164 assert opname.startswith(_OP_PREFIX), \
165 "Invalid OpCode name, doesn't start with %s: %s" % (_OP_PREFIX, opname)
167 return _LU_PREFIX + opname[len(_OP_PREFIX):]
170 def _ComputeDispatchTable():
171 """Computes the opcode-to-lu dispatch table.
174 return dict((op, getattr(cmdlib, _LUNameForOpName(op.__name__)))
175 for op in opcodes.OP_MAPPING.values()
179 def _SetBaseOpParams(src, defcomment, dst):
180 """Copies basic opcode parameters.
182 @type src: L{opcodes.OpCode}
183 @param src: Source opcode
184 @type defcomment: string
185 @param defcomment: Comment to specify if not already given
186 @type dst: L{opcodes.OpCode}
187 @param dst: Destination opcode
190 if hasattr(src, "debug_level"):
191 dst.debug_level = src.debug_level
193 if (getattr(dst, "priority", None) is None and
194 hasattr(src, "priority")):
195 dst.priority = src.priority
197 if not getattr(dst, opcodes.COMMENT_ATTR, None):
198 dst.comment = defcomment
201 def _ProcessResult(submit_fn, op, result):
202 """Examines opcode result.
204 If necessary, additional processing on the result is done.
207 if isinstance(result, cmdlib.ResultWithJobs):
208 # Copy basic parameters (e.g. priority)
209 map(compat.partial(_SetBaseOpParams, op,
210 "Submitted by %s" % op.OP_ID),
211 itertools.chain(*result.jobs))
214 job_submission = submit_fn(result.jobs)
217 result = result.other
219 assert constants.JOB_IDS_KEY not in result, \
220 "Key '%s' found in additional return values" % constants.JOB_IDS_KEY
222 result[constants.JOB_IDS_KEY] = job_submission
227 def _FailingSubmitManyJobs(_):
228 """Implementation of L{OpExecCbBase.SubmitManyJobs} to raise an exception.
231 raise errors.ProgrammerError("Opcodes processed without callbacks (e.g."
232 " queries) can not submit jobs")
235 def _RpcResultsToHooksResults(rpc_results):
236 """Function to convert RPC results to the format expected by HooksMaster.
238 @type rpc_results: dict(node: L{rpc.RpcResult})
239 @param rpc_results: RPC results
240 @rtype: dict(node: (fail_msg, offline, hooks_results))
241 @return: RPC results unpacked according to the format expected by
245 return dict((node, (rpc_res.fail_msg, rpc_res.offline, rpc_res.payload))
246 for (node, rpc_res) in rpc_results.items())
249 class Processor(object):
250 """Object which runs OpCodes"""
251 DISPATCH_TABLE = _ComputeDispatchTable()
253 def __init__(self, context, ec_id, enable_locks=True):
254 """Constructor for Processor
256 @type context: GanetiContext
257 @param context: global Ganeti context
259 @param ec_id: execution context identifier
262 self.context = context
265 self.rpc = context.rpc
266 self.hmclass = HooksMaster
267 self._enable_locks = enable_locks
269 def _CheckLocksEnabled(self):
270 """Checks if locking is enabled.
272 @raise errors.ProgrammerError: In case locking is not enabled
275 if not self._enable_locks:
276 raise errors.ProgrammerError("Attempted to use disabled locks")
278 def _AcquireLocks(self, level, names, shared, timeout):
279 """Acquires locks via the Ganeti lock manager.
282 @param level: Lock level
283 @type names: list or string
284 @param names: Lock names
286 @param shared: Whether the locks should be acquired in shared mode
287 @type timeout: None or float
288 @param timeout: Timeout for acquiring the locks
289 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
293 self._CheckLocksEnabled()
296 priority = self._cbs.CurrentPriority()
300 acquired = self.context.glm.acquire(level, names, shared=shared,
301 timeout=timeout, priority=priority)
304 raise LockAcquireTimeout()
308 def _ExecLU(self, lu):
309 """Logical Unit execution sequence.
312 write_count = self.context.cfg.write_count
315 hm = self.BuildHooksManager(lu)
316 h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
317 lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
320 if getattr(lu.op, "dry_run", False):
321 # in this mode, no post-hooks are run, and the config is not
322 # written (as it might have been modified by another LU, and we
323 # shouldn't do writeout on behalf of other threads
324 self.LogInfo("dry-run mode requested, not actually executing"
326 return lu.dry_run_result
329 submit_mj_fn = self._cbs.SubmitManyJobs
331 submit_mj_fn = _FailingSubmitManyJobs
334 result = _ProcessResult(submit_mj_fn, lu.op, lu.Exec(self.Log))
335 h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
336 result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
339 # FIXME: This needs locks if not lu_class.REQ_BGL
340 if write_count != self.context.cfg.write_count:
345 def BuildHooksManager(self, lu):
346 return self.hmclass.BuildFromLu(lu.rpc.call_hooks_runner, lu)
348 def _LockAndExecLU(self, lu, level, calc_timeout):
349 """Execute a Logical Unit, with the needed locks.
351 This is a recursive function that starts locking the given level, and
352 proceeds up, till there are no more locks to acquire. Then it executes the
353 given LU and its opcodes.
356 adding_locks = level in lu.add_locks
357 acquiring_locks = level in lu.needed_locks
358 if level not in locking.LEVELS:
360 self._cbs.NotifyStart()
363 result = self._ExecLU(lu)
364 except AssertionError, err:
365 # this is a bit ugly, as we don't know from which phase
366 # (prereq, exec) this comes; but it's better than an exception
367 # with no information
368 (_, _, tb) = sys.exc_info()
369 err_info = traceback.format_tb(tb)
371 logging.exception("Detected AssertionError")
372 raise errors.OpExecError("Internal assertion error: please report"
373 " this as a bug.\nError message: '%s';"
374 " location:\n%s" % (str(err), err_info[-1]))
376 elif adding_locks and acquiring_locks:
377 # We could both acquire and add locks at the same level, but for now we
378 # don't need this, so we'll avoid the complicated code needed.
379 raise NotImplementedError("Can't declare locks to acquire when adding"
382 elif adding_locks or acquiring_locks:
383 self._CheckLocksEnabled()
385 lu.DeclareLocks(level)
386 share = lu.share_locks[level]
389 assert adding_locks ^ acquiring_locks, \
390 "Locks must be either added or acquired"
394 needed_locks = lu.needed_locks[level]
396 self._AcquireLocks(level, needed_locks, share,
400 add_locks = lu.add_locks[level]
401 lu.remove_locks[level] = add_locks
404 self.context.glm.add(level, add_locks, acquired=1, shared=share)
405 except errors.LockError:
406 logging.exception("Detected lock error in level %s for locks"
407 " %s, shared=%s", level, add_locks, share)
408 raise errors.OpPrereqError(
409 "Couldn't add locks (%s), most likely because of another"
410 " job who added them first" % add_locks,
411 errors.ECODE_NOTUNIQUE)
414 result = self._LockAndExecLU(lu, level + 1, calc_timeout)
416 if level in lu.remove_locks:
417 self.context.glm.remove(level, lu.remove_locks[level])
419 if self.context.glm.is_owned(level):
420 self.context.glm.release(level)
423 result = self._LockAndExecLU(lu, level + 1, calc_timeout)
427 def ExecOpCode(self, op, cbs, timeout=None):
428 """Execute an opcode.
430 @type op: an OpCode instance
431 @param op: the opcode to be executed
432 @type cbs: L{OpExecCbBase}
433 @param cbs: Runtime callbacks
434 @type timeout: float or None
435 @param timeout: Maximum time to acquire all locks, None for no timeout
436 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
440 if not isinstance(op, opcodes.OpCode):
441 raise errors.ProgrammerError("Non-opcode instance passed"
442 " to ExecOpcode (%s)" % type(op))
444 lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
446 raise errors.OpCodeUnknown("Unknown opcode")
449 calc_timeout = lambda: None
451 calc_timeout = utils.RunningTimeout(timeout, False).Remaining
455 if self._enable_locks:
456 # Acquire the Big Ganeti Lock exclusively if this LU requires it,
457 # and in a shared fashion otherwise (to prevent concurrent run with
459 self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL,
460 not lu_class.REQ_BGL, calc_timeout())
461 elif lu_class.REQ_BGL:
462 raise errors.ProgrammerError("Opcode '%s' requires BGL, but locks are"
463 " disabled" % op.OP_ID)
466 lu = lu_class(self, op, self.context, self.rpc)
468 assert lu.needed_locks is not None, "needed_locks not set by LU"
471 result = self._LockAndExecLU(lu, locking.LEVEL_INSTANCE, calc_timeout)
474 self.context.cfg.DropECReservations(self._ec_id)
476 # Release BGL if owned
477 if self.context.glm.is_owned(locking.LEVEL_CLUSTER):
478 assert self._enable_locks
479 self.context.glm.release(locking.LEVEL_CLUSTER)
483 resultcheck_fn = op.OP_RESULT
484 if not (resultcheck_fn is None or resultcheck_fn(result)):
485 logging.error("Expected opcode result matching %s, got %s",
486 resultcheck_fn, result)
487 raise errors.OpResultError("Opcode result does not match %s: %s" %
488 (resultcheck_fn, utils.Truncate(result, 80)))
492 def Log(self, *args):
493 """Forward call to feedback callback function.
497 self._cbs.Feedback(*args)
499 def LogStep(self, current, total, message):
500 """Log a change in LU execution progress.
503 logging.debug("Step %d/%d %s", current, total, message)
504 self.Log("STEP %d/%d %s" % (current, total, message))
506 def LogWarning(self, message, *args, **kwargs):
507 """Log a warning to the logs and the user.
509 The optional keyword argument is 'hint' and can be used to show a
510 hint to the user (presumably related to the warning). If the
511 message is empty, it will not be printed at all, allowing one to
515 assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
516 "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
518 message = message % tuple(args)
520 logging.warning(message)
521 self.Log(" - WARNING: %s" % message)
523 self.Log(" Hint: %s" % kwargs["hint"])
525 def LogInfo(self, message, *args):
526 """Log an informational message to the logs and the user.
530 message = message % tuple(args)
531 logging.info(message)
532 self.Log(" - INFO: %s" % message)
535 """Returns the current execution context ID.
539 raise errors.ProgrammerError("Tried to use execution context id when"
544 class HooksMaster(object):
545 def __init__(self, opcode, hooks_path, nodes, hooks_execution_fn,
546 hooks_results_adapt_fn, build_env_fn, log_fn, htype=None,
547 cluster_name=None, master_name=None):
548 """Base class for hooks masters.
550 This class invokes the execution of hooks according to the behaviour
551 specified by its parameters.
554 @param opcode: opcode of the operation to which the hooks are tied
555 @type hooks_path: string
556 @param hooks_path: prefix of the hooks directories
557 @type nodes: 2-tuple of lists
558 @param nodes: 2-tuple of lists containing nodes on which pre-hooks must be
559 run and nodes on which post-hooks must be run
560 @type hooks_execution_fn: function that accepts the following parameters:
561 (node_list, hooks_path, phase, environment)
562 @param hooks_execution_fn: function that will execute the hooks; can be
563 None, indicating that no conversion is necessary.
564 @type hooks_results_adapt_fn: function
565 @param hooks_results_adapt_fn: function that will adapt the return value of
566 hooks_execution_fn to the format expected by RunPhase
567 @type build_env_fn: function that returns a dictionary having strings as
569 @param build_env_fn: function that builds the environment for the hooks
570 @type log_fn: function that accepts a string
571 @param log_fn: logging function
572 @type htype: string or None
573 @param htype: None or one of L{constants.HTYPE_CLUSTER},
574 L{constants.HTYPE_NODE}, L{constants.HTYPE_INSTANCE}
575 @type cluster_name: string
576 @param cluster_name: name of the cluster
577 @type master_name: string
578 @param master_name: name of the master
582 self.hooks_path = hooks_path
583 self.hooks_execution_fn = hooks_execution_fn
584 self.hooks_results_adapt_fn = hooks_results_adapt_fn
585 self.build_env_fn = build_env_fn
588 self.cluster_name = cluster_name
589 self.master_name = master_name
591 self.pre_env = self._BuildEnv(constants.HOOKS_PHASE_PRE)
592 (self.pre_nodes, self.post_nodes) = nodes
594 def _BuildEnv(self, phase):
595 """Compute the environment and the target nodes.
597 Based on the opcode and the current node list, this builds the
598 environment for the hooks and the target node list for the run.
601 if phase == constants.HOOKS_PHASE_PRE:
603 elif phase == constants.HOOKS_PHASE_POST:
604 prefix = "GANETI_POST_"
606 raise AssertionError("Unknown phase '%s'" % phase)
610 if self.hooks_path is not None:
611 phase_env = self.build_env_fn()
613 assert not compat.any(key.upper().startswith(prefix)
614 for key in phase_env)
615 env.update(("%s%s" % (prefix, key), value)
616 for (key, value) in phase_env.items())
618 if phase == constants.HOOKS_PHASE_PRE:
619 assert compat.all((key.startswith("GANETI_") and
620 not key.startswith("GANETI_POST_"))
623 elif phase == constants.HOOKS_PHASE_POST:
624 assert compat.all(key.startswith("GANETI_POST_") for key in env)
625 assert isinstance(self.pre_env, dict)
627 # Merge with pre-phase environment
628 assert not compat.any(key.startswith("GANETI_POST_")
629 for key in self.pre_env)
630 env.update(self.pre_env)
632 raise AssertionError("Unknown phase '%s'" % phase)
636 def _RunWrapper(self, node_list, hpath, phase, phase_env):
637 """Simple wrapper over self.callfn.
639 This method fixes the environment before executing the hooks.
643 "PATH": constants.HOOKS_PATH,
644 "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
645 "GANETI_OP_CODE": self.opcode,
646 "GANETI_DATA_DIR": pathutils.DATA_DIR,
647 "GANETI_HOOKS_PHASE": phase,
648 "GANETI_HOOKS_PATH": hpath,
652 env["GANETI_OBJECT_TYPE"] = self.htype
654 if self.cluster_name is not None:
655 env["GANETI_CLUSTER"] = self.cluster_name
657 if self.master_name is not None:
658 env["GANETI_MASTER"] = self.master_name
661 env = utils.algo.JoinDisjointDicts(env, phase_env)
663 # Convert everything to strings
664 env = dict([(str(key), str(val)) for key, val in env.iteritems()])
666 assert compat.all(key == "PATH" or key.startswith("GANETI_")
669 return self.hooks_execution_fn(node_list, hpath, phase, env)
671 def RunPhase(self, phase, nodes=None):
672 """Run all the scripts for a phase.
674 This is the main function of the HookMaster.
675 It executes self.hooks_execution_fn, and after running
676 self.hooks_results_adapt_fn on its results it expects them to be in the form
677 {node_name: (fail_msg, [(script, result, output), ...]}).
679 @param phase: one of L{constants.HOOKS_PHASE_POST} or
680 L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
681 @param nodes: overrides the predefined list of nodes for the given phase
682 @return: the processed results of the hooks multi-node rpc call
683 @raise errors.HooksFailure: on communication failure to the nodes
684 @raise errors.HooksAbort: on failure of one of the hooks
687 if phase == constants.HOOKS_PHASE_PRE:
689 nodes = self.pre_nodes
691 elif phase == constants.HOOKS_PHASE_POST:
693 nodes = self.post_nodes
694 env = self._BuildEnv(phase)
696 raise AssertionError("Unknown phase '%s'" % phase)
699 # empty node list, we should not attempt to run this as either
700 # we're in the cluster init phase and the rpc client part can't
701 # even attempt to run, or this LU doesn't do hooks at all
704 results = self._RunWrapper(nodes, self.hooks_path, phase, env)
706 msg = "Communication Failure"
707 if phase == constants.HOOKS_PHASE_PRE:
708 raise errors.HooksFailure(msg)
713 converted_res = results
714 if self.hooks_results_adapt_fn:
715 converted_res = self.hooks_results_adapt_fn(results)
718 for node_name, (fail_msg, offline, hooks_results) in converted_res.items():
723 self.log_fn("Communication failure to node %s: %s", node_name, fail_msg)
726 for script, hkr, output in hooks_results:
727 if hkr == constants.HKR_FAIL:
728 if phase == constants.HOOKS_PHASE_PRE:
729 errs.append((node_name, script, output))
732 output = "(no output)"
733 self.log_fn("On %s script %s failed, output: %s" %
734 (node_name, script, output))
736 if errs and phase == constants.HOOKS_PHASE_PRE:
737 raise errors.HooksAbort(errs)
741 def RunConfigUpdate(self):
742 """Run the special configuration update hook
744 This is a special hook that runs only on the master after each
745 top-level LI if the configuration has been updated.
748 phase = constants.HOOKS_PHASE_POST
749 hpath = constants.HOOKS_NAME_CFGUPDATE
750 nodes = [self.master_name]
751 self._RunWrapper(nodes, hpath, phase, self.pre_env)
754 def BuildFromLu(hooks_execution_fn, lu):
758 nodes = map(frozenset, lu.BuildHooksNodes())
760 master_name = cluster_name = None
762 master_name = lu.cfg.GetMasterNode()
763 cluster_name = lu.cfg.GetClusterName()
765 return HooksMaster(lu.op.OP_ID, lu.HPATH, nodes, hooks_execution_fn,
766 _RpcResultsToHooksResults, lu.BuildHooksEnv,
767 lu.LogWarning, lu.HTYPE, cluster_name, master_name)