Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ adfa3b26

History | View | Annotate | Download (46.2 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
_PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
116

    
117
#: Do not remember instance state changes
118
_PNoRemember = ("no_remember", False, ht.TBool,
119
                "Do not remember the state change")
120

    
121
#: OP_ID conversion regular expression
122
_OPID_RE = re.compile("([a-z])([A-Z])")
123

    
124
#: Utility function for L{OpClusterSetParams}
125
_TestClusterOsList = ht.TOr(ht.TNone,
126
  ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
127
    ht.TMap(ht.WithDesc("GetFirstItem")(operator.itemgetter(0)),
128
            ht.TElemOf(constants.DDMS_VALUES)))))
129

    
130

    
131
# TODO: Generate check from constants.INIC_PARAMS_TYPES
132
#: Utility function for testing NIC definitions
133
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
134
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
135

    
136
_SUMMARY_PREFIX = {
137
  "CLUSTER_": "C_",
138
  "GROUP_": "G_",
139
  "NODE_": "N_",
140
  "INSTANCE_": "I_",
141
  }
142

    
143

    
144
def _NameToId(name):
145
  """Convert an opcode class name to an OP_ID.
146

147
  @type name: string
148
  @param name: the class name, as OpXxxYyy
149
  @rtype: string
150
  @return: the name in the OP_XXXX_YYYY format
151

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

    
164

    
165
def RequireFileStorage():
166
  """Checks that file storage is enabled.
167

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

171
  @raise errors.OpPrereqError: when file storage is disabled
172

173
  """
174
  if not constants.ENABLE_FILE_STORAGE:
175
    raise errors.OpPrereqError("File storage disabled at configure time",
176
                               errors.ECODE_INVAL)
177

    
178

    
179
def RequireSharedFileStorage():
180
  """Checks that shared file storage is enabled.
181

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

185
  @raise errors.OpPrereqError: when shared file storage is disabled
186

187
  """
188
  if not constants.ENABLE_SHARED_FILE_STORAGE:
189
    raise errors.OpPrereqError("Shared file storage disabled at"
190
                               " configure time", errors.ECODE_INVAL)
191

    
192

    
193
@ht.WithDesc("CheckFileStorage")
194
def _CheckFileStorage(value):
195
  """Ensures file storage is enabled if used.
196

197
  """
198
  if value == constants.DT_FILE:
199
    RequireFileStorage()
200
  elif value == constants.DT_SHARED_FILE:
201
    RequireSharedFileStorage()
202
  return True
203

    
204

    
205
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
206
                             _CheckFileStorage)
207

    
208

    
209
def _CheckStorageType(storage_type):
210
  """Ensure a given storage type is valid.
211

212
  """
213
  if storage_type not in constants.VALID_STORAGE_TYPES:
214
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
215
                               errors.ECODE_INVAL)
216
  if storage_type == constants.ST_FILE:
217
    RequireFileStorage()
218
  return True
219

    
220

    
221
#: Storage type parameter
222
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
223
                 "Storage type")
224

    
225

    
226
class _AutoOpParamSlots(type):
227
  """Meta class for opcode definitions.
228

229
  """
230
  def __new__(mcs, name, bases, attrs):
231
    """Called when a class should be created.
232

233
    @param mcs: The meta class
234
    @param name: Name of created class
235
    @param bases: Base classes
236
    @type attrs: dict
237
    @param attrs: Class attributes
238

239
    """
240
    assert "__slots__" not in attrs, \
241
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
242
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
243

    
244
    attrs["OP_ID"] = _NameToId(name)
245

    
246
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
247
    params = attrs.setdefault("OP_PARAMS", [])
248

    
249
    # Use parameter names as slots
250
    slots = [pname for (pname, _, _, _) in params]
251

    
252
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
253
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
254

    
255
    attrs["__slots__"] = slots
256

    
257
    return type.__new__(mcs, name, bases, attrs)
258

    
259

    
260
class BaseOpCode(object):
261
  """A simple serializable object.
262

263
  This object serves as a parent class for OpCode without any custom
264
  field handling.
265

266
  """
267
  # pylint: disable-msg=E1101
268
  # as OP_ID is dynamically defined
269
  __metaclass__ = _AutoOpParamSlots
270

    
271
  def __init__(self, **kwargs):
272
    """Constructor for BaseOpCode.
273

274
    The constructor takes only keyword arguments and will set
275
    attributes on this object based on the passed arguments. As such,
276
    it means that you should not pass arguments which are not in the
277
    __slots__ attribute for this class.
278

279
    """
280
    slots = self._all_slots()
281
    for key in kwargs:
282
      if key not in slots:
283
        raise TypeError("Object %s doesn't support the parameter '%s'" %
284
                        (self.__class__.__name__, key))
285
      setattr(self, key, kwargs[key])
286

    
287
  def __getstate__(self):
288
    """Generic serializer.
289

290
    This method just returns the contents of the instance as a
291
    dictionary.
292

293
    @rtype:  C{dict}
294
    @return: the instance attributes and their values
295

296
    """
297
    state = {}
298
    for name in self._all_slots():
299
      if hasattr(self, name):
300
        state[name] = getattr(self, name)
301
    return state
302

    
303
  def __setstate__(self, state):
304
    """Generic unserializer.
305

306
    This method just restores from the serialized state the attributes
307
    of the current instance.
308

309
    @param state: the serialized opcode data
310
    @type state:  C{dict}
311

312
    """
313
    if not isinstance(state, dict):
314
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
315
                       type(state))
316

    
317
    for name in self._all_slots():
318
      if name not in state and hasattr(self, name):
319
        delattr(self, name)
320

    
321
    for name in state:
322
      setattr(self, name, state[name])
323

    
324
  @classmethod
325
  def _all_slots(cls):
326
    """Compute the list of all declared slots for a class.
327

328
    """
329
    slots = []
330
    for parent in cls.__mro__:
331
      slots.extend(getattr(parent, "__slots__", []))
332
    return slots
333

    
334
  @classmethod
335
  def GetAllParams(cls):
336
    """Compute list of all parameters for an opcode.
337

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

    
344
  def Validate(self, set_defaults):
345
    """Validate opcode parameters, optionally setting default values.
346

347
    @type set_defaults: bool
348
    @param set_defaults: Whether to set default values
349
    @raise errors.OpPrereqError: When a parameter value doesn't match
350
                                 requirements
351

352
    """
353
    for (attr_name, default, test, _) in self.GetAllParams():
354
      assert test == ht.NoType or callable(test)
355

    
356
      if not hasattr(self, attr_name):
357
        if default == ht.NoDefault:
358
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
359
                                     (self.OP_ID, attr_name),
360
                                     errors.ECODE_INVAL)
361
        elif set_defaults:
362
          if callable(default):
363
            dval = default()
364
          else:
365
            dval = default
366
          setattr(self, attr_name, dval)
367

    
368
      if test == ht.NoType:
369
        # no tests here
370
        continue
371

    
372
      if set_defaults or hasattr(self, attr_name):
373
        attr_val = getattr(self, attr_name)
374
        if not test(attr_val):
375
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
376
                        self.OP_ID, attr_name, type(attr_val), attr_val)
377
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
378
                                     (self.OP_ID, attr_name),
379
                                     errors.ECODE_INVAL)
380

    
381

    
382
class OpCode(BaseOpCode):
383
  """Abstract OpCode.
384

385
  This is the root of the actual OpCode hierarchy. All clases derived
386
  from this class should override OP_ID.
387

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

401
  """
402
  # pylint: disable-msg=E1101
403
  # as OP_ID is dynamically defined
404
  WITH_LU = True
405
  OP_PARAMS = [
406
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
407
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
408
    ("priority", constants.OP_PRIO_DEFAULT,
409
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
410
    ]
411

    
412
  def __getstate__(self):
413
    """Specialized getstate for opcodes.
414

415
    This method adds to the state dictionary the OP_ID of the class,
416
    so that on unload we can identify the correct class for
417
    instantiating the opcode.
418

419
    @rtype:   C{dict}
420
    @return:  the state as a dictionary
421

422
    """
423
    data = BaseOpCode.__getstate__(self)
424
    data["OP_ID"] = self.OP_ID
425
    return data
426

    
427
  @classmethod
428
  def LoadOpCode(cls, data):
429
    """Generic load opcode method.
430

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

435
    @type data:  C{dict}
436
    @param data: the serialized opcode
437

438
    """
439
    if not isinstance(data, dict):
440
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
441
    if "OP_ID" not in data:
442
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
443
    op_id = data["OP_ID"]
444
    op_class = None
445
    if op_id in OP_MAPPING:
446
      op_class = OP_MAPPING[op_id]
447
    else:
448
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
449
                       op_id)
450
    op = op_class()
451
    new_data = data.copy()
452
    del new_data["OP_ID"]
453
    op.__setstate__(new_data)
454
    return op
455

    
456
  def Summary(self):
457
    """Generates a summary description of this opcode.
458

459
    The summary is the value of the OP_ID attribute (without the "OP_"
460
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
461
    defined; this field should allow to easily identify the operation
462
    (for an instance creation job, e.g., it would be the instance
463
    name).
464

465
    """
466
    assert self.OP_ID is not None and len(self.OP_ID) > 3
467
    # all OP_ID start with OP_, we remove that
468
    txt = self.OP_ID[3:]
469
    field_name = getattr(self, "OP_DSC_FIELD", None)
470
    if field_name:
471
      field_value = getattr(self, field_name, None)
472
      if isinstance(field_value, (list, tuple)):
473
        field_value = ",".join(str(i) for i in field_value)
474
      txt = "%s(%s)" % (txt, field_value)
475
    return txt
476

    
477
  def TinySummary(self):
478
    """Generates a compact summary description of the opcode.
479

480
    """
481
    assert self.OP_ID.startswith("OP_")
482

    
483
    text = self.OP_ID[3:]
484

    
485
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
486
      if text.startswith(prefix):
487
        return supplement + text[len(prefix):]
488

    
489
    return text
490

    
491

    
492
# cluster opcodes
493

    
494
class OpClusterPostInit(OpCode):
495
  """Post cluster initialization.
496

497
  This opcode does not touch the cluster at all. Its purpose is to run hooks
498
  after the cluster has been initialized.
499

500
  """
501

    
502

    
503
class OpClusterDestroy(OpCode):
504
  """Destroy the cluster.
505

506
  This opcode has no other parameters. All the state is irreversibly
507
  lost after the execution of this opcode.
508

509
  """
510

    
511

    
512
class OpClusterQuery(OpCode):
513
  """Query cluster information."""
514

    
515

    
516
class OpClusterVerifyConfig(OpCode):
517
  """Verify the cluster config.
518

519
  """
520
  OP_PARAMS = [
521
    ("verbose", False, ht.TBool, None),
522
    ("error_codes", False, ht.TBool, None),
523
    ("debug_simulate_errors", False, ht.TBool, None),
524
    ]
525

    
526

    
527
class OpClusterVerifyGroup(OpCode):
528
  """Run verify on a node group from the cluster.
529

530
  @type skip_checks: C{list}
531
  @ivar skip_checks: steps to be skipped from the verify process; this
532
                     needs to be a subset of
533
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
534
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
535

536
  """
537
  OP_DSC_FIELD = "group_name"
538
  OP_PARAMS = [
539
    ("group_name", ht.NoDefault, ht.TNonEmptyString, None),
540
    ("skip_checks", ht.EmptyList,
541
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
542
    ("verbose", False, ht.TBool, None),
543
    ("error_codes", False, ht.TBool, None),
544
    ("debug_simulate_errors", False, ht.TBool, None),
545
    ]
546

    
547

    
548
class OpClusterVerifyDisks(OpCode):
549
  """Verify the cluster disks.
550

551
  Parameters: none
552

553
  Result: a tuple of four elements:
554
    - list of node names with bad data returned (unreachable, etc.)
555
    - dict of node names with broken volume groups (values: error msg)
556
    - list of instances with degraded disks (that should be activated)
557
    - dict of instances with missing logical volumes (values: (node, vol)
558
      pairs with details about the missing volumes)
559

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

565
  Note that only instances that are drbd-based are taken into
566
  consideration. This might need to be revisited in the future.
567

568
  """
569

    
570

    
571
class OpClusterRepairDiskSizes(OpCode):
572
  """Verify the disk sizes of the instances and fixes configuration
573
  mimatches.
574

575
  Parameters: optional instances list, in case we want to restrict the
576
  checks to only a subset of the instances.
577

578
  Result: a list of tuples, (instance, disk, new-size) for changed
579
  configurations.
580

581
  In normal operation, the list should be empty.
582

583
  @type instances: list
584
  @ivar instances: the list of instances to check, or empty for all instances
585

586
  """
587
  OP_PARAMS = [
588
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
589
    ]
590

    
591

    
592
class OpClusterConfigQuery(OpCode):
593
  """Query cluster configuration values."""
594
  OP_PARAMS = [
595
    _POutputFields
596
    ]
597

    
598

    
599
class OpClusterRename(OpCode):
600
  """Rename the cluster.
601

602
  @type name: C{str}
603
  @ivar name: The new name of the cluster. The name and/or the master IP
604
              address will be changed to match the new name and its IP
605
              address.
606

607
  """
608
  OP_DSC_FIELD = "name"
609
  OP_PARAMS = [
610
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
611
    ]
612

    
613

    
614
class OpClusterSetParams(OpCode):
615
  """Change the parameters of the cluster.
616

617
  @type vg_name: C{str} or C{None}
618
  @ivar vg_name: The new volume group name or None to disable LVM usage.
619

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

    
672

    
673
class OpClusterRedistConf(OpCode):
674
  """Force a full push of the cluster configuration.
675

676
  """
677

    
678

    
679
class OpQuery(OpCode):
680
  """Query for resources/items.
681

682
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
683
  @ivar fields: List of fields to retrieve
684
  @ivar filter: Query filter
685

686
  """
687
  OP_PARAMS = [
688
    _PQueryWhat,
689
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
690
     "Requested fields"),
691
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
692
     "Query filter"),
693
    ]
694

    
695

    
696
class OpQueryFields(OpCode):
697
  """Query for available resource/item fields.
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

702
  """
703
  OP_PARAMS = [
704
    _PQueryWhat,
705
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
706
     "Requested fields; if not given, all are returned"),
707
    ]
708

    
709

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

    
725

    
726
# node opcodes
727

    
728
class OpNodeRemove(OpCode):
729
  """Remove a node.
730

731
  @type node_name: C{str}
732
  @ivar node_name: The name of the node to remove. If the node still has
733
                   instances on it, the operation will fail.
734

735
  """
736
  OP_DSC_FIELD = "node_name"
737
  OP_PARAMS = [
738
    _PNodeName,
739
    ]
740

    
741

    
742
class OpNodeAdd(OpCode):
743
  """Add a node to the cluster.
744

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

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

    
784

    
785
class OpNodeQuery(OpCode):
786
  """Compute the list of nodes."""
787
  OP_PARAMS = [
788
    _POutputFields,
789
    _PUseLocking,
790
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
791
     "Empty list to query all nodes, node names otherwise"),
792
    ]
793

    
794

    
795
class OpNodeQueryvols(OpCode):
796
  """Get list of volumes on node."""
797
  OP_PARAMS = [
798
    _POutputFields,
799
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
800
     "Empty list to query all nodes, node names otherwise"),
801
    ]
802

    
803

    
804
class OpNodeQueryStorage(OpCode):
805
  """Get information on storage for node(s)."""
806
  OP_PARAMS = [
807
    _POutputFields,
808
    _PStorageType,
809
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
810
    ("name", None, ht.TMaybeString, "Storage name"),
811
    ]
812

    
813

    
814
class OpNodeModifyStorage(OpCode):
815
  """Modifies the properies of a storage unit"""
816
  OP_PARAMS = [
817
    _PNodeName,
818
    _PStorageType,
819
    _PStorageName,
820
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
821
    ]
822

    
823

    
824
class OpRepairNodeStorage(OpCode):
825
  """Repairs the volume group on a node."""
826
  OP_DSC_FIELD = "node_name"
827
  OP_PARAMS = [
828
    _PNodeName,
829
    _PStorageType,
830
    _PStorageName,
831
    _PIgnoreConsistency,
832
    ]
833

    
834

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

    
860

    
861
class OpNodePowercycle(OpCode):
862
  """Tries to powercycle a node."""
863
  OP_DSC_FIELD = "node_name"
864
  OP_PARAMS = [
865
    _PNodeName,
866
    _PForce,
867
    ]
868

    
869

    
870
class OpNodeMigrate(OpCode):
871
  """Migrate all instances from a node."""
872
  OP_DSC_FIELD = "node_name"
873
  OP_PARAMS = [
874
    _PNodeName,
875
    _PMigrationMode,
876
    _PMigrationLive,
877
    ("iallocator", None, ht.TMaybeString,
878
     "Iallocator for deciding the target node for shared-storage instances"),
879
    ]
880

    
881

    
882
class OpNodeEvacStrategy(OpCode):
883
  """Compute the evacuation strategy for a list of nodes."""
884
  OP_DSC_FIELD = "nodes"
885
  OP_PARAMS = [
886
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None),
887
    ("remote_node", None, ht.TMaybeString, None),
888
    ("iallocator", None, ht.TMaybeString, None),
889
    ]
890

    
891

    
892
# instance opcodes
893

    
894
class OpInstanceCreate(OpCode):
895
  """Create an instance.
896

897
  @ivar instance_name: Instance name
898
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
899
  @ivar source_handshake: Signed handshake from source (remote import only)
900
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
901
  @ivar source_instance_name: Previous name of instance (remote import only)
902
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
903
    (remote import only)
904

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

    
965

    
966
class OpInstanceReinstall(OpCode):
967
  """Reinstall an instance's OS."""
968
  OP_DSC_FIELD = "instance_name"
969
  OP_PARAMS = [
970
    _PInstanceName,
971
    _PForceVariant,
972
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
973
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
974
    ]
975

    
976

    
977
class OpInstanceRemove(OpCode):
978
  """Remove an instance."""
979
  OP_DSC_FIELD = "instance_name"
980
  OP_PARAMS = [
981
    _PInstanceName,
982
    _PShutdownTimeout,
983
    ("ignore_failures", False, ht.TBool,
984
     "Whether to ignore failures during removal"),
985
    ]
986

    
987

    
988
class OpInstanceRename(OpCode):
989
  """Rename an instance."""
990
  OP_PARAMS = [
991
    _PInstanceName,
992
    _PNameCheck,
993
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
994
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
995
    ]
996

    
997

    
998
class OpInstanceStartup(OpCode):
999
  """Startup an instance."""
1000
  OP_DSC_FIELD = "instance_name"
1001
  OP_PARAMS = [
1002
    _PInstanceName,
1003
    _PForce,
1004
    _PIgnoreOfflineNodes,
1005
    ("hvparams", ht.EmptyDict, ht.TDict,
1006
     "Temporary hypervisor parameters, hypervisor-dependent"),
1007
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1008
    _PNoRemember,
1009
    ]
1010

    
1011

    
1012
class OpInstanceShutdown(OpCode):
1013
  """Shutdown an instance."""
1014
  OP_DSC_FIELD = "instance_name"
1015
  OP_PARAMS = [
1016
    _PInstanceName,
1017
    _PIgnoreOfflineNodes,
1018
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1019
     "How long to wait for instance to shut down"),
1020
    _PNoRemember,
1021
    ]
1022

    
1023

    
1024
class OpInstanceReboot(OpCode):
1025
  """Reboot an instance."""
1026
  OP_DSC_FIELD = "instance_name"
1027
  OP_PARAMS = [
1028
    _PInstanceName,
1029
    _PShutdownTimeout,
1030
    ("ignore_secondaries", False, ht.TBool,
1031
     "Whether to start the instance even if secondary disks are failing"),
1032
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1033
     "How to reboot instance"),
1034
    ]
1035

    
1036

    
1037
class OpInstanceReplaceDisks(OpCode):
1038
  """Replace the disks of an instance."""
1039
  OP_DSC_FIELD = "instance_name"
1040
  OP_PARAMS = [
1041
    _PInstanceName,
1042
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1043
     "Replacement mode"),
1044
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1045
     "Disk indexes"),
1046
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1047
    ("iallocator", None, ht.TMaybeString,
1048
     "Iallocator for deciding new secondary node"),
1049
    ("early_release", False, ht.TBool,
1050
     "Whether to release locks as soon as possible"),
1051
    ]
1052

    
1053

    
1054
class OpInstanceFailover(OpCode):
1055
  """Failover an instance."""
1056
  OP_DSC_FIELD = "instance_name"
1057
  OP_PARAMS = [
1058
    _PInstanceName,
1059
    _PShutdownTimeout,
1060
    _PIgnoreConsistency,
1061
    ("iallocator", None, ht.TMaybeString,
1062
     "Iallocator for deciding the target node for shared-storage instances"),
1063
    ("target_node", None, ht.TMaybeString,
1064
     "Target node for shared-storage instances"),
1065
    ]
1066

    
1067

    
1068
class OpInstanceMigrate(OpCode):
1069
  """Migrate an instance.
1070

1071
  This migrates (without shutting down an instance) to its secondary
1072
  node.
1073

1074
  @ivar instance_name: the name of the instance
1075
  @ivar mode: the migration mode (live, non-live or None for auto)
1076

1077
  """
1078
  OP_DSC_FIELD = "instance_name"
1079
  OP_PARAMS = [
1080
    _PInstanceName,
1081
    _PMigrationMode,
1082
    _PMigrationLive,
1083
    ("cleanup", False, ht.TBool,
1084
     "Whether a previously failed migration should be cleaned up"),
1085
    ("iallocator", None, ht.TMaybeString,
1086
     "Iallocator for deciding the target node for shared-storage instances"),
1087
    ("target_node", None, ht.TMaybeString,
1088
     "Target node for shared-storage instances"),
1089
    ("allow_failover", False, ht.TBool,
1090
     "Whether we can fallback to failover if migration is not possible"),
1091
    ]
1092

    
1093

    
1094
class OpInstanceMove(OpCode):
1095
  """Move an instance.
1096

1097
  This move (with shutting down an instance and data copying) to an
1098
  arbitrary node.
1099

1100
  @ivar instance_name: the name of the instance
1101
  @ivar target_node: the destination node
1102

1103
  """
1104
  OP_DSC_FIELD = "instance_name"
1105
  OP_PARAMS = [
1106
    _PInstanceName,
1107
    _PShutdownTimeout,
1108
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1109
    _PIgnoreConsistency,
1110
    ]
1111

    
1112

    
1113
class OpInstanceConsole(OpCode):
1114
  """Connect to an instance's console."""
1115
  OP_DSC_FIELD = "instance_name"
1116
  OP_PARAMS = [
1117
    _PInstanceName
1118
    ]
1119

    
1120

    
1121
class OpInstanceActivateDisks(OpCode):
1122
  """Activate an instance's disks."""
1123
  OP_DSC_FIELD = "instance_name"
1124
  OP_PARAMS = [
1125
    _PInstanceName,
1126
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1127
    ]
1128

    
1129

    
1130
class OpInstanceDeactivateDisks(OpCode):
1131
  """Deactivate an instance's disks."""
1132
  OP_DSC_FIELD = "instance_name"
1133
  OP_PARAMS = [
1134
    _PInstanceName,
1135
    _PForce,
1136
    ]
1137

    
1138

    
1139
class OpInstanceRecreateDisks(OpCode):
1140
  """Deactivate an instance's disks."""
1141
  OP_DSC_FIELD = "instance_name"
1142
  OP_PARAMS = [
1143
    _PInstanceName,
1144
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1145
     "List of disk indexes"),
1146
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1147
     "New instance nodes, if relocation is desired"),
1148
    ]
1149

    
1150

    
1151
class OpInstanceQuery(OpCode):
1152
  """Compute the list of instances."""
1153
  OP_PARAMS = [
1154
    _POutputFields,
1155
    _PUseLocking,
1156
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1157
     "Empty list to query all instances, instance names otherwise"),
1158
    ]
1159

    
1160

    
1161
class OpInstanceQueryData(OpCode):
1162
  """Compute the run-time status of instances."""
1163
  OP_PARAMS = [
1164
    _PUseLocking,
1165
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1166
     "Instance names"),
1167
    ("static", False, ht.TBool,
1168
     "Whether to only return configuration data without querying"
1169
     " nodes"),
1170
    ]
1171

    
1172

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

    
1202

    
1203
class OpInstanceGrowDisk(OpCode):
1204
  """Grow a disk of an instance."""
1205
  OP_DSC_FIELD = "instance_name"
1206
  OP_PARAMS = [
1207
    _PInstanceName,
1208
    _PWaitForSync,
1209
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1210
    ("amount", ht.NoDefault, ht.TInt,
1211
     "Amount of disk space to add (megabytes)"),
1212
    ]
1213

    
1214

    
1215
# Node group opcodes
1216

    
1217
class OpGroupAdd(OpCode):
1218
  """Add a node group to the cluster."""
1219
  OP_DSC_FIELD = "group_name"
1220
  OP_PARAMS = [
1221
    _PGroupName,
1222
    _PNodeGroupAllocPolicy,
1223
    _PGroupNodeParams,
1224
    ]
1225

    
1226

    
1227
class OpGroupAssignNodes(OpCode):
1228
  """Assign nodes to a node group."""
1229
  OP_DSC_FIELD = "group_name"
1230
  OP_PARAMS = [
1231
    _PGroupName,
1232
    _PForce,
1233
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1234
     "List of nodes to assign"),
1235
    ]
1236

    
1237

    
1238
class OpGroupQuery(OpCode):
1239
  """Compute the list of node groups."""
1240
  OP_PARAMS = [
1241
    _POutputFields,
1242
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1243
     "Empty list to query all groups, group names otherwise"),
1244
    ]
1245

    
1246

    
1247
class OpGroupSetParams(OpCode):
1248
  """Change the parameters of a node group."""
1249
  OP_DSC_FIELD = "group_name"
1250
  OP_PARAMS = [
1251
    _PGroupName,
1252
    _PNodeGroupAllocPolicy,
1253
    _PGroupNodeParams,
1254
    ]
1255

    
1256

    
1257
class OpGroupRemove(OpCode):
1258
  """Remove a node group from the cluster."""
1259
  OP_DSC_FIELD = "group_name"
1260
  OP_PARAMS = [
1261
    _PGroupName,
1262
    ]
1263

    
1264

    
1265
class OpGroupRename(OpCode):
1266
  """Rename a node group in the cluster."""
1267
  OP_PARAMS = [
1268
    _PGroupName,
1269
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1270
    ]
1271

    
1272

    
1273
# OS opcodes
1274
class OpOsDiagnose(OpCode):
1275
  """Compute the list of guest operating systems."""
1276
  OP_PARAMS = [
1277
    _POutputFields,
1278
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1279
     "Which operating systems to diagnose"),
1280
    ]
1281

    
1282

    
1283
# Exports opcodes
1284
class OpBackupQuery(OpCode):
1285
  """Compute the list of exported images."""
1286
  OP_PARAMS = [
1287
    _PUseLocking,
1288
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1289
     "Empty list to query all nodes, node names otherwise"),
1290
    ]
1291

    
1292

    
1293
class OpBackupPrepare(OpCode):
1294
  """Prepares an instance export.
1295

1296
  @ivar instance_name: Instance name
1297
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1298

1299
  """
1300
  OP_DSC_FIELD = "instance_name"
1301
  OP_PARAMS = [
1302
    _PInstanceName,
1303
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1304
     "Export mode"),
1305
    ]
1306

    
1307

    
1308
class OpBackupExport(OpCode):
1309
  """Export an instance.
1310

1311
  For local exports, the export destination is the node name. For remote
1312
  exports, the export destination is a list of tuples, each consisting of
1313
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1314
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1315
  destination X509 CA must be a signed certificate.
1316

1317
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1318
  @ivar target_node: Export destination
1319
  @ivar x509_key_name: X509 key to use (remote export only)
1320
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1321
                             only)
1322

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

    
1345

    
1346
class OpBackupRemove(OpCode):
1347
  """Remove an instance's export."""
1348
  OP_DSC_FIELD = "instance_name"
1349
  OP_PARAMS = [
1350
    _PInstanceName,
1351
    ]
1352

    
1353

    
1354
# Tags opcodes
1355
class OpTagsGet(OpCode):
1356
  """Returns the tags of the given object."""
1357
  OP_DSC_FIELD = "name"
1358
  OP_PARAMS = [
1359
    _PTagKind,
1360
    # Name is only meaningful for nodes and instances
1361
    ("name", ht.NoDefault, ht.TMaybeString, None),
1362
    ]
1363

    
1364

    
1365
class OpTagsSearch(OpCode):
1366
  """Searches the tags in the cluster for a given pattern."""
1367
  OP_DSC_FIELD = "pattern"
1368
  OP_PARAMS = [
1369
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1370
    ]
1371

    
1372

    
1373
class OpTagsSet(OpCode):
1374
  """Add a list of tags on a given object."""
1375
  OP_PARAMS = [
1376
    _PTagKind,
1377
    _PTags,
1378
    # Name is only meaningful for nodes and instances
1379
    ("name", ht.NoDefault, ht.TMaybeString, None),
1380
    ]
1381

    
1382

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

    
1392
# Test opcodes
1393
class OpTestDelay(OpCode):
1394
  """Sleeps for a configured amount of time.
1395

1396
  This is used just for debugging and testing.
1397

1398
  Parameters:
1399
    - duration: the time to sleep
1400
    - on_master: if true, sleep on the master
1401
    - on_nodes: list of nodes in which to sleep
1402

1403
  If the on_master parameter is true, it will execute a sleep on the
1404
  master (before any node sleep).
1405

1406
  If the on_nodes list is not empty, it will sleep on those nodes
1407
  (after the sleep on the master, if that is enabled).
1408

1409
  As an additional feature, the case of duration < 0 will be reported
1410
  as an execution error, so this opcode can be used as a failure
1411
  generator. The case of duration == 0 will not be treated specially.
1412

1413
  """
1414
  OP_DSC_FIELD = "duration"
1415
  OP_PARAMS = [
1416
    ("duration", ht.NoDefault, ht.TFloat, None),
1417
    ("on_master", True, ht.TBool, None),
1418
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1419
    ("repeat", 0, ht.TPositiveInt, None),
1420
    ]
1421

    
1422

    
1423
class OpTestAllocator(OpCode):
1424
  """Allocator framework testing.
1425

1426
  This opcode has two modes:
1427
    - gather and return allocator input for a given mode (allocate new
1428
      or replace secondary) and a given instance definition (direction
1429
      'in')
1430
    - run a selected allocator for a given operation (as above) and
1431
      return the allocator output (direction 'out')
1432

1433
  """
1434
  OP_DSC_FIELD = "allocator"
1435
  OP_PARAMS = [
1436
    ("direction", ht.NoDefault,
1437
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1438
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1439
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1440
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1441
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1442
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1443
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1444
    ("hypervisor", None, ht.TMaybeString, None),
1445
    ("allocator", None, ht.TMaybeString, None),
1446
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1447
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1448
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1449
    ("os", None, ht.TMaybeString, None),
1450
    ("disk_template", None, ht.TMaybeString, None),
1451
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1452
     None),
1453
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1454
     None),
1455
    ("reloc_mode", None,
1456
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_MRELOC_MODES)), None),
1457
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1458
     None),
1459
    ]
1460

    
1461

    
1462
class OpTestJqueue(OpCode):
1463
  """Utility opcode to test some aspects of the job queue.
1464

1465
  """
1466
  OP_PARAMS = [
1467
    ("notify_waitlock", False, ht.TBool, None),
1468
    ("notify_exec", False, ht.TBool, None),
1469
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1470
    ("fail", False, ht.TBool, None),
1471
    ]
1472

    
1473

    
1474
class OpTestDummy(OpCode):
1475
  """Utility opcode used by unittests.
1476

1477
  """
1478
  OP_PARAMS = [
1479
    ("result", ht.NoDefault, ht.NoType, None),
1480
    ("messages", ht.NoDefault, ht.NoType, None),
1481
    ("fail", ht.NoDefault, ht.NoType, None),
1482
    ("submit_jobs", None, ht.NoType, None),
1483
    ]
1484
  WITH_LU = False
1485

    
1486

    
1487
def _GetOpList():
1488
  """Returns list of all defined opcodes.
1489

1490
  Does not eliminate duplicates by C{OP_ID}.
1491

1492
  """
1493
  return [v for v in globals().values()
1494
          if (isinstance(v, type) and issubclass(v, OpCode) and
1495
              hasattr(v, "OP_ID") and v is not OpCode)]
1496

    
1497

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