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,
53 opcodes.OpAddNode: cmdlib.LUAddNode,
54 opcodes.OpQueryNodes: cmdlib.LUQueryNodes,
55 opcodes.OpQueryNodeVolumes: cmdlib.LUQueryNodeVolumes,
56 opcodes.OpRemoveNode: cmdlib.LURemoveNode,
57 opcodes.OpSetNodeParams: cmdlib.LUSetNodeParams,
59 opcodes.OpCreateInstance: cmdlib.LUCreateInstance,
60 opcodes.OpReinstallInstance: cmdlib.LUReinstallInstance,
61 opcodes.OpRemoveInstance: cmdlib.LURemoveInstance,
62 opcodes.OpRenameInstance: cmdlib.LURenameInstance,
63 opcodes.OpActivateInstanceDisks: cmdlib.LUActivateInstanceDisks,
64 opcodes.OpShutdownInstance: cmdlib.LUShutdownInstance,
65 opcodes.OpStartupInstance: cmdlib.LUStartupInstance,
66 opcodes.OpRebootInstance: cmdlib.LURebootInstance,
67 opcodes.OpDeactivateInstanceDisks: cmdlib.LUDeactivateInstanceDisks,
68 opcodes.OpReplaceDisks: cmdlib.LUReplaceDisks,
69 opcodes.OpFailoverInstance: cmdlib.LUFailoverInstance,
70 opcodes.OpConnectConsole: cmdlib.LUConnectConsole,
71 opcodes.OpQueryInstances: cmdlib.LUQueryInstances,
72 opcodes.OpQueryInstanceData: cmdlib.LUQueryInstanceData,
73 opcodes.OpSetInstanceParams: cmdlib.LUSetInstanceParams,
74 opcodes.OpGrowDisk: cmdlib.LUGrowDisk,
76 opcodes.OpDiagnoseOS: cmdlib.LUDiagnoseOS,
78 opcodes.OpQueryExports: cmdlib.LUQueryExports,
79 opcodes.OpExportInstance: cmdlib.LUExportInstance,
80 opcodes.OpRemoveExport: cmdlib.LURemoveExport,
82 opcodes.OpGetTags: cmdlib.LUGetTags,
83 opcodes.OpSearchTags: cmdlib.LUSearchTags,
84 opcodes.OpAddTags: cmdlib.LUAddTags,
85 opcodes.OpDelTags: cmdlib.LUDelTags,
87 opcodes.OpTestDelay: cmdlib.LUTestDelay,
88 opcodes.OpTestAllocator: cmdlib.LUTestAllocator,
91 def __init__(self, context):
92 """Constructor for Processor
95 - feedback_fn: the feedback function (taking one string) to be run when
96 interesting events are happening
98 self.context = context
99 self._feedback_fn = None
100 self.exclusive_BGL = False
101 self.rpc = rpc.RpcRunner(context.cfg)
103 def _ExecLU(self, lu):
104 """Logical Unit execution sequence.
107 write_count = self.context.cfg.write_count
109 hm = HooksMaster(self.rpc.call_hooks_runner, self, lu)
110 h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
111 lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
112 self._feedback_fn, None)
114 result = lu.Exec(self._feedback_fn)
115 h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
116 result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
117 self._feedback_fn, result)
119 # FIXME: This needs locks if not lu_class.REQ_BGL
120 if write_count != self.context.cfg.write_count:
125 def _LockAndExecLU(self, lu, level):
126 """Execute a Logical Unit, with the needed locks.
128 This is a recursive function that starts locking the given level, and
129 proceeds up, till there are no more locks to acquire. Then it executes the
130 given LU and its opcodes.
133 adding_locks = level in lu.add_locks
134 acquiring_locks = level in lu.needed_locks
135 if level not in locking.LEVELS:
136 if callable(self._run_notifier):
138 result = self._ExecLU(lu)
139 elif adding_locks and acquiring_locks:
140 # We could both acquire and add locks at the same level, but for now we
141 # don't need this, so we'll avoid the complicated code needed.
142 raise NotImplementedError(
143 "Can't declare locks to acquire when adding others")
144 elif adding_locks or acquiring_locks:
145 lu.DeclareLocks(level)
146 share = lu.share_locks[level]
148 needed_locks = lu.needed_locks[level]
149 lu.acquired_locks[level] = self.context.glm.acquire(level,
153 add_locks = lu.add_locks[level]
154 lu.remove_locks[level] = add_locks
156 self.context.glm.add(level, add_locks, acquired=1, shared=share)
157 except errors.LockError:
158 raise errors.OpPrereqError(
159 "Coudn't add locks (%s), probably because of a race condition"
160 " with another job, who added them first" % add_locks)
164 lu.acquired_locks[level] = add_locks
165 result = self._LockAndExecLU(lu, level + 1)
167 if level in lu.remove_locks:
168 self.context.glm.remove(level, lu.remove_locks[level])
170 if self.context.glm.is_owned(level):
171 self.context.glm.release(level)
173 result = self._LockAndExecLU(lu, level + 1)
177 def ExecOpCode(self, op, feedback_fn, run_notifier):
178 """Execute an opcode.
180 @type op: an OpCode instance
181 @param op: the opcode to be executed
182 @type feedback_fn: a function that takes a single argument
183 @param feedback_fn: this function will be used as feedback from the LU
185 @type run_notifier: callable (no arguments) or None
186 @param run_notifier: this function (if callable) will be called when
187 we are about to call the lu's Exec() method, that
188 is, after we have aquired all locks
191 if not isinstance(op, opcodes.OpCode):
192 raise errors.ProgrammerError("Non-opcode instance passed"
195 self._feedback_fn = feedback_fn
196 self._run_notifier = run_notifier
197 lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
199 raise errors.OpCodeUnknown("Unknown opcode")
201 # Acquire the Big Ganeti Lock exclusively if this LU requires it, and in a
202 # shared fashion otherwise (to prevent concurrent run with an exclusive LU.
203 self.context.glm.acquire(locking.LEVEL_CLUSTER, [locking.BGL],
204 shared=not lu_class.REQ_BGL)
206 self.exclusive_BGL = lu_class.REQ_BGL
207 lu = lu_class(self, op, self.context, self.rpc)
209 assert lu.needed_locks is not None, "needed_locks not set by LU"
210 result = self._LockAndExecLU(lu, locking.LEVEL_INSTANCE)
212 self.context.glm.release(locking.LEVEL_CLUSTER)
213 self.exclusive_BGL = False
217 def LogStep(self, current, total, message):
218 """Log a change in LU execution progress.
221 logging.debug("Step %d/%d %s", current, total, message)
222 self._feedback_fn("STEP %d/%d %s" % (current, total, message))
224 def LogWarning(self, message, *args, **kwargs):
225 """Log a warning to the logs and the user.
227 The optional keyword argument is 'hint' and can be used to show a
228 hint to the user (presumably related to the warning). If the
229 message is empty, it will not be printed at all, allowing one to
233 assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
234 "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
236 message = message % tuple(args)
238 logging.warning(message)
239 self._feedback_fn(" - WARNING: %s" % message)
241 self._feedback_fn(" Hint: %s" % kwargs["hint"])
243 def LogInfo(self, message, *args):
244 """Log an informational message to the logs and the user.
248 message = message % tuple(args)
249 logging.info(message)
250 self._feedback_fn(" - INFO: %s" % message)
253 class HooksMaster(object):
256 This class distributes the run commands to the nodes based on the
259 In order to remove the direct dependency on the rpc module, the
260 constructor needs a function which actually does the remote
261 call. This will usually be rpc.call_hooks_runner, but any function
262 which behaves the same works.
265 def __init__(self, callfn, proc, lu):
270 self.env, node_list_pre, node_list_post = self._BuildEnv()
271 self.node_list = {constants.HOOKS_PHASE_PRE: node_list_pre,
272 constants.HOOKS_PHASE_POST: node_list_post}
275 """Compute the environment and the target nodes.
277 Based on the opcode and the current node list, this builds the
278 environment for the hooks and the target node list for the run.
282 "PATH": "/sbin:/bin:/usr/sbin:/usr/bin",
283 "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
284 "GANETI_OP_CODE": self.op.OP_ID,
285 "GANETI_OBJECT_TYPE": self.lu.HTYPE,
286 "GANETI_DATA_DIR": constants.DATA_DIR,
289 if self.lu.HPATH is not None:
290 lu_env, lu_nodes_pre, lu_nodes_post = self.lu.BuildHooksEnv()
293 env["GANETI_" + key] = lu_env[key]
295 lu_nodes_pre = lu_nodes_post = []
297 return env, frozenset(lu_nodes_pre), frozenset(lu_nodes_post)
299 def _RunWrapper(self, node_list, hpath, phase):
300 """Simple wrapper over self.callfn.
302 This method fixes the environment before doing the rpc call.
305 env = self.env.copy()
306 env["GANETI_HOOKS_PHASE"] = phase
307 env["GANETI_HOOKS_PATH"] = hpath
308 if self.lu.cfg is not None:
309 env["GANETI_CLUSTER"] = self.lu.cfg.GetClusterName()
310 env["GANETI_MASTER"] = self.lu.cfg.GetMasterNode()
312 env = dict([(str(key), str(val)) for key, val in env.iteritems()])
314 return self.callfn(node_list, hpath, phase, env)
316 def RunPhase(self, phase):
317 """Run all the scripts for a phase.
319 This is the main function of the HookMaster.
321 @param phase: one of L{constants.HOOKS_PHASE_POST} or
322 L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
323 @return: the processed results of the hooks multi-node rpc call
324 @raise errors.HooksFailure: on communication failure to the nodes
327 if not self.node_list[phase]:
328 # empty node list, we should not attempt to run this as either
329 # we're in the cluster init phase and the rpc client part can't
330 # even attempt to run, or this LU doesn't do hooks at all
332 hpath = self.lu.HPATH
333 results = self._RunWrapper(self.node_list[phase], hpath, phase)
334 if phase == constants.HOOKS_PHASE_PRE:
337 raise errors.HooksFailure("Communication failure")
338 for node_name in results:
339 res = results[node_name]
340 if res.failed or res.data is False or not isinstance(res.data, list):
341 self.proc.LogWarning("Communication failure to node %s" % node_name)
343 for script, hkr, output in res.data:
344 if hkr == constants.HKR_FAIL:
345 output = output.strip().encode("string_escape")
346 errs.append((node_name, script, output))
348 raise errors.HooksAbort(errs)
351 def RunConfigUpdate(self):
352 """Run the special configuration update hook
354 This is a special hook that runs only on the master after each
355 top-level LI if the configuration has been updated.
358 phase = constants.HOOKS_PHASE_POST
359 hpath = constants.HOOKS_NAME_CFGUPDATE
360 nodes = [self.lu.cfg.GetMasterNode()]
361 results = self._RunWrapper(nodes, hpath, phase)