4 # Copyright (C) 2006, 2007 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
43 class _LockAcquireTimeout(Exception):
44 """Internal exception to report timeouts on acquiring locks.
49 def _CalculateLockAttemptTimeouts():
50 """Calculate timeouts for lock attempts.
56 # Wait for a total of at least 150s before doing a blocking acquire
57 while sum(result) < 150.0:
58 timeout = (result[-1] * 1.05) ** 1.25
60 # Cap timeout at 10 seconds. This gives other jobs a chance to run
61 # even if we're still trying to get our locks, before finally moving
62 # to a blocking acquire.
67 # Lower boundary for safety
70 result.append(timeout)
75 class _LockAttemptTimeoutStrategy(object):
76 """Class with lock acquire timeout strategy.
87 _TIMEOUT_PER_ATTEMPT = _CalculateLockAttemptTimeouts()
89 def __init__(self, attempt=0, _time_fn=time.time, _random_fn=random.random):
90 """Initializes this class.
93 @param attempt: Current attempt number
94 @param _time_fn: Time function for unittests
95 @param _random_fn: Random number generator for unittests
101 raise ValueError("Attempt must be zero or positive")
103 self._attempt = attempt
104 self._time_fn = _time_fn
105 self._random_fn = _random_fn
108 timeout = self._TIMEOUT_PER_ATTEMPT[attempt]
110 # No more timeouts, do blocking acquire
113 self._running_timeout = locking.RunningTimeout(timeout, False,
116 def NextAttempt(self):
117 """Returns the strategy for the next attempt.
120 return _LockAttemptTimeoutStrategy(attempt=self._attempt + 1,
121 _time_fn=self._time_fn,
122 _random_fn=self._random_fn)
124 def CalcRemainingTimeout(self):
125 """Returns the remaining timeout.
128 timeout = self._running_timeout.Remaining()
130 if timeout is not None:
131 # Add a small variation (-/+ 5%) to timeout. This helps in situations
132 # where two or more jobs are fighting for the same lock(s).
133 variation_range = timeout * 0.1
134 timeout += ((self._random_fn() * variation_range) -
135 (variation_range * 0.5))
141 """Base class for OpCode execution callbacks.
144 def NotifyStart(self):
145 """Called when we are about to execute the LU.
147 This function is called when we're about to start the lu's Exec() method,
148 that is, after we have acquired all locks.
152 def Feedback(self, *args):
153 """Sends feedback from the LU code to the end-user.
157 def ReportLocks(self, msg):
158 """Report lock operations.
163 class Processor(object):
164 """Object which runs OpCodes"""
167 opcodes.OpPostInitCluster: cmdlib.LUPostInitCluster,
168 opcodes.OpDestroyCluster: cmdlib.LUDestroyCluster,
169 opcodes.OpQueryClusterInfo: cmdlib.LUQueryClusterInfo,
170 opcodes.OpVerifyCluster: cmdlib.LUVerifyCluster,
171 opcodes.OpQueryConfigValues: cmdlib.LUQueryConfigValues,
172 opcodes.OpRenameCluster: cmdlib.LURenameCluster,
173 opcodes.OpVerifyDisks: cmdlib.LUVerifyDisks,
174 opcodes.OpSetClusterParams: cmdlib.LUSetClusterParams,
175 opcodes.OpRedistributeConfig: cmdlib.LURedistributeConfig,
176 opcodes.OpRepairDiskSizes: cmdlib.LURepairDiskSizes,
178 opcodes.OpAddNode: cmdlib.LUAddNode,
179 opcodes.OpQueryNodes: cmdlib.LUQueryNodes,
180 opcodes.OpQueryNodeVolumes: cmdlib.LUQueryNodeVolumes,
181 opcodes.OpQueryNodeStorage: cmdlib.LUQueryNodeStorage,
182 opcodes.OpModifyNodeStorage: cmdlib.LUModifyNodeStorage,
183 opcodes.OpRepairNodeStorage: cmdlib.LURepairNodeStorage,
184 opcodes.OpRemoveNode: cmdlib.LURemoveNode,
185 opcodes.OpSetNodeParams: cmdlib.LUSetNodeParams,
186 opcodes.OpPowercycleNode: cmdlib.LUPowercycleNode,
187 opcodes.OpEvacuateNode: cmdlib.LUEvacuateNode,
188 opcodes.OpMigrateNode: cmdlib.LUMigrateNode,
190 opcodes.OpCreateInstance: cmdlib.LUCreateInstance,
191 opcodes.OpReinstallInstance: cmdlib.LUReinstallInstance,
192 opcodes.OpRemoveInstance: cmdlib.LURemoveInstance,
193 opcodes.OpRenameInstance: cmdlib.LURenameInstance,
194 opcodes.OpActivateInstanceDisks: cmdlib.LUActivateInstanceDisks,
195 opcodes.OpShutdownInstance: cmdlib.LUShutdownInstance,
196 opcodes.OpStartupInstance: cmdlib.LUStartupInstance,
197 opcodes.OpRebootInstance: cmdlib.LURebootInstance,
198 opcodes.OpDeactivateInstanceDisks: cmdlib.LUDeactivateInstanceDisks,
199 opcodes.OpReplaceDisks: cmdlib.LUReplaceDisks,
200 opcodes.OpRecreateInstanceDisks: cmdlib.LURecreateInstanceDisks,
201 opcodes.OpFailoverInstance: cmdlib.LUFailoverInstance,
202 opcodes.OpMigrateInstance: cmdlib.LUMigrateInstance,
203 opcodes.OpMoveInstance: cmdlib.LUMoveInstance,
204 opcodes.OpConnectConsole: cmdlib.LUConnectConsole,
205 opcodes.OpQueryInstances: cmdlib.LUQueryInstances,
206 opcodes.OpQueryInstanceData: cmdlib.LUQueryInstanceData,
207 opcodes.OpSetInstanceParams: cmdlib.LUSetInstanceParams,
208 opcodes.OpGrowDisk: cmdlib.LUGrowDisk,
210 opcodes.OpDiagnoseOS: cmdlib.LUDiagnoseOS,
212 opcodes.OpQueryExports: cmdlib.LUQueryExports,
213 opcodes.OpExportInstance: cmdlib.LUExportInstance,
214 opcodes.OpRemoveExport: cmdlib.LURemoveExport,
216 opcodes.OpGetTags: cmdlib.LUGetTags,
217 opcodes.OpSearchTags: cmdlib.LUSearchTags,
218 opcodes.OpAddTags: cmdlib.LUAddTags,
219 opcodes.OpDelTags: cmdlib.LUDelTags,
221 opcodes.OpTestDelay: cmdlib.LUTestDelay,
222 opcodes.OpTestAllocator: cmdlib.LUTestAllocator,
225 def __init__(self, context):
226 """Constructor for Processor
229 self.context = context
231 self.rpc = rpc.RpcRunner(context.cfg)
232 self.hmclass = HooksMaster
234 def _ReportLocks(self, level, names, shared, timeout, acquired, result):
235 """Reports lock operations.
238 @param level: Lock level
239 @type names: list or string
240 @param names: Lock names
242 @param shared: Whether the locks should be acquired in shared mode
243 @type timeout: None or float
244 @param timeout: Timeout for acquiring the locks
246 @param acquired: Whether the locks have already been acquired
247 @type result: None or set
248 @param result: Result from L{locking.GanetiLockManager.acquire}
256 parts.append("timeout")
258 parts.append("acquired")
260 parts.append("waiting")
262 parts.append("blocking")
264 parts.append("timeout=%0.6fs" % timeout)
266 parts.append(locking.LEVEL_NAMES[level])
268 if names == locking.ALL_SET:
270 elif isinstance(names, basestring):
273 parts.append(",".join(names))
276 parts.append("shared")
278 parts.append("exclusive")
280 msg = "/".join(parts)
282 logging.debug("LU locks %s", msg)
285 self._cbs.ReportLocks(msg)
287 def _AcquireLocks(self, level, names, shared, timeout):
288 """Acquires locks via the Ganeti lock manager.
291 @param level: Lock level
292 @type names: list or string
293 @param names: Lock names
295 @param shared: Whether the locks should be acquired in shared mode
296 @type timeout: None or float
297 @param timeout: Timeout for acquiring the locks
300 self._ReportLocks(level, names, shared, timeout, False, None)
302 acquired = self.context.glm.acquire(level, names, shared=shared,
305 self._ReportLocks(level, names, shared, timeout, True, acquired)
309 def _ExecLU(self, lu):
310 """Logical Unit execution sequence.
313 write_count = self.context.cfg.write_count
315 hm = HooksMaster(self.rpc.call_hooks_runner, lu)
316 h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
317 lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
318 self._Feedback, None)
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 result = lu.Exec(self._Feedback)
330 h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
331 result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
332 self._Feedback, result)
334 # FIXME: This needs locks if not lu_class.REQ_BGL
335 if write_count != self.context.cfg.write_count:
340 def _LockAndExecLU(self, lu, level, calc_timeout):
341 """Execute a Logical Unit, with the needed locks.
343 This is a recursive function that starts locking the given level, and
344 proceeds up, till there are no more locks to acquire. Then it executes the
345 given LU and its opcodes.
348 adding_locks = level in lu.add_locks
349 acquiring_locks = level in lu.needed_locks
350 if level not in locking.LEVELS:
352 self._cbs.NotifyStart()
354 result = self._ExecLU(lu)
356 elif adding_locks and acquiring_locks:
357 # We could both acquire and add locks at the same level, but for now we
358 # don't need this, so we'll avoid the complicated code needed.
359 raise NotImplementedError("Can't declare locks to acquire when adding"
362 elif adding_locks or acquiring_locks:
363 lu.DeclareLocks(level)
364 share = lu.share_locks[level]
367 assert adding_locks ^ acquiring_locks, \
368 "Locks must be either added or acquired"
372 needed_locks = lu.needed_locks[level]
374 acquired = self._AcquireLocks(level, needed_locks, share,
378 raise _LockAcquireTimeout()
382 add_locks = lu.add_locks[level]
383 lu.remove_locks[level] = add_locks
386 self.context.glm.add(level, add_locks, acquired=1, shared=share)
387 except errors.LockError:
388 raise errors.OpPrereqError(
389 "Couldn't add locks (%s), probably because of a race condition"
390 " with another job, who added them first" % add_locks,
396 lu.acquired_locks[level] = acquired
398 result = self._LockAndExecLU(lu, level + 1, calc_timeout)
400 if level in lu.remove_locks:
401 self.context.glm.remove(level, lu.remove_locks[level])
403 if self.context.glm.is_owned(level):
404 self.context.glm.release(level)
407 result = self._LockAndExecLU(lu, level + 1, calc_timeout)
411 def ExecOpCode(self, op, cbs):
412 """Execute an opcode.
414 @type op: an OpCode instance
415 @param op: the opcode to be executed
416 @type cbs: L{OpExecCbBase}
417 @param cbs: Runtime callbacks
420 if not isinstance(op, opcodes.OpCode):
421 raise errors.ProgrammerError("Non-opcode instance passed"
426 lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
428 raise errors.OpCodeUnknown("Unknown opcode")
430 timeout_strategy = _LockAttemptTimeoutStrategy()
434 acquire_timeout = timeout_strategy.CalcRemainingTimeout()
436 # Acquire the Big Ganeti Lock exclusively if this LU requires it,
437 # and in a shared fashion otherwise (to prevent concurrent run with
439 if self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL,
440 not lu_class.REQ_BGL, acquire_timeout) is None:
441 raise _LockAcquireTimeout()
444 lu = lu_class(self, op, self.context, self.rpc)
446 assert lu.needed_locks is not None, "needed_locks not set by LU"
448 return self._LockAndExecLU(lu, locking.LEVEL_INSTANCE,
449 timeout_strategy.CalcRemainingTimeout)
451 self.context.glm.release(locking.LEVEL_CLUSTER)
453 except _LockAcquireTimeout:
454 # Timeout while waiting for lock, try again
457 timeout_strategy = timeout_strategy.NextAttempt()
462 def _Feedback(self, *args):
463 """Forward call to feedback callback function.
467 self._cbs.Feedback(*args)
469 def LogStep(self, current, total, message):
470 """Log a change in LU execution progress.
473 logging.debug("Step %d/%d %s", current, total, message)
474 self._Feedback("STEP %d/%d %s" % (current, total, message))
476 def LogWarning(self, message, *args, **kwargs):
477 """Log a warning to the logs and the user.
479 The optional keyword argument is 'hint' and can be used to show a
480 hint to the user (presumably related to the warning). If the
481 message is empty, it will not be printed at all, allowing one to
485 assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
486 "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
488 message = message % tuple(args)
490 logging.warning(message)
491 self._Feedback(" - WARNING: %s" % message)
493 self._Feedback(" Hint: %s" % kwargs["hint"])
495 def LogInfo(self, message, *args):
496 """Log an informational message to the logs and the user.
500 message = message % tuple(args)
501 logging.info(message)
502 self._Feedback(" - INFO: %s" % message)
505 class HooksMaster(object):
508 This class distributes the run commands to the nodes based on the
511 In order to remove the direct dependency on the rpc module, the
512 constructor needs a function which actually does the remote
513 call. This will usually be rpc.call_hooks_runner, but any function
514 which behaves the same works.
517 def __init__(self, callfn, lu):
521 self.env, node_list_pre, node_list_post = self._BuildEnv()
522 self.node_list = {constants.HOOKS_PHASE_PRE: node_list_pre,
523 constants.HOOKS_PHASE_POST: node_list_post}
526 """Compute the environment and the target nodes.
528 Based on the opcode and the current node list, this builds the
529 environment for the hooks and the target node list for the run.
533 "PATH": "/sbin:/bin:/usr/sbin:/usr/bin",
534 "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
535 "GANETI_OP_CODE": self.op.OP_ID,
536 "GANETI_OBJECT_TYPE": self.lu.HTYPE,
537 "GANETI_DATA_DIR": constants.DATA_DIR,
540 if self.lu.HPATH is not None:
541 lu_env, lu_nodes_pre, lu_nodes_post = self.lu.BuildHooksEnv()
544 env["GANETI_" + key] = lu_env[key]
546 lu_nodes_pre = lu_nodes_post = []
548 return env, frozenset(lu_nodes_pre), frozenset(lu_nodes_post)
550 def _RunWrapper(self, node_list, hpath, phase):
551 """Simple wrapper over self.callfn.
553 This method fixes the environment before doing the rpc call.
556 env = self.env.copy()
557 env["GANETI_HOOKS_PHASE"] = phase
558 env["GANETI_HOOKS_PATH"] = hpath
559 if self.lu.cfg is not None:
560 env["GANETI_CLUSTER"] = self.lu.cfg.GetClusterName()
561 env["GANETI_MASTER"] = self.lu.cfg.GetMasterNode()
563 env = dict([(str(key), str(val)) for key, val in env.iteritems()])
565 return self.callfn(node_list, hpath, phase, env)
567 def RunPhase(self, phase, nodes=None):
568 """Run all the scripts for a phase.
570 This is the main function of the HookMaster.
572 @param phase: one of L{constants.HOOKS_PHASE_POST} or
573 L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
574 @param nodes: overrides the predefined list of nodes for the given phase
575 @return: the processed results of the hooks multi-node rpc call
576 @raise errors.HooksFailure: on communication failure to the nodes
577 @raise errors.HooksAbort: on failure of one of the hooks
580 if not self.node_list[phase] and not nodes:
581 # empty node list, we should not attempt to run this as either
582 # we're in the cluster init phase and the rpc client part can't
583 # even attempt to run, or this LU doesn't do hooks at all
585 hpath = self.lu.HPATH
586 if nodes is not None:
587 results = self._RunWrapper(nodes, hpath, phase)
589 results = self._RunWrapper(self.node_list[phase], hpath, phase)
592 msg = "Communication Failure"
593 if phase == constants.HOOKS_PHASE_PRE:
594 raise errors.HooksFailure(msg)
596 self.lu.LogWarning(msg)
598 for node_name in results:
599 res = results[node_name]
604 self.lu.LogWarning("Communication failure to node %s: %s",
607 for script, hkr, output in res.payload:
608 if hkr == constants.HKR_FAIL:
609 if phase == constants.HOOKS_PHASE_PRE:
610 errs.append((node_name, script, output))
613 output = "(no output)"
614 self.lu.LogWarning("On %s script %s failed, output: %s" %
615 (node_name, script, output))
616 if errs and phase == constants.HOOKS_PHASE_PRE:
617 raise errors.HooksAbort(errs)
620 def RunConfigUpdate(self):
621 """Run the special configuration update hook
623 This is a special hook that runs only on the master after each
624 top-level LI if the configuration has been updated.
627 phase = constants.HOOKS_PHASE_POST
628 hpath = constants.HOOKS_NAME_CFGUPDATE
629 nodes = [self.lu.cfg.GetMasterNode()]
630 self._RunWrapper(nodes, hpath, phase)