Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ ff8067cf

History | View | Annotate | Download (53.3 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

    
43

    
44
# Common opcode attributes
45

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
96
_PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
97

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

    
101
_PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
102

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

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

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

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

    
117
_PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
118

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

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

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

    
130
_PVerbose = ("verbose", False, ht.TBool, "Verbose mode")
131

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

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

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

    
154

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

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

    
162

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

    
166
#: Utility function for L{OpClusterSetParams}
167
_TestClusterOsListItem = \
168
  ht.TAnd(ht.TIsLength(2), ht.TItems([
169
    ht.TElemOf(constants.DDMS_VALUES),
170
    ht.TNonEmptyString,
171
    ]))
172

    
173
_TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
174

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

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

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

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

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

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

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

    
207

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

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

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

    
228

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

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

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

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

    
242

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

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

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

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

    
256

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

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

    
268

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

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

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

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

    
282
  return ht.TAnd(template_check, _CheckFileStorage)
283

    
284

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

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

    
296

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

    
301

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

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

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

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

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

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

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

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

    
331
    attrs["__slots__"] = slots
332

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

    
335

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
457

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

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

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

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

    
476
  return ht.TMaybeListOf(job_dep)
477

    
478

    
479
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
480

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

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

    
495

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
605
    text = self.OP_ID[3:]
606

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

    
611
    return text
612

    
613

    
614
# cluster opcodes
615

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

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

622
  """
623

    
624

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

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

631
  """
632

    
633

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

    
637

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

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

    
652

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

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

    
665

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

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

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

    
687

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

691
  """
692
  OP_RESULT = TJobIdListOnly
693

    
694

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

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

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

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

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

    
724

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

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

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

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

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

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

    
745

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

    
752

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

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

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

    
767

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

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

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

    
835

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

839
  """
840

    
841

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

845
  """
846

    
847

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

851
  """
852

    
853

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

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

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

    
872

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

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

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

    
887

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

    
903

    
904
# node opcodes
905

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

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

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

    
919

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

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

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

    
964

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

    
974

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

    
983

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

    
993

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

    
1003

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

    
1014

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

    
1043

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

    
1052

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

    
1068

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

    
1082

    
1083
# instance opcodes
1084

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

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

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

    
1157

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

    
1168

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

    
1179

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

    
1190

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

    
1205

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

    
1217

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

    
1230

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

    
1247

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

    
1261

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

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

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

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

    
1288

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

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

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

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

    
1308

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

    
1316

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

    
1325

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

    
1334

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

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

    
1353

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

    
1363

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

    
1375

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

    
1409

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

    
1421

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

    
1434

    
1435
# Node group opcodes
1436

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

    
1451

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

    
1462

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

    
1471

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

    
1486

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

    
1494

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

    
1503

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

    
1516

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

    
1526

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

    
1536

    
1537
class OpBackupPrepare(OpCode):
1538
  """Prepares an instance export.
1539

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

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

    
1551

    
1552
class OpBackupExport(OpCode):
1553
  """Export an instance.
1554

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

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

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

    
1589

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

    
1597

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

    
1608

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

    
1616

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

    
1626

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

    
1636

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

1641
  This is used just for debugging and testing.
1642

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

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

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

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

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

    
1667

    
1668
class OpTestAllocator(OpCode):
1669
  """Allocator framework testing.
1670

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

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

    
1705

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

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

    
1717

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

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

    
1730

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

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

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

    
1741

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