Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 5661b908

History | View | Annotate | Download (14.9 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
"""OpCodes module
23

24
This module implements the data structures which define the cluster
25
operations - the so-called opcodes.
26

27
Every operation which modifies the cluster state is expressed via
28
opcodes.
29

30
"""
31

    
32
# this are practically structures, so disable the message about too
33
# few public methods:
34
# pylint: disable-msg=R0903
35

    
36

    
37
class BaseOpCode(object):
38
  """A simple serializable object.
39

40
  This object serves as a parent class for OpCode without any custom
41
  field handling.
42

43
  """
44
  __slots__ = []
45

    
46
  def __init__(self, **kwargs):
47
    """Constructor for BaseOpCode.
48

49
    The constructor takes only keyword arguments and will set
50
    attributes on this object based on the passed arguments. As such,
51
    it means that you should not pass arguments which are not in the
52
    __slots__ attribute for this class.
53

54
    """
55
    for key in kwargs:
56
      if key not in self.__slots__:
57
        raise TypeError("Object %s doesn't support the parameter '%s'" %
58
                        (self.__class__.__name__, key))
59
      setattr(self, key, kwargs[key])
60

    
61
  def __getstate__(self):
62
    """Generic serializer.
63

64
    This method just returns the contents of the instance as a
65
    dictionary.
66

67
    @rtype:  C{dict}
68
    @return: the instance attributes and their values
69

70
    """
71
    state = {}
72
    for name in self.__slots__:
73
      if hasattr(self, name):
74
        state[name] = getattr(self, name)
75
    return state
76

    
77
  def __setstate__(self, state):
78
    """Generic unserializer.
79

80
    This method just restores from the serialized state the attributes
81
    of the current instance.
82

83
    @param state: the serialized opcode data
84
    @type state:  C{dict}
85

86
    """
87
    if not isinstance(state, dict):
88
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
89
                       type(state))
90

    
91
    for name in self.__slots__:
92
      if name not in state:
93
        delattr(self, name)
94

    
95
    for name in state:
96
      setattr(self, name, state[name])
97

    
98

    
99
class OpCode(BaseOpCode):
100
  """Abstract OpCode.
101

102
  This is the root of the actual OpCode hierarchy. All clases derived
103
  from this class should override OP_ID.
104

105
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
106
               childre of this class.
107

108
  """
109
  OP_ID = "OP_ABSTRACT"
110
  __slots__ = []
111

    
112
  def __getstate__(self):
113
    """Specialized getstate for opcodes.
114

115
    This method adds to the state dictionary the OP_ID of the class,
116
    so that on unload we can identify the correct class for
117
    instantiating the opcode.
118

119
    @rtype:   C{dict}
120
    @return:  the state as a dictionary
121

122
    """
123
    data = BaseOpCode.__getstate__(self)
124
    data["OP_ID"] = self.OP_ID
125
    return data
126

    
127
  @classmethod
128
  def LoadOpCode(cls, data):
129
    """Generic load opcode method.
130

131
    The method identifies the correct opcode class from the dict-form
132
    by looking for a OP_ID key, if this is not found, or its value is
133
    not available in this module as a child of this class, we fail.
134

135
    @type data:  C{dict}
136
    @param data: the serialized opcode
137

138
    """
139
    if not isinstance(data, dict):
140
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
141
    if "OP_ID" not in data:
142
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
143
    op_id = data["OP_ID"]
144
    op_class = None
145
    for item in globals().values():
146
      if (isinstance(item, type) and
147
          issubclass(item, cls) and
148
          hasattr(item, "OP_ID") and
149
          getattr(item, "OP_ID") == op_id):
150
        op_class = item
151
        break
152
    if op_class is None:
153
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
154
                       op_id)
155
    op = op_class()
156
    new_data = data.copy()
157
    del new_data["OP_ID"]
158
    op.__setstate__(new_data)
159
    return op
160

    
161
  def Summary(self):
162
    """Generates a summary description of this opcode.
163

164
    """
165
    # all OP_ID start with OP_, we remove that
166
    txt = self.OP_ID[3:]
167
    field_name = getattr(self, "OP_DSC_FIELD", None)
168
    if field_name:
169
      field_value = getattr(self, field_name, None)
170
      txt = "%s(%s)" % (txt, field_value)
171
    return txt
172

    
173

    
174
class OpDestroyCluster(OpCode):
175
  """Destroy the cluster.
176

177
  This opcode has no other parameters. All the state is irreversibly
178
  lost after the execution of this opcode.
179

180
  """
181
  OP_ID = "OP_CLUSTER_DESTROY"
182
  __slots__ = []
183

    
184

    
185
class OpQueryClusterInfo(OpCode):
186
  """Query cluster information."""
187
  OP_ID = "OP_CLUSTER_QUERY"
188
  __slots__ = []
189

    
190

    
191
class OpVerifyCluster(OpCode):
192
  """Verify the cluster state.
193

194
  @type skip_checks: C{list}
195
  @ivar skip_checks: steps to be skipped from the verify process; this
196
                     needs to be a subset of
197
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
198
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
199

200
  """
201
  OP_ID = "OP_CLUSTER_VERIFY"
202
  __slots__ = ["skip_checks"]
203

    
204

    
205
class OpVerifyDisks(OpCode):
206
  """Verify the cluster disks.
207

208
  Parameters: none
209

210
  Result: a tuple of four elements:
211
    - list of node names with bad data returned (unreachable, etc.)
212
    - dict of node names with broken volume groups (values: error msg)
213
    - list of instances with degraded disks (that should be activated)
214
    - dict of instances with missing logical volumes (values: (node, vol)
215
      pairs with details about the missing volumes)
216

217
  In normal operation, all lists should be empty. A non-empty instance
218
  list (3rd element of the result) is still ok (errors were fixed) but
219
  non-empty node list means some node is down, and probably there are
220
  unfixable drbd errors.
221

222
  Note that only instances that are drbd-based are taken into
223
  consideration. This might need to be revisited in the future.
224

225
  """
226
  OP_ID = "OP_CLUSTER_VERIFY_DISKS"
227
  __slots__ = []
228

    
229

    
230
class OpQueryConfigValues(OpCode):
231
  """Query cluster configuration values."""
232
  OP_ID = "OP_CLUSTER_CONFIG_QUERY"
233
  __slots__ = ["output_fields"]
234

    
235

    
236
class OpRenameCluster(OpCode):
237
  """Rename the cluster.
238

239
  @type name: C{str}
240
  @ivar name: The new name of the cluster. The name and/or the master IP
241
              address will be changed to match the new name and its IP
242
              address.
243

244
  """
245
  OP_ID = "OP_CLUSTER_RENAME"
246
  OP_DSC_FIELD = "name"
247
  __slots__ = ["name"]
248

    
249

    
250
class OpSetClusterParams(OpCode):
251
  """Change the parameters of the cluster.
252

253
  @type vg_name: C{str} or C{None}
254
  @ivar vg_name: The new volume group name or None to disable LVM usage.
255

256
  """
257
  OP_ID = "OP_CLUSTER_SET_PARAMS"
258
  __slots__ = [
259
    "vg_name",
260
    "enabled_hypervisors",
261
    "hvparams",
262
    "beparams",
263
    "candidate_pool_size",
264
    ]
265

    
266

    
267
# node opcodes
268

    
269
class OpRemoveNode(OpCode):
270
  """Remove a node.
271

272
  @type node_name: C{str}
273
  @ivar node_name: The name of the node to remove. If the node still has
274
                   instances on it, the operation will fail.
275

276
  """
277
  OP_ID = "OP_NODE_REMOVE"
278
  OP_DSC_FIELD = "node_name"
279
  __slots__ = ["node_name"]
280

    
281

    
282
class OpAddNode(OpCode):
283
  """Add a node to the cluster.
284

285
  @type node_name: C{str}
286
  @ivar node_name: The name of the node to add. This can be a short name,
287
                   but it will be expanded to the FQDN.
288
  @type primary_ip: IP address
289
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
290
                    opcode is submitted, but will be filled during the node
291
                    add (so it will be visible in the job query).
292
  @type secondary_ip: IP address
293
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
294
                      if the cluster has been initialized in 'dual-network'
295
                      mode, otherwise it must not be given.
296
  @type readd: C{bool}
297
  @ivar readd: Whether to re-add an existing node to the cluster. If
298
               this is not passed, then the operation will abort if the node
299
               name is already in the cluster; use this parameter to 'repair'
300
               a node that had its configuration broken, or was reinstalled
301
               without removal from the cluster.
302

303
  """
304
  OP_ID = "OP_NODE_ADD"
305
  OP_DSC_FIELD = "node_name"
306
  __slots__ = ["node_name", "primary_ip", "secondary_ip", "readd"]
307

    
308

    
309
class OpQueryNodes(OpCode):
310
  """Compute the list of nodes."""
311
  OP_ID = "OP_NODE_QUERY"
312
  __slots__ = ["output_fields", "names"]
313

    
314

    
315
class OpQueryNodeVolumes(OpCode):
316
  """Get list of volumes on node."""
317
  OP_ID = "OP_NODE_QUERYVOLS"
318
  __slots__ = ["nodes", "output_fields"]
319

    
320

    
321
class OpSetNodeParams(OpCode):
322
  """Change the parameters of a node."""
323
  OP_ID = "OP_NODE_SET_PARAMS"
324
  OP_DSC_FIELD = "node_name"
325
  __slots__ = [
326
    "node_name",
327
    "force",
328
    "master_candidate",
329
    "offline",
330
    ]
331

    
332
# instance opcodes
333

    
334
class OpCreateInstance(OpCode):
335
  """Create an instance."""
336
  OP_ID = "OP_INSTANCE_CREATE"
337
  OP_DSC_FIELD = "instance_name"
338
  __slots__ = [
339
    "instance_name", "os_type", "pnode",
340
    "disk_template", "snode", "mode",
341
    "disks", "nics",
342
    "src_node", "src_path", "start",
343
    "wait_for_sync", "ip_check",
344
    "file_storage_dir", "file_driver",
345
    "iallocator",
346
    "hypervisor", "hvparams", "beparams",
347
    ]
348

    
349

    
350
class OpReinstallInstance(OpCode):
351
  """Reinstall an instance's OS."""
352
  OP_ID = "OP_INSTANCE_REINSTALL"
353
  OP_DSC_FIELD = "instance_name"
354
  __slots__ = ["instance_name", "os_type"]
355

    
356

    
357
class OpRemoveInstance(OpCode):
358
  """Remove an instance."""
359
  OP_ID = "OP_INSTANCE_REMOVE"
360
  OP_DSC_FIELD = "instance_name"
361
  __slots__ = ["instance_name", "ignore_failures"]
362

    
363

    
364
class OpRenameInstance(OpCode):
365
  """Rename an instance."""
366
  OP_ID = "OP_INSTANCE_RENAME"
367
  __slots__ = ["instance_name", "ignore_ip", "new_name"]
368

    
369

    
370
class OpStartupInstance(OpCode):
371
  """Startup an instance."""
372
  OP_ID = "OP_INSTANCE_STARTUP"
373
  OP_DSC_FIELD = "instance_name"
374
  __slots__ = ["instance_name", "force", "extra_args"]
375

    
376

    
377
class OpShutdownInstance(OpCode):
378
  """Shutdown an instance."""
379
  OP_ID = "OP_INSTANCE_SHUTDOWN"
380
  OP_DSC_FIELD = "instance_name"
381
  __slots__ = ["instance_name"]
382

    
383

    
384
class OpRebootInstance(OpCode):
385
  """Reboot an instance."""
386
  OP_ID = "OP_INSTANCE_REBOOT"
387
  OP_DSC_FIELD = "instance_name"
388
  __slots__ = ["instance_name", "reboot_type", "extra_args",
389
               "ignore_secondaries" ]
390

    
391

    
392
class OpReplaceDisks(OpCode):
393
  """Replace the disks of an instance."""
394
  OP_ID = "OP_INSTANCE_REPLACE_DISKS"
395
  OP_DSC_FIELD = "instance_name"
396
  __slots__ = ["instance_name", "remote_node", "mode", "disks", "iallocator"]
397

    
398

    
399
class OpFailoverInstance(OpCode):
400
  """Failover an instance."""
401
  OP_ID = "OP_INSTANCE_FAILOVER"
402
  OP_DSC_FIELD = "instance_name"
403
  __slots__ = ["instance_name", "ignore_consistency"]
404

    
405

    
406
class OpConnectConsole(OpCode):
407
  """Connect to an instance's console."""
408
  OP_ID = "OP_INSTANCE_CONSOLE"
409
  OP_DSC_FIELD = "instance_name"
410
  __slots__ = ["instance_name"]
411

    
412

    
413
class OpActivateInstanceDisks(OpCode):
414
  """Activate an instance's disks."""
415
  OP_ID = "OP_INSTANCE_ACTIVATE_DISKS"
416
  OP_DSC_FIELD = "instance_name"
417
  __slots__ = ["instance_name"]
418

    
419

    
420
class OpDeactivateInstanceDisks(OpCode):
421
  """Deactivate an instance's disks."""
422
  OP_ID = "OP_INSTANCE_DEACTIVATE_DISKS"
423
  OP_DSC_FIELD = "instance_name"
424
  __slots__ = ["instance_name"]
425

    
426

    
427
class OpQueryInstances(OpCode):
428
  """Compute the list of instances."""
429
  OP_ID = "OP_INSTANCE_QUERY"
430
  __slots__ = ["output_fields", "names"]
431

    
432

    
433
class OpQueryInstanceData(OpCode):
434
  """Compute the run-time status of instances."""
435
  OP_ID = "OP_INSTANCE_QUERY_DATA"
436
  __slots__ = ["instances", "static"]
437

    
438

    
439
class OpSetInstanceParams(OpCode):
440
  """Change the parameters of an instance."""
441
  OP_ID = "OP_INSTANCE_SET_PARAMS"
442
  OP_DSC_FIELD = "instance_name"
443
  __slots__ = [
444
    "instance_name",
445
    "hvparams", "beparams", "force",
446
    "nics", "disks",
447
    ]
448

    
449

    
450
class OpGrowDisk(OpCode):
451
  """Grow a disk of an instance."""
452
  OP_ID = "OP_INSTANCE_GROW_DISK"
453
  OP_DSC_FIELD = "instance_name"
454
  __slots__ = ["instance_name", "disk", "amount", "wait_for_sync"]
455

    
456

    
457
# OS opcodes
458
class OpDiagnoseOS(OpCode):
459
  """Compute the list of guest operating systems."""
460
  OP_ID = "OP_OS_DIAGNOSE"
461
  __slots__ = ["output_fields", "names"]
462

    
463

    
464
# Exports opcodes
465
class OpQueryExports(OpCode):
466
  """Compute the list of exported images."""
467
  OP_ID = "OP_BACKUP_QUERY"
468
  __slots__ = ["nodes"]
469

    
470

    
471
class OpExportInstance(OpCode):
472
  """Export an instance."""
473
  OP_ID = "OP_BACKUP_EXPORT"
474
  OP_DSC_FIELD = "instance_name"
475
  __slots__ = ["instance_name", "target_node", "shutdown"]
476

    
477

    
478
class OpRemoveExport(OpCode):
479
  """Remove an instance's export."""
480
  OP_ID = "OP_BACKUP_REMOVE"
481
  OP_DSC_FIELD = "instance_name"
482
  __slots__ = ["instance_name"]
483

    
484

    
485
# Tags opcodes
486
class OpGetTags(OpCode):
487
  """Returns the tags of the given object."""
488
  OP_ID = "OP_TAGS_GET"
489
  OP_DSC_FIELD = "name"
490
  __slots__ = ["kind", "name"]
491

    
492

    
493
class OpSearchTags(OpCode):
494
  """Searches the tags in the cluster for a given pattern."""
495
  OP_ID = "OP_TAGS_SEARCH"
496
  OP_DSC_FIELD = "pattern"
497
  __slots__ = ["pattern"]
498

    
499

    
500
class OpAddTags(OpCode):
501
  """Add a list of tags on a given object."""
502
  OP_ID = "OP_TAGS_SET"
503
  __slots__ = ["kind", "name", "tags"]
504

    
505

    
506
class OpDelTags(OpCode):
507
  """Remove a list of tags from a given object."""
508
  OP_ID = "OP_TAGS_DEL"
509
  __slots__ = ["kind", "name", "tags"]
510

    
511

    
512
# Test opcodes
513
class OpTestDelay(OpCode):
514
  """Sleeps for a configured amount of time.
515

516
  This is used just for debugging and testing.
517

518
  Parameters:
519
    - duration: the time to sleep
520
    - on_master: if true, sleep on the master
521
    - on_nodes: list of nodes in which to sleep
522

523
  If the on_master parameter is true, it will execute a sleep on the
524
  master (before any node sleep).
525

526
  If the on_nodes list is not empty, it will sleep on those nodes
527
  (after the sleep on the master, if that is enabled).
528

529
  As an additional feature, the case of duration < 0 will be reported
530
  as an execution error, so this opcode can be used as a failure
531
  generator. The case of duration == 0 will not be treated specially.
532

533
  """
534
  OP_ID = "OP_TEST_DELAY"
535
  OP_DSC_FIELD = "duration"
536
  __slots__ = ["duration", "on_master", "on_nodes"]
537

    
538

    
539
class OpTestAllocator(OpCode):
540
  """Allocator framework testing.
541

542
  This opcode has two modes:
543
    - gather and return allocator input for a given mode (allocate new
544
      or replace secondary) and a given instance definition (direction
545
      'in')
546
    - run a selected allocator for a given operation (as above) and
547
      return the allocator output (direction 'out')
548

549
  """
550
  OP_ID = "OP_TEST_ALLOCATOR"
551
  OP_DSC_FIELD = "allocator"
552
  __slots__ = [
553
    "direction", "mode", "allocator", "name",
554
    "mem_size", "disks", "disk_template",
555
    "os", "tags", "nics", "vcpus", "hypervisor",
556
    ]