Statistics
| Branch: | Tag: | Revision:

root / lib / mcpu.py @ fb8dcb62

History | View | Annotate | Download (12.2 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007 Google Inc.
5
#
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.
10
#
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.
15
#
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
19
# 02110-1301, USA.
20

    
21

    
22
"""Module implementing the logic behind the cluster operations
23

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
28

29
"""
30

    
31

    
32
from ganeti import opcodes
33
from ganeti import constants
34
from ganeti import errors
35
from ganeti import rpc
36
from ganeti import cmdlib
37
from ganeti import config
38
from ganeti import ssconf
39
from ganeti import logger
40
from ganeti import locking
41

    
42

    
43
class Processor(object):
44
  """Object which runs OpCodes"""
45
  DISPATCH_TABLE = {
46
    # Cluster
47
    opcodes.OpDestroyCluster: cmdlib.LUDestroyCluster,
48
    opcodes.OpQueryClusterInfo: cmdlib.LUQueryClusterInfo,
49
    opcodes.OpVerifyCluster: cmdlib.LUVerifyCluster,
50
    opcodes.OpDumpClusterConfig: cmdlib.LUDumpClusterConfig,
51
    opcodes.OpRenameCluster: cmdlib.LURenameCluster,
52
    opcodes.OpVerifyDisks: cmdlib.LUVerifyDisks,
53
    opcodes.OpSetClusterParams: cmdlib.LUSetClusterParams,
54
    # node lu
55
    opcodes.OpAddNode: cmdlib.LUAddNode,
56
    opcodes.OpQueryNodes: cmdlib.LUQueryNodes,
57
    opcodes.OpQueryNodeVolumes: cmdlib.LUQueryNodeVolumes,
58
    opcodes.OpRemoveNode: cmdlib.LURemoveNode,
59
    # instance lu
60
    opcodes.OpCreateInstance: cmdlib.LUCreateInstance,
61
    opcodes.OpReinstallInstance: cmdlib.LUReinstallInstance,
62
    opcodes.OpRemoveInstance: cmdlib.LURemoveInstance,
63
    opcodes.OpRenameInstance: cmdlib.LURenameInstance,
64
    opcodes.OpActivateInstanceDisks: cmdlib.LUActivateInstanceDisks,
65
    opcodes.OpShutdownInstance: cmdlib.LUShutdownInstance,
66
    opcodes.OpStartupInstance: cmdlib.LUStartupInstance,
67
    opcodes.OpRebootInstance: cmdlib.LURebootInstance,
68
    opcodes.OpDeactivateInstanceDisks: cmdlib.LUDeactivateInstanceDisks,
69
    opcodes.OpReplaceDisks: cmdlib.LUReplaceDisks,
70
    opcodes.OpFailoverInstance: cmdlib.LUFailoverInstance,
71
    opcodes.OpConnectConsole: cmdlib.LUConnectConsole,
72
    opcodes.OpQueryInstances: cmdlib.LUQueryInstances,
73
    opcodes.OpQueryInstanceData: cmdlib.LUQueryInstanceData,
74
    opcodes.OpSetInstanceParams: cmdlib.LUSetInstanceParams,
75
    opcodes.OpGrowDisk: cmdlib.LUGrowDisk,
76
    # os lu
77
    opcodes.OpDiagnoseOS: cmdlib.LUDiagnoseOS,
78
    # exports lu
79
    opcodes.OpQueryExports: cmdlib.LUQueryExports,
80
    opcodes.OpExportInstance: cmdlib.LUExportInstance,
81
    opcodes.OpRemoveExport: cmdlib.LURemoveExport,
82
    # tags lu
83
    opcodes.OpGetTags: cmdlib.LUGetTags,
84
    opcodes.OpSearchTags: cmdlib.LUSearchTags,
85
    opcodes.OpAddTags: cmdlib.LUAddTags,
86
    opcodes.OpDelTags: cmdlib.LUDelTags,
87
    # test lu
88
    opcodes.OpTestDelay: cmdlib.LUTestDelay,
89
    opcodes.OpTestAllocator: cmdlib.LUTestAllocator,
90
    }
91

    
92
  def __init__(self, context):
93
    """Constructor for Processor
94

95
    Args:
96
     - feedback_fn: the feedback function (taking one string) to be run when
97
                    interesting events are happening
98
    """
99
    self.context = context
100
    self._feedback_fn = None
101
    self.exclusive_BGL = False
102

    
103
  def _ExecLU(self, lu):
104
    """Logical Unit execution sequence.
105

106
    """
107
    write_count = self.context.cfg.write_count
108
    lu.CheckPrereq()
109
    hm = HooksMaster(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)
113
    try:
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)
118
    finally:
119
      # FIXME: This needs locks if not lu_class.REQ_BGL
120
      if write_count != self.context.cfg.write_count:
121
        hm.RunConfigUpdate()
122

    
123
    return result
124

    
125
  def _LockAndExecLU(self, lu, level):
126
    """Execute a Logical Unit, with the needed locks.
127

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.
131

132
    """
133
    if level in lu.needed_locks:
134
      # This gives a chance to LUs to make last-minute changes after acquiring
135
      # locks at any preceding level.
136
      lu.DeclareLocks(level)
137
      # This is always safe to do, as we can't acquire more/less locks than
138
      # what was requested.
139
      lu.needed_locks[level] = self.context.glm.acquire(level,
140
                                                        lu.needed_locks[level])
141
      try:
142
        result = self._LockAndExecLU(lu, level + 1)
143
      finally:
144
        if lu.needed_locks[level]:
145
          self.context.glm.release(level)
146
    else:
147
      result = self._ExecLU(lu)
148

    
149
    return result
150

    
151
  def ExecOpCode(self, op, feedback_fn):
152
    """Execute an opcode.
153

154
    Args:
155
      op: the opcode to be executed
156

157
    """
158
    if not isinstance(op, opcodes.OpCode):
159
      raise errors.ProgrammerError("Non-opcode instance passed"
160
                                   " to ExecOpcode")
161

    
162
    self._feedback_fn = feedback_fn
163
    lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
164
    if lu_class is None:
165
      raise errors.OpCodeUnknown("Unknown opcode")
166

    
167
    if lu_class.REQ_WSSTORE:
168
      sstore = ssconf.WritableSimpleStore()
169
    else:
170
      sstore = ssconf.SimpleStore()
171

    
172
    # Acquire the Big Ganeti Lock exclusively if this LU requires it, and in a
173
    # shared fashion otherwise (to prevent concurrent run with an exclusive LU.
174
    self.context.glm.acquire(locking.LEVEL_CLUSTER, [locking.BGL],
175
                             shared=not lu_class.REQ_BGL)
176
    try:
177
      self.exclusive_BGL = lu_class.REQ_BGL
178
      lu = lu_class(self, op, self.context, sstore)
179
      lu.ExpandNames()
180
      assert lu.needed_locks is not None, "needed_locks not set by LU"
181
      result = self._LockAndExecLU(lu, locking.LEVEL_INSTANCE)
182
    finally:
183
      self.context.glm.release(locking.LEVEL_CLUSTER)
184
      self.exclusive_BGL = False
185

    
186
    return result
187

    
188
  def ChainOpCode(self, op):
189
    """Chain and execute an opcode.
190

191
    This is used by LUs when they need to execute a child LU.
192

193
    Args:
194
     - opcode: the opcode to be executed
195

196
    """
197
    if not isinstance(op, opcodes.OpCode):
198
      raise errors.ProgrammerError("Non-opcode instance passed"
199
                                   " to ExecOpcode")
200

    
201
    lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
202
    if lu_class is None:
203
      raise errors.OpCodeUnknown("Unknown opcode")
204

    
205
    if lu_class.REQ_BGL and not self.exclusive_BGL:
206
      raise errors.ProgrammerError("LUs which require the BGL cannot"
207
                                   " be chained to granular ones.")
208

    
209
    if lu_class.REQ_WSSTORE:
210
      sstore = ssconf.WritableSimpleStore()
211
    else:
212
      sstore = ssconf.SimpleStore()
213

    
214
    #do_hooks = lu_class.HPATH is not None
215
    lu = lu_class(self, op, self.context, sstore)
216
    lu.CheckPrereq()
217
    #if do_hooks:
218
    #  hm = HooksMaster(rpc.call_hooks_runner, self, lu)
219
    #  h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
220
    #  lu.HooksCallBack(constants.HOOKS_PHASE_PRE,
221
    #                   h_results, self._feedback_fn, None)
222
    result = lu.Exec(self._feedback_fn)
223
    #if do_hooks:
224
    #  h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
225
    #  result = lu.HooksCallBack(constants.HOOKS_PHASE_POST,
226
    #                   h_results, self._feedback_fn, result)
227
    return result
228

    
229
  def LogStep(self, current, total, message):
230
    """Log a change in LU execution progress.
231

232
    """
233
    logger.Debug("Step %d/%d %s" % (current, total, message))
234
    self._feedback_fn("STEP %d/%d %s" % (current, total, message))
235

    
236
  def LogWarning(self, message, hint=None):
237
    """Log a warning to the logs and the user.
238

239
    """
240
    logger.Error(message)
241
    self._feedback_fn(" - WARNING: %s" % message)
242
    if hint:
243
      self._feedback_fn("      Hint: %s" % hint)
244

    
245
  def LogInfo(self, message):
246
    """Log an informational message to the logs and the user.
247

248
    """
249
    logger.Info(message)
250
    self._feedback_fn(" - INFO: %s" % message)
251

    
252

    
253
class HooksMaster(object):
254
  """Hooks master.
255

256
  This class distributes the run commands to the nodes based on the
257
  specific LU class.
258

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.
263

264
  """
265
  def __init__(self, callfn, proc, lu):
266
    self.callfn = callfn
267
    self.proc = proc
268
    self.lu = lu
269
    self.op = lu.op
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}
273

    
274
  def _BuildEnv(self):
275
    """Compute the environment and the target nodes.
276

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.
279

280
    """
281
    env = {
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,
287
      }
288

    
289
    if self.lu.HPATH is not None:
290
      lu_env, lu_nodes_pre, lu_nodes_post = self.lu.BuildHooksEnv()
291
      if lu_env:
292
        for key in lu_env:
293
          env["GANETI_" + key] = lu_env[key]
294
    else:
295
      lu_nodes_pre = lu_nodes_post = []
296

    
297
    return env, frozenset(lu_nodes_pre), frozenset(lu_nodes_post)
298

    
299
  def _RunWrapper(self, node_list, hpath, phase):
300
    """Simple wrapper over self.callfn.
301

302
    This method fixes the environment before doing the rpc call.
303

304
    """
305
    env = self.env.copy()
306
    env["GANETI_HOOKS_PHASE"] = phase
307
    env["GANETI_HOOKS_PATH"] = hpath
308
    if self.lu.sstore is not None:
309
      env["GANETI_CLUSTER"] = self.lu.sstore.GetClusterName()
310
      env["GANETI_MASTER"] = self.lu.sstore.GetMasterNode()
311

    
312
    env = dict([(str(key), str(val)) for key, val in env.iteritems()])
313

    
314
    return self.callfn(node_list, hpath, phase, env)
315

    
316
  def RunPhase(self, phase):
317
    """Run all the scripts for a phase.
318

319
    This is the main function of the HookMaster.
320

321
    Args:
322
      phase: the hooks phase to run
323

324
    Returns:
325
      the result of the hooks multi-node rpc call
326

327
    """
328
    if not self.node_list[phase]:
329
      # empty node list, we should not attempt to run this as either
330
      # we're in the cluster init phase and the rpc client part can't
331
      # even attempt to run, or this LU doesn't do hooks at all
332
      return
333
    hpath = self.lu.HPATH
334
    results = self._RunWrapper(self.node_list[phase], hpath, phase)
335
    if phase == constants.HOOKS_PHASE_PRE:
336
      errs = []
337
      if not results:
338
        raise errors.HooksFailure("Communication failure")
339
      for node_name in results:
340
        res = results[node_name]
341
        if res is False or not isinstance(res, list):
342
          self.proc.LogWarning("Communication failure to node %s" % node_name)
343
          continue
344
        for script, hkr, output in res:
345
          if hkr == constants.HKR_FAIL:
346
            output = output.strip().encode("string_escape")
347
            errs.append((node_name, script, output))
348
      if errs:
349
        raise errors.HooksAbort(errs)
350
    return results
351

    
352
  def RunConfigUpdate(self):
353
    """Run the special configuration update hook
354

355
    This is a special hook that runs only on the master after each
356
    top-level LI if the configuration has been updated.
357

358
    """
359
    phase = constants.HOOKS_PHASE_POST
360
    hpath = constants.HOOKS_NAME_CFGUPDATE
361
    if self.lu.sstore is None:
362
      raise errors.ProgrammerError("Null sstore on config update hook")
363
    nodes = [self.lu.sstore.GetMasterNode()]
364
    results = self._RunWrapper(nodes, hpath, phase)