Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ f2f57b6e

History | View | Annotate | Download (52.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 compat
40
from ganeti import constants
41
from ganeti import errors
42
from ganeti import ht
43

    
44

    
45
# Common opcode attributes
46

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
155
#: OP_ID conversion regular expression
156
_OPID_RE = re.compile("([a-z])([A-Z])")
157

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

    
164

    
165
# TODO: Generate check from constants.INIC_PARAMS_TYPES
166
#: Utility function for testing NIC definitions
167
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
168
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
169

    
170
_TSetParamsResultItemItems = [
171
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
172
  ht.Comment("new value")(ht.TAny),
173
  ]
174

    
175
_TSetParamsResult = \
176
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
177
                     ht.TItems(_TSetParamsResultItemItems)))
178

    
179
_SUMMARY_PREFIX = {
180
  "CLUSTER_": "C_",
181
  "GROUP_": "G_",
182
  "NODE_": "N_",
183
  "INSTANCE_": "I_",
184
  }
185

    
186
#: Attribute name for dependencies
187
DEPEND_ATTR = "depends"
188

    
189
#: Attribute name for comment
190
COMMENT_ATTR = "comment"
191

    
192

    
193
def _NameToId(name):
194
  """Convert an opcode class name to an OP_ID.
195

196
  @type name: string
197
  @param name: the class name, as OpXxxYyy
198
  @rtype: string
199
  @return: the name in the OP_XXXX_YYYY format
200

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

    
213

    
214
def RequireFileStorage():
215
  """Checks that file storage is enabled.
216

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

220
  @raise errors.OpPrereqError: when file storage is disabled
221

222
  """
223
  if not constants.ENABLE_FILE_STORAGE:
224
    raise errors.OpPrereqError("File storage disabled at configure time",
225
                               errors.ECODE_INVAL)
226

    
227

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

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

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

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

    
241

    
242
@ht.WithDesc("CheckFileStorage")
243
def _CheckFileStorage(value):
244
  """Ensures file storage is enabled if used.
245

246
  """
247
  if value == constants.DT_FILE:
248
    RequireFileStorage()
249
  elif value == constants.DT_SHARED_FILE:
250
    RequireSharedFileStorage()
251
  return True
252

    
253

    
254
def _BuildDiskTemplateCheck(accept_none):
255
  """Builds check for disk template.
256

257
  @type accept_none: bool
258
  @param accept_none: whether to accept None as a correct value
259
  @rtype: callable
260

261
  """
262
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
263

    
264
  if accept_none:
265
    template_check = ht.TOr(template_check, ht.TNone)
266

    
267
  return ht.TAnd(template_check, _CheckFileStorage)
268

    
269

    
270
def _CheckStorageType(storage_type):
271
  """Ensure a given storage type is valid.
272

273
  """
274
  if storage_type not in constants.VALID_STORAGE_TYPES:
275
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
276
                               errors.ECODE_INVAL)
277
  if storage_type == constants.ST_FILE:
278
    RequireFileStorage()
279
  return True
280

    
281

    
282
#: Storage type parameter
283
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
284
                 "Storage type")
285

    
286

    
287
class _AutoOpParamSlots(type):
288
  """Meta class for opcode definitions.
289

290
  """
291
  def __new__(mcs, name, bases, attrs):
292
    """Called when a class should be created.
293

294
    @param mcs: The meta class
295
    @param name: Name of created class
296
    @param bases: Base classes
297
    @type attrs: dict
298
    @param attrs: Class attributes
299

300
    """
301
    assert "__slots__" not in attrs, \
302
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
303
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
304

    
305
    attrs["OP_ID"] = _NameToId(name)
306

    
307
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
308
    params = attrs.setdefault("OP_PARAMS", [])
309

    
310
    # Use parameter names as slots
311
    slots = [pname for (pname, _, _, _) in params]
312

    
313
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
314
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
315

    
316
    attrs["__slots__"] = slots
317

    
318
    return type.__new__(mcs, name, bases, attrs)
319

    
320

    
321
class BaseOpCode(object):
322
  """A simple serializable object.
323

324
  This object serves as a parent class for OpCode without any custom
325
  field handling.
326

327
  """
328
  # pylint: disable=E1101
329
  # as OP_ID is dynamically defined
330
  __metaclass__ = _AutoOpParamSlots
331

    
332
  def __init__(self, **kwargs):
333
    """Constructor for BaseOpCode.
334

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

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

    
348
  def __getstate__(self):
349
    """Generic serializer.
350

351
    This method just returns the contents of the instance as a
352
    dictionary.
353

354
    @rtype:  C{dict}
355
    @return: the instance attributes and their values
356

357
    """
358
    state = {}
359
    for name in self._all_slots():
360
      if hasattr(self, name):
361
        state[name] = getattr(self, name)
362
    return state
363

    
364
  def __setstate__(self, state):
365
    """Generic unserializer.
366

367
    This method just restores from the serialized state the attributes
368
    of the current instance.
369

370
    @param state: the serialized opcode data
371
    @type state:  C{dict}
372

373
    """
374
    if not isinstance(state, dict):
375
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
376
                       type(state))
377

    
378
    for name in self._all_slots():
379
      if name not in state and hasattr(self, name):
380
        delattr(self, name)
381

    
382
    for name in state:
383
      setattr(self, name, state[name])
384

    
385
  @classmethod
386
  def _all_slots(cls):
387
    """Compute the list of all declared slots for a class.
388

389
    """
390
    slots = []
391
    for parent in cls.__mro__:
392
      slots.extend(getattr(parent, "__slots__", []))
393
    return slots
394

    
395
  @classmethod
396
  def GetAllParams(cls):
397
    """Compute list of all parameters for an opcode.
398

399
    """
400
    slots = []
401
    for parent in cls.__mro__:
402
      slots.extend(getattr(parent, "OP_PARAMS", []))
403
    return slots
404

    
405
  def Validate(self, set_defaults):
406
    """Validate opcode parameters, optionally setting default values.
407

408
    @type set_defaults: bool
409
    @param set_defaults: Whether to set default values
410
    @raise errors.OpPrereqError: When a parameter value doesn't match
411
                                 requirements
412

413
    """
414
    for (attr_name, default, test, _) in self.GetAllParams():
415
      assert test == ht.NoType or callable(test)
416

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

    
429
      if test == ht.NoType:
430
        # no tests here
431
        continue
432

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

    
442

    
443
def _BuildJobDepCheck(relative):
444
  """Builds check for job dependencies (L{DEPEND_ATTR}).
445

446
  @type relative: bool
447
  @param relative: Whether to accept relative job IDs (negative)
448
  @rtype: callable
449

450
  """
451
  if relative:
452
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
453
  else:
454
    job_id = ht.TJobId
455

    
456
  job_dep = \
457
    ht.TAnd(ht.TIsLength(2),
458
            ht.TItems([job_id,
459
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
460

    
461
  return ht.TOr(ht.TNone, ht.TListOf(job_dep))
462

    
463

    
464
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
465

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

    
475
#: Result containing only list of submitted jobs
476
TJobIdListOnly = ht.TStrictDict(True, True, {
477
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
478
  })
479

    
480

    
481
class OpCode(BaseOpCode):
482
  """Abstract OpCode.
483

484
  This is the root of the actual OpCode hierarchy. All clases derived
485
  from this class should override OP_ID.
486

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

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

    
518
  def __getstate__(self):
519
    """Specialized getstate for opcodes.
520

521
    This method adds to the state dictionary the OP_ID of the class,
522
    so that on unload we can identify the correct class for
523
    instantiating the opcode.
524

525
    @rtype:   C{dict}
526
    @return:  the state as a dictionary
527

528
    """
529
    data = BaseOpCode.__getstate__(self)
530
    data["OP_ID"] = self.OP_ID
531
    return data
532

    
533
  @classmethod
534
  def LoadOpCode(cls, data):
535
    """Generic load opcode method.
536

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

541
    @type data:  C{dict}
542
    @param data: the serialized opcode
543

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

    
562
  def Summary(self):
563
    """Generates a summary description of this opcode.
564

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

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

    
583
  def TinySummary(self):
584
    """Generates a compact summary description of the opcode.
585

586
    """
587
    assert self.OP_ID.startswith("OP_")
588

    
589
    text = self.OP_ID[3:]
590

    
591
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
592
      if text.startswith(prefix):
593
        return supplement + text[len(prefix):]
594

    
595
    return text
596

    
597

    
598
# cluster opcodes
599

    
600
class OpClusterPostInit(OpCode):
601
  """Post cluster initialization.
602

603
  This opcode does not touch the cluster at all. Its purpose is to run hooks
604
  after the cluster has been initialized.
605

606
  """
607

    
608

    
609
class OpClusterDestroy(OpCode):
610
  """Destroy the cluster.
611

612
  This opcode has no other parameters. All the state is irreversibly
613
  lost after the execution of this opcode.
614

615
  """
616

    
617

    
618
class OpClusterQuery(OpCode):
619
  """Query cluster information."""
620

    
621

    
622
class OpClusterVerify(OpCode):
623
  """Submits all jobs necessary to verify the cluster.
624

625
  """
626
  OP_PARAMS = [
627
    _PDebugSimulateErrors,
628
    _PErrorCodes,
629
    _PSkipChecks,
630
    _PIgnoreErrors,
631
    _PVerbose,
632
    ("group_name", None, ht.TMaybeString, "Group to verify")
633
    ]
634
  OP_RESULT = TJobIdListOnly
635

    
636

    
637
class OpClusterVerifyConfig(OpCode):
638
  """Verify the cluster config.
639

640
  """
641
  OP_PARAMS = [
642
    _PDebugSimulateErrors,
643
    _PErrorCodes,
644
    _PIgnoreErrors,
645
    _PVerbose,
646
    ]
647
  OP_RESULT = ht.TBool
648

    
649

    
650
class OpClusterVerifyGroup(OpCode):
651
  """Run verify on a node group from the cluster.
652

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

659
  """
660
  OP_DSC_FIELD = "group_name"
661
  OP_PARAMS = [
662
    _PGroupName,
663
    _PDebugSimulateErrors,
664
    _PErrorCodes,
665
    _PSkipChecks,
666
    _PIgnoreErrors,
667
    _PVerbose,
668
    ]
669
  OP_RESULT = ht.TBool
670

    
671

    
672
class OpClusterVerifyDisks(OpCode):
673
  """Verify the cluster disks.
674

675
  """
676
  OP_RESULT = TJobIdListOnly
677

    
678

    
679
class OpGroupVerifyDisks(OpCode):
680
  """Verifies the status of all disks in a node group.
681

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

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

693
  Note that only instances that are drbd-based are taken into
694
  consideration. This might need to be revisited in the future.
695

696
  """
697
  OP_DSC_FIELD = "group_name"
698
  OP_PARAMS = [
699
    _PGroupName,
700
    ]
701
  OP_RESULT = \
702
    ht.TAnd(ht.TIsLength(3),
703
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
704
                       ht.TListOf(ht.TString),
705
                       ht.TDictOf(ht.TString,
706
                                  ht.TListOf(ht.TListOf(ht.TString)))]))
707

    
708

    
709
class OpClusterRepairDiskSizes(OpCode):
710
  """Verify the disk sizes of the instances and fixes configuration
711
  mimatches.
712

713
  Parameters: optional instances list, in case we want to restrict the
714
  checks to only a subset of the instances.
715

716
  Result: a list of tuples, (instance, disk, new-size) for changed
717
  configurations.
718

719
  In normal operation, the list should be empty.
720

721
  @type instances: list
722
  @ivar instances: the list of instances to check, or empty for all instances
723

724
  """
725
  OP_PARAMS = [
726
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
727
    ]
728

    
729

    
730
class OpClusterConfigQuery(OpCode):
731
  """Query cluster configuration values."""
732
  OP_PARAMS = [
733
    _POutputFields
734
    ]
735

    
736

    
737
class OpClusterRename(OpCode):
738
  """Rename the cluster.
739

740
  @type name: C{str}
741
  @ivar name: The new name of the cluster. The name and/or the master IP
742
              address will be changed to match the new name and its IP
743
              address.
744

745
  """
746
  OP_DSC_FIELD = "name"
747
  OP_PARAMS = [
748
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
749
    ]
750

    
751

    
752
class OpClusterSetParams(OpCode):
753
  """Change the parameters of the cluster.
754

755
  @type vg_name: C{str} or C{None}
756
  @ivar vg_name: The new volume group name or None to disable LVM usage.
757

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

    
818

    
819
class OpClusterRedistConf(OpCode):
820
  """Force a full push of the cluster configuration.
821

822
  """
823

    
824

    
825
class OpClusterActivateMasterIp(OpCode):
826
  """Activate the master IP on the master node.
827

828
  """
829

    
830

    
831
class OpClusterDeactivateMasterIp(OpCode):
832
  """Deactivate the master IP on the master node.
833

834
  """
835

    
836

    
837
class OpQuery(OpCode):
838
  """Query for resources/items.
839

840
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
841
  @ivar fields: List of fields to retrieve
842
  @ivar qfilter: Query filter
843

844
  """
845
  OP_DSC_FIELD = "what"
846
  OP_PARAMS = [
847
    _PQueryWhat,
848
    _PUseLocking,
849
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
850
     "Requested fields"),
851
    ("qfilter", None, ht.TOr(ht.TNone, ht.TListOf),
852
     "Query filter"),
853
    ]
854

    
855

    
856
class OpQueryFields(OpCode):
857
  """Query for available resource/item fields.
858

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

862
  """
863
  OP_DSC_FIELD = "what"
864
  OP_PARAMS = [
865
    _PQueryWhat,
866
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
867
     "Requested fields; if not given, all are returned"),
868
    ]
869

    
870

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

    
886

    
887
# node opcodes
888

    
889
class OpNodeRemove(OpCode):
890
  """Remove a node.
891

892
  @type node_name: C{str}
893
  @ivar node_name: The name of the node to remove. If the node still has
894
                   instances on it, the operation will fail.
895

896
  """
897
  OP_DSC_FIELD = "node_name"
898
  OP_PARAMS = [
899
    _PNodeName,
900
    ]
901

    
902

    
903
class OpNodeAdd(OpCode):
904
  """Add a node to the cluster.
905

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

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

    
945

    
946
class OpNodeQuery(OpCode):
947
  """Compute the list of nodes."""
948
  OP_PARAMS = [
949
    _POutputFields,
950
    _PUseLocking,
951
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
952
     "Empty list to query all nodes, node names otherwise"),
953
    ]
954

    
955

    
956
class OpNodeQueryvols(OpCode):
957
  """Get list of volumes on node."""
958
  OP_PARAMS = [
959
    _POutputFields,
960
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
961
     "Empty list to query all nodes, node names otherwise"),
962
    ]
963

    
964

    
965
class OpNodeQueryStorage(OpCode):
966
  """Get information on storage for node(s)."""
967
  OP_PARAMS = [
968
    _POutputFields,
969
    _PStorageType,
970
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
971
    ("name", None, ht.TMaybeString, "Storage name"),
972
    ]
973

    
974

    
975
class OpNodeModifyStorage(OpCode):
976
  """Modifies the properies of a storage unit"""
977
  OP_PARAMS = [
978
    _PNodeName,
979
    _PStorageType,
980
    _PStorageName,
981
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
982
    ]
983

    
984

    
985
class OpRepairNodeStorage(OpCode):
986
  """Repairs the volume group on a node."""
987
  OP_DSC_FIELD = "node_name"
988
  OP_PARAMS = [
989
    _PNodeName,
990
    _PStorageType,
991
    _PStorageName,
992
    _PIgnoreConsistency,
993
    ]
994

    
995

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

    
1024

    
1025
class OpNodePowercycle(OpCode):
1026
  """Tries to powercycle a node."""
1027
  OP_DSC_FIELD = "node_name"
1028
  OP_PARAMS = [
1029
    _PNodeName,
1030
    _PForce,
1031
    ]
1032

    
1033

    
1034
class OpNodeMigrate(OpCode):
1035
  """Migrate all instances from a node."""
1036
  OP_DSC_FIELD = "node_name"
1037
  OP_PARAMS = [
1038
    _PNodeName,
1039
    _PMigrationMode,
1040
    _PMigrationLive,
1041
    _PMigrationTargetNode,
1042
    ("iallocator", None, ht.TMaybeString,
1043
     "Iallocator for deciding the target node for shared-storage instances"),
1044
    ]
1045
  OP_RESULT = TJobIdListOnly
1046

    
1047

    
1048
class OpNodeEvacuate(OpCode):
1049
  """Evacuate instances off a number of nodes."""
1050
  OP_DSC_FIELD = "node_name"
1051
  OP_PARAMS = [
1052
    _PEarlyRelease,
1053
    _PNodeName,
1054
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1055
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1056
    ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1057
     "Node evacuation mode"),
1058
    ]
1059
  OP_RESULT = TJobIdListOnly
1060

    
1061

    
1062
# instance opcodes
1063

    
1064
class OpInstanceCreate(OpCode):
1065
  """Create an instance.
1066

1067
  @ivar instance_name: Instance name
1068
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1069
  @ivar source_handshake: Signed handshake from source (remote import only)
1070
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1071
  @ivar source_instance_name: Previous name of instance (remote import only)
1072
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1073
    (remote import only)
1074

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

    
1138

    
1139
class OpInstanceReinstall(OpCode):
1140
  """Reinstall an instance's OS."""
1141
  OP_DSC_FIELD = "instance_name"
1142
  OP_PARAMS = [
1143
    _PInstanceName,
1144
    _PForceVariant,
1145
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1146
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1147
    ]
1148

    
1149

    
1150
class OpInstanceRemove(OpCode):
1151
  """Remove an instance."""
1152
  OP_DSC_FIELD = "instance_name"
1153
  OP_PARAMS = [
1154
    _PInstanceName,
1155
    _PShutdownTimeout,
1156
    ("ignore_failures", False, ht.TBool,
1157
     "Whether to ignore failures during removal"),
1158
    ]
1159

    
1160

    
1161
class OpInstanceRename(OpCode):
1162
  """Rename an instance."""
1163
  OP_PARAMS = [
1164
    _PInstanceName,
1165
    _PNameCheck,
1166
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1167
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1168
    ]
1169
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1170

    
1171

    
1172
class OpInstanceStartup(OpCode):
1173
  """Startup an instance."""
1174
  OP_DSC_FIELD = "instance_name"
1175
  OP_PARAMS = [
1176
    _PInstanceName,
1177
    _PForce,
1178
    _PIgnoreOfflineNodes,
1179
    ("hvparams", ht.EmptyDict, ht.TDict,
1180
     "Temporary hypervisor parameters, hypervisor-dependent"),
1181
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1182
    _PNoRemember,
1183
    _PStartupPaused,
1184
    ]
1185

    
1186

    
1187
class OpInstanceShutdown(OpCode):
1188
  """Shutdown an instance."""
1189
  OP_DSC_FIELD = "instance_name"
1190
  OP_PARAMS = [
1191
    _PInstanceName,
1192
    _PIgnoreOfflineNodes,
1193
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1194
     "How long to wait for instance to shut down"),
1195
    _PNoRemember,
1196
    ]
1197

    
1198

    
1199
class OpInstanceReboot(OpCode):
1200
  """Reboot an instance."""
1201
  OP_DSC_FIELD = "instance_name"
1202
  OP_PARAMS = [
1203
    _PInstanceName,
1204
    _PShutdownTimeout,
1205
    ("ignore_secondaries", False, ht.TBool,
1206
     "Whether to start the instance even if secondary disks are failing"),
1207
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1208
     "How to reboot instance"),
1209
    ]
1210

    
1211

    
1212
class OpInstanceReplaceDisks(OpCode):
1213
  """Replace the disks of an instance."""
1214
  OP_DSC_FIELD = "instance_name"
1215
  OP_PARAMS = [
1216
    _PInstanceName,
1217
    _PEarlyRelease,
1218
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1219
     "Replacement mode"),
1220
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1221
     "Disk indexes"),
1222
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1223
    ("iallocator", None, ht.TMaybeString,
1224
     "Iallocator for deciding new secondary node"),
1225
    ]
1226

    
1227

    
1228
class OpInstanceFailover(OpCode):
1229
  """Failover an instance."""
1230
  OP_DSC_FIELD = "instance_name"
1231
  OP_PARAMS = [
1232
    _PInstanceName,
1233
    _PShutdownTimeout,
1234
    _PIgnoreConsistency,
1235
    _PMigrationTargetNode,
1236
    ("iallocator", None, ht.TMaybeString,
1237
     "Iallocator for deciding the target node for shared-storage instances"),
1238
    ]
1239

    
1240

    
1241
class OpInstanceMigrate(OpCode):
1242
  """Migrate an instance.
1243

1244
  This migrates (without shutting down an instance) to its secondary
1245
  node.
1246

1247
  @ivar instance_name: the name of the instance
1248
  @ivar mode: the migration mode (live, non-live or None for auto)
1249

1250
  """
1251
  OP_DSC_FIELD = "instance_name"
1252
  OP_PARAMS = [
1253
    _PInstanceName,
1254
    _PMigrationMode,
1255
    _PMigrationLive,
1256
    _PMigrationTargetNode,
1257
    ("cleanup", False, ht.TBool,
1258
     "Whether a previously failed migration should be cleaned up"),
1259
    ("iallocator", None, ht.TMaybeString,
1260
     "Iallocator for deciding the target node for shared-storage instances"),
1261
    ("allow_failover", False, ht.TBool,
1262
     "Whether we can fallback to failover if migration is not possible"),
1263
    ]
1264

    
1265

    
1266
class OpInstanceMove(OpCode):
1267
  """Move an instance.
1268

1269
  This move (with shutting down an instance and data copying) to an
1270
  arbitrary node.
1271

1272
  @ivar instance_name: the name of the instance
1273
  @ivar target_node: the destination node
1274

1275
  """
1276
  OP_DSC_FIELD = "instance_name"
1277
  OP_PARAMS = [
1278
    _PInstanceName,
1279
    _PShutdownTimeout,
1280
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1281
    _PIgnoreConsistency,
1282
    ]
1283

    
1284

    
1285
class OpInstanceConsole(OpCode):
1286
  """Connect to an instance's console."""
1287
  OP_DSC_FIELD = "instance_name"
1288
  OP_PARAMS = [
1289
    _PInstanceName
1290
    ]
1291

    
1292

    
1293
class OpInstanceActivateDisks(OpCode):
1294
  """Activate an instance's disks."""
1295
  OP_DSC_FIELD = "instance_name"
1296
  OP_PARAMS = [
1297
    _PInstanceName,
1298
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1299
    ]
1300

    
1301

    
1302
class OpInstanceDeactivateDisks(OpCode):
1303
  """Deactivate an instance's disks."""
1304
  OP_DSC_FIELD = "instance_name"
1305
  OP_PARAMS = [
1306
    _PInstanceName,
1307
    _PForce,
1308
    ]
1309

    
1310

    
1311
class OpInstanceRecreateDisks(OpCode):
1312
  """Recreate an instance's disks."""
1313
  OP_DSC_FIELD = "instance_name"
1314
  OP_PARAMS = [
1315
    _PInstanceName,
1316
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1317
     "List of disk indexes"),
1318
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1319
     "New instance nodes, if relocation is desired"),
1320
    ]
1321

    
1322

    
1323
class OpInstanceQuery(OpCode):
1324
  """Compute the list of instances."""
1325
  OP_PARAMS = [
1326
    _POutputFields,
1327
    _PUseLocking,
1328
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1329
     "Empty list to query all instances, instance names otherwise"),
1330
    ]
1331

    
1332

    
1333
class OpInstanceQueryData(OpCode):
1334
  """Compute the run-time status of instances."""
1335
  OP_PARAMS = [
1336
    _PUseLocking,
1337
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1338
     "Instance names"),
1339
    ("static", False, ht.TBool,
1340
     "Whether to only return configuration data without querying"
1341
     " nodes"),
1342
    ]
1343

    
1344

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

    
1379

    
1380
class OpInstanceGrowDisk(OpCode):
1381
  """Grow a disk of an instance."""
1382
  OP_DSC_FIELD = "instance_name"
1383
  OP_PARAMS = [
1384
    _PInstanceName,
1385
    _PWaitForSync,
1386
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1387
    ("amount", ht.NoDefault, ht.TInt,
1388
     "Amount of disk space to add (megabytes)"),
1389
    ]
1390

    
1391

    
1392
class OpInstanceChangeGroup(OpCode):
1393
  """Moves an instance to another node group."""
1394
  OP_DSC_FIELD = "instance_name"
1395
  OP_PARAMS = [
1396
    _PInstanceName,
1397
    _PEarlyRelease,
1398
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1399
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1400
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1401
    ]
1402
  OP_RESULT = TJobIdListOnly
1403

    
1404

    
1405
# Node group opcodes
1406

    
1407
class OpGroupAdd(OpCode):
1408
  """Add a node group to the cluster."""
1409
  OP_DSC_FIELD = "group_name"
1410
  OP_PARAMS = [
1411
    _PGroupName,
1412
    _PNodeGroupAllocPolicy,
1413
    _PGroupNodeParams,
1414
    _PDiskParams,
1415
    ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1416
    ]
1417

    
1418

    
1419
class OpGroupAssignNodes(OpCode):
1420
  """Assign nodes to a node group."""
1421
  OP_DSC_FIELD = "group_name"
1422
  OP_PARAMS = [
1423
    _PGroupName,
1424
    _PForce,
1425
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1426
     "List of nodes to assign"),
1427
    ]
1428

    
1429

    
1430
class OpGroupQuery(OpCode):
1431
  """Compute the list of node groups."""
1432
  OP_PARAMS = [
1433
    _POutputFields,
1434
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1435
     "Empty list to query all groups, group names otherwise"),
1436
    ]
1437

    
1438

    
1439
class OpGroupSetParams(OpCode):
1440
  """Change the parameters of a node group."""
1441
  OP_DSC_FIELD = "group_name"
1442
  OP_PARAMS = [
1443
    _PGroupName,
1444
    _PNodeGroupAllocPolicy,
1445
    _PGroupNodeParams,
1446
    _PDiskParams,
1447
    _PHvState,
1448
    _PDiskState,
1449
    ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1450
    ]
1451
  OP_RESULT = _TSetParamsResult
1452

    
1453

    
1454
class OpGroupRemove(OpCode):
1455
  """Remove a node group from the cluster."""
1456
  OP_DSC_FIELD = "group_name"
1457
  OP_PARAMS = [
1458
    _PGroupName,
1459
    ]
1460

    
1461

    
1462
class OpGroupRename(OpCode):
1463
  """Rename a node group in the cluster."""
1464
  OP_PARAMS = [
1465
    _PGroupName,
1466
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1467
    ]
1468
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1469

    
1470

    
1471
class OpGroupEvacuate(OpCode):
1472
  """Evacuate a node group in the cluster."""
1473
  OP_DSC_FIELD = "group_name"
1474
  OP_PARAMS = [
1475
    _PGroupName,
1476
    _PEarlyRelease,
1477
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1478
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1479
     "Destination group names or UUIDs"),
1480
    ]
1481
  OP_RESULT = TJobIdListOnly
1482

    
1483

    
1484
# OS opcodes
1485
class OpOsDiagnose(OpCode):
1486
  """Compute the list of guest operating systems."""
1487
  OP_PARAMS = [
1488
    _POutputFields,
1489
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1490
     "Which operating systems to diagnose"),
1491
    ]
1492

    
1493

    
1494
# Exports opcodes
1495
class OpBackupQuery(OpCode):
1496
  """Compute the list of exported images."""
1497
  OP_PARAMS = [
1498
    _PUseLocking,
1499
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1500
     "Empty list to query all nodes, node names otherwise"),
1501
    ]
1502

    
1503

    
1504
class OpBackupPrepare(OpCode):
1505
  """Prepares an instance export.
1506

1507
  @ivar instance_name: Instance name
1508
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1509

1510
  """
1511
  OP_DSC_FIELD = "instance_name"
1512
  OP_PARAMS = [
1513
    _PInstanceName,
1514
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1515
     "Export mode"),
1516
    ]
1517

    
1518

    
1519
class OpBackupExport(OpCode):
1520
  """Export an instance.
1521

1522
  For local exports, the export destination is the node name. For remote
1523
  exports, the export destination is a list of tuples, each consisting of
1524
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1525
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1526
  destination X509 CA must be a signed certificate.
1527

1528
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1529
  @ivar target_node: Export destination
1530
  @ivar x509_key_name: X509 key to use (remote export only)
1531
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1532
                             only)
1533

1534
  """
1535
  OP_DSC_FIELD = "instance_name"
1536
  OP_PARAMS = [
1537
    _PInstanceName,
1538
    _PShutdownTimeout,
1539
    # TODO: Rename target_node as it changes meaning for different export modes
1540
    # (e.g. "destination")
1541
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1542
     "Destination information, depends on export mode"),
1543
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1544
    ("remove_instance", False, ht.TBool,
1545
     "Whether to remove instance after export"),
1546
    ("ignore_remove_failures", False, ht.TBool,
1547
     "Whether to ignore failures while removing instances"),
1548
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1549
     "Export mode"),
1550
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1551
     "Name of X509 key (remote export only)"),
1552
    ("destination_x509_ca", None, ht.TMaybeString,
1553
     "Destination X509 CA (remote export only)"),
1554
    ]
1555

    
1556

    
1557
class OpBackupRemove(OpCode):
1558
  """Remove an instance's export."""
1559
  OP_DSC_FIELD = "instance_name"
1560
  OP_PARAMS = [
1561
    _PInstanceName,
1562
    ]
1563

    
1564

    
1565
# Tags opcodes
1566
class OpTagsGet(OpCode):
1567
  """Returns the tags of the given object."""
1568
  OP_DSC_FIELD = "name"
1569
  OP_PARAMS = [
1570
    _PTagKind,
1571
    # Name is only meaningful for nodes and instances
1572
    ("name", ht.NoDefault, ht.TMaybeString, None),
1573
    ]
1574

    
1575

    
1576
class OpTagsSearch(OpCode):
1577
  """Searches the tags in the cluster for a given pattern."""
1578
  OP_DSC_FIELD = "pattern"
1579
  OP_PARAMS = [
1580
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1581
    ]
1582

    
1583

    
1584
class OpTagsSet(OpCode):
1585
  """Add a list of tags on a given object."""
1586
  OP_PARAMS = [
1587
    _PTagKind,
1588
    _PTags,
1589
    # Name is only meaningful for nodes and instances
1590
    ("name", ht.NoDefault, ht.TMaybeString, None),
1591
    ]
1592

    
1593

    
1594
class OpTagsDel(OpCode):
1595
  """Remove a list of tags from a given object."""
1596
  OP_PARAMS = [
1597
    _PTagKind,
1598
    _PTags,
1599
    # Name is only meaningful for nodes and instances
1600
    ("name", ht.NoDefault, ht.TMaybeString, None),
1601
    ]
1602

    
1603

    
1604
# Test opcodes
1605
class OpTestDelay(OpCode):
1606
  """Sleeps for a configured amount of time.
1607

1608
  This is used just for debugging and testing.
1609

1610
  Parameters:
1611
    - duration: the time to sleep
1612
    - on_master: if true, sleep on the master
1613
    - on_nodes: list of nodes in which to sleep
1614

1615
  If the on_master parameter is true, it will execute a sleep on the
1616
  master (before any node sleep).
1617

1618
  If the on_nodes list is not empty, it will sleep on those nodes
1619
  (after the sleep on the master, if that is enabled).
1620

1621
  As an additional feature, the case of duration < 0 will be reported
1622
  as an execution error, so this opcode can be used as a failure
1623
  generator. The case of duration == 0 will not be treated specially.
1624

1625
  """
1626
  OP_DSC_FIELD = "duration"
1627
  OP_PARAMS = [
1628
    ("duration", ht.NoDefault, ht.TNumber, None),
1629
    ("on_master", True, ht.TBool, None),
1630
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1631
    ("repeat", 0, ht.TPositiveInt, None),
1632
    ]
1633

    
1634

    
1635
class OpTestAllocator(OpCode):
1636
  """Allocator framework testing.
1637

1638
  This opcode has two modes:
1639
    - gather and return allocator input for a given mode (allocate new
1640
      or replace secondary) and a given instance definition (direction
1641
      'in')
1642
    - run a selected allocator for a given operation (as above) and
1643
      return the allocator output (direction 'out')
1644

1645
  """
1646
  OP_DSC_FIELD = "allocator"
1647
  OP_PARAMS = [
1648
    ("direction", ht.NoDefault,
1649
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1650
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1651
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1652
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1653
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1654
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1655
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1656
    ("hypervisor", None, ht.TMaybeString, None),
1657
    ("allocator", None, ht.TMaybeString, None),
1658
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1659
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1660
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1661
    ("os", None, ht.TMaybeString, None),
1662
    ("disk_template", None, ht.TMaybeString, None),
1663
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1664
     None),
1665
    ("evac_mode", None,
1666
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1667
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1668
     None),
1669
    ]
1670

    
1671

    
1672
class OpTestJqueue(OpCode):
1673
  """Utility opcode to test some aspects of the job queue.
1674

1675
  """
1676
  OP_PARAMS = [
1677
    ("notify_waitlock", False, ht.TBool, None),
1678
    ("notify_exec", False, ht.TBool, None),
1679
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1680
    ("fail", False, ht.TBool, None),
1681
    ]
1682

    
1683

    
1684
class OpTestDummy(OpCode):
1685
  """Utility opcode used by unittests.
1686

1687
  """
1688
  OP_PARAMS = [
1689
    ("result", ht.NoDefault, ht.NoType, None),
1690
    ("messages", ht.NoDefault, ht.NoType, None),
1691
    ("fail", ht.NoDefault, ht.NoType, None),
1692
    ("submit_jobs", None, ht.NoType, None),
1693
    ]
1694
  WITH_LU = False
1695

    
1696

    
1697
def _GetOpList():
1698
  """Returns list of all defined opcodes.
1699

1700
  Does not eliminate duplicates by C{OP_ID}.
1701

1702
  """
1703
  return [v for v in globals().values()
1704
          if (isinstance(v, type) and issubclass(v, OpCode) and
1705
              hasattr(v, "OP_ID") and v is not OpCode)]
1706

    
1707

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