Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 5af3da74

History | View | Annotate | Download (15.6 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
# cluster opcodes
175

    
176
class OpDestroyCluster(OpCode):
177
  """Destroy the cluster.
178

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

182
  """
183
  OP_ID = "OP_CLUSTER_DESTROY"
184
  __slots__ = []
185

    
186

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

    
192

    
193
class OpVerifyCluster(OpCode):
194
  """Verify the cluster state.
195

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

202
  """
203
  OP_ID = "OP_CLUSTER_VERIFY"
204
  __slots__ = ["skip_checks"]
205

    
206

    
207
class OpVerifyDisks(OpCode):
208
  """Verify the cluster disks.
209

210
  Parameters: none
211

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

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

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

227
  """
228
  OP_ID = "OP_CLUSTER_VERIFY_DISKS"
229
  __slots__ = []
230

    
231

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

    
237

    
238
class OpRenameCluster(OpCode):
239
  """Rename the cluster.
240

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

246
  """
247
  OP_ID = "OP_CLUSTER_RENAME"
248
  OP_DSC_FIELD = "name"
249
  __slots__ = ["name"]
250

    
251

    
252
class OpSetClusterParams(OpCode):
253
  """Change the parameters of the cluster.
254

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

258
  """
259
  OP_ID = "OP_CLUSTER_SET_PARAMS"
260
  __slots__ = [
261
    "vg_name",
262
    "enabled_hypervisors",
263
    "hvparams",
264
    "beparams",
265
    "nicparams",
266
    "candidate_pool_size",
267
    ]
268

    
269

    
270
class OpRedistributeConfig(OpCode):
271
  """Force a full push of the cluster configuration.
272

273
  """
274
  OP_ID = "OP_CLUSTER_REDIST_CONF"
275
  __slots__ = [
276
    ]
277

    
278
# node opcodes
279

    
280
class OpRemoveNode(OpCode):
281
  """Remove a node.
282

283
  @type node_name: C{str}
284
  @ivar node_name: The name of the node to remove. If the node still has
285
                   instances on it, the operation will fail.
286

287
  """
288
  OP_ID = "OP_NODE_REMOVE"
289
  OP_DSC_FIELD = "node_name"
290
  __slots__ = ["node_name"]
291

    
292

    
293
class OpAddNode(OpCode):
294
  """Add a node to the cluster.
295

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

314
  """
315
  OP_ID = "OP_NODE_ADD"
316
  OP_DSC_FIELD = "node_name"
317
  __slots__ = ["node_name", "primary_ip", "secondary_ip", "readd"]
318

    
319

    
320
class OpQueryNodes(OpCode):
321
  """Compute the list of nodes."""
322
  OP_ID = "OP_NODE_QUERY"
323
  __slots__ = ["output_fields", "names", "use_locking"]
324

    
325

    
326
class OpQueryNodeVolumes(OpCode):
327
  """Get list of volumes on node."""
328
  OP_ID = "OP_NODE_QUERYVOLS"
329
  __slots__ = ["nodes", "output_fields"]
330

    
331

    
332
class OpSetNodeParams(OpCode):
333
  """Change the parameters of a node."""
334
  OP_ID = "OP_NODE_SET_PARAMS"
335
  OP_DSC_FIELD = "node_name"
336
  __slots__ = [
337
    "node_name",
338
    "force",
339
    "master_candidate",
340
    "offline",
341
    "drained",
342
    ]
343

    
344

    
345
class OpPowercycleNode(OpCode):
346
  """Tries to powercycle a node."""
347
  OP_ID = "OP_NODE_POWERCYCLE"
348
  OP_DSC_FIELD = "node_name"
349
  __slots__ = [
350
    "node_name",
351
    "force",
352
    ]
353

    
354
# instance opcodes
355

    
356
class OpCreateInstance(OpCode):
357
  """Create an instance."""
358
  OP_ID = "OP_INSTANCE_CREATE"
359
  OP_DSC_FIELD = "instance_name"
360
  __slots__ = [
361
    "instance_name", "os_type", "pnode",
362
    "disk_template", "snode", "mode",
363
    "disks", "nics",
364
    "src_node", "src_path", "start",
365
    "wait_for_sync", "ip_check",
366
    "file_storage_dir", "file_driver",
367
    "iallocator",
368
    "hypervisor", "hvparams", "beparams",
369
    ]
370

    
371

    
372
class OpReinstallInstance(OpCode):
373
  """Reinstall an instance's OS."""
374
  OP_ID = "OP_INSTANCE_REINSTALL"
375
  OP_DSC_FIELD = "instance_name"
376
  __slots__ = ["instance_name", "os_type"]
377

    
378

    
379
class OpRemoveInstance(OpCode):
380
  """Remove an instance."""
381
  OP_ID = "OP_INSTANCE_REMOVE"
382
  OP_DSC_FIELD = "instance_name"
383
  __slots__ = ["instance_name", "ignore_failures"]
384

    
385

    
386
class OpRenameInstance(OpCode):
387
  """Rename an instance."""
388
  OP_ID = "OP_INSTANCE_RENAME"
389
  __slots__ = ["instance_name", "ignore_ip", "new_name"]
390

    
391

    
392
class OpStartupInstance(OpCode):
393
  """Startup an instance."""
394
  OP_ID = "OP_INSTANCE_STARTUP"
395
  OP_DSC_FIELD = "instance_name"
396
  __slots__ = ["instance_name", "force", "hvparams", "beparams"]
397

    
398

    
399
class OpShutdownInstance(OpCode):
400
  """Shutdown an instance."""
401
  OP_ID = "OP_INSTANCE_SHUTDOWN"
402
  OP_DSC_FIELD = "instance_name"
403
  __slots__ = ["instance_name"]
404

    
405

    
406
class OpRebootInstance(OpCode):
407
  """Reboot an instance."""
408
  OP_ID = "OP_INSTANCE_REBOOT"
409
  OP_DSC_FIELD = "instance_name"
410
  __slots__ = ["instance_name", "reboot_type", "ignore_secondaries" ]
411

    
412

    
413
class OpReplaceDisks(OpCode):
414
  """Replace the disks of an instance."""
415
  OP_ID = "OP_INSTANCE_REPLACE_DISKS"
416
  OP_DSC_FIELD = "instance_name"
417
  __slots__ = ["instance_name", "remote_node", "mode", "disks", "iallocator"]
418

    
419

    
420
class OpFailoverInstance(OpCode):
421
  """Failover an instance."""
422
  OP_ID = "OP_INSTANCE_FAILOVER"
423
  OP_DSC_FIELD = "instance_name"
424
  __slots__ = ["instance_name", "ignore_consistency"]
425

    
426

    
427
class OpMigrateInstance(OpCode):
428
  """Migrate an instance.
429

430
  This migrates (without shutting down an instance) to its secondary
431
  node.
432

433
  @ivar instance_name: the name of the instance
434

435
  """
436
  OP_ID = "OP_INSTANCE_MIGRATE"
437
  OP_DSC_FIELD = "instance_name"
438
  __slots__ = ["instance_name", "live", "cleanup"]
439

    
440

    
441
class OpConnectConsole(OpCode):
442
  """Connect to an instance's console."""
443
  OP_ID = "OP_INSTANCE_CONSOLE"
444
  OP_DSC_FIELD = "instance_name"
445
  __slots__ = ["instance_name"]
446

    
447

    
448
class OpActivateInstanceDisks(OpCode):
449
  """Activate an instance's disks."""
450
  OP_ID = "OP_INSTANCE_ACTIVATE_DISKS"
451
  OP_DSC_FIELD = "instance_name"
452
  __slots__ = ["instance_name"]
453

    
454

    
455
class OpDeactivateInstanceDisks(OpCode):
456
  """Deactivate an instance's disks."""
457
  OP_ID = "OP_INSTANCE_DEACTIVATE_DISKS"
458
  OP_DSC_FIELD = "instance_name"
459
  __slots__ = ["instance_name"]
460

    
461

    
462
class OpQueryInstances(OpCode):
463
  """Compute the list of instances."""
464
  OP_ID = "OP_INSTANCE_QUERY"
465
  __slots__ = ["output_fields", "names", "use_locking"]
466

    
467

    
468
class OpQueryInstanceData(OpCode):
469
  """Compute the run-time status of instances."""
470
  OP_ID = "OP_INSTANCE_QUERY_DATA"
471
  __slots__ = ["instances", "static"]
472

    
473

    
474
class OpSetInstanceParams(OpCode):
475
  """Change the parameters of an instance."""
476
  OP_ID = "OP_INSTANCE_SET_PARAMS"
477
  OP_DSC_FIELD = "instance_name"
478
  __slots__ = [
479
    "instance_name",
480
    "hvparams", "beparams", "force",
481
    "nics", "disks",
482
    ]
483

    
484

    
485
class OpGrowDisk(OpCode):
486
  """Grow a disk of an instance."""
487
  OP_ID = "OP_INSTANCE_GROW_DISK"
488
  OP_DSC_FIELD = "instance_name"
489
  __slots__ = ["instance_name", "disk", "amount", "wait_for_sync"]
490

    
491

    
492
# OS opcodes
493
class OpDiagnoseOS(OpCode):
494
  """Compute the list of guest operating systems."""
495
  OP_ID = "OP_OS_DIAGNOSE"
496
  __slots__ = ["output_fields", "names"]
497

    
498

    
499
# Exports opcodes
500
class OpQueryExports(OpCode):
501
  """Compute the list of exported images."""
502
  OP_ID = "OP_BACKUP_QUERY"
503
  __slots__ = ["nodes", "use_locking"]
504

    
505

    
506
class OpExportInstance(OpCode):
507
  """Export an instance."""
508
  OP_ID = "OP_BACKUP_EXPORT"
509
  OP_DSC_FIELD = "instance_name"
510
  __slots__ = ["instance_name", "target_node", "shutdown"]
511

    
512

    
513
class OpRemoveExport(OpCode):
514
  """Remove an instance's export."""
515
  OP_ID = "OP_BACKUP_REMOVE"
516
  OP_DSC_FIELD = "instance_name"
517
  __slots__ = ["instance_name"]
518

    
519

    
520
# Tags opcodes
521
class OpGetTags(OpCode):
522
  """Returns the tags of the given object."""
523
  OP_ID = "OP_TAGS_GET"
524
  OP_DSC_FIELD = "name"
525
  __slots__ = ["kind", "name"]
526

    
527

    
528
class OpSearchTags(OpCode):
529
  """Searches the tags in the cluster for a given pattern."""
530
  OP_ID = "OP_TAGS_SEARCH"
531
  OP_DSC_FIELD = "pattern"
532
  __slots__ = ["pattern"]
533

    
534

    
535
class OpAddTags(OpCode):
536
  """Add a list of tags on a given object."""
537
  OP_ID = "OP_TAGS_SET"
538
  __slots__ = ["kind", "name", "tags"]
539

    
540

    
541
class OpDelTags(OpCode):
542
  """Remove a list of tags from a given object."""
543
  OP_ID = "OP_TAGS_DEL"
544
  __slots__ = ["kind", "name", "tags"]
545

    
546

    
547
# Test opcodes
548
class OpTestDelay(OpCode):
549
  """Sleeps for a configured amount of time.
550

551
  This is used just for debugging and testing.
552

553
  Parameters:
554
    - duration: the time to sleep
555
    - on_master: if true, sleep on the master
556
    - on_nodes: list of nodes in which to sleep
557

558
  If the on_master parameter is true, it will execute a sleep on the
559
  master (before any node sleep).
560

561
  If the on_nodes list is not empty, it will sleep on those nodes
562
  (after the sleep on the master, if that is enabled).
563

564
  As an additional feature, the case of duration < 0 will be reported
565
  as an execution error, so this opcode can be used as a failure
566
  generator. The case of duration == 0 will not be treated specially.
567

568
  """
569
  OP_ID = "OP_TEST_DELAY"
570
  OP_DSC_FIELD = "duration"
571
  __slots__ = ["duration", "on_master", "on_nodes"]
572

    
573

    
574
class OpTestAllocator(OpCode):
575
  """Allocator framework testing.
576

577
  This opcode has two modes:
578
    - gather and return allocator input for a given mode (allocate new
579
      or replace secondary) and a given instance definition (direction
580
      'in')
581
    - run a selected allocator for a given operation (as above) and
582
      return the allocator output (direction 'out')
583

584
  """
585
  OP_ID = "OP_TEST_ALLOCATOR"
586
  OP_DSC_FIELD = "allocator"
587
  __slots__ = [
588
    "direction", "mode", "allocator", "name",
589
    "mem_size", "disks", "disk_template",
590
    "os", "tags", "nics", "vcpus", "hypervisor",
591
    ]