Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 21d70642

History | View | Annotate | Download (46.5 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 OpNodeEvacuate(OpCode):
891
  """Evacuate instances off a number of nodes."""
892
  OP_DSC_FIELD = "node_name"
893
  OP_PARAMS = [
894
    _PEarlyRelease,
895
    _PNodeName,
896
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
897
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
898
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
899
     "Node evacuation mode"),
900
    ]
901

    
902

    
903
# instance opcodes
904

    
905
class OpInstanceCreate(OpCode):
906
  """Create an instance.
907

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

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

    
977

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

    
988

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

    
999

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

    
1009

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

    
1023

    
1024
class OpInstanceShutdown(OpCode):
1025
  """Shutdown an instance."""
1026
  OP_DSC_FIELD = "instance_name"
1027
  OP_PARAMS = [
1028
    _PInstanceName,
1029
    _PIgnoreOfflineNodes,
1030
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1031
     "How long to wait for instance to shut down"),
1032
    _PNoRemember,
1033
    ]
1034

    
1035

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

    
1048

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

    
1064

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

    
1077

    
1078
class OpInstanceMigrate(OpCode):
1079
  """Migrate an instance.
1080

1081
  This migrates (without shutting down an instance) to its secondary
1082
  node.
1083

1084
  @ivar instance_name: the name of the instance
1085
  @ivar mode: the migration mode (live, non-live or None for auto)
1086

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

    
1102

    
1103
class OpInstanceMove(OpCode):
1104
  """Move an instance.
1105

1106
  This move (with shutting down an instance and data copying) to an
1107
  arbitrary node.
1108

1109
  @ivar instance_name: the name of the instance
1110
  @ivar target_node: the destination node
1111

1112
  """
1113
  OP_DSC_FIELD = "instance_name"
1114
  OP_PARAMS = [
1115
    _PInstanceName,
1116
    _PShutdownTimeout,
1117
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1118
    _PIgnoreConsistency,
1119
    ]
1120

    
1121

    
1122
class OpInstanceConsole(OpCode):
1123
  """Connect to an instance's console."""
1124
  OP_DSC_FIELD = "instance_name"
1125
  OP_PARAMS = [
1126
    _PInstanceName
1127
    ]
1128

    
1129

    
1130
class OpInstanceActivateDisks(OpCode):
1131
  """Activate an instance's disks."""
1132
  OP_DSC_FIELD = "instance_name"
1133
  OP_PARAMS = [
1134
    _PInstanceName,
1135
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1136
    ]
1137

    
1138

    
1139
class OpInstanceDeactivateDisks(OpCode):
1140
  """Deactivate an instance's disks."""
1141
  OP_DSC_FIELD = "instance_name"
1142
  OP_PARAMS = [
1143
    _PInstanceName,
1144
    _PForce,
1145
    ]
1146

    
1147

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

    
1159

    
1160
class OpInstanceQuery(OpCode):
1161
  """Compute the list of instances."""
1162
  OP_PARAMS = [
1163
    _POutputFields,
1164
    _PUseLocking,
1165
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1166
     "Empty list to query all instances, instance names otherwise"),
1167
    ]
1168

    
1169

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

    
1181

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

    
1211

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

    
1223

    
1224
# Node group opcodes
1225

    
1226
class OpGroupAdd(OpCode):
1227
  """Add a node group to the cluster."""
1228
  OP_DSC_FIELD = "group_name"
1229
  OP_PARAMS = [
1230
    _PGroupName,
1231
    _PNodeGroupAllocPolicy,
1232
    _PGroupNodeParams,
1233
    ]
1234

    
1235

    
1236
class OpGroupAssignNodes(OpCode):
1237
  """Assign nodes to a node group."""
1238
  OP_DSC_FIELD = "group_name"
1239
  OP_PARAMS = [
1240
    _PGroupName,
1241
    _PForce,
1242
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1243
     "List of nodes to assign"),
1244
    ]
1245

    
1246

    
1247
class OpGroupQuery(OpCode):
1248
  """Compute the list of node groups."""
1249
  OP_PARAMS = [
1250
    _POutputFields,
1251
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1252
     "Empty list to query all groups, group names otherwise"),
1253
    ]
1254

    
1255

    
1256
class OpGroupSetParams(OpCode):
1257
  """Change the parameters of a node group."""
1258
  OP_DSC_FIELD = "group_name"
1259
  OP_PARAMS = [
1260
    _PGroupName,
1261
    _PNodeGroupAllocPolicy,
1262
    _PGroupNodeParams,
1263
    ]
1264

    
1265

    
1266
class OpGroupRemove(OpCode):
1267
  """Remove a node group from the cluster."""
1268
  OP_DSC_FIELD = "group_name"
1269
  OP_PARAMS = [
1270
    _PGroupName,
1271
    ]
1272

    
1273

    
1274
class OpGroupRename(OpCode):
1275
  """Rename a node group in the cluster."""
1276
  OP_PARAMS = [
1277
    _PGroupName,
1278
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1279
    ]
1280

    
1281

    
1282
# OS opcodes
1283
class OpOsDiagnose(OpCode):
1284
  """Compute the list of guest operating systems."""
1285
  OP_PARAMS = [
1286
    _POutputFields,
1287
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1288
     "Which operating systems to diagnose"),
1289
    ]
1290

    
1291

    
1292
# Exports opcodes
1293
class OpBackupQuery(OpCode):
1294
  """Compute the list of exported images."""
1295
  OP_PARAMS = [
1296
    _PUseLocking,
1297
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1298
     "Empty list to query all nodes, node names otherwise"),
1299
    ]
1300

    
1301

    
1302
class OpBackupPrepare(OpCode):
1303
  """Prepares an instance export.
1304

1305
  @ivar instance_name: Instance name
1306
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1307

1308
  """
1309
  OP_DSC_FIELD = "instance_name"
1310
  OP_PARAMS = [
1311
    _PInstanceName,
1312
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1313
     "Export mode"),
1314
    ]
1315

    
1316

    
1317
class OpBackupExport(OpCode):
1318
  """Export an instance.
1319

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

1326
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1327
  @ivar target_node: Export destination
1328
  @ivar x509_key_name: X509 key to use (remote export only)
1329
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1330
                             only)
1331

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

    
1354

    
1355
class OpBackupRemove(OpCode):
1356
  """Remove an instance's export."""
1357
  OP_DSC_FIELD = "instance_name"
1358
  OP_PARAMS = [
1359
    _PInstanceName,
1360
    ]
1361

    
1362

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

    
1373

    
1374
class OpTagsSearch(OpCode):
1375
  """Searches the tags in the cluster for a given pattern."""
1376
  OP_DSC_FIELD = "pattern"
1377
  OP_PARAMS = [
1378
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1379
    ]
1380

    
1381

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

    
1391

    
1392
class OpTagsDel(OpCode):
1393
  """Remove a list of tags from 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
# Test opcodes
1402
class OpTestDelay(OpCode):
1403
  """Sleeps for a configured amount of time.
1404

1405
  This is used just for debugging and testing.
1406

1407
  Parameters:
1408
    - duration: the time to sleep
1409
    - on_master: if true, sleep on the master
1410
    - on_nodes: list of nodes in which to sleep
1411

1412
  If the on_master parameter is true, it will execute a sleep on the
1413
  master (before any node sleep).
1414

1415
  If the on_nodes list is not empty, it will sleep on those nodes
1416
  (after the sleep on the master, if that is enabled).
1417

1418
  As an additional feature, the case of duration < 0 will be reported
1419
  as an execution error, so this opcode can be used as a failure
1420
  generator. The case of duration == 0 will not be treated specially.
1421

1422
  """
1423
  OP_DSC_FIELD = "duration"
1424
  OP_PARAMS = [
1425
    ("duration", ht.NoDefault, ht.TFloat, None),
1426
    ("on_master", True, ht.TBool, None),
1427
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1428
    ("repeat", 0, ht.TPositiveInt, None),
1429
    ]
1430

    
1431

    
1432
class OpTestAllocator(OpCode):
1433
  """Allocator framework testing.
1434

1435
  This opcode has two modes:
1436
    - gather and return allocator input for a given mode (allocate new
1437
      or replace secondary) and a given instance definition (direction
1438
      'in')
1439
    - run a selected allocator for a given operation (as above) and
1440
      return the allocator output (direction 'out')
1441

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

    
1470

    
1471
class OpTestJqueue(OpCode):
1472
  """Utility opcode to test some aspects of the job queue.
1473

1474
  """
1475
  OP_PARAMS = [
1476
    ("notify_waitlock", False, ht.TBool, None),
1477
    ("notify_exec", False, ht.TBool, None),
1478
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1479
    ("fail", False, ht.TBool, None),
1480
    ]
1481

    
1482

    
1483
class OpTestDummy(OpCode):
1484
  """Utility opcode used by unittests.
1485

1486
  """
1487
  OP_PARAMS = [
1488
    ("result", ht.NoDefault, ht.NoType, None),
1489
    ("messages", ht.NoDefault, ht.NoType, None),
1490
    ("fail", ht.NoDefault, ht.NoType, None),
1491
    ("submit_jobs", None, ht.NoType, None),
1492
    ]
1493
  WITH_LU = False
1494

    
1495

    
1496
def _GetOpList():
1497
  """Returns list of all defined opcodes.
1498

1499
  Does not eliminate duplicates by C{OP_ID}.
1500

1501
  """
1502
  return [v for v in globals().values()
1503
          if (isinstance(v, type) and issubclass(v, OpCode) and
1504
              hasattr(v, "OP_ID") and v is not OpCode)]
1505

    
1506

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