Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ c711d09e

History | View | Annotate | Download (45.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
_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 OpClusterVerify(OpCode):
517
  """Verify the cluster state.
518

519
  @type skip_checks: C{list}
520
  @ivar skip_checks: steps to be skipped from the verify process; this
521
                     needs to be a subset of
522
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
523
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
524

525
  """
526
  OP_PARAMS = [
527
    ("skip_checks", ht.EmptyList,
528
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
529
    ("verbose", False, ht.TBool, None),
530
    ("error_codes", False, ht.TBool, None),
531
    ("debug_simulate_errors", False, ht.TBool, None),
532
    ]
533

    
534

    
535
class OpClusterVerifyDisks(OpCode):
536
  """Verify the cluster disks.
537

538
  Parameters: none
539

540
  Result: a tuple of four elements:
541
    - list of node names with bad data returned (unreachable, etc.)
542
    - dict of node names with broken volume groups (values: error msg)
543
    - list of instances with degraded disks (that should be activated)
544
    - dict of instances with missing logical volumes (values: (node, vol)
545
      pairs with details about the missing volumes)
546

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

552
  Note that only instances that are drbd-based are taken into
553
  consideration. This might need to be revisited in the future.
554

555
  """
556

    
557

    
558
class OpClusterRepairDiskSizes(OpCode):
559
  """Verify the disk sizes of the instances and fixes configuration
560
  mimatches.
561

562
  Parameters: optional instances list, in case we want to restrict the
563
  checks to only a subset of the instances.
564

565
  Result: a list of tuples, (instance, disk, new-size) for changed
566
  configurations.
567

568
  In normal operation, the list should be empty.
569

570
  @type instances: list
571
  @ivar instances: the list of instances to check, or empty for all instances
572

573
  """
574
  OP_PARAMS = [
575
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
576
    ]
577

    
578

    
579
class OpClusterConfigQuery(OpCode):
580
  """Query cluster configuration values."""
581
  OP_PARAMS = [
582
    _POutputFields
583
    ]
584

    
585

    
586
class OpClusterRename(OpCode):
587
  """Rename the cluster.
588

589
  @type name: C{str}
590
  @ivar name: The new name of the cluster. The name and/or the master IP
591
              address will be changed to match the new name and its IP
592
              address.
593

594
  """
595
  OP_DSC_FIELD = "name"
596
  OP_PARAMS = [
597
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
598
    ]
599

    
600

    
601
class OpClusterSetParams(OpCode):
602
  """Change the parameters of the cluster.
603

604
  @type vg_name: C{str} or C{None}
605
  @ivar vg_name: The new volume group name or None to disable LVM usage.
606

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

    
659

    
660
class OpClusterRedistConf(OpCode):
661
  """Force a full push of the cluster configuration.
662

663
  """
664

    
665

    
666
class OpQuery(OpCode):
667
  """Query for resources/items.
668

669
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
670
  @ivar fields: List of fields to retrieve
671
  @ivar filter: Query filter
672

673
  """
674
  OP_PARAMS = [
675
    _PQueryWhat,
676
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
677
     "Requested fields"),
678
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
679
     "Query filter"),
680
    ]
681

    
682

    
683
class OpQueryFields(OpCode):
684
  """Query for available resource/item fields.
685

686
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
687
  @ivar fields: List of fields to retrieve
688

689
  """
690
  OP_PARAMS = [
691
    _PQueryWhat,
692
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
693
     "Requested fields; if not given, all are returned"),
694
    ]
695

    
696

    
697
class OpOobCommand(OpCode):
698
  """Interact with OOB."""
699
  OP_PARAMS = [
700
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
701
     "List of nodes to run the OOB command against"),
702
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
703
     "OOB command to be run"),
704
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
705
     "Timeout before the OOB helper will be terminated"),
706
    ("ignore_status", False, ht.TBool,
707
     "Ignores the node offline status for power off"),
708
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
709
     "Time in seconds to wait between powering on nodes"),
710
    ]
711

    
712

    
713
# node opcodes
714

    
715
class OpNodeRemove(OpCode):
716
  """Remove a node.
717

718
  @type node_name: C{str}
719
  @ivar node_name: The name of the node to remove. If the node still has
720
                   instances on it, the operation will fail.
721

722
  """
723
  OP_DSC_FIELD = "node_name"
724
  OP_PARAMS = [
725
    _PNodeName,
726
    ]
727

    
728

    
729
class OpNodeAdd(OpCode):
730
  """Add a node to the cluster.
731

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

756
  """
757
  OP_DSC_FIELD = "node_name"
758
  OP_PARAMS = [
759
    _PNodeName,
760
    ("primary_ip", None, ht.NoType, "Primary IP address"),
761
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
762
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
763
    ("group", None, ht.TMaybeString, "Initial node group"),
764
    ("master_capable", None, ht.TMaybeBool,
765
     "Whether node can become master or master candidate"),
766
    ("vm_capable", None, ht.TMaybeBool,
767
     "Whether node can host instances"),
768
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
769
    ]
770

    
771

    
772
class OpNodeQuery(OpCode):
773
  """Compute the list of nodes."""
774
  OP_PARAMS = [
775
    _POutputFields,
776
    _PUseLocking,
777
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
778
     "Empty list to query all nodes, node names otherwise"),
779
    ]
780

    
781

    
782
class OpNodeQueryvols(OpCode):
783
  """Get list of volumes on node."""
784
  OP_PARAMS = [
785
    _POutputFields,
786
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
787
     "Empty list to query all nodes, node names otherwise"),
788
    ]
789

    
790

    
791
class OpNodeQueryStorage(OpCode):
792
  """Get information on storage for node(s)."""
793
  OP_PARAMS = [
794
    _POutputFields,
795
    _PStorageType,
796
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
797
    ("name", None, ht.TMaybeString, "Storage name"),
798
    ]
799

    
800

    
801
class OpNodeModifyStorage(OpCode):
802
  """Modifies the properies of a storage unit"""
803
  OP_PARAMS = [
804
    _PNodeName,
805
    _PStorageType,
806
    _PStorageName,
807
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
808
    ]
809

    
810

    
811
class OpRepairNodeStorage(OpCode):
812
  """Repairs the volume group on a node."""
813
  OP_DSC_FIELD = "node_name"
814
  OP_PARAMS = [
815
    _PNodeName,
816
    _PStorageType,
817
    _PStorageName,
818
    _PIgnoreConsistency,
819
    ]
820

    
821

    
822
class OpNodeSetParams(OpCode):
823
  """Change the parameters of a node."""
824
  OP_DSC_FIELD = "node_name"
825
  OP_PARAMS = [
826
    _PNodeName,
827
    _PForce,
828
    ("master_candidate", None, ht.TMaybeBool,
829
     "Whether the node should become a master candidate"),
830
    ("offline", None, ht.TMaybeBool,
831
     "Whether the node should be marked as offline"),
832
    ("drained", None, ht.TMaybeBool,
833
     "Whether the node should be marked as drained"),
834
    ("auto_promote", False, ht.TBool,
835
     "Whether node(s) should be promoted to master candidate if necessary"),
836
    ("master_capable", None, ht.TMaybeBool,
837
     "Denote whether node can become master or master candidate"),
838
    ("vm_capable", None, ht.TMaybeBool,
839
     "Denote whether node can host instances"),
840
    ("secondary_ip", None, ht.TMaybeString,
841
     "Change node's secondary IP address"),
842
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
843
    ("powered", None, ht.TMaybeBool,
844
     "Whether the node should be marked as powered"),
845
    ]
846

    
847

    
848
class OpNodePowercycle(OpCode):
849
  """Tries to powercycle a node."""
850
  OP_DSC_FIELD = "node_name"
851
  OP_PARAMS = [
852
    _PNodeName,
853
    _PForce,
854
    ]
855

    
856

    
857
class OpNodeMigrate(OpCode):
858
  """Migrate all instances from a node."""
859
  OP_DSC_FIELD = "node_name"
860
  OP_PARAMS = [
861
    _PNodeName,
862
    _PMigrationMode,
863
    _PMigrationLive,
864
    ("iallocator", None, ht.TMaybeString,
865
     "Iallocator for deciding the target node for shared-storage instances"),
866
    ]
867

    
868

    
869
class OpNodeEvacStrategy(OpCode):
870
  """Compute the evacuation strategy for a list of nodes."""
871
  OP_DSC_FIELD = "nodes"
872
  OP_PARAMS = [
873
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None),
874
    ("remote_node", None, ht.TMaybeString, None),
875
    ("iallocator", None, ht.TMaybeString, None),
876
    ]
877

    
878

    
879
# instance opcodes
880

    
881
class OpInstanceCreate(OpCode):
882
  """Create an instance.
883

884
  @ivar instance_name: Instance name
885
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
886
  @ivar source_handshake: Signed handshake from source (remote import only)
887
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
888
  @ivar source_instance_name: Previous name of instance (remote import only)
889
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
890
    (remote import only)
891

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

    
952

    
953
class OpInstanceReinstall(OpCode):
954
  """Reinstall an instance's OS."""
955
  OP_DSC_FIELD = "instance_name"
956
  OP_PARAMS = [
957
    _PInstanceName,
958
    _PForceVariant,
959
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
960
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
961
    ]
962

    
963

    
964
class OpInstanceRemove(OpCode):
965
  """Remove an instance."""
966
  OP_DSC_FIELD = "instance_name"
967
  OP_PARAMS = [
968
    _PInstanceName,
969
    _PShutdownTimeout,
970
    ("ignore_failures", False, ht.TBool,
971
     "Whether to ignore failures during removal"),
972
    ]
973

    
974

    
975
class OpInstanceRename(OpCode):
976
  """Rename an instance."""
977
  OP_PARAMS = [
978
    _PInstanceName,
979
    _PNameCheck,
980
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
981
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
982
    ]
983

    
984

    
985
class OpInstanceStartup(OpCode):
986
  """Startup an instance."""
987
  OP_DSC_FIELD = "instance_name"
988
  OP_PARAMS = [
989
    _PInstanceName,
990
    _PForce,
991
    _PIgnoreOfflineNodes,
992
    ("hvparams", ht.EmptyDict, ht.TDict,
993
     "Temporary hypervisor parameters, hypervisor-dependent"),
994
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
995
    _PNoRemember,
996
    ]
997

    
998

    
999
class OpInstanceShutdown(OpCode):
1000
  """Shutdown an instance."""
1001
  OP_DSC_FIELD = "instance_name"
1002
  OP_PARAMS = [
1003
    _PInstanceName,
1004
    _PIgnoreOfflineNodes,
1005
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1006
     "How long to wait for instance to shut down"),
1007
    _PNoRemember,
1008
    ]
1009

    
1010

    
1011
class OpInstanceReboot(OpCode):
1012
  """Reboot an instance."""
1013
  OP_DSC_FIELD = "instance_name"
1014
  OP_PARAMS = [
1015
    _PInstanceName,
1016
    _PShutdownTimeout,
1017
    ("ignore_secondaries", False, ht.TBool,
1018
     "Whether to start the instance even if secondary disks are failing"),
1019
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1020
     "How to reboot instance"),
1021
    ]
1022

    
1023

    
1024
class OpInstanceReplaceDisks(OpCode):
1025
  """Replace the disks of an instance."""
1026
  OP_DSC_FIELD = "instance_name"
1027
  OP_PARAMS = [
1028
    _PInstanceName,
1029
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1030
     "Replacement mode"),
1031
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1032
     "Disk indexes"),
1033
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1034
    ("iallocator", None, ht.TMaybeString,
1035
     "Iallocator for deciding new secondary node"),
1036
    ("early_release", False, ht.TBool,
1037
     "Whether to release locks as soon as possible"),
1038
    ]
1039

    
1040

    
1041
class OpInstanceFailover(OpCode):
1042
  """Failover an instance."""
1043
  OP_DSC_FIELD = "instance_name"
1044
  OP_PARAMS = [
1045
    _PInstanceName,
1046
    _PShutdownTimeout,
1047
    _PIgnoreConsistency,
1048
    ("iallocator", None, ht.TMaybeString,
1049
     "Iallocator for deciding the target node for shared-storage instances"),
1050
    ("target_node", None, ht.TMaybeString,
1051
     "Target node for shared-storage instances"),
1052
    ]
1053

    
1054

    
1055
class OpInstanceMigrate(OpCode):
1056
  """Migrate an instance.
1057

1058
  This migrates (without shutting down an instance) to its secondary
1059
  node.
1060

1061
  @ivar instance_name: the name of the instance
1062
  @ivar mode: the migration mode (live, non-live or None for auto)
1063

1064
  """
1065
  OP_DSC_FIELD = "instance_name"
1066
  OP_PARAMS = [
1067
    _PInstanceName,
1068
    _PMigrationMode,
1069
    _PMigrationLive,
1070
    ("cleanup", False, ht.TBool,
1071
     "Whether a previously failed migration should be cleaned up"),
1072
    ("iallocator", None, ht.TMaybeString,
1073
     "Iallocator for deciding the target node for shared-storage instances"),
1074
    ("target_node", None, ht.TMaybeString,
1075
     "Target node for shared-storage instances"),
1076
    ("allow_failover", False, ht.TBool,
1077
     "Whether we can fallback to failover if migration is not possible"),
1078
    ]
1079

    
1080

    
1081
class OpInstanceMove(OpCode):
1082
  """Move an instance.
1083

1084
  This move (with shutting down an instance and data copying) to an
1085
  arbitrary node.
1086

1087
  @ivar instance_name: the name of the instance
1088
  @ivar target_node: the destination node
1089

1090
  """
1091
  OP_DSC_FIELD = "instance_name"
1092
  OP_PARAMS = [
1093
    _PInstanceName,
1094
    _PShutdownTimeout,
1095
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1096
    _PIgnoreConsistency,
1097
    ]
1098

    
1099

    
1100
class OpInstanceConsole(OpCode):
1101
  """Connect to an instance's console."""
1102
  OP_DSC_FIELD = "instance_name"
1103
  OP_PARAMS = [
1104
    _PInstanceName
1105
    ]
1106

    
1107

    
1108
class OpInstanceActivateDisks(OpCode):
1109
  """Activate an instance's disks."""
1110
  OP_DSC_FIELD = "instance_name"
1111
  OP_PARAMS = [
1112
    _PInstanceName,
1113
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1114
    ]
1115

    
1116

    
1117
class OpInstanceDeactivateDisks(OpCode):
1118
  """Deactivate an instance's disks."""
1119
  OP_DSC_FIELD = "instance_name"
1120
  OP_PARAMS = [
1121
    _PInstanceName,
1122
    _PForce,
1123
    ]
1124

    
1125

    
1126
class OpInstanceRecreateDisks(OpCode):
1127
  """Deactivate an instance's disks."""
1128
  OP_DSC_FIELD = "instance_name"
1129
  OP_PARAMS = [
1130
    _PInstanceName,
1131
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1132
     "List of disk indexes"),
1133
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1134
     "New instance nodes, if relocation is desired"),
1135
    ]
1136

    
1137

    
1138
class OpInstanceQuery(OpCode):
1139
  """Compute the list of instances."""
1140
  OP_PARAMS = [
1141
    _POutputFields,
1142
    _PUseLocking,
1143
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1144
     "Empty list to query all instances, instance names otherwise"),
1145
    ]
1146

    
1147

    
1148
class OpInstanceQueryData(OpCode):
1149
  """Compute the run-time status of instances."""
1150
  OP_PARAMS = [
1151
    _PUseLocking,
1152
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1153
     "Instance names"),
1154
    ("static", False, ht.TBool,
1155
     "Whether to only return configuration data without querying"
1156
     " nodes"),
1157
    ]
1158

    
1159

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

    
1189

    
1190
class OpInstanceGrowDisk(OpCode):
1191
  """Grow a disk of an instance."""
1192
  OP_DSC_FIELD = "instance_name"
1193
  OP_PARAMS = [
1194
    _PInstanceName,
1195
    _PWaitForSync,
1196
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1197
    ("amount", ht.NoDefault, ht.TInt,
1198
     "Amount of disk space to add (megabytes)"),
1199
    ]
1200

    
1201

    
1202
# Node group opcodes
1203

    
1204
class OpGroupAdd(OpCode):
1205
  """Add a node group to the cluster."""
1206
  OP_DSC_FIELD = "group_name"
1207
  OP_PARAMS = [
1208
    _PGroupName,
1209
    _PNodeGroupAllocPolicy,
1210
    _PGroupNodeParams,
1211
    ]
1212

    
1213

    
1214
class OpGroupAssignNodes(OpCode):
1215
  """Assign nodes to a node group."""
1216
  OP_DSC_FIELD = "group_name"
1217
  OP_PARAMS = [
1218
    _PGroupName,
1219
    _PForce,
1220
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1221
     "List of nodes to assign"),
1222
    ]
1223

    
1224

    
1225
class OpGroupQuery(OpCode):
1226
  """Compute the list of node groups."""
1227
  OP_PARAMS = [
1228
    _POutputFields,
1229
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1230
     "Empty list to query all groups, group names otherwise"),
1231
    ]
1232

    
1233

    
1234
class OpGroupSetParams(OpCode):
1235
  """Change the parameters of a node group."""
1236
  OP_DSC_FIELD = "group_name"
1237
  OP_PARAMS = [
1238
    _PGroupName,
1239
    _PNodeGroupAllocPolicy,
1240
    _PGroupNodeParams,
1241
    ]
1242

    
1243

    
1244
class OpGroupRemove(OpCode):
1245
  """Remove a node group from the cluster."""
1246
  OP_DSC_FIELD = "group_name"
1247
  OP_PARAMS = [
1248
    _PGroupName,
1249
    ]
1250

    
1251

    
1252
class OpGroupRename(OpCode):
1253
  """Rename a node group in the cluster."""
1254
  OP_PARAMS = [
1255
    _PGroupName,
1256
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1257
    ]
1258

    
1259

    
1260
# OS opcodes
1261
class OpOsDiagnose(OpCode):
1262
  """Compute the list of guest operating systems."""
1263
  OP_PARAMS = [
1264
    _POutputFields,
1265
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1266
     "Which operating systems to diagnose"),
1267
    ]
1268

    
1269

    
1270
# Exports opcodes
1271
class OpBackupQuery(OpCode):
1272
  """Compute the list of exported images."""
1273
  OP_PARAMS = [
1274
    _PUseLocking,
1275
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1276
     "Empty list to query all nodes, node names otherwise"),
1277
    ]
1278

    
1279

    
1280
class OpBackupPrepare(OpCode):
1281
  """Prepares an instance export.
1282

1283
  @ivar instance_name: Instance name
1284
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1285

1286
  """
1287
  OP_DSC_FIELD = "instance_name"
1288
  OP_PARAMS = [
1289
    _PInstanceName,
1290
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1291
     "Export mode"),
1292
    ]
1293

    
1294

    
1295
class OpBackupExport(OpCode):
1296
  """Export an instance.
1297

1298
  For local exports, the export destination is the node name. For remote
1299
  exports, the export destination is a list of tuples, each consisting of
1300
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1301
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1302
  destination X509 CA must be a signed certificate.
1303

1304
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1305
  @ivar target_node: Export destination
1306
  @ivar x509_key_name: X509 key to use (remote export only)
1307
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1308
                             only)
1309

1310
  """
1311
  OP_DSC_FIELD = "instance_name"
1312
  OP_PARAMS = [
1313
    _PInstanceName,
1314
    _PShutdownTimeout,
1315
    # TODO: Rename target_node as it changes meaning for different export modes
1316
    # (e.g. "destination")
1317
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1318
     "Destination information, depends on export mode"),
1319
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1320
    ("remove_instance", False, ht.TBool,
1321
     "Whether to remove instance after export"),
1322
    ("ignore_remove_failures", False, ht.TBool,
1323
     "Whether to ignore failures while removing instances"),
1324
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1325
     "Export mode"),
1326
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1327
     "Name of X509 key (remote export only)"),
1328
    ("destination_x509_ca", None, ht.TMaybeString,
1329
     "Destination X509 CA (remote export only)"),
1330
    ]
1331

    
1332

    
1333
class OpBackupRemove(OpCode):
1334
  """Remove an instance's export."""
1335
  OP_DSC_FIELD = "instance_name"
1336
  OP_PARAMS = [
1337
    _PInstanceName,
1338
    ]
1339

    
1340

    
1341
# Tags opcodes
1342
class OpTagsGet(OpCode):
1343
  """Returns the tags of the given object."""
1344
  OP_DSC_FIELD = "name"
1345
  OP_PARAMS = [
1346
    _PTagKind,
1347
    # Name is only meaningful for nodes and instances
1348
    ("name", ht.NoDefault, ht.TMaybeString, None),
1349
    ]
1350

    
1351

    
1352
class OpTagsSearch(OpCode):
1353
  """Searches the tags in the cluster for a given pattern."""
1354
  OP_DSC_FIELD = "pattern"
1355
  OP_PARAMS = [
1356
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1357
    ]
1358

    
1359

    
1360
class OpTagsSet(OpCode):
1361
  """Add a list of tags on a given object."""
1362
  OP_PARAMS = [
1363
    _PTagKind,
1364
    _PTags,
1365
    # Name is only meaningful for nodes and instances
1366
    ("name", ht.NoDefault, ht.TMaybeString, None),
1367
    ]
1368

    
1369

    
1370
class OpTagsDel(OpCode):
1371
  """Remove a list of tags from a given object."""
1372
  OP_PARAMS = [
1373
    _PTagKind,
1374
    _PTags,
1375
    # Name is only meaningful for nodes and instances
1376
    ("name", ht.NoDefault, ht.TMaybeString, None),
1377
    ]
1378

    
1379
# Test opcodes
1380
class OpTestDelay(OpCode):
1381
  """Sleeps for a configured amount of time.
1382

1383
  This is used just for debugging and testing.
1384

1385
  Parameters:
1386
    - duration: the time to sleep
1387
    - on_master: if true, sleep on the master
1388
    - on_nodes: list of nodes in which to sleep
1389

1390
  If the on_master parameter is true, it will execute a sleep on the
1391
  master (before any node sleep).
1392

1393
  If the on_nodes list is not empty, it will sleep on those nodes
1394
  (after the sleep on the master, if that is enabled).
1395

1396
  As an additional feature, the case of duration < 0 will be reported
1397
  as an execution error, so this opcode can be used as a failure
1398
  generator. The case of duration == 0 will not be treated specially.
1399

1400
  """
1401
  OP_DSC_FIELD = "duration"
1402
  OP_PARAMS = [
1403
    ("duration", ht.NoDefault, ht.TFloat, None),
1404
    ("on_master", True, ht.TBool, None),
1405
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1406
    ("repeat", 0, ht.TPositiveInt, None),
1407
    ]
1408

    
1409

    
1410
class OpTestAllocator(OpCode):
1411
  """Allocator framework testing.
1412

1413
  This opcode has two modes:
1414
    - gather and return allocator input for a given mode (allocate new
1415
      or replace secondary) and a given instance definition (direction
1416
      'in')
1417
    - run a selected allocator for a given operation (as above) and
1418
      return the allocator output (direction 'out')
1419

1420
  """
1421
  OP_DSC_FIELD = "allocator"
1422
  OP_PARAMS = [
1423
    ("direction", ht.NoDefault,
1424
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1425
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1426
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1427
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1428
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1429
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1430
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1431
    ("hypervisor", None, ht.TMaybeString, None),
1432
    ("allocator", None, ht.TMaybeString, None),
1433
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1434
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1435
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1436
    ("os", None, ht.TMaybeString, None),
1437
    ("disk_template", None, ht.TMaybeString, None),
1438
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1439
     None),
1440
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1441
     None),
1442
    ("reloc_mode", None,
1443
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_MRELOC_MODES)), None),
1444
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1445
     None),
1446
    ]
1447

    
1448

    
1449
class OpTestJqueue(OpCode):
1450
  """Utility opcode to test some aspects of the job queue.
1451

1452
  """
1453
  OP_PARAMS = [
1454
    ("notify_waitlock", False, ht.TBool, None),
1455
    ("notify_exec", False, ht.TBool, None),
1456
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1457
    ("fail", False, ht.TBool, None),
1458
    ]
1459

    
1460

    
1461
class OpTestDummy(OpCode):
1462
  """Utility opcode used by unittests.
1463

1464
  """
1465
  OP_PARAMS = [
1466
    ("result", ht.NoDefault, ht.NoType, None),
1467
    ("messages", ht.NoDefault, ht.NoType, None),
1468
    ("fail", ht.NoDefault, ht.NoType, None),
1469
    ("submit_jobs", None, ht.NoType, None),
1470
    ]
1471
  WITH_LU = False
1472

    
1473

    
1474
def _GetOpList():
1475
  """Returns list of all defined opcodes.
1476

1477
  Does not eliminate duplicates by C{OP_ID}.
1478

1479
  """
1480
  return [v for v in globals().values()
1481
          if (isinstance(v, type) and issubclass(v, OpCode) and
1482
              hasattr(v, "OP_ID") and v is not OpCode)]
1483

    
1484

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