Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 323f9095

History | View | Annotate | Download (46.6 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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
import logging
37
import re
38
import operator
39

    
40
from ganeti import constants
41
from ganeti import errors
42
from ganeti import ht
43

    
44

    
45
# Common opcode attributes
46

    
47
#: output fields for a query operation
48
_POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
49
                  "Selected output fields")
50

    
51
#: the shutdown timeout
52
_PShutdownTimeout = \
53
  ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
54
   "How long to wait for instance to shut down")
55

    
56
#: the force parameter
57
_PForce = ("force", False, ht.TBool, "Whether to force the operation")
58

    
59
#: a required instance name (for single-instance LUs)
60
_PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString,
61
                  "Instance name")
62

    
63
#: Whether to ignore offline nodes
64
_PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool,
65
                        "Whether to ignore offline nodes")
66

    
67
#: a required node name (for single-node LUs)
68
_PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString, "Node name")
69

    
70
#: a required node group name (for single-group LUs)
71
_PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString, "Group name")
72

    
73
#: Migration type (live/non-live)
74
_PMigrationMode = ("mode", None,
75
                   ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)),
76
                   "Migration mode")
77

    
78
#: Obsolete 'live' migration mode (boolean)
79
_PMigrationLive = ("live", None, ht.TMaybeBool,
80
                   "Legacy setting for live migration, do not use")
81

    
82
#: Tag type
83
_PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES), None)
84

    
85
#: List of tag strings
86
_PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None)
87

    
88
_PForceVariant = ("force_variant", False, ht.TBool,
89
                  "Whether to force an unknown OS variant")
90

    
91
_PWaitForSync = ("wait_for_sync", True, ht.TBool,
92
                 "Whether to wait for the disk to synchronize")
93

    
94
_PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
95
                       "Whether to ignore disk consistency")
96

    
97
_PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
98

    
99
_PUseLocking = ("use_locking", False, ht.TBool,
100
                "Whether to use synchronization")
101

    
102
_PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
103

    
104
_PNodeGroupAllocPolicy = \
105
  ("alloc_policy", None,
106
   ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
107
   "Instance allocation policy")
108

    
109
_PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
110
                     "Default node parameters for group")
111

    
112
_PQueryWhat = ("what", ht.NoDefault, ht.TElemOf(constants.QR_VIA_OP),
113
               "Resource(s) to query for")
114

    
115
_PEarlyRelease = ("early_release", False, ht.TBool,
116
                  "Whether to release locks as soon as possible")
117

    
118
_PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
119

    
120
#: Do not remember instance state changes
121
_PNoRemember = ("no_remember", False, ht.TBool,
122
                "Do not remember the state change")
123

    
124
#: Target node for instance migration/failover
125
_PMigrationTargetNode = ("target_node", None, ht.TMaybeString,
126
                         "Target node for shared-storage instances")
127

    
128
_PStartupPaused = ("startup_paused", False, ht.TBool,
129
                   "Pause instance at startup")
130

    
131

    
132
#: OP_ID conversion regular expression
133
_OPID_RE = re.compile("([a-z])([A-Z])")
134

    
135
#: Utility function for L{OpClusterSetParams}
136
_TestClusterOsList = ht.TOr(ht.TNone,
137
  ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
138
    ht.TMap(ht.WithDesc("GetFirstItem")(operator.itemgetter(0)),
139
            ht.TElemOf(constants.DDMS_VALUES)))))
140

    
141

    
142
# TODO: Generate check from constants.INIC_PARAMS_TYPES
143
#: Utility function for testing NIC definitions
144
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
145
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
146

    
147
_SUMMARY_PREFIX = {
148
  "CLUSTER_": "C_",
149
  "GROUP_": "G_",
150
  "NODE_": "N_",
151
  "INSTANCE_": "I_",
152
  }
153

    
154

    
155
def _NameToId(name):
156
  """Convert an opcode class name to an OP_ID.
157

158
  @type name: string
159
  @param name: the class name, as OpXxxYyy
160
  @rtype: string
161
  @return: the name in the OP_XXXX_YYYY format
162

163
  """
164
  if not name.startswith("Op"):
165
    return None
166
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
167
  # consume any input, and hence we would just have all the elements
168
  # in the list, one by one; but it seems that split doesn't work on
169
  # non-consuming input, hence we have to process the input string a
170
  # bit
171
  name = _OPID_RE.sub(r"\1,\2", name)
172
  elems = name.split(",")
173
  return "_".join(n.upper() for n in elems)
174

    
175

    
176
def RequireFileStorage():
177
  """Checks that file storage is enabled.
178

179
  While it doesn't really fit into this module, L{utils} was deemed too large
180
  of a dependency to be imported for just one or two functions.
181

182
  @raise errors.OpPrereqError: when file storage is disabled
183

184
  """
185
  if not constants.ENABLE_FILE_STORAGE:
186
    raise errors.OpPrereqError("File storage disabled at configure time",
187
                               errors.ECODE_INVAL)
188

    
189

    
190
def RequireSharedFileStorage():
191
  """Checks that shared file storage is enabled.
192

193
  While it doesn't really fit into this module, L{utils} was deemed too large
194
  of a dependency to be imported for just one or two functions.
195

196
  @raise errors.OpPrereqError: when shared file storage is disabled
197

198
  """
199
  if not constants.ENABLE_SHARED_FILE_STORAGE:
200
    raise errors.OpPrereqError("Shared file storage disabled at"
201
                               " configure time", errors.ECODE_INVAL)
202

    
203

    
204
@ht.WithDesc("CheckFileStorage")
205
def _CheckFileStorage(value):
206
  """Ensures file storage is enabled if used.
207

208
  """
209
  if value == constants.DT_FILE:
210
    RequireFileStorage()
211
  elif value == constants.DT_SHARED_FILE:
212
    RequireSharedFileStorage()
213
  return True
214

    
215

    
216
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
217
                             _CheckFileStorage)
218

    
219

    
220
def _CheckStorageType(storage_type):
221
  """Ensure a given storage type is valid.
222

223
  """
224
  if storage_type not in constants.VALID_STORAGE_TYPES:
225
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
226
                               errors.ECODE_INVAL)
227
  if storage_type == constants.ST_FILE:
228
    RequireFileStorage()
229
  return True
230

    
231

    
232
#: Storage type parameter
233
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
234
                 "Storage type")
235

    
236

    
237
class _AutoOpParamSlots(type):
238
  """Meta class for opcode definitions.
239

240
  """
241
  def __new__(mcs, name, bases, attrs):
242
    """Called when a class should be created.
243

244
    @param mcs: The meta class
245
    @param name: Name of created class
246
    @param bases: Base classes
247
    @type attrs: dict
248
    @param attrs: Class attributes
249

250
    """
251
    assert "__slots__" not in attrs, \
252
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
253
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
254

    
255
    attrs["OP_ID"] = _NameToId(name)
256

    
257
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
258
    params = attrs.setdefault("OP_PARAMS", [])
259

    
260
    # Use parameter names as slots
261
    slots = [pname for (pname, _, _, _) in params]
262

    
263
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
264
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
265

    
266
    attrs["__slots__"] = slots
267

    
268
    return type.__new__(mcs, name, bases, attrs)
269

    
270

    
271
class BaseOpCode(object):
272
  """A simple serializable object.
273

274
  This object serves as a parent class for OpCode without any custom
275
  field handling.
276

277
  """
278
  # pylint: disable-msg=E1101
279
  # as OP_ID is dynamically defined
280
  __metaclass__ = _AutoOpParamSlots
281

    
282
  def __init__(self, **kwargs):
283
    """Constructor for BaseOpCode.
284

285
    The constructor takes only keyword arguments and will set
286
    attributes on this object based on the passed arguments. As such,
287
    it means that you should not pass arguments which are not in the
288
    __slots__ attribute for this class.
289

290
    """
291
    slots = self._all_slots()
292
    for key in kwargs:
293
      if key not in slots:
294
        raise TypeError("Object %s doesn't support the parameter '%s'" %
295
                        (self.__class__.__name__, key))
296
      setattr(self, key, kwargs[key])
297

    
298
  def __getstate__(self):
299
    """Generic serializer.
300

301
    This method just returns the contents of the instance as a
302
    dictionary.
303

304
    @rtype:  C{dict}
305
    @return: the instance attributes and their values
306

307
    """
308
    state = {}
309
    for name in self._all_slots():
310
      if hasattr(self, name):
311
        state[name] = getattr(self, name)
312
    return state
313

    
314
  def __setstate__(self, state):
315
    """Generic unserializer.
316

317
    This method just restores from the serialized state the attributes
318
    of the current instance.
319

320
    @param state: the serialized opcode data
321
    @type state:  C{dict}
322

323
    """
324
    if not isinstance(state, dict):
325
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
326
                       type(state))
327

    
328
    for name in self._all_slots():
329
      if name not in state and hasattr(self, name):
330
        delattr(self, name)
331

    
332
    for name in state:
333
      setattr(self, name, state[name])
334

    
335
  @classmethod
336
  def _all_slots(cls):
337
    """Compute the list of all declared slots for a class.
338

339
    """
340
    slots = []
341
    for parent in cls.__mro__:
342
      slots.extend(getattr(parent, "__slots__", []))
343
    return slots
344

    
345
  @classmethod
346
  def GetAllParams(cls):
347
    """Compute list of all parameters for an opcode.
348

349
    """
350
    slots = []
351
    for parent in cls.__mro__:
352
      slots.extend(getattr(parent, "OP_PARAMS", []))
353
    return slots
354

    
355
  def Validate(self, set_defaults):
356
    """Validate opcode parameters, optionally setting default values.
357

358
    @type set_defaults: bool
359
    @param set_defaults: Whether to set default values
360
    @raise errors.OpPrereqError: When a parameter value doesn't match
361
                                 requirements
362

363
    """
364
    for (attr_name, default, test, _) in self.GetAllParams():
365
      assert test == ht.NoType or callable(test)
366

    
367
      if not hasattr(self, attr_name):
368
        if default == ht.NoDefault:
369
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
370
                                     (self.OP_ID, attr_name),
371
                                     errors.ECODE_INVAL)
372
        elif set_defaults:
373
          if callable(default):
374
            dval = default()
375
          else:
376
            dval = default
377
          setattr(self, attr_name, dval)
378

    
379
      if test == ht.NoType:
380
        # no tests here
381
        continue
382

    
383
      if set_defaults or hasattr(self, attr_name):
384
        attr_val = getattr(self, attr_name)
385
        if not test(attr_val):
386
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
387
                        self.OP_ID, attr_name, type(attr_val), attr_val)
388
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
389
                                     (self.OP_ID, attr_name),
390
                                     errors.ECODE_INVAL)
391

    
392

    
393
class OpCode(BaseOpCode):
394
  """Abstract OpCode.
395

396
  This is the root of the actual OpCode hierarchy. All clases derived
397
  from this class should override OP_ID.
398

399
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
400
               children of this class.
401
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
402
                      string returned by Summary(); see the docstring of that
403
                      method for details).
404
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
405
                   get if not already defined, and types they must match.
406
  @cvar WITH_LU: Boolean that specifies whether this should be included in
407
      mcpu's dispatch table
408
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
409
                 the check steps
410
  @ivar priority: Opcode priority for queue
411

412
  """
413
  # pylint: disable-msg=E1101
414
  # as OP_ID is dynamically defined
415
  WITH_LU = True
416
  OP_PARAMS = [
417
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
418
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
419
    ("priority", constants.OP_PRIO_DEFAULT,
420
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
421
    ]
422

    
423
  def __getstate__(self):
424
    """Specialized getstate for opcodes.
425

426
    This method adds to the state dictionary the OP_ID of the class,
427
    so that on unload we can identify the correct class for
428
    instantiating the opcode.
429

430
    @rtype:   C{dict}
431
    @return:  the state as a dictionary
432

433
    """
434
    data = BaseOpCode.__getstate__(self)
435
    data["OP_ID"] = self.OP_ID
436
    return data
437

    
438
  @classmethod
439
  def LoadOpCode(cls, data):
440
    """Generic load opcode method.
441

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

446
    @type data:  C{dict}
447
    @param data: the serialized opcode
448

449
    """
450
    if not isinstance(data, dict):
451
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
452
    if "OP_ID" not in data:
453
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
454
    op_id = data["OP_ID"]
455
    op_class = None
456
    if op_id in OP_MAPPING:
457
      op_class = OP_MAPPING[op_id]
458
    else:
459
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
460
                       op_id)
461
    op = op_class()
462
    new_data = data.copy()
463
    del new_data["OP_ID"]
464
    op.__setstate__(new_data)
465
    return op
466

    
467
  def Summary(self):
468
    """Generates a summary description of this opcode.
469

470
    The summary is the value of the OP_ID attribute (without the "OP_"
471
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
472
    defined; this field should allow to easily identify the operation
473
    (for an instance creation job, e.g., it would be the instance
474
    name).
475

476
    """
477
    assert self.OP_ID is not None and len(self.OP_ID) > 3
478
    # all OP_ID start with OP_, we remove that
479
    txt = self.OP_ID[3:]
480
    field_name = getattr(self, "OP_DSC_FIELD", None)
481
    if field_name:
482
      field_value = getattr(self, field_name, None)
483
      if isinstance(field_value, (list, tuple)):
484
        field_value = ",".join(str(i) for i in field_value)
485
      txt = "%s(%s)" % (txt, field_value)
486
    return txt
487

    
488
  def TinySummary(self):
489
    """Generates a compact summary description of the opcode.
490

491
    """
492
    assert self.OP_ID.startswith("OP_")
493

    
494
    text = self.OP_ID[3:]
495

    
496
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
497
      if text.startswith(prefix):
498
        return supplement + text[len(prefix):]
499

    
500
    return text
501

    
502

    
503
# cluster opcodes
504

    
505
class OpClusterPostInit(OpCode):
506
  """Post cluster initialization.
507

508
  This opcode does not touch the cluster at all. Its purpose is to run hooks
509
  after the cluster has been initialized.
510

511
  """
512

    
513

    
514
class OpClusterDestroy(OpCode):
515
  """Destroy the cluster.
516

517
  This opcode has no other parameters. All the state is irreversibly
518
  lost after the execution of this opcode.
519

520
  """
521

    
522

    
523
class OpClusterQuery(OpCode):
524
  """Query cluster information."""
525

    
526

    
527
class OpClusterVerifyConfig(OpCode):
528
  """Verify the cluster config.
529

530
  """
531
  OP_PARAMS = [
532
    ("verbose", False, ht.TBool, None),
533
    ("error_codes", False, ht.TBool, None),
534
    ("debug_simulate_errors", False, ht.TBool, None),
535
    ]
536

    
537

    
538
class OpClusterVerifyGroup(OpCode):
539
  """Run verify on a node group from the cluster.
540

541
  @type skip_checks: C{list}
542
  @ivar skip_checks: steps to be skipped from the verify process; this
543
                     needs to be a subset of
544
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
545
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
546

547
  """
548
  OP_DSC_FIELD = "group_name"
549
  OP_PARAMS = [
550
    ("group_name", ht.NoDefault, ht.TNonEmptyString, None),
551
    ("skip_checks", ht.EmptyList,
552
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
553
    ("verbose", False, ht.TBool, None),
554
    ("error_codes", False, ht.TBool, None),
555
    ("debug_simulate_errors", False, ht.TBool, None),
556
    ]
557

    
558

    
559
class OpClusterVerifyDisks(OpCode):
560
  """Verify the cluster disks.
561

562
  Parameters: none
563

564
  Result: a tuple of four elements:
565
    - list of node names with bad data returned (unreachable, etc.)
566
    - dict of node names with broken volume groups (values: error msg)
567
    - list of instances with degraded disks (that should be activated)
568
    - dict of instances with missing logical volumes (values: (node, vol)
569
      pairs with details about the missing volumes)
570

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

576
  Note that only instances that are drbd-based are taken into
577
  consideration. This might need to be revisited in the future.
578

579
  """
580

    
581

    
582
class OpClusterRepairDiskSizes(OpCode):
583
  """Verify the disk sizes of the instances and fixes configuration
584
  mimatches.
585

586
  Parameters: optional instances list, in case we want to restrict the
587
  checks to only a subset of the instances.
588

589
  Result: a list of tuples, (instance, disk, new-size) for changed
590
  configurations.
591

592
  In normal operation, the list should be empty.
593

594
  @type instances: list
595
  @ivar instances: the list of instances to check, or empty for all instances
596

597
  """
598
  OP_PARAMS = [
599
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
600
    ]
601

    
602

    
603
class OpClusterConfigQuery(OpCode):
604
  """Query cluster configuration values."""
605
  OP_PARAMS = [
606
    _POutputFields
607
    ]
608

    
609

    
610
class OpClusterRename(OpCode):
611
  """Rename the cluster.
612

613
  @type name: C{str}
614
  @ivar name: The new name of the cluster. The name and/or the master IP
615
              address will be changed to match the new name and its IP
616
              address.
617

618
  """
619
  OP_DSC_FIELD = "name"
620
  OP_PARAMS = [
621
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
622
    ]
623

    
624

    
625
class OpClusterSetParams(OpCode):
626
  """Change the parameters of the cluster.
627

628
  @type vg_name: C{str} or C{None}
629
  @ivar vg_name: The new volume group name or None to disable LVM usage.
630

631
  """
632
  OP_PARAMS = [
633
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
634
    ("enabled_hypervisors", None,
635
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
636
            ht.TNone),
637
     "List of enabled hypervisors"),
638
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
639
                              ht.TNone),
640
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
641
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
642
     "Cluster-wide backend parameter defaults"),
643
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
644
                            ht.TNone),
645
     "Cluster-wide per-OS hypervisor parameter defaults"),
646
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
647
                              ht.TNone),
648
     "Cluster-wide OS parameter defaults"),
649
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
650
     "Master candidate pool size"),
651
    ("uid_pool", None, ht.NoType,
652
     "Set UID pool, must be list of lists describing UID ranges (two items,"
653
     " start and end inclusive)"),
654
    ("add_uids", None, ht.NoType,
655
     "Extend UID pool, must be list of lists describing UID ranges (two"
656
     " items, start and end inclusive) to be added"),
657
    ("remove_uids", None, ht.NoType,
658
     "Shrink UID pool, must be list of lists describing UID ranges (two"
659
     " items, start and end inclusive) to be removed"),
660
    ("maintain_node_health", None, ht.TMaybeBool,
661
     "Whether to automatically maintain node health"),
662
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
663
     "Whether to wipe disks before allocating them to instances"),
664
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
665
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
666
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
667
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
668
     "Default iallocator for cluster"),
669
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
670
     "Master network device"),
671
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
672
     "List of reserved LVs"),
673
    ("hidden_os", None, _TestClusterOsList,
674
     "Modify list of hidden operating systems. Each modification must have"
675
     " two items, the operation and the OS name. The operation can be"
676
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
677
    ("blacklisted_os", None, _TestClusterOsList,
678
     "Modify list of blacklisted operating systems. Each modification must have"
679
     " two items, the operation and the OS name. The operation can be"
680
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
681
    ]
682

    
683

    
684
class OpClusterRedistConf(OpCode):
685
  """Force a full push of the cluster configuration.
686

687
  """
688

    
689

    
690
class OpQuery(OpCode):
691
  """Query for resources/items.
692

693
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
694
  @ivar fields: List of fields to retrieve
695
  @ivar filter: Query filter
696

697
  """
698
  OP_PARAMS = [
699
    _PQueryWhat,
700
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
701
     "Requested fields"),
702
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
703
     "Query filter"),
704
    ]
705

    
706

    
707
class OpQueryFields(OpCode):
708
  """Query for available resource/item fields.
709

710
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
711
  @ivar fields: List of fields to retrieve
712

713
  """
714
  OP_PARAMS = [
715
    _PQueryWhat,
716
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
717
     "Requested fields; if not given, all are returned"),
718
    ]
719

    
720

    
721
class OpOobCommand(OpCode):
722
  """Interact with OOB."""
723
  OP_PARAMS = [
724
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
725
     "List of nodes to run the OOB command against"),
726
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
727
     "OOB command to be run"),
728
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
729
     "Timeout before the OOB helper will be terminated"),
730
    ("ignore_status", False, ht.TBool,
731
     "Ignores the node offline status for power off"),
732
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
733
     "Time in seconds to wait between powering on nodes"),
734
    ]
735

    
736

    
737
# node opcodes
738

    
739
class OpNodeRemove(OpCode):
740
  """Remove a node.
741

742
  @type node_name: C{str}
743
  @ivar node_name: The name of the node to remove. If the node still has
744
                   instances on it, the operation will fail.
745

746
  """
747
  OP_DSC_FIELD = "node_name"
748
  OP_PARAMS = [
749
    _PNodeName,
750
    ]
751

    
752

    
753
class OpNodeAdd(OpCode):
754
  """Add a node to the cluster.
755

756
  @type node_name: C{str}
757
  @ivar node_name: The name of the node to add. This can be a short name,
758
                   but it will be expanded to the FQDN.
759
  @type primary_ip: IP address
760
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
761
                    opcode is submitted, but will be filled during the node
762
                    add (so it will be visible in the job query).
763
  @type secondary_ip: IP address
764
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
765
                      if the cluster has been initialized in 'dual-network'
766
                      mode, otherwise it must not be given.
767
  @type readd: C{bool}
768
  @ivar readd: Whether to re-add an existing node to the cluster. If
769
               this is not passed, then the operation will abort if the node
770
               name is already in the cluster; use this parameter to 'repair'
771
               a node that had its configuration broken, or was reinstalled
772
               without removal from the cluster.
773
  @type group: C{str}
774
  @ivar group: The node group to which this node will belong.
775
  @type vm_capable: C{bool}
776
  @ivar vm_capable: The vm_capable node attribute
777
  @type master_capable: C{bool}
778
  @ivar master_capable: The master_capable node attribute
779

780
  """
781
  OP_DSC_FIELD = "node_name"
782
  OP_PARAMS = [
783
    _PNodeName,
784
    ("primary_ip", None, ht.NoType, "Primary IP address"),
785
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
786
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
787
    ("group", None, ht.TMaybeString, "Initial node group"),
788
    ("master_capable", None, ht.TMaybeBool,
789
     "Whether node can become master or master candidate"),
790
    ("vm_capable", None, ht.TMaybeBool,
791
     "Whether node can host instances"),
792
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
793
    ]
794

    
795

    
796
class OpNodeQuery(OpCode):
797
  """Compute the list of nodes."""
798
  OP_PARAMS = [
799
    _POutputFields,
800
    _PUseLocking,
801
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
802
     "Empty list to query all nodes, node names otherwise"),
803
    ]
804

    
805

    
806
class OpNodeQueryvols(OpCode):
807
  """Get list of volumes on node."""
808
  OP_PARAMS = [
809
    _POutputFields,
810
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
811
     "Empty list to query all nodes, node names otherwise"),
812
    ]
813

    
814

    
815
class OpNodeQueryStorage(OpCode):
816
  """Get information on storage for node(s)."""
817
  OP_PARAMS = [
818
    _POutputFields,
819
    _PStorageType,
820
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
821
    ("name", None, ht.TMaybeString, "Storage name"),
822
    ]
823

    
824

    
825
class OpNodeModifyStorage(OpCode):
826
  """Modifies the properies of a storage unit"""
827
  OP_PARAMS = [
828
    _PNodeName,
829
    _PStorageType,
830
    _PStorageName,
831
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
832
    ]
833

    
834

    
835
class OpRepairNodeStorage(OpCode):
836
  """Repairs the volume group on a node."""
837
  OP_DSC_FIELD = "node_name"
838
  OP_PARAMS = [
839
    _PNodeName,
840
    _PStorageType,
841
    _PStorageName,
842
    _PIgnoreConsistency,
843
    ]
844

    
845

    
846
class OpNodeSetParams(OpCode):
847
  """Change the parameters of a node."""
848
  OP_DSC_FIELD = "node_name"
849
  OP_PARAMS = [
850
    _PNodeName,
851
    _PForce,
852
    ("master_candidate", None, ht.TMaybeBool,
853
     "Whether the node should become a master candidate"),
854
    ("offline", None, ht.TMaybeBool,
855
     "Whether the node should be marked as offline"),
856
    ("drained", None, ht.TMaybeBool,
857
     "Whether the node should be marked as drained"),
858
    ("auto_promote", False, ht.TBool,
859
     "Whether node(s) should be promoted to master candidate if necessary"),
860
    ("master_capable", None, ht.TMaybeBool,
861
     "Denote whether node can become master or master candidate"),
862
    ("vm_capable", None, ht.TMaybeBool,
863
     "Denote whether node can host instances"),
864
    ("secondary_ip", None, ht.TMaybeString,
865
     "Change node's secondary IP address"),
866
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
867
    ("powered", None, ht.TMaybeBool,
868
     "Whether the node should be marked as powered"),
869
    ]
870

    
871

    
872
class OpNodePowercycle(OpCode):
873
  """Tries to powercycle a node."""
874
  OP_DSC_FIELD = "node_name"
875
  OP_PARAMS = [
876
    _PNodeName,
877
    _PForce,
878
    ]
879

    
880

    
881
class OpNodeMigrate(OpCode):
882
  """Migrate all instances from a node."""
883
  OP_DSC_FIELD = "node_name"
884
  OP_PARAMS = [
885
    _PNodeName,
886
    _PMigrationMode,
887
    _PMigrationLive,
888
    _PMigrationTargetNode,
889
    ("iallocator", None, ht.TMaybeString,
890
     "Iallocator for deciding the target node for shared-storage instances"),
891
    ]
892

    
893

    
894
class OpNodeEvacuate(OpCode):
895
  """Evacuate instances off a number of nodes."""
896
  OP_DSC_FIELD = "node_name"
897
  OP_PARAMS = [
898
    _PEarlyRelease,
899
    _PNodeName,
900
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
901
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
902
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
903
     "Node evacuation mode"),
904
    ]
905

    
906

    
907
# instance opcodes
908

    
909
class OpInstanceCreate(OpCode):
910
  """Create an instance.
911

912
  @ivar instance_name: Instance name
913
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
914
  @ivar source_handshake: Signed handshake from source (remote import only)
915
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
916
  @ivar source_instance_name: Previous name of instance (remote import only)
917
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
918
    (remote import only)
919

920
  """
921
  OP_DSC_FIELD = "instance_name"
922
  OP_PARAMS = [
923
    _PInstanceName,
924
    _PForceVariant,
925
    _PWaitForSync,
926
    _PNameCheck,
927
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
928
    ("disks", ht.NoDefault,
929
     # TODO: Generate check from constants.IDISK_PARAMS_TYPES
930
     ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
931
                           ht.TOr(ht.TNonEmptyString, ht.TInt))),
932
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
933
     " each disk definition must contain a ``%s`` value and"
934
     " can contain an optional ``%s`` value denoting the disk access mode"
935
     " (%s)" %
936
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
937
      constants.IDISK_MODE,
938
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
939
    ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
940
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
941
     "Driver for file-backed disks"),
942
    ("file_storage_dir", None, ht.TMaybeString,
943
     "Directory for storing file-backed disks"),
944
    ("hvparams", ht.EmptyDict, ht.TDict,
945
     "Hypervisor parameters for instance, hypervisor-dependent"),
946
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
947
    ("iallocator", None, ht.TMaybeString,
948
     "Iallocator for deciding which node(s) to use"),
949
    ("identify_defaults", False, ht.TBool,
950
     "Reset instance parameters to default if equal"),
951
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
952
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
953
     "Instance creation mode"),
954
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
955
     "List of NIC (network interface) definitions, for example"
956
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
957
     " contain the optional values %s" %
958
     (constants.INIC_IP,
959
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
960
    ("no_install", None, ht.TMaybeBool,
961
     "Do not install the OS (will disable automatic start)"),
962
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
963
    ("os_type", None, ht.TMaybeString, "Operating system"),
964
    ("pnode", None, ht.TMaybeString, "Primary node"),
965
    ("snode", None, ht.TMaybeString, "Secondary node"),
966
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
967
     "Signed handshake from source (remote import only)"),
968
    ("source_instance_name", None, ht.TMaybeString,
969
     "Source instance name (remote import only)"),
970
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
971
     ht.TPositiveInt,
972
     "How long source instance was given to shut down (remote import only)"),
973
    ("source_x509_ca", None, ht.TMaybeString,
974
     "Source X509 CA in PEM format (remote import only)"),
975
    ("src_node", None, ht.TMaybeString, "Source node for import"),
976
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
977
    ("start", True, ht.TBool, "Whether to start instance after creation"),
978
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
979
    ]
980

    
981

    
982
class OpInstanceReinstall(OpCode):
983
  """Reinstall an instance's OS."""
984
  OP_DSC_FIELD = "instance_name"
985
  OP_PARAMS = [
986
    _PInstanceName,
987
    _PForceVariant,
988
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
989
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
990
    ]
991

    
992

    
993
class OpInstanceRemove(OpCode):
994
  """Remove an instance."""
995
  OP_DSC_FIELD = "instance_name"
996
  OP_PARAMS = [
997
    _PInstanceName,
998
    _PShutdownTimeout,
999
    ("ignore_failures", False, ht.TBool,
1000
     "Whether to ignore failures during removal"),
1001
    ]
1002

    
1003

    
1004
class OpInstanceRename(OpCode):
1005
  """Rename an instance."""
1006
  OP_PARAMS = [
1007
    _PInstanceName,
1008
    _PNameCheck,
1009
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1010
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1011
    ]
1012

    
1013

    
1014
class OpInstanceStartup(OpCode):
1015
  """Startup an instance."""
1016
  OP_DSC_FIELD = "instance_name"
1017
  OP_PARAMS = [
1018
    _PInstanceName,
1019
    _PForce,
1020
    _PIgnoreOfflineNodes,
1021
    ("hvparams", ht.EmptyDict, ht.TDict,
1022
     "Temporary hypervisor parameters, hypervisor-dependent"),
1023
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1024
    _PNoRemember,
1025
    _PStartupPaused,
1026
    ]
1027

    
1028

    
1029
class OpInstanceShutdown(OpCode):
1030
  """Shutdown an instance."""
1031
  OP_DSC_FIELD = "instance_name"
1032
  OP_PARAMS = [
1033
    _PInstanceName,
1034
    _PIgnoreOfflineNodes,
1035
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1036
     "How long to wait for instance to shut down"),
1037
    _PNoRemember,
1038
    ]
1039

    
1040

    
1041
class OpInstanceReboot(OpCode):
1042
  """Reboot an instance."""
1043
  OP_DSC_FIELD = "instance_name"
1044
  OP_PARAMS = [
1045
    _PInstanceName,
1046
    _PShutdownTimeout,
1047
    ("ignore_secondaries", False, ht.TBool,
1048
     "Whether to start the instance even if secondary disks are failing"),
1049
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1050
     "How to reboot instance"),
1051
    ]
1052

    
1053

    
1054
class OpInstanceReplaceDisks(OpCode):
1055
  """Replace the disks of an instance."""
1056
  OP_DSC_FIELD = "instance_name"
1057
  OP_PARAMS = [
1058
    _PInstanceName,
1059
    _PEarlyRelease,
1060
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1061
     "Replacement mode"),
1062
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1063
     "Disk indexes"),
1064
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1065
    ("iallocator", None, ht.TMaybeString,
1066
     "Iallocator for deciding new secondary node"),
1067
    ]
1068

    
1069

    
1070
class OpInstanceFailover(OpCode):
1071
  """Failover an instance."""
1072
  OP_DSC_FIELD = "instance_name"
1073
  OP_PARAMS = [
1074
    _PInstanceName,
1075
    _PShutdownTimeout,
1076
    _PIgnoreConsistency,
1077
    _PMigrationTargetNode,
1078
    ("iallocator", None, ht.TMaybeString,
1079
     "Iallocator for deciding the target node for shared-storage instances"),
1080
    ]
1081

    
1082

    
1083
class OpInstanceMigrate(OpCode):
1084
  """Migrate an instance.
1085

1086
  This migrates (without shutting down an instance) to its secondary
1087
  node.
1088

1089
  @ivar instance_name: the name of the instance
1090
  @ivar mode: the migration mode (live, non-live or None for auto)
1091

1092
  """
1093
  OP_DSC_FIELD = "instance_name"
1094
  OP_PARAMS = [
1095
    _PInstanceName,
1096
    _PMigrationMode,
1097
    _PMigrationLive,
1098
    _PMigrationTargetNode,
1099
    ("cleanup", False, ht.TBool,
1100
     "Whether a previously failed migration should be cleaned up"),
1101
    ("iallocator", None, ht.TMaybeString,
1102
     "Iallocator for deciding the target node for shared-storage instances"),
1103
    ("allow_failover", False, ht.TBool,
1104
     "Whether we can fallback to failover if migration is not possible"),
1105
    ]
1106

    
1107

    
1108
class OpInstanceMove(OpCode):
1109
  """Move an instance.
1110

1111
  This move (with shutting down an instance and data copying) to an
1112
  arbitrary node.
1113

1114
  @ivar instance_name: the name of the instance
1115
  @ivar target_node: the destination node
1116

1117
  """
1118
  OP_DSC_FIELD = "instance_name"
1119
  OP_PARAMS = [
1120
    _PInstanceName,
1121
    _PShutdownTimeout,
1122
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1123
    _PIgnoreConsistency,
1124
    ]
1125

    
1126

    
1127
class OpInstanceConsole(OpCode):
1128
  """Connect to an instance's console."""
1129
  OP_DSC_FIELD = "instance_name"
1130
  OP_PARAMS = [
1131
    _PInstanceName
1132
    ]
1133

    
1134

    
1135
class OpInstanceActivateDisks(OpCode):
1136
  """Activate an instance's disks."""
1137
  OP_DSC_FIELD = "instance_name"
1138
  OP_PARAMS = [
1139
    _PInstanceName,
1140
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1141
    ]
1142

    
1143

    
1144
class OpInstanceDeactivateDisks(OpCode):
1145
  """Deactivate an instance's disks."""
1146
  OP_DSC_FIELD = "instance_name"
1147
  OP_PARAMS = [
1148
    _PInstanceName,
1149
    _PForce,
1150
    ]
1151

    
1152

    
1153
class OpInstanceRecreateDisks(OpCode):
1154
  """Deactivate an instance's disks."""
1155
  OP_DSC_FIELD = "instance_name"
1156
  OP_PARAMS = [
1157
    _PInstanceName,
1158
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1159
     "List of disk indexes"),
1160
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1161
     "New instance nodes, if relocation is desired"),
1162
    ]
1163

    
1164

    
1165
class OpInstanceQuery(OpCode):
1166
  """Compute the list of instances."""
1167
  OP_PARAMS = [
1168
    _POutputFields,
1169
    _PUseLocking,
1170
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1171
     "Empty list to query all instances, instance names otherwise"),
1172
    ]
1173

    
1174

    
1175
class OpInstanceQueryData(OpCode):
1176
  """Compute the run-time status of instances."""
1177
  OP_PARAMS = [
1178
    _PUseLocking,
1179
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1180
     "Instance names"),
1181
    ("static", False, ht.TBool,
1182
     "Whether to only return configuration data without querying"
1183
     " nodes"),
1184
    ]
1185

    
1186

    
1187
class OpInstanceSetParams(OpCode):
1188
  """Change the parameters of an instance."""
1189
  OP_DSC_FIELD = "instance_name"
1190
  OP_PARAMS = [
1191
    _PInstanceName,
1192
    _PForce,
1193
    _PForceVariant,
1194
    # TODO: Use _TestNicDef
1195
    ("nics", ht.EmptyList, ht.TList,
1196
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1197
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1198
     " ``%s`` to remove the last NIC or a number to modify the settings"
1199
     " of the NIC with that index." %
1200
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1201
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1202
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1203
    ("hvparams", ht.EmptyDict, ht.TDict,
1204
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1205
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1206
     "Disk template for instance"),
1207
    ("remote_node", None, ht.TMaybeString,
1208
     "Secondary node (used when changing disk template)"),
1209
    ("os_name", None, ht.TMaybeString,
1210
     "Change instance's OS name. Does not reinstall the instance."),
1211
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1212
    ("wait_for_sync", True, ht.TBool,
1213
     "Whether to wait for the disk to synchronize, when changing template"),
1214
    ]
1215

    
1216

    
1217
class OpInstanceGrowDisk(OpCode):
1218
  """Grow a disk of an instance."""
1219
  OP_DSC_FIELD = "instance_name"
1220
  OP_PARAMS = [
1221
    _PInstanceName,
1222
    _PWaitForSync,
1223
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1224
    ("amount", ht.NoDefault, ht.TInt,
1225
     "Amount of disk space to add (megabytes)"),
1226
    ]
1227

    
1228

    
1229
# Node group opcodes
1230

    
1231
class OpGroupAdd(OpCode):
1232
  """Add a node group to the cluster."""
1233
  OP_DSC_FIELD = "group_name"
1234
  OP_PARAMS = [
1235
    _PGroupName,
1236
    _PNodeGroupAllocPolicy,
1237
    _PGroupNodeParams,
1238
    ]
1239

    
1240

    
1241
class OpGroupAssignNodes(OpCode):
1242
  """Assign nodes to a node group."""
1243
  OP_DSC_FIELD = "group_name"
1244
  OP_PARAMS = [
1245
    _PGroupName,
1246
    _PForce,
1247
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1248
     "List of nodes to assign"),
1249
    ]
1250

    
1251

    
1252
class OpGroupQuery(OpCode):
1253
  """Compute the list of node groups."""
1254
  OP_PARAMS = [
1255
    _POutputFields,
1256
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1257
     "Empty list to query all groups, group names otherwise"),
1258
    ]
1259

    
1260

    
1261
class OpGroupSetParams(OpCode):
1262
  """Change the parameters of a node group."""
1263
  OP_DSC_FIELD = "group_name"
1264
  OP_PARAMS = [
1265
    _PGroupName,
1266
    _PNodeGroupAllocPolicy,
1267
    _PGroupNodeParams,
1268
    ]
1269

    
1270

    
1271
class OpGroupRemove(OpCode):
1272
  """Remove a node group from the cluster."""
1273
  OP_DSC_FIELD = "group_name"
1274
  OP_PARAMS = [
1275
    _PGroupName,
1276
    ]
1277

    
1278

    
1279
class OpGroupRename(OpCode):
1280
  """Rename a node group in the cluster."""
1281
  OP_PARAMS = [
1282
    _PGroupName,
1283
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1284
    ]
1285

    
1286

    
1287
# OS opcodes
1288
class OpOsDiagnose(OpCode):
1289
  """Compute the list of guest operating systems."""
1290
  OP_PARAMS = [
1291
    _POutputFields,
1292
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1293
     "Which operating systems to diagnose"),
1294
    ]
1295

    
1296

    
1297
# Exports opcodes
1298
class OpBackupQuery(OpCode):
1299
  """Compute the list of exported images."""
1300
  OP_PARAMS = [
1301
    _PUseLocking,
1302
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1303
     "Empty list to query all nodes, node names otherwise"),
1304
    ]
1305

    
1306

    
1307
class OpBackupPrepare(OpCode):
1308
  """Prepares an instance export.
1309

1310
  @ivar instance_name: Instance name
1311
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1312

1313
  """
1314
  OP_DSC_FIELD = "instance_name"
1315
  OP_PARAMS = [
1316
    _PInstanceName,
1317
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1318
     "Export mode"),
1319
    ]
1320

    
1321

    
1322
class OpBackupExport(OpCode):
1323
  """Export an instance.
1324

1325
  For local exports, the export destination is the node name. For remote
1326
  exports, the export destination is a list of tuples, each consisting of
1327
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1328
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1329
  destination X509 CA must be a signed certificate.
1330

1331
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1332
  @ivar target_node: Export destination
1333
  @ivar x509_key_name: X509 key to use (remote export only)
1334
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1335
                             only)
1336

1337
  """
1338
  OP_DSC_FIELD = "instance_name"
1339
  OP_PARAMS = [
1340
    _PInstanceName,
1341
    _PShutdownTimeout,
1342
    # TODO: Rename target_node as it changes meaning for different export modes
1343
    # (e.g. "destination")
1344
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1345
     "Destination information, depends on export mode"),
1346
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1347
    ("remove_instance", False, ht.TBool,
1348
     "Whether to remove instance after export"),
1349
    ("ignore_remove_failures", False, ht.TBool,
1350
     "Whether to ignore failures while removing instances"),
1351
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1352
     "Export mode"),
1353
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1354
     "Name of X509 key (remote export only)"),
1355
    ("destination_x509_ca", None, ht.TMaybeString,
1356
     "Destination X509 CA (remote export only)"),
1357
    ]
1358

    
1359

    
1360
class OpBackupRemove(OpCode):
1361
  """Remove an instance's export."""
1362
  OP_DSC_FIELD = "instance_name"
1363
  OP_PARAMS = [
1364
    _PInstanceName,
1365
    ]
1366

    
1367

    
1368
# Tags opcodes
1369
class OpTagsGet(OpCode):
1370
  """Returns the tags of the given object."""
1371
  OP_DSC_FIELD = "name"
1372
  OP_PARAMS = [
1373
    _PTagKind,
1374
    # Name is only meaningful for nodes and instances
1375
    ("name", ht.NoDefault, ht.TMaybeString, None),
1376
    ]
1377

    
1378

    
1379
class OpTagsSearch(OpCode):
1380
  """Searches the tags in the cluster for a given pattern."""
1381
  OP_DSC_FIELD = "pattern"
1382
  OP_PARAMS = [
1383
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1384
    ]
1385

    
1386

    
1387
class OpTagsSet(OpCode):
1388
  """Add a list of tags on a given object."""
1389
  OP_PARAMS = [
1390
    _PTagKind,
1391
    _PTags,
1392
    # Name is only meaningful for nodes and instances
1393
    ("name", ht.NoDefault, ht.TMaybeString, None),
1394
    ]
1395

    
1396

    
1397
class OpTagsDel(OpCode):
1398
  """Remove a list of tags from a given object."""
1399
  OP_PARAMS = [
1400
    _PTagKind,
1401
    _PTags,
1402
    # Name is only meaningful for nodes and instances
1403
    ("name", ht.NoDefault, ht.TMaybeString, None),
1404
    ]
1405

    
1406
# Test opcodes
1407
class OpTestDelay(OpCode):
1408
  """Sleeps for a configured amount of time.
1409

1410
  This is used just for debugging and testing.
1411

1412
  Parameters:
1413
    - duration: the time to sleep
1414
    - on_master: if true, sleep on the master
1415
    - on_nodes: list of nodes in which to sleep
1416

1417
  If the on_master parameter is true, it will execute a sleep on the
1418
  master (before any node sleep).
1419

1420
  If the on_nodes list is not empty, it will sleep on those nodes
1421
  (after the sleep on the master, if that is enabled).
1422

1423
  As an additional feature, the case of duration < 0 will be reported
1424
  as an execution error, so this opcode can be used as a failure
1425
  generator. The case of duration == 0 will not be treated specially.
1426

1427
  """
1428
  OP_DSC_FIELD = "duration"
1429
  OP_PARAMS = [
1430
    ("duration", ht.NoDefault, ht.TFloat, None),
1431
    ("on_master", True, ht.TBool, None),
1432
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1433
    ("repeat", 0, ht.TPositiveInt, None),
1434
    ]
1435

    
1436

    
1437
class OpTestAllocator(OpCode):
1438
  """Allocator framework testing.
1439

1440
  This opcode has two modes:
1441
    - gather and return allocator input for a given mode (allocate new
1442
      or replace secondary) and a given instance definition (direction
1443
      'in')
1444
    - run a selected allocator for a given operation (as above) and
1445
      return the allocator output (direction 'out')
1446

1447
  """
1448
  OP_DSC_FIELD = "allocator"
1449
  OP_PARAMS = [
1450
    ("direction", ht.NoDefault,
1451
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1452
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1453
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1454
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1455
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1456
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1457
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1458
    ("hypervisor", None, ht.TMaybeString, None),
1459
    ("allocator", None, ht.TMaybeString, None),
1460
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1461
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1462
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1463
    ("os", None, ht.TMaybeString, None),
1464
    ("disk_template", None, ht.TMaybeString, None),
1465
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1466
     None),
1467
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1468
     None),
1469
    ("evac_mode", None,
1470
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1471
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1472
     None),
1473
    ]
1474

    
1475

    
1476
class OpTestJqueue(OpCode):
1477
  """Utility opcode to test some aspects of the job queue.
1478

1479
  """
1480
  OP_PARAMS = [
1481
    ("notify_waitlock", False, ht.TBool, None),
1482
    ("notify_exec", False, ht.TBool, None),
1483
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1484
    ("fail", False, ht.TBool, None),
1485
    ]
1486

    
1487

    
1488
class OpTestDummy(OpCode):
1489
  """Utility opcode used by unittests.
1490

1491
  """
1492
  OP_PARAMS = [
1493
    ("result", ht.NoDefault, ht.NoType, None),
1494
    ("messages", ht.NoDefault, ht.NoType, None),
1495
    ("fail", ht.NoDefault, ht.NoType, None),
1496
    ("submit_jobs", None, ht.NoType, None),
1497
    ]
1498
  WITH_LU = False
1499

    
1500

    
1501
def _GetOpList():
1502
  """Returns list of all defined opcodes.
1503

1504
  Does not eliminate duplicates by C{OP_ID}.
1505

1506
  """
1507
  return [v for v in globals().values()
1508
          if (isinstance(v, type) and issubclass(v, OpCode) and
1509
              hasattr(v, "OP_ID") and v is not OpCode)]
1510

    
1511

    
1512
OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())