Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ ae1a845c

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
  """
598

    
599

    
600
class OpGroupVerifyDisks(OpCode):
601
  """Verifies the status of all disks in a node group.
602

603
  Result: a tuple of three elements:
604
    - dict of node names with issues (values: error msg)
605
    - list of instances with degraded disks (that should be activated)
606
    - dict of instances with missing logical volumes (values: (node, vol)
607
      pairs with details about the missing volumes)
608

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

614
  Note that only instances that are drbd-based are taken into
615
  consideration. This might need to be revisited in the future.
616

617
  """
618
  OP_DSC_FIELD = "group_name"
619
  OP_PARAMS = [
620
    _PGroupName,
621
    ]
622

    
623

    
624
class OpClusterRepairDiskSizes(OpCode):
625
  """Verify the disk sizes of the instances and fixes configuration
626
  mimatches.
627

628
  Parameters: optional instances list, in case we want to restrict the
629
  checks to only a subset of the instances.
630

631
  Result: a list of tuples, (instance, disk, new-size) for changed
632
  configurations.
633

634
  In normal operation, the list should be empty.
635

636
  @type instances: list
637
  @ivar instances: the list of instances to check, or empty for all instances
638

639
  """
640
  OP_PARAMS = [
641
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
642
    ]
643

    
644

    
645
class OpClusterConfigQuery(OpCode):
646
  """Query cluster configuration values."""
647
  OP_PARAMS = [
648
    _POutputFields
649
    ]
650

    
651

    
652
class OpClusterRename(OpCode):
653
  """Rename the cluster.
654

655
  @type name: C{str}
656
  @ivar name: The new name of the cluster. The name and/or the master IP
657
              address will be changed to match the new name and its IP
658
              address.
659

660
  """
661
  OP_DSC_FIELD = "name"
662
  OP_PARAMS = [
663
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
664
    ]
665

    
666

    
667
class OpClusterSetParams(OpCode):
668
  """Change the parameters of the cluster.
669

670
  @type vg_name: C{str} or C{None}
671
  @ivar vg_name: The new volume group name or None to disable LVM usage.
672

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

    
725

    
726
class OpClusterRedistConf(OpCode):
727
  """Force a full push of the cluster configuration.
728

729
  """
730

    
731

    
732
class OpQuery(OpCode):
733
  """Query for resources/items.
734

735
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
736
  @ivar fields: List of fields to retrieve
737
  @ivar filter: Query filter
738

739
  """
740
  OP_PARAMS = [
741
    _PQueryWhat,
742
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
743
     "Requested fields"),
744
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
745
     "Query filter"),
746
    ]
747

    
748

    
749
class OpQueryFields(OpCode):
750
  """Query for available resource/item fields.
751

752
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
753
  @ivar fields: List of fields to retrieve
754

755
  """
756
  OP_PARAMS = [
757
    _PQueryWhat,
758
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
759
     "Requested fields; if not given, all are returned"),
760
    ]
761

    
762

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

    
778

    
779
# node opcodes
780

    
781
class OpNodeRemove(OpCode):
782
  """Remove a node.
783

784
  @type node_name: C{str}
785
  @ivar node_name: The name of the node to remove. If the node still has
786
                   instances on it, the operation will fail.
787

788
  """
789
  OP_DSC_FIELD = "node_name"
790
  OP_PARAMS = [
791
    _PNodeName,
792
    ]
793

    
794

    
795
class OpNodeAdd(OpCode):
796
  """Add a node to the cluster.
797

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

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

    
837

    
838
class OpNodeQuery(OpCode):
839
  """Compute the list of nodes."""
840
  OP_PARAMS = [
841
    _POutputFields,
842
    _PUseLocking,
843
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
844
     "Empty list to query all nodes, node names otherwise"),
845
    ]
846

    
847

    
848
class OpNodeQueryvols(OpCode):
849
  """Get list of volumes on node."""
850
  OP_PARAMS = [
851
    _POutputFields,
852
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
853
     "Empty list to query all nodes, node names otherwise"),
854
    ]
855

    
856

    
857
class OpNodeQueryStorage(OpCode):
858
  """Get information on storage for node(s)."""
859
  OP_PARAMS = [
860
    _POutputFields,
861
    _PStorageType,
862
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
863
    ("name", None, ht.TMaybeString, "Storage name"),
864
    ]
865

    
866

    
867
class OpNodeModifyStorage(OpCode):
868
  """Modifies the properies of a storage unit"""
869
  OP_PARAMS = [
870
    _PNodeName,
871
    _PStorageType,
872
    _PStorageName,
873
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
874
    ]
875

    
876

    
877
class OpRepairNodeStorage(OpCode):
878
  """Repairs the volume group on a node."""
879
  OP_DSC_FIELD = "node_name"
880
  OP_PARAMS = [
881
    _PNodeName,
882
    _PStorageType,
883
    _PStorageName,
884
    _PIgnoreConsistency,
885
    ]
886

    
887

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

    
913

    
914
class OpNodePowercycle(OpCode):
915
  """Tries to powercycle a node."""
916
  OP_DSC_FIELD = "node_name"
917
  OP_PARAMS = [
918
    _PNodeName,
919
    _PForce,
920
    ]
921

    
922

    
923
class OpNodeMigrate(OpCode):
924
  """Migrate all instances from a node."""
925
  OP_DSC_FIELD = "node_name"
926
  OP_PARAMS = [
927
    _PNodeName,
928
    _PMigrationMode,
929
    _PMigrationLive,
930
    _PMigrationTargetNode,
931
    ("iallocator", None, ht.TMaybeString,
932
     "Iallocator for deciding the target node for shared-storage instances"),
933
    ]
934

    
935

    
936
class OpNodeEvacuate(OpCode):
937
  """Evacuate instances off a number of nodes."""
938
  OP_DSC_FIELD = "node_name"
939
  OP_PARAMS = [
940
    _PEarlyRelease,
941
    _PNodeName,
942
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
943
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
944
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
945
     "Node evacuation mode"),
946
    ]
947

    
948

    
949
# instance opcodes
950

    
951
class OpInstanceCreate(OpCode):
952
  """Create an instance.
953

954
  @ivar instance_name: Instance name
955
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
956
  @ivar source_handshake: Signed handshake from source (remote import only)
957
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
958
  @ivar source_instance_name: Previous name of instance (remote import only)
959
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
960
    (remote import only)
961

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

    
1023

    
1024
class OpInstanceReinstall(OpCode):
1025
  """Reinstall an instance's OS."""
1026
  OP_DSC_FIELD = "instance_name"
1027
  OP_PARAMS = [
1028
    _PInstanceName,
1029
    _PForceVariant,
1030
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1031
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1032
    ]
1033

    
1034

    
1035
class OpInstanceRemove(OpCode):
1036
  """Remove an instance."""
1037
  OP_DSC_FIELD = "instance_name"
1038
  OP_PARAMS = [
1039
    _PInstanceName,
1040
    _PShutdownTimeout,
1041
    ("ignore_failures", False, ht.TBool,
1042
     "Whether to ignore failures during removal"),
1043
    ]
1044

    
1045

    
1046
class OpInstanceRename(OpCode):
1047
  """Rename an instance."""
1048
  OP_PARAMS = [
1049
    _PInstanceName,
1050
    _PNameCheck,
1051
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1052
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1053
    ]
1054

    
1055

    
1056
class OpInstanceStartup(OpCode):
1057
  """Startup an instance."""
1058
  OP_DSC_FIELD = "instance_name"
1059
  OP_PARAMS = [
1060
    _PInstanceName,
1061
    _PForce,
1062
    _PIgnoreOfflineNodes,
1063
    ("hvparams", ht.EmptyDict, ht.TDict,
1064
     "Temporary hypervisor parameters, hypervisor-dependent"),
1065
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1066
    _PNoRemember,
1067
    _PStartupPaused,
1068
    ]
1069

    
1070

    
1071
class OpInstanceShutdown(OpCode):
1072
  """Shutdown an instance."""
1073
  OP_DSC_FIELD = "instance_name"
1074
  OP_PARAMS = [
1075
    _PInstanceName,
1076
    _PIgnoreOfflineNodes,
1077
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1078
     "How long to wait for instance to shut down"),
1079
    _PNoRemember,
1080
    ]
1081

    
1082

    
1083
class OpInstanceReboot(OpCode):
1084
  """Reboot an instance."""
1085
  OP_DSC_FIELD = "instance_name"
1086
  OP_PARAMS = [
1087
    _PInstanceName,
1088
    _PShutdownTimeout,
1089
    ("ignore_secondaries", False, ht.TBool,
1090
     "Whether to start the instance even if secondary disks are failing"),
1091
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1092
     "How to reboot instance"),
1093
    ]
1094

    
1095

    
1096
class OpInstanceReplaceDisks(OpCode):
1097
  """Replace the disks of an instance."""
1098
  OP_DSC_FIELD = "instance_name"
1099
  OP_PARAMS = [
1100
    _PInstanceName,
1101
    _PEarlyRelease,
1102
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1103
     "Replacement mode"),
1104
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1105
     "Disk indexes"),
1106
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1107
    ("iallocator", None, ht.TMaybeString,
1108
     "Iallocator for deciding new secondary node"),
1109
    ]
1110

    
1111

    
1112
class OpInstanceFailover(OpCode):
1113
  """Failover an instance."""
1114
  OP_DSC_FIELD = "instance_name"
1115
  OP_PARAMS = [
1116
    _PInstanceName,
1117
    _PShutdownTimeout,
1118
    _PIgnoreConsistency,
1119
    _PMigrationTargetNode,
1120
    ("iallocator", None, ht.TMaybeString,
1121
     "Iallocator for deciding the target node for shared-storage instances"),
1122
    ]
1123

    
1124

    
1125
class OpInstanceMigrate(OpCode):
1126
  """Migrate an instance.
1127

1128
  This migrates (without shutting down an instance) to its secondary
1129
  node.
1130

1131
  @ivar instance_name: the name of the instance
1132
  @ivar mode: the migration mode (live, non-live or None for auto)
1133

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

    
1149

    
1150
class OpInstanceMove(OpCode):
1151
  """Move an instance.
1152

1153
  This move (with shutting down an instance and data copying) to an
1154
  arbitrary node.
1155

1156
  @ivar instance_name: the name of the instance
1157
  @ivar target_node: the destination node
1158

1159
  """
1160
  OP_DSC_FIELD = "instance_name"
1161
  OP_PARAMS = [
1162
    _PInstanceName,
1163
    _PShutdownTimeout,
1164
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1165
    _PIgnoreConsistency,
1166
    ]
1167

    
1168

    
1169
class OpInstanceConsole(OpCode):
1170
  """Connect to an instance's console."""
1171
  OP_DSC_FIELD = "instance_name"
1172
  OP_PARAMS = [
1173
    _PInstanceName
1174
    ]
1175

    
1176

    
1177
class OpInstanceActivateDisks(OpCode):
1178
  """Activate an instance's disks."""
1179
  OP_DSC_FIELD = "instance_name"
1180
  OP_PARAMS = [
1181
    _PInstanceName,
1182
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1183
    ]
1184

    
1185

    
1186
class OpInstanceDeactivateDisks(OpCode):
1187
  """Deactivate an instance's disks."""
1188
  OP_DSC_FIELD = "instance_name"
1189
  OP_PARAMS = [
1190
    _PInstanceName,
1191
    _PForce,
1192
    ]
1193

    
1194

    
1195
class OpInstanceRecreateDisks(OpCode):
1196
  """Deactivate an instance's disks."""
1197
  OP_DSC_FIELD = "instance_name"
1198
  OP_PARAMS = [
1199
    _PInstanceName,
1200
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1201
     "List of disk indexes"),
1202
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1203
     "New instance nodes, if relocation is desired"),
1204
    ]
1205

    
1206

    
1207
class OpInstanceQuery(OpCode):
1208
  """Compute the list of instances."""
1209
  OP_PARAMS = [
1210
    _POutputFields,
1211
    _PUseLocking,
1212
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1213
     "Empty list to query all instances, instance names otherwise"),
1214
    ]
1215

    
1216

    
1217
class OpInstanceQueryData(OpCode):
1218
  """Compute the run-time status of instances."""
1219
  OP_PARAMS = [
1220
    _PUseLocking,
1221
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1222
     "Instance names"),
1223
    ("static", False, ht.TBool,
1224
     "Whether to only return configuration data without querying"
1225
     " nodes"),
1226
    ]
1227

    
1228

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

    
1258

    
1259
class OpInstanceGrowDisk(OpCode):
1260
  """Grow a disk of an instance."""
1261
  OP_DSC_FIELD = "instance_name"
1262
  OP_PARAMS = [
1263
    _PInstanceName,
1264
    _PWaitForSync,
1265
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1266
    ("amount", ht.NoDefault, ht.TInt,
1267
     "Amount of disk space to add (megabytes)"),
1268
    ]
1269

    
1270

    
1271
# Node group opcodes
1272

    
1273
class OpGroupAdd(OpCode):
1274
  """Add a node group to the cluster."""
1275
  OP_DSC_FIELD = "group_name"
1276
  OP_PARAMS = [
1277
    _PGroupName,
1278
    _PNodeGroupAllocPolicy,
1279
    _PGroupNodeParams,
1280
    ]
1281

    
1282

    
1283
class OpGroupAssignNodes(OpCode):
1284
  """Assign nodes to a node group."""
1285
  OP_DSC_FIELD = "group_name"
1286
  OP_PARAMS = [
1287
    _PGroupName,
1288
    _PForce,
1289
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1290
     "List of nodes to assign"),
1291
    ]
1292

    
1293

    
1294
class OpGroupQuery(OpCode):
1295
  """Compute the list of node groups."""
1296
  OP_PARAMS = [
1297
    _POutputFields,
1298
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1299
     "Empty list to query all groups, group names otherwise"),
1300
    ]
1301

    
1302

    
1303
class OpGroupSetParams(OpCode):
1304
  """Change the parameters of a node group."""
1305
  OP_DSC_FIELD = "group_name"
1306
  OP_PARAMS = [
1307
    _PGroupName,
1308
    _PNodeGroupAllocPolicy,
1309
    _PGroupNodeParams,
1310
    ]
1311

    
1312

    
1313
class OpGroupRemove(OpCode):
1314
  """Remove a node group from the cluster."""
1315
  OP_DSC_FIELD = "group_name"
1316
  OP_PARAMS = [
1317
    _PGroupName,
1318
    ]
1319

    
1320

    
1321
class OpGroupRename(OpCode):
1322
  """Rename a node group in the cluster."""
1323
  OP_PARAMS = [
1324
    _PGroupName,
1325
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1326
    ]
1327

    
1328

    
1329
class OpGroupEvacuate(OpCode):
1330
  """Evacuate a node group in the cluster."""
1331
  OP_DSC_FIELD = "group_name"
1332
  OP_PARAMS = [
1333
    _PGroupName,
1334
    _PEarlyRelease,
1335
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1336
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1337
     "Destination group names or UUIDs"),
1338
    ]
1339

    
1340

    
1341
# OS opcodes
1342
class OpOsDiagnose(OpCode):
1343
  """Compute the list of guest operating systems."""
1344
  OP_PARAMS = [
1345
    _POutputFields,
1346
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1347
     "Which operating systems to diagnose"),
1348
    ]
1349

    
1350

    
1351
# Exports opcodes
1352
class OpBackupQuery(OpCode):
1353
  """Compute the list of exported images."""
1354
  OP_PARAMS = [
1355
    _PUseLocking,
1356
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1357
     "Empty list to query all nodes, node names otherwise"),
1358
    ]
1359

    
1360

    
1361
class OpBackupPrepare(OpCode):
1362
  """Prepares an instance export.
1363

1364
  @ivar instance_name: Instance name
1365
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1366

1367
  """
1368
  OP_DSC_FIELD = "instance_name"
1369
  OP_PARAMS = [
1370
    _PInstanceName,
1371
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1372
     "Export mode"),
1373
    ]
1374

    
1375

    
1376
class OpBackupExport(OpCode):
1377
  """Export an instance.
1378

1379
  For local exports, the export destination is the node name. For remote
1380
  exports, the export destination is a list of tuples, each consisting of
1381
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1382
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1383
  destination X509 CA must be a signed certificate.
1384

1385
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1386
  @ivar target_node: Export destination
1387
  @ivar x509_key_name: X509 key to use (remote export only)
1388
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1389
                             only)
1390

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

    
1413

    
1414
class OpBackupRemove(OpCode):
1415
  """Remove an instance's export."""
1416
  OP_DSC_FIELD = "instance_name"
1417
  OP_PARAMS = [
1418
    _PInstanceName,
1419
    ]
1420

    
1421

    
1422
# Tags opcodes
1423
class OpTagsGet(OpCode):
1424
  """Returns the tags of the given object."""
1425
  OP_DSC_FIELD = "name"
1426
  OP_PARAMS = [
1427
    _PTagKind,
1428
    # Name is only meaningful for nodes and instances
1429
    ("name", ht.NoDefault, ht.TMaybeString, None),
1430
    ]
1431

    
1432

    
1433
class OpTagsSearch(OpCode):
1434
  """Searches the tags in the cluster for a given pattern."""
1435
  OP_DSC_FIELD = "pattern"
1436
  OP_PARAMS = [
1437
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1438
    ]
1439

    
1440

    
1441
class OpTagsSet(OpCode):
1442
  """Add a list of tags on a given object."""
1443
  OP_PARAMS = [
1444
    _PTagKind,
1445
    _PTags,
1446
    # Name is only meaningful for nodes and instances
1447
    ("name", ht.NoDefault, ht.TMaybeString, None),
1448
    ]
1449

    
1450

    
1451
class OpTagsDel(OpCode):
1452
  """Remove a list of tags from a given object."""
1453
  OP_PARAMS = [
1454
    _PTagKind,
1455
    _PTags,
1456
    # Name is only meaningful for nodes and instances
1457
    ("name", ht.NoDefault, ht.TMaybeString, None),
1458
    ]
1459

    
1460
# Test opcodes
1461
class OpTestDelay(OpCode):
1462
  """Sleeps for a configured amount of time.
1463

1464
  This is used just for debugging and testing.
1465

1466
  Parameters:
1467
    - duration: the time to sleep
1468
    - on_master: if true, sleep on the master
1469
    - on_nodes: list of nodes in which to sleep
1470

1471
  If the on_master parameter is true, it will execute a sleep on the
1472
  master (before any node sleep).
1473

1474
  If the on_nodes list is not empty, it will sleep on those nodes
1475
  (after the sleep on the master, if that is enabled).
1476

1477
  As an additional feature, the case of duration < 0 will be reported
1478
  as an execution error, so this opcode can be used as a failure
1479
  generator. The case of duration == 0 will not be treated specially.
1480

1481
  """
1482
  OP_DSC_FIELD = "duration"
1483
  OP_PARAMS = [
1484
    ("duration", ht.NoDefault, ht.TNumber, None),
1485
    ("on_master", True, ht.TBool, None),
1486
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1487
    ("repeat", 0, ht.TPositiveInt, None),
1488
    ]
1489

    
1490

    
1491
class OpTestAllocator(OpCode):
1492
  """Allocator framework testing.
1493

1494
  This opcode has two modes:
1495
    - gather and return allocator input for a given mode (allocate new
1496
      or replace secondary) and a given instance definition (direction
1497
      'in')
1498
    - run a selected allocator for a given operation (as above) and
1499
      return the allocator output (direction 'out')
1500

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

    
1529

    
1530
class OpTestJqueue(OpCode):
1531
  """Utility opcode to test some aspects of the job queue.
1532

1533
  """
1534
  OP_PARAMS = [
1535
    ("notify_waitlock", False, ht.TBool, None),
1536
    ("notify_exec", False, ht.TBool, None),
1537
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1538
    ("fail", False, ht.TBool, None),
1539
    ]
1540

    
1541

    
1542
class OpTestDummy(OpCode):
1543
  """Utility opcode used by unittests.
1544

1545
  """
1546
  OP_PARAMS = [
1547
    ("result", ht.NoDefault, ht.NoType, None),
1548
    ("messages", ht.NoDefault, ht.NoType, None),
1549
    ("fail", ht.NoDefault, ht.NoType, None),
1550
    ("submit_jobs", None, ht.NoType, None),
1551
    ]
1552
  WITH_LU = False
1553

    
1554

    
1555
def _GetOpList():
1556
  """Returns list of all defined opcodes.
1557

1558
  Does not eliminate duplicates by C{OP_ID}.
1559

1560
  """
1561
  return [v for v in globals().values()
1562
          if (isinstance(v, type) and issubclass(v, OpCode) and
1563
              hasattr(v, "OP_ID") and v is not OpCode)]
1564

    
1565

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