Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 8c0b16f6

History | View | Annotate | Download (53.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=R0903
35

    
36
import logging
37
import re
38

    
39
from ganeti import compat
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
_PVerbose = ("verbose", False, ht.TBool, "Verbose mode")
132

    
133
# Parameters for cluster verification
134
_PDebugSimulateErrors = ("debug_simulate_errors", False, ht.TBool,
135
                         "Whether to simulate errors (useful for debugging)")
136
_PErrorCodes = ("error_codes", False, ht.TBool, "Error codes")
137
_PSkipChecks = ("skip_checks", ht.EmptyList,
138
                ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)),
139
                "Which checks to skip")
140
_PIgnoreErrors = ("ignore_errors", ht.EmptyList,
141
                  ht.TListOf(ht.TElemOf(constants.CV_ALL_ECODES_STRINGS)),
142
                  "List of error codes that should be treated as warnings")
143

    
144
# Disk parameters
145
_PDiskParams = ("diskparams", None,
146
                ht.TOr(
147
                  ht.TDictOf(ht.TElemOf(constants.DISK_TEMPLATES), ht.TDict),
148
                  ht.TNone),
149
                "Disk templates' parameter defaults")
150

    
151
# Parameters for node resource model
152
_PHvState = ("hv_state", None, ht.TMaybeDict, "Set hypervisor states")
153
_PDiskState = ("disk_state", None, ht.TMaybeDict, "Set disk states")
154

    
155

    
156
_PIgnoreIpolicy = ("ignore_ipolicy", False, ht.TBool,
157
                   "Whether to ignore ipolicy violations")
158

    
159
# Allow runtime changes while migrating
160
_PAllowRuntimeChgs = ("allow_runtime_changes", True, ht.TBool,
161
                      "Allow runtime changes (eg. memory ballooning)")
162

    
163

    
164
#: OP_ID conversion regular expression
165
_OPID_RE = re.compile("([a-z])([A-Z])")
166

    
167
#: Utility function for L{OpClusterSetParams}
168
_TestClusterOsList = ht.TOr(ht.TNone,
169
  ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
170
    ht.TMap(ht.WithDesc("GetFirstItem")(compat.fst),
171
            ht.TElemOf(constants.DDMS_VALUES)))))
172

    
173

    
174
# TODO: Generate check from constants.INIC_PARAMS_TYPES
175
#: Utility function for testing NIC definitions
176
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
177
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
178

    
179
_TSetParamsResultItemItems = [
180
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
181
  ht.Comment("new value")(ht.TAny),
182
  ]
183

    
184
_TSetParamsResult = \
185
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
186
                     ht.TItems(_TSetParamsResultItemItems)))
187

    
188
# TODO: Generate check from constants.IDISK_PARAMS_TYPES (however, not all users
189
# of this check support all parameters)
190
_TDiskParams = ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
191
                          ht.TOr(ht.TNonEmptyString, ht.TInt))
192

    
193
_SUMMARY_PREFIX = {
194
  "CLUSTER_": "C_",
195
  "GROUP_": "G_",
196
  "NODE_": "N_",
197
  "INSTANCE_": "I_",
198
  }
199

    
200
#: Attribute name for dependencies
201
DEPEND_ATTR = "depends"
202

    
203
#: Attribute name for comment
204
COMMENT_ATTR = "comment"
205

    
206

    
207
def _NameToId(name):
208
  """Convert an opcode class name to an OP_ID.
209

210
  @type name: string
211
  @param name: the class name, as OpXxxYyy
212
  @rtype: string
213
  @return: the name in the OP_XXXX_YYYY format
214

215
  """
216
  if not name.startswith("Op"):
217
    return None
218
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
219
  # consume any input, and hence we would just have all the elements
220
  # in the list, one by one; but it seems that split doesn't work on
221
  # non-consuming input, hence we have to process the input string a
222
  # bit
223
  name = _OPID_RE.sub(r"\1,\2", name)
224
  elems = name.split(",")
225
  return "_".join(n.upper() for n in elems)
226

    
227

    
228
def RequireFileStorage():
229
  """Checks that file storage is enabled.
230

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

234
  @raise errors.OpPrereqError: when file storage is disabled
235

236
  """
237
  if not constants.ENABLE_FILE_STORAGE:
238
    raise errors.OpPrereqError("File storage disabled at configure time",
239
                               errors.ECODE_INVAL)
240

    
241

    
242
def RequireSharedFileStorage():
243
  """Checks that shared file storage is enabled.
244

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

248
  @raise errors.OpPrereqError: when shared file storage is disabled
249

250
  """
251
  if not constants.ENABLE_SHARED_FILE_STORAGE:
252
    raise errors.OpPrereqError("Shared file storage disabled at"
253
                               " configure time", errors.ECODE_INVAL)
254

    
255

    
256
@ht.WithDesc("CheckFileStorage")
257
def _CheckFileStorage(value):
258
  """Ensures file storage is enabled if used.
259

260
  """
261
  if value == constants.DT_FILE:
262
    RequireFileStorage()
263
  elif value == constants.DT_SHARED_FILE:
264
    RequireSharedFileStorage()
265
  return True
266

    
267

    
268
def _BuildDiskTemplateCheck(accept_none):
269
  """Builds check for disk template.
270

271
  @type accept_none: bool
272
  @param accept_none: whether to accept None as a correct value
273
  @rtype: callable
274

275
  """
276
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
277

    
278
  if accept_none:
279
    template_check = ht.TOr(template_check, ht.TNone)
280

    
281
  return ht.TAnd(template_check, _CheckFileStorage)
282

    
283

    
284
def _CheckStorageType(storage_type):
285
  """Ensure a given storage type is valid.
286

287
  """
288
  if storage_type not in constants.VALID_STORAGE_TYPES:
289
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
290
                               errors.ECODE_INVAL)
291
  if storage_type == constants.ST_FILE:
292
    RequireFileStorage()
293
  return True
294

    
295

    
296
#: Storage type parameter
297
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
298
                 "Storage type")
299

    
300

    
301
class _AutoOpParamSlots(type):
302
  """Meta class for opcode definitions.
303

304
  """
305
  def __new__(mcs, name, bases, attrs):
306
    """Called when a class should be created.
307

308
    @param mcs: The meta class
309
    @param name: Name of created class
310
    @param bases: Base classes
311
    @type attrs: dict
312
    @param attrs: Class attributes
313

314
    """
315
    assert "__slots__" not in attrs, \
316
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
317
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
318

    
319
    attrs["OP_ID"] = _NameToId(name)
320

    
321
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
322
    params = attrs.setdefault("OP_PARAMS", [])
323

    
324
    # Use parameter names as slots
325
    slots = [pname for (pname, _, _, _) in params]
326

    
327
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
328
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
329

    
330
    attrs["__slots__"] = slots
331

    
332
    return type.__new__(mcs, name, bases, attrs)
333

    
334

    
335
class BaseOpCode(object):
336
  """A simple serializable object.
337

338
  This object serves as a parent class for OpCode without any custom
339
  field handling.
340

341
  """
342
  # pylint: disable=E1101
343
  # as OP_ID is dynamically defined
344
  __metaclass__ = _AutoOpParamSlots
345

    
346
  def __init__(self, **kwargs):
347
    """Constructor for BaseOpCode.
348

349
    The constructor takes only keyword arguments and will set
350
    attributes on this object based on the passed arguments. As such,
351
    it means that you should not pass arguments which are not in the
352
    __slots__ attribute for this class.
353

354
    """
355
    slots = self._all_slots()
356
    for key in kwargs:
357
      if key not in slots:
358
        raise TypeError("Object %s doesn't support the parameter '%s'" %
359
                        (self.__class__.__name__, key))
360
      setattr(self, key, kwargs[key])
361

    
362
  def __getstate__(self):
363
    """Generic serializer.
364

365
    This method just returns the contents of the instance as a
366
    dictionary.
367

368
    @rtype:  C{dict}
369
    @return: the instance attributes and their values
370

371
    """
372
    state = {}
373
    for name in self._all_slots():
374
      if hasattr(self, name):
375
        state[name] = getattr(self, name)
376
    return state
377

    
378
  def __setstate__(self, state):
379
    """Generic unserializer.
380

381
    This method just restores from the serialized state the attributes
382
    of the current instance.
383

384
    @param state: the serialized opcode data
385
    @type state:  C{dict}
386

387
    """
388
    if not isinstance(state, dict):
389
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
390
                       type(state))
391

    
392
    for name in self._all_slots():
393
      if name not in state and hasattr(self, name):
394
        delattr(self, name)
395

    
396
    for name in state:
397
      setattr(self, name, state[name])
398

    
399
  @classmethod
400
  def _all_slots(cls):
401
    """Compute the list of all declared slots for a class.
402

403
    """
404
    slots = []
405
    for parent in cls.__mro__:
406
      slots.extend(getattr(parent, "__slots__", []))
407
    return slots
408

    
409
  @classmethod
410
  def GetAllParams(cls):
411
    """Compute list of all parameters for an opcode.
412

413
    """
414
    slots = []
415
    for parent in cls.__mro__:
416
      slots.extend(getattr(parent, "OP_PARAMS", []))
417
    return slots
418

    
419
  def Validate(self, set_defaults):
420
    """Validate opcode parameters, optionally setting default values.
421

422
    @type set_defaults: bool
423
    @param set_defaults: Whether to set default values
424
    @raise errors.OpPrereqError: When a parameter value doesn't match
425
                                 requirements
426

427
    """
428
    for (attr_name, default, test, _) in self.GetAllParams():
429
      assert test == ht.NoType or callable(test)
430

    
431
      if not hasattr(self, attr_name):
432
        if default == ht.NoDefault:
433
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
434
                                     (self.OP_ID, attr_name),
435
                                     errors.ECODE_INVAL)
436
        elif set_defaults:
437
          if callable(default):
438
            dval = default()
439
          else:
440
            dval = default
441
          setattr(self, attr_name, dval)
442

    
443
      if test == ht.NoType:
444
        # no tests here
445
        continue
446

    
447
      if set_defaults or hasattr(self, attr_name):
448
        attr_val = getattr(self, attr_name)
449
        if not test(attr_val):
450
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
451
                        self.OP_ID, attr_name, type(attr_val), attr_val)
452
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
453
                                     (self.OP_ID, attr_name),
454
                                     errors.ECODE_INVAL)
455

    
456

    
457
def _BuildJobDepCheck(relative):
458
  """Builds check for job dependencies (L{DEPEND_ATTR}).
459

460
  @type relative: bool
461
  @param relative: Whether to accept relative job IDs (negative)
462
  @rtype: callable
463

464
  """
465
  if relative:
466
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
467
  else:
468
    job_id = ht.TJobId
469

    
470
  job_dep = \
471
    ht.TAnd(ht.TIsLength(2),
472
            ht.TItems([job_id,
473
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
474

    
475
  return ht.TOr(ht.TNone, ht.TListOf(job_dep))
476

    
477

    
478
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
479

    
480
#: List of submission status and job ID as returned by C{SubmitManyJobs}
481
_TJobIdListItem = \
482
  ht.TAnd(ht.TIsLength(2),
483
          ht.TItems([ht.Comment("success")(ht.TBool),
484
                     ht.Comment("Job ID if successful, error message"
485
                                " otherwise")(ht.TOr(ht.TString,
486
                                                     ht.TJobId))]))
487
TJobIdList = ht.TListOf(_TJobIdListItem)
488

    
489
#: Result containing only list of submitted jobs
490
TJobIdListOnly = ht.TStrictDict(True, True, {
491
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
492
  })
493

    
494

    
495
class OpCode(BaseOpCode):
496
  """Abstract OpCode.
497

498
  This is the root of the actual OpCode hierarchy. All clases derived
499
  from this class should override OP_ID.
500

501
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
502
               children of this class.
503
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
504
                      string returned by Summary(); see the docstring of that
505
                      method for details).
506
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
507
                   get if not already defined, and types they must match.
508
  @cvar OP_RESULT: Callable to verify opcode result
509
  @cvar WITH_LU: Boolean that specifies whether this should be included in
510
      mcpu's dispatch table
511
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
512
                 the check steps
513
  @ivar priority: Opcode priority for queue
514

515
  """
516
  # pylint: disable=E1101
517
  # as OP_ID is dynamically defined
518
  WITH_LU = True
519
  OP_PARAMS = [
520
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
521
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
522
    ("priority", constants.OP_PRIO_DEFAULT,
523
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
524
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
525
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
526
     " job IDs can be used; see :doc:`design document <design-chained-jobs>`"
527
     " for details"),
528
    (COMMENT_ATTR, None, ht.TMaybeString,
529
     "Comment describing the purpose of the opcode"),
530
    ]
531
  OP_RESULT = None
532

    
533
  def __getstate__(self):
534
    """Specialized getstate for opcodes.
535

536
    This method adds to the state dictionary the OP_ID of the class,
537
    so that on unload we can identify the correct class for
538
    instantiating the opcode.
539

540
    @rtype:   C{dict}
541
    @return:  the state as a dictionary
542

543
    """
544
    data = BaseOpCode.__getstate__(self)
545
    data["OP_ID"] = self.OP_ID
546
    return data
547

    
548
  @classmethod
549
  def LoadOpCode(cls, data):
550
    """Generic load opcode method.
551

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

556
    @type data:  C{dict}
557
    @param data: the serialized opcode
558

559
    """
560
    if not isinstance(data, dict):
561
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
562
    if "OP_ID" not in data:
563
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
564
    op_id = data["OP_ID"]
565
    op_class = None
566
    if op_id in OP_MAPPING:
567
      op_class = OP_MAPPING[op_id]
568
    else:
569
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
570
                       op_id)
571
    op = op_class()
572
    new_data = data.copy()
573
    del new_data["OP_ID"]
574
    op.__setstate__(new_data)
575
    return op
576

    
577
  def Summary(self):
578
    """Generates a summary description of this opcode.
579

580
    The summary is the value of the OP_ID attribute (without the "OP_"
581
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
582
    defined; this field should allow to easily identify the operation
583
    (for an instance creation job, e.g., it would be the instance
584
    name).
585

586
    """
587
    assert self.OP_ID is not None and len(self.OP_ID) > 3
588
    # all OP_ID start with OP_, we remove that
589
    txt = self.OP_ID[3:]
590
    field_name = getattr(self, "OP_DSC_FIELD", None)
591
    if field_name:
592
      field_value = getattr(self, field_name, None)
593
      if isinstance(field_value, (list, tuple)):
594
        field_value = ",".join(str(i) for i in field_value)
595
      txt = "%s(%s)" % (txt, field_value)
596
    return txt
597

    
598
  def TinySummary(self):
599
    """Generates a compact summary description of the opcode.
600

601
    """
602
    assert self.OP_ID.startswith("OP_")
603

    
604
    text = self.OP_ID[3:]
605

    
606
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
607
      if text.startswith(prefix):
608
        return supplement + text[len(prefix):]
609

    
610
    return text
611

    
612

    
613
# cluster opcodes
614

    
615
class OpClusterPostInit(OpCode):
616
  """Post cluster initialization.
617

618
  This opcode does not touch the cluster at all. Its purpose is to run hooks
619
  after the cluster has been initialized.
620

621
  """
622

    
623

    
624
class OpClusterDestroy(OpCode):
625
  """Destroy the cluster.
626

627
  This opcode has no other parameters. All the state is irreversibly
628
  lost after the execution of this opcode.
629

630
  """
631

    
632

    
633
class OpClusterQuery(OpCode):
634
  """Query cluster information."""
635

    
636

    
637
class OpClusterVerify(OpCode):
638
  """Submits all jobs necessary to verify the cluster.
639

640
  """
641
  OP_PARAMS = [
642
    _PDebugSimulateErrors,
643
    _PErrorCodes,
644
    _PSkipChecks,
645
    _PIgnoreErrors,
646
    _PVerbose,
647
    ("group_name", None, ht.TMaybeString, "Group to verify")
648
    ]
649
  OP_RESULT = TJobIdListOnly
650

    
651

    
652
class OpClusterVerifyConfig(OpCode):
653
  """Verify the cluster config.
654

655
  """
656
  OP_PARAMS = [
657
    _PDebugSimulateErrors,
658
    _PErrorCodes,
659
    _PIgnoreErrors,
660
    _PVerbose,
661
    ]
662
  OP_RESULT = ht.TBool
663

    
664

    
665
class OpClusterVerifyGroup(OpCode):
666
  """Run verify on a node group from the cluster.
667

668
  @type skip_checks: C{list}
669
  @ivar skip_checks: steps to be skipped from the verify process; this
670
                     needs to be a subset of
671
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
672
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
673

674
  """
675
  OP_DSC_FIELD = "group_name"
676
  OP_PARAMS = [
677
    _PGroupName,
678
    _PDebugSimulateErrors,
679
    _PErrorCodes,
680
    _PSkipChecks,
681
    _PIgnoreErrors,
682
    _PVerbose,
683
    ]
684
  OP_RESULT = ht.TBool
685

    
686

    
687
class OpClusterVerifyDisks(OpCode):
688
  """Verify the cluster disks.
689

690
  """
691
  OP_RESULT = TJobIdListOnly
692

    
693

    
694
class OpGroupVerifyDisks(OpCode):
695
  """Verifies the status of all disks in a node group.
696

697
  Result: a tuple of three elements:
698
    - dict of node names with issues (values: error msg)
699
    - list of instances with degraded disks (that should be activated)
700
    - dict of instances with missing logical volumes (values: (node, vol)
701
      pairs with details about the missing volumes)
702

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

708
  Note that only instances that are drbd-based are taken into
709
  consideration. This might need to be revisited in the future.
710

711
  """
712
  OP_DSC_FIELD = "group_name"
713
  OP_PARAMS = [
714
    _PGroupName,
715
    ]
716
  OP_RESULT = \
717
    ht.TAnd(ht.TIsLength(3),
718
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
719
                       ht.TListOf(ht.TString),
720
                       ht.TDictOf(ht.TString,
721
                                  ht.TListOf(ht.TListOf(ht.TString)))]))
722

    
723

    
724
class OpClusterRepairDiskSizes(OpCode):
725
  """Verify the disk sizes of the instances and fixes configuration
726
  mimatches.
727

728
  Parameters: optional instances list, in case we want to restrict the
729
  checks to only a subset of the instances.
730

731
  Result: a list of tuples, (instance, disk, new-size) for changed
732
  configurations.
733

734
  In normal operation, the list should be empty.
735

736
  @type instances: list
737
  @ivar instances: the list of instances to check, or empty for all instances
738

739
  """
740
  OP_PARAMS = [
741
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
742
    ]
743

    
744

    
745
class OpClusterConfigQuery(OpCode):
746
  """Query cluster configuration values."""
747
  OP_PARAMS = [
748
    _POutputFields
749
    ]
750

    
751

    
752
class OpClusterRename(OpCode):
753
  """Rename the cluster.
754

755
  @type name: C{str}
756
  @ivar name: The new name of the cluster. The name and/or the master IP
757
              address will be changed to match the new name and its IP
758
              address.
759

760
  """
761
  OP_DSC_FIELD = "name"
762
  OP_PARAMS = [
763
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
764
    ]
765

    
766

    
767
class OpClusterSetParams(OpCode):
768
  """Change the parameters of the cluster.
769

770
  @type vg_name: C{str} or C{None}
771
  @ivar vg_name: The new volume group name or None to disable LVM usage.
772

773
  """
774
  OP_PARAMS = [
775
    _PHvState,
776
    _PDiskState,
777
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
778
    ("enabled_hypervisors", None,
779
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
780
            ht.TNone),
781
     "List of enabled hypervisors"),
782
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
783
                              ht.TNone),
784
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
785
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
786
     "Cluster-wide backend parameter defaults"),
787
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
788
                            ht.TNone),
789
     "Cluster-wide per-OS hypervisor parameter defaults"),
790
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
791
                              ht.TNone),
792
     "Cluster-wide OS parameter defaults"),
793
    _PDiskParams,
794
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
795
     "Master candidate pool size"),
796
    ("uid_pool", None, ht.NoType,
797
     "Set UID pool, must be list of lists describing UID ranges (two items,"
798
     " start and end inclusive)"),
799
    ("add_uids", None, ht.NoType,
800
     "Extend UID pool, must be list of lists describing UID ranges (two"
801
     " items, start and end inclusive) to be added"),
802
    ("remove_uids", None, ht.NoType,
803
     "Shrink UID pool, must be list of lists describing UID ranges (two"
804
     " items, start and end inclusive) to be removed"),
805
    ("maintain_node_health", None, ht.TMaybeBool,
806
     "Whether to automatically maintain node health"),
807
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
808
     "Whether to wipe disks before allocating them to instances"),
809
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
810
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
811
    ("ipolicy", None, ht.TMaybeDict,
812
     "Cluster-wide :ref:`instance policy <rapi-ipolicy>` specs"),
813
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
814
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
815
     "Default iallocator for cluster"),
816
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
817
     "Master network device"),
818
    ("master_netmask", None, ht.TOr(ht.TInt, ht.TNone),
819
     "Netmask of the master IP"),
820
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
821
     "List of reserved LVs"),
822
    ("hidden_os", None, _TestClusterOsList,
823
     "Modify list of hidden operating systems. Each modification must have"
824
     " two items, the operation and the OS name. The operation can be"
825
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
826
    ("blacklisted_os", None, _TestClusterOsList,
827
     "Modify list of blacklisted operating systems. Each modification must have"
828
     " two items, the operation and the OS name. The operation can be"
829
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
830
    ("use_external_mip_script", None, ht.TMaybeBool,
831
     "Whether to use an external master IP address setup script"),
832
    ]
833

    
834

    
835
class OpClusterRedistConf(OpCode):
836
  """Force a full push of the cluster configuration.
837

838
  """
839

    
840

    
841
class OpClusterActivateMasterIp(OpCode):
842
  """Activate the master IP on the master node.
843

844
  """
845

    
846

    
847
class OpClusterDeactivateMasterIp(OpCode):
848
  """Deactivate the master IP on the master node.
849

850
  """
851

    
852

    
853
class OpQuery(OpCode):
854
  """Query for resources/items.
855

856
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
857
  @ivar fields: List of fields to retrieve
858
  @ivar qfilter: Query filter
859

860
  """
861
  OP_DSC_FIELD = "what"
862
  OP_PARAMS = [
863
    _PQueryWhat,
864
    _PUseLocking,
865
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
866
     "Requested fields"),
867
    ("qfilter", None, ht.TOr(ht.TNone, ht.TListOf),
868
     "Query filter"),
869
    ]
870

    
871

    
872
class OpQueryFields(OpCode):
873
  """Query for available resource/item fields.
874

875
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
876
  @ivar fields: List of fields to retrieve
877

878
  """
879
  OP_DSC_FIELD = "what"
880
  OP_PARAMS = [
881
    _PQueryWhat,
882
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
883
     "Requested fields; if not given, all are returned"),
884
    ]
885

    
886

    
887
class OpOobCommand(OpCode):
888
  """Interact with OOB."""
889
  OP_PARAMS = [
890
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
891
     "List of nodes to run the OOB command against"),
892
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
893
     "OOB command to be run"),
894
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
895
     "Timeout before the OOB helper will be terminated"),
896
    ("ignore_status", False, ht.TBool,
897
     "Ignores the node offline status for power off"),
898
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
899
     "Time in seconds to wait between powering on nodes"),
900
    ]
901

    
902

    
903
# node opcodes
904

    
905
class OpNodeRemove(OpCode):
906
  """Remove a node.
907

908
  @type node_name: C{str}
909
  @ivar node_name: The name of the node to remove. If the node still has
910
                   instances on it, the operation will fail.
911

912
  """
913
  OP_DSC_FIELD = "node_name"
914
  OP_PARAMS = [
915
    _PNodeName,
916
    ]
917

    
918

    
919
class OpNodeAdd(OpCode):
920
  """Add a node to the cluster.
921

922
  @type node_name: C{str}
923
  @ivar node_name: The name of the node to add. This can be a short name,
924
                   but it will be expanded to the FQDN.
925
  @type primary_ip: IP address
926
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
927
                    opcode is submitted, but will be filled during the node
928
                    add (so it will be visible in the job query).
929
  @type secondary_ip: IP address
930
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
931
                      if the cluster has been initialized in 'dual-network'
932
                      mode, otherwise it must not be given.
933
  @type readd: C{bool}
934
  @ivar readd: Whether to re-add an existing node to the cluster. If
935
               this is not passed, then the operation will abort if the node
936
               name is already in the cluster; use this parameter to 'repair'
937
               a node that had its configuration broken, or was reinstalled
938
               without removal from the cluster.
939
  @type group: C{str}
940
  @ivar group: The node group to which this node will belong.
941
  @type vm_capable: C{bool}
942
  @ivar vm_capable: The vm_capable node attribute
943
  @type master_capable: C{bool}
944
  @ivar master_capable: The master_capable node attribute
945

946
  """
947
  OP_DSC_FIELD = "node_name"
948
  OP_PARAMS = [
949
    _PNodeName,
950
    _PHvState,
951
    _PDiskState,
952
    ("primary_ip", None, ht.NoType, "Primary IP address"),
953
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
954
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
955
    ("group", None, ht.TMaybeString, "Initial node group"),
956
    ("master_capable", None, ht.TMaybeBool,
957
     "Whether node can become master or master candidate"),
958
    ("vm_capable", None, ht.TMaybeBool,
959
     "Whether node can host instances"),
960
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
961
    ]
962

    
963

    
964
class OpNodeQuery(OpCode):
965
  """Compute the list of nodes."""
966
  OP_PARAMS = [
967
    _POutputFields,
968
    _PUseLocking,
969
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
970
     "Empty list to query all nodes, node names otherwise"),
971
    ]
972

    
973

    
974
class OpNodeQueryvols(OpCode):
975
  """Get list of volumes on node."""
976
  OP_PARAMS = [
977
    _POutputFields,
978
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
979
     "Empty list to query all nodes, node names otherwise"),
980
    ]
981

    
982

    
983
class OpNodeQueryStorage(OpCode):
984
  """Get information on storage for node(s)."""
985
  OP_PARAMS = [
986
    _POutputFields,
987
    _PStorageType,
988
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
989
    ("name", None, ht.TMaybeString, "Storage name"),
990
    ]
991

    
992

    
993
class OpNodeModifyStorage(OpCode):
994
  """Modifies the properies of a storage unit"""
995
  OP_PARAMS = [
996
    _PNodeName,
997
    _PStorageType,
998
    _PStorageName,
999
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1000
    ]
1001

    
1002

    
1003
class OpRepairNodeStorage(OpCode):
1004
  """Repairs the volume group on a node."""
1005
  OP_DSC_FIELD = "node_name"
1006
  OP_PARAMS = [
1007
    _PNodeName,
1008
    _PStorageType,
1009
    _PStorageName,
1010
    _PIgnoreConsistency,
1011
    ]
1012

    
1013

    
1014
class OpNodeSetParams(OpCode):
1015
  """Change the parameters of a node."""
1016
  OP_DSC_FIELD = "node_name"
1017
  OP_PARAMS = [
1018
    _PNodeName,
1019
    _PForce,
1020
    _PHvState,
1021
    _PDiskState,
1022
    ("master_candidate", None, ht.TMaybeBool,
1023
     "Whether the node should become a master candidate"),
1024
    ("offline", None, ht.TMaybeBool,
1025
     "Whether the node should be marked as offline"),
1026
    ("drained", None, ht.TMaybeBool,
1027
     "Whether the node should be marked as drained"),
1028
    ("auto_promote", False, ht.TBool,
1029
     "Whether node(s) should be promoted to master candidate if necessary"),
1030
    ("master_capable", None, ht.TMaybeBool,
1031
     "Denote whether node can become master or master candidate"),
1032
    ("vm_capable", None, ht.TMaybeBool,
1033
     "Denote whether node can host instances"),
1034
    ("secondary_ip", None, ht.TMaybeString,
1035
     "Change node's secondary IP address"),
1036
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1037
    ("powered", None, ht.TMaybeBool,
1038
     "Whether the node should be marked as powered"),
1039
    ]
1040
  OP_RESULT = _TSetParamsResult
1041

    
1042

    
1043
class OpNodePowercycle(OpCode):
1044
  """Tries to powercycle a node."""
1045
  OP_DSC_FIELD = "node_name"
1046
  OP_PARAMS = [
1047
    _PNodeName,
1048
    _PForce,
1049
    ]
1050

    
1051

    
1052
class OpNodeMigrate(OpCode):
1053
  """Migrate all instances from a node."""
1054
  OP_DSC_FIELD = "node_name"
1055
  OP_PARAMS = [
1056
    _PNodeName,
1057
    _PMigrationMode,
1058
    _PMigrationLive,
1059
    _PMigrationTargetNode,
1060
    _PAllowRuntimeChgs,
1061
    _PIgnoreIpolicy,
1062
    ("iallocator", None, ht.TMaybeString,
1063
     "Iallocator for deciding the target node for shared-storage instances"),
1064
    ]
1065
  OP_RESULT = TJobIdListOnly
1066

    
1067

    
1068
class OpNodeEvacuate(OpCode):
1069
  """Evacuate instances off a number of nodes."""
1070
  OP_DSC_FIELD = "node_name"
1071
  OP_PARAMS = [
1072
    _PEarlyRelease,
1073
    _PNodeName,
1074
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1075
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1076
    ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1077
     "Node evacuation mode"),
1078
    ]
1079
  OP_RESULT = TJobIdListOnly
1080

    
1081

    
1082
# instance opcodes
1083

    
1084
class OpInstanceCreate(OpCode):
1085
  """Create an instance.
1086

1087
  @ivar instance_name: Instance name
1088
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1089
  @ivar source_handshake: Signed handshake from source (remote import only)
1090
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1091
  @ivar source_instance_name: Previous name of instance (remote import only)
1092
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1093
    (remote import only)
1094

1095
  """
1096
  OP_DSC_FIELD = "instance_name"
1097
  OP_PARAMS = [
1098
    _PInstanceName,
1099
    _PForceVariant,
1100
    _PWaitForSync,
1101
    _PNameCheck,
1102
    _PIgnoreIpolicy,
1103
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1104
    ("disks", ht.NoDefault, ht.TListOf(_TDiskParams),
1105
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1106
     " each disk definition must contain a ``%s`` value and"
1107
     " can contain an optional ``%s`` value denoting the disk access mode"
1108
     " (%s)" %
1109
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1110
      constants.IDISK_MODE,
1111
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1112
    ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1113
     "Disk template"),
1114
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1115
     "Driver for file-backed disks"),
1116
    ("file_storage_dir", None, ht.TMaybeString,
1117
     "Directory for storing file-backed disks"),
1118
    ("hvparams", ht.EmptyDict, ht.TDict,
1119
     "Hypervisor parameters for instance, hypervisor-dependent"),
1120
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1121
    ("iallocator", None, ht.TMaybeString,
1122
     "Iallocator for deciding which node(s) to use"),
1123
    ("identify_defaults", False, ht.TBool,
1124
     "Reset instance parameters to default if equal"),
1125
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1126
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1127
     "Instance creation mode"),
1128
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1129
     "List of NIC (network interface) definitions, for example"
1130
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1131
     " contain the optional values %s" %
1132
     (constants.INIC_IP,
1133
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1134
    ("no_install", None, ht.TMaybeBool,
1135
     "Do not install the OS (will disable automatic start)"),
1136
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1137
    ("os_type", None, ht.TMaybeString, "Operating system"),
1138
    ("pnode", None, ht.TMaybeString, "Primary node"),
1139
    ("snode", None, ht.TMaybeString, "Secondary node"),
1140
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1141
     "Signed handshake from source (remote import only)"),
1142
    ("source_instance_name", None, ht.TMaybeString,
1143
     "Source instance name (remote import only)"),
1144
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1145
     ht.TPositiveInt,
1146
     "How long source instance was given to shut down (remote import only)"),
1147
    ("source_x509_ca", None, ht.TMaybeString,
1148
     "Source X509 CA in PEM format (remote import only)"),
1149
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1150
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1151
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1152
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1153
    ]
1154
  OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1155

    
1156

    
1157
class OpInstanceReinstall(OpCode):
1158
  """Reinstall an instance's OS."""
1159
  OP_DSC_FIELD = "instance_name"
1160
  OP_PARAMS = [
1161
    _PInstanceName,
1162
    _PForceVariant,
1163
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1164
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1165
    ]
1166

    
1167

    
1168
class OpInstanceRemove(OpCode):
1169
  """Remove an instance."""
1170
  OP_DSC_FIELD = "instance_name"
1171
  OP_PARAMS = [
1172
    _PInstanceName,
1173
    _PShutdownTimeout,
1174
    ("ignore_failures", False, ht.TBool,
1175
     "Whether to ignore failures during removal"),
1176
    ]
1177

    
1178

    
1179
class OpInstanceRename(OpCode):
1180
  """Rename an instance."""
1181
  OP_PARAMS = [
1182
    _PInstanceName,
1183
    _PNameCheck,
1184
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1185
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1186
    ]
1187
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1188

    
1189

    
1190
class OpInstanceStartup(OpCode):
1191
  """Startup an instance."""
1192
  OP_DSC_FIELD = "instance_name"
1193
  OP_PARAMS = [
1194
    _PInstanceName,
1195
    _PForce,
1196
    _PIgnoreOfflineNodes,
1197
    ("hvparams", ht.EmptyDict, ht.TDict,
1198
     "Temporary hypervisor parameters, hypervisor-dependent"),
1199
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1200
    _PNoRemember,
1201
    _PStartupPaused,
1202
    ]
1203

    
1204

    
1205
class OpInstanceShutdown(OpCode):
1206
  """Shutdown an instance."""
1207
  OP_DSC_FIELD = "instance_name"
1208
  OP_PARAMS = [
1209
    _PInstanceName,
1210
    _PIgnoreOfflineNodes,
1211
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1212
     "How long to wait for instance to shut down"),
1213
    _PNoRemember,
1214
    ]
1215

    
1216

    
1217
class OpInstanceReboot(OpCode):
1218
  """Reboot an instance."""
1219
  OP_DSC_FIELD = "instance_name"
1220
  OP_PARAMS = [
1221
    _PInstanceName,
1222
    _PShutdownTimeout,
1223
    ("ignore_secondaries", False, ht.TBool,
1224
     "Whether to start the instance even if secondary disks are failing"),
1225
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1226
     "How to reboot instance"),
1227
    ]
1228

    
1229

    
1230
class OpInstanceReplaceDisks(OpCode):
1231
  """Replace the disks of an instance."""
1232
  OP_DSC_FIELD = "instance_name"
1233
  OP_PARAMS = [
1234
    _PInstanceName,
1235
    _PEarlyRelease,
1236
    _PIgnoreIpolicy,
1237
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1238
     "Replacement mode"),
1239
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1240
     "Disk indexes"),
1241
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1242
    ("iallocator", None, ht.TMaybeString,
1243
     "Iallocator for deciding new secondary node"),
1244
    ]
1245

    
1246

    
1247
class OpInstanceFailover(OpCode):
1248
  """Failover an instance."""
1249
  OP_DSC_FIELD = "instance_name"
1250
  OP_PARAMS = [
1251
    _PInstanceName,
1252
    _PShutdownTimeout,
1253
    _PIgnoreConsistency,
1254
    _PMigrationTargetNode,
1255
    _PIgnoreIpolicy,
1256
    ("iallocator", None, ht.TMaybeString,
1257
     "Iallocator for deciding the target node for shared-storage instances"),
1258
    ]
1259

    
1260

    
1261
class OpInstanceMigrate(OpCode):
1262
  """Migrate an instance.
1263

1264
  This migrates (without shutting down an instance) to its secondary
1265
  node.
1266

1267
  @ivar instance_name: the name of the instance
1268
  @ivar mode: the migration mode (live, non-live or None for auto)
1269

1270
  """
1271
  OP_DSC_FIELD = "instance_name"
1272
  OP_PARAMS = [
1273
    _PInstanceName,
1274
    _PMigrationMode,
1275
    _PMigrationLive,
1276
    _PMigrationTargetNode,
1277
    _PAllowRuntimeChgs,
1278
    _PIgnoreIpolicy,
1279
    ("cleanup", False, ht.TBool,
1280
     "Whether a previously failed migration should be cleaned up"),
1281
    ("iallocator", None, ht.TMaybeString,
1282
     "Iallocator for deciding the target node for shared-storage instances"),
1283
    ("allow_failover", False, ht.TBool,
1284
     "Whether we can fallback to failover if migration is not possible"),
1285
    ]
1286

    
1287

    
1288
class OpInstanceMove(OpCode):
1289
  """Move an instance.
1290

1291
  This move (with shutting down an instance and data copying) to an
1292
  arbitrary node.
1293

1294
  @ivar instance_name: the name of the instance
1295
  @ivar target_node: the destination node
1296

1297
  """
1298
  OP_DSC_FIELD = "instance_name"
1299
  OP_PARAMS = [
1300
    _PInstanceName,
1301
    _PShutdownTimeout,
1302
    _PIgnoreIpolicy,
1303
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1304
    _PIgnoreConsistency,
1305
    ]
1306

    
1307

    
1308
class OpInstanceConsole(OpCode):
1309
  """Connect to an instance's console."""
1310
  OP_DSC_FIELD = "instance_name"
1311
  OP_PARAMS = [
1312
    _PInstanceName
1313
    ]
1314

    
1315

    
1316
class OpInstanceActivateDisks(OpCode):
1317
  """Activate an instance's disks."""
1318
  OP_DSC_FIELD = "instance_name"
1319
  OP_PARAMS = [
1320
    _PInstanceName,
1321
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1322
    ]
1323

    
1324

    
1325
class OpInstanceDeactivateDisks(OpCode):
1326
  """Deactivate an instance's disks."""
1327
  OP_DSC_FIELD = "instance_name"
1328
  OP_PARAMS = [
1329
    _PInstanceName,
1330
    _PForce,
1331
    ]
1332

    
1333

    
1334
class OpInstanceRecreateDisks(OpCode):
1335
  """Recreate an instance's disks."""
1336
  _TDiskChanges = \
1337
    ht.TAnd(ht.TIsLength(2),
1338
            ht.TItems([ht.Comment("Disk index")(ht.TPositiveInt),
1339
                       ht.Comment("Parameters")(_TDiskParams)]))
1340

    
1341
  OP_DSC_FIELD = "instance_name"
1342
  OP_PARAMS = [
1343
    _PInstanceName,
1344
    ("disks", ht.EmptyList,
1345
     ht.TOr(ht.TListOf(ht.TPositiveInt), ht.TListOf(_TDiskChanges)),
1346
     "List of disk indexes (deprecated) or a list of tuples containing a disk"
1347
     " index and a possibly empty dictionary with disk parameter changes"),
1348
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1349
     "New instance nodes, if relocation is desired"),
1350
    ]
1351

    
1352

    
1353
class OpInstanceQuery(OpCode):
1354
  """Compute the list of instances."""
1355
  OP_PARAMS = [
1356
    _POutputFields,
1357
    _PUseLocking,
1358
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1359
     "Empty list to query all instances, instance names otherwise"),
1360
    ]
1361

    
1362

    
1363
class OpInstanceQueryData(OpCode):
1364
  """Compute the run-time status of instances."""
1365
  OP_PARAMS = [
1366
    _PUseLocking,
1367
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1368
     "Instance names"),
1369
    ("static", False, ht.TBool,
1370
     "Whether to only return configuration data without querying"
1371
     " nodes"),
1372
    ]
1373

    
1374

    
1375
class OpInstanceSetParams(OpCode):
1376
  """Change the parameters of an instance."""
1377
  OP_DSC_FIELD = "instance_name"
1378
  OP_PARAMS = [
1379
    _PInstanceName,
1380
    _PForce,
1381
    _PForceVariant,
1382
    _PIgnoreIpolicy,
1383
    # TODO: Use _TestNicDef
1384
    ("nics", ht.EmptyList, ht.TList,
1385
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1386
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1387
     " ``%s`` to remove the last NIC or a number to modify the settings"
1388
     " of the NIC with that index." %
1389
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1390
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1391
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1392
    ("runtime_mem", None, ht.TMaybeStrictPositiveInt, "New runtime memory"),
1393
    ("hvparams", ht.EmptyDict, ht.TDict,
1394
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1395
    ("disk_template", None, ht.TOr(ht.TNone, _BuildDiskTemplateCheck(False)),
1396
     "Disk template for instance"),
1397
    ("remote_node", None, ht.TMaybeString,
1398
     "Secondary node (used when changing disk template)"),
1399
    ("os_name", None, ht.TMaybeString,
1400
     "Change instance's OS name. Does not reinstall the instance."),
1401
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1402
    ("wait_for_sync", True, ht.TBool,
1403
     "Whether to wait for the disk to synchronize, when changing template"),
1404
    ("offline_inst", False, ht.TBool,
1405
     "Whether to turn off the down instance completely"),
1406
    ("online_inst", False, ht.TBool,
1407
     "Whether to enable the offline instance"),
1408
    ]
1409
  OP_RESULT = _TSetParamsResult
1410

    
1411

    
1412
class OpInstanceGrowDisk(OpCode):
1413
  """Grow a disk of an instance."""
1414
  OP_DSC_FIELD = "instance_name"
1415
  OP_PARAMS = [
1416
    _PInstanceName,
1417
    _PWaitForSync,
1418
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1419
    ("amount", ht.NoDefault, ht.TInt,
1420
     "Amount of disk space to add (megabytes)"),
1421
    ]
1422

    
1423

    
1424
class OpInstanceChangeGroup(OpCode):
1425
  """Moves an instance to another node group."""
1426
  OP_DSC_FIELD = "instance_name"
1427
  OP_PARAMS = [
1428
    _PInstanceName,
1429
    _PEarlyRelease,
1430
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1431
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1432
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1433
    ]
1434
  OP_RESULT = TJobIdListOnly
1435

    
1436

    
1437
# Node group opcodes
1438

    
1439
class OpGroupAdd(OpCode):
1440
  """Add a node group to the cluster."""
1441
  OP_DSC_FIELD = "group_name"
1442
  OP_PARAMS = [
1443
    _PGroupName,
1444
    _PNodeGroupAllocPolicy,
1445
    _PGroupNodeParams,
1446
    _PDiskParams,
1447
    _PHvState,
1448
    _PDiskState,
1449
    ("ipolicy", None, ht.TMaybeDict,
1450
     "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1451
    ]
1452

    
1453

    
1454
class OpGroupAssignNodes(OpCode):
1455
  """Assign nodes to a node group."""
1456
  OP_DSC_FIELD = "group_name"
1457
  OP_PARAMS = [
1458
    _PGroupName,
1459
    _PForce,
1460
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1461
     "List of nodes to assign"),
1462
    ]
1463

    
1464

    
1465
class OpGroupQuery(OpCode):
1466
  """Compute the list of node groups."""
1467
  OP_PARAMS = [
1468
    _POutputFields,
1469
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1470
     "Empty list to query all groups, group names otherwise"),
1471
    ]
1472

    
1473

    
1474
class OpGroupSetParams(OpCode):
1475
  """Change the parameters of a node group."""
1476
  OP_DSC_FIELD = "group_name"
1477
  OP_PARAMS = [
1478
    _PGroupName,
1479
    _PNodeGroupAllocPolicy,
1480
    _PGroupNodeParams,
1481
    _PDiskParams,
1482
    _PHvState,
1483
    _PDiskState,
1484
    ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1485
    ]
1486
  OP_RESULT = _TSetParamsResult
1487

    
1488

    
1489
class OpGroupRemove(OpCode):
1490
  """Remove a node group from the cluster."""
1491
  OP_DSC_FIELD = "group_name"
1492
  OP_PARAMS = [
1493
    _PGroupName,
1494
    ]
1495

    
1496

    
1497
class OpGroupRename(OpCode):
1498
  """Rename a node group in the cluster."""
1499
  OP_PARAMS = [
1500
    _PGroupName,
1501
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1502
    ]
1503
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1504

    
1505

    
1506
class OpGroupEvacuate(OpCode):
1507
  """Evacuate a node group in the cluster."""
1508
  OP_DSC_FIELD = "group_name"
1509
  OP_PARAMS = [
1510
    _PGroupName,
1511
    _PEarlyRelease,
1512
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1513
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1514
     "Destination group names or UUIDs"),
1515
    ]
1516
  OP_RESULT = TJobIdListOnly
1517

    
1518

    
1519
# OS opcodes
1520
class OpOsDiagnose(OpCode):
1521
  """Compute the list of guest operating systems."""
1522
  OP_PARAMS = [
1523
    _POutputFields,
1524
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1525
     "Which operating systems to diagnose"),
1526
    ]
1527

    
1528

    
1529
# Exports opcodes
1530
class OpBackupQuery(OpCode):
1531
  """Compute the list of exported images."""
1532
  OP_PARAMS = [
1533
    _PUseLocking,
1534
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1535
     "Empty list to query all nodes, node names otherwise"),
1536
    ]
1537

    
1538

    
1539
class OpBackupPrepare(OpCode):
1540
  """Prepares an instance export.
1541

1542
  @ivar instance_name: Instance name
1543
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1544

1545
  """
1546
  OP_DSC_FIELD = "instance_name"
1547
  OP_PARAMS = [
1548
    _PInstanceName,
1549
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1550
     "Export mode"),
1551
    ]
1552

    
1553

    
1554
class OpBackupExport(OpCode):
1555
  """Export an instance.
1556

1557
  For local exports, the export destination is the node name. For remote
1558
  exports, the export destination is a list of tuples, each consisting of
1559
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1560
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1561
  destination X509 CA must be a signed certificate.
1562

1563
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1564
  @ivar target_node: Export destination
1565
  @ivar x509_key_name: X509 key to use (remote export only)
1566
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1567
                             only)
1568

1569
  """
1570
  OP_DSC_FIELD = "instance_name"
1571
  OP_PARAMS = [
1572
    _PInstanceName,
1573
    _PShutdownTimeout,
1574
    # TODO: Rename target_node as it changes meaning for different export modes
1575
    # (e.g. "destination")
1576
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1577
     "Destination information, depends on export mode"),
1578
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1579
    ("remove_instance", False, ht.TBool,
1580
     "Whether to remove instance after export"),
1581
    ("ignore_remove_failures", False, ht.TBool,
1582
     "Whether to ignore failures while removing instances"),
1583
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1584
     "Export mode"),
1585
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1586
     "Name of X509 key (remote export only)"),
1587
    ("destination_x509_ca", None, ht.TMaybeString,
1588
     "Destination X509 CA (remote export only)"),
1589
    ]
1590

    
1591

    
1592
class OpBackupRemove(OpCode):
1593
  """Remove an instance's export."""
1594
  OP_DSC_FIELD = "instance_name"
1595
  OP_PARAMS = [
1596
    _PInstanceName,
1597
    ]
1598

    
1599

    
1600
# Tags opcodes
1601
class OpTagsGet(OpCode):
1602
  """Returns the tags of the given object."""
1603
  OP_DSC_FIELD = "name"
1604
  OP_PARAMS = [
1605
    _PTagKind,
1606
    # Name is only meaningful for nodes and instances
1607
    ("name", ht.NoDefault, ht.TMaybeString, None),
1608
    ]
1609

    
1610

    
1611
class OpTagsSearch(OpCode):
1612
  """Searches the tags in the cluster for a given pattern."""
1613
  OP_DSC_FIELD = "pattern"
1614
  OP_PARAMS = [
1615
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1616
    ]
1617

    
1618

    
1619
class OpTagsSet(OpCode):
1620
  """Add a list of tags on a given object."""
1621
  OP_PARAMS = [
1622
    _PTagKind,
1623
    _PTags,
1624
    # Name is only meaningful for nodes and instances
1625
    ("name", ht.NoDefault, ht.TMaybeString, None),
1626
    ]
1627

    
1628

    
1629
class OpTagsDel(OpCode):
1630
  """Remove a list of tags from a given object."""
1631
  OP_PARAMS = [
1632
    _PTagKind,
1633
    _PTags,
1634
    # Name is only meaningful for nodes and instances
1635
    ("name", ht.NoDefault, ht.TMaybeString, None),
1636
    ]
1637

    
1638

    
1639
# Test opcodes
1640
class OpTestDelay(OpCode):
1641
  """Sleeps for a configured amount of time.
1642

1643
  This is used just for debugging and testing.
1644

1645
  Parameters:
1646
    - duration: the time to sleep
1647
    - on_master: if true, sleep on the master
1648
    - on_nodes: list of nodes in which to sleep
1649

1650
  If the on_master parameter is true, it will execute a sleep on the
1651
  master (before any node sleep).
1652

1653
  If the on_nodes list is not empty, it will sleep on those nodes
1654
  (after the sleep on the master, if that is enabled).
1655

1656
  As an additional feature, the case of duration < 0 will be reported
1657
  as an execution error, so this opcode can be used as a failure
1658
  generator. The case of duration == 0 will not be treated specially.
1659

1660
  """
1661
  OP_DSC_FIELD = "duration"
1662
  OP_PARAMS = [
1663
    ("duration", ht.NoDefault, ht.TNumber, None),
1664
    ("on_master", True, ht.TBool, None),
1665
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1666
    ("repeat", 0, ht.TPositiveInt, None),
1667
    ]
1668

    
1669

    
1670
class OpTestAllocator(OpCode):
1671
  """Allocator framework testing.
1672

1673
  This opcode has two modes:
1674
    - gather and return allocator input for a given mode (allocate new
1675
      or replace secondary) and a given instance definition (direction
1676
      'in')
1677
    - run a selected allocator for a given operation (as above) and
1678
      return the allocator output (direction 'out')
1679

1680
  """
1681
  OP_DSC_FIELD = "allocator"
1682
  OP_PARAMS = [
1683
    ("direction", ht.NoDefault,
1684
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1685
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1686
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1687
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1688
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1689
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1690
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1691
    ("hypervisor", None, ht.TMaybeString, None),
1692
    ("allocator", None, ht.TMaybeString, None),
1693
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1694
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1695
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1696
    ("os", None, ht.TMaybeString, None),
1697
    ("disk_template", None, ht.TMaybeString, None),
1698
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1699
     None),
1700
    ("evac_mode", None,
1701
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1702
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1703
     None),
1704
    ]
1705

    
1706

    
1707
class OpTestJqueue(OpCode):
1708
  """Utility opcode to test some aspects of the job queue.
1709

1710
  """
1711
  OP_PARAMS = [
1712
    ("notify_waitlock", False, ht.TBool, None),
1713
    ("notify_exec", False, ht.TBool, None),
1714
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1715
    ("fail", False, ht.TBool, None),
1716
    ]
1717

    
1718

    
1719
class OpTestDummy(OpCode):
1720
  """Utility opcode used by unittests.
1721

1722
  """
1723
  OP_PARAMS = [
1724
    ("result", ht.NoDefault, ht.NoType, None),
1725
    ("messages", ht.NoDefault, ht.NoType, None),
1726
    ("fail", ht.NoDefault, ht.NoType, None),
1727
    ("submit_jobs", None, ht.NoType, None),
1728
    ]
1729
  WITH_LU = False
1730

    
1731

    
1732
def _GetOpList():
1733
  """Returns list of all defined opcodes.
1734

1735
  Does not eliminate duplicates by C{OP_ID}.
1736

1737
  """
1738
  return [v for v in globals().values()
1739
          if (isinstance(v, type) and issubclass(v, OpCode) and
1740
              hasattr(v, "OP_ID") and v is not OpCode)]
1741

    
1742

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