Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 36c70d4d

History | View | Annotate | Download (58 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 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), 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
_TestClusterOsListItem = \
169
  ht.TAnd(ht.TIsLength(2), ht.TItems([
170
    ht.TElemOf(constants.DDMS_VALUES),
171
    ht.TNonEmptyString,
172
    ]))
173

    
174
_TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
175

    
176
# TODO: Generate check from constants.INIC_PARAMS_TYPES
177
#: Utility function for testing NIC definitions
178
_TestNicDef = \
179
  ht.Comment("NIC parameters")(ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
180
                                          ht.TOr(ht.TNone, ht.TNonEmptyString)))
181

    
182
_TSetParamsResultItemItems = [
183
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
184
  ht.Comment("new value")(ht.TAny),
185
  ]
186

    
187
_TSetParamsResult = \
188
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
189
                     ht.TItems(_TSetParamsResultItemItems)))
190

    
191
# TODO: Generate check from constants.IDISK_PARAMS_TYPES (however, not all users
192
# of this check support all parameters)
193
_TDiskParams = \
194
  ht.Comment("Disk parameters")(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
195
                                           ht.TOr(ht.TNonEmptyString, ht.TInt)))
196

    
197
_TQueryRow = \
198
  ht.TListOf(ht.TAnd(ht.TIsLength(2),
199
                     ht.TItems([ht.TElemOf(constants.RS_ALL),
200
                                ht.TAny])))
201

    
202
_TQueryResult = ht.TListOf(_TQueryRow)
203

    
204
_TOldQueryRow = ht.TListOf(ht.TAny)
205

    
206
_TOldQueryResult = ht.TListOf(_TOldQueryRow)
207

    
208

    
209
_SUMMARY_PREFIX = {
210
  "CLUSTER_": "C_",
211
  "GROUP_": "G_",
212
  "NODE_": "N_",
213
  "INSTANCE_": "I_",
214
  }
215

    
216
#: Attribute name for dependencies
217
DEPEND_ATTR = "depends"
218

    
219
#: Attribute name for comment
220
COMMENT_ATTR = "comment"
221

    
222

    
223
def _NameToId(name):
224
  """Convert an opcode class name to an OP_ID.
225

226
  @type name: string
227
  @param name: the class name, as OpXxxYyy
228
  @rtype: string
229
  @return: the name in the OP_XXXX_YYYY format
230

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

    
243

    
244
def _GenerateObjectTypeCheck(obj, fields_types):
245
  """Helper to generate type checks for objects.
246

247
  @param obj: The object to generate type checks
248
  @param fields_types: The fields and their types as a dict
249
  @return: A ht type check function
250

251
  """
252
  assert set(obj.GetAllSlots()) == set(fields_types.keys()), \
253
    "%s != %s" % (set(obj.GetAllSlots()), set(fields_types.keys()))
254
  return ht.TStrictDict(True, True, fields_types)
255

    
256

    
257
_TQueryFieldDef = \
258
  _GenerateObjectTypeCheck(objects.QueryFieldDefinition, {
259
    "name": ht.TNonEmptyString,
260
    "title": ht.TNonEmptyString,
261
    "kind": ht.TElemOf(constants.QFT_ALL),
262
    "doc": ht.TNonEmptyString,
263
    })
264

    
265

    
266
def RequireFileStorage():
267
  """Checks that file storage is enabled.
268

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

272
  @raise errors.OpPrereqError: when file storage is disabled
273

274
  """
275
  if not constants.ENABLE_FILE_STORAGE:
276
    raise errors.OpPrereqError("File storage disabled at configure time",
277
                               errors.ECODE_INVAL)
278

    
279

    
280
def RequireSharedFileStorage():
281
  """Checks that shared file storage is enabled.
282

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

286
  @raise errors.OpPrereqError: when shared file storage is disabled
287

288
  """
289
  if not constants.ENABLE_SHARED_FILE_STORAGE:
290
    raise errors.OpPrereqError("Shared file storage disabled at"
291
                               " configure time", errors.ECODE_INVAL)
292

    
293

    
294
@ht.WithDesc("CheckFileStorage")
295
def _CheckFileStorage(value):
296
  """Ensures file storage is enabled if used.
297

298
  """
299
  if value == constants.DT_FILE:
300
    RequireFileStorage()
301
  elif value == constants.DT_SHARED_FILE:
302
    RequireSharedFileStorage()
303
  return True
304

    
305

    
306
def _BuildDiskTemplateCheck(accept_none):
307
  """Builds check for disk template.
308

309
  @type accept_none: bool
310
  @param accept_none: whether to accept None as a correct value
311
  @rtype: callable
312

313
  """
314
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
315

    
316
  if accept_none:
317
    template_check = ht.TOr(template_check, ht.TNone)
318

    
319
  return ht.TAnd(template_check, _CheckFileStorage)
320

    
321

    
322
def _CheckStorageType(storage_type):
323
  """Ensure a given storage type is valid.
324

325
  """
326
  if storage_type not in constants.VALID_STORAGE_TYPES:
327
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
328
                               errors.ECODE_INVAL)
329
  if storage_type == constants.ST_FILE:
330
    RequireFileStorage()
331
  return True
332

    
333

    
334
#: Storage type parameter
335
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
336
                 "Storage type")
337

    
338

    
339
class _AutoOpParamSlots(type):
340
  """Meta class for opcode definitions.
341

342
  """
343
  def __new__(mcs, name, bases, attrs):
344
    """Called when a class should be created.
345

346
    @param mcs: The meta class
347
    @param name: Name of created class
348
    @param bases: Base classes
349
    @type attrs: dict
350
    @param attrs: Class attributes
351

352
    """
353
    assert "__slots__" not in attrs, \
354
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
355
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
356

    
357
    attrs["OP_ID"] = _NameToId(name)
358

    
359
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
360
    params = attrs.setdefault("OP_PARAMS", [])
361

    
362
    # Use parameter names as slots
363
    slots = [pname for (pname, _, _, _) in params]
364

    
365
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
366
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
367

    
368
    attrs["__slots__"] = slots
369

    
370
    return type.__new__(mcs, name, bases, attrs)
371

    
372

    
373
class BaseOpCode(object):
374
  """A simple serializable object.
375

376
  This object serves as a parent class for OpCode without any custom
377
  field handling.
378

379
  """
380
  # pylint: disable=E1101
381
  # as OP_ID is dynamically defined
382
  __metaclass__ = _AutoOpParamSlots
383

    
384
  def __init__(self, **kwargs):
385
    """Constructor for BaseOpCode.
386

387
    The constructor takes only keyword arguments and will set
388
    attributes on this object based on the passed arguments. As such,
389
    it means that you should not pass arguments which are not in the
390
    __slots__ attribute for this class.
391

392
    """
393
    slots = self._all_slots()
394
    for key in kwargs:
395
      if key not in slots:
396
        raise TypeError("Object %s doesn't support the parameter '%s'" %
397
                        (self.__class__.__name__, key))
398
      setattr(self, key, kwargs[key])
399

    
400
  def __getstate__(self):
401
    """Generic serializer.
402

403
    This method just returns the contents of the instance as a
404
    dictionary.
405

406
    @rtype:  C{dict}
407
    @return: the instance attributes and their values
408

409
    """
410
    state = {}
411
    for name in self._all_slots():
412
      if hasattr(self, name):
413
        state[name] = getattr(self, name)
414
    return state
415

    
416
  def __setstate__(self, state):
417
    """Generic unserializer.
418

419
    This method just restores from the serialized state the attributes
420
    of the current instance.
421

422
    @param state: the serialized opcode data
423
    @type state:  C{dict}
424

425
    """
426
    if not isinstance(state, dict):
427
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
428
                       type(state))
429

    
430
    for name in self._all_slots():
431
      if name not in state and hasattr(self, name):
432
        delattr(self, name)
433

    
434
    for name in state:
435
      setattr(self, name, state[name])
436

    
437
  @classmethod
438
  def _all_slots(cls):
439
    """Compute the list of all declared slots for a class.
440

441
    """
442
    slots = []
443
    for parent in cls.__mro__:
444
      slots.extend(getattr(parent, "__slots__", []))
445
    return slots
446

    
447
  @classmethod
448
  def GetAllParams(cls):
449
    """Compute list of all parameters for an opcode.
450

451
    """
452
    slots = []
453
    for parent in cls.__mro__:
454
      slots.extend(getattr(parent, "OP_PARAMS", []))
455
    return slots
456

    
457
  def Validate(self, set_defaults):
458
    """Validate opcode parameters, optionally setting default values.
459

460
    @type set_defaults: bool
461
    @param set_defaults: Whether to set default values
462
    @raise errors.OpPrereqError: When a parameter value doesn't match
463
                                 requirements
464

465
    """
466
    for (attr_name, default, test, _) in self.GetAllParams():
467
      assert test == ht.NoType or callable(test)
468

    
469
      if not hasattr(self, attr_name):
470
        if default == ht.NoDefault:
471
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
472
                                     (self.OP_ID, attr_name),
473
                                     errors.ECODE_INVAL)
474
        elif set_defaults:
475
          if callable(default):
476
            dval = default()
477
          else:
478
            dval = default
479
          setattr(self, attr_name, dval)
480

    
481
      if test == ht.NoType:
482
        # no tests here
483
        continue
484

    
485
      if set_defaults or hasattr(self, attr_name):
486
        attr_val = getattr(self, attr_name)
487
        if not test(attr_val):
488
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
489
                        self.OP_ID, attr_name, type(attr_val), attr_val)
490
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
491
                                     (self.OP_ID, attr_name),
492
                                     errors.ECODE_INVAL)
493

    
494

    
495
def _BuildJobDepCheck(relative):
496
  """Builds check for job dependencies (L{DEPEND_ATTR}).
497

498
  @type relative: bool
499
  @param relative: Whether to accept relative job IDs (negative)
500
  @rtype: callable
501

502
  """
503
  if relative:
504
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
505
  else:
506
    job_id = ht.TJobId
507

    
508
  job_dep = \
509
    ht.TAnd(ht.TIsLength(2),
510
            ht.TItems([job_id,
511
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
512

    
513
  return ht.TMaybeListOf(job_dep)
514

    
515

    
516
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
517

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

    
527
#: Result containing only list of submitted jobs
528
TJobIdListOnly = ht.TStrictDict(True, True, {
529
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
530
  })
531

    
532

    
533
class OpCode(BaseOpCode):
534
  """Abstract OpCode.
535

536
  This is the root of the actual OpCode hierarchy. All clases derived
537
  from this class should override OP_ID.
538

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

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

    
571
  def __getstate__(self):
572
    """Specialized getstate for opcodes.
573

574
    This method adds to the state dictionary the OP_ID of the class,
575
    so that on unload we can identify the correct class for
576
    instantiating the opcode.
577

578
    @rtype:   C{dict}
579
    @return:  the state as a dictionary
580

581
    """
582
    data = BaseOpCode.__getstate__(self)
583
    data["OP_ID"] = self.OP_ID
584
    return data
585

    
586
  @classmethod
587
  def LoadOpCode(cls, data):
588
    """Generic load opcode method.
589

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

594
    @type data:  C{dict}
595
    @param data: the serialized opcode
596

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

    
615
  def Summary(self):
616
    """Generates a summary description of this opcode.
617

618
    The summary is the value of the OP_ID attribute (without the "OP_"
619
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
620
    defined; this field should allow to easily identify the operation
621
    (for an instance creation job, e.g., it would be the instance
622
    name).
623

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

    
636
  def TinySummary(self):
637
    """Generates a compact summary description of the opcode.
638

639
    """
640
    assert self.OP_ID.startswith("OP_")
641

    
642
    text = self.OP_ID[3:]
643

    
644
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
645
      if text.startswith(prefix):
646
        return supplement + text[len(prefix):]
647

    
648
    return text
649

    
650

    
651
# cluster opcodes
652

    
653
class OpClusterPostInit(OpCode):
654
  """Post cluster initialization.
655

656
  This opcode does not touch the cluster at all. Its purpose is to run hooks
657
  after the cluster has been initialized.
658

659
  """
660
  OP_RESULT = ht.TBool
661

    
662

    
663
class OpClusterDestroy(OpCode):
664
  """Destroy the cluster.
665

666
  This opcode has no other parameters. All the state is irreversibly
667
  lost after the execution of this opcode.
668

669
  """
670
  OP_RESULT = ht.TNonEmptyString
671

    
672

    
673
class OpClusterQuery(OpCode):
674
  """Query cluster information."""
675
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TAny)
676

    
677

    
678
class OpClusterVerify(OpCode):
679
  """Submits all jobs necessary to verify the cluster.
680

681
  """
682
  OP_PARAMS = [
683
    _PDebugSimulateErrors,
684
    _PErrorCodes,
685
    _PSkipChecks,
686
    _PIgnoreErrors,
687
    _PVerbose,
688
    ("group_name", None, ht.TMaybeString, "Group to verify")
689
    ]
690
  OP_RESULT = TJobIdListOnly
691

    
692

    
693
class OpClusterVerifyConfig(OpCode):
694
  """Verify the cluster config.
695

696
  """
697
  OP_PARAMS = [
698
    _PDebugSimulateErrors,
699
    _PErrorCodes,
700
    _PIgnoreErrors,
701
    _PVerbose,
702
    ]
703
  OP_RESULT = ht.TBool
704

    
705

    
706
class OpClusterVerifyGroup(OpCode):
707
  """Run verify on a node group from the cluster.
708

709
  @type skip_checks: C{list}
710
  @ivar skip_checks: steps to be skipped from the verify process; this
711
                     needs to be a subset of
712
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
713
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
714

715
  """
716
  OP_DSC_FIELD = "group_name"
717
  OP_PARAMS = [
718
    _PGroupName,
719
    _PDebugSimulateErrors,
720
    _PErrorCodes,
721
    _PSkipChecks,
722
    _PIgnoreErrors,
723
    _PVerbose,
724
    ]
725
  OP_RESULT = ht.TBool
726

    
727

    
728
class OpClusterVerifyDisks(OpCode):
729
  """Verify the cluster disks.
730

731
  """
732
  OP_RESULT = TJobIdListOnly
733

    
734

    
735
class OpGroupVerifyDisks(OpCode):
736
  """Verifies the status of all disks in a node group.
737

738
  Result: a tuple of three elements:
739
    - dict of node names with issues (values: error msg)
740
    - list of instances with degraded disks (that should be activated)
741
    - dict of instances with missing logical volumes (values: (node, vol)
742
      pairs with details about the missing volumes)
743

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

749
  Note that only instances that are drbd-based are taken into
750
  consideration. This might need to be revisited in the future.
751

752
  """
753
  OP_DSC_FIELD = "group_name"
754
  OP_PARAMS = [
755
    _PGroupName,
756
    ]
757
  OP_RESULT = \
758
    ht.TAnd(ht.TIsLength(3),
759
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
760
                       ht.TListOf(ht.TString),
761
                       ht.TDictOf(ht.TString,
762
                                  ht.TListOf(ht.TListOf(ht.TString)))]))
763

    
764

    
765
class OpClusterRepairDiskSizes(OpCode):
766
  """Verify the disk sizes of the instances and fixes configuration
767
  mimatches.
768

769
  Parameters: optional instances list, in case we want to restrict the
770
  checks to only a subset of the instances.
771

772
  Result: a list of tuples, (instance, disk, new-size) for changed
773
  configurations.
774

775
  In normal operation, the list should be empty.
776

777
  @type instances: list
778
  @ivar instances: the list of instances to check, or empty for all instances
779

780
  """
781
  OP_PARAMS = [
782
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
783
    ]
784
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
785
                                 ht.TItems([ht.TNonEmptyString,
786
                                            ht.TPositiveInt,
787
                                            ht.TPositiveInt])))
788

    
789

    
790
class OpClusterConfigQuery(OpCode):
791
  """Query cluster configuration values."""
792
  OP_PARAMS = [
793
    _POutputFields
794
    ]
795
  OP_RESULT = ht.TListOf(ht.TAny)
796

    
797

    
798
class OpClusterRename(OpCode):
799
  """Rename the cluster.
800

801
  @type name: C{str}
802
  @ivar name: The new name of the cluster. The name and/or the master IP
803
              address will be changed to match the new name and its IP
804
              address.
805

806
  """
807
  OP_DSC_FIELD = "name"
808
  OP_PARAMS = [
809
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
810
    ]
811
  OP_RESULT = ht.TNonEmptyString
812

    
813

    
814
class OpClusterSetParams(OpCode):
815
  """Change the parameters of the cluster.
816

817
  @type vg_name: C{str} or C{None}
818
  @ivar vg_name: The new volume group name or None to disable LVM usage.
819

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

    
882

    
883
class OpClusterRedistConf(OpCode):
884
  """Force a full push of the cluster configuration.
885

886
  """
887
  OP_RESULT = ht.TNone
888

    
889

    
890
class OpClusterActivateMasterIp(OpCode):
891
  """Activate the master IP on the master node.
892

893
  """
894
  OP_RESULT = ht.TNone
895

    
896

    
897
class OpClusterDeactivateMasterIp(OpCode):
898
  """Deactivate the master IP on the master node.
899

900
  """
901
  OP_RESULT = ht.TNone
902

    
903

    
904
class OpQuery(OpCode):
905
  """Query for resources/items.
906

907
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
908
  @ivar fields: List of fields to retrieve
909
  @ivar qfilter: Query filter
910

911
  """
912
  OP_DSC_FIELD = "what"
913
  OP_PARAMS = [
914
    _PQueryWhat,
915
    _PUseLocking,
916
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
917
     "Requested fields"),
918
    ("qfilter", None, ht.TOr(ht.TNone, ht.TList),
919
     "Query filter"),
920
    ]
921
  OP_RESULT = \
922
    _GenerateObjectTypeCheck(objects.QueryResponse, {
923
      "fields": ht.TListOf(_TQueryFieldDef),
924
      "data": _TQueryResult,
925
      })
926

    
927

    
928
class OpQueryFields(OpCode):
929
  """Query for available resource/item fields.
930

931
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
932
  @ivar fields: List of fields to retrieve
933

934
  """
935
  OP_DSC_FIELD = "what"
936
  OP_PARAMS = [
937
    _PQueryWhat,
938
    ("fields", None, ht.TMaybeListOf(ht.TNonEmptyString),
939
     "Requested fields; if not given, all are returned"),
940
    ]
941
  OP_RESULT = \
942
    _GenerateObjectTypeCheck(objects.QueryFieldsResponse, {
943
      "fields": ht.TListOf(_TQueryFieldDef),
944
      })
945

    
946

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

    
964

    
965
# node opcodes
966

    
967
class OpNodeRemove(OpCode):
968
  """Remove a node.
969

970
  @type node_name: C{str}
971
  @ivar node_name: The name of the node to remove. If the node still has
972
                   instances on it, the operation will fail.
973

974
  """
975
  OP_DSC_FIELD = "node_name"
976
  OP_PARAMS = [
977
    _PNodeName,
978
    ]
979
  OP_RESULT = ht.TNone
980

    
981

    
982
class OpNodeAdd(OpCode):
983
  """Add a node to the cluster.
984

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

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

    
1027

    
1028
class OpNodeQuery(OpCode):
1029
  """Compute the list of nodes."""
1030
  OP_PARAMS = [
1031
    _POutputFields,
1032
    _PUseLocking,
1033
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1034
     "Empty list to query all nodes, node names otherwise"),
1035
    ]
1036
  OP_RESULT = _TOldQueryResult
1037

    
1038

    
1039
class OpNodeQueryvols(OpCode):
1040
  """Get list of volumes on node."""
1041
  OP_PARAMS = [
1042
    _POutputFields,
1043
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1044
     "Empty list to query all nodes, node names otherwise"),
1045
    ]
1046
  OP_RESULT = ht.TListOf(ht.TAny)
1047

    
1048

    
1049
class OpNodeQueryStorage(OpCode):
1050
  """Get information on storage for node(s)."""
1051
  OP_PARAMS = [
1052
    _POutputFields,
1053
    _PStorageType,
1054
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
1055
    ("name", None, ht.TMaybeString, "Storage name"),
1056
    ]
1057
  OP_RESULT = _TOldQueryResult
1058

    
1059

    
1060
class OpNodeModifyStorage(OpCode):
1061
  """Modifies the properies of a storage unit"""
1062
  OP_PARAMS = [
1063
    _PNodeName,
1064
    _PStorageType,
1065
    _PStorageName,
1066
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1067
    ]
1068
  OP_RESULT = ht.TNone
1069

    
1070

    
1071
class OpRepairNodeStorage(OpCode):
1072
  """Repairs the volume group on a node."""
1073
  OP_DSC_FIELD = "node_name"
1074
  OP_PARAMS = [
1075
    _PNodeName,
1076
    _PStorageType,
1077
    _PStorageName,
1078
    _PIgnoreConsistency,
1079
    ]
1080
  OP_RESULT = ht.TNone
1081

    
1082

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

    
1111

    
1112
class OpNodePowercycle(OpCode):
1113
  """Tries to powercycle a node."""
1114
  OP_DSC_FIELD = "node_name"
1115
  OP_PARAMS = [
1116
    _PNodeName,
1117
    _PForce,
1118
    ]
1119
  OP_RESULT = ht.TMaybeString
1120

    
1121

    
1122
class OpNodeMigrate(OpCode):
1123
  """Migrate all instances from a node."""
1124
  OP_DSC_FIELD = "node_name"
1125
  OP_PARAMS = [
1126
    _PNodeName,
1127
    _PMigrationMode,
1128
    _PMigrationLive,
1129
    _PMigrationTargetNode,
1130
    _PAllowRuntimeChgs,
1131
    _PIgnoreIpolicy,
1132
    ("iallocator", None, ht.TMaybeString,
1133
     "Iallocator for deciding the target node for shared-storage instances"),
1134
    ]
1135
  OP_RESULT = TJobIdListOnly
1136

    
1137

    
1138
class OpNodeEvacuate(OpCode):
1139
  """Evacuate instances off a number of nodes."""
1140
  OP_DSC_FIELD = "node_name"
1141
  OP_PARAMS = [
1142
    _PEarlyRelease,
1143
    _PNodeName,
1144
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1145
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1146
    ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1147
     "Node evacuation mode"),
1148
    ]
1149
  OP_RESULT = TJobIdListOnly
1150

    
1151

    
1152
# instance opcodes
1153

    
1154
class OpInstanceCreate(OpCode):
1155
  """Create an instance.
1156

1157
  @ivar instance_name: Instance name
1158
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1159
  @ivar source_handshake: Signed handshake from source (remote import only)
1160
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1161
  @ivar source_instance_name: Previous name of instance (remote import only)
1162
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1163
    (remote import only)
1164

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

    
1226

    
1227
class OpInstanceReinstall(OpCode):
1228
  """Reinstall an instance's OS."""
1229
  OP_DSC_FIELD = "instance_name"
1230
  OP_PARAMS = [
1231
    _PInstanceName,
1232
    _PForceVariant,
1233
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1234
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1235
    ]
1236
  OP_RESULT = ht.TNone
1237

    
1238

    
1239
class OpInstanceRemove(OpCode):
1240
  """Remove an instance."""
1241
  OP_DSC_FIELD = "instance_name"
1242
  OP_PARAMS = [
1243
    _PInstanceName,
1244
    _PShutdownTimeout,
1245
    ("ignore_failures", False, ht.TBool,
1246
     "Whether to ignore failures during removal"),
1247
    ]
1248
  OP_RESULT = ht.TNone
1249

    
1250

    
1251
class OpInstanceRename(OpCode):
1252
  """Rename an instance."""
1253
  OP_PARAMS = [
1254
    _PInstanceName,
1255
    _PNameCheck,
1256
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1257
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1258
    ]
1259
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1260

    
1261

    
1262
class OpInstanceStartup(OpCode):
1263
  """Startup an instance."""
1264
  OP_DSC_FIELD = "instance_name"
1265
  OP_PARAMS = [
1266
    _PInstanceName,
1267
    _PForce,
1268
    _PIgnoreOfflineNodes,
1269
    ("hvparams", ht.EmptyDict, ht.TDict,
1270
     "Temporary hypervisor parameters, hypervisor-dependent"),
1271
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1272
    _PNoRemember,
1273
    _PStartupPaused,
1274
    ]
1275
  OP_RESULT = ht.TNone
1276

    
1277

    
1278
class OpInstanceShutdown(OpCode):
1279
  """Shutdown an instance."""
1280
  OP_DSC_FIELD = "instance_name"
1281
  OP_PARAMS = [
1282
    _PInstanceName,
1283
    _PIgnoreOfflineNodes,
1284
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1285
     "How long to wait for instance to shut down"),
1286
    _PNoRemember,
1287
    ]
1288
  OP_RESULT = ht.TNone
1289

    
1290

    
1291
class OpInstanceReboot(OpCode):
1292
  """Reboot an instance."""
1293
  OP_DSC_FIELD = "instance_name"
1294
  OP_PARAMS = [
1295
    _PInstanceName,
1296
    _PShutdownTimeout,
1297
    ("ignore_secondaries", False, ht.TBool,
1298
     "Whether to start the instance even if secondary disks are failing"),
1299
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1300
     "How to reboot instance"),
1301
    ]
1302
  OP_RESULT = ht.TNone
1303

    
1304

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

    
1322

    
1323
class OpInstanceFailover(OpCode):
1324
  """Failover an instance."""
1325
  OP_DSC_FIELD = "instance_name"
1326
  OP_PARAMS = [
1327
    _PInstanceName,
1328
    _PShutdownTimeout,
1329
    _PIgnoreConsistency,
1330
    _PMigrationTargetNode,
1331
    _PIgnoreIpolicy,
1332
    ("iallocator", None, ht.TMaybeString,
1333
     "Iallocator for deciding the target node for shared-storage instances"),
1334
    ]
1335
  OP_RESULT = ht.TNone
1336

    
1337

    
1338
class OpInstanceMigrate(OpCode):
1339
  """Migrate an instance.
1340

1341
  This migrates (without shutting down an instance) to its secondary
1342
  node.
1343

1344
  @ivar instance_name: the name of the instance
1345
  @ivar mode: the migration mode (live, non-live or None for auto)
1346

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

    
1365

    
1366
class OpInstanceMove(OpCode):
1367
  """Move an instance.
1368

1369
  This move (with shutting down an instance and data copying) to an
1370
  arbitrary node.
1371

1372
  @ivar instance_name: the name of the instance
1373
  @ivar target_node: the destination node
1374

1375
  """
1376
  OP_DSC_FIELD = "instance_name"
1377
  OP_PARAMS = [
1378
    _PInstanceName,
1379
    _PShutdownTimeout,
1380
    _PIgnoreIpolicy,
1381
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1382
    _PIgnoreConsistency,
1383
    ]
1384
  OP_RESULT = ht.TNone
1385

    
1386

    
1387
class OpInstanceConsole(OpCode):
1388
  """Connect to an instance's console."""
1389
  OP_DSC_FIELD = "instance_name"
1390
  OP_PARAMS = [
1391
    _PInstanceName
1392
    ]
1393
  OP_RESULT = ht.TDict
1394

    
1395

    
1396
class OpInstanceActivateDisks(OpCode):
1397
  """Activate an instance's disks."""
1398
  OP_DSC_FIELD = "instance_name"
1399
  OP_PARAMS = [
1400
    _PInstanceName,
1401
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1402
    ]
1403
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
1404
                                 ht.TItems([ht.TNonEmptyString,
1405
                                            ht.TNonEmptyString,
1406
                                            ht.TNonEmptyString])))
1407

    
1408

    
1409
class OpInstanceDeactivateDisks(OpCode):
1410
  """Deactivate an instance's disks."""
1411
  OP_DSC_FIELD = "instance_name"
1412
  OP_PARAMS = [
1413
    _PInstanceName,
1414
    _PForce,
1415
    ]
1416
  OP_RESULT = ht.TNone
1417

    
1418

    
1419
class OpInstanceRecreateDisks(OpCode):
1420
  """Recreate an instance's disks."""
1421
  _TDiskChanges = \
1422
    ht.TAnd(ht.TIsLength(2),
1423
            ht.TItems([ht.Comment("Disk index")(ht.TPositiveInt),
1424
                       ht.Comment("Parameters")(_TDiskParams)]))
1425

    
1426
  OP_DSC_FIELD = "instance_name"
1427
  OP_PARAMS = [
1428
    _PInstanceName,
1429
    ("disks", ht.EmptyList,
1430
     ht.TOr(ht.TListOf(ht.TPositiveInt), ht.TListOf(_TDiskChanges)),
1431
     "List of disk indexes (deprecated) or a list of tuples containing a disk"
1432
     " index and a possibly empty dictionary with disk parameter changes"),
1433
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1434
     "New instance nodes, if relocation is desired"),
1435
    ]
1436
  OP_RESULT = ht.TNone
1437

    
1438

    
1439
class OpInstanceQuery(OpCode):
1440
  """Compute the list of instances."""
1441
  OP_PARAMS = [
1442
    _POutputFields,
1443
    _PUseLocking,
1444
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1445
     "Empty list to query all instances, instance names otherwise"),
1446
    ]
1447
  OP_RESULT = _TOldQueryResult
1448

    
1449

    
1450
class OpInstanceQueryData(OpCode):
1451
  """Compute the run-time status of instances."""
1452
  OP_PARAMS = [
1453
    _PUseLocking,
1454
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1455
     "Instance names"),
1456
    ("static", False, ht.TBool,
1457
     "Whether to only return configuration data without querying"
1458
     " nodes"),
1459
    ]
1460
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TDict)
1461

    
1462

    
1463
def _TestInstSetParamsModList(fn):
1464
  """Generates a check for modification lists.
1465

1466
  """
1467
  # Old format
1468
  # TODO: Remove in version 2.8 including support in LUInstanceSetParams
1469
  old_mod_item_fn = \
1470
    ht.TAnd(ht.TIsLength(2), ht.TItems([
1471
      ht.TOr(ht.TElemOf(constants.DDMS_VALUES), ht.TPositiveInt),
1472
      fn,
1473
      ]))
1474

    
1475
  # New format, supporting adding/removing disks/NICs at arbitrary indices
1476
  mod_item_fn = \
1477
    ht.TAnd(ht.TIsLength(3), ht.TItems([
1478
      ht.TElemOf(constants.DDMS_VALUES_WITH_MODIFY),
1479
      ht.Comment("Disk index, can be negative, e.g. -1 for last disk")(ht.TInt),
1480
      fn,
1481
      ]))
1482

    
1483
  return ht.TOr(ht.Comment("Recommended")(ht.TListOf(mod_item_fn)),
1484
                ht.Comment("Deprecated")(ht.TListOf(old_mod_item_fn)))
1485

    
1486

    
1487
class OpInstanceSetParams(OpCode):
1488
  """Change the parameters of an instance.
1489

1490
  """
1491
  TestNicModifications = _TestInstSetParamsModList(_TestNicDef)
1492
  TestDiskModifications = _TestInstSetParamsModList(_TDiskParams)
1493

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

    
1529

    
1530
class OpInstanceGrowDisk(OpCode):
1531
  """Grow a disk of an instance."""
1532
  OP_DSC_FIELD = "instance_name"
1533
  OP_PARAMS = [
1534
    _PInstanceName,
1535
    _PWaitForSync,
1536
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1537
    ("amount", ht.NoDefault, ht.TInt,
1538
     "Amount of disk space to add (megabytes)"),
1539
    ]
1540
  OP_RESULT = ht.TNone
1541

    
1542

    
1543
class OpInstanceChangeGroup(OpCode):
1544
  """Moves an instance to another node group."""
1545
  OP_DSC_FIELD = "instance_name"
1546
  OP_PARAMS = [
1547
    _PInstanceName,
1548
    _PEarlyRelease,
1549
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1550
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1551
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1552
    ]
1553
  OP_RESULT = TJobIdListOnly
1554

    
1555

    
1556
# Node group opcodes
1557

    
1558
class OpGroupAdd(OpCode):
1559
  """Add a node group to the cluster."""
1560
  OP_DSC_FIELD = "group_name"
1561
  OP_PARAMS = [
1562
    _PGroupName,
1563
    _PNodeGroupAllocPolicy,
1564
    _PGroupNodeParams,
1565
    _PDiskParams,
1566
    _PHvState,
1567
    _PDiskState,
1568
    ("ipolicy", None, ht.TMaybeDict,
1569
     "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1570
    ]
1571
  OP_RESULT = ht.TNone
1572

    
1573

    
1574
class OpGroupAssignNodes(OpCode):
1575
  """Assign nodes to a node group."""
1576
  OP_DSC_FIELD = "group_name"
1577
  OP_PARAMS = [
1578
    _PGroupName,
1579
    _PForce,
1580
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1581
     "List of nodes to assign"),
1582
    ]
1583
  OP_RESULT = ht.TNone
1584

    
1585

    
1586
class OpGroupQuery(OpCode):
1587
  """Compute the list of node groups."""
1588
  OP_PARAMS = [
1589
    _POutputFields,
1590
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1591
     "Empty list to query all groups, group names otherwise"),
1592
    ]
1593
  OP_RESULT = _TOldQueryResult
1594

    
1595

    
1596
class OpGroupSetParams(OpCode):
1597
  """Change the parameters of a node group."""
1598
  OP_DSC_FIELD = "group_name"
1599
  OP_PARAMS = [
1600
    _PGroupName,
1601
    _PNodeGroupAllocPolicy,
1602
    _PGroupNodeParams,
1603
    _PDiskParams,
1604
    _PHvState,
1605
    _PDiskState,
1606
    ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1607
    ]
1608
  OP_RESULT = _TSetParamsResult
1609

    
1610

    
1611
class OpGroupRemove(OpCode):
1612
  """Remove a node group from the cluster."""
1613
  OP_DSC_FIELD = "group_name"
1614
  OP_PARAMS = [
1615
    _PGroupName,
1616
    ]
1617
  OP_RESULT = ht.TNone
1618

    
1619

    
1620
class OpGroupRename(OpCode):
1621
  """Rename a node group in the cluster."""
1622
  OP_PARAMS = [
1623
    _PGroupName,
1624
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1625
    ]
1626
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1627

    
1628

    
1629
class OpGroupEvacuate(OpCode):
1630
  """Evacuate a node group in the cluster."""
1631
  OP_DSC_FIELD = "group_name"
1632
  OP_PARAMS = [
1633
    _PGroupName,
1634
    _PEarlyRelease,
1635
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1636
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1637
     "Destination group names or UUIDs"),
1638
    ]
1639
  OP_RESULT = TJobIdListOnly
1640

    
1641

    
1642
# OS opcodes
1643
class OpOsDiagnose(OpCode):
1644
  """Compute the list of guest operating systems."""
1645
  OP_PARAMS = [
1646
    _POutputFields,
1647
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1648
     "Which operating systems to diagnose"),
1649
    ]
1650
  OP_RESULT = _TOldQueryResult
1651

    
1652

    
1653
# Exports opcodes
1654
class OpBackupQuery(OpCode):
1655
  """Compute the list of exported images."""
1656
  OP_PARAMS = [
1657
    _PUseLocking,
1658
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1659
     "Empty list to query all nodes, node names otherwise"),
1660
    ]
1661
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString,
1662
                         ht.TOr(ht.Comment("False on error")(ht.TBool),
1663
                                ht.TListOf(ht.TNonEmptyString)))
1664

    
1665

    
1666
class OpBackupPrepare(OpCode):
1667
  """Prepares an instance export.
1668

1669
  @ivar instance_name: Instance name
1670
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1671

1672
  """
1673
  OP_DSC_FIELD = "instance_name"
1674
  OP_PARAMS = [
1675
    _PInstanceName,
1676
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1677
     "Export mode"),
1678
    ]
1679
  OP_RESULT = ht.TOr(ht.TNone, ht.TDict)
1680

    
1681

    
1682
class OpBackupExport(OpCode):
1683
  """Export an instance.
1684

1685
  For local exports, the export destination is the node name. For remote
1686
  exports, the export destination is a list of tuples, each consisting of
1687
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1688
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1689
  destination X509 CA must be a signed certificate.
1690

1691
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1692
  @ivar target_node: Export destination
1693
  @ivar x509_key_name: X509 key to use (remote export only)
1694
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1695
                             only)
1696

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

    
1724

    
1725
class OpBackupRemove(OpCode):
1726
  """Remove an instance's export."""
1727
  OP_DSC_FIELD = "instance_name"
1728
  OP_PARAMS = [
1729
    _PInstanceName,
1730
    ]
1731
  OP_RESULT = ht.TNone
1732

    
1733

    
1734
# Tags opcodes
1735
class OpTagsGet(OpCode):
1736
  """Returns the tags of the given object."""
1737
  OP_DSC_FIELD = "name"
1738
  OP_PARAMS = [
1739
    _PTagKind,
1740
    # Name is only meaningful for nodes and instances
1741
    ("name", ht.NoDefault, ht.TMaybeString, None),
1742
    ]
1743
  OP_RESULT = ht.TListOf(ht.TNonEmptyString)
1744

    
1745

    
1746
class OpTagsSearch(OpCode):
1747
  """Searches the tags in the cluster for a given pattern."""
1748
  OP_DSC_FIELD = "pattern"
1749
  OP_PARAMS = [
1750
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1751
    ]
1752
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
1753
    ht.TNonEmptyString,
1754
    ht.TNonEmptyString,
1755
    ])))
1756

    
1757

    
1758
class OpTagsSet(OpCode):
1759
  """Add a list of tags on a given object."""
1760
  OP_PARAMS = [
1761
    _PTagKind,
1762
    _PTags,
1763
    # Name is only meaningful for nodes and instances
1764
    ("name", ht.NoDefault, ht.TMaybeString, None),
1765
    ]
1766
  OP_RESULT = ht.TNone
1767

    
1768

    
1769
class OpTagsDel(OpCode):
1770
  """Remove a list of tags from a given object."""
1771
  OP_PARAMS = [
1772
    _PTagKind,
1773
    _PTags,
1774
    # Name is only meaningful for nodes and instances
1775
    ("name", ht.NoDefault, ht.TMaybeString, None),
1776
    ]
1777
  OP_RESULT = ht.TNone
1778

    
1779

    
1780
# Test opcodes
1781
class OpTestDelay(OpCode):
1782
  """Sleeps for a configured amount of time.
1783

1784
  This is used just for debugging and testing.
1785

1786
  Parameters:
1787
    - duration: the time to sleep
1788
    - on_master: if true, sleep on the master
1789
    - on_nodes: list of nodes in which to sleep
1790

1791
  If the on_master parameter is true, it will execute a sleep on the
1792
  master (before any node sleep).
1793

1794
  If the on_nodes list is not empty, it will sleep on those nodes
1795
  (after the sleep on the master, if that is enabled).
1796

1797
  As an additional feature, the case of duration < 0 will be reported
1798
  as an execution error, so this opcode can be used as a failure
1799
  generator. The case of duration == 0 will not be treated specially.
1800

1801
  """
1802
  OP_DSC_FIELD = "duration"
1803
  OP_PARAMS = [
1804
    ("duration", ht.NoDefault, ht.TNumber, None),
1805
    ("on_master", True, ht.TBool, None),
1806
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1807
    ("repeat", 0, ht.TPositiveInt, None),
1808
    ]
1809

    
1810

    
1811
class OpTestAllocator(OpCode):
1812
  """Allocator framework testing.
1813

1814
  This opcode has two modes:
1815
    - gather and return allocator input for a given mode (allocate new
1816
      or replace secondary) and a given instance definition (direction
1817
      'in')
1818
    - run a selected allocator for a given operation (as above) and
1819
      return the allocator output (direction 'out')
1820

1821
  """
1822
  OP_DSC_FIELD = "allocator"
1823
  OP_PARAMS = [
1824
    ("direction", ht.NoDefault,
1825
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1826
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1827
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1828
    ("nics", ht.NoDefault,
1829
     ht.TMaybeListOf(ht.TDictOf(ht.TElemOf([constants.INIC_MAC,
1830
                                            constants.INIC_IP,
1831
                                            "bridge"]),
1832
                                ht.TOr(ht.TNone, ht.TNonEmptyString))),
1833
     None),
1834
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1835
    ("hypervisor", None, ht.TMaybeString, None),
1836
    ("allocator", None, ht.TMaybeString, None),
1837
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1838
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1839
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1840
    ("os", None, ht.TMaybeString, None),
1841
    ("disk_template", None, ht.TMaybeString, None),
1842
    ("instances", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1843
    ("evac_mode", None,
1844
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1845
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1846
    ]
1847

    
1848

    
1849
class OpTestJqueue(OpCode):
1850
  """Utility opcode to test some aspects of the job queue.
1851

1852
  """
1853
  OP_PARAMS = [
1854
    ("notify_waitlock", False, ht.TBool, None),
1855
    ("notify_exec", False, ht.TBool, None),
1856
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1857
    ("fail", False, ht.TBool, None),
1858
    ]
1859

    
1860

    
1861
class OpTestDummy(OpCode):
1862
  """Utility opcode used by unittests.
1863

1864
  """
1865
  OP_PARAMS = [
1866
    ("result", ht.NoDefault, ht.NoType, None),
1867
    ("messages", ht.NoDefault, ht.NoType, None),
1868
    ("fail", ht.NoDefault, ht.NoType, None),
1869
    ("submit_jobs", None, ht.NoType, None),
1870
    ]
1871
  WITH_LU = False
1872

    
1873

    
1874
def _GetOpList():
1875
  """Returns list of all defined opcodes.
1876

1877
  Does not eliminate duplicates by C{OP_ID}.
1878

1879
  """
1880
  return [v for v in globals().values()
1881
          if (isinstance(v, type) and issubclass(v, OpCode) and
1882
              hasattr(v, "OP_ID") and v is not OpCode)]
1883

    
1884

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