Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 018ae30b

History | View | Annotate | Download (47.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""OpCodes module
23

24
This module implements the data structures which define the cluster
25
operations - the so-called opcodes.
26

27
Every operation which modifies the cluster state is expressed via
28
opcodes.
29

30
"""
31

    
32
# this are practically structures, so disable the message about too
33
# few public methods:
34
# pylint: disable-msg=R0903
35

    
36
import logging
37
import re
38
import operator
39

    
40
from ganeti import constants
41
from ganeti import errors
42
from ganeti import ht
43

    
44

    
45
# Common opcode attributes
46

    
47
#: output fields for a query operation
48
_POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
49
                  "Selected output fields")
50

    
51
#: the shutdown timeout
52
_PShutdownTimeout = \
53
  ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
54
   "How long to wait for instance to shut down")
55

    
56
#: the force parameter
57
_PForce = ("force", False, ht.TBool, "Whether to force the operation")
58

    
59
#: a required instance name (for single-instance LUs)
60
_PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString,
61
                  "Instance name")
62

    
63
#: Whether to ignore offline nodes
64
_PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool,
65
                        "Whether to ignore offline nodes")
66

    
67
#: a required node name (for single-node LUs)
68
_PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString, "Node name")
69

    
70
#: a required node group name (for single-group LUs)
71
_PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString, "Group name")
72

    
73
#: Migration type (live/non-live)
74
_PMigrationMode = ("mode", None,
75
                   ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)),
76
                   "Migration mode")
77

    
78
#: Obsolete 'live' migration mode (boolean)
79
_PMigrationLive = ("live", None, ht.TMaybeBool,
80
                   "Legacy setting for live migration, do not use")
81

    
82
#: Tag type
83
_PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES), None)
84

    
85
#: List of tag strings
86
_PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None)
87

    
88
_PForceVariant = ("force_variant", False, ht.TBool,
89
                  "Whether to force an unknown OS variant")
90

    
91
_PWaitForSync = ("wait_for_sync", True, ht.TBool,
92
                 "Whether to wait for the disk to synchronize")
93

    
94
_PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
95
                       "Whether to ignore disk consistency")
96

    
97
_PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
98

    
99
_PUseLocking = ("use_locking", False, ht.TBool,
100
                "Whether to use synchronization")
101

    
102
_PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
103

    
104
_PNodeGroupAllocPolicy = \
105
  ("alloc_policy", None,
106
   ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
107
   "Instance allocation policy")
108

    
109
_PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
110
                     "Default node parameters for group")
111

    
112
_PQueryWhat = ("what", ht.NoDefault, ht.TElemOf(constants.QR_VIA_OP),
113
               "Resource(s) to query for")
114

    
115
_PEarlyRelease = ("early_release", False, ht.TBool,
116
                  "Whether to release locks as soon as possible")
117

    
118
_PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
119

    
120
#: Do not remember instance state changes
121
_PNoRemember = ("no_remember", False, ht.TBool,
122
                "Do not remember the state change")
123

    
124
#: Target node for instance migration/failover
125
_PMigrationTargetNode = ("target_node", None, ht.TMaybeString,
126
                         "Target node for shared-storage instances")
127

    
128
_PStartupPaused = ("startup_paused", False, ht.TBool,
129
                   "Pause instance at startup")
130

    
131

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

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

    
141

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

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

    
154
#: Attribute name for dependencies
155
DEPEND_ATTR = "depends"
156

    
157
#: Attribute name for comment
158
COMMENT_ATTR = "comment"
159

    
160

    
161
def _NameToId(name):
162
  """Convert an opcode class name to an OP_ID.
163

164
  @type name: string
165
  @param name: the class name, as OpXxxYyy
166
  @rtype: string
167
  @return: the name in the OP_XXXX_YYYY format
168

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

    
181

    
182
def RequireFileStorage():
183
  """Checks that file storage is enabled.
184

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

188
  @raise errors.OpPrereqError: when file storage is disabled
189

190
  """
191
  if not constants.ENABLE_FILE_STORAGE:
192
    raise errors.OpPrereqError("File storage disabled at configure time",
193
                               errors.ECODE_INVAL)
194

    
195

    
196
def RequireSharedFileStorage():
197
  """Checks that shared file storage is enabled.
198

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

202
  @raise errors.OpPrereqError: when shared file storage is disabled
203

204
  """
205
  if not constants.ENABLE_SHARED_FILE_STORAGE:
206
    raise errors.OpPrereqError("Shared file storage disabled at"
207
                               " configure time", errors.ECODE_INVAL)
208

    
209

    
210
@ht.WithDesc("CheckFileStorage")
211
def _CheckFileStorage(value):
212
  """Ensures file storage is enabled if used.
213

214
  """
215
  if value == constants.DT_FILE:
216
    RequireFileStorage()
217
  elif value == constants.DT_SHARED_FILE:
218
    RequireSharedFileStorage()
219
  return True
220

    
221

    
222
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
223
                             _CheckFileStorage)
224

    
225

    
226
def _CheckStorageType(storage_type):
227
  """Ensure a given storage type is valid.
228

229
  """
230
  if storage_type not in constants.VALID_STORAGE_TYPES:
231
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
232
                               errors.ECODE_INVAL)
233
  if storage_type == constants.ST_FILE:
234
    RequireFileStorage()
235
  return True
236

    
237

    
238
#: Storage type parameter
239
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
240
                 "Storage type")
241

    
242

    
243
class _AutoOpParamSlots(type):
244
  """Meta class for opcode definitions.
245

246
  """
247
  def __new__(mcs, name, bases, attrs):
248
    """Called when a class should be created.
249

250
    @param mcs: The meta class
251
    @param name: Name of created class
252
    @param bases: Base classes
253
    @type attrs: dict
254
    @param attrs: Class attributes
255

256
    """
257
    assert "__slots__" not in attrs, \
258
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
259
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
260

    
261
    attrs["OP_ID"] = _NameToId(name)
262

    
263
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
264
    params = attrs.setdefault("OP_PARAMS", [])
265

    
266
    # Use parameter names as slots
267
    slots = [pname for (pname, _, _, _) in params]
268

    
269
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
270
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
271

    
272
    attrs["__slots__"] = slots
273

    
274
    return type.__new__(mcs, name, bases, attrs)
275

    
276

    
277
class BaseOpCode(object):
278
  """A simple serializable object.
279

280
  This object serves as a parent class for OpCode without any custom
281
  field handling.
282

283
  """
284
  # pylint: disable-msg=E1101
285
  # as OP_ID is dynamically defined
286
  __metaclass__ = _AutoOpParamSlots
287

    
288
  def __init__(self, **kwargs):
289
    """Constructor for BaseOpCode.
290

291
    The constructor takes only keyword arguments and will set
292
    attributes on this object based on the passed arguments. As such,
293
    it means that you should not pass arguments which are not in the
294
    __slots__ attribute for this class.
295

296
    """
297
    slots = self._all_slots()
298
    for key in kwargs:
299
      if key not in slots:
300
        raise TypeError("Object %s doesn't support the parameter '%s'" %
301
                        (self.__class__.__name__, key))
302
      setattr(self, key, kwargs[key])
303

    
304
  def __getstate__(self):
305
    """Generic serializer.
306

307
    This method just returns the contents of the instance as a
308
    dictionary.
309

310
    @rtype:  C{dict}
311
    @return: the instance attributes and their values
312

313
    """
314
    state = {}
315
    for name in self._all_slots():
316
      if hasattr(self, name):
317
        state[name] = getattr(self, name)
318
    return state
319

    
320
  def __setstate__(self, state):
321
    """Generic unserializer.
322

323
    This method just restores from the serialized state the attributes
324
    of the current instance.
325

326
    @param state: the serialized opcode data
327
    @type state:  C{dict}
328

329
    """
330
    if not isinstance(state, dict):
331
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
332
                       type(state))
333

    
334
    for name in self._all_slots():
335
      if name not in state and hasattr(self, name):
336
        delattr(self, name)
337

    
338
    for name in state:
339
      setattr(self, name, state[name])
340

    
341
  @classmethod
342
  def _all_slots(cls):
343
    """Compute the list of all declared slots for a class.
344

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

    
351
  @classmethod
352
  def GetAllParams(cls):
353
    """Compute list of all parameters for an opcode.
354

355
    """
356
    slots = []
357
    for parent in cls.__mro__:
358
      slots.extend(getattr(parent, "OP_PARAMS", []))
359
    return slots
360

    
361
  def Validate(self, set_defaults):
362
    """Validate opcode parameters, optionally setting default values.
363

364
    @type set_defaults: bool
365
    @param set_defaults: Whether to set default values
366
    @raise errors.OpPrereqError: When a parameter value doesn't match
367
                                 requirements
368

369
    """
370
    for (attr_name, default, test, _) in self.GetAllParams():
371
      assert test == ht.NoType or callable(test)
372

    
373
      if not hasattr(self, attr_name):
374
        if default == ht.NoDefault:
375
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
376
                                     (self.OP_ID, attr_name),
377
                                     errors.ECODE_INVAL)
378
        elif set_defaults:
379
          if callable(default):
380
            dval = default()
381
          else:
382
            dval = default
383
          setattr(self, attr_name, dval)
384

    
385
      if test == ht.NoType:
386
        # no tests here
387
        continue
388

    
389
      if set_defaults or hasattr(self, attr_name):
390
        attr_val = getattr(self, attr_name)
391
        if not test(attr_val):
392
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
393
                        self.OP_ID, attr_name, type(attr_val), attr_val)
394
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
395
                                     (self.OP_ID, attr_name),
396
                                     errors.ECODE_INVAL)
397

    
398

    
399
def _BuildJobDepCheck(relative):
400
  """Builds check for job dependencies (L{DEPEND_ATTR}).
401

402
  @type relative: bool
403
  @param relative: Whether to accept relative job IDs (negative)
404
  @rtype: callable
405

406
  """
407
  if relative:
408
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
409
  else:
410
    job_id = ht.TJobId
411

    
412
  job_dep = \
413
    ht.TAnd(ht.TIsLength(2),
414
            ht.TItems([job_id,
415
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
416

    
417
  return ht.TOr(ht.TNone, ht.TListOf(job_dep))
418

    
419

    
420
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
421

    
422

    
423
class OpCode(BaseOpCode):
424
  """Abstract OpCode.
425

426
  This is the root of the actual OpCode hierarchy. All clases derived
427
  from this class should override OP_ID.
428

429
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
430
               children of this class.
431
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
432
                      string returned by Summary(); see the docstring of that
433
                      method for details).
434
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
435
                   get if not already defined, and types they must match.
436
  @cvar WITH_LU: Boolean that specifies whether this should be included in
437
      mcpu's dispatch table
438
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
439
                 the check steps
440
  @ivar priority: Opcode priority for queue
441

442
  """
443
  # pylint: disable-msg=E1101
444
  # as OP_ID is dynamically defined
445
  WITH_LU = True
446
  OP_PARAMS = [
447
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
448
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
449
    ("priority", constants.OP_PRIO_DEFAULT,
450
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
451
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
452
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
453
     " job IDs can be used"),
454
    (COMMENT_ATTR, None, ht.TMaybeString,
455
     "Comment describing the purpose of the opcode"),
456
    ]
457

    
458
  def __getstate__(self):
459
    """Specialized getstate for opcodes.
460

461
    This method adds to the state dictionary the OP_ID of the class,
462
    so that on unload we can identify the correct class for
463
    instantiating the opcode.
464

465
    @rtype:   C{dict}
466
    @return:  the state as a dictionary
467

468
    """
469
    data = BaseOpCode.__getstate__(self)
470
    data["OP_ID"] = self.OP_ID
471
    return data
472

    
473
  @classmethod
474
  def LoadOpCode(cls, data):
475
    """Generic load opcode method.
476

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

481
    @type data:  C{dict}
482
    @param data: the serialized opcode
483

484
    """
485
    if not isinstance(data, dict):
486
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
487
    if "OP_ID" not in data:
488
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
489
    op_id = data["OP_ID"]
490
    op_class = None
491
    if op_id in OP_MAPPING:
492
      op_class = OP_MAPPING[op_id]
493
    else:
494
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
495
                       op_id)
496
    op = op_class()
497
    new_data = data.copy()
498
    del new_data["OP_ID"]
499
    op.__setstate__(new_data)
500
    return op
501

    
502
  def Summary(self):
503
    """Generates a summary description of this opcode.
504

505
    The summary is the value of the OP_ID attribute (without the "OP_"
506
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
507
    defined; this field should allow to easily identify the operation
508
    (for an instance creation job, e.g., it would be the instance
509
    name).
510

511
    """
512
    assert self.OP_ID is not None and len(self.OP_ID) > 3
513
    # all OP_ID start with OP_, we remove that
514
    txt = self.OP_ID[3:]
515
    field_name = getattr(self, "OP_DSC_FIELD", None)
516
    if field_name:
517
      field_value = getattr(self, field_name, None)
518
      if isinstance(field_value, (list, tuple)):
519
        field_value = ",".join(str(i) for i in field_value)
520
      txt = "%s(%s)" % (txt, field_value)
521
    return txt
522

    
523
  def TinySummary(self):
524
    """Generates a compact summary description of the opcode.
525

526
    """
527
    assert self.OP_ID.startswith("OP_")
528

    
529
    text = self.OP_ID[3:]
530

    
531
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
532
      if text.startswith(prefix):
533
        return supplement + text[len(prefix):]
534

    
535
    return text
536

    
537

    
538
# cluster opcodes
539

    
540
class OpClusterPostInit(OpCode):
541
  """Post cluster initialization.
542

543
  This opcode does not touch the cluster at all. Its purpose is to run hooks
544
  after the cluster has been initialized.
545

546
  """
547

    
548

    
549
class OpClusterDestroy(OpCode):
550
  """Destroy the cluster.
551

552
  This opcode has no other parameters. All the state is irreversibly
553
  lost after the execution of this opcode.
554

555
  """
556

    
557

    
558
class OpClusterQuery(OpCode):
559
  """Query cluster information."""
560

    
561

    
562
class OpClusterVerifyConfig(OpCode):
563
  """Verify the cluster config.
564

565
  """
566
  OP_PARAMS = [
567
    ("verbose", False, ht.TBool, None),
568
    ("error_codes", False, ht.TBool, None),
569
    ("debug_simulate_errors", False, ht.TBool, None),
570
    ]
571

    
572

    
573
class OpClusterVerifyGroup(OpCode):
574
  """Run verify on a node group from the cluster.
575

576
  @type skip_checks: C{list}
577
  @ivar skip_checks: steps to be skipped from the verify process; this
578
                     needs to be a subset of
579
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
580
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
581

582
  """
583
  OP_DSC_FIELD = "group_name"
584
  OP_PARAMS = [
585
    ("group_name", ht.NoDefault, ht.TNonEmptyString, None),
586
    ("skip_checks", ht.EmptyList,
587
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
588
    ("verbose", False, ht.TBool, None),
589
    ("error_codes", False, ht.TBool, None),
590
    ("debug_simulate_errors", False, ht.TBool, None),
591
    ]
592

    
593

    
594
class OpClusterVerifyDisks(OpCode):
595
  """Verify the cluster disks.
596

597
  Parameters: none
598

599
  Result: a tuple of four elements:
600
    - list of node names with bad data returned (unreachable, etc.)
601
    - dict of node names with broken volume groups (values: error msg)
602
    - list of instances with degraded disks (that should be activated)
603
    - dict of instances with missing logical volumes (values: (node, vol)
604
      pairs with details about the missing volumes)
605

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

611
  Note that only instances that are drbd-based are taken into
612
  consideration. This might need to be revisited in the future.
613

614
  """
615

    
616

    
617
class OpClusterRepairDiskSizes(OpCode):
618
  """Verify the disk sizes of the instances and fixes configuration
619
  mimatches.
620

621
  Parameters: optional instances list, in case we want to restrict the
622
  checks to only a subset of the instances.
623

624
  Result: a list of tuples, (instance, disk, new-size) for changed
625
  configurations.
626

627
  In normal operation, the list should be empty.
628

629
  @type instances: list
630
  @ivar instances: the list of instances to check, or empty for all instances
631

632
  """
633
  OP_PARAMS = [
634
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
635
    ]
636

    
637

    
638
class OpClusterConfigQuery(OpCode):
639
  """Query cluster configuration values."""
640
  OP_PARAMS = [
641
    _POutputFields
642
    ]
643

    
644

    
645
class OpClusterRename(OpCode):
646
  """Rename the cluster.
647

648
  @type name: C{str}
649
  @ivar name: The new name of the cluster. The name and/or the master IP
650
              address will be changed to match the new name and its IP
651
              address.
652

653
  """
654
  OP_DSC_FIELD = "name"
655
  OP_PARAMS = [
656
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
657
    ]
658

    
659

    
660
class OpClusterSetParams(OpCode):
661
  """Change the parameters of the cluster.
662

663
  @type vg_name: C{str} or C{None}
664
  @ivar vg_name: The new volume group name or None to disable LVM usage.
665

666
  """
667
  OP_PARAMS = [
668
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
669
    ("enabled_hypervisors", None,
670
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
671
            ht.TNone),
672
     "List of enabled hypervisors"),
673
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
674
                              ht.TNone),
675
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
676
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
677
     "Cluster-wide backend parameter defaults"),
678
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
679
                            ht.TNone),
680
     "Cluster-wide per-OS hypervisor parameter defaults"),
681
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
682
                              ht.TNone),
683
     "Cluster-wide OS parameter defaults"),
684
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
685
     "Master candidate pool size"),
686
    ("uid_pool", None, ht.NoType,
687
     "Set UID pool, must be list of lists describing UID ranges (two items,"
688
     " start and end inclusive)"),
689
    ("add_uids", None, ht.NoType,
690
     "Extend UID pool, must be list of lists describing UID ranges (two"
691
     " items, start and end inclusive) to be added"),
692
    ("remove_uids", None, ht.NoType,
693
     "Shrink UID pool, must be list of lists describing UID ranges (two"
694
     " items, start and end inclusive) to be removed"),
695
    ("maintain_node_health", None, ht.TMaybeBool,
696
     "Whether to automatically maintain node health"),
697
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
698
     "Whether to wipe disks before allocating them to instances"),
699
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
700
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
701
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
702
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
703
     "Default iallocator for cluster"),
704
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
705
     "Master network device"),
706
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
707
     "List of reserved LVs"),
708
    ("hidden_os", None, _TestClusterOsList,
709
     "Modify list of hidden operating systems. Each modification must have"
710
     " two items, the operation and the OS name. The operation can be"
711
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
712
    ("blacklisted_os", None, _TestClusterOsList,
713
     "Modify list of blacklisted operating systems. Each modification must have"
714
     " two items, the operation and the OS name. The operation can be"
715
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
716
    ]
717

    
718

    
719
class OpClusterRedistConf(OpCode):
720
  """Force a full push of the cluster configuration.
721

722
  """
723

    
724

    
725
class OpQuery(OpCode):
726
  """Query for resources/items.
727

728
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
729
  @ivar fields: List of fields to retrieve
730
  @ivar filter: Query filter
731

732
  """
733
  OP_PARAMS = [
734
    _PQueryWhat,
735
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
736
     "Requested fields"),
737
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
738
     "Query filter"),
739
    ]
740

    
741

    
742
class OpQueryFields(OpCode):
743
  """Query for available resource/item fields.
744

745
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
746
  @ivar fields: List of fields to retrieve
747

748
  """
749
  OP_PARAMS = [
750
    _PQueryWhat,
751
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
752
     "Requested fields; if not given, all are returned"),
753
    ]
754

    
755

    
756
class OpOobCommand(OpCode):
757
  """Interact with OOB."""
758
  OP_PARAMS = [
759
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
760
     "List of nodes to run the OOB command against"),
761
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
762
     "OOB command to be run"),
763
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
764
     "Timeout before the OOB helper will be terminated"),
765
    ("ignore_status", False, ht.TBool,
766
     "Ignores the node offline status for power off"),
767
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
768
     "Time in seconds to wait between powering on nodes"),
769
    ]
770

    
771

    
772
# node opcodes
773

    
774
class OpNodeRemove(OpCode):
775
  """Remove a node.
776

777
  @type node_name: C{str}
778
  @ivar node_name: The name of the node to remove. If the node still has
779
                   instances on it, the operation will fail.
780

781
  """
782
  OP_DSC_FIELD = "node_name"
783
  OP_PARAMS = [
784
    _PNodeName,
785
    ]
786

    
787

    
788
class OpNodeAdd(OpCode):
789
  """Add a node to the cluster.
790

791
  @type node_name: C{str}
792
  @ivar node_name: The name of the node to add. This can be a short name,
793
                   but it will be expanded to the FQDN.
794
  @type primary_ip: IP address
795
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
796
                    opcode is submitted, but will be filled during the node
797
                    add (so it will be visible in the job query).
798
  @type secondary_ip: IP address
799
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
800
                      if the cluster has been initialized in 'dual-network'
801
                      mode, otherwise it must not be given.
802
  @type readd: C{bool}
803
  @ivar readd: Whether to re-add an existing node to the cluster. If
804
               this is not passed, then the operation will abort if the node
805
               name is already in the cluster; use this parameter to 'repair'
806
               a node that had its configuration broken, or was reinstalled
807
               without removal from the cluster.
808
  @type group: C{str}
809
  @ivar group: The node group to which this node will belong.
810
  @type vm_capable: C{bool}
811
  @ivar vm_capable: The vm_capable node attribute
812
  @type master_capable: C{bool}
813
  @ivar master_capable: The master_capable node attribute
814

815
  """
816
  OP_DSC_FIELD = "node_name"
817
  OP_PARAMS = [
818
    _PNodeName,
819
    ("primary_ip", None, ht.NoType, "Primary IP address"),
820
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
821
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
822
    ("group", None, ht.TMaybeString, "Initial node group"),
823
    ("master_capable", None, ht.TMaybeBool,
824
     "Whether node can become master or master candidate"),
825
    ("vm_capable", None, ht.TMaybeBool,
826
     "Whether node can host instances"),
827
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
828
    ]
829

    
830

    
831
class OpNodeQuery(OpCode):
832
  """Compute the list of nodes."""
833
  OP_PARAMS = [
834
    _POutputFields,
835
    _PUseLocking,
836
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
837
     "Empty list to query all nodes, node names otherwise"),
838
    ]
839

    
840

    
841
class OpNodeQueryvols(OpCode):
842
  """Get list of volumes on node."""
843
  OP_PARAMS = [
844
    _POutputFields,
845
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
846
     "Empty list to query all nodes, node names otherwise"),
847
    ]
848

    
849

    
850
class OpNodeQueryStorage(OpCode):
851
  """Get information on storage for node(s)."""
852
  OP_PARAMS = [
853
    _POutputFields,
854
    _PStorageType,
855
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
856
    ("name", None, ht.TMaybeString, "Storage name"),
857
    ]
858

    
859

    
860
class OpNodeModifyStorage(OpCode):
861
  """Modifies the properies of a storage unit"""
862
  OP_PARAMS = [
863
    _PNodeName,
864
    _PStorageType,
865
    _PStorageName,
866
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
867
    ]
868

    
869

    
870
class OpRepairNodeStorage(OpCode):
871
  """Repairs the volume group on a node."""
872
  OP_DSC_FIELD = "node_name"
873
  OP_PARAMS = [
874
    _PNodeName,
875
    _PStorageType,
876
    _PStorageName,
877
    _PIgnoreConsistency,
878
    ]
879

    
880

    
881
class OpNodeSetParams(OpCode):
882
  """Change the parameters of a node."""
883
  OP_DSC_FIELD = "node_name"
884
  OP_PARAMS = [
885
    _PNodeName,
886
    _PForce,
887
    ("master_candidate", None, ht.TMaybeBool,
888
     "Whether the node should become a master candidate"),
889
    ("offline", None, ht.TMaybeBool,
890
     "Whether the node should be marked as offline"),
891
    ("drained", None, ht.TMaybeBool,
892
     "Whether the node should be marked as drained"),
893
    ("auto_promote", False, ht.TBool,
894
     "Whether node(s) should be promoted to master candidate if necessary"),
895
    ("master_capable", None, ht.TMaybeBool,
896
     "Denote whether node can become master or master candidate"),
897
    ("vm_capable", None, ht.TMaybeBool,
898
     "Denote whether node can host instances"),
899
    ("secondary_ip", None, ht.TMaybeString,
900
     "Change node's secondary IP address"),
901
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
902
    ("powered", None, ht.TMaybeBool,
903
     "Whether the node should be marked as powered"),
904
    ]
905

    
906

    
907
class OpNodePowercycle(OpCode):
908
  """Tries to powercycle a node."""
909
  OP_DSC_FIELD = "node_name"
910
  OP_PARAMS = [
911
    _PNodeName,
912
    _PForce,
913
    ]
914

    
915

    
916
class OpNodeMigrate(OpCode):
917
  """Migrate all instances from a node."""
918
  OP_DSC_FIELD = "node_name"
919
  OP_PARAMS = [
920
    _PNodeName,
921
    _PMigrationMode,
922
    _PMigrationLive,
923
    _PMigrationTargetNode,
924
    ("iallocator", None, ht.TMaybeString,
925
     "Iallocator for deciding the target node for shared-storage instances"),
926
    ]
927

    
928

    
929
class OpNodeEvacuate(OpCode):
930
  """Evacuate instances off a number of nodes."""
931
  OP_DSC_FIELD = "node_name"
932
  OP_PARAMS = [
933
    _PEarlyRelease,
934
    _PNodeName,
935
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
936
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
937
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
938
     "Node evacuation mode"),
939
    ]
940

    
941

    
942
# instance opcodes
943

    
944
class OpInstanceCreate(OpCode):
945
  """Create an instance.
946

947
  @ivar instance_name: Instance name
948
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
949
  @ivar source_handshake: Signed handshake from source (remote import only)
950
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
951
  @ivar source_instance_name: Previous name of instance (remote import only)
952
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
953
    (remote import only)
954

955
  """
956
  OP_DSC_FIELD = "instance_name"
957
  OP_PARAMS = [
958
    _PInstanceName,
959
    _PForceVariant,
960
    _PWaitForSync,
961
    _PNameCheck,
962
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
963
    ("disks", ht.NoDefault,
964
     # TODO: Generate check from constants.IDISK_PARAMS_TYPES
965
     ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
966
                           ht.TOr(ht.TNonEmptyString, ht.TInt))),
967
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
968
     " each disk definition must contain a ``%s`` value and"
969
     " can contain an optional ``%s`` value denoting the disk access mode"
970
     " (%s)" %
971
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
972
      constants.IDISK_MODE,
973
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
974
    ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
975
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
976
     "Driver for file-backed disks"),
977
    ("file_storage_dir", None, ht.TMaybeString,
978
     "Directory for storing file-backed disks"),
979
    ("hvparams", ht.EmptyDict, ht.TDict,
980
     "Hypervisor parameters for instance, hypervisor-dependent"),
981
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
982
    ("iallocator", None, ht.TMaybeString,
983
     "Iallocator for deciding which node(s) to use"),
984
    ("identify_defaults", False, ht.TBool,
985
     "Reset instance parameters to default if equal"),
986
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
987
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
988
     "Instance creation mode"),
989
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
990
     "List of NIC (network interface) definitions, for example"
991
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
992
     " contain the optional values %s" %
993
     (constants.INIC_IP,
994
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
995
    ("no_install", None, ht.TMaybeBool,
996
     "Do not install the OS (will disable automatic start)"),
997
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
998
    ("os_type", None, ht.TMaybeString, "Operating system"),
999
    ("pnode", None, ht.TMaybeString, "Primary node"),
1000
    ("snode", None, ht.TMaybeString, "Secondary node"),
1001
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1002
     "Signed handshake from source (remote import only)"),
1003
    ("source_instance_name", None, ht.TMaybeString,
1004
     "Source instance name (remote import only)"),
1005
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1006
     ht.TPositiveInt,
1007
     "How long source instance was given to shut down (remote import only)"),
1008
    ("source_x509_ca", None, ht.TMaybeString,
1009
     "Source X509 CA in PEM format (remote import only)"),
1010
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1011
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1012
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1013
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1014
    ]
1015

    
1016

    
1017
class OpInstanceReinstall(OpCode):
1018
  """Reinstall an instance's OS."""
1019
  OP_DSC_FIELD = "instance_name"
1020
  OP_PARAMS = [
1021
    _PInstanceName,
1022
    _PForceVariant,
1023
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1024
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1025
    ]
1026

    
1027

    
1028
class OpInstanceRemove(OpCode):
1029
  """Remove an instance."""
1030
  OP_DSC_FIELD = "instance_name"
1031
  OP_PARAMS = [
1032
    _PInstanceName,
1033
    _PShutdownTimeout,
1034
    ("ignore_failures", False, ht.TBool,
1035
     "Whether to ignore failures during removal"),
1036
    ]
1037

    
1038

    
1039
class OpInstanceRename(OpCode):
1040
  """Rename an instance."""
1041
  OP_PARAMS = [
1042
    _PInstanceName,
1043
    _PNameCheck,
1044
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1045
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1046
    ]
1047

    
1048

    
1049
class OpInstanceStartup(OpCode):
1050
  """Startup an instance."""
1051
  OP_DSC_FIELD = "instance_name"
1052
  OP_PARAMS = [
1053
    _PInstanceName,
1054
    _PForce,
1055
    _PIgnoreOfflineNodes,
1056
    ("hvparams", ht.EmptyDict, ht.TDict,
1057
     "Temporary hypervisor parameters, hypervisor-dependent"),
1058
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1059
    _PNoRemember,
1060
    _PStartupPaused,
1061
    ]
1062

    
1063

    
1064
class OpInstanceShutdown(OpCode):
1065
  """Shutdown an instance."""
1066
  OP_DSC_FIELD = "instance_name"
1067
  OP_PARAMS = [
1068
    _PInstanceName,
1069
    _PIgnoreOfflineNodes,
1070
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1071
     "How long to wait for instance to shut down"),
1072
    _PNoRemember,
1073
    ]
1074

    
1075

    
1076
class OpInstanceReboot(OpCode):
1077
  """Reboot an instance."""
1078
  OP_DSC_FIELD = "instance_name"
1079
  OP_PARAMS = [
1080
    _PInstanceName,
1081
    _PShutdownTimeout,
1082
    ("ignore_secondaries", False, ht.TBool,
1083
     "Whether to start the instance even if secondary disks are failing"),
1084
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1085
     "How to reboot instance"),
1086
    ]
1087

    
1088

    
1089
class OpInstanceReplaceDisks(OpCode):
1090
  """Replace the disks of an instance."""
1091
  OP_DSC_FIELD = "instance_name"
1092
  OP_PARAMS = [
1093
    _PInstanceName,
1094
    _PEarlyRelease,
1095
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1096
     "Replacement mode"),
1097
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1098
     "Disk indexes"),
1099
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1100
    ("iallocator", None, ht.TMaybeString,
1101
     "Iallocator for deciding new secondary node"),
1102
    ]
1103

    
1104

    
1105
class OpInstanceFailover(OpCode):
1106
  """Failover an instance."""
1107
  OP_DSC_FIELD = "instance_name"
1108
  OP_PARAMS = [
1109
    _PInstanceName,
1110
    _PShutdownTimeout,
1111
    _PIgnoreConsistency,
1112
    _PMigrationTargetNode,
1113
    ("iallocator", None, ht.TMaybeString,
1114
     "Iallocator for deciding the target node for shared-storage instances"),
1115
    ]
1116

    
1117

    
1118
class OpInstanceMigrate(OpCode):
1119
  """Migrate an instance.
1120

1121
  This migrates (without shutting down an instance) to its secondary
1122
  node.
1123

1124
  @ivar instance_name: the name of the instance
1125
  @ivar mode: the migration mode (live, non-live or None for auto)
1126

1127
  """
1128
  OP_DSC_FIELD = "instance_name"
1129
  OP_PARAMS = [
1130
    _PInstanceName,
1131
    _PMigrationMode,
1132
    _PMigrationLive,
1133
    _PMigrationTargetNode,
1134
    ("cleanup", False, ht.TBool,
1135
     "Whether a previously failed migration should be cleaned up"),
1136
    ("iallocator", None, ht.TMaybeString,
1137
     "Iallocator for deciding the target node for shared-storage instances"),
1138
    ("allow_failover", False, ht.TBool,
1139
     "Whether we can fallback to failover if migration is not possible"),
1140
    ]
1141

    
1142

    
1143
class OpInstanceMove(OpCode):
1144
  """Move an instance.
1145

1146
  This move (with shutting down an instance and data copying) to an
1147
  arbitrary node.
1148

1149
  @ivar instance_name: the name of the instance
1150
  @ivar target_node: the destination node
1151

1152
  """
1153
  OP_DSC_FIELD = "instance_name"
1154
  OP_PARAMS = [
1155
    _PInstanceName,
1156
    _PShutdownTimeout,
1157
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1158
    _PIgnoreConsistency,
1159
    ]
1160

    
1161

    
1162
class OpInstanceConsole(OpCode):
1163
  """Connect to an instance's console."""
1164
  OP_DSC_FIELD = "instance_name"
1165
  OP_PARAMS = [
1166
    _PInstanceName
1167
    ]
1168

    
1169

    
1170
class OpInstanceActivateDisks(OpCode):
1171
  """Activate an instance's disks."""
1172
  OP_DSC_FIELD = "instance_name"
1173
  OP_PARAMS = [
1174
    _PInstanceName,
1175
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1176
    ]
1177

    
1178

    
1179
class OpInstanceDeactivateDisks(OpCode):
1180
  """Deactivate an instance's disks."""
1181
  OP_DSC_FIELD = "instance_name"
1182
  OP_PARAMS = [
1183
    _PInstanceName,
1184
    _PForce,
1185
    ]
1186

    
1187

    
1188
class OpInstanceRecreateDisks(OpCode):
1189
  """Deactivate an instance's disks."""
1190
  OP_DSC_FIELD = "instance_name"
1191
  OP_PARAMS = [
1192
    _PInstanceName,
1193
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1194
     "List of disk indexes"),
1195
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1196
     "New instance nodes, if relocation is desired"),
1197
    ]
1198

    
1199

    
1200
class OpInstanceQuery(OpCode):
1201
  """Compute the list of instances."""
1202
  OP_PARAMS = [
1203
    _POutputFields,
1204
    _PUseLocking,
1205
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1206
     "Empty list to query all instances, instance names otherwise"),
1207
    ]
1208

    
1209

    
1210
class OpInstanceQueryData(OpCode):
1211
  """Compute the run-time status of instances."""
1212
  OP_PARAMS = [
1213
    _PUseLocking,
1214
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1215
     "Instance names"),
1216
    ("static", False, ht.TBool,
1217
     "Whether to only return configuration data without querying"
1218
     " nodes"),
1219
    ]
1220

    
1221

    
1222
class OpInstanceSetParams(OpCode):
1223
  """Change the parameters of an instance."""
1224
  OP_DSC_FIELD = "instance_name"
1225
  OP_PARAMS = [
1226
    _PInstanceName,
1227
    _PForce,
1228
    _PForceVariant,
1229
    # TODO: Use _TestNicDef
1230
    ("nics", ht.EmptyList, ht.TList,
1231
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1232
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1233
     " ``%s`` to remove the last NIC or a number to modify the settings"
1234
     " of the NIC with that index." %
1235
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1236
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1237
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1238
    ("hvparams", ht.EmptyDict, ht.TDict,
1239
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1240
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1241
     "Disk template for instance"),
1242
    ("remote_node", None, ht.TMaybeString,
1243
     "Secondary node (used when changing disk template)"),
1244
    ("os_name", None, ht.TMaybeString,
1245
     "Change instance's OS name. Does not reinstall the instance."),
1246
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1247
    ("wait_for_sync", True, ht.TBool,
1248
     "Whether to wait for the disk to synchronize, when changing template"),
1249
    ]
1250

    
1251

    
1252
class OpInstanceGrowDisk(OpCode):
1253
  """Grow a disk of an instance."""
1254
  OP_DSC_FIELD = "instance_name"
1255
  OP_PARAMS = [
1256
    _PInstanceName,
1257
    _PWaitForSync,
1258
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1259
    ("amount", ht.NoDefault, ht.TInt,
1260
     "Amount of disk space to add (megabytes)"),
1261
    ]
1262

    
1263

    
1264
# Node group opcodes
1265

    
1266
class OpGroupAdd(OpCode):
1267
  """Add a node group to the cluster."""
1268
  OP_DSC_FIELD = "group_name"
1269
  OP_PARAMS = [
1270
    _PGroupName,
1271
    _PNodeGroupAllocPolicy,
1272
    _PGroupNodeParams,
1273
    ]
1274

    
1275

    
1276
class OpGroupAssignNodes(OpCode):
1277
  """Assign nodes to a node group."""
1278
  OP_DSC_FIELD = "group_name"
1279
  OP_PARAMS = [
1280
    _PGroupName,
1281
    _PForce,
1282
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1283
     "List of nodes to assign"),
1284
    ]
1285

    
1286

    
1287
class OpGroupQuery(OpCode):
1288
  """Compute the list of node groups."""
1289
  OP_PARAMS = [
1290
    _POutputFields,
1291
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1292
     "Empty list to query all groups, group names otherwise"),
1293
    ]
1294

    
1295

    
1296
class OpGroupSetParams(OpCode):
1297
  """Change the parameters of a node group."""
1298
  OP_DSC_FIELD = "group_name"
1299
  OP_PARAMS = [
1300
    _PGroupName,
1301
    _PNodeGroupAllocPolicy,
1302
    _PGroupNodeParams,
1303
    ]
1304

    
1305

    
1306
class OpGroupRemove(OpCode):
1307
  """Remove a node group from the cluster."""
1308
  OP_DSC_FIELD = "group_name"
1309
  OP_PARAMS = [
1310
    _PGroupName,
1311
    ]
1312

    
1313

    
1314
class OpGroupRename(OpCode):
1315
  """Rename a node group in the cluster."""
1316
  OP_PARAMS = [
1317
    _PGroupName,
1318
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1319
    ]
1320

    
1321

    
1322
class OpGroupEvacuate(OpCode):
1323
  """Evacuate a node group in the cluster."""
1324
  OP_DSC_FIELD = "group_name"
1325
  OP_PARAMS = [
1326
    _PGroupName,
1327
    _PEarlyRelease,
1328
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1329
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1330
     "Destination group names or UUIDs"),
1331
    ]
1332

    
1333

    
1334
# OS opcodes
1335
class OpOsDiagnose(OpCode):
1336
  """Compute the list of guest operating systems."""
1337
  OP_PARAMS = [
1338
    _POutputFields,
1339
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1340
     "Which operating systems to diagnose"),
1341
    ]
1342

    
1343

    
1344
# Exports opcodes
1345
class OpBackupQuery(OpCode):
1346
  """Compute the list of exported images."""
1347
  OP_PARAMS = [
1348
    _PUseLocking,
1349
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1350
     "Empty list to query all nodes, node names otherwise"),
1351
    ]
1352

    
1353

    
1354
class OpBackupPrepare(OpCode):
1355
  """Prepares an instance export.
1356

1357
  @ivar instance_name: Instance name
1358
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1359

1360
  """
1361
  OP_DSC_FIELD = "instance_name"
1362
  OP_PARAMS = [
1363
    _PInstanceName,
1364
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1365
     "Export mode"),
1366
    ]
1367

    
1368

    
1369
class OpBackupExport(OpCode):
1370
  """Export an instance.
1371

1372
  For local exports, the export destination is the node name. For remote
1373
  exports, the export destination is a list of tuples, each consisting of
1374
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1375
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1376
  destination X509 CA must be a signed certificate.
1377

1378
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1379
  @ivar target_node: Export destination
1380
  @ivar x509_key_name: X509 key to use (remote export only)
1381
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1382
                             only)
1383

1384
  """
1385
  OP_DSC_FIELD = "instance_name"
1386
  OP_PARAMS = [
1387
    _PInstanceName,
1388
    _PShutdownTimeout,
1389
    # TODO: Rename target_node as it changes meaning for different export modes
1390
    # (e.g. "destination")
1391
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1392
     "Destination information, depends on export mode"),
1393
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1394
    ("remove_instance", False, ht.TBool,
1395
     "Whether to remove instance after export"),
1396
    ("ignore_remove_failures", False, ht.TBool,
1397
     "Whether to ignore failures while removing instances"),
1398
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1399
     "Export mode"),
1400
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1401
     "Name of X509 key (remote export only)"),
1402
    ("destination_x509_ca", None, ht.TMaybeString,
1403
     "Destination X509 CA (remote export only)"),
1404
    ]
1405

    
1406

    
1407
class OpBackupRemove(OpCode):
1408
  """Remove an instance's export."""
1409
  OP_DSC_FIELD = "instance_name"
1410
  OP_PARAMS = [
1411
    _PInstanceName,
1412
    ]
1413

    
1414

    
1415
# Tags opcodes
1416
class OpTagsGet(OpCode):
1417
  """Returns the tags of the given object."""
1418
  OP_DSC_FIELD = "name"
1419
  OP_PARAMS = [
1420
    _PTagKind,
1421
    # Name is only meaningful for nodes and instances
1422
    ("name", ht.NoDefault, ht.TMaybeString, None),
1423
    ]
1424

    
1425

    
1426
class OpTagsSearch(OpCode):
1427
  """Searches the tags in the cluster for a given pattern."""
1428
  OP_DSC_FIELD = "pattern"
1429
  OP_PARAMS = [
1430
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1431
    ]
1432

    
1433

    
1434
class OpTagsSet(OpCode):
1435
  """Add a list of tags on a given object."""
1436
  OP_PARAMS = [
1437
    _PTagKind,
1438
    _PTags,
1439
    # Name is only meaningful for nodes and instances
1440
    ("name", ht.NoDefault, ht.TMaybeString, None),
1441
    ]
1442

    
1443

    
1444
class OpTagsDel(OpCode):
1445
  """Remove a list of tags from a given object."""
1446
  OP_PARAMS = [
1447
    _PTagKind,
1448
    _PTags,
1449
    # Name is only meaningful for nodes and instances
1450
    ("name", ht.NoDefault, ht.TMaybeString, None),
1451
    ]
1452

    
1453
# Test opcodes
1454
class OpTestDelay(OpCode):
1455
  """Sleeps for a configured amount of time.
1456

1457
  This is used just for debugging and testing.
1458

1459
  Parameters:
1460
    - duration: the time to sleep
1461
    - on_master: if true, sleep on the master
1462
    - on_nodes: list of nodes in which to sleep
1463

1464
  If the on_master parameter is true, it will execute a sleep on the
1465
  master (before any node sleep).
1466

1467
  If the on_nodes list is not empty, it will sleep on those nodes
1468
  (after the sleep on the master, if that is enabled).
1469

1470
  As an additional feature, the case of duration < 0 will be reported
1471
  as an execution error, so this opcode can be used as a failure
1472
  generator. The case of duration == 0 will not be treated specially.
1473

1474
  """
1475
  OP_DSC_FIELD = "duration"
1476
  OP_PARAMS = [
1477
    ("duration", ht.NoDefault, ht.TNumber, None),
1478
    ("on_master", True, ht.TBool, None),
1479
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1480
    ("repeat", 0, ht.TPositiveInt, None),
1481
    ]
1482

    
1483

    
1484
class OpTestAllocator(OpCode):
1485
  """Allocator framework testing.
1486

1487
  This opcode has two modes:
1488
    - gather and return allocator input for a given mode (allocate new
1489
      or replace secondary) and a given instance definition (direction
1490
      'in')
1491
    - run a selected allocator for a given operation (as above) and
1492
      return the allocator output (direction 'out')
1493

1494
  """
1495
  OP_DSC_FIELD = "allocator"
1496
  OP_PARAMS = [
1497
    ("direction", ht.NoDefault,
1498
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1499
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1500
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1501
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1502
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1503
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1504
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1505
    ("hypervisor", None, ht.TMaybeString, None),
1506
    ("allocator", None, ht.TMaybeString, None),
1507
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1508
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1509
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1510
    ("os", None, ht.TMaybeString, None),
1511
    ("disk_template", None, ht.TMaybeString, None),
1512
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1513
     None),
1514
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1515
     None),
1516
    ("evac_mode", None,
1517
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1518
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1519
     None),
1520
    ]
1521

    
1522

    
1523
class OpTestJqueue(OpCode):
1524
  """Utility opcode to test some aspects of the job queue.
1525

1526
  """
1527
  OP_PARAMS = [
1528
    ("notify_waitlock", False, ht.TBool, None),
1529
    ("notify_exec", False, ht.TBool, None),
1530
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1531
    ("fail", False, ht.TBool, None),
1532
    ]
1533

    
1534

    
1535
class OpTestDummy(OpCode):
1536
  """Utility opcode used by unittests.
1537

1538
  """
1539
  OP_PARAMS = [
1540
    ("result", ht.NoDefault, ht.NoType, None),
1541
    ("messages", ht.NoDefault, ht.NoType, None),
1542
    ("fail", ht.NoDefault, ht.NoType, None),
1543
    ("submit_jobs", None, ht.NoType, None),
1544
    ]
1545
  WITH_LU = False
1546

    
1547

    
1548
def _GetOpList():
1549
  """Returns list of all defined opcodes.
1550

1551
  Does not eliminate duplicates by C{OP_ID}.
1552

1553
  """
1554
  return [v for v in globals().values()
1555
          if (isinstance(v, type) and issubclass(v, OpCode) and
1556
              hasattr(v, "OP_ID") and v is not OpCode)]
1557

    
1558

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