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
33 from ganeti import opcodes
34 from ganeti import constants
35 from ganeti import errors
36 from ganeti import rpc
37 from ganeti import cmdlib
38 from ganeti import locking
41 class Processor(object):
42 """Object which runs OpCodes"""
45 opcodes.OpDestroyCluster: cmdlib.LUDestroyCluster,
46 opcodes.OpQueryClusterInfo: cmdlib.LUQueryClusterInfo,
47 opcodes.OpVerifyCluster: cmdlib.LUVerifyCluster,
48 opcodes.OpQueryConfigValues: cmdlib.LUQueryConfigValues,
49 opcodes.OpRenameCluster: cmdlib.LURenameCluster,
50 opcodes.OpVerifyDisks: cmdlib.LUVerifyDisks,
51 opcodes.OpSetClusterParams: cmdlib.LUSetClusterParams,
52 opcodes.OpRedistributeConfig: cmdlib.LURedistributeConfig,
54 opcodes.OpAddNode: cmdlib.LUAddNode,
55 opcodes.OpQueryNodes: cmdlib.LUQueryNodes,
56 opcodes.OpQueryNodeVolumes: cmdlib.LUQueryNodeVolumes,
57 opcodes.OpRemoveNode: cmdlib.LURemoveNode,
58 opcodes.OpSetNodeParams: cmdlib.LUSetNodeParams,
59 opcodes.OpPowercycleNode: cmdlib.LUPowercycleNode,
61 opcodes.OpCreateInstance: cmdlib.LUCreateInstance,
62 opcodes.OpReinstallInstance: cmdlib.LUReinstallInstance,
63 opcodes.OpRemoveInstance: cmdlib.LURemoveInstance,
64 opcodes.OpRenameInstance: cmdlib.LURenameInstance,
65 opcodes.OpActivateInstanceDisks: cmdlib.LUActivateInstanceDisks,
66 opcodes.OpShutdownInstance: cmdlib.LUShutdownInstance,
67 opcodes.OpStartupInstance: cmdlib.LUStartupInstance,
68 opcodes.OpRebootInstance: cmdlib.LURebootInstance,
69 opcodes.OpDeactivateInstanceDisks: cmdlib.LUDeactivateInstanceDisks,
70 opcodes.OpReplaceDisks: cmdlib.LUReplaceDisks,
71 opcodes.OpFailoverInstance: cmdlib.LUFailoverInstance,
72 opcodes.OpMigrateInstance: cmdlib.LUMigrateInstance,
73 opcodes.OpConnectConsole: cmdlib.LUConnectConsole,
74 opcodes.OpQueryInstances: cmdlib.LUQueryInstances,
75 opcodes.OpQueryInstanceData: cmdlib.LUQueryInstanceData,
76 opcodes.OpSetInstanceParams: cmdlib.LUSetInstanceParams,
77 opcodes.OpGrowDisk: cmdlib.LUGrowDisk,
79 opcodes.OpDiagnoseOS: cmdlib.LUDiagnoseOS,
81 opcodes.OpQueryExports: cmdlib.LUQueryExports,
82 opcodes.OpExportInstance: cmdlib.LUExportInstance,
83 opcodes.OpRemoveExport: cmdlib.LURemoveExport,
85 opcodes.OpGetTags: cmdlib.LUGetTags,
86 opcodes.OpSearchTags: cmdlib.LUSearchTags,
87 opcodes.OpAddTags: cmdlib.LUAddTags,
88 opcodes.OpDelTags: cmdlib.LUDelTags,
90 opcodes.OpTestDelay: cmdlib.LUTestDelay,
91 opcodes.OpTestAllocator: cmdlib.LUTestAllocator,
94 def __init__(self, context):
95 """Constructor for Processor
98 - feedback_fn: the feedback function (taking one string) to be run when
99 interesting events are happening
101 self.context = context
102 self._feedback_fn = None
103 self.exclusive_BGL = False
104 self.rpc = rpc.RpcRunner(context.cfg)
106 def _ExecLU(self, lu):
107 """Logical Unit execution sequence.
110 write_count = self.context.cfg.write_count
112 hm = HooksMaster(self.rpc.call_hooks_runner, self, lu)
113 h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
114 lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
115 self._feedback_fn, None)
117 if getattr(lu.op, "dry_run", False):
118 # in this mode, no post-hooks are run, and the config is not
119 # written (as it might have been modified by another LU, and we
120 # shouldn't do writeout on behalf of other threads
121 self.LogInfo("dry-run mode requested, not actually executing"
123 return lu.dry_run_result
126 result = lu.Exec(self._feedback_fn)
127 h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
128 result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
129 self._feedback_fn, result)
131 # FIXME: This needs locks if not lu_class.REQ_BGL
132 if write_count != self.context.cfg.write_count:
137 def _LockAndExecLU(self, lu, level):
138 """Execute a Logical Unit, with the needed locks.
140 This is a recursive function that starts locking the given level, and
141 proceeds up, till there are no more locks to acquire. Then it executes the
142 given LU and its opcodes.
145 adding_locks = level in lu.add_locks
146 acquiring_locks = level in lu.needed_locks
147 if level not in locking.LEVELS:
148 if callable(self._run_notifier):
150 result = self._ExecLU(lu)
151 elif adding_locks and acquiring_locks:
152 # We could both acquire and add locks at the same level, but for now we
153 # don't need this, so we'll avoid the complicated code needed.
154 raise NotImplementedError(
155 "Can't declare locks to acquire when adding others")
156 elif adding_locks or acquiring_locks:
157 lu.DeclareLocks(level)
158 share = lu.share_locks[level]
160 needed_locks = lu.needed_locks[level]
161 lu.acquired_locks[level] = self.context.glm.acquire(level,
165 add_locks = lu.add_locks[level]
166 lu.remove_locks[level] = add_locks
168 self.context.glm.add(level, add_locks, acquired=1, shared=share)
169 except errors.LockError:
170 raise errors.OpPrereqError(
171 "Couldn't add locks (%s), probably because of a race condition"
172 " with another job, who added them first" % add_locks)
176 lu.acquired_locks[level] = add_locks
177 result = self._LockAndExecLU(lu, level + 1)
179 if level in lu.remove_locks:
180 self.context.glm.remove(level, lu.remove_locks[level])
182 if self.context.glm.is_owned(level):
183 self.context.glm.release(level)
185 result = self._LockAndExecLU(lu, level + 1)
189 def ExecOpCode(self, op, feedback_fn, run_notifier):
190 """Execute an opcode.
192 @type op: an OpCode instance
193 @param op: the opcode to be executed
194 @type feedback_fn: a function that takes a single argument
195 @param feedback_fn: this function will be used as feedback from the LU
197 @type run_notifier: callable (no arguments) or None
198 @param run_notifier: this function (if callable) will be called when
199 we are about to call the lu's Exec() method, that
200 is, after we have acquired all locks
203 if not isinstance(op, opcodes.OpCode):
204 raise errors.ProgrammerError("Non-opcode instance passed"
207 self._feedback_fn = feedback_fn
208 self._run_notifier = run_notifier
209 lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
211 raise errors.OpCodeUnknown("Unknown opcode")
213 # Acquire the Big Ganeti Lock exclusively if this LU requires it, and in a
214 # shared fashion otherwise (to prevent concurrent run with an exclusive LU.
215 self.context.glm.acquire(locking.LEVEL_CLUSTER, [locking.BGL],
216 shared=not lu_class.REQ_BGL)
218 self.exclusive_BGL = lu_class.REQ_BGL
219 lu = lu_class(self, op, self.context, self.rpc)
221 assert lu.needed_locks is not None, "needed_locks not set by LU"
222 result = self._LockAndExecLU(lu, locking.LEVEL_INSTANCE)
224 self.context.glm.release(locking.LEVEL_CLUSTER)
225 self.exclusive_BGL = False
229 def LogStep(self, current, total, message):
230 """Log a change in LU execution progress.
233 logging.debug("Step %d/%d %s", current, total, message)
234 self._feedback_fn("STEP %d/%d %s" % (current, total, message))
236 def LogWarning(self, message, *args, **kwargs):
237 """Log a warning to the logs and the user.
239 The optional keyword argument is 'hint' and can be used to show a
240 hint to the user (presumably related to the warning). If the
241 message is empty, it will not be printed at all, allowing one to
245 assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
246 "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
248 message = message % tuple(args)
250 logging.warning(message)
251 self._feedback_fn(" - WARNING: %s" % message)
253 self._feedback_fn(" Hint: %s" % kwargs["hint"])
255 def LogInfo(self, message, *args):
256 """Log an informational message to the logs and the user.
260 message = message % tuple(args)
261 logging.info(message)
262 self._feedback_fn(" - INFO: %s" % message)
265 class HooksMaster(object):
268 This class distributes the run commands to the nodes based on the
271 In order to remove the direct dependency on the rpc module, the
272 constructor needs a function which actually does the remote
273 call. This will usually be rpc.call_hooks_runner, but any function
274 which behaves the same works.
277 def __init__(self, callfn, proc, lu):
282 self.env, node_list_pre, node_list_post = self._BuildEnv()
283 self.node_list = {constants.HOOKS_PHASE_PRE: node_list_pre,
284 constants.HOOKS_PHASE_POST: node_list_post}
287 """Compute the environment and the target nodes.
289 Based on the opcode and the current node list, this builds the
290 environment for the hooks and the target node list for the run.
294 "PATH": "/sbin:/bin:/usr/sbin:/usr/bin",
295 "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
296 "GANETI_OP_CODE": self.op.OP_ID,
297 "GANETI_OBJECT_TYPE": self.lu.HTYPE,
298 "GANETI_DATA_DIR": constants.DATA_DIR,
301 if self.lu.HPATH is not None:
302 lu_env, lu_nodes_pre, lu_nodes_post = self.lu.BuildHooksEnv()
305 env["GANETI_" + key] = lu_env[key]
307 lu_nodes_pre = lu_nodes_post = []
309 return env, frozenset(lu_nodes_pre), frozenset(lu_nodes_post)
311 def _RunWrapper(self, node_list, hpath, phase):
312 """Simple wrapper over self.callfn.
314 This method fixes the environment before doing the rpc call.
317 env = self.env.copy()
318 env["GANETI_HOOKS_PHASE"] = phase
319 env["GANETI_HOOKS_PATH"] = hpath
320 if self.lu.cfg is not None:
321 env["GANETI_CLUSTER"] = self.lu.cfg.GetClusterName()
322 env["GANETI_MASTER"] = self.lu.cfg.GetMasterNode()
324 env = dict([(str(key), str(val)) for key, val in env.iteritems()])
326 return self.callfn(node_list, hpath, phase, env)
328 def RunPhase(self, phase):
329 """Run all the scripts for a phase.
331 This is the main function of the HookMaster.
333 @param phase: one of L{constants.HOOKS_PHASE_POST} or
334 L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
335 @return: the processed results of the hooks multi-node rpc call
336 @raise errors.HooksFailure: on communication failure to the nodes
339 if not self.node_list[phase]:
340 # empty node list, we should not attempt to run this as either
341 # we're in the cluster init phase and the rpc client part can't
342 # even attempt to run, or this LU doesn't do hooks at all
344 hpath = self.lu.HPATH
345 results = self._RunWrapper(self.node_list[phase], hpath, phase)
346 if phase == constants.HOOKS_PHASE_PRE:
349 raise errors.HooksFailure("Communication failure")
350 for node_name in results:
351 res = results[node_name]
354 msg = res.RemoteFailMsg()
356 self.proc.LogWarning("Communication failure to node %s: %s",
359 for script, hkr, output in res.payload:
360 if hkr == constants.HKR_FAIL:
361 errs.append((node_name, script, output))
363 raise errors.HooksAbort(errs)
366 def RunConfigUpdate(self):
367 """Run the special configuration update hook
369 This is a special hook that runs only on the master after each
370 top-level LI if the configuration has been updated.
373 phase = constants.HOOKS_PHASE_POST
374 hpath = constants.HOOKS_NAME_CFGUPDATE
375 nodes = [self.lu.cfg.GetMasterNode()]
376 self._RunWrapper(nodes, hpath, phase)