Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ e1f23243

History | View | Annotate | Download (46.8 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
#: OP_ID conversion regular expression
129
_OPID_RE = re.compile("([a-z])([A-Z])")
130

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

    
137

    
138
# TODO: Generate check from constants.INIC_PARAMS_TYPES
139
#: Utility function for testing NIC definitions
140
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
141
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
142

    
143
_SUMMARY_PREFIX = {
144
  "CLUSTER_": "C_",
145
  "GROUP_": "G_",
146
  "NODE_": "N_",
147
  "INSTANCE_": "I_",
148
  }
149

    
150

    
151
def _NameToId(name):
152
  """Convert an opcode class name to an OP_ID.
153

154
  @type name: string
155
  @param name: the class name, as OpXxxYyy
156
  @rtype: string
157
  @return: the name in the OP_XXXX_YYYY format
158

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

    
171

    
172
def RequireFileStorage():
173
  """Checks that file storage is enabled.
174

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

178
  @raise errors.OpPrereqError: when file storage is disabled
179

180
  """
181
  if not constants.ENABLE_FILE_STORAGE:
182
    raise errors.OpPrereqError("File storage disabled at configure time",
183
                               errors.ECODE_INVAL)
184

    
185

    
186
def RequireSharedFileStorage():
187
  """Checks that shared file storage is enabled.
188

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

192
  @raise errors.OpPrereqError: when shared file storage is disabled
193

194
  """
195
  if not constants.ENABLE_SHARED_FILE_STORAGE:
196
    raise errors.OpPrereqError("Shared file storage disabled at"
197
                               " configure time", errors.ECODE_INVAL)
198

    
199

    
200
@ht.WithDesc("CheckFileStorage")
201
def _CheckFileStorage(value):
202
  """Ensures file storage is enabled if used.
203

204
  """
205
  if value == constants.DT_FILE:
206
    RequireFileStorage()
207
  elif value == constants.DT_SHARED_FILE:
208
    RequireSharedFileStorage()
209
  return True
210

    
211

    
212
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
213
                             _CheckFileStorage)
214

    
215

    
216
def _CheckStorageType(storage_type):
217
  """Ensure a given storage type is valid.
218

219
  """
220
  if storage_type not in constants.VALID_STORAGE_TYPES:
221
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
222
                               errors.ECODE_INVAL)
223
  if storage_type == constants.ST_FILE:
224
    RequireFileStorage()
225
  return True
226

    
227

    
228
#: Storage type parameter
229
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
230
                 "Storage type")
231

    
232

    
233
class _AutoOpParamSlots(type):
234
  """Meta class for opcode definitions.
235

236
  """
237
  def __new__(mcs, name, bases, attrs):
238
    """Called when a class should be created.
239

240
    @param mcs: The meta class
241
    @param name: Name of created class
242
    @param bases: Base classes
243
    @type attrs: dict
244
    @param attrs: Class attributes
245

246
    """
247
    assert "__slots__" not in attrs, \
248
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
249
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
250

    
251
    attrs["OP_ID"] = _NameToId(name)
252

    
253
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
254
    params = attrs.setdefault("OP_PARAMS", [])
255

    
256
    # Use parameter names as slots
257
    slots = [pname for (pname, _, _, _) in params]
258

    
259
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
260
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
261

    
262
    attrs["__slots__"] = slots
263

    
264
    return type.__new__(mcs, name, bases, attrs)
265

    
266

    
267
class BaseOpCode(object):
268
  """A simple serializable object.
269

270
  This object serves as a parent class for OpCode without any custom
271
  field handling.
272

273
  """
274
  # pylint: disable-msg=E1101
275
  # as OP_ID is dynamically defined
276
  __metaclass__ = _AutoOpParamSlots
277

    
278
  def __init__(self, **kwargs):
279
    """Constructor for BaseOpCode.
280

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

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

    
294
  def __getstate__(self):
295
    """Generic serializer.
296

297
    This method just returns the contents of the instance as a
298
    dictionary.
299

300
    @rtype:  C{dict}
301
    @return: the instance attributes and their values
302

303
    """
304
    state = {}
305
    for name in self._all_slots():
306
      if hasattr(self, name):
307
        state[name] = getattr(self, name)
308
    return state
309

    
310
  def __setstate__(self, state):
311
    """Generic unserializer.
312

313
    This method just restores from the serialized state the attributes
314
    of the current instance.
315

316
    @param state: the serialized opcode data
317
    @type state:  C{dict}
318

319
    """
320
    if not isinstance(state, dict):
321
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
322
                       type(state))
323

    
324
    for name in self._all_slots():
325
      if name not in state and hasattr(self, name):
326
        delattr(self, name)
327

    
328
    for name in state:
329
      setattr(self, name, state[name])
330

    
331
  @classmethod
332
  def _all_slots(cls):
333
    """Compute the list of all declared slots for a class.
334

335
    """
336
    slots = []
337
    for parent in cls.__mro__:
338
      slots.extend(getattr(parent, "__slots__", []))
339
    return slots
340

    
341
  @classmethod
342
  def GetAllParams(cls):
343
    """Compute list of all parameters for an opcode.
344

345
    """
346
    slots = []
347
    for parent in cls.__mro__:
348
      slots.extend(getattr(parent, "OP_PARAMS", []))
349
    return slots
350

    
351
  def Validate(self, set_defaults):
352
    """Validate opcode parameters, optionally setting default values.
353

354
    @type set_defaults: bool
355
    @param set_defaults: Whether to set default values
356
    @raise errors.OpPrereqError: When a parameter value doesn't match
357
                                 requirements
358

359
    """
360
    for (attr_name, default, test, _) in self.GetAllParams():
361
      assert test == ht.NoType or callable(test)
362

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

    
375
      if test == ht.NoType:
376
        # no tests here
377
        continue
378

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

    
388

    
389
class OpCode(BaseOpCode):
390
  """Abstract OpCode.
391

392
  This is the root of the actual OpCode hierarchy. All clases derived
393
  from this class should override OP_ID.
394

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

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

    
419
  def __getstate__(self):
420
    """Specialized getstate for opcodes.
421

422
    This method adds to the state dictionary the OP_ID of the class,
423
    so that on unload we can identify the correct class for
424
    instantiating the opcode.
425

426
    @rtype:   C{dict}
427
    @return:  the state as a dictionary
428

429
    """
430
    data = BaseOpCode.__getstate__(self)
431
    data["OP_ID"] = self.OP_ID
432
    return data
433

    
434
  @classmethod
435
  def LoadOpCode(cls, data):
436
    """Generic load opcode method.
437

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

442
    @type data:  C{dict}
443
    @param data: the serialized opcode
444

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

    
463
  def Summary(self):
464
    """Generates a summary description of this opcode.
465

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

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

    
484
  def TinySummary(self):
485
    """Generates a compact summary description of the opcode.
486

487
    """
488
    assert self.OP_ID.startswith("OP_")
489

    
490
    text = self.OP_ID[3:]
491

    
492
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
493
      if text.startswith(prefix):
494
        return supplement + text[len(prefix):]
495

    
496
    return text
497

    
498

    
499
# cluster opcodes
500

    
501
class OpClusterPostInit(OpCode):
502
  """Post cluster initialization.
503

504
  This opcode does not touch the cluster at all. Its purpose is to run hooks
505
  after the cluster has been initialized.
506

507
  """
508

    
509

    
510
class OpClusterDestroy(OpCode):
511
  """Destroy the cluster.
512

513
  This opcode has no other parameters. All the state is irreversibly
514
  lost after the execution of this opcode.
515

516
  """
517

    
518

    
519
class OpClusterQuery(OpCode):
520
  """Query cluster information."""
521

    
522

    
523
class OpClusterVerifyConfig(OpCode):
524
  """Verify the cluster config.
525

526
  """
527
  OP_PARAMS = [
528
    ("verbose", False, ht.TBool, None),
529
    ("error_codes", False, ht.TBool, None),
530
    ("debug_simulate_errors", False, ht.TBool, None),
531
    ]
532

    
533

    
534
class OpClusterVerifyGroup(OpCode):
535
  """Run verify on a node group from the cluster.
536

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

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

    
554

    
555
class OpClusterVerifyDisks(OpCode):
556
  """Verify the cluster disks.
557

558
  Parameters: none
559

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

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

572
  Note that only instances that are drbd-based are taken into
573
  consideration. This might need to be revisited in the future.
574

575
  """
576

    
577

    
578
class OpClusterRepairDiskSizes(OpCode):
579
  """Verify the disk sizes of the instances and fixes configuration
580
  mimatches.
581

582
  Parameters: optional instances list, in case we want to restrict the
583
  checks to only a subset of the instances.
584

585
  Result: a list of tuples, (instance, disk, new-size) for changed
586
  configurations.
587

588
  In normal operation, the list should be empty.
589

590
  @type instances: list
591
  @ivar instances: the list of instances to check, or empty for all instances
592

593
  """
594
  OP_PARAMS = [
595
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
596
    ]
597

    
598

    
599
class OpClusterConfigQuery(OpCode):
600
  """Query cluster configuration values."""
601
  OP_PARAMS = [
602
    _POutputFields
603
    ]
604

    
605

    
606
class OpClusterRename(OpCode):
607
  """Rename the cluster.
608

609
  @type name: C{str}
610
  @ivar name: The new name of the cluster. The name and/or the master IP
611
              address will be changed to match the new name and its IP
612
              address.
613

614
  """
615
  OP_DSC_FIELD = "name"
616
  OP_PARAMS = [
617
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
618
    ]
619

    
620

    
621
class OpClusterSetParams(OpCode):
622
  """Change the parameters of the cluster.
623

624
  @type vg_name: C{str} or C{None}
625
  @ivar vg_name: The new volume group name or None to disable LVM usage.
626

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

    
679

    
680
class OpClusterRedistConf(OpCode):
681
  """Force a full push of the cluster configuration.
682

683
  """
684

    
685

    
686
class OpQuery(OpCode):
687
  """Query for resources/items.
688

689
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
690
  @ivar fields: List of fields to retrieve
691
  @ivar filter: Query filter
692

693
  """
694
  OP_PARAMS = [
695
    _PQueryWhat,
696
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
697
     "Requested fields"),
698
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
699
     "Query filter"),
700
    ]
701

    
702

    
703
class OpQueryFields(OpCode):
704
  """Query for available resource/item fields.
705

706
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
707
  @ivar fields: List of fields to retrieve
708

709
  """
710
  OP_PARAMS = [
711
    _PQueryWhat,
712
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
713
     "Requested fields; if not given, all are returned"),
714
    ]
715

    
716

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

    
732

    
733
# node opcodes
734

    
735
class OpNodeRemove(OpCode):
736
  """Remove a node.
737

738
  @type node_name: C{str}
739
  @ivar node_name: The name of the node to remove. If the node still has
740
                   instances on it, the operation will fail.
741

742
  """
743
  OP_DSC_FIELD = "node_name"
744
  OP_PARAMS = [
745
    _PNodeName,
746
    ]
747

    
748

    
749
class OpNodeAdd(OpCode):
750
  """Add a node to the cluster.
751

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

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

    
791

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

    
801

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

    
810

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

    
820

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

    
830

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

    
841

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

    
867

    
868
class OpNodePowercycle(OpCode):
869
  """Tries to powercycle a node."""
870
  OP_DSC_FIELD = "node_name"
871
  OP_PARAMS = [
872
    _PNodeName,
873
    _PForce,
874
    ]
875

    
876

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

    
889

    
890
class OpNodeEvacStrategy(OpCode):
891
  """Compute the evacuation strategy for a list of nodes."""
892
  OP_DSC_FIELD = "nodes"
893
  OP_PARAMS = [
894
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None),
895
    ("remote_node", None, ht.TMaybeString, None),
896
    ("iallocator", None, ht.TMaybeString, None),
897
    ]
898

    
899

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

    
912

    
913
# instance opcodes
914

    
915
class OpInstanceCreate(OpCode):
916
  """Create an instance.
917

918
  @ivar instance_name: Instance name
919
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
920
  @ivar source_handshake: Signed handshake from source (remote import only)
921
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
922
  @ivar source_instance_name: Previous name of instance (remote import only)
923
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
924
    (remote import only)
925

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

    
987

    
988
class OpInstanceReinstall(OpCode):
989
  """Reinstall an instance's OS."""
990
  OP_DSC_FIELD = "instance_name"
991
  OP_PARAMS = [
992
    _PInstanceName,
993
    _PForceVariant,
994
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
995
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
996
    ]
997

    
998

    
999
class OpInstanceRemove(OpCode):
1000
  """Remove an instance."""
1001
  OP_DSC_FIELD = "instance_name"
1002
  OP_PARAMS = [
1003
    _PInstanceName,
1004
    _PShutdownTimeout,
1005
    ("ignore_failures", False, ht.TBool,
1006
     "Whether to ignore failures during removal"),
1007
    ]
1008

    
1009

    
1010
class OpInstanceRename(OpCode):
1011
  """Rename an instance."""
1012
  OP_PARAMS = [
1013
    _PInstanceName,
1014
    _PNameCheck,
1015
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1016
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1017
    ]
1018

    
1019

    
1020
class OpInstanceStartup(OpCode):
1021
  """Startup an instance."""
1022
  OP_DSC_FIELD = "instance_name"
1023
  OP_PARAMS = [
1024
    _PInstanceName,
1025
    _PForce,
1026
    _PIgnoreOfflineNodes,
1027
    ("hvparams", ht.EmptyDict, ht.TDict,
1028
     "Temporary hypervisor parameters, hypervisor-dependent"),
1029
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1030
    _PNoRemember,
1031
    ]
1032

    
1033

    
1034
class OpInstanceShutdown(OpCode):
1035
  """Shutdown an instance."""
1036
  OP_DSC_FIELD = "instance_name"
1037
  OP_PARAMS = [
1038
    _PInstanceName,
1039
    _PIgnoreOfflineNodes,
1040
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1041
     "How long to wait for instance to shut down"),
1042
    _PNoRemember,
1043
    ]
1044

    
1045

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

    
1058

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

    
1074

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

    
1087

    
1088
class OpInstanceMigrate(OpCode):
1089
  """Migrate an instance.
1090

1091
  This migrates (without shutting down an instance) to its secondary
1092
  node.
1093

1094
  @ivar instance_name: the name of the instance
1095
  @ivar mode: the migration mode (live, non-live or None for auto)
1096

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

    
1112

    
1113
class OpInstanceMove(OpCode):
1114
  """Move an instance.
1115

1116
  This move (with shutting down an instance and data copying) to an
1117
  arbitrary node.
1118

1119
  @ivar instance_name: the name of the instance
1120
  @ivar target_node: the destination node
1121

1122
  """
1123
  OP_DSC_FIELD = "instance_name"
1124
  OP_PARAMS = [
1125
    _PInstanceName,
1126
    _PShutdownTimeout,
1127
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1128
    _PIgnoreConsistency,
1129
    ]
1130

    
1131

    
1132
class OpInstanceConsole(OpCode):
1133
  """Connect to an instance's console."""
1134
  OP_DSC_FIELD = "instance_name"
1135
  OP_PARAMS = [
1136
    _PInstanceName
1137
    ]
1138

    
1139

    
1140
class OpInstanceActivateDisks(OpCode):
1141
  """Activate an instance's disks."""
1142
  OP_DSC_FIELD = "instance_name"
1143
  OP_PARAMS = [
1144
    _PInstanceName,
1145
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1146
    ]
1147

    
1148

    
1149
class OpInstanceDeactivateDisks(OpCode):
1150
  """Deactivate an instance's disks."""
1151
  OP_DSC_FIELD = "instance_name"
1152
  OP_PARAMS = [
1153
    _PInstanceName,
1154
    _PForce,
1155
    ]
1156

    
1157

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

    
1169

    
1170
class OpInstanceQuery(OpCode):
1171
  """Compute the list of instances."""
1172
  OP_PARAMS = [
1173
    _POutputFields,
1174
    _PUseLocking,
1175
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1176
     "Empty list to query all instances, instance names otherwise"),
1177
    ]
1178

    
1179

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

    
1191

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

    
1221

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

    
1233

    
1234
# Node group opcodes
1235

    
1236
class OpGroupAdd(OpCode):
1237
  """Add a node group to the cluster."""
1238
  OP_DSC_FIELD = "group_name"
1239
  OP_PARAMS = [
1240
    _PGroupName,
1241
    _PNodeGroupAllocPolicy,
1242
    _PGroupNodeParams,
1243
    ]
1244

    
1245

    
1246
class OpGroupAssignNodes(OpCode):
1247
  """Assign nodes to a node group."""
1248
  OP_DSC_FIELD = "group_name"
1249
  OP_PARAMS = [
1250
    _PGroupName,
1251
    _PForce,
1252
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1253
     "List of nodes to assign"),
1254
    ]
1255

    
1256

    
1257
class OpGroupQuery(OpCode):
1258
  """Compute the list of node groups."""
1259
  OP_PARAMS = [
1260
    _POutputFields,
1261
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1262
     "Empty list to query all groups, group names otherwise"),
1263
    ]
1264

    
1265

    
1266
class OpGroupSetParams(OpCode):
1267
  """Change the parameters of a node group."""
1268
  OP_DSC_FIELD = "group_name"
1269
  OP_PARAMS = [
1270
    _PGroupName,
1271
    _PNodeGroupAllocPolicy,
1272
    _PGroupNodeParams,
1273
    ]
1274

    
1275

    
1276
class OpGroupRemove(OpCode):
1277
  """Remove a node group from the cluster."""
1278
  OP_DSC_FIELD = "group_name"
1279
  OP_PARAMS = [
1280
    _PGroupName,
1281
    ]
1282

    
1283

    
1284
class OpGroupRename(OpCode):
1285
  """Rename a node group in the cluster."""
1286
  OP_PARAMS = [
1287
    _PGroupName,
1288
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1289
    ]
1290

    
1291

    
1292
# OS opcodes
1293
class OpOsDiagnose(OpCode):
1294
  """Compute the list of guest operating systems."""
1295
  OP_PARAMS = [
1296
    _POutputFields,
1297
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1298
     "Which operating systems to diagnose"),
1299
    ]
1300

    
1301

    
1302
# Exports opcodes
1303
class OpBackupQuery(OpCode):
1304
  """Compute the list of exported images."""
1305
  OP_PARAMS = [
1306
    _PUseLocking,
1307
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1308
     "Empty list to query all nodes, node names otherwise"),
1309
    ]
1310

    
1311

    
1312
class OpBackupPrepare(OpCode):
1313
  """Prepares an instance export.
1314

1315
  @ivar instance_name: Instance name
1316
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1317

1318
  """
1319
  OP_DSC_FIELD = "instance_name"
1320
  OP_PARAMS = [
1321
    _PInstanceName,
1322
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1323
     "Export mode"),
1324
    ]
1325

    
1326

    
1327
class OpBackupExport(OpCode):
1328
  """Export an instance.
1329

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

1336
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1337
  @ivar target_node: Export destination
1338
  @ivar x509_key_name: X509 key to use (remote export only)
1339
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1340
                             only)
1341

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

    
1364

    
1365
class OpBackupRemove(OpCode):
1366
  """Remove an instance's export."""
1367
  OP_DSC_FIELD = "instance_name"
1368
  OP_PARAMS = [
1369
    _PInstanceName,
1370
    ]
1371

    
1372

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

    
1383

    
1384
class OpTagsSearch(OpCode):
1385
  """Searches the tags in the cluster for a given pattern."""
1386
  OP_DSC_FIELD = "pattern"
1387
  OP_PARAMS = [
1388
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1389
    ]
1390

    
1391

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

    
1401

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

    
1411
# Test opcodes
1412
class OpTestDelay(OpCode):
1413
  """Sleeps for a configured amount of time.
1414

1415
  This is used just for debugging and testing.
1416

1417
  Parameters:
1418
    - duration: the time to sleep
1419
    - on_master: if true, sleep on the master
1420
    - on_nodes: list of nodes in which to sleep
1421

1422
  If the on_master parameter is true, it will execute a sleep on the
1423
  master (before any node sleep).
1424

1425
  If the on_nodes list is not empty, it will sleep on those nodes
1426
  (after the sleep on the master, if that is enabled).
1427

1428
  As an additional feature, the case of duration < 0 will be reported
1429
  as an execution error, so this opcode can be used as a failure
1430
  generator. The case of duration == 0 will not be treated specially.
1431

1432
  """
1433
  OP_DSC_FIELD = "duration"
1434
  OP_PARAMS = [
1435
    ("duration", ht.NoDefault, ht.TFloat, None),
1436
    ("on_master", True, ht.TBool, None),
1437
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1438
    ("repeat", 0, ht.TPositiveInt, None),
1439
    ]
1440

    
1441

    
1442
class OpTestAllocator(OpCode):
1443
  """Allocator framework testing.
1444

1445
  This opcode has two modes:
1446
    - gather and return allocator input for a given mode (allocate new
1447
      or replace secondary) and a given instance definition (direction
1448
      'in')
1449
    - run a selected allocator for a given operation (as above) and
1450
      return the allocator output (direction 'out')
1451

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

    
1480

    
1481
class OpTestJqueue(OpCode):
1482
  """Utility opcode to test some aspects of the job queue.
1483

1484
  """
1485
  OP_PARAMS = [
1486
    ("notify_waitlock", False, ht.TBool, None),
1487
    ("notify_exec", False, ht.TBool, None),
1488
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1489
    ("fail", False, ht.TBool, None),
1490
    ]
1491

    
1492

    
1493
class OpTestDummy(OpCode):
1494
  """Utility opcode used by unittests.
1495

1496
  """
1497
  OP_PARAMS = [
1498
    ("result", ht.NoDefault, ht.NoType, None),
1499
    ("messages", ht.NoDefault, ht.NoType, None),
1500
    ("fail", ht.NoDefault, ht.NoType, None),
1501
    ("submit_jobs", None, ht.NoType, None),
1502
    ]
1503
  WITH_LU = False
1504

    
1505

    
1506
def _GetOpList():
1507
  """Returns list of all defined opcodes.
1508

1509
  Does not eliminate duplicates by C{OP_ID}.
1510

1511
  """
1512
  return [v for v in globals().values()
1513
          if (isinstance(v, type) and issubclass(v, OpCode) and
1514
              hasattr(v, "OP_ID") and v is not OpCode)]
1515

    
1516

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