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 """Exception to report timeouts on acquiring locks.
49 def _CalculateLockAttemptTimeouts():
50 """Calculate timeouts for lock attempts.
55 # Wait for a total of at least 150s before doing a blocking acquire
56 while sum(result) < 150.0:
57 timeout = (result[-1] * 1.05) ** 1.25
59 # Cap timeout at 10 seconds. This gives other jobs a chance to run
60 # even if we're still trying to get our locks, before finally moving
61 # to a blocking acquire.
66 # Lower boundary for safety
69 result.append(timeout)
74 class LockAttemptTimeoutStrategy(object):
75 """Class with lock acquire timeout strategy.
84 _TIMEOUT_PER_ATTEMPT = _CalculateLockAttemptTimeouts()
86 def __init__(self, _time_fn=time.time, _random_fn=random.random):
87 """Initializes this class.
89 @param _time_fn: Time function for unittests
90 @param _random_fn: Random number generator for unittests
95 self._timeouts = iter(self._TIMEOUT_PER_ATTEMPT)
96 self._time_fn = _time_fn
97 self._random_fn = _random_fn
99 def NextAttempt(self):
100 """Returns the timeout for the next attempt.
104 timeout = self._timeouts.next()
105 except StopIteration:
106 # No more timeouts, do blocking acquire
109 if timeout is not None:
110 # Add a small variation (-/+ 5%) to timeout. This helps in situations
111 # where two or more jobs are fighting for the same lock(s).
112 variation_range = timeout * 0.1
113 timeout += ((self._random_fn() * variation_range) -
114 (variation_range * 0.5))
119 class OpExecCbBase: # pylint: disable-msg=W0232
120 """Base class for OpCode execution callbacks.
123 def NotifyStart(self):
124 """Called when we are about to execute the LU.
126 This function is called when we're about to start the lu's Exec() method,
127 that is, after we have acquired all locks.
131 def Feedback(self, *args):
132 """Sends feedback from the LU code to the end-user.
136 def CheckCancel(self):
137 """Check whether job has been cancelled.
142 class Processor(object):
143 """Object which runs OpCodes"""
146 opcodes.OpPostInitCluster: cmdlib.LUPostInitCluster,
147 opcodes.OpDestroyCluster: cmdlib.LUDestroyCluster,
148 opcodes.OpQueryClusterInfo: cmdlib.LUQueryClusterInfo,
149 opcodes.OpVerifyCluster: cmdlib.LUVerifyCluster,
150 opcodes.OpQueryConfigValues: cmdlib.LUQueryConfigValues,
151 opcodes.OpRenameCluster: cmdlib.LURenameCluster,
152 opcodes.OpVerifyDisks: cmdlib.LUVerifyDisks,
153 opcodes.OpSetClusterParams: cmdlib.LUSetClusterParams,
154 opcodes.OpRedistributeConfig: cmdlib.LURedistributeConfig,
155 opcodes.OpRepairDiskSizes: cmdlib.LURepairDiskSizes,
157 opcodes.OpAddNode: cmdlib.LUAddNode,
158 opcodes.OpQueryNodes: cmdlib.LUQueryNodes,
159 opcodes.OpQueryNodeVolumes: cmdlib.LUQueryNodeVolumes,
160 opcodes.OpQueryNodeStorage: cmdlib.LUQueryNodeStorage,
161 opcodes.OpModifyNodeStorage: cmdlib.LUModifyNodeStorage,
162 opcodes.OpRepairNodeStorage: cmdlib.LURepairNodeStorage,
163 opcodes.OpRemoveNode: cmdlib.LURemoveNode,
164 opcodes.OpSetNodeParams: cmdlib.LUSetNodeParams,
165 opcodes.OpPowercycleNode: cmdlib.LUPowercycleNode,
166 opcodes.OpMigrateNode: cmdlib.LUMigrateNode,
167 opcodes.OpNodeEvacuationStrategy: cmdlib.LUNodeEvacuationStrategy,
169 opcodes.OpCreateInstance: cmdlib.LUCreateInstance,
170 opcodes.OpReinstallInstance: cmdlib.LUReinstallInstance,
171 opcodes.OpRemoveInstance: cmdlib.LURemoveInstance,
172 opcodes.OpRenameInstance: cmdlib.LURenameInstance,
173 opcodes.OpActivateInstanceDisks: cmdlib.LUActivateInstanceDisks,
174 opcodes.OpShutdownInstance: cmdlib.LUShutdownInstance,
175 opcodes.OpStartupInstance: cmdlib.LUStartupInstance,
176 opcodes.OpRebootInstance: cmdlib.LURebootInstance,
177 opcodes.OpDeactivateInstanceDisks: cmdlib.LUDeactivateInstanceDisks,
178 opcodes.OpReplaceDisks: cmdlib.LUReplaceDisks,
179 opcodes.OpRecreateInstanceDisks: cmdlib.LURecreateInstanceDisks,
180 opcodes.OpFailoverInstance: cmdlib.LUFailoverInstance,
181 opcodes.OpMigrateInstance: cmdlib.LUMigrateInstance,
182 opcodes.OpMoveInstance: cmdlib.LUMoveInstance,
183 opcodes.OpConnectConsole: cmdlib.LUConnectConsole,
184 opcodes.OpQueryInstances: cmdlib.LUQueryInstances,
185 opcodes.OpQueryInstanceData: cmdlib.LUQueryInstanceData,
186 opcodes.OpSetInstanceParams: cmdlib.LUSetInstanceParams,
187 opcodes.OpGrowDisk: cmdlib.LUGrowDisk,
189 opcodes.OpDiagnoseOS: cmdlib.LUDiagnoseOS,
191 opcodes.OpQueryExports: cmdlib.LUQueryExports,
192 opcodes.OpPrepareExport: cmdlib.LUPrepareExport,
193 opcodes.OpExportInstance: cmdlib.LUExportInstance,
194 opcodes.OpRemoveExport: cmdlib.LURemoveExport,
196 opcodes.OpGetTags: cmdlib.LUGetTags,
197 opcodes.OpSearchTags: cmdlib.LUSearchTags,
198 opcodes.OpAddTags: cmdlib.LUAddTags,
199 opcodes.OpDelTags: cmdlib.LUDelTags,
201 opcodes.OpTestDelay: cmdlib.LUTestDelay,
202 opcodes.OpTestAllocator: cmdlib.LUTestAllocator,
203 opcodes.OpTestJobqueue: cmdlib.LUTestJobqueue,
206 def __init__(self, context, ec_id):
207 """Constructor for Processor
209 @type context: GanetiContext
210 @param context: global Ganeti context
212 @param ec_id: execution context identifier
215 self.context = context
218 self.rpc = rpc.RpcRunner(context.cfg)
219 self.hmclass = HooksMaster
221 def _AcquireLocks(self, level, names, shared, timeout, priority):
222 """Acquires locks via the Ganeti lock manager.
225 @param level: Lock level
226 @type names: list or string
227 @param names: Lock names
229 @param shared: Whether the locks should be acquired in shared mode
230 @type timeout: None or float
231 @param timeout: Timeout for acquiring the locks
235 self._cbs.CheckCancel()
237 acquired = self.context.glm.acquire(level, names, shared=shared,
238 timeout=timeout, priority=priority)
242 def _ExecLU(self, lu):
243 """Logical Unit execution sequence.
246 write_count = self.context.cfg.write_count
248 hm = HooksMaster(self.rpc.call_hooks_runner, lu)
249 h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
250 lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
253 if getattr(lu.op, "dry_run", False):
254 # in this mode, no post-hooks are run, and the config is not
255 # written (as it might have been modified by another LU, and we
256 # shouldn't do writeout on behalf of other threads
257 self.LogInfo("dry-run mode requested, not actually executing"
259 return lu.dry_run_result
262 result = lu.Exec(self.Log)
263 h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
264 result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
267 # FIXME: This needs locks if not lu_class.REQ_BGL
268 if write_count != self.context.cfg.write_count:
273 def _LockAndExecLU(self, lu, level, calc_timeout, priority):
274 """Execute a Logical Unit, with the needed locks.
276 This is a recursive function that starts locking the given level, and
277 proceeds up, till there are no more locks to acquire. Then it executes the
278 given LU and its opcodes.
281 adding_locks = level in lu.add_locks
282 acquiring_locks = level in lu.needed_locks
283 if level not in locking.LEVELS:
285 self._cbs.NotifyStart()
287 result = self._ExecLU(lu)
289 elif adding_locks and acquiring_locks:
290 # We could both acquire and add locks at the same level, but for now we
291 # don't need this, so we'll avoid the complicated code needed.
292 raise NotImplementedError("Can't declare locks to acquire when adding"
295 elif adding_locks or acquiring_locks:
296 lu.DeclareLocks(level)
297 share = lu.share_locks[level]
300 assert adding_locks ^ acquiring_locks, \
301 "Locks must be either added or acquired"
305 needed_locks = lu.needed_locks[level]
307 acquired = self._AcquireLocks(level, needed_locks, share,
308 calc_timeout(), priority)
311 raise LockAcquireTimeout()
315 add_locks = lu.add_locks[level]
316 lu.remove_locks[level] = add_locks
319 self.context.glm.add(level, add_locks, acquired=1, shared=share)
320 except errors.LockError:
321 raise errors.OpPrereqError(
322 "Couldn't add locks (%s), probably because of a race condition"
323 " with another job, who added them first" % add_locks,
329 lu.acquired_locks[level] = acquired
331 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
333 if level in lu.remove_locks:
334 self.context.glm.remove(level, lu.remove_locks[level])
336 if self.context.glm.is_owned(level):
337 self.context.glm.release(level)
340 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
344 def ExecOpCode(self, op, cbs, timeout=None, priority=None):
345 """Execute an opcode.
347 @type op: an OpCode instance
348 @param op: the opcode to be executed
349 @type cbs: L{OpExecCbBase}
350 @param cbs: Runtime callbacks
351 @type timeout: float or None
352 @param timeout: Maximum time to acquire all locks, None for no timeout
353 @type priority: number or None
354 @param priority: Priority for acquiring lock(s)
355 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
359 if not isinstance(op, opcodes.OpCode):
360 raise errors.ProgrammerError("Non-opcode instance passed"
363 lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
365 raise errors.OpCodeUnknown("Unknown opcode")
368 calc_timeout = lambda: None
370 calc_timeout = locking.RunningTimeout(timeout, False).Remaining
374 # Acquire the Big Ganeti Lock exclusively if this LU requires it,
375 # and in a shared fashion otherwise (to prevent concurrent run with
377 if self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL,
378 not lu_class.REQ_BGL, calc_timeout(),
380 raise LockAcquireTimeout()
383 lu = lu_class(self, op, self.context, self.rpc)
385 assert lu.needed_locks is not None, "needed_locks not set by LU"
388 return self._LockAndExecLU(lu, locking.LEVEL_INSTANCE, calc_timeout,
392 self.context.cfg.DropECReservations(self._ec_id)
394 self.context.glm.release(locking.LEVEL_CLUSTER)
398 def Log(self, *args):
399 """Forward call to feedback callback function.
403 self._cbs.Feedback(*args)
405 def LogStep(self, current, total, message):
406 """Log a change in LU execution progress.
409 logging.debug("Step %d/%d %s", current, total, message)
410 self.Log("STEP %d/%d %s" % (current, total, message))
412 def LogWarning(self, message, *args, **kwargs):
413 """Log a warning to the logs and the user.
415 The optional keyword argument is 'hint' and can be used to show a
416 hint to the user (presumably related to the warning). If the
417 message is empty, it will not be printed at all, allowing one to
421 assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
422 "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
424 message = message % tuple(args)
426 logging.warning(message)
427 self.Log(" - WARNING: %s" % message)
429 self.Log(" Hint: %s" % kwargs["hint"])
431 def LogInfo(self, message, *args):
432 """Log an informational message to the logs and the user.
436 message = message % tuple(args)
437 logging.info(message)
438 self.Log(" - INFO: %s" % message)
442 errors.ProgrammerError("Tried to use execution context id when not set")
446 class HooksMaster(object):
449 This class distributes the run commands to the nodes based on the
452 In order to remove the direct dependency on the rpc module, the
453 constructor needs a function which actually does the remote
454 call. This will usually be rpc.call_hooks_runner, but any function
455 which behaves the same works.
458 def __init__(self, callfn, lu):
462 self.env, node_list_pre, node_list_post = self._BuildEnv()
463 self.node_list = {constants.HOOKS_PHASE_PRE: node_list_pre,
464 constants.HOOKS_PHASE_POST: node_list_post}
467 """Compute the environment and the target nodes.
469 Based on the opcode and the current node list, this builds the
470 environment for the hooks and the target node list for the run.
474 "PATH": "/sbin:/bin:/usr/sbin:/usr/bin",
475 "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
476 "GANETI_OP_CODE": self.op.OP_ID,
477 "GANETI_OBJECT_TYPE": self.lu.HTYPE,
478 "GANETI_DATA_DIR": constants.DATA_DIR,
481 if self.lu.HPATH is not None:
482 lu_env, lu_nodes_pre, lu_nodes_post = self.lu.BuildHooksEnv()
485 env["GANETI_" + key] = lu_env[key]
487 lu_nodes_pre = lu_nodes_post = []
489 return env, frozenset(lu_nodes_pre), frozenset(lu_nodes_post)
491 def _RunWrapper(self, node_list, hpath, phase):
492 """Simple wrapper over self.callfn.
494 This method fixes the environment before doing the rpc call.
497 env = self.env.copy()
498 env["GANETI_HOOKS_PHASE"] = phase
499 env["GANETI_HOOKS_PATH"] = hpath
500 if self.lu.cfg is not None:
501 env["GANETI_CLUSTER"] = self.lu.cfg.GetClusterName()
502 env["GANETI_MASTER"] = self.lu.cfg.GetMasterNode()
504 env = dict([(str(key), str(val)) for key, val in env.iteritems()])
506 return self.callfn(node_list, hpath, phase, env)
508 def RunPhase(self, phase, nodes=None):
509 """Run all the scripts for a phase.
511 This is the main function of the HookMaster.
513 @param phase: one of L{constants.HOOKS_PHASE_POST} or
514 L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
515 @param nodes: overrides the predefined list of nodes for the given phase
516 @return: the processed results of the hooks multi-node rpc call
517 @raise errors.HooksFailure: on communication failure to the nodes
518 @raise errors.HooksAbort: on failure of one of the hooks
521 if not self.node_list[phase] and not nodes:
522 # empty node list, we should not attempt to run this as either
523 # we're in the cluster init phase and the rpc client part can't
524 # even attempt to run, or this LU doesn't do hooks at all
526 hpath = self.lu.HPATH
527 if nodes is not None:
528 results = self._RunWrapper(nodes, hpath, phase)
530 results = self._RunWrapper(self.node_list[phase], hpath, phase)
533 msg = "Communication Failure"
534 if phase == constants.HOOKS_PHASE_PRE:
535 raise errors.HooksFailure(msg)
537 self.lu.LogWarning(msg)
539 for node_name in results:
540 res = results[node_name]
545 self.lu.LogWarning("Communication failure to node %s: %s",
548 for script, hkr, output in res.payload:
549 if hkr == constants.HKR_FAIL:
550 if phase == constants.HOOKS_PHASE_PRE:
551 errs.append((node_name, script, output))
554 output = "(no output)"
555 self.lu.LogWarning("On %s script %s failed, output: %s" %
556 (node_name, script, output))
557 if errs and phase == constants.HOOKS_PHASE_PRE:
558 raise errors.HooksAbort(errs)
561 def RunConfigUpdate(self):
562 """Run the special configuration update hook
564 This is a special hook that runs only on the master after each
565 top-level LI if the configuration has been updated.
568 phase = constants.HOOKS_PHASE_POST
569 hpath = constants.HOOKS_NAME_CFGUPDATE
570 nodes = [self.lu.cfg.GetMasterNode()]
571 self._RunWrapper(nodes, hpath, phase)