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
232 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
237 self._cbs.CheckCancel()
239 acquired = self.context.glm.acquire(level, names, shared=shared,
240 timeout=timeout, priority=priority)
243 raise LockAcquireTimeout()
247 def _ExecLU(self, lu):
248 """Logical Unit execution sequence.
251 write_count = self.context.cfg.write_count
253 hm = HooksMaster(self.rpc.call_hooks_runner, lu)
254 h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
255 lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
258 if getattr(lu.op, "dry_run", False):
259 # in this mode, no post-hooks are run, and the config is not
260 # written (as it might have been modified by another LU, and we
261 # shouldn't do writeout on behalf of other threads
262 self.LogInfo("dry-run mode requested, not actually executing"
264 return lu.dry_run_result
267 result = lu.Exec(self.Log)
268 h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
269 result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
272 # FIXME: This needs locks if not lu_class.REQ_BGL
273 if write_count != self.context.cfg.write_count:
278 def _LockAndExecLU(self, lu, level, calc_timeout, priority):
279 """Execute a Logical Unit, with the needed locks.
281 This is a recursive function that starts locking the given level, and
282 proceeds up, till there are no more locks to acquire. Then it executes the
283 given LU and its opcodes.
286 adding_locks = level in lu.add_locks
287 acquiring_locks = level in lu.needed_locks
288 if level not in locking.LEVELS:
290 self._cbs.NotifyStart()
292 result = self._ExecLU(lu)
294 elif adding_locks and acquiring_locks:
295 # We could both acquire and add locks at the same level, but for now we
296 # don't need this, so we'll avoid the complicated code needed.
297 raise NotImplementedError("Can't declare locks to acquire when adding"
300 elif adding_locks or acquiring_locks:
301 lu.DeclareLocks(level)
302 share = lu.share_locks[level]
305 assert adding_locks ^ acquiring_locks, \
306 "Locks must be either added or acquired"
310 needed_locks = lu.needed_locks[level]
312 acquired = self._AcquireLocks(level, needed_locks, share,
313 calc_timeout(), priority)
316 add_locks = lu.add_locks[level]
317 lu.remove_locks[level] = add_locks
320 self.context.glm.add(level, add_locks, acquired=1, shared=share)
321 except errors.LockError:
322 raise errors.OpPrereqError(
323 "Couldn't add locks (%s), probably because of a race condition"
324 " with another job, who added them first" % add_locks,
330 lu.acquired_locks[level] = acquired
332 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
334 if level in lu.remove_locks:
335 self.context.glm.remove(level, lu.remove_locks[level])
337 if self.context.glm.is_owned(level):
338 self.context.glm.release(level)
341 result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
345 def ExecOpCode(self, op, cbs, timeout=None, priority=None):
346 """Execute an opcode.
348 @type op: an OpCode instance
349 @param op: the opcode to be executed
350 @type cbs: L{OpExecCbBase}
351 @param cbs: Runtime callbacks
352 @type timeout: float or None
353 @param timeout: Maximum time to acquire all locks, None for no timeout
354 @type priority: number or None
355 @param priority: Priority for acquiring lock(s)
356 @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
360 if not isinstance(op, opcodes.OpCode):
361 raise errors.ProgrammerError("Non-opcode instance passed"
364 lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
366 raise errors.OpCodeUnknown("Unknown opcode")
369 calc_timeout = lambda: None
371 calc_timeout = locking.RunningTimeout(timeout, False).Remaining
375 # Acquire the Big Ganeti Lock exclusively if this LU requires it,
376 # and in a shared fashion otherwise (to prevent concurrent run with
378 self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL,
379 not lu_class.REQ_BGL, calc_timeout(),
382 lu = lu_class(self, op, self.context, self.rpc)
384 assert lu.needed_locks is not None, "needed_locks not set by LU"
387 return self._LockAndExecLU(lu, locking.LEVEL_INSTANCE, calc_timeout,
391 self.context.cfg.DropECReservations(self._ec_id)
393 self.context.glm.release(locking.LEVEL_CLUSTER)
397 def Log(self, *args):
398 """Forward call to feedback callback function.
402 self._cbs.Feedback(*args)
404 def LogStep(self, current, total, message):
405 """Log a change in LU execution progress.
408 logging.debug("Step %d/%d %s", current, total, message)
409 self.Log("STEP %d/%d %s" % (current, total, message))
411 def LogWarning(self, message, *args, **kwargs):
412 """Log a warning to the logs and the user.
414 The optional keyword argument is 'hint' and can be used to show a
415 hint to the user (presumably related to the warning). If the
416 message is empty, it will not be printed at all, allowing one to
420 assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
421 "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
423 message = message % tuple(args)
425 logging.warning(message)
426 self.Log(" - WARNING: %s" % message)
428 self.Log(" Hint: %s" % kwargs["hint"])
430 def LogInfo(self, message, *args):
431 """Log an informational message to the logs and the user.
435 message = message % tuple(args)
436 logging.info(message)
437 self.Log(" - INFO: %s" % message)
441 errors.ProgrammerError("Tried to use execution context id when not set")
445 class HooksMaster(object):
448 This class distributes the run commands to the nodes based on the
451 In order to remove the direct dependency on the rpc module, the
452 constructor needs a function which actually does the remote
453 call. This will usually be rpc.call_hooks_runner, but any function
454 which behaves the same works.
457 def __init__(self, callfn, lu):
461 self.env, node_list_pre, node_list_post = self._BuildEnv()
462 self.node_list = {constants.HOOKS_PHASE_PRE: node_list_pre,
463 constants.HOOKS_PHASE_POST: node_list_post}
466 """Compute the environment and the target nodes.
468 Based on the opcode and the current node list, this builds the
469 environment for the hooks and the target node list for the run.
473 "PATH": "/sbin:/bin:/usr/sbin:/usr/bin",
474 "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
475 "GANETI_OP_CODE": self.op.OP_ID,
476 "GANETI_OBJECT_TYPE": self.lu.HTYPE,
477 "GANETI_DATA_DIR": constants.DATA_DIR,
480 if self.lu.HPATH is not None:
481 lu_env, lu_nodes_pre, lu_nodes_post = self.lu.BuildHooksEnv()
484 env["GANETI_" + key] = lu_env[key]
486 lu_nodes_pre = lu_nodes_post = []
488 return env, frozenset(lu_nodes_pre), frozenset(lu_nodes_post)
490 def _RunWrapper(self, node_list, hpath, phase):
491 """Simple wrapper over self.callfn.
493 This method fixes the environment before doing the rpc call.
496 env = self.env.copy()
497 env["GANETI_HOOKS_PHASE"] = phase
498 env["GANETI_HOOKS_PATH"] = hpath
499 if self.lu.cfg is not None:
500 env["GANETI_CLUSTER"] = self.lu.cfg.GetClusterName()
501 env["GANETI_MASTER"] = self.lu.cfg.GetMasterNode()
503 env = dict([(str(key), str(val)) for key, val in env.iteritems()])
505 return self.callfn(node_list, hpath, phase, env)
507 def RunPhase(self, phase, nodes=None):
508 """Run all the scripts for a phase.
510 This is the main function of the HookMaster.
512 @param phase: one of L{constants.HOOKS_PHASE_POST} or
513 L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
514 @param nodes: overrides the predefined list of nodes for the given phase
515 @return: the processed results of the hooks multi-node rpc call
516 @raise errors.HooksFailure: on communication failure to the nodes
517 @raise errors.HooksAbort: on failure of one of the hooks
520 if not self.node_list[phase] and not nodes:
521 # empty node list, we should not attempt to run this as either
522 # we're in the cluster init phase and the rpc client part can't
523 # even attempt to run, or this LU doesn't do hooks at all
525 hpath = self.lu.HPATH
526 if nodes is not None:
527 results = self._RunWrapper(nodes, hpath, phase)
529 results = self._RunWrapper(self.node_list[phase], hpath, phase)
532 msg = "Communication Failure"
533 if phase == constants.HOOKS_PHASE_PRE:
534 raise errors.HooksFailure(msg)
536 self.lu.LogWarning(msg)
538 for node_name in results:
539 res = results[node_name]
544 self.lu.LogWarning("Communication failure to node %s: %s",
547 for script, hkr, output in res.payload:
548 if hkr == constants.HKR_FAIL:
549 if phase == constants.HOOKS_PHASE_PRE:
550 errs.append((node_name, script, output))
553 output = "(no output)"
554 self.lu.LogWarning("On %s script %s failed, output: %s" %
555 (node_name, script, output))
556 if errs and phase == constants.HOOKS_PHASE_PRE:
557 raise errors.HooksAbort(errs)
560 def RunConfigUpdate(self):
561 """Run the special configuration update hook
563 This is a special hook that runs only on the master after each
564 top-level LI if the configuration has been updated.
567 phase = constants.HOOKS_PHASE_POST
568 hpath = constants.HOOKS_NAME_CFGUPDATE
569 nodes = [self.lu.cfg.GetMasterNode()]
570 self._RunWrapper(nodes, hpath, phase)