Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ eb62069e

History | View | Annotate | Download (48.5 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 compat
41
from ganeti import constants
42
from ganeti import errors
43
from ganeti import ht
44

    
45

    
46
# Common opcode attributes
47

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
132

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

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

    
142

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

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

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

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

    
161

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

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

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

    
182

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

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

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

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

    
196

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

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

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

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

    
210

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

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

    
222

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

    
226

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

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

    
238

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

    
243

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

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

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

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

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

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

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

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

    
273
    attrs["__slots__"] = slots
274

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

    
277

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
399

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

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

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

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

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

    
420

    
421
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
422

    
423
#: List of submission status and job ID as returned by C{SubmitManyJobs}
424
TJobIdList = ht.TListOf(ht.TItems([ht.TBool, ht.TOr(ht.TString, ht.TJobId)]))
425

    
426

    
427
class OpCode(BaseOpCode):
428
  """Abstract OpCode.
429

430
  This is the root of the actual OpCode hierarchy. All clases derived
431
  from this class should override OP_ID.
432

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

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

    
464
  def __getstate__(self):
465
    """Specialized getstate for opcodes.
466

467
    This method adds to the state dictionary the OP_ID of the class,
468
    so that on unload we can identify the correct class for
469
    instantiating the opcode.
470

471
    @rtype:   C{dict}
472
    @return:  the state as a dictionary
473

474
    """
475
    data = BaseOpCode.__getstate__(self)
476
    data["OP_ID"] = self.OP_ID
477
    return data
478

    
479
  @classmethod
480
  def LoadOpCode(cls, data):
481
    """Generic load opcode method.
482

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

487
    @type data:  C{dict}
488
    @param data: the serialized opcode
489

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

    
508
  def Summary(self):
509
    """Generates a summary description of this opcode.
510

511
    The summary is the value of the OP_ID attribute (without the "OP_"
512
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
513
    defined; this field should allow to easily identify the operation
514
    (for an instance creation job, e.g., it would be the instance
515
    name).
516

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

    
529
  def TinySummary(self):
530
    """Generates a compact summary description of the opcode.
531

532
    """
533
    assert self.OP_ID.startswith("OP_")
534

    
535
    text = self.OP_ID[3:]
536

    
537
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
538
      if text.startswith(prefix):
539
        return supplement + text[len(prefix):]
540

    
541
    return text
542

    
543

    
544
# cluster opcodes
545

    
546
class OpClusterPostInit(OpCode):
547
  """Post cluster initialization.
548

549
  This opcode does not touch the cluster at all. Its purpose is to run hooks
550
  after the cluster has been initialized.
551

552
  """
553

    
554

    
555
class OpClusterDestroy(OpCode):
556
  """Destroy the cluster.
557

558
  This opcode has no other parameters. All the state is irreversibly
559
  lost after the execution of this opcode.
560

561
  """
562

    
563

    
564
class OpClusterQuery(OpCode):
565
  """Query cluster information."""
566

    
567

    
568
class OpClusterVerifyConfig(OpCode):
569
  """Verify the cluster config.
570

571
  """
572
  OP_PARAMS = [
573
    ("verbose", False, ht.TBool, None),
574
    ("error_codes", False, ht.TBool, None),
575
    ("debug_simulate_errors", False, ht.TBool, None),
576
    ]
577

    
578

    
579
class OpClusterVerifyGroup(OpCode):
580
  """Run verify on a node group from the cluster.
581

582
  @type skip_checks: C{list}
583
  @ivar skip_checks: steps to be skipped from the verify process; this
584
                     needs to be a subset of
585
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
586
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
587

588
  """
589
  OP_DSC_FIELD = "group_name"
590
  OP_PARAMS = [
591
    ("group_name", ht.NoDefault, ht.TNonEmptyString, None),
592
    ("skip_checks", ht.EmptyList,
593
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
594
    ("verbose", False, ht.TBool, None),
595
    ("error_codes", False, ht.TBool, None),
596
    ("debug_simulate_errors", False, ht.TBool, None),
597
    ]
598

    
599

    
600
class OpClusterVerifyDisks(OpCode):
601
  """Verify the cluster disks.
602

603
  """
604
  OP_RESULT = ht.TStrictDict(True, True, {
605
    constants.JOB_IDS_KEY: TJobIdList,
606
    })
607

    
608

    
609
class OpGroupVerifyDisks(OpCode):
610
  """Verifies the status of all disks in a node group.
611

612
  Result: a tuple of three elements:
613
    - dict of node names with issues (values: error msg)
614
    - list of instances with degraded disks (that should be activated)
615
    - dict of instances with missing logical volumes (values: (node, vol)
616
      pairs with details about the missing volumes)
617

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

623
  Note that only instances that are drbd-based are taken into
624
  consideration. This might need to be revisited in the future.
625

626
  """
627
  OP_DSC_FIELD = "group_name"
628
  OP_PARAMS = [
629
    _PGroupName,
630
    ]
631
  OP_RESULT = \
632
    ht.TAnd(ht.TIsLength(3),
633
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
634
                       ht.TListOf(ht.TString),
635
                       ht.TDictOf(ht.TString, ht.TListOf(ht.TString))]))
636

    
637

    
638
class OpClusterRepairDiskSizes(OpCode):
639
  """Verify the disk sizes of the instances and fixes configuration
640
  mimatches.
641

642
  Parameters: optional instances list, in case we want to restrict the
643
  checks to only a subset of the instances.
644

645
  Result: a list of tuples, (instance, disk, new-size) for changed
646
  configurations.
647

648
  In normal operation, the list should be empty.
649

650
  @type instances: list
651
  @ivar instances: the list of instances to check, or empty for all instances
652

653
  """
654
  OP_PARAMS = [
655
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
656
    ]
657

    
658

    
659
class OpClusterConfigQuery(OpCode):
660
  """Query cluster configuration values."""
661
  OP_PARAMS = [
662
    _POutputFields
663
    ]
664

    
665

    
666
class OpClusterRename(OpCode):
667
  """Rename the cluster.
668

669
  @type name: C{str}
670
  @ivar name: The new name of the cluster. The name and/or the master IP
671
              address will be changed to match the new name and its IP
672
              address.
673

674
  """
675
  OP_DSC_FIELD = "name"
676
  OP_PARAMS = [
677
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
678
    ]
679

    
680

    
681
class OpClusterSetParams(OpCode):
682
  """Change the parameters of the cluster.
683

684
  @type vg_name: C{str} or C{None}
685
  @ivar vg_name: The new volume group name or None to disable LVM usage.
686

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

    
739

    
740
class OpClusterRedistConf(OpCode):
741
  """Force a full push of the cluster configuration.
742

743
  """
744

    
745

    
746
class OpQuery(OpCode):
747
  """Query for resources/items.
748

749
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
750
  @ivar fields: List of fields to retrieve
751
  @ivar filter: Query filter
752

753
  """
754
  OP_PARAMS = [
755
    _PQueryWhat,
756
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
757
     "Requested fields"),
758
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
759
     "Query filter"),
760
    ]
761

    
762

    
763
class OpQueryFields(OpCode):
764
  """Query for available resource/item fields.
765

766
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
767
  @ivar fields: List of fields to retrieve
768

769
  """
770
  OP_PARAMS = [
771
    _PQueryWhat,
772
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
773
     "Requested fields; if not given, all are returned"),
774
    ]
775

    
776

    
777
class OpOobCommand(OpCode):
778
  """Interact with OOB."""
779
  OP_PARAMS = [
780
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
781
     "List of nodes to run the OOB command against"),
782
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
783
     "OOB command to be run"),
784
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
785
     "Timeout before the OOB helper will be terminated"),
786
    ("ignore_status", False, ht.TBool,
787
     "Ignores the node offline status for power off"),
788
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
789
     "Time in seconds to wait between powering on nodes"),
790
    ]
791

    
792

    
793
# node opcodes
794

    
795
class OpNodeRemove(OpCode):
796
  """Remove a node.
797

798
  @type node_name: C{str}
799
  @ivar node_name: The name of the node to remove. If the node still has
800
                   instances on it, the operation will fail.
801

802
  """
803
  OP_DSC_FIELD = "node_name"
804
  OP_PARAMS = [
805
    _PNodeName,
806
    ]
807

    
808

    
809
class OpNodeAdd(OpCode):
810
  """Add a node to the cluster.
811

812
  @type node_name: C{str}
813
  @ivar node_name: The name of the node to add. This can be a short name,
814
                   but it will be expanded to the FQDN.
815
  @type primary_ip: IP address
816
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
817
                    opcode is submitted, but will be filled during the node
818
                    add (so it will be visible in the job query).
819
  @type secondary_ip: IP address
820
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
821
                      if the cluster has been initialized in 'dual-network'
822
                      mode, otherwise it must not be given.
823
  @type readd: C{bool}
824
  @ivar readd: Whether to re-add an existing node to the cluster. If
825
               this is not passed, then the operation will abort if the node
826
               name is already in the cluster; use this parameter to 'repair'
827
               a node that had its configuration broken, or was reinstalled
828
               without removal from the cluster.
829
  @type group: C{str}
830
  @ivar group: The node group to which this node will belong.
831
  @type vm_capable: C{bool}
832
  @ivar vm_capable: The vm_capable node attribute
833
  @type master_capable: C{bool}
834
  @ivar master_capable: The master_capable node attribute
835

836
  """
837
  OP_DSC_FIELD = "node_name"
838
  OP_PARAMS = [
839
    _PNodeName,
840
    ("primary_ip", None, ht.NoType, "Primary IP address"),
841
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
842
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
843
    ("group", None, ht.TMaybeString, "Initial node group"),
844
    ("master_capable", None, ht.TMaybeBool,
845
     "Whether node can become master or master candidate"),
846
    ("vm_capable", None, ht.TMaybeBool,
847
     "Whether node can host instances"),
848
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
849
    ]
850

    
851

    
852
class OpNodeQuery(OpCode):
853
  """Compute the list of nodes."""
854
  OP_PARAMS = [
855
    _POutputFields,
856
    _PUseLocking,
857
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
858
     "Empty list to query all nodes, node names otherwise"),
859
    ]
860

    
861

    
862
class OpNodeQueryvols(OpCode):
863
  """Get list of volumes on node."""
864
  OP_PARAMS = [
865
    _POutputFields,
866
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
867
     "Empty list to query all nodes, node names otherwise"),
868
    ]
869

    
870

    
871
class OpNodeQueryStorage(OpCode):
872
  """Get information on storage for node(s)."""
873
  OP_PARAMS = [
874
    _POutputFields,
875
    _PStorageType,
876
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
877
    ("name", None, ht.TMaybeString, "Storage name"),
878
    ]
879

    
880

    
881
class OpNodeModifyStorage(OpCode):
882
  """Modifies the properies of a storage unit"""
883
  OP_PARAMS = [
884
    _PNodeName,
885
    _PStorageType,
886
    _PStorageName,
887
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
888
    ]
889

    
890

    
891
class OpRepairNodeStorage(OpCode):
892
  """Repairs the volume group on a node."""
893
  OP_DSC_FIELD = "node_name"
894
  OP_PARAMS = [
895
    _PNodeName,
896
    _PStorageType,
897
    _PStorageName,
898
    _PIgnoreConsistency,
899
    ]
900

    
901

    
902
class OpNodeSetParams(OpCode):
903
  """Change the parameters of a node."""
904
  OP_DSC_FIELD = "node_name"
905
  OP_PARAMS = [
906
    _PNodeName,
907
    _PForce,
908
    ("master_candidate", None, ht.TMaybeBool,
909
     "Whether the node should become a master candidate"),
910
    ("offline", None, ht.TMaybeBool,
911
     "Whether the node should be marked as offline"),
912
    ("drained", None, ht.TMaybeBool,
913
     "Whether the node should be marked as drained"),
914
    ("auto_promote", False, ht.TBool,
915
     "Whether node(s) should be promoted to master candidate if necessary"),
916
    ("master_capable", None, ht.TMaybeBool,
917
     "Denote whether node can become master or master candidate"),
918
    ("vm_capable", None, ht.TMaybeBool,
919
     "Denote whether node can host instances"),
920
    ("secondary_ip", None, ht.TMaybeString,
921
     "Change node's secondary IP address"),
922
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
923
    ("powered", None, ht.TMaybeBool,
924
     "Whether the node should be marked as powered"),
925
    ]
926

    
927

    
928
class OpNodePowercycle(OpCode):
929
  """Tries to powercycle a node."""
930
  OP_DSC_FIELD = "node_name"
931
  OP_PARAMS = [
932
    _PNodeName,
933
    _PForce,
934
    ]
935

    
936

    
937
class OpNodeMigrate(OpCode):
938
  """Migrate all instances from a node."""
939
  OP_DSC_FIELD = "node_name"
940
  OP_PARAMS = [
941
    _PNodeName,
942
    _PMigrationMode,
943
    _PMigrationLive,
944
    _PMigrationTargetNode,
945
    ("iallocator", None, ht.TMaybeString,
946
     "Iallocator for deciding the target node for shared-storage instances"),
947
    ]
948

    
949

    
950
class OpNodeEvacuate(OpCode):
951
  """Evacuate instances off a number of nodes."""
952
  OP_DSC_FIELD = "node_name"
953
  OP_PARAMS = [
954
    _PEarlyRelease,
955
    _PNodeName,
956
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
957
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
958
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
959
     "Node evacuation mode"),
960
    ]
961

    
962

    
963
# instance opcodes
964

    
965
class OpInstanceCreate(OpCode):
966
  """Create an instance.
967

968
  @ivar instance_name: Instance name
969
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
970
  @ivar source_handshake: Signed handshake from source (remote import only)
971
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
972
  @ivar source_instance_name: Previous name of instance (remote import only)
973
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
974
    (remote import only)
975

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

    
1037

    
1038
class OpInstanceReinstall(OpCode):
1039
  """Reinstall an instance's OS."""
1040
  OP_DSC_FIELD = "instance_name"
1041
  OP_PARAMS = [
1042
    _PInstanceName,
1043
    _PForceVariant,
1044
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1045
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1046
    ]
1047

    
1048

    
1049
class OpInstanceRemove(OpCode):
1050
  """Remove an instance."""
1051
  OP_DSC_FIELD = "instance_name"
1052
  OP_PARAMS = [
1053
    _PInstanceName,
1054
    _PShutdownTimeout,
1055
    ("ignore_failures", False, ht.TBool,
1056
     "Whether to ignore failures during removal"),
1057
    ]
1058

    
1059

    
1060
class OpInstanceRename(OpCode):
1061
  """Rename an instance."""
1062
  OP_PARAMS = [
1063
    _PInstanceName,
1064
    _PNameCheck,
1065
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1066
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1067
    ]
1068

    
1069

    
1070
class OpInstanceStartup(OpCode):
1071
  """Startup an instance."""
1072
  OP_DSC_FIELD = "instance_name"
1073
  OP_PARAMS = [
1074
    _PInstanceName,
1075
    _PForce,
1076
    _PIgnoreOfflineNodes,
1077
    ("hvparams", ht.EmptyDict, ht.TDict,
1078
     "Temporary hypervisor parameters, hypervisor-dependent"),
1079
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1080
    _PNoRemember,
1081
    _PStartupPaused,
1082
    ]
1083

    
1084

    
1085
class OpInstanceShutdown(OpCode):
1086
  """Shutdown an instance."""
1087
  OP_DSC_FIELD = "instance_name"
1088
  OP_PARAMS = [
1089
    _PInstanceName,
1090
    _PIgnoreOfflineNodes,
1091
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1092
     "How long to wait for instance to shut down"),
1093
    _PNoRemember,
1094
    ]
1095

    
1096

    
1097
class OpInstanceReboot(OpCode):
1098
  """Reboot an instance."""
1099
  OP_DSC_FIELD = "instance_name"
1100
  OP_PARAMS = [
1101
    _PInstanceName,
1102
    _PShutdownTimeout,
1103
    ("ignore_secondaries", False, ht.TBool,
1104
     "Whether to start the instance even if secondary disks are failing"),
1105
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1106
     "How to reboot instance"),
1107
    ]
1108

    
1109

    
1110
class OpInstanceReplaceDisks(OpCode):
1111
  """Replace the disks of an instance."""
1112
  OP_DSC_FIELD = "instance_name"
1113
  OP_PARAMS = [
1114
    _PInstanceName,
1115
    _PEarlyRelease,
1116
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1117
     "Replacement mode"),
1118
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1119
     "Disk indexes"),
1120
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1121
    ("iallocator", None, ht.TMaybeString,
1122
     "Iallocator for deciding new secondary node"),
1123
    ]
1124

    
1125

    
1126
class OpInstanceFailover(OpCode):
1127
  """Failover an instance."""
1128
  OP_DSC_FIELD = "instance_name"
1129
  OP_PARAMS = [
1130
    _PInstanceName,
1131
    _PShutdownTimeout,
1132
    _PIgnoreConsistency,
1133
    _PMigrationTargetNode,
1134
    ("iallocator", None, ht.TMaybeString,
1135
     "Iallocator for deciding the target node for shared-storage instances"),
1136
    ]
1137

    
1138

    
1139
class OpInstanceMigrate(OpCode):
1140
  """Migrate an instance.
1141

1142
  This migrates (without shutting down an instance) to its secondary
1143
  node.
1144

1145
  @ivar instance_name: the name of the instance
1146
  @ivar mode: the migration mode (live, non-live or None for auto)
1147

1148
  """
1149
  OP_DSC_FIELD = "instance_name"
1150
  OP_PARAMS = [
1151
    _PInstanceName,
1152
    _PMigrationMode,
1153
    _PMigrationLive,
1154
    _PMigrationTargetNode,
1155
    ("cleanup", False, ht.TBool,
1156
     "Whether a previously failed migration should be cleaned up"),
1157
    ("iallocator", None, ht.TMaybeString,
1158
     "Iallocator for deciding the target node for shared-storage instances"),
1159
    ("allow_failover", False, ht.TBool,
1160
     "Whether we can fallback to failover if migration is not possible"),
1161
    ]
1162

    
1163

    
1164
class OpInstanceMove(OpCode):
1165
  """Move an instance.
1166

1167
  This move (with shutting down an instance and data copying) to an
1168
  arbitrary node.
1169

1170
  @ivar instance_name: the name of the instance
1171
  @ivar target_node: the destination node
1172

1173
  """
1174
  OP_DSC_FIELD = "instance_name"
1175
  OP_PARAMS = [
1176
    _PInstanceName,
1177
    _PShutdownTimeout,
1178
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1179
    _PIgnoreConsistency,
1180
    ]
1181

    
1182

    
1183
class OpInstanceConsole(OpCode):
1184
  """Connect to an instance's console."""
1185
  OP_DSC_FIELD = "instance_name"
1186
  OP_PARAMS = [
1187
    _PInstanceName
1188
    ]
1189

    
1190

    
1191
class OpInstanceActivateDisks(OpCode):
1192
  """Activate an instance's disks."""
1193
  OP_DSC_FIELD = "instance_name"
1194
  OP_PARAMS = [
1195
    _PInstanceName,
1196
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1197
    ]
1198

    
1199

    
1200
class OpInstanceDeactivateDisks(OpCode):
1201
  """Deactivate an instance's disks."""
1202
  OP_DSC_FIELD = "instance_name"
1203
  OP_PARAMS = [
1204
    _PInstanceName,
1205
    _PForce,
1206
    ]
1207

    
1208

    
1209
class OpInstanceRecreateDisks(OpCode):
1210
  """Deactivate an instance's disks."""
1211
  OP_DSC_FIELD = "instance_name"
1212
  OP_PARAMS = [
1213
    _PInstanceName,
1214
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1215
     "List of disk indexes"),
1216
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1217
     "New instance nodes, if relocation is desired"),
1218
    ]
1219

    
1220

    
1221
class OpInstanceQuery(OpCode):
1222
  """Compute the list of instances."""
1223
  OP_PARAMS = [
1224
    _POutputFields,
1225
    _PUseLocking,
1226
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1227
     "Empty list to query all instances, instance names otherwise"),
1228
    ]
1229

    
1230

    
1231
class OpInstanceQueryData(OpCode):
1232
  """Compute the run-time status of instances."""
1233
  OP_PARAMS = [
1234
    _PUseLocking,
1235
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1236
     "Instance names"),
1237
    ("static", False, ht.TBool,
1238
     "Whether to only return configuration data without querying"
1239
     " nodes"),
1240
    ]
1241

    
1242

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

    
1272

    
1273
class OpInstanceGrowDisk(OpCode):
1274
  """Grow a disk of an instance."""
1275
  OP_DSC_FIELD = "instance_name"
1276
  OP_PARAMS = [
1277
    _PInstanceName,
1278
    _PWaitForSync,
1279
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1280
    ("amount", ht.NoDefault, ht.TInt,
1281
     "Amount of disk space to add (megabytes)"),
1282
    ]
1283

    
1284

    
1285
# Node group opcodes
1286

    
1287
class OpGroupAdd(OpCode):
1288
  """Add a node group to the cluster."""
1289
  OP_DSC_FIELD = "group_name"
1290
  OP_PARAMS = [
1291
    _PGroupName,
1292
    _PNodeGroupAllocPolicy,
1293
    _PGroupNodeParams,
1294
    ]
1295

    
1296

    
1297
class OpGroupAssignNodes(OpCode):
1298
  """Assign nodes to a node group."""
1299
  OP_DSC_FIELD = "group_name"
1300
  OP_PARAMS = [
1301
    _PGroupName,
1302
    _PForce,
1303
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1304
     "List of nodes to assign"),
1305
    ]
1306

    
1307

    
1308
class OpGroupQuery(OpCode):
1309
  """Compute the list of node groups."""
1310
  OP_PARAMS = [
1311
    _POutputFields,
1312
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1313
     "Empty list to query all groups, group names otherwise"),
1314
    ]
1315

    
1316

    
1317
class OpGroupSetParams(OpCode):
1318
  """Change the parameters of a node group."""
1319
  OP_DSC_FIELD = "group_name"
1320
  OP_PARAMS = [
1321
    _PGroupName,
1322
    _PNodeGroupAllocPolicy,
1323
    _PGroupNodeParams,
1324
    ]
1325

    
1326

    
1327
class OpGroupRemove(OpCode):
1328
  """Remove a node group from the cluster."""
1329
  OP_DSC_FIELD = "group_name"
1330
  OP_PARAMS = [
1331
    _PGroupName,
1332
    ]
1333

    
1334

    
1335
class OpGroupRename(OpCode):
1336
  """Rename a node group in the cluster."""
1337
  OP_PARAMS = [
1338
    _PGroupName,
1339
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1340
    ]
1341

    
1342

    
1343
class OpGroupEvacuate(OpCode):
1344
  """Evacuate a node group in the cluster."""
1345
  OP_DSC_FIELD = "group_name"
1346
  OP_PARAMS = [
1347
    _PGroupName,
1348
    _PEarlyRelease,
1349
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1350
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1351
     "Destination group names or UUIDs"),
1352
    ]
1353

    
1354

    
1355
# OS opcodes
1356
class OpOsDiagnose(OpCode):
1357
  """Compute the list of guest operating systems."""
1358
  OP_PARAMS = [
1359
    _POutputFields,
1360
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1361
     "Which operating systems to diagnose"),
1362
    ]
1363

    
1364

    
1365
# Exports opcodes
1366
class OpBackupQuery(OpCode):
1367
  """Compute the list of exported images."""
1368
  OP_PARAMS = [
1369
    _PUseLocking,
1370
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1371
     "Empty list to query all nodes, node names otherwise"),
1372
    ]
1373

    
1374

    
1375
class OpBackupPrepare(OpCode):
1376
  """Prepares an instance export.
1377

1378
  @ivar instance_name: Instance name
1379
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1380

1381
  """
1382
  OP_DSC_FIELD = "instance_name"
1383
  OP_PARAMS = [
1384
    _PInstanceName,
1385
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1386
     "Export mode"),
1387
    ]
1388

    
1389

    
1390
class OpBackupExport(OpCode):
1391
  """Export an instance.
1392

1393
  For local exports, the export destination is the node name. For remote
1394
  exports, the export destination is a list of tuples, each consisting of
1395
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1396
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1397
  destination X509 CA must be a signed certificate.
1398

1399
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1400
  @ivar target_node: Export destination
1401
  @ivar x509_key_name: X509 key to use (remote export only)
1402
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1403
                             only)
1404

1405
  """
1406
  OP_DSC_FIELD = "instance_name"
1407
  OP_PARAMS = [
1408
    _PInstanceName,
1409
    _PShutdownTimeout,
1410
    # TODO: Rename target_node as it changes meaning for different export modes
1411
    # (e.g. "destination")
1412
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1413
     "Destination information, depends on export mode"),
1414
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1415
    ("remove_instance", False, ht.TBool,
1416
     "Whether to remove instance after export"),
1417
    ("ignore_remove_failures", False, ht.TBool,
1418
     "Whether to ignore failures while removing instances"),
1419
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1420
     "Export mode"),
1421
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1422
     "Name of X509 key (remote export only)"),
1423
    ("destination_x509_ca", None, ht.TMaybeString,
1424
     "Destination X509 CA (remote export only)"),
1425
    ]
1426

    
1427

    
1428
class OpBackupRemove(OpCode):
1429
  """Remove an instance's export."""
1430
  OP_DSC_FIELD = "instance_name"
1431
  OP_PARAMS = [
1432
    _PInstanceName,
1433
    ]
1434

    
1435

    
1436
# Tags opcodes
1437
class OpTagsGet(OpCode):
1438
  """Returns the tags of the given object."""
1439
  OP_DSC_FIELD = "name"
1440
  OP_PARAMS = [
1441
    _PTagKind,
1442
    # Name is only meaningful for nodes and instances
1443
    ("name", ht.NoDefault, ht.TMaybeString, None),
1444
    ]
1445

    
1446

    
1447
class OpTagsSearch(OpCode):
1448
  """Searches the tags in the cluster for a given pattern."""
1449
  OP_DSC_FIELD = "pattern"
1450
  OP_PARAMS = [
1451
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1452
    ]
1453

    
1454

    
1455
class OpTagsSet(OpCode):
1456
  """Add a list of tags on a given object."""
1457
  OP_PARAMS = [
1458
    _PTagKind,
1459
    _PTags,
1460
    # Name is only meaningful for nodes and instances
1461
    ("name", ht.NoDefault, ht.TMaybeString, None),
1462
    ]
1463

    
1464

    
1465
class OpTagsDel(OpCode):
1466
  """Remove a list of tags from a given object."""
1467
  OP_PARAMS = [
1468
    _PTagKind,
1469
    _PTags,
1470
    # Name is only meaningful for nodes and instances
1471
    ("name", ht.NoDefault, ht.TMaybeString, None),
1472
    ]
1473

    
1474
# Test opcodes
1475
class OpTestDelay(OpCode):
1476
  """Sleeps for a configured amount of time.
1477

1478
  This is used just for debugging and testing.
1479

1480
  Parameters:
1481
    - duration: the time to sleep
1482
    - on_master: if true, sleep on the master
1483
    - on_nodes: list of nodes in which to sleep
1484

1485
  If the on_master parameter is true, it will execute a sleep on the
1486
  master (before any node sleep).
1487

1488
  If the on_nodes list is not empty, it will sleep on those nodes
1489
  (after the sleep on the master, if that is enabled).
1490

1491
  As an additional feature, the case of duration < 0 will be reported
1492
  as an execution error, so this opcode can be used as a failure
1493
  generator. The case of duration == 0 will not be treated specially.
1494

1495
  """
1496
  OP_DSC_FIELD = "duration"
1497
  OP_PARAMS = [
1498
    ("duration", ht.NoDefault, ht.TNumber, None),
1499
    ("on_master", True, ht.TBool, None),
1500
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1501
    ("repeat", 0, ht.TPositiveInt, None),
1502
    ]
1503

    
1504

    
1505
class OpTestAllocator(OpCode):
1506
  """Allocator framework testing.
1507

1508
  This opcode has two modes:
1509
    - gather and return allocator input for a given mode (allocate new
1510
      or replace secondary) and a given instance definition (direction
1511
      'in')
1512
    - run a selected allocator for a given operation (as above) and
1513
      return the allocator output (direction 'out')
1514

1515
  """
1516
  OP_DSC_FIELD = "allocator"
1517
  OP_PARAMS = [
1518
    ("direction", ht.NoDefault,
1519
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1520
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1521
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1522
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1523
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1524
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1525
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1526
    ("hypervisor", None, ht.TMaybeString, None),
1527
    ("allocator", None, ht.TMaybeString, None),
1528
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1529
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1530
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1531
    ("os", None, ht.TMaybeString, None),
1532
    ("disk_template", None, ht.TMaybeString, None),
1533
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1534
     None),
1535
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1536
     None),
1537
    ("evac_mode", None,
1538
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1539
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1540
     None),
1541
    ]
1542

    
1543

    
1544
class OpTestJqueue(OpCode):
1545
  """Utility opcode to test some aspects of the job queue.
1546

1547
  """
1548
  OP_PARAMS = [
1549
    ("notify_waitlock", False, ht.TBool, None),
1550
    ("notify_exec", False, ht.TBool, None),
1551
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1552
    ("fail", False, ht.TBool, None),
1553
    ]
1554

    
1555

    
1556
class OpTestDummy(OpCode):
1557
  """Utility opcode used by unittests.
1558

1559
  """
1560
  OP_PARAMS = [
1561
    ("result", ht.NoDefault, ht.NoType, None),
1562
    ("messages", ht.NoDefault, ht.NoType, None),
1563
    ("fail", ht.NoDefault, ht.NoType, None),
1564
    ("submit_jobs", None, ht.NoType, None),
1565
    ]
1566
  WITH_LU = False
1567

    
1568

    
1569
def _GetOpList():
1570
  """Returns list of all defined opcodes.
1571

1572
  Does not eliminate duplicates by C{OP_ID}.
1573

1574
  """
1575
  return [v for v in globals().values()
1576
          if (isinstance(v, type) and issubclass(v, OpCode) and
1577
              hasattr(v, "OP_ID") and v is not OpCode)]
1578

    
1579

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