Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 3aa8ed2b

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
_PStartupPaused = ("startup_paused", False, ht.TBool,
129
                   "Pause instance at startup")
130

    
131

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

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

    
141

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

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

    
154

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

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

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

    
175

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

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

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

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

    
189

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

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

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

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

    
203

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

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

    
215

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

    
219

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

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

    
231

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

    
236

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

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

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

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

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

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

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

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

    
266
    attrs["__slots__"] = slots
267

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

    
270

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
392

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

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

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

412
  """
413
  # pylint: disable-msg=E1101
414
  # as OP_ID is dynamically defined
415
  WITH_LU = True
416
  _T_JOB_DEP = \
417
    ht.TAnd(ht.TIsLength(2),
418
            ht.TItems([ht.TJobId,
419
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
420
  OP_PARAMS = [
421
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
422
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
423
    ("priority", constants.OP_PRIO_DEFAULT,
424
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
425
    ("depends", None, ht.TOr(ht.TNone, ht.TListOf(_T_JOB_DEP)),
426
     "Job dependencies"),
427
    ]
428

    
429
  def __getstate__(self):
430
    """Specialized getstate for opcodes.
431

432
    This method adds to the state dictionary the OP_ID of the class,
433
    so that on unload we can identify the correct class for
434
    instantiating the opcode.
435

436
    @rtype:   C{dict}
437
    @return:  the state as a dictionary
438

439
    """
440
    data = BaseOpCode.__getstate__(self)
441
    data["OP_ID"] = self.OP_ID
442
    return data
443

    
444
  @classmethod
445
  def LoadOpCode(cls, data):
446
    """Generic load opcode method.
447

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

452
    @type data:  C{dict}
453
    @param data: the serialized opcode
454

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

    
473
  def Summary(self):
474
    """Generates a summary description of this opcode.
475

476
    The summary is the value of the OP_ID attribute (without the "OP_"
477
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
478
    defined; this field should allow to easily identify the operation
479
    (for an instance creation job, e.g., it would be the instance
480
    name).
481

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

    
494
  def TinySummary(self):
495
    """Generates a compact summary description of the opcode.
496

497
    """
498
    assert self.OP_ID.startswith("OP_")
499

    
500
    text = self.OP_ID[3:]
501

    
502
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
503
      if text.startswith(prefix):
504
        return supplement + text[len(prefix):]
505

    
506
    return text
507

    
508

    
509
# cluster opcodes
510

    
511
class OpClusterPostInit(OpCode):
512
  """Post cluster initialization.
513

514
  This opcode does not touch the cluster at all. Its purpose is to run hooks
515
  after the cluster has been initialized.
516

517
  """
518

    
519

    
520
class OpClusterDestroy(OpCode):
521
  """Destroy the cluster.
522

523
  This opcode has no other parameters. All the state is irreversibly
524
  lost after the execution of this opcode.
525

526
  """
527

    
528

    
529
class OpClusterQuery(OpCode):
530
  """Query cluster information."""
531

    
532

    
533
class OpClusterVerifyConfig(OpCode):
534
  """Verify the cluster config.
535

536
  """
537
  OP_PARAMS = [
538
    ("verbose", False, ht.TBool, None),
539
    ("error_codes", False, ht.TBool, None),
540
    ("debug_simulate_errors", False, ht.TBool, None),
541
    ]
542

    
543

    
544
class OpClusterVerifyGroup(OpCode):
545
  """Run verify on a node group from the cluster.
546

547
  @type skip_checks: C{list}
548
  @ivar skip_checks: steps to be skipped from the verify process; this
549
                     needs to be a subset of
550
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
551
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
552

553
  """
554
  OP_DSC_FIELD = "group_name"
555
  OP_PARAMS = [
556
    ("group_name", ht.NoDefault, ht.TNonEmptyString, None),
557
    ("skip_checks", ht.EmptyList,
558
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
559
    ("verbose", False, ht.TBool, None),
560
    ("error_codes", False, ht.TBool, None),
561
    ("debug_simulate_errors", False, ht.TBool, None),
562
    ]
563

    
564

    
565
class OpClusterVerifyDisks(OpCode):
566
  """Verify the cluster disks.
567

568
  Parameters: none
569

570
  Result: a tuple of four elements:
571
    - list of node names with bad data returned (unreachable, etc.)
572
    - dict of node names with broken volume groups (values: error msg)
573
    - list of instances with degraded disks (that should be activated)
574
    - dict of instances with missing logical volumes (values: (node, vol)
575
      pairs with details about the missing volumes)
576

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

582
  Note that only instances that are drbd-based are taken into
583
  consideration. This might need to be revisited in the future.
584

585
  """
586

    
587

    
588
class OpClusterRepairDiskSizes(OpCode):
589
  """Verify the disk sizes of the instances and fixes configuration
590
  mimatches.
591

592
  Parameters: optional instances list, in case we want to restrict the
593
  checks to only a subset of the instances.
594

595
  Result: a list of tuples, (instance, disk, new-size) for changed
596
  configurations.
597

598
  In normal operation, the list should be empty.
599

600
  @type instances: list
601
  @ivar instances: the list of instances to check, or empty for all instances
602

603
  """
604
  OP_PARAMS = [
605
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
606
    ]
607

    
608

    
609
class OpClusterConfigQuery(OpCode):
610
  """Query cluster configuration values."""
611
  OP_PARAMS = [
612
    _POutputFields
613
    ]
614

    
615

    
616
class OpClusterRename(OpCode):
617
  """Rename the cluster.
618

619
  @type name: C{str}
620
  @ivar name: The new name of the cluster. The name and/or the master IP
621
              address will be changed to match the new name and its IP
622
              address.
623

624
  """
625
  OP_DSC_FIELD = "name"
626
  OP_PARAMS = [
627
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
628
    ]
629

    
630

    
631
class OpClusterSetParams(OpCode):
632
  """Change the parameters of the cluster.
633

634
  @type vg_name: C{str} or C{None}
635
  @ivar vg_name: The new volume group name or None to disable LVM usage.
636

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

    
689

    
690
class OpClusterRedistConf(OpCode):
691
  """Force a full push of the cluster configuration.
692

693
  """
694

    
695

    
696
class OpQuery(OpCode):
697
  """Query for resources/items.
698

699
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
700
  @ivar fields: List of fields to retrieve
701
  @ivar filter: Query filter
702

703
  """
704
  OP_PARAMS = [
705
    _PQueryWhat,
706
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
707
     "Requested fields"),
708
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
709
     "Query filter"),
710
    ]
711

    
712

    
713
class OpQueryFields(OpCode):
714
  """Query for available resource/item fields.
715

716
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
717
  @ivar fields: List of fields to retrieve
718

719
  """
720
  OP_PARAMS = [
721
    _PQueryWhat,
722
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
723
     "Requested fields; if not given, all are returned"),
724
    ]
725

    
726

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

    
742

    
743
# node opcodes
744

    
745
class OpNodeRemove(OpCode):
746
  """Remove a node.
747

748
  @type node_name: C{str}
749
  @ivar node_name: The name of the node to remove. If the node still has
750
                   instances on it, the operation will fail.
751

752
  """
753
  OP_DSC_FIELD = "node_name"
754
  OP_PARAMS = [
755
    _PNodeName,
756
    ]
757

    
758

    
759
class OpNodeAdd(OpCode):
760
  """Add a node to the cluster.
761

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

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

    
801

    
802
class OpNodeQuery(OpCode):
803
  """Compute the list of nodes."""
804
  OP_PARAMS = [
805
    _POutputFields,
806
    _PUseLocking,
807
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
808
     "Empty list to query all nodes, node names otherwise"),
809
    ]
810

    
811

    
812
class OpNodeQueryvols(OpCode):
813
  """Get list of volumes on node."""
814
  OP_PARAMS = [
815
    _POutputFields,
816
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
817
     "Empty list to query all nodes, node names otherwise"),
818
    ]
819

    
820

    
821
class OpNodeQueryStorage(OpCode):
822
  """Get information on storage for node(s)."""
823
  OP_PARAMS = [
824
    _POutputFields,
825
    _PStorageType,
826
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
827
    ("name", None, ht.TMaybeString, "Storage name"),
828
    ]
829

    
830

    
831
class OpNodeModifyStorage(OpCode):
832
  """Modifies the properies of a storage unit"""
833
  OP_PARAMS = [
834
    _PNodeName,
835
    _PStorageType,
836
    _PStorageName,
837
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
838
    ]
839

    
840

    
841
class OpRepairNodeStorage(OpCode):
842
  """Repairs the volume group on a node."""
843
  OP_DSC_FIELD = "node_name"
844
  OP_PARAMS = [
845
    _PNodeName,
846
    _PStorageType,
847
    _PStorageName,
848
    _PIgnoreConsistency,
849
    ]
850

    
851

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

    
877

    
878
class OpNodePowercycle(OpCode):
879
  """Tries to powercycle a node."""
880
  OP_DSC_FIELD = "node_name"
881
  OP_PARAMS = [
882
    _PNodeName,
883
    _PForce,
884
    ]
885

    
886

    
887
class OpNodeMigrate(OpCode):
888
  """Migrate all instances from a node."""
889
  OP_DSC_FIELD = "node_name"
890
  OP_PARAMS = [
891
    _PNodeName,
892
    _PMigrationMode,
893
    _PMigrationLive,
894
    _PMigrationTargetNode,
895
    ("iallocator", None, ht.TMaybeString,
896
     "Iallocator for deciding the target node for shared-storage instances"),
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
    _PStartupPaused,
1032
    ]
1033

    
1034

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

    
1046

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

    
1059

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

    
1075

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

    
1088

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

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

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

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

    
1113

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

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

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

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

    
1132

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

    
1140

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

    
1149

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

    
1158

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

    
1170

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

    
1180

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

    
1192

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

    
1222

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

    
1234

    
1235
# Node group opcodes
1236

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

    
1246

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

    
1257

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

    
1266

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

    
1276

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

    
1284

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

    
1292

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

    
1302

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

    
1312

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

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

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

    
1327

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

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

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

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

    
1365

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

    
1373

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

    
1384

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

    
1392

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

    
1402

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

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

1416
  This is used just for debugging and testing.
1417

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

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

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

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

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

    
1442

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

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

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

    
1481

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

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

    
1493

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

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

    
1506

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

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

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

    
1517

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