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 class Processor(object):
176 """Object which runs OpCodes"""
177 DISPATCH_TABLE = _ComputeDispatchTable()
179 def __init__(self, context, ec_id, enable_locks=True):
180 """Constructor for Processor
182 @type context: GanetiContext
183 @param context: global Ganeti context
185 @param ec_id: execution context identifier
188 self.context = context
191 self.rpc = rpc.RpcRunner(context.cfg)
192 self.hmclass = HooksMaster
193 self._enable_locks = enable_locks
195 def _CheckLocksEnabled(self):
196 """Checks if locking is enabled.
198 @raise errors.ProgrammerError: In case locking is not enabled
201 if not self._enable_locks:
202 raise errors.ProgrammerError("Attempted to use disabled locks")
204 def _AcquireLocks(self, level, names, shared, timeout, priority):
205 """Acquires locks via the Ganeti lock manager.
208 @param level: Lock level
209 @type names: list or string
210 @param names: Lock names
212 @param shared: Whether the locks should be acquired in shared mode
213 @type timeout: None or float
214 @param timeout: Timeout for acquiring the locks
215 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
219 self._CheckLocksEnabled()
222 self._cbs.CheckCancel()
224 acquired = self.context.glm.acquire(level, names, shared=shared,
225 timeout=timeout, priority=priority)
228 raise LockAcquireTimeout()
232 def _ProcessResult(self, result):
233 """Examines opcode result.
235 If necessary, additional processing on the result is done.
238 if isinstance(result, cmdlib.ResultWithJobs):
240 job_submission = self._cbs.SubmitManyJobs(result.jobs)
243 result = result.other
245 assert constants.JOB_IDS_KEY not in result, \
246 "Key '%s' found in additional return values" % constants.JOB_IDS_KEY
248 result[constants.JOB_IDS_KEY] = job_submission
252 def _ExecLU(self, lu):
253 """Logical Unit execution sequence.
256 write_count = self.context.cfg.write_count
258 hm = HooksMaster(self.rpc.call_hooks_runner, lu)
259 h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
260 lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
263 if getattr(lu.op, "dry_run", False):
264 # in this mode, no post-hooks are run, and the config is not
265 # written (as it might have been modified by another LU, and we
266 # shouldn't do writeout on behalf of other threads
267 self.LogInfo("dry-run mode requested, not actually executing"
269 return lu.dry_run_result
272 result = self._ProcessResult(lu.Exec(self.Log))
273 h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
274 result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
277 # FIXME: This needs locks if not lu_class.REQ_BGL
278 if write_count != self.context.cfg.write_count:
283 def _LockAndExecLU(self, lu, level, calc_timeout, priority):
284 """Execute a Logical Unit, with the needed locks.
286 This is a recursive function that starts locking the given level, and
287 proceeds up, till there are no more locks to acquire. Then it executes the
288 given LU and its opcodes.
291 adding_locks = level in lu.add_locks
292 acquiring_locks = level in lu.needed_locks
293 if level not in locking.LEVELS:
295 self._cbs.NotifyStart()
297 result = self._ExecLU(lu)
299 elif adding_locks and acquiring_locks:
300 # We could both acquire and add locks at the same level, but for now we
301 # don't need this, so we'll avoid the complicated code needed.
302 raise NotImplementedError("Can't declare locks to acquire when adding"
305 elif adding_locks or acquiring_locks:
306 self._CheckLocksEnabled()
308 lu.DeclareLocks(level)
309 share = lu.share_locks[level]
312 assert adding_locks ^ acquiring_locks, \
313 "Locks must be either added or acquired"
317 needed_locks = lu.needed_locks[level]
319 self._AcquireLocks(level, needed_locks, share,
320 calc_timeout(), priority)
323 add_locks = lu.add_locks[level]
324 lu.remove_locks[level] = add_locks
327 self.context.glm.add(level, add_locks, acquired=1, shared=share)
328 except errors.LockError:
329 raise errors.OpPrereqError(
330 "Couldn't add locks (%s), probably because of a race condition"
331 " with another job, who added them first" % add_locks,
335 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
337 if level in lu.remove_locks:
338 self.context.glm.remove(level, lu.remove_locks[level])
340 if self.context.glm.is_owned(level):
341 self.context.glm.release(level)
344 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
348 def ExecOpCode(self, op, cbs, timeout=None, priority=None):
349 """Execute an opcode.
351 @type op: an OpCode instance
352 @param op: the opcode to be executed
353 @type cbs: L{OpExecCbBase}
354 @param cbs: Runtime callbacks
355 @type timeout: float or None
356 @param timeout: Maximum time to acquire all locks, None for no timeout
357 @type priority: number or None
358 @param priority: Priority for acquiring lock(s)
359 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
363 if not isinstance(op, opcodes.OpCode):
364 raise errors.ProgrammerError("Non-opcode instance passed"
365 " to ExecOpcode (%s)" % type(op))
367 lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
369 raise errors.OpCodeUnknown("Unknown opcode")
372 calc_timeout = lambda: None
374 calc_timeout = utils.RunningTimeout(timeout, False).Remaining
378 if self._enable_locks:
379 # Acquire the Big Ganeti Lock exclusively if this LU requires it,
380 # and in a shared fashion otherwise (to prevent concurrent run with
382 self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL,
383 not lu_class.REQ_BGL, calc_timeout(),
385 elif lu_class.REQ_BGL:
386 raise errors.ProgrammerError("Opcode '%s' requires BGL, but locks are"
387 " disabled" % op.OP_ID)
390 lu = lu_class(self, op, self.context, self.rpc)
392 assert lu.needed_locks is not None, "needed_locks not set by LU"
395 result = self._LockAndExecLU(lu, locking.LEVEL_INSTANCE, calc_timeout,
399 self.context.cfg.DropECReservations(self._ec_id)
401 # Release BGL if owned
402 if self.context.glm.is_owned(locking.LEVEL_CLUSTER):
403 assert self._enable_locks
404 self.context.glm.release(locking.LEVEL_CLUSTER)
408 resultcheck_fn = op.OP_RESULT
409 if not (resultcheck_fn is None or resultcheck_fn(result)):
410 logging.error("Expected opcode result matching %s, got %s",
411 resultcheck_fn, result)
412 raise errors.OpResultError("Opcode result does not match %s" %
417 def Log(self, *args):
418 """Forward call to feedback callback function.
422 self._cbs.Feedback(*args)
424 def LogStep(self, current, total, message):
425 """Log a change in LU execution progress.
428 logging.debug("Step %d/%d %s", current, total, message)
429 self.Log("STEP %d/%d %s" % (current, total, message))
431 def LogWarning(self, message, *args, **kwargs):
432 """Log a warning to the logs and the user.
434 The optional keyword argument is 'hint' and can be used to show a
435 hint to the user (presumably related to the warning). If the
436 message is empty, it will not be printed at all, allowing one to
440 assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
441 "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
443 message = message % tuple(args)
445 logging.warning(message)
446 self.Log(" - WARNING: %s" % message)
448 self.Log(" Hint: %s" % kwargs["hint"])
450 def LogInfo(self, message, *args):
451 """Log an informational message to the logs and the user.
455 message = message % tuple(args)
456 logging.info(message)
457 self.Log(" - INFO: %s" % message)
460 """Returns the current execution context ID.
464 raise errors.ProgrammerError("Tried to use execution context id when"
469 class HooksMaster(object):
472 This class distributes the run commands to the nodes based on the
475 In order to remove the direct dependency on the rpc module, the
476 constructor needs a function which actually does the remote
477 call. This will usually be rpc.call_hooks_runner, but any function
478 which behaves the same works.
481 def __init__(self, callfn, lu):
485 self.pre_env = self._BuildEnv(constants.HOOKS_PHASE_PRE)
487 if self.lu.HPATH is None:
490 nodes = map(frozenset, self.lu.BuildHooksNodes())
492 (self.pre_nodes, self.post_nodes) = nodes
494 def _BuildEnv(self, phase):
495 """Compute the environment and the target nodes.
497 Based on the opcode and the current node list, this builds the
498 environment for the hooks and the target node list for the run.
501 if phase == constants.HOOKS_PHASE_PRE:
503 elif phase == constants.HOOKS_PHASE_POST:
504 prefix = "GANETI_POST_"
506 raise AssertionError("Unknown phase '%s'" % phase)
510 if self.lu.HPATH is not None:
511 lu_env = self.lu.BuildHooksEnv()
513 assert not compat.any(key.upper().startswith(prefix) for key in lu_env)
514 env.update(("%s%s" % (prefix, key), value)
515 for (key, value) in lu_env.items())
517 if phase == constants.HOOKS_PHASE_PRE:
518 assert compat.all((key.startswith("GANETI_") and
519 not key.startswith("GANETI_POST_"))
522 elif phase == constants.HOOKS_PHASE_POST:
523 assert compat.all(key.startswith("GANETI_POST_") for key in env)
524 assert isinstance(self.pre_env, dict)
526 # Merge with pre-phase environment
527 assert not compat.any(key.startswith("GANETI_POST_")
528 for key in self.pre_env)
529 env.update(self.pre_env)
531 raise AssertionError("Unknown phase '%s'" % phase)
535 def _RunWrapper(self, node_list, hpath, phase, phase_env):
536 """Simple wrapper over self.callfn.
538 This method fixes the environment before doing the rpc call.
544 "PATH": "/sbin:/bin:/usr/sbin:/usr/bin",
545 "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
546 "GANETI_OP_CODE": self.op.OP_ID,
547 "GANETI_DATA_DIR": constants.DATA_DIR,
548 "GANETI_HOOKS_PHASE": phase,
549 "GANETI_HOOKS_PATH": hpath,
553 env["GANETI_OBJECT_TYPE"] = self.lu.HTYPE
556 env["GANETI_CLUSTER"] = cfg.GetClusterName()
557 env["GANETI_MASTER"] = cfg.GetMasterNode()
560 assert not (set(env) & set(phase_env)), "Environment variables conflict"
561 env.update(phase_env)
563 # Convert everything to strings
564 env = dict([(str(key), str(val)) for key, val in env.iteritems()])
566 assert compat.all(key == "PATH" or key.startswith("GANETI_")
569 return self.callfn(node_list, hpath, phase, env)
571 def RunPhase(self, phase, nodes=None):
572 """Run all the scripts for a phase.
574 This is the main function of the HookMaster.
576 @param phase: one of L{constants.HOOKS_PHASE_POST} or
577 L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
578 @param nodes: overrides the predefined list of nodes for the given phase
579 @return: the processed results of the hooks multi-node rpc call
580 @raise errors.HooksFailure: on communication failure to the nodes
581 @raise errors.HooksAbort: on failure of one of the hooks
584 if phase == constants.HOOKS_PHASE_PRE:
586 nodes = self.pre_nodes
588 elif phase == constants.HOOKS_PHASE_POST:
590 nodes = self.post_nodes
591 env = self._BuildEnv(phase)
593 raise AssertionError("Unknown phase '%s'" % phase)
596 # empty node list, we should not attempt to run this as either
597 # we're in the cluster init phase and the rpc client part can't
598 # even attempt to run, or this LU doesn't do hooks at all
601 results = self._RunWrapper(nodes, self.lu.HPATH, phase, env)
603 msg = "Communication Failure"
604 if phase == constants.HOOKS_PHASE_PRE:
605 raise errors.HooksFailure(msg)
607 self.lu.LogWarning(msg)
611 for node_name in results:
612 res = results[node_name]
618 self.lu.LogWarning("Communication failure to node %s: %s",
622 for script, hkr, output in res.payload:
623 if hkr == constants.HKR_FAIL:
624 if phase == constants.HOOKS_PHASE_PRE:
625 errs.append((node_name, script, output))
628 output = "(no output)"
629 self.lu.LogWarning("On %s script %s failed, output: %s" %
630 (node_name, script, output))
632 if errs and phase == constants.HOOKS_PHASE_PRE:
633 raise errors.HooksAbort(errs)
637 def RunConfigUpdate(self):
638 """Run the special configuration update hook
640 This is a special hook that runs only on the master after each
641 top-level LI if the configuration has been updated.
644 phase = constants.HOOKS_PHASE_POST
645 hpath = constants.HOOKS_NAME_CFGUPDATE
646 nodes = [self.lu.cfg.GetMasterNode()]
647 self._RunWrapper(nodes, hpath, phase, self.pre_env)