Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ b69437c5

History | View | Annotate | Download (58.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 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 constants
40
from ganeti import errors
41
from ganeti import ht
42
from ganeti import objects
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),
84
             "Tag kind")
85

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

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

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

    
96
_PWaitForSyncFalse = ("wait_for_sync", False, ht.TBool,
97
                      "Whether to wait for the disk to synchronize"
98
                      " (defaults to false)")
99

    
100
_PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
101
                       "Whether to ignore disk consistency")
102

    
103
_PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
104

    
105
_PUseLocking = ("use_locking", False, ht.TBool,
106
                "Whether to use synchronization")
107

    
108
_PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
109

    
110
_PNodeGroupAllocPolicy = \
111
  ("alloc_policy", None,
112
   ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
113
   "Instance allocation policy")
114

    
115
_PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
116
                     "Default node parameters for group")
117

    
118
_PQueryWhat = ("what", ht.NoDefault, ht.TElemOf(constants.QR_VIA_OP),
119
               "Resource(s) to query for")
120

    
121
_PEarlyRelease = ("early_release", False, ht.TBool,
122
                  "Whether to release locks as soon as possible")
123

    
124
_PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
125

    
126
#: Do not remember instance state changes
127
_PNoRemember = ("no_remember", False, ht.TBool,
128
                "Do not remember the state change")
129

    
130
#: Target node for instance migration/failover
131
_PMigrationTargetNode = ("target_node", None, ht.TMaybeString,
132
                         "Target node for shared-storage instances")
133

    
134
_PStartupPaused = ("startup_paused", False, ht.TBool,
135
                   "Pause instance at startup")
136

    
137
_PVerbose = ("verbose", False, ht.TBool, "Verbose mode")
138

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

    
150
# Disk parameters
151
_PDiskParams = ("diskparams", None,
152
                ht.TOr(
153
                  ht.TDictOf(ht.TElemOf(constants.DISK_TEMPLATES), ht.TDict),
154
                  ht.TNone),
155
                "Disk templates' parameter defaults")
156

    
157
# Parameters for node resource model
158
_PHvState = ("hv_state", None, ht.TMaybeDict, "Set hypervisor states")
159
_PDiskState = ("disk_state", None, ht.TMaybeDict, "Set disk states")
160

    
161

    
162
_PIgnoreIpolicy = ("ignore_ipolicy", False, ht.TBool,
163
                   "Whether to ignore ipolicy violations")
164

    
165
# Allow runtime changes while migrating
166
_PAllowRuntimeChgs = ("allow_runtime_changes", True, ht.TBool,
167
                      "Allow runtime changes (eg. memory ballooning)")
168

    
169

    
170
#: OP_ID conversion regular expression
171
_OPID_RE = re.compile("([a-z])([A-Z])")
172

    
173
#: Utility function for L{OpClusterSetParams}
174
_TestClusterOsListItem = \
175
  ht.TAnd(ht.TIsLength(2), ht.TItems([
176
    ht.TElemOf(constants.DDMS_VALUES),
177
    ht.TNonEmptyString,
178
    ]))
179

    
180
_TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
181

    
182
# TODO: Generate check from constants.INIC_PARAMS_TYPES
183
#: Utility function for testing NIC definitions
184
_TestNicDef = \
185
  ht.Comment("NIC parameters")(ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
186
                                          ht.TOr(ht.TNone, ht.TNonEmptyString)))
187

    
188
_TSetParamsResultItemItems = [
189
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
190
  ht.Comment("new value")(ht.TAny),
191
  ]
192

    
193
_TSetParamsResult = \
194
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
195
                     ht.TItems(_TSetParamsResultItemItems)))
196

    
197
# TODO: Generate check from constants.IDISK_PARAMS_TYPES (however, not all users
198
# of this check support all parameters)
199
_TDiskParams = \
200
  ht.Comment("Disk parameters")(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
201
                                           ht.TOr(ht.TNonEmptyString, ht.TInt)))
202

    
203
_TQueryRow = \
204
  ht.TListOf(ht.TAnd(ht.TIsLength(2),
205
                     ht.TItems([ht.TElemOf(constants.RS_ALL),
206
                                ht.TAny])))
207

    
208
_TQueryResult = ht.TListOf(_TQueryRow)
209

    
210
_TOldQueryRow = ht.TListOf(ht.TAny)
211

    
212
_TOldQueryResult = ht.TListOf(_TOldQueryRow)
213

    
214

    
215
_SUMMARY_PREFIX = {
216
  "CLUSTER_": "C_",
217
  "GROUP_": "G_",
218
  "NODE_": "N_",
219
  "INSTANCE_": "I_",
220
  }
221

    
222
#: Attribute name for dependencies
223
DEPEND_ATTR = "depends"
224

    
225
#: Attribute name for comment
226
COMMENT_ATTR = "comment"
227

    
228

    
229
def _NameToId(name):
230
  """Convert an opcode class name to an OP_ID.
231

232
  @type name: string
233
  @param name: the class name, as OpXxxYyy
234
  @rtype: string
235
  @return: the name in the OP_XXXX_YYYY format
236

237
  """
238
  if not name.startswith("Op"):
239
    return None
240
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
241
  # consume any input, and hence we would just have all the elements
242
  # in the list, one by one; but it seems that split doesn't work on
243
  # non-consuming input, hence we have to process the input string a
244
  # bit
245
  name = _OPID_RE.sub(r"\1,\2", name)
246
  elems = name.split(",")
247
  return "_".join(n.upper() for n in elems)
248

    
249

    
250
def _GenerateObjectTypeCheck(obj, fields_types):
251
  """Helper to generate type checks for objects.
252

253
  @param obj: The object to generate type checks
254
  @param fields_types: The fields and their types as a dict
255
  @return: A ht type check function
256

257
  """
258
  assert set(obj.GetAllSlots()) == set(fields_types.keys()), \
259
    "%s != %s" % (set(obj.GetAllSlots()), set(fields_types.keys()))
260
  return ht.TStrictDict(True, True, fields_types)
261

    
262

    
263
_TQueryFieldDef = \
264
  _GenerateObjectTypeCheck(objects.QueryFieldDefinition, {
265
    "name": ht.TNonEmptyString,
266
    "title": ht.TNonEmptyString,
267
    "kind": ht.TElemOf(constants.QFT_ALL),
268
    "doc": ht.TNonEmptyString,
269
    })
270

    
271

    
272
def RequireFileStorage():
273
  """Checks that file storage is enabled.
274

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

278
  @raise errors.OpPrereqError: when file storage is disabled
279

280
  """
281
  if not constants.ENABLE_FILE_STORAGE:
282
    raise errors.OpPrereqError("File storage disabled at configure time",
283
                               errors.ECODE_INVAL)
284

    
285

    
286
def RequireSharedFileStorage():
287
  """Checks that shared file storage is enabled.
288

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

292
  @raise errors.OpPrereqError: when shared file storage is disabled
293

294
  """
295
  if not constants.ENABLE_SHARED_FILE_STORAGE:
296
    raise errors.OpPrereqError("Shared file storage disabled at"
297
                               " configure time", errors.ECODE_INVAL)
298

    
299

    
300
@ht.WithDesc("CheckFileStorage")
301
def _CheckFileStorage(value):
302
  """Ensures file storage is enabled if used.
303

304
  """
305
  if value == constants.DT_FILE:
306
    RequireFileStorage()
307
  elif value == constants.DT_SHARED_FILE:
308
    RequireSharedFileStorage()
309
  return True
310

    
311

    
312
def _BuildDiskTemplateCheck(accept_none):
313
  """Builds check for disk template.
314

315
  @type accept_none: bool
316
  @param accept_none: whether to accept None as a correct value
317
  @rtype: callable
318

319
  """
320
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
321

    
322
  if accept_none:
323
    template_check = ht.TOr(template_check, ht.TNone)
324

    
325
  return ht.TAnd(template_check, _CheckFileStorage)
326

    
327

    
328
def _CheckStorageType(storage_type):
329
  """Ensure a given storage type is valid.
330

331
  """
332
  if storage_type not in constants.VALID_STORAGE_TYPES:
333
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
334
                               errors.ECODE_INVAL)
335
  if storage_type == constants.ST_FILE:
336
    RequireFileStorage()
337
  return True
338

    
339

    
340
#: Storage type parameter
341
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
342
                 "Storage type")
343

    
344

    
345
class _AutoOpParamSlots(type):
346
  """Meta class for opcode definitions.
347

348
  """
349
  def __new__(mcs, name, bases, attrs):
350
    """Called when a class should be created.
351

352
    @param mcs: The meta class
353
    @param name: Name of created class
354
    @param bases: Base classes
355
    @type attrs: dict
356
    @param attrs: Class attributes
357

358
    """
359
    assert "__slots__" not in attrs, \
360
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
361
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
362

    
363
    attrs["OP_ID"] = _NameToId(name)
364

    
365
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
366
    params = attrs.setdefault("OP_PARAMS", [])
367

    
368
    # Use parameter names as slots
369
    slots = [pname for (pname, _, _, _) in params]
370

    
371
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
372
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
373

    
374
    attrs["__slots__"] = slots
375

    
376
    return type.__new__(mcs, name, bases, attrs)
377

    
378

    
379
class BaseOpCode(object):
380
  """A simple serializable object.
381

382
  This object serves as a parent class for OpCode without any custom
383
  field handling.
384

385
  """
386
  # pylint: disable=E1101
387
  # as OP_ID is dynamically defined
388
  __metaclass__ = _AutoOpParamSlots
389

    
390
  def __init__(self, **kwargs):
391
    """Constructor for BaseOpCode.
392

393
    The constructor takes only keyword arguments and will set
394
    attributes on this object based on the passed arguments. As such,
395
    it means that you should not pass arguments which are not in the
396
    __slots__ attribute for this class.
397

398
    """
399
    slots = self._all_slots()
400
    for key in kwargs:
401
      if key not in slots:
402
        raise TypeError("Object %s doesn't support the parameter '%s'" %
403
                        (self.__class__.__name__, key))
404
      setattr(self, key, kwargs[key])
405

    
406
  def __getstate__(self):
407
    """Generic serializer.
408

409
    This method just returns the contents of the instance as a
410
    dictionary.
411

412
    @rtype:  C{dict}
413
    @return: the instance attributes and their values
414

415
    """
416
    state = {}
417
    for name in self._all_slots():
418
      if hasattr(self, name):
419
        state[name] = getattr(self, name)
420
    return state
421

    
422
  def __setstate__(self, state):
423
    """Generic unserializer.
424

425
    This method just restores from the serialized state the attributes
426
    of the current instance.
427

428
    @param state: the serialized opcode data
429
    @type state:  C{dict}
430

431
    """
432
    if not isinstance(state, dict):
433
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
434
                       type(state))
435

    
436
    for name in self._all_slots():
437
      if name not in state and hasattr(self, name):
438
        delattr(self, name)
439

    
440
    for name in state:
441
      setattr(self, name, state[name])
442

    
443
  @classmethod
444
  def _all_slots(cls):
445
    """Compute the list of all declared slots for a class.
446

447
    """
448
    slots = []
449
    for parent in cls.__mro__:
450
      slots.extend(getattr(parent, "__slots__", []))
451
    return slots
452

    
453
  @classmethod
454
  def GetAllParams(cls):
455
    """Compute list of all parameters for an opcode.
456

457
    """
458
    slots = []
459
    for parent in cls.__mro__:
460
      slots.extend(getattr(parent, "OP_PARAMS", []))
461
    return slots
462

    
463
  def Validate(self, set_defaults):
464
    """Validate opcode parameters, optionally setting default values.
465

466
    @type set_defaults: bool
467
    @param set_defaults: Whether to set default values
468
    @raise errors.OpPrereqError: When a parameter value doesn't match
469
                                 requirements
470

471
    """
472
    for (attr_name, default, test, _) in self.GetAllParams():
473
      assert test == ht.NoType or callable(test)
474

    
475
      if not hasattr(self, attr_name):
476
        if default == ht.NoDefault:
477
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
478
                                     (self.OP_ID, attr_name),
479
                                     errors.ECODE_INVAL)
480
        elif set_defaults:
481
          if callable(default):
482
            dval = default()
483
          else:
484
            dval = default
485
          setattr(self, attr_name, dval)
486

    
487
      if test == ht.NoType:
488
        # no tests here
489
        continue
490

    
491
      if set_defaults or hasattr(self, attr_name):
492
        attr_val = getattr(self, attr_name)
493
        if not test(attr_val):
494
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
495
                        self.OP_ID, attr_name, type(attr_val), attr_val)
496
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
497
                                     (self.OP_ID, attr_name),
498
                                     errors.ECODE_INVAL)
499

    
500

    
501
def _BuildJobDepCheck(relative):
502
  """Builds check for job dependencies (L{DEPEND_ATTR}).
503

504
  @type relative: bool
505
  @param relative: Whether to accept relative job IDs (negative)
506
  @rtype: callable
507

508
  """
509
  if relative:
510
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
511
  else:
512
    job_id = ht.TJobId
513

    
514
  job_dep = \
515
    ht.TAnd(ht.TIsLength(2),
516
            ht.TItems([job_id,
517
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
518

    
519
  return ht.TMaybeListOf(job_dep)
520

    
521

    
522
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
523

    
524
#: List of submission status and job ID as returned by C{SubmitManyJobs}
525
_TJobIdListItem = \
526
  ht.TAnd(ht.TIsLength(2),
527
          ht.TItems([ht.Comment("success")(ht.TBool),
528
                     ht.Comment("Job ID if successful, error message"
529
                                " otherwise")(ht.TOr(ht.TString,
530
                                                     ht.TJobId))]))
531
TJobIdList = ht.TListOf(_TJobIdListItem)
532

    
533
#: Result containing only list of submitted jobs
534
TJobIdListOnly = ht.TStrictDict(True, True, {
535
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
536
  })
537

    
538

    
539
class OpCode(BaseOpCode):
540
  """Abstract OpCode.
541

542
  This is the root of the actual OpCode hierarchy. All clases derived
543
  from this class should override OP_ID.
544

545
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
546
               children of this class.
547
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
548
                      string returned by Summary(); see the docstring of that
549
                      method for details).
550
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
551
                   get if not already defined, and types they must match.
552
  @cvar OP_RESULT: Callable to verify opcode result
553
  @cvar WITH_LU: Boolean that specifies whether this should be included in
554
      mcpu's dispatch table
555
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
556
                 the check steps
557
  @ivar priority: Opcode priority for queue
558

559
  """
560
  # pylint: disable=E1101
561
  # as OP_ID is dynamically defined
562
  WITH_LU = True
563
  OP_PARAMS = [
564
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
565
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
566
    ("priority", constants.OP_PRIO_DEFAULT,
567
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
568
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
569
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
570
     " job IDs can be used; see :doc:`design document <design-chained-jobs>`"
571
     " for details"),
572
    (COMMENT_ATTR, None, ht.TMaybeString,
573
     "Comment describing the purpose of the opcode"),
574
    ]
575
  OP_RESULT = None
576

    
577
  def __getstate__(self):
578
    """Specialized getstate for opcodes.
579

580
    This method adds to the state dictionary the OP_ID of the class,
581
    so that on unload we can identify the correct class for
582
    instantiating the opcode.
583

584
    @rtype:   C{dict}
585
    @return:  the state as a dictionary
586

587
    """
588
    data = BaseOpCode.__getstate__(self)
589
    data["OP_ID"] = self.OP_ID
590
    return data
591

    
592
  @classmethod
593
  def LoadOpCode(cls, data):
594
    """Generic load opcode method.
595

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

600
    @type data:  C{dict}
601
    @param data: the serialized opcode
602

603
    """
604
    if not isinstance(data, dict):
605
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
606
    if "OP_ID" not in data:
607
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
608
    op_id = data["OP_ID"]
609
    op_class = None
610
    if op_id in OP_MAPPING:
611
      op_class = OP_MAPPING[op_id]
612
    else:
613
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
614
                       op_id)
615
    op = op_class()
616
    new_data = data.copy()
617
    del new_data["OP_ID"]
618
    op.__setstate__(new_data)
619
    return op
620

    
621
  def Summary(self):
622
    """Generates a summary description of this opcode.
623

624
    The summary is the value of the OP_ID attribute (without the "OP_"
625
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
626
    defined; this field should allow to easily identify the operation
627
    (for an instance creation job, e.g., it would be the instance
628
    name).
629

630
    """
631
    assert self.OP_ID is not None and len(self.OP_ID) > 3
632
    # all OP_ID start with OP_, we remove that
633
    txt = self.OP_ID[3:]
634
    field_name = getattr(self, "OP_DSC_FIELD", None)
635
    if field_name:
636
      field_value = getattr(self, field_name, None)
637
      if isinstance(field_value, (list, tuple)):
638
        field_value = ",".join(str(i) for i in field_value)
639
      txt = "%s(%s)" % (txt, field_value)
640
    return txt
641

    
642
  def TinySummary(self):
643
    """Generates a compact summary description of the opcode.
644

645
    """
646
    assert self.OP_ID.startswith("OP_")
647

    
648
    text = self.OP_ID[3:]
649

    
650
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
651
      if text.startswith(prefix):
652
        return supplement + text[len(prefix):]
653

    
654
    return text
655

    
656

    
657
# cluster opcodes
658

    
659
class OpClusterPostInit(OpCode):
660
  """Post cluster initialization.
661

662
  This opcode does not touch the cluster at all. Its purpose is to run hooks
663
  after the cluster has been initialized.
664

665
  """
666
  OP_RESULT = ht.TBool
667

    
668

    
669
class OpClusterDestroy(OpCode):
670
  """Destroy the cluster.
671

672
  This opcode has no other parameters. All the state is irreversibly
673
  lost after the execution of this opcode.
674

675
  """
676
  OP_RESULT = ht.TNonEmptyString
677

    
678

    
679
class OpClusterQuery(OpCode):
680
  """Query cluster information."""
681
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TAny)
682

    
683

    
684
class OpClusterVerify(OpCode):
685
  """Submits all jobs necessary to verify the cluster.
686

687
  """
688
  OP_PARAMS = [
689
    _PDebugSimulateErrors,
690
    _PErrorCodes,
691
    _PSkipChecks,
692
    _PIgnoreErrors,
693
    _PVerbose,
694
    ("group_name", None, ht.TMaybeString, "Group to verify")
695
    ]
696
  OP_RESULT = TJobIdListOnly
697

    
698

    
699
class OpClusterVerifyConfig(OpCode):
700
  """Verify the cluster config.
701

702
  """
703
  OP_PARAMS = [
704
    _PDebugSimulateErrors,
705
    _PErrorCodes,
706
    _PIgnoreErrors,
707
    _PVerbose,
708
    ]
709
  OP_RESULT = ht.TBool
710

    
711

    
712
class OpClusterVerifyGroup(OpCode):
713
  """Run verify on a node group from the cluster.
714

715
  @type skip_checks: C{list}
716
  @ivar skip_checks: steps to be skipped from the verify process; this
717
                     needs to be a subset of
718
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
719
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
720

721
  """
722
  OP_DSC_FIELD = "group_name"
723
  OP_PARAMS = [
724
    _PGroupName,
725
    _PDebugSimulateErrors,
726
    _PErrorCodes,
727
    _PSkipChecks,
728
    _PIgnoreErrors,
729
    _PVerbose,
730
    ]
731
  OP_RESULT = ht.TBool
732

    
733

    
734
class OpClusterVerifyDisks(OpCode):
735
  """Verify the cluster disks.
736

737
  """
738
  OP_RESULT = TJobIdListOnly
739

    
740

    
741
class OpGroupVerifyDisks(OpCode):
742
  """Verifies the status of all disks in a node group.
743

744
  Result: a tuple of three elements:
745
    - dict of node names with issues (values: error msg)
746
    - list of instances with degraded disks (that should be activated)
747
    - dict of instances with missing logical volumes (values: (node, vol)
748
      pairs with details about the missing volumes)
749

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

755
  Note that only instances that are drbd-based are taken into
756
  consideration. This might need to be revisited in the future.
757

758
  """
759
  OP_DSC_FIELD = "group_name"
760
  OP_PARAMS = [
761
    _PGroupName,
762
    ]
763
  OP_RESULT = \
764
    ht.TAnd(ht.TIsLength(3),
765
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
766
                       ht.TListOf(ht.TString),
767
                       ht.TDictOf(ht.TString,
768
                                  ht.TListOf(ht.TListOf(ht.TString)))]))
769

    
770

    
771
class OpClusterRepairDiskSizes(OpCode):
772
  """Verify the disk sizes of the instances and fixes configuration
773
  mimatches.
774

775
  Parameters: optional instances list, in case we want to restrict the
776
  checks to only a subset of the instances.
777

778
  Result: a list of tuples, (instance, disk, new-size) for changed
779
  configurations.
780

781
  In normal operation, the list should be empty.
782

783
  @type instances: list
784
  @ivar instances: the list of instances to check, or empty for all instances
785

786
  """
787
  OP_PARAMS = [
788
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
789
    ]
790
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
791
                                 ht.TItems([ht.TNonEmptyString,
792
                                            ht.TPositiveInt,
793
                                            ht.TPositiveInt])))
794

    
795

    
796
class OpClusterConfigQuery(OpCode):
797
  """Query cluster configuration values."""
798
  OP_PARAMS = [
799
    _POutputFields
800
    ]
801
  OP_RESULT = ht.TListOf(ht.TAny)
802

    
803

    
804
class OpClusterRename(OpCode):
805
  """Rename the cluster.
806

807
  @type name: C{str}
808
  @ivar name: The new name of the cluster. The name and/or the master IP
809
              address will be changed to match the new name and its IP
810
              address.
811

812
  """
813
  OP_DSC_FIELD = "name"
814
  OP_PARAMS = [
815
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
816
    ]
817
  OP_RESULT = ht.TNonEmptyString
818

    
819

    
820
class OpClusterSetParams(OpCode):
821
  """Change the parameters of the cluster.
822

823
  @type vg_name: C{str} or C{None}
824
  @ivar vg_name: The new volume group name or None to disable LVM usage.
825

826
  """
827
  OP_PARAMS = [
828
    _PHvState,
829
    _PDiskState,
830
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
831
    ("enabled_hypervisors", None,
832
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
833
            ht.TNone),
834
     "List of enabled hypervisors"),
835
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
836
                              ht.TNone),
837
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
838
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
839
     "Cluster-wide backend parameter defaults"),
840
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
841
                            ht.TNone),
842
     "Cluster-wide per-OS hypervisor parameter defaults"),
843
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
844
                              ht.TNone),
845
     "Cluster-wide OS parameter defaults"),
846
    _PDiskParams,
847
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
848
     "Master candidate pool size"),
849
    ("uid_pool", None, ht.NoType,
850
     "Set UID pool, must be list of lists describing UID ranges (two items,"
851
     " start and end inclusive)"),
852
    ("add_uids", None, ht.NoType,
853
     "Extend UID pool, must be list of lists describing UID ranges (two"
854
     " items, start and end inclusive) to be added"),
855
    ("remove_uids", None, ht.NoType,
856
     "Shrink UID pool, must be list of lists describing UID ranges (two"
857
     " items, start and end inclusive) to be removed"),
858
    ("maintain_node_health", None, ht.TMaybeBool,
859
     "Whether to automatically maintain node health"),
860
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
861
     "Whether to wipe disks before allocating them to instances"),
862
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
863
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
864
    ("ipolicy", None, ht.TMaybeDict,
865
     "Cluster-wide :ref:`instance policy <rapi-ipolicy>` specs"),
866
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
867
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
868
     "Default iallocator for cluster"),
869
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
870
     "Master network device"),
871
    ("master_netmask", None, ht.TOr(ht.TInt, ht.TNone),
872
     "Netmask of the master IP"),
873
    ("reserved_lvs", None, ht.TMaybeListOf(ht.TNonEmptyString),
874
     "List of reserved LVs"),
875
    ("hidden_os", None, _TestClusterOsList,
876
     "Modify list of hidden operating systems. Each modification must have"
877
     " two items, the operation and the OS name. The operation can be"
878
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
879
    ("blacklisted_os", None, _TestClusterOsList,
880
     "Modify list of blacklisted operating systems. Each modification must have"
881
     " two items, the operation and the OS name. The operation can be"
882
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
883
    ("use_external_mip_script", None, ht.TMaybeBool,
884
     "Whether to use an external master IP address setup script"),
885
    ]
886
  OP_RESULT = ht.TNone
887

    
888

    
889
class OpClusterRedistConf(OpCode):
890
  """Force a full push of the cluster configuration.
891

892
  """
893
  OP_RESULT = ht.TNone
894

    
895

    
896
class OpClusterActivateMasterIp(OpCode):
897
  """Activate the master IP on the master node.
898

899
  """
900
  OP_RESULT = ht.TNone
901

    
902

    
903
class OpClusterDeactivateMasterIp(OpCode):
904
  """Deactivate the master IP on the master node.
905

906
  """
907
  OP_RESULT = ht.TNone
908

    
909

    
910
class OpQuery(OpCode):
911
  """Query for resources/items.
912

913
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
914
  @ivar fields: List of fields to retrieve
915
  @ivar qfilter: Query filter
916

917
  """
918
  OP_DSC_FIELD = "what"
919
  OP_PARAMS = [
920
    _PQueryWhat,
921
    _PUseLocking,
922
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
923
     "Requested fields"),
924
    ("qfilter", None, ht.TOr(ht.TNone, ht.TList),
925
     "Query filter"),
926
    ]
927
  OP_RESULT = \
928
    _GenerateObjectTypeCheck(objects.QueryResponse, {
929
      "fields": ht.TListOf(_TQueryFieldDef),
930
      "data": _TQueryResult,
931
      })
932

    
933

    
934
class OpQueryFields(OpCode):
935
  """Query for available resource/item fields.
936

937
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
938
  @ivar fields: List of fields to retrieve
939

940
  """
941
  OP_DSC_FIELD = "what"
942
  OP_PARAMS = [
943
    _PQueryWhat,
944
    ("fields", None, ht.TMaybeListOf(ht.TNonEmptyString),
945
     "Requested fields; if not given, all are returned"),
946
    ]
947
  OP_RESULT = \
948
    _GenerateObjectTypeCheck(objects.QueryFieldsResponse, {
949
      "fields": ht.TListOf(_TQueryFieldDef),
950
      })
951

    
952

    
953
class OpOobCommand(OpCode):
954
  """Interact with OOB."""
955
  OP_PARAMS = [
956
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
957
     "List of nodes to run the OOB command against"),
958
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
959
     "OOB command to be run"),
960
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
961
     "Timeout before the OOB helper will be terminated"),
962
    ("ignore_status", False, ht.TBool,
963
     "Ignores the node offline status for power off"),
964
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
965
     "Time in seconds to wait between powering on nodes"),
966
    ]
967
  # Fixme: Make it more specific with all the special cases in LUOobCommand
968
  OP_RESULT = _TQueryResult
969

    
970

    
971
# node opcodes
972

    
973
class OpNodeRemove(OpCode):
974
  """Remove a node.
975

976
  @type node_name: C{str}
977
  @ivar node_name: The name of the node to remove. If the node still has
978
                   instances on it, the operation will fail.
979

980
  """
981
  OP_DSC_FIELD = "node_name"
982
  OP_PARAMS = [
983
    _PNodeName,
984
    ]
985
  OP_RESULT = ht.TNone
986

    
987

    
988
class OpNodeAdd(OpCode):
989
  """Add a node to the cluster.
990

991
  @type node_name: C{str}
992
  @ivar node_name: The name of the node to add. This can be a short name,
993
                   but it will be expanded to the FQDN.
994
  @type primary_ip: IP address
995
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
996
                    opcode is submitted, but will be filled during the node
997
                    add (so it will be visible in the job query).
998
  @type secondary_ip: IP address
999
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
1000
                      if the cluster has been initialized in 'dual-network'
1001
                      mode, otherwise it must not be given.
1002
  @type readd: C{bool}
1003
  @ivar readd: Whether to re-add an existing node to the cluster. If
1004
               this is not passed, then the operation will abort if the node
1005
               name is already in the cluster; use this parameter to 'repair'
1006
               a node that had its configuration broken, or was reinstalled
1007
               without removal from the cluster.
1008
  @type group: C{str}
1009
  @ivar group: The node group to which this node will belong.
1010
  @type vm_capable: C{bool}
1011
  @ivar vm_capable: The vm_capable node attribute
1012
  @type master_capable: C{bool}
1013
  @ivar master_capable: The master_capable node attribute
1014

1015
  """
1016
  OP_DSC_FIELD = "node_name"
1017
  OP_PARAMS = [
1018
    _PNodeName,
1019
    _PHvState,
1020
    _PDiskState,
1021
    ("primary_ip", None, ht.NoType, "Primary IP address"),
1022
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
1023
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
1024
    ("group", None, ht.TMaybeString, "Initial node group"),
1025
    ("master_capable", None, ht.TMaybeBool,
1026
     "Whether node can become master or master candidate"),
1027
    ("vm_capable", None, ht.TMaybeBool,
1028
     "Whether node can host instances"),
1029
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
1030
    ]
1031
  OP_RESULT = ht.TNone
1032

    
1033

    
1034
class OpNodeQuery(OpCode):
1035
  """Compute the list of nodes."""
1036
  OP_PARAMS = [
1037
    _POutputFields,
1038
    _PUseLocking,
1039
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1040
     "Empty list to query all nodes, node names otherwise"),
1041
    ]
1042
  OP_RESULT = _TOldQueryResult
1043

    
1044

    
1045
class OpNodeQueryvols(OpCode):
1046
  """Get list of volumes on node."""
1047
  OP_PARAMS = [
1048
    _POutputFields,
1049
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1050
     "Empty list to query all nodes, node names otherwise"),
1051
    ]
1052
  OP_RESULT = ht.TListOf(ht.TAny)
1053

    
1054

    
1055
class OpNodeQueryStorage(OpCode):
1056
  """Get information on storage for node(s)."""
1057
  OP_PARAMS = [
1058
    _POutputFields,
1059
    _PStorageType,
1060
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
1061
    ("name", None, ht.TMaybeString, "Storage name"),
1062
    ]
1063
  OP_RESULT = _TOldQueryResult
1064

    
1065

    
1066
class OpNodeModifyStorage(OpCode):
1067
  """Modifies the properies of a storage unit"""
1068
  OP_DSC_FIELD = "node_name"
1069
  OP_PARAMS = [
1070
    _PNodeName,
1071
    _PStorageType,
1072
    _PStorageName,
1073
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1074
    ]
1075
  OP_RESULT = ht.TNone
1076

    
1077

    
1078
class OpRepairNodeStorage(OpCode):
1079
  """Repairs the volume group on a node."""
1080
  OP_DSC_FIELD = "node_name"
1081
  OP_PARAMS = [
1082
    _PNodeName,
1083
    _PStorageType,
1084
    _PStorageName,
1085
    _PIgnoreConsistency,
1086
    ]
1087
  OP_RESULT = ht.TNone
1088

    
1089

    
1090
class OpNodeSetParams(OpCode):
1091
  """Change the parameters of a node."""
1092
  OP_DSC_FIELD = "node_name"
1093
  OP_PARAMS = [
1094
    _PNodeName,
1095
    _PForce,
1096
    _PHvState,
1097
    _PDiskState,
1098
    ("master_candidate", None, ht.TMaybeBool,
1099
     "Whether the node should become a master candidate"),
1100
    ("offline", None, ht.TMaybeBool,
1101
     "Whether the node should be marked as offline"),
1102
    ("drained", None, ht.TMaybeBool,
1103
     "Whether the node should be marked as drained"),
1104
    ("auto_promote", False, ht.TBool,
1105
     "Whether node(s) should be promoted to master candidate if necessary"),
1106
    ("master_capable", None, ht.TMaybeBool,
1107
     "Denote whether node can become master or master candidate"),
1108
    ("vm_capable", None, ht.TMaybeBool,
1109
     "Denote whether node can host instances"),
1110
    ("secondary_ip", None, ht.TMaybeString,
1111
     "Change node's secondary IP address"),
1112
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1113
    ("powered", None, ht.TMaybeBool,
1114
     "Whether the node should be marked as powered"),
1115
    ]
1116
  OP_RESULT = _TSetParamsResult
1117

    
1118

    
1119
class OpNodePowercycle(OpCode):
1120
  """Tries to powercycle a node."""
1121
  OP_DSC_FIELD = "node_name"
1122
  OP_PARAMS = [
1123
    _PNodeName,
1124
    _PForce,
1125
    ]
1126
  OP_RESULT = ht.TMaybeString
1127

    
1128

    
1129
class OpNodeMigrate(OpCode):
1130
  """Migrate all instances from a node."""
1131
  OP_DSC_FIELD = "node_name"
1132
  OP_PARAMS = [
1133
    _PNodeName,
1134
    _PMigrationMode,
1135
    _PMigrationLive,
1136
    _PMigrationTargetNode,
1137
    _PAllowRuntimeChgs,
1138
    _PIgnoreIpolicy,
1139
    ("iallocator", None, ht.TMaybeString,
1140
     "Iallocator for deciding the target node for shared-storage instances"),
1141
    ]
1142
  OP_RESULT = TJobIdListOnly
1143

    
1144

    
1145
class OpNodeEvacuate(OpCode):
1146
  """Evacuate instances off a number of nodes."""
1147
  OP_DSC_FIELD = "node_name"
1148
  OP_PARAMS = [
1149
    _PEarlyRelease,
1150
    _PNodeName,
1151
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1152
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1153
    ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1154
     "Node evacuation mode"),
1155
    ]
1156
  OP_RESULT = TJobIdListOnly
1157

    
1158

    
1159
# instance opcodes
1160

    
1161
class OpInstanceCreate(OpCode):
1162
  """Create an instance.
1163

1164
  @ivar instance_name: Instance name
1165
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1166
  @ivar source_handshake: Signed handshake from source (remote import only)
1167
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1168
  @ivar source_instance_name: Previous name of instance (remote import only)
1169
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1170
    (remote import only)
1171

1172
  """
1173
  OP_DSC_FIELD = "instance_name"
1174
  OP_PARAMS = [
1175
    _PInstanceName,
1176
    _PForceVariant,
1177
    _PWaitForSync,
1178
    _PNameCheck,
1179
    _PIgnoreIpolicy,
1180
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1181
    ("disks", ht.NoDefault, ht.TListOf(_TDiskParams),
1182
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1183
     " each disk definition must contain a ``%s`` value and"
1184
     " can contain an optional ``%s`` value denoting the disk access mode"
1185
     " (%s)" %
1186
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1187
      constants.IDISK_MODE,
1188
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1189
    ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1190
     "Disk template"),
1191
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1192
     "Driver for file-backed disks"),
1193
    ("file_storage_dir", None, ht.TMaybeString,
1194
     "Directory for storing file-backed disks"),
1195
    ("hvparams", ht.EmptyDict, ht.TDict,
1196
     "Hypervisor parameters for instance, hypervisor-dependent"),
1197
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1198
    ("iallocator", None, ht.TMaybeString,
1199
     "Iallocator for deciding which node(s) to use"),
1200
    ("identify_defaults", False, ht.TBool,
1201
     "Reset instance parameters to default if equal"),
1202
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1203
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1204
     "Instance creation mode"),
1205
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1206
     "List of NIC (network interface) definitions, for example"
1207
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1208
     " contain the optional values %s" %
1209
     (constants.INIC_IP,
1210
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1211
    ("no_install", None, ht.TMaybeBool,
1212
     "Do not install the OS (will disable automatic start)"),
1213
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1214
    ("os_type", None, ht.TMaybeString, "Operating system"),
1215
    ("pnode", None, ht.TMaybeString, "Primary node"),
1216
    ("snode", None, ht.TMaybeString, "Secondary node"),
1217
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1218
     "Signed handshake from source (remote import only)"),
1219
    ("source_instance_name", None, ht.TMaybeString,
1220
     "Source instance name (remote import only)"),
1221
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1222
     ht.TPositiveInt,
1223
     "How long source instance was given to shut down (remote import only)"),
1224
    ("source_x509_ca", None, ht.TMaybeString,
1225
     "Source X509 CA in PEM format (remote import only)"),
1226
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1227
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1228
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1229
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1230
    ]
1231
  OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1232

    
1233

    
1234
class OpInstanceReinstall(OpCode):
1235
  """Reinstall an instance's OS."""
1236
  OP_DSC_FIELD = "instance_name"
1237
  OP_PARAMS = [
1238
    _PInstanceName,
1239
    _PForceVariant,
1240
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1241
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1242
    ]
1243
  OP_RESULT = ht.TNone
1244

    
1245

    
1246
class OpInstanceRemove(OpCode):
1247
  """Remove an instance."""
1248
  OP_DSC_FIELD = "instance_name"
1249
  OP_PARAMS = [
1250
    _PInstanceName,
1251
    _PShutdownTimeout,
1252
    ("ignore_failures", False, ht.TBool,
1253
     "Whether to ignore failures during removal"),
1254
    ]
1255
  OP_RESULT = ht.TNone
1256

    
1257

    
1258
class OpInstanceRename(OpCode):
1259
  """Rename an instance."""
1260
  OP_PARAMS = [
1261
    _PInstanceName,
1262
    _PNameCheck,
1263
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1264
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1265
    ]
1266
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1267

    
1268

    
1269
class OpInstanceStartup(OpCode):
1270
  """Startup an instance."""
1271
  OP_DSC_FIELD = "instance_name"
1272
  OP_PARAMS = [
1273
    _PInstanceName,
1274
    _PForce,
1275
    _PIgnoreOfflineNodes,
1276
    ("hvparams", ht.EmptyDict, ht.TDict,
1277
     "Temporary hypervisor parameters, hypervisor-dependent"),
1278
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1279
    _PNoRemember,
1280
    _PStartupPaused,
1281
    ]
1282
  OP_RESULT = ht.TNone
1283

    
1284

    
1285
class OpInstanceShutdown(OpCode):
1286
  """Shutdown an instance."""
1287
  OP_DSC_FIELD = "instance_name"
1288
  OP_PARAMS = [
1289
    _PInstanceName,
1290
    _PIgnoreOfflineNodes,
1291
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1292
     "How long to wait for instance to shut down"),
1293
    _PNoRemember,
1294
    ]
1295
  OP_RESULT = ht.TNone
1296

    
1297

    
1298
class OpInstanceReboot(OpCode):
1299
  """Reboot an instance."""
1300
  OP_DSC_FIELD = "instance_name"
1301
  OP_PARAMS = [
1302
    _PInstanceName,
1303
    _PShutdownTimeout,
1304
    ("ignore_secondaries", False, ht.TBool,
1305
     "Whether to start the instance even if secondary disks are failing"),
1306
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1307
     "How to reboot instance"),
1308
    ]
1309
  OP_RESULT = ht.TNone
1310

    
1311

    
1312
class OpInstanceReplaceDisks(OpCode):
1313
  """Replace the disks of an instance."""
1314
  OP_DSC_FIELD = "instance_name"
1315
  OP_PARAMS = [
1316
    _PInstanceName,
1317
    _PEarlyRelease,
1318
    _PIgnoreIpolicy,
1319
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1320
     "Replacement mode"),
1321
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1322
     "Disk indexes"),
1323
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1324
    ("iallocator", None, ht.TMaybeString,
1325
     "Iallocator for deciding new secondary node"),
1326
    ]
1327
  OP_RESULT = ht.TNone
1328

    
1329

    
1330
class OpInstanceFailover(OpCode):
1331
  """Failover an instance."""
1332
  OP_DSC_FIELD = "instance_name"
1333
  OP_PARAMS = [
1334
    _PInstanceName,
1335
    _PShutdownTimeout,
1336
    _PIgnoreConsistency,
1337
    _PMigrationTargetNode,
1338
    _PIgnoreIpolicy,
1339
    ("iallocator", None, ht.TMaybeString,
1340
     "Iallocator for deciding the target node for shared-storage instances"),
1341
    ]
1342
  OP_RESULT = ht.TNone
1343

    
1344

    
1345
class OpInstanceMigrate(OpCode):
1346
  """Migrate an instance.
1347

1348
  This migrates (without shutting down an instance) to its secondary
1349
  node.
1350

1351
  @ivar instance_name: the name of the instance
1352
  @ivar mode: the migration mode (live, non-live or None for auto)
1353

1354
  """
1355
  OP_DSC_FIELD = "instance_name"
1356
  OP_PARAMS = [
1357
    _PInstanceName,
1358
    _PMigrationMode,
1359
    _PMigrationLive,
1360
    _PMigrationTargetNode,
1361
    _PAllowRuntimeChgs,
1362
    _PIgnoreIpolicy,
1363
    ("cleanup", False, ht.TBool,
1364
     "Whether a previously failed migration should be cleaned up"),
1365
    ("iallocator", None, ht.TMaybeString,
1366
     "Iallocator for deciding the target node for shared-storage instances"),
1367
    ("allow_failover", False, ht.TBool,
1368
     "Whether we can fallback to failover if migration is not possible"),
1369
    ]
1370
  OP_RESULT = ht.TNone
1371

    
1372

    
1373
class OpInstanceMove(OpCode):
1374
  """Move an instance.
1375

1376
  This move (with shutting down an instance and data copying) to an
1377
  arbitrary node.
1378

1379
  @ivar instance_name: the name of the instance
1380
  @ivar target_node: the destination node
1381

1382
  """
1383
  OP_DSC_FIELD = "instance_name"
1384
  OP_PARAMS = [
1385
    _PInstanceName,
1386
    _PShutdownTimeout,
1387
    _PIgnoreIpolicy,
1388
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1389
    _PIgnoreConsistency,
1390
    ]
1391
  OP_RESULT = ht.TNone
1392

    
1393

    
1394
class OpInstanceConsole(OpCode):
1395
  """Connect to an instance's console."""
1396
  OP_DSC_FIELD = "instance_name"
1397
  OP_PARAMS = [
1398
    _PInstanceName
1399
    ]
1400
  OP_RESULT = ht.TDict
1401

    
1402

    
1403
class OpInstanceActivateDisks(OpCode):
1404
  """Activate an instance's disks."""
1405
  OP_DSC_FIELD = "instance_name"
1406
  OP_PARAMS = [
1407
    _PInstanceName,
1408
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1409
    _PWaitForSyncFalse,
1410
    ]
1411
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
1412
                                 ht.TItems([ht.TNonEmptyString,
1413
                                            ht.TNonEmptyString,
1414
                                            ht.TNonEmptyString])))
1415

    
1416

    
1417
class OpInstanceDeactivateDisks(OpCode):
1418
  """Deactivate an instance's disks."""
1419
  OP_DSC_FIELD = "instance_name"
1420
  OP_PARAMS = [
1421
    _PInstanceName,
1422
    _PForce,
1423
    ]
1424
  OP_RESULT = ht.TNone
1425

    
1426

    
1427
class OpInstanceRecreateDisks(OpCode):
1428
  """Recreate an instance's disks."""
1429
  _TDiskChanges = \
1430
    ht.TAnd(ht.TIsLength(2),
1431
            ht.TItems([ht.Comment("Disk index")(ht.TPositiveInt),
1432
                       ht.Comment("Parameters")(_TDiskParams)]))
1433

    
1434
  OP_DSC_FIELD = "instance_name"
1435
  OP_PARAMS = [
1436
    _PInstanceName,
1437
    ("disks", ht.EmptyList,
1438
     ht.TOr(ht.TListOf(ht.TPositiveInt), ht.TListOf(_TDiskChanges)),
1439
     "List of disk indexes (deprecated) or a list of tuples containing a disk"
1440
     " index and a possibly empty dictionary with disk parameter changes"),
1441
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1442
     "New instance nodes, if relocation is desired"),
1443
    ]
1444
  OP_RESULT = ht.TNone
1445

    
1446

    
1447
class OpInstanceQuery(OpCode):
1448
  """Compute the list of instances."""
1449
  OP_PARAMS = [
1450
    _POutputFields,
1451
    _PUseLocking,
1452
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1453
     "Empty list to query all instances, instance names otherwise"),
1454
    ]
1455
  OP_RESULT = _TOldQueryResult
1456

    
1457

    
1458
class OpInstanceQueryData(OpCode):
1459
  """Compute the run-time status of instances."""
1460
  OP_PARAMS = [
1461
    _PUseLocking,
1462
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1463
     "Instance names"),
1464
    ("static", False, ht.TBool,
1465
     "Whether to only return configuration data without querying"
1466
     " nodes"),
1467
    ]
1468
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TDict)
1469

    
1470

    
1471
def _TestInstSetParamsModList(fn):
1472
  """Generates a check for modification lists.
1473

1474
  """
1475
  # Old format
1476
  # TODO: Remove in version 2.8 including support in LUInstanceSetParams
1477
  old_mod_item_fn = \
1478
    ht.TAnd(ht.TIsLength(2), ht.TItems([
1479
      ht.TOr(ht.TElemOf(constants.DDMS_VALUES), ht.TPositiveInt),
1480
      fn,
1481
      ]))
1482

    
1483
  # New format, supporting adding/removing disks/NICs at arbitrary indices
1484
  mod_item_fn = \
1485
    ht.TAnd(ht.TIsLength(3), ht.TItems([
1486
      ht.TElemOf(constants.DDMS_VALUES_WITH_MODIFY),
1487
      ht.Comment("Disk index, can be negative, e.g. -1 for last disk")(ht.TInt),
1488
      fn,
1489
      ]))
1490

    
1491
  return ht.TOr(ht.Comment("Recommended")(ht.TListOf(mod_item_fn)),
1492
                ht.Comment("Deprecated")(ht.TListOf(old_mod_item_fn)))
1493

    
1494

    
1495
class OpInstanceSetParams(OpCode):
1496
  """Change the parameters of an instance.
1497

1498
  """
1499
  TestNicModifications = _TestInstSetParamsModList(_TestNicDef)
1500
  TestDiskModifications = _TestInstSetParamsModList(_TDiskParams)
1501

    
1502
  OP_DSC_FIELD = "instance_name"
1503
  OP_PARAMS = [
1504
    _PInstanceName,
1505
    _PForce,
1506
    _PForceVariant,
1507
    _PIgnoreIpolicy,
1508
    ("nics", ht.EmptyList, TestNicModifications,
1509
     "List of NIC changes. Each item is of the form ``(op, index, settings)``."
1510
     " ``op`` is one of ``%s``, ``%s`` or ``%s``. ``index`` can be either -1 to"
1511
     " refer to the last position, or a zero-based index number. A deprecated"
1512
     " version of this parameter used the form ``(op, settings)``, where "
1513
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1514
     " ``%s`` to remove the last NIC or a number to modify the settings"
1515
     " of the NIC with that index." %
1516
     (constants.DDM_ADD, constants.DDM_MODIFY, constants.DDM_REMOVE,
1517
      constants.DDM_ADD, constants.DDM_REMOVE)),
1518
    ("disks", ht.EmptyList, TestDiskModifications,
1519
     "List of disk changes. See ``nics``."),
1520
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1521
    ("runtime_mem", None, ht.TMaybeStrictPositiveInt, "New runtime memory"),
1522
    ("hvparams", ht.EmptyDict, ht.TDict,
1523
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1524
    ("disk_template", None, ht.TOr(ht.TNone, _BuildDiskTemplateCheck(False)),
1525
     "Disk template for instance"),
1526
    ("remote_node", None, ht.TMaybeString,
1527
     "Secondary node (used when changing disk template)"),
1528
    ("os_name", None, ht.TMaybeString,
1529
     "Change instance's OS name. Does not reinstall the instance."),
1530
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1531
    ("wait_for_sync", True, ht.TBool,
1532
     "Whether to wait for the disk to synchronize, when changing template"),
1533
    ("offline", None, ht.TMaybeBool, "Whether to mark instance as offline"),
1534
    ]
1535
  OP_RESULT = _TSetParamsResult
1536

    
1537

    
1538
class OpInstanceGrowDisk(OpCode):
1539
  """Grow a disk of an instance."""
1540
  OP_DSC_FIELD = "instance_name"
1541
  OP_PARAMS = [
1542
    _PInstanceName,
1543
    _PWaitForSync,
1544
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1545
    ("amount", ht.NoDefault, ht.TPositiveInt,
1546
     "Amount of disk space to add (megabytes)"),
1547
    ("absolute", False, ht.TBool,
1548
     "Whether the amount parameter is an absolute target or a relative one"),
1549
    ]
1550
  OP_RESULT = ht.TNone
1551

    
1552

    
1553
class OpInstanceChangeGroup(OpCode):
1554
  """Moves an instance to another node group."""
1555
  OP_DSC_FIELD = "instance_name"
1556
  OP_PARAMS = [
1557
    _PInstanceName,
1558
    _PEarlyRelease,
1559
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1560
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1561
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1562
    ]
1563
  OP_RESULT = TJobIdListOnly
1564

    
1565

    
1566
# Node group opcodes
1567

    
1568
class OpGroupAdd(OpCode):
1569
  """Add a node group to the cluster."""
1570
  OP_DSC_FIELD = "group_name"
1571
  OP_PARAMS = [
1572
    _PGroupName,
1573
    _PNodeGroupAllocPolicy,
1574
    _PGroupNodeParams,
1575
    _PDiskParams,
1576
    _PHvState,
1577
    _PDiskState,
1578
    ("ipolicy", None, ht.TMaybeDict,
1579
     "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1580
    ]
1581
  OP_RESULT = ht.TNone
1582

    
1583

    
1584
class OpGroupAssignNodes(OpCode):
1585
  """Assign nodes to a node group."""
1586
  OP_DSC_FIELD = "group_name"
1587
  OP_PARAMS = [
1588
    _PGroupName,
1589
    _PForce,
1590
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1591
     "List of nodes to assign"),
1592
    ]
1593
  OP_RESULT = ht.TNone
1594

    
1595

    
1596
class OpGroupQuery(OpCode):
1597
  """Compute the list of node groups."""
1598
  OP_PARAMS = [
1599
    _POutputFields,
1600
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1601
     "Empty list to query all groups, group names otherwise"),
1602
    ]
1603
  OP_RESULT = _TOldQueryResult
1604

    
1605

    
1606
class OpGroupSetParams(OpCode):
1607
  """Change the parameters of a node group."""
1608
  OP_DSC_FIELD = "group_name"
1609
  OP_PARAMS = [
1610
    _PGroupName,
1611
    _PNodeGroupAllocPolicy,
1612
    _PGroupNodeParams,
1613
    _PDiskParams,
1614
    _PHvState,
1615
    _PDiskState,
1616
    ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1617
    ]
1618
  OP_RESULT = _TSetParamsResult
1619

    
1620

    
1621
class OpGroupRemove(OpCode):
1622
  """Remove a node group from the cluster."""
1623
  OP_DSC_FIELD = "group_name"
1624
  OP_PARAMS = [
1625
    _PGroupName,
1626
    ]
1627
  OP_RESULT = ht.TNone
1628

    
1629

    
1630
class OpGroupRename(OpCode):
1631
  """Rename a node group in the cluster."""
1632
  OP_PARAMS = [
1633
    _PGroupName,
1634
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1635
    ]
1636
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1637

    
1638

    
1639
class OpGroupEvacuate(OpCode):
1640
  """Evacuate a node group in the cluster."""
1641
  OP_DSC_FIELD = "group_name"
1642
  OP_PARAMS = [
1643
    _PGroupName,
1644
    _PEarlyRelease,
1645
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1646
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1647
     "Destination group names or UUIDs"),
1648
    ]
1649
  OP_RESULT = TJobIdListOnly
1650

    
1651

    
1652
# OS opcodes
1653
class OpOsDiagnose(OpCode):
1654
  """Compute the list of guest operating systems."""
1655
  OP_PARAMS = [
1656
    _POutputFields,
1657
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1658
     "Which operating systems to diagnose"),
1659
    ]
1660
  OP_RESULT = _TOldQueryResult
1661

    
1662

    
1663
# Exports opcodes
1664
class OpBackupQuery(OpCode):
1665
  """Compute the list of exported images."""
1666
  OP_PARAMS = [
1667
    _PUseLocking,
1668
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1669
     "Empty list to query all nodes, node names otherwise"),
1670
    ]
1671
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString,
1672
                         ht.TOr(ht.Comment("False on error")(ht.TBool),
1673
                                ht.TListOf(ht.TNonEmptyString)))
1674

    
1675

    
1676
class OpBackupPrepare(OpCode):
1677
  """Prepares an instance export.
1678

1679
  @ivar instance_name: Instance name
1680
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1681

1682
  """
1683
  OP_DSC_FIELD = "instance_name"
1684
  OP_PARAMS = [
1685
    _PInstanceName,
1686
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1687
     "Export mode"),
1688
    ]
1689
  OP_RESULT = ht.TOr(ht.TNone, ht.TDict)
1690

    
1691

    
1692
class OpBackupExport(OpCode):
1693
  """Export an instance.
1694

1695
  For local exports, the export destination is the node name. For remote
1696
  exports, the export destination is a list of tuples, each consisting of
1697
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1698
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1699
  destination X509 CA must be a signed certificate.
1700

1701
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1702
  @ivar target_node: Export destination
1703
  @ivar x509_key_name: X509 key to use (remote export only)
1704
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1705
                             only)
1706

1707
  """
1708
  OP_DSC_FIELD = "instance_name"
1709
  OP_PARAMS = [
1710
    _PInstanceName,
1711
    _PShutdownTimeout,
1712
    # TODO: Rename target_node as it changes meaning for different export modes
1713
    # (e.g. "destination")
1714
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1715
     "Destination information, depends on export mode"),
1716
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1717
    ("remove_instance", False, ht.TBool,
1718
     "Whether to remove instance after export"),
1719
    ("ignore_remove_failures", False, ht.TBool,
1720
     "Whether to ignore failures while removing instances"),
1721
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1722
     "Export mode"),
1723
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1724
     "Name of X509 key (remote export only)"),
1725
    ("destination_x509_ca", None, ht.TMaybeString,
1726
     "Destination X509 CA (remote export only)"),
1727
    ]
1728
  OP_RESULT = \
1729
    ht.TAnd(ht.TIsLength(2), ht.TItems([
1730
      ht.Comment("Finalizing status")(ht.TBool),
1731
      ht.Comment("Status for every exported disk")(ht.TListOf(ht.TBool)),
1732
      ]))
1733

    
1734

    
1735
class OpBackupRemove(OpCode):
1736
  """Remove an instance's export."""
1737
  OP_DSC_FIELD = "instance_name"
1738
  OP_PARAMS = [
1739
    _PInstanceName,
1740
    ]
1741
  OP_RESULT = ht.TNone
1742

    
1743

    
1744
# Tags opcodes
1745
class OpTagsGet(OpCode):
1746
  """Returns the tags of the given object."""
1747
  OP_DSC_FIELD = "name"
1748
  OP_PARAMS = [
1749
    _PTagKind,
1750
    # Not using _PUseLocking as the default is different for historical reasons
1751
    ("use_locking", True, ht.TBool, "Whether to use synchronization"),
1752
    # Name is only meaningful for nodes and instances
1753
    ("name", ht.NoDefault, ht.TMaybeString,
1754
     "Name of object to retrieve tags from"),
1755
    ]
1756
  OP_RESULT = ht.TListOf(ht.TNonEmptyString)
1757

    
1758

    
1759
class OpTagsSearch(OpCode):
1760
  """Searches the tags in the cluster for a given pattern."""
1761
  OP_DSC_FIELD = "pattern"
1762
  OP_PARAMS = [
1763
    ("pattern", ht.NoDefault, ht.TNonEmptyString,
1764
     "Search pattern (regular expression)"),
1765
    ]
1766
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
1767
    ht.TNonEmptyString,
1768
    ht.TNonEmptyString,
1769
    ])))
1770

    
1771

    
1772
class OpTagsSet(OpCode):
1773
  """Add a list of tags on a given object."""
1774
  OP_PARAMS = [
1775
    _PTagKind,
1776
    _PTags,
1777
    # Name is only meaningful for nodes and instances
1778
    ("name", ht.NoDefault, ht.TMaybeString,
1779
     "Name of object where tag(s) should be added"),
1780
    ]
1781
  OP_RESULT = ht.TNone
1782

    
1783

    
1784
class OpTagsDel(OpCode):
1785
  """Remove a list of tags from a given object."""
1786
  OP_PARAMS = [
1787
    _PTagKind,
1788
    _PTags,
1789
    # Name is only meaningful for nodes and instances
1790
    ("name", ht.NoDefault, ht.TMaybeString,
1791
     "Name of object where tag(s) should be deleted"),
1792
    ]
1793
  OP_RESULT = ht.TNone
1794

    
1795

    
1796
# Test opcodes
1797
class OpTestDelay(OpCode):
1798
  """Sleeps for a configured amount of time.
1799

1800
  This is used just for debugging and testing.
1801

1802
  Parameters:
1803
    - duration: the time to sleep
1804
    - on_master: if true, sleep on the master
1805
    - on_nodes: list of nodes in which to sleep
1806

1807
  If the on_master parameter is true, it will execute a sleep on the
1808
  master (before any node sleep).
1809

1810
  If the on_nodes list is not empty, it will sleep on those nodes
1811
  (after the sleep on the master, if that is enabled).
1812

1813
  As an additional feature, the case of duration < 0 will be reported
1814
  as an execution error, so this opcode can be used as a failure
1815
  generator. The case of duration == 0 will not be treated specially.
1816

1817
  """
1818
  OP_DSC_FIELD = "duration"
1819
  OP_PARAMS = [
1820
    ("duration", ht.NoDefault, ht.TNumber, None),
1821
    ("on_master", True, ht.TBool, None),
1822
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1823
    ("repeat", 0, ht.TPositiveInt, None),
1824
    ]
1825

    
1826

    
1827
class OpTestAllocator(OpCode):
1828
  """Allocator framework testing.
1829

1830
  This opcode has two modes:
1831
    - gather and return allocator input for a given mode (allocate new
1832
      or replace secondary) and a given instance definition (direction
1833
      'in')
1834
    - run a selected allocator for a given operation (as above) and
1835
      return the allocator output (direction 'out')
1836

1837
  """
1838
  OP_DSC_FIELD = "allocator"
1839
  OP_PARAMS = [
1840
    ("direction", ht.NoDefault,
1841
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1842
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1843
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1844
    ("nics", ht.NoDefault,
1845
     ht.TMaybeListOf(ht.TDictOf(ht.TElemOf([constants.INIC_MAC,
1846
                                            constants.INIC_IP,
1847
                                            "bridge"]),
1848
                                ht.TOr(ht.TNone, ht.TNonEmptyString))),
1849
     None),
1850
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1851
    ("hypervisor", None, ht.TMaybeString, None),
1852
    ("allocator", None, ht.TMaybeString, None),
1853
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1854
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1855
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1856
    ("os", None, ht.TMaybeString, None),
1857
    ("disk_template", None, ht.TMaybeString, None),
1858
    ("instances", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1859
    ("evac_mode", None,
1860
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1861
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1862
    ]
1863

    
1864

    
1865
class OpTestJqueue(OpCode):
1866
  """Utility opcode to test some aspects of the job queue.
1867

1868
  """
1869
  OP_PARAMS = [
1870
    ("notify_waitlock", False, ht.TBool, None),
1871
    ("notify_exec", False, ht.TBool, None),
1872
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1873
    ("fail", False, ht.TBool, None),
1874
    ]
1875

    
1876

    
1877
class OpTestDummy(OpCode):
1878
  """Utility opcode used by unittests.
1879

1880
  """
1881
  OP_PARAMS = [
1882
    ("result", ht.NoDefault, ht.NoType, None),
1883
    ("messages", ht.NoDefault, ht.NoType, None),
1884
    ("fail", ht.NoDefault, ht.NoType, None),
1885
    ("submit_jobs", None, ht.NoType, None),
1886
    ]
1887
  WITH_LU = False
1888

    
1889

    
1890
def _GetOpList():
1891
  """Returns list of all defined opcodes.
1892

1893
  Does not eliminate duplicates by C{OP_ID}.
1894

1895
  """
1896
  return [v for v in globals().values()
1897
          if (isinstance(v, type) and issubclass(v, OpCode) and
1898
              hasattr(v, "OP_ID") and v is not OpCode)]
1899

    
1900

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