Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ bc5d0215

History | View | Annotate | Download (51.8 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""OpCodes module
23

24
This module implements the data structures which define the cluster
25
operations - the so-called opcodes.
26

27
Every operation which modifies the cluster state is expressed via
28
opcodes.
29

30
"""
31

    
32
# this are practically structures, so disable the message about too
33
# few public methods:
34
# pylint: disable=R0903
35

    
36
import logging
37
import re
38

    
39
from ganeti import compat
40
from ganeti import constants
41
from ganeti import errors
42
from ganeti import ht
43

    
44

    
45
# Common opcode attributes
46

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
151
#: OP_ID conversion regular expression
152
_OPID_RE = re.compile("([a-z])([A-Z])")
153

    
154
#: Utility function for L{OpClusterSetParams}
155
_TestClusterOsList = ht.TOr(ht.TNone,
156
  ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
157
    ht.TMap(ht.WithDesc("GetFirstItem")(compat.fst),
158
            ht.TElemOf(constants.DDMS_VALUES)))))
159

    
160

    
161
# TODO: Generate check from constants.INIC_PARAMS_TYPES
162
#: Utility function for testing NIC definitions
163
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
164
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
165

    
166
_TSetParamsResultItemItems = [
167
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
168
  ht.Comment("new value")(ht.TAny),
169
  ]
170

    
171
_TSetParamsResult = \
172
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
173
                     ht.TItems(_TSetParamsResultItemItems)))
174

    
175
_SUMMARY_PREFIX = {
176
  "CLUSTER_": "C_",
177
  "GROUP_": "G_",
178
  "NODE_": "N_",
179
  "INSTANCE_": "I_",
180
  }
181

    
182
#: Attribute name for dependencies
183
DEPEND_ATTR = "depends"
184

    
185
#: Attribute name for comment
186
COMMENT_ATTR = "comment"
187

    
188

    
189
def _NameToId(name):
190
  """Convert an opcode class name to an OP_ID.
191

192
  @type name: string
193
  @param name: the class name, as OpXxxYyy
194
  @rtype: string
195
  @return: the name in the OP_XXXX_YYYY format
196

197
  """
198
  if not name.startswith("Op"):
199
    return None
200
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
201
  # consume any input, and hence we would just have all the elements
202
  # in the list, one by one; but it seems that split doesn't work on
203
  # non-consuming input, hence we have to process the input string a
204
  # bit
205
  name = _OPID_RE.sub(r"\1,\2", name)
206
  elems = name.split(",")
207
  return "_".join(n.upper() for n in elems)
208

    
209

    
210
def RequireFileStorage():
211
  """Checks that file storage is enabled.
212

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

216
  @raise errors.OpPrereqError: when file storage is disabled
217

218
  """
219
  if not constants.ENABLE_FILE_STORAGE:
220
    raise errors.OpPrereqError("File storage disabled at configure time",
221
                               errors.ECODE_INVAL)
222

    
223

    
224
def RequireSharedFileStorage():
225
  """Checks that shared file storage is enabled.
226

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

230
  @raise errors.OpPrereqError: when shared file storage is disabled
231

232
  """
233
  if not constants.ENABLE_SHARED_FILE_STORAGE:
234
    raise errors.OpPrereqError("Shared file storage disabled at"
235
                               " configure time", errors.ECODE_INVAL)
236

    
237

    
238
@ht.WithDesc("CheckFileStorage")
239
def _CheckFileStorage(value):
240
  """Ensures file storage is enabled if used.
241

242
  """
243
  if value == constants.DT_FILE:
244
    RequireFileStorage()
245
  elif value == constants.DT_SHARED_FILE:
246
    RequireSharedFileStorage()
247
  return True
248

    
249

    
250
def _BuildDiskTemplateCheck(accept_none):
251
  """Builds check for disk template.
252

253
  @type accept_none: bool
254
  @param accept_none: whether to accept None as a correct value
255
  @rtype: callable
256

257
  """
258
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
259

    
260
  if accept_none:
261
    template_check = ht.TOr(template_check, ht.TNone)
262

    
263
  return ht.TAnd(template_check, _CheckFileStorage)
264

    
265

    
266
def _CheckStorageType(storage_type):
267
  """Ensure a given storage type is valid.
268

269
  """
270
  if storage_type not in constants.VALID_STORAGE_TYPES:
271
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
272
                               errors.ECODE_INVAL)
273
  if storage_type == constants.ST_FILE:
274
    RequireFileStorage()
275
  return True
276

    
277

    
278
#: Storage type parameter
279
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
280
                 "Storage type")
281

    
282

    
283
class _AutoOpParamSlots(type):
284
  """Meta class for opcode definitions.
285

286
  """
287
  def __new__(mcs, name, bases, attrs):
288
    """Called when a class should be created.
289

290
    @param mcs: The meta class
291
    @param name: Name of created class
292
    @param bases: Base classes
293
    @type attrs: dict
294
    @param attrs: Class attributes
295

296
    """
297
    assert "__slots__" not in attrs, \
298
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
299
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
300

    
301
    attrs["OP_ID"] = _NameToId(name)
302

    
303
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
304
    params = attrs.setdefault("OP_PARAMS", [])
305

    
306
    # Use parameter names as slots
307
    slots = [pname for (pname, _, _, _) in params]
308

    
309
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
310
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
311

    
312
    attrs["__slots__"] = slots
313

    
314
    return type.__new__(mcs, name, bases, attrs)
315

    
316

    
317
class BaseOpCode(object):
318
  """A simple serializable object.
319

320
  This object serves as a parent class for OpCode without any custom
321
  field handling.
322

323
  """
324
  # pylint: disable=E1101
325
  # as OP_ID is dynamically defined
326
  __metaclass__ = _AutoOpParamSlots
327

    
328
  def __init__(self, **kwargs):
329
    """Constructor for BaseOpCode.
330

331
    The constructor takes only keyword arguments and will set
332
    attributes on this object based on the passed arguments. As such,
333
    it means that you should not pass arguments which are not in the
334
    __slots__ attribute for this class.
335

336
    """
337
    slots = self._all_slots()
338
    for key in kwargs:
339
      if key not in slots:
340
        raise TypeError("Object %s doesn't support the parameter '%s'" %
341
                        (self.__class__.__name__, key))
342
      setattr(self, key, kwargs[key])
343

    
344
  def __getstate__(self):
345
    """Generic serializer.
346

347
    This method just returns the contents of the instance as a
348
    dictionary.
349

350
    @rtype:  C{dict}
351
    @return: the instance attributes and their values
352

353
    """
354
    state = {}
355
    for name in self._all_slots():
356
      if hasattr(self, name):
357
        state[name] = getattr(self, name)
358
    return state
359

    
360
  def __setstate__(self, state):
361
    """Generic unserializer.
362

363
    This method just restores from the serialized state the attributes
364
    of the current instance.
365

366
    @param state: the serialized opcode data
367
    @type state:  C{dict}
368

369
    """
370
    if not isinstance(state, dict):
371
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
372
                       type(state))
373

    
374
    for name in self._all_slots():
375
      if name not in state and hasattr(self, name):
376
        delattr(self, name)
377

    
378
    for name in state:
379
      setattr(self, name, state[name])
380

    
381
  @classmethod
382
  def _all_slots(cls):
383
    """Compute the list of all declared slots for a class.
384

385
    """
386
    slots = []
387
    for parent in cls.__mro__:
388
      slots.extend(getattr(parent, "__slots__", []))
389
    return slots
390

    
391
  @classmethod
392
  def GetAllParams(cls):
393
    """Compute list of all parameters for an opcode.
394

395
    """
396
    slots = []
397
    for parent in cls.__mro__:
398
      slots.extend(getattr(parent, "OP_PARAMS", []))
399
    return slots
400

    
401
  def Validate(self, set_defaults):
402
    """Validate opcode parameters, optionally setting default values.
403

404
    @type set_defaults: bool
405
    @param set_defaults: Whether to set default values
406
    @raise errors.OpPrereqError: When a parameter value doesn't match
407
                                 requirements
408

409
    """
410
    for (attr_name, default, test, _) in self.GetAllParams():
411
      assert test == ht.NoType or callable(test)
412

    
413
      if not hasattr(self, attr_name):
414
        if default == ht.NoDefault:
415
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
416
                                     (self.OP_ID, attr_name),
417
                                     errors.ECODE_INVAL)
418
        elif set_defaults:
419
          if callable(default):
420
            dval = default()
421
          else:
422
            dval = default
423
          setattr(self, attr_name, dval)
424

    
425
      if test == ht.NoType:
426
        # no tests here
427
        continue
428

    
429
      if set_defaults or hasattr(self, attr_name):
430
        attr_val = getattr(self, attr_name)
431
        if not test(attr_val):
432
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
433
                        self.OP_ID, attr_name, type(attr_val), attr_val)
434
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
435
                                     (self.OP_ID, attr_name),
436
                                     errors.ECODE_INVAL)
437

    
438

    
439
def _BuildJobDepCheck(relative):
440
  """Builds check for job dependencies (L{DEPEND_ATTR}).
441

442
  @type relative: bool
443
  @param relative: Whether to accept relative job IDs (negative)
444
  @rtype: callable
445

446
  """
447
  if relative:
448
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
449
  else:
450
    job_id = ht.TJobId
451

    
452
  job_dep = \
453
    ht.TAnd(ht.TIsLength(2),
454
            ht.TItems([job_id,
455
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
456

    
457
  return ht.TOr(ht.TNone, ht.TListOf(job_dep))
458

    
459

    
460
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
461

    
462
#: List of submission status and job ID as returned by C{SubmitManyJobs}
463
_TJobIdListItem = \
464
  ht.TAnd(ht.TIsLength(2),
465
          ht.TItems([ht.Comment("success")(ht.TBool),
466
                     ht.Comment("Job ID if successful, error message"
467
                                " otherwise")(ht.TOr(ht.TString,
468
                                                     ht.TJobId))]))
469
TJobIdList = ht.TListOf(_TJobIdListItem)
470

    
471
#: Result containing only list of submitted jobs
472
TJobIdListOnly = ht.TStrictDict(True, True, {
473
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
474
  })
475

    
476

    
477
class OpCode(BaseOpCode):
478
  """Abstract OpCode.
479

480
  This is the root of the actual OpCode hierarchy. All clases derived
481
  from this class should override OP_ID.
482

483
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
484
               children of this class.
485
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
486
                      string returned by Summary(); see the docstring of that
487
                      method for details).
488
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
489
                   get if not already defined, and types they must match.
490
  @cvar OP_RESULT: Callable to verify opcode result
491
  @cvar WITH_LU: Boolean that specifies whether this should be included in
492
      mcpu's dispatch table
493
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
494
                 the check steps
495
  @ivar priority: Opcode priority for queue
496

497
  """
498
  # pylint: disable=E1101
499
  # as OP_ID is dynamically defined
500
  WITH_LU = True
501
  OP_PARAMS = [
502
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
503
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
504
    ("priority", constants.OP_PRIO_DEFAULT,
505
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
506
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
507
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
508
     " job IDs can be used"),
509
    (COMMENT_ATTR, None, ht.TMaybeString,
510
     "Comment describing the purpose of the opcode"),
511
    ]
512
  OP_RESULT = None
513

    
514
  def __getstate__(self):
515
    """Specialized getstate for opcodes.
516

517
    This method adds to the state dictionary the OP_ID of the class,
518
    so that on unload we can identify the correct class for
519
    instantiating the opcode.
520

521
    @rtype:   C{dict}
522
    @return:  the state as a dictionary
523

524
    """
525
    data = BaseOpCode.__getstate__(self)
526
    data["OP_ID"] = self.OP_ID
527
    return data
528

    
529
  @classmethod
530
  def LoadOpCode(cls, data):
531
    """Generic load opcode method.
532

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

537
    @type data:  C{dict}
538
    @param data: the serialized opcode
539

540
    """
541
    if not isinstance(data, dict):
542
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
543
    if "OP_ID" not in data:
544
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
545
    op_id = data["OP_ID"]
546
    op_class = None
547
    if op_id in OP_MAPPING:
548
      op_class = OP_MAPPING[op_id]
549
    else:
550
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
551
                       op_id)
552
    op = op_class()
553
    new_data = data.copy()
554
    del new_data["OP_ID"]
555
    op.__setstate__(new_data)
556
    return op
557

    
558
  def Summary(self):
559
    """Generates a summary description of this opcode.
560

561
    The summary is the value of the OP_ID attribute (without the "OP_"
562
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
563
    defined; this field should allow to easily identify the operation
564
    (for an instance creation job, e.g., it would be the instance
565
    name).
566

567
    """
568
    assert self.OP_ID is not None and len(self.OP_ID) > 3
569
    # all OP_ID start with OP_, we remove that
570
    txt = self.OP_ID[3:]
571
    field_name = getattr(self, "OP_DSC_FIELD", None)
572
    if field_name:
573
      field_value = getattr(self, field_name, None)
574
      if isinstance(field_value, (list, tuple)):
575
        field_value = ",".join(str(i) for i in field_value)
576
      txt = "%s(%s)" % (txt, field_value)
577
    return txt
578

    
579
  def TinySummary(self):
580
    """Generates a compact summary description of the opcode.
581

582
    """
583
    assert self.OP_ID.startswith("OP_")
584

    
585
    text = self.OP_ID[3:]
586

    
587
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
588
      if text.startswith(prefix):
589
        return supplement + text[len(prefix):]
590

    
591
    return text
592

    
593

    
594
# cluster opcodes
595

    
596
class OpClusterPostInit(OpCode):
597
  """Post cluster initialization.
598

599
  This opcode does not touch the cluster at all. Its purpose is to run hooks
600
  after the cluster has been initialized.
601

602
  """
603

    
604

    
605
class OpClusterDestroy(OpCode):
606
  """Destroy the cluster.
607

608
  This opcode has no other parameters. All the state is irreversibly
609
  lost after the execution of this opcode.
610

611
  """
612

    
613

    
614
class OpClusterQuery(OpCode):
615
  """Query cluster information."""
616

    
617

    
618
class OpClusterVerify(OpCode):
619
  """Submits all jobs necessary to verify the cluster.
620

621
  """
622
  OP_PARAMS = [
623
    _PDebugSimulateErrors,
624
    _PErrorCodes,
625
    _PSkipChecks,
626
    _PIgnoreErrors,
627
    _PVerbose,
628
    ("group_name", None, ht.TMaybeString, "Group to verify")
629
    ]
630
  OP_RESULT = TJobIdListOnly
631

    
632

    
633
class OpClusterVerifyConfig(OpCode):
634
  """Verify the cluster config.
635

636
  """
637
  OP_PARAMS = [
638
    _PDebugSimulateErrors,
639
    _PErrorCodes,
640
    _PIgnoreErrors,
641
    _PVerbose,
642
    ]
643
  OP_RESULT = ht.TBool
644

    
645

    
646
class OpClusterVerifyGroup(OpCode):
647
  """Run verify on a node group from the cluster.
648

649
  @type skip_checks: C{list}
650
  @ivar skip_checks: steps to be skipped from the verify process; this
651
                     needs to be a subset of
652
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
653
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
654

655
  """
656
  OP_DSC_FIELD = "group_name"
657
  OP_PARAMS = [
658
    _PGroupName,
659
    _PDebugSimulateErrors,
660
    _PErrorCodes,
661
    _PSkipChecks,
662
    _PIgnoreErrors,
663
    _PVerbose,
664
    ]
665
  OP_RESULT = ht.TBool
666

    
667

    
668
class OpClusterVerifyDisks(OpCode):
669
  """Verify the cluster disks.
670

671
  """
672
  OP_RESULT = TJobIdListOnly
673

    
674

    
675
class OpGroupVerifyDisks(OpCode):
676
  """Verifies the status of all disks in a node group.
677

678
  Result: a tuple of three elements:
679
    - dict of node names with issues (values: error msg)
680
    - list of instances with degraded disks (that should be activated)
681
    - dict of instances with missing logical volumes (values: (node, vol)
682
      pairs with details about the missing volumes)
683

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

689
  Note that only instances that are drbd-based are taken into
690
  consideration. This might need to be revisited in the future.
691

692
  """
693
  OP_DSC_FIELD = "group_name"
694
  OP_PARAMS = [
695
    _PGroupName,
696
    ]
697
  OP_RESULT = \
698
    ht.TAnd(ht.TIsLength(3),
699
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
700
                       ht.TListOf(ht.TString),
701
                       ht.TDictOf(ht.TString,
702
                                  ht.TListOf(ht.TListOf(ht.TString)))]))
703

    
704

    
705
class OpClusterRepairDiskSizes(OpCode):
706
  """Verify the disk sizes of the instances and fixes configuration
707
  mimatches.
708

709
  Parameters: optional instances list, in case we want to restrict the
710
  checks to only a subset of the instances.
711

712
  Result: a list of tuples, (instance, disk, new-size) for changed
713
  configurations.
714

715
  In normal operation, the list should be empty.
716

717
  @type instances: list
718
  @ivar instances: the list of instances to check, or empty for all instances
719

720
  """
721
  OP_PARAMS = [
722
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
723
    ]
724

    
725

    
726
class OpClusterConfigQuery(OpCode):
727
  """Query cluster configuration values."""
728
  OP_PARAMS = [
729
    _POutputFields
730
    ]
731

    
732

    
733
class OpClusterRename(OpCode):
734
  """Rename the cluster.
735

736
  @type name: C{str}
737
  @ivar name: The new name of the cluster. The name and/or the master IP
738
              address will be changed to match the new name and its IP
739
              address.
740

741
  """
742
  OP_DSC_FIELD = "name"
743
  OP_PARAMS = [
744
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
745
    ]
746

    
747

    
748
class OpClusterSetParams(OpCode):
749
  """Change the parameters of the cluster.
750

751
  @type vg_name: C{str} or C{None}
752
  @ivar vg_name: The new volume group name or None to disable LVM usage.
753

754
  """
755
  OP_PARAMS = [
756
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
757
    ("enabled_hypervisors", None,
758
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
759
            ht.TNone),
760
     "List of enabled hypervisors"),
761
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
762
                              ht.TNone),
763
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
764
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
765
     "Cluster-wide backend parameter defaults"),
766
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
767
                            ht.TNone),
768
     "Cluster-wide per-OS hypervisor parameter defaults"),
769
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
770
                              ht.TNone),
771
     "Cluster-wide OS parameter defaults"),
772
    _PDiskParams,
773
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
774
     "Master candidate pool size"),
775
    ("uid_pool", None, ht.NoType,
776
     "Set UID pool, must be list of lists describing UID ranges (two items,"
777
     " start and end inclusive)"),
778
    ("add_uids", None, ht.NoType,
779
     "Extend UID pool, must be list of lists describing UID ranges (two"
780
     " items, start and end inclusive) to be added"),
781
    ("remove_uids", None, ht.NoType,
782
     "Shrink UID pool, must be list of lists describing UID ranges (two"
783
     " items, start and end inclusive) to be removed"),
784
    ("maintain_node_health", None, ht.TMaybeBool,
785
     "Whether to automatically maintain node health"),
786
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
787
     "Whether to wipe disks before allocating them to instances"),
788
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
789
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
790
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
791
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
792
     "Default iallocator for cluster"),
793
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
794
     "Master network device"),
795
    ("master_netmask", None, ht.TOr(ht.TInt, ht.TNone),
796
     "Netmask of the master IP"),
797
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
798
     "List of reserved LVs"),
799
    ("hidden_os", None, _TestClusterOsList,
800
     "Modify list of hidden operating systems. Each modification must have"
801
     " two items, the operation and the OS name. The operation can be"
802
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
803
    ("blacklisted_os", None, _TestClusterOsList,
804
     "Modify list of blacklisted operating systems. Each modification must have"
805
     " two items, the operation and the OS name. The operation can be"
806
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
807
    ("use_external_mip_script", None, ht.TMaybeBool,
808
     "Whether to use an external master IP address setup script"),
809
    ]
810

    
811

    
812
class OpClusterRedistConf(OpCode):
813
  """Force a full push of the cluster configuration.
814

815
  """
816

    
817

    
818
class OpClusterActivateMasterIp(OpCode):
819
  """Activate the master IP on the master node.
820

821
  """
822

    
823

    
824
class OpClusterDeactivateMasterIp(OpCode):
825
  """Deactivate the master IP on the master node.
826

827
  """
828

    
829

    
830
class OpQuery(OpCode):
831
  """Query for resources/items.
832

833
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
834
  @ivar fields: List of fields to retrieve
835
  @ivar qfilter: Query filter
836

837
  """
838
  OP_DSC_FIELD = "what"
839
  OP_PARAMS = [
840
    _PQueryWhat,
841
    _PUseLocking,
842
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
843
     "Requested fields"),
844
    ("qfilter", None, ht.TOr(ht.TNone, ht.TListOf),
845
     "Query filter"),
846
    ]
847

    
848

    
849
class OpQueryFields(OpCode):
850
  """Query for available resource/item fields.
851

852
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
853
  @ivar fields: List of fields to retrieve
854

855
  """
856
  OP_DSC_FIELD = "what"
857
  OP_PARAMS = [
858
    _PQueryWhat,
859
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
860
     "Requested fields; if not given, all are returned"),
861
    ]
862

    
863

    
864
class OpOobCommand(OpCode):
865
  """Interact with OOB."""
866
  OP_PARAMS = [
867
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
868
     "List of nodes to run the OOB command against"),
869
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
870
     "OOB command to be run"),
871
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
872
     "Timeout before the OOB helper will be terminated"),
873
    ("ignore_status", False, ht.TBool,
874
     "Ignores the node offline status for power off"),
875
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
876
     "Time in seconds to wait between powering on nodes"),
877
    ]
878

    
879

    
880
# node opcodes
881

    
882
class OpNodeRemove(OpCode):
883
  """Remove a node.
884

885
  @type node_name: C{str}
886
  @ivar node_name: The name of the node to remove. If the node still has
887
                   instances on it, the operation will fail.
888

889
  """
890
  OP_DSC_FIELD = "node_name"
891
  OP_PARAMS = [
892
    _PNodeName,
893
    ]
894

    
895

    
896
class OpNodeAdd(OpCode):
897
  """Add a node to the cluster.
898

899
  @type node_name: C{str}
900
  @ivar node_name: The name of the node to add. This can be a short name,
901
                   but it will be expanded to the FQDN.
902
  @type primary_ip: IP address
903
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
904
                    opcode is submitted, but will be filled during the node
905
                    add (so it will be visible in the job query).
906
  @type secondary_ip: IP address
907
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
908
                      if the cluster has been initialized in 'dual-network'
909
                      mode, otherwise it must not be given.
910
  @type readd: C{bool}
911
  @ivar readd: Whether to re-add an existing node to the cluster. If
912
               this is not passed, then the operation will abort if the node
913
               name is already in the cluster; use this parameter to 'repair'
914
               a node that had its configuration broken, or was reinstalled
915
               without removal from the cluster.
916
  @type group: C{str}
917
  @ivar group: The node group to which this node will belong.
918
  @type vm_capable: C{bool}
919
  @ivar vm_capable: The vm_capable node attribute
920
  @type master_capable: C{bool}
921
  @ivar master_capable: The master_capable node attribute
922

923
  """
924
  OP_DSC_FIELD = "node_name"
925
  OP_PARAMS = [
926
    _PNodeName,
927
    ("primary_ip", None, ht.NoType, "Primary IP address"),
928
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
929
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
930
    ("group", None, ht.TMaybeString, "Initial node group"),
931
    ("master_capable", None, ht.TMaybeBool,
932
     "Whether node can become master or master candidate"),
933
    ("vm_capable", None, ht.TMaybeBool,
934
     "Whether node can host instances"),
935
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
936
    ]
937

    
938

    
939
class OpNodeQuery(OpCode):
940
  """Compute the list of nodes."""
941
  OP_PARAMS = [
942
    _POutputFields,
943
    _PUseLocking,
944
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
945
     "Empty list to query all nodes, node names otherwise"),
946
    ]
947

    
948

    
949
class OpNodeQueryvols(OpCode):
950
  """Get list of volumes on node."""
951
  OP_PARAMS = [
952
    _POutputFields,
953
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
954
     "Empty list to query all nodes, node names otherwise"),
955
    ]
956

    
957

    
958
class OpNodeQueryStorage(OpCode):
959
  """Get information on storage for node(s)."""
960
  OP_PARAMS = [
961
    _POutputFields,
962
    _PStorageType,
963
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
964
    ("name", None, ht.TMaybeString, "Storage name"),
965
    ]
966

    
967

    
968
class OpNodeModifyStorage(OpCode):
969
  """Modifies the properies of a storage unit"""
970
  OP_PARAMS = [
971
    _PNodeName,
972
    _PStorageType,
973
    _PStorageName,
974
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
975
    ]
976

    
977

    
978
class OpRepairNodeStorage(OpCode):
979
  """Repairs the volume group on a node."""
980
  OP_DSC_FIELD = "node_name"
981
  OP_PARAMS = [
982
    _PNodeName,
983
    _PStorageType,
984
    _PStorageName,
985
    _PIgnoreConsistency,
986
    ]
987

    
988

    
989
class OpNodeSetParams(OpCode):
990
  """Change the parameters of a node."""
991
  OP_DSC_FIELD = "node_name"
992
  OP_PARAMS = [
993
    _PNodeName,
994
    _PForce,
995
    ("master_candidate", None, ht.TMaybeBool,
996
     "Whether the node should become a master candidate"),
997
    ("offline", None, ht.TMaybeBool,
998
     "Whether the node should be marked as offline"),
999
    ("drained", None, ht.TMaybeBool,
1000
     "Whether the node should be marked as drained"),
1001
    ("auto_promote", False, ht.TBool,
1002
     "Whether node(s) should be promoted to master candidate if necessary"),
1003
    ("master_capable", None, ht.TMaybeBool,
1004
     "Denote whether node can become master or master candidate"),
1005
    ("vm_capable", None, ht.TMaybeBool,
1006
     "Denote whether node can host instances"),
1007
    ("secondary_ip", None, ht.TMaybeString,
1008
     "Change node's secondary IP address"),
1009
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1010
    ("powered", None, ht.TMaybeBool,
1011
     "Whether the node should be marked as powered"),
1012
    ]
1013
  OP_RESULT = _TSetParamsResult
1014

    
1015

    
1016
class OpNodePowercycle(OpCode):
1017
  """Tries to powercycle a node."""
1018
  OP_DSC_FIELD = "node_name"
1019
  OP_PARAMS = [
1020
    _PNodeName,
1021
    _PForce,
1022
    ]
1023

    
1024

    
1025
class OpNodeMigrate(OpCode):
1026
  """Migrate all instances from a node."""
1027
  OP_DSC_FIELD = "node_name"
1028
  OP_PARAMS = [
1029
    _PNodeName,
1030
    _PMigrationMode,
1031
    _PMigrationLive,
1032
    _PMigrationTargetNode,
1033
    ("iallocator", None, ht.TMaybeString,
1034
     "Iallocator for deciding the target node for shared-storage instances"),
1035
    ]
1036
  OP_RESULT = TJobIdListOnly
1037

    
1038

    
1039
class OpNodeEvacuate(OpCode):
1040
  """Evacuate instances off a number of nodes."""
1041
  OP_DSC_FIELD = "node_name"
1042
  OP_PARAMS = [
1043
    _PEarlyRelease,
1044
    _PNodeName,
1045
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1046
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1047
    ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1048
     "Node evacuation mode"),
1049
    ]
1050
  OP_RESULT = TJobIdListOnly
1051

    
1052

    
1053
# instance opcodes
1054

    
1055
class OpInstanceCreate(OpCode):
1056
  """Create an instance.
1057

1058
  @ivar instance_name: Instance name
1059
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1060
  @ivar source_handshake: Signed handshake from source (remote import only)
1061
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1062
  @ivar source_instance_name: Previous name of instance (remote import only)
1063
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1064
    (remote import only)
1065

1066
  """
1067
  OP_DSC_FIELD = "instance_name"
1068
  OP_PARAMS = [
1069
    _PInstanceName,
1070
    _PForceVariant,
1071
    _PWaitForSync,
1072
    _PNameCheck,
1073
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1074
    ("disks", ht.NoDefault,
1075
     # TODO: Generate check from constants.IDISK_PARAMS_TYPES
1076
     ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
1077
                           ht.TOr(ht.TNonEmptyString, ht.TInt))),
1078
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1079
     " each disk definition must contain a ``%s`` value and"
1080
     " can contain an optional ``%s`` value denoting the disk access mode"
1081
     " (%s)" %
1082
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1083
      constants.IDISK_MODE,
1084
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1085
    ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1086
     "Disk template"),
1087
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1088
     "Driver for file-backed disks"),
1089
    ("file_storage_dir", None, ht.TMaybeString,
1090
     "Directory for storing file-backed disks"),
1091
    ("hvparams", ht.EmptyDict, ht.TDict,
1092
     "Hypervisor parameters for instance, hypervisor-dependent"),
1093
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1094
    ("iallocator", None, ht.TMaybeString,
1095
     "Iallocator for deciding which node(s) to use"),
1096
    ("identify_defaults", False, ht.TBool,
1097
     "Reset instance parameters to default if equal"),
1098
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1099
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1100
     "Instance creation mode"),
1101
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1102
     "List of NIC (network interface) definitions, for example"
1103
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1104
     " contain the optional values %s" %
1105
     (constants.INIC_IP,
1106
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1107
    ("no_install", None, ht.TMaybeBool,
1108
     "Do not install the OS (will disable automatic start)"),
1109
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1110
    ("os_type", None, ht.TMaybeString, "Operating system"),
1111
    ("pnode", None, ht.TMaybeString, "Primary node"),
1112
    ("snode", None, ht.TMaybeString, "Secondary node"),
1113
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1114
     "Signed handshake from source (remote import only)"),
1115
    ("source_instance_name", None, ht.TMaybeString,
1116
     "Source instance name (remote import only)"),
1117
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1118
     ht.TPositiveInt,
1119
     "How long source instance was given to shut down (remote import only)"),
1120
    ("source_x509_ca", None, ht.TMaybeString,
1121
     "Source X509 CA in PEM format (remote import only)"),
1122
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1123
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1124
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1125
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1126
    ]
1127
  OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1128

    
1129

    
1130
class OpInstanceReinstall(OpCode):
1131
  """Reinstall an instance's OS."""
1132
  OP_DSC_FIELD = "instance_name"
1133
  OP_PARAMS = [
1134
    _PInstanceName,
1135
    _PForceVariant,
1136
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1137
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1138
    ]
1139

    
1140

    
1141
class OpInstanceRemove(OpCode):
1142
  """Remove an instance."""
1143
  OP_DSC_FIELD = "instance_name"
1144
  OP_PARAMS = [
1145
    _PInstanceName,
1146
    _PShutdownTimeout,
1147
    ("ignore_failures", False, ht.TBool,
1148
     "Whether to ignore failures during removal"),
1149
    ]
1150

    
1151

    
1152
class OpInstanceRename(OpCode):
1153
  """Rename an instance."""
1154
  OP_PARAMS = [
1155
    _PInstanceName,
1156
    _PNameCheck,
1157
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1158
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1159
    ]
1160
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1161

    
1162

    
1163
class OpInstanceStartup(OpCode):
1164
  """Startup an instance."""
1165
  OP_DSC_FIELD = "instance_name"
1166
  OP_PARAMS = [
1167
    _PInstanceName,
1168
    _PForce,
1169
    _PIgnoreOfflineNodes,
1170
    ("hvparams", ht.EmptyDict, ht.TDict,
1171
     "Temporary hypervisor parameters, hypervisor-dependent"),
1172
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1173
    _PNoRemember,
1174
    _PStartupPaused,
1175
    ]
1176

    
1177

    
1178
class OpInstanceShutdown(OpCode):
1179
  """Shutdown an instance."""
1180
  OP_DSC_FIELD = "instance_name"
1181
  OP_PARAMS = [
1182
    _PInstanceName,
1183
    _PIgnoreOfflineNodes,
1184
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1185
     "How long to wait for instance to shut down"),
1186
    _PNoRemember,
1187
    ]
1188

    
1189

    
1190
class OpInstanceReboot(OpCode):
1191
  """Reboot an instance."""
1192
  OP_DSC_FIELD = "instance_name"
1193
  OP_PARAMS = [
1194
    _PInstanceName,
1195
    _PShutdownTimeout,
1196
    ("ignore_secondaries", False, ht.TBool,
1197
     "Whether to start the instance even if secondary disks are failing"),
1198
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1199
     "How to reboot instance"),
1200
    ]
1201

    
1202

    
1203
class OpInstanceReplaceDisks(OpCode):
1204
  """Replace the disks of an instance."""
1205
  OP_DSC_FIELD = "instance_name"
1206
  OP_PARAMS = [
1207
    _PInstanceName,
1208
    _PEarlyRelease,
1209
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1210
     "Replacement mode"),
1211
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1212
     "Disk indexes"),
1213
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1214
    ("iallocator", None, ht.TMaybeString,
1215
     "Iallocator for deciding new secondary node"),
1216
    ]
1217

    
1218

    
1219
class OpInstanceFailover(OpCode):
1220
  """Failover an instance."""
1221
  OP_DSC_FIELD = "instance_name"
1222
  OP_PARAMS = [
1223
    _PInstanceName,
1224
    _PShutdownTimeout,
1225
    _PIgnoreConsistency,
1226
    _PMigrationTargetNode,
1227
    ("iallocator", None, ht.TMaybeString,
1228
     "Iallocator for deciding the target node for shared-storage instances"),
1229
    ]
1230

    
1231

    
1232
class OpInstanceMigrate(OpCode):
1233
  """Migrate an instance.
1234

1235
  This migrates (without shutting down an instance) to its secondary
1236
  node.
1237

1238
  @ivar instance_name: the name of the instance
1239
  @ivar mode: the migration mode (live, non-live or None for auto)
1240

1241
  """
1242
  OP_DSC_FIELD = "instance_name"
1243
  OP_PARAMS = [
1244
    _PInstanceName,
1245
    _PMigrationMode,
1246
    _PMigrationLive,
1247
    _PMigrationTargetNode,
1248
    ("cleanup", False, ht.TBool,
1249
     "Whether a previously failed migration should be cleaned up"),
1250
    ("iallocator", None, ht.TMaybeString,
1251
     "Iallocator for deciding the target node for shared-storage instances"),
1252
    ("allow_failover", False, ht.TBool,
1253
     "Whether we can fallback to failover if migration is not possible"),
1254
    ]
1255

    
1256

    
1257
class OpInstanceMove(OpCode):
1258
  """Move an instance.
1259

1260
  This move (with shutting down an instance and data copying) to an
1261
  arbitrary node.
1262

1263
  @ivar instance_name: the name of the instance
1264
  @ivar target_node: the destination node
1265

1266
  """
1267
  OP_DSC_FIELD = "instance_name"
1268
  OP_PARAMS = [
1269
    _PInstanceName,
1270
    _PShutdownTimeout,
1271
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1272
    _PIgnoreConsistency,
1273
    ]
1274

    
1275

    
1276
class OpInstanceConsole(OpCode):
1277
  """Connect to an instance's console."""
1278
  OP_DSC_FIELD = "instance_name"
1279
  OP_PARAMS = [
1280
    _PInstanceName
1281
    ]
1282

    
1283

    
1284
class OpInstanceActivateDisks(OpCode):
1285
  """Activate an instance's disks."""
1286
  OP_DSC_FIELD = "instance_name"
1287
  OP_PARAMS = [
1288
    _PInstanceName,
1289
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1290
    ]
1291

    
1292

    
1293
class OpInstanceDeactivateDisks(OpCode):
1294
  """Deactivate an instance's disks."""
1295
  OP_DSC_FIELD = "instance_name"
1296
  OP_PARAMS = [
1297
    _PInstanceName,
1298
    _PForce,
1299
    ]
1300

    
1301

    
1302
class OpInstanceRecreateDisks(OpCode):
1303
  """Recreate an instance's disks."""
1304
  OP_DSC_FIELD = "instance_name"
1305
  OP_PARAMS = [
1306
    _PInstanceName,
1307
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1308
     "List of disk indexes"),
1309
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1310
     "New instance nodes, if relocation is desired"),
1311
    ]
1312

    
1313

    
1314
class OpInstanceQuery(OpCode):
1315
  """Compute the list of instances."""
1316
  OP_PARAMS = [
1317
    _POutputFields,
1318
    _PUseLocking,
1319
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1320
     "Empty list to query all instances, instance names otherwise"),
1321
    ]
1322

    
1323

    
1324
class OpInstanceQueryData(OpCode):
1325
  """Compute the run-time status of instances."""
1326
  OP_PARAMS = [
1327
    _PUseLocking,
1328
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1329
     "Instance names"),
1330
    ("static", False, ht.TBool,
1331
     "Whether to only return configuration data without querying"
1332
     " nodes"),
1333
    ]
1334

    
1335

    
1336
class OpInstanceSetParams(OpCode):
1337
  """Change the parameters of an instance."""
1338
  OP_DSC_FIELD = "instance_name"
1339
  OP_PARAMS = [
1340
    _PInstanceName,
1341
    _PForce,
1342
    _PForceVariant,
1343
    # TODO: Use _TestNicDef
1344
    ("nics", ht.EmptyList, ht.TList,
1345
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1346
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1347
     " ``%s`` to remove the last NIC or a number to modify the settings"
1348
     " of the NIC with that index." %
1349
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1350
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1351
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1352
    ("hvparams", ht.EmptyDict, ht.TDict,
1353
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1354
    ("disk_template", None, ht.TOr(ht.TNone, _BuildDiskTemplateCheck(False)),
1355
     "Disk template for instance"),
1356
    ("remote_node", None, ht.TMaybeString,
1357
     "Secondary node (used when changing disk template)"),
1358
    ("os_name", None, ht.TMaybeString,
1359
     "Change instance's OS name. Does not reinstall the instance."),
1360
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1361
    ("wait_for_sync", True, ht.TBool,
1362
     "Whether to wait for the disk to synchronize, when changing template"),
1363
    ("offline_inst", False, ht.TBool,
1364
     "Whether to turn off the down instance completely"),
1365
    ("online_inst", False, ht.TBool,
1366
     "Whether to enable the offline instance"),
1367
    ]
1368
  OP_RESULT = _TSetParamsResult
1369

    
1370

    
1371
class OpInstanceGrowDisk(OpCode):
1372
  """Grow a disk of an instance."""
1373
  OP_DSC_FIELD = "instance_name"
1374
  OP_PARAMS = [
1375
    _PInstanceName,
1376
    _PWaitForSync,
1377
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1378
    ("amount", ht.NoDefault, ht.TInt,
1379
     "Amount of disk space to add (megabytes)"),
1380
    ]
1381

    
1382

    
1383
class OpInstanceChangeGroup(OpCode):
1384
  """Moves an instance to another node group."""
1385
  OP_DSC_FIELD = "instance_name"
1386
  OP_PARAMS = [
1387
    _PInstanceName,
1388
    _PEarlyRelease,
1389
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1390
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1391
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1392
    ]
1393
  OP_RESULT = TJobIdListOnly
1394

    
1395

    
1396
# Node group opcodes
1397

    
1398
class OpGroupAdd(OpCode):
1399
  """Add a node group to the cluster."""
1400
  OP_DSC_FIELD = "group_name"
1401
  OP_PARAMS = [
1402
    _PGroupName,
1403
    _PNodeGroupAllocPolicy,
1404
    _PGroupNodeParams,
1405
    _PDiskParams,
1406
    ]
1407

    
1408

    
1409
class OpGroupAssignNodes(OpCode):
1410
  """Assign nodes to a node group."""
1411
  OP_DSC_FIELD = "group_name"
1412
  OP_PARAMS = [
1413
    _PGroupName,
1414
    _PForce,
1415
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1416
     "List of nodes to assign"),
1417
    ]
1418

    
1419

    
1420
class OpGroupQuery(OpCode):
1421
  """Compute the list of node groups."""
1422
  OP_PARAMS = [
1423
    _POutputFields,
1424
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1425
     "Empty list to query all groups, group names otherwise"),
1426
    ]
1427

    
1428

    
1429
class OpGroupSetParams(OpCode):
1430
  """Change the parameters of a node group."""
1431
  OP_DSC_FIELD = "group_name"
1432
  OP_PARAMS = [
1433
    _PGroupName,
1434
    _PNodeGroupAllocPolicy,
1435
    _PGroupNodeParams,
1436
    _PDiskParams,
1437
    ]
1438
  OP_RESULT = _TSetParamsResult
1439

    
1440

    
1441
class OpGroupRemove(OpCode):
1442
  """Remove a node group from the cluster."""
1443
  OP_DSC_FIELD = "group_name"
1444
  OP_PARAMS = [
1445
    _PGroupName,
1446
    ]
1447

    
1448

    
1449
class OpGroupRename(OpCode):
1450
  """Rename a node group in the cluster."""
1451
  OP_PARAMS = [
1452
    _PGroupName,
1453
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1454
    ]
1455
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1456

    
1457

    
1458
class OpGroupEvacuate(OpCode):
1459
  """Evacuate a node group in the cluster."""
1460
  OP_DSC_FIELD = "group_name"
1461
  OP_PARAMS = [
1462
    _PGroupName,
1463
    _PEarlyRelease,
1464
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1465
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1466
     "Destination group names or UUIDs"),
1467
    ]
1468
  OP_RESULT = TJobIdListOnly
1469

    
1470

    
1471
# OS opcodes
1472
class OpOsDiagnose(OpCode):
1473
  """Compute the list of guest operating systems."""
1474
  OP_PARAMS = [
1475
    _POutputFields,
1476
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1477
     "Which operating systems to diagnose"),
1478
    ]
1479

    
1480

    
1481
# Exports opcodes
1482
class OpBackupQuery(OpCode):
1483
  """Compute the list of exported images."""
1484
  OP_PARAMS = [
1485
    _PUseLocking,
1486
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1487
     "Empty list to query all nodes, node names otherwise"),
1488
    ]
1489

    
1490

    
1491
class OpBackupPrepare(OpCode):
1492
  """Prepares an instance export.
1493

1494
  @ivar instance_name: Instance name
1495
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1496

1497
  """
1498
  OP_DSC_FIELD = "instance_name"
1499
  OP_PARAMS = [
1500
    _PInstanceName,
1501
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1502
     "Export mode"),
1503
    ]
1504

    
1505

    
1506
class OpBackupExport(OpCode):
1507
  """Export an instance.
1508

1509
  For local exports, the export destination is the node name. For remote
1510
  exports, the export destination is a list of tuples, each consisting of
1511
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1512
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1513
  destination X509 CA must be a signed certificate.
1514

1515
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1516
  @ivar target_node: Export destination
1517
  @ivar x509_key_name: X509 key to use (remote export only)
1518
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1519
                             only)
1520

1521
  """
1522
  OP_DSC_FIELD = "instance_name"
1523
  OP_PARAMS = [
1524
    _PInstanceName,
1525
    _PShutdownTimeout,
1526
    # TODO: Rename target_node as it changes meaning for different export modes
1527
    # (e.g. "destination")
1528
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1529
     "Destination information, depends on export mode"),
1530
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1531
    ("remove_instance", False, ht.TBool,
1532
     "Whether to remove instance after export"),
1533
    ("ignore_remove_failures", False, ht.TBool,
1534
     "Whether to ignore failures while removing instances"),
1535
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1536
     "Export mode"),
1537
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1538
     "Name of X509 key (remote export only)"),
1539
    ("destination_x509_ca", None, ht.TMaybeString,
1540
     "Destination X509 CA (remote export only)"),
1541
    ]
1542

    
1543

    
1544
class OpBackupRemove(OpCode):
1545
  """Remove an instance's export."""
1546
  OP_DSC_FIELD = "instance_name"
1547
  OP_PARAMS = [
1548
    _PInstanceName,
1549
    ]
1550

    
1551

    
1552
# Tags opcodes
1553
class OpTagsGet(OpCode):
1554
  """Returns the tags of the given object."""
1555
  OP_DSC_FIELD = "name"
1556
  OP_PARAMS = [
1557
    _PTagKind,
1558
    # Name is only meaningful for nodes and instances
1559
    ("name", ht.NoDefault, ht.TMaybeString, None),
1560
    ]
1561

    
1562

    
1563
class OpTagsSearch(OpCode):
1564
  """Searches the tags in the cluster for a given pattern."""
1565
  OP_DSC_FIELD = "pattern"
1566
  OP_PARAMS = [
1567
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1568
    ]
1569

    
1570

    
1571
class OpTagsSet(OpCode):
1572
  """Add a list of tags on a given object."""
1573
  OP_PARAMS = [
1574
    _PTagKind,
1575
    _PTags,
1576
    # Name is only meaningful for nodes and instances
1577
    ("name", ht.NoDefault, ht.TMaybeString, None),
1578
    ]
1579

    
1580

    
1581
class OpTagsDel(OpCode):
1582
  """Remove a list of tags from a given object."""
1583
  OP_PARAMS = [
1584
    _PTagKind,
1585
    _PTags,
1586
    # Name is only meaningful for nodes and instances
1587
    ("name", ht.NoDefault, ht.TMaybeString, None),
1588
    ]
1589

    
1590

    
1591
# Test opcodes
1592
class OpTestDelay(OpCode):
1593
  """Sleeps for a configured amount of time.
1594

1595
  This is used just for debugging and testing.
1596

1597
  Parameters:
1598
    - duration: the time to sleep
1599
    - on_master: if true, sleep on the master
1600
    - on_nodes: list of nodes in which to sleep
1601

1602
  If the on_master parameter is true, it will execute a sleep on the
1603
  master (before any node sleep).
1604

1605
  If the on_nodes list is not empty, it will sleep on those nodes
1606
  (after the sleep on the master, if that is enabled).
1607

1608
  As an additional feature, the case of duration < 0 will be reported
1609
  as an execution error, so this opcode can be used as a failure
1610
  generator. The case of duration == 0 will not be treated specially.
1611

1612
  """
1613
  OP_DSC_FIELD = "duration"
1614
  OP_PARAMS = [
1615
    ("duration", ht.NoDefault, ht.TNumber, None),
1616
    ("on_master", True, ht.TBool, None),
1617
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1618
    ("repeat", 0, ht.TPositiveInt, None),
1619
    ]
1620

    
1621

    
1622
class OpTestAllocator(OpCode):
1623
  """Allocator framework testing.
1624

1625
  This opcode has two modes:
1626
    - gather and return allocator input for a given mode (allocate new
1627
      or replace secondary) and a given instance definition (direction
1628
      'in')
1629
    - run a selected allocator for a given operation (as above) and
1630
      return the allocator output (direction 'out')
1631

1632
  """
1633
  OP_DSC_FIELD = "allocator"
1634
  OP_PARAMS = [
1635
    ("direction", ht.NoDefault,
1636
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1637
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1638
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1639
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1640
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1641
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1642
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1643
    ("hypervisor", None, ht.TMaybeString, None),
1644
    ("allocator", None, ht.TMaybeString, None),
1645
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1646
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1647
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1648
    ("os", None, ht.TMaybeString, None),
1649
    ("disk_template", None, ht.TMaybeString, None),
1650
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1651
     None),
1652
    ("evac_mode", None,
1653
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1654
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1655
     None),
1656
    ]
1657

    
1658

    
1659
class OpTestJqueue(OpCode):
1660
  """Utility opcode to test some aspects of the job queue.
1661

1662
  """
1663
  OP_PARAMS = [
1664
    ("notify_waitlock", False, ht.TBool, None),
1665
    ("notify_exec", False, ht.TBool, None),
1666
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1667
    ("fail", False, ht.TBool, None),
1668
    ]
1669

    
1670

    
1671
class OpTestDummy(OpCode):
1672
  """Utility opcode used by unittests.
1673

1674
  """
1675
  OP_PARAMS = [
1676
    ("result", ht.NoDefault, ht.NoType, None),
1677
    ("messages", ht.NoDefault, ht.NoType, None),
1678
    ("fail", ht.NoDefault, ht.NoType, None),
1679
    ("submit_jobs", None, ht.NoType, None),
1680
    ]
1681
  WITH_LU = False
1682

    
1683

    
1684
def _GetOpList():
1685
  """Returns list of all defined opcodes.
1686

1687
  Does not eliminate duplicates by C{OP_ID}.
1688

1689
  """
1690
  return [v for v in globals().values()
1691
          if (isinstance(v, type) and issubclass(v, OpCode) and
1692
              hasattr(v, "OP_ID") and v is not OpCode)]
1693

    
1694

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