Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ cb92e7a1

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

    
141
#: OP_ID conversion regular expression
142
_OPID_RE = re.compile("([a-z])([A-Z])")
143

    
144
#: Utility function for L{OpClusterSetParams}
145
_TestClusterOsList = ht.TOr(ht.TNone,
146
  ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
147
    ht.TMap(ht.WithDesc("GetFirstItem")(compat.fst),
148
            ht.TElemOf(constants.DDMS_VALUES)))))
149

    
150

    
151
# TODO: Generate check from constants.INIC_PARAMS_TYPES
152
#: Utility function for testing NIC definitions
153
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
154
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
155

    
156
_TSetParamsResultItemItems = [
157
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
158
  ht.Comment("new value")(ht.TAny),
159
  ]
160

    
161
_TSetParamsResult = \
162
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
163
                     ht.TItems(_TSetParamsResultItemItems)))
164

    
165
_SUMMARY_PREFIX = {
166
  "CLUSTER_": "C_",
167
  "GROUP_": "G_",
168
  "NODE_": "N_",
169
  "INSTANCE_": "I_",
170
  }
171

    
172
#: Attribute name for dependencies
173
DEPEND_ATTR = "depends"
174

    
175
#: Attribute name for comment
176
COMMENT_ATTR = "comment"
177

    
178

    
179
def _NameToId(name):
180
  """Convert an opcode class name to an OP_ID.
181

182
  @type name: string
183
  @param name: the class name, as OpXxxYyy
184
  @rtype: string
185
  @return: the name in the OP_XXXX_YYYY format
186

187
  """
188
  if not name.startswith("Op"):
189
    return None
190
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
191
  # consume any input, and hence we would just have all the elements
192
  # in the list, one by one; but it seems that split doesn't work on
193
  # non-consuming input, hence we have to process the input string a
194
  # bit
195
  name = _OPID_RE.sub(r"\1,\2", name)
196
  elems = name.split(",")
197
  return "_".join(n.upper() for n in elems)
198

    
199

    
200
def RequireFileStorage():
201
  """Checks that file storage is enabled.
202

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

206
  @raise errors.OpPrereqError: when file storage is disabled
207

208
  """
209
  if not constants.ENABLE_FILE_STORAGE:
210
    raise errors.OpPrereqError("File storage disabled at configure time",
211
                               errors.ECODE_INVAL)
212

    
213

    
214
def RequireSharedFileStorage():
215
  """Checks that shared 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 shared file storage is disabled
221

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

    
227

    
228
@ht.WithDesc("CheckFileStorage")
229
def _CheckFileStorage(value):
230
  """Ensures file storage is enabled if used.
231

232
  """
233
  if value == constants.DT_FILE:
234
    RequireFileStorage()
235
  elif value == constants.DT_SHARED_FILE:
236
    RequireSharedFileStorage()
237
  return True
238

    
239

    
240
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
241
                             _CheckFileStorage)
242

    
243

    
244
def _CheckStorageType(storage_type):
245
  """Ensure a given storage type is valid.
246

247
  """
248
  if storage_type not in constants.VALID_STORAGE_TYPES:
249
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
250
                               errors.ECODE_INVAL)
251
  if storage_type == constants.ST_FILE:
252
    RequireFileStorage()
253
  return True
254

    
255

    
256
#: Storage type parameter
257
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
258
                 "Storage type")
259

    
260

    
261
class _AutoOpParamSlots(type):
262
  """Meta class for opcode definitions.
263

264
  """
265
  def __new__(mcs, name, bases, attrs):
266
    """Called when a class should be created.
267

268
    @param mcs: The meta class
269
    @param name: Name of created class
270
    @param bases: Base classes
271
    @type attrs: dict
272
    @param attrs: Class attributes
273

274
    """
275
    assert "__slots__" not in attrs, \
276
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
277
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
278

    
279
    attrs["OP_ID"] = _NameToId(name)
280

    
281
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
282
    params = attrs.setdefault("OP_PARAMS", [])
283

    
284
    # Use parameter names as slots
285
    slots = [pname for (pname, _, _, _) in params]
286

    
287
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
288
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
289

    
290
    attrs["__slots__"] = slots
291

    
292
    return type.__new__(mcs, name, bases, attrs)
293

    
294

    
295
class BaseOpCode(object):
296
  """A simple serializable object.
297

298
  This object serves as a parent class for OpCode without any custom
299
  field handling.
300

301
  """
302
  # pylint: disable=E1101
303
  # as OP_ID is dynamically defined
304
  __metaclass__ = _AutoOpParamSlots
305

    
306
  def __init__(self, **kwargs):
307
    """Constructor for BaseOpCode.
308

309
    The constructor takes only keyword arguments and will set
310
    attributes on this object based on the passed arguments. As such,
311
    it means that you should not pass arguments which are not in the
312
    __slots__ attribute for this class.
313

314
    """
315
    slots = self._all_slots()
316
    for key in kwargs:
317
      if key not in slots:
318
        raise TypeError("Object %s doesn't support the parameter '%s'" %
319
                        (self.__class__.__name__, key))
320
      setattr(self, key, kwargs[key])
321

    
322
  def __getstate__(self):
323
    """Generic serializer.
324

325
    This method just returns the contents of the instance as a
326
    dictionary.
327

328
    @rtype:  C{dict}
329
    @return: the instance attributes and their values
330

331
    """
332
    state = {}
333
    for name in self._all_slots():
334
      if hasattr(self, name):
335
        state[name] = getattr(self, name)
336
    return state
337

    
338
  def __setstate__(self, state):
339
    """Generic unserializer.
340

341
    This method just restores from the serialized state the attributes
342
    of the current instance.
343

344
    @param state: the serialized opcode data
345
    @type state:  C{dict}
346

347
    """
348
    if not isinstance(state, dict):
349
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
350
                       type(state))
351

    
352
    for name in self._all_slots():
353
      if name not in state and hasattr(self, name):
354
        delattr(self, name)
355

    
356
    for name in state:
357
      setattr(self, name, state[name])
358

    
359
  @classmethod
360
  def _all_slots(cls):
361
    """Compute the list of all declared slots for a class.
362

363
    """
364
    slots = []
365
    for parent in cls.__mro__:
366
      slots.extend(getattr(parent, "__slots__", []))
367
    return slots
368

    
369
  @classmethod
370
  def GetAllParams(cls):
371
    """Compute list of all parameters for an opcode.
372

373
    """
374
    slots = []
375
    for parent in cls.__mro__:
376
      slots.extend(getattr(parent, "OP_PARAMS", []))
377
    return slots
378

    
379
  def Validate(self, set_defaults):
380
    """Validate opcode parameters, optionally setting default values.
381

382
    @type set_defaults: bool
383
    @param set_defaults: Whether to set default values
384
    @raise errors.OpPrereqError: When a parameter value doesn't match
385
                                 requirements
386

387
    """
388
    for (attr_name, default, test, _) in self.GetAllParams():
389
      assert test == ht.NoType or callable(test)
390

    
391
      if not hasattr(self, attr_name):
392
        if default == ht.NoDefault:
393
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
394
                                     (self.OP_ID, attr_name),
395
                                     errors.ECODE_INVAL)
396
        elif set_defaults:
397
          if callable(default):
398
            dval = default()
399
          else:
400
            dval = default
401
          setattr(self, attr_name, dval)
402

    
403
      if test == ht.NoType:
404
        # no tests here
405
        continue
406

    
407
      if set_defaults or hasattr(self, attr_name):
408
        attr_val = getattr(self, attr_name)
409
        if not test(attr_val):
410
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
411
                        self.OP_ID, attr_name, type(attr_val), attr_val)
412
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
413
                                     (self.OP_ID, attr_name),
414
                                     errors.ECODE_INVAL)
415

    
416

    
417
def _BuildJobDepCheck(relative):
418
  """Builds check for job dependencies (L{DEPEND_ATTR}).
419

420
  @type relative: bool
421
  @param relative: Whether to accept relative job IDs (negative)
422
  @rtype: callable
423

424
  """
425
  if relative:
426
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
427
  else:
428
    job_id = ht.TJobId
429

    
430
  job_dep = \
431
    ht.TAnd(ht.TIsLength(2),
432
            ht.TItems([job_id,
433
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
434

    
435
  return ht.TOr(ht.TNone, ht.TListOf(job_dep))
436

    
437

    
438
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
439

    
440
#: List of submission status and job ID as returned by C{SubmitManyJobs}
441
_TJobIdListItem = \
442
  ht.TAnd(ht.TIsLength(2),
443
          ht.TItems([ht.Comment("success")(ht.TBool),
444
                     ht.Comment("Job ID if successful, error message"
445
                                " otherwise")(ht.TOr(ht.TString,
446
                                                     ht.TJobId))]))
447
TJobIdList = ht.TListOf(_TJobIdListItem)
448

    
449
#: Result containing only list of submitted jobs
450
TJobIdListOnly = ht.TStrictDict(True, True, {
451
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
452
  })
453

    
454

    
455
class OpCode(BaseOpCode):
456
  """Abstract OpCode.
457

458
  This is the root of the actual OpCode hierarchy. All clases derived
459
  from this class should override OP_ID.
460

461
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
462
               children of this class.
463
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
464
                      string returned by Summary(); see the docstring of that
465
                      method for details).
466
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
467
                   get if not already defined, and types they must match.
468
  @cvar OP_RESULT: Callable to verify opcode result
469
  @cvar WITH_LU: Boolean that specifies whether this should be included in
470
      mcpu's dispatch table
471
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
472
                 the check steps
473
  @ivar priority: Opcode priority for queue
474

475
  """
476
  # pylint: disable=E1101
477
  # as OP_ID is dynamically defined
478
  WITH_LU = True
479
  OP_PARAMS = [
480
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
481
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
482
    ("priority", constants.OP_PRIO_DEFAULT,
483
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
484
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
485
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
486
     " job IDs can be used"),
487
    (COMMENT_ATTR, None, ht.TMaybeString,
488
     "Comment describing the purpose of the opcode"),
489
    ]
490
  OP_RESULT = None
491

    
492
  def __getstate__(self):
493
    """Specialized getstate for opcodes.
494

495
    This method adds to the state dictionary the OP_ID of the class,
496
    so that on unload we can identify the correct class for
497
    instantiating the opcode.
498

499
    @rtype:   C{dict}
500
    @return:  the state as a dictionary
501

502
    """
503
    data = BaseOpCode.__getstate__(self)
504
    data["OP_ID"] = self.OP_ID
505
    return data
506

    
507
  @classmethod
508
  def LoadOpCode(cls, data):
509
    """Generic load opcode method.
510

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

515
    @type data:  C{dict}
516
    @param data: the serialized opcode
517

518
    """
519
    if not isinstance(data, dict):
520
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
521
    if "OP_ID" not in data:
522
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
523
    op_id = data["OP_ID"]
524
    op_class = None
525
    if op_id in OP_MAPPING:
526
      op_class = OP_MAPPING[op_id]
527
    else:
528
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
529
                       op_id)
530
    op = op_class()
531
    new_data = data.copy()
532
    del new_data["OP_ID"]
533
    op.__setstate__(new_data)
534
    return op
535

    
536
  def Summary(self):
537
    """Generates a summary description of this opcode.
538

539
    The summary is the value of the OP_ID attribute (without the "OP_"
540
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
541
    defined; this field should allow to easily identify the operation
542
    (for an instance creation job, e.g., it would be the instance
543
    name).
544

545
    """
546
    assert self.OP_ID is not None and len(self.OP_ID) > 3
547
    # all OP_ID start with OP_, we remove that
548
    txt = self.OP_ID[3:]
549
    field_name = getattr(self, "OP_DSC_FIELD", None)
550
    if field_name:
551
      field_value = getattr(self, field_name, None)
552
      if isinstance(field_value, (list, tuple)):
553
        field_value = ",".join(str(i) for i in field_value)
554
      txt = "%s(%s)" % (txt, field_value)
555
    return txt
556

    
557
  def TinySummary(self):
558
    """Generates a compact summary description of the opcode.
559

560
    """
561
    assert self.OP_ID.startswith("OP_")
562

    
563
    text = self.OP_ID[3:]
564

    
565
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
566
      if text.startswith(prefix):
567
        return supplement + text[len(prefix):]
568

    
569
    return text
570

    
571

    
572
# cluster opcodes
573

    
574
class OpClusterPostInit(OpCode):
575
  """Post cluster initialization.
576

577
  This opcode does not touch the cluster at all. Its purpose is to run hooks
578
  after the cluster has been initialized.
579

580
  """
581

    
582

    
583
class OpClusterDestroy(OpCode):
584
  """Destroy the cluster.
585

586
  This opcode has no other parameters. All the state is irreversibly
587
  lost after the execution of this opcode.
588

589
  """
590

    
591

    
592
class OpClusterQuery(OpCode):
593
  """Query cluster information."""
594

    
595

    
596
class OpClusterVerify(OpCode):
597
  """Submits all jobs necessary to verify the cluster.
598

599
  """
600
  OP_PARAMS = [
601
    _PDebugSimulateErrors,
602
    _PErrorCodes,
603
    _PSkipChecks,
604
    _PVerbose,
605
    ("group_name", None, ht.TMaybeString, "Group to verify")
606
    ]
607
  OP_RESULT = TJobIdListOnly
608

    
609

    
610
class OpClusterVerifyConfig(OpCode):
611
  """Verify the cluster config.
612

613
  """
614
  OP_PARAMS = [
615
    _PDebugSimulateErrors,
616
    _PErrorCodes,
617
    _PVerbose,
618
    ]
619
  OP_RESULT = ht.TBool
620

    
621

    
622
class OpClusterVerifyGroup(OpCode):
623
  """Run verify on a node group from the cluster.
624

625
  @type skip_checks: C{list}
626
  @ivar skip_checks: steps to be skipped from the verify process; this
627
                     needs to be a subset of
628
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
629
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
630

631
  """
632
  OP_DSC_FIELD = "group_name"
633
  OP_PARAMS = [
634
    _PGroupName,
635
    _PDebugSimulateErrors,
636
    _PErrorCodes,
637
    _PSkipChecks,
638
    _PVerbose,
639
    ]
640
  OP_RESULT = ht.TBool
641

    
642

    
643
class OpClusterVerifyDisks(OpCode):
644
  """Verify the cluster disks.
645

646
  """
647
  OP_RESULT = TJobIdListOnly
648

    
649

    
650
class OpGroupVerifyDisks(OpCode):
651
  """Verifies the status of all disks in a node group.
652

653
  Result: a tuple of three elements:
654
    - dict of node names with issues (values: error msg)
655
    - list of instances with degraded disks (that should be activated)
656
    - dict of instances with missing logical volumes (values: (node, vol)
657
      pairs with details about the missing volumes)
658

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

664
  Note that only instances that are drbd-based are taken into
665
  consideration. This might need to be revisited in the future.
666

667
  """
668
  OP_DSC_FIELD = "group_name"
669
  OP_PARAMS = [
670
    _PGroupName,
671
    ]
672
  OP_RESULT = \
673
    ht.TAnd(ht.TIsLength(3),
674
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
675
                       ht.TListOf(ht.TString),
676
                       ht.TDictOf(ht.TString,
677
                                  ht.TListOf(ht.TListOf(ht.TString)))]))
678

    
679

    
680
class OpClusterRepairDiskSizes(OpCode):
681
  """Verify the disk sizes of the instances and fixes configuration
682
  mimatches.
683

684
  Parameters: optional instances list, in case we want to restrict the
685
  checks to only a subset of the instances.
686

687
  Result: a list of tuples, (instance, disk, new-size) for changed
688
  configurations.
689

690
  In normal operation, the list should be empty.
691

692
  @type instances: list
693
  @ivar instances: the list of instances to check, or empty for all instances
694

695
  """
696
  OP_PARAMS = [
697
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
698
    ]
699

    
700

    
701
class OpClusterConfigQuery(OpCode):
702
  """Query cluster configuration values."""
703
  OP_PARAMS = [
704
    _POutputFields
705
    ]
706

    
707

    
708
class OpClusterRename(OpCode):
709
  """Rename the cluster.
710

711
  @type name: C{str}
712
  @ivar name: The new name of the cluster. The name and/or the master IP
713
              address will be changed to match the new name and its IP
714
              address.
715

716
  """
717
  OP_DSC_FIELD = "name"
718
  OP_PARAMS = [
719
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
720
    ]
721

    
722

    
723
class OpClusterSetParams(OpCode):
724
  """Change the parameters of the cluster.
725

726
  @type vg_name: C{str} or C{None}
727
  @ivar vg_name: The new volume group name or None to disable LVM usage.
728

729
  """
730
  OP_PARAMS = [
731
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
732
    ("enabled_hypervisors", None,
733
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
734
            ht.TNone),
735
     "List of enabled hypervisors"),
736
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
737
                              ht.TNone),
738
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
739
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
740
     "Cluster-wide backend parameter defaults"),
741
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
742
                            ht.TNone),
743
     "Cluster-wide per-OS hypervisor parameter defaults"),
744
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
745
                              ht.TNone),
746
     "Cluster-wide OS parameter defaults"),
747
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
748
     "Master candidate pool size"),
749
    ("uid_pool", None, ht.NoType,
750
     "Set UID pool, must be list of lists describing UID ranges (two items,"
751
     " start and end inclusive)"),
752
    ("add_uids", None, ht.NoType,
753
     "Extend UID pool, must be list of lists describing UID ranges (two"
754
     " items, start and end inclusive) to be added"),
755
    ("remove_uids", None, ht.NoType,
756
     "Shrink UID pool, must be list of lists describing UID ranges (two"
757
     " items, start and end inclusive) to be removed"),
758
    ("maintain_node_health", None, ht.TMaybeBool,
759
     "Whether to automatically maintain node health"),
760
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
761
     "Whether to wipe disks before allocating them to instances"),
762
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
763
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
764
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
765
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
766
     "Default iallocator for cluster"),
767
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
768
     "Master network device"),
769
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
770
     "List of reserved LVs"),
771
    ("hidden_os", None, _TestClusterOsList,
772
     "Modify list of hidden operating systems. Each modification must have"
773
     " two items, the operation and the OS name. The operation can be"
774
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
775
    ("blacklisted_os", None, _TestClusterOsList,
776
     "Modify list of blacklisted operating systems. Each modification must have"
777
     " two items, the operation and the OS name. The operation can be"
778
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
779
    ]
780

    
781

    
782
class OpClusterRedistConf(OpCode):
783
  """Force a full push of the cluster configuration.
784

785
  """
786

    
787

    
788
class OpClusterActivateMasterIp(OpCode):
789
  """Activate the master IP on the master node.
790

791
  """
792

    
793

    
794
class OpClusterDeactivateMasterIp(OpCode):
795
  """Deactivate the master IP on the master node.
796

797
  """
798

    
799

    
800
class OpQuery(OpCode):
801
  """Query for resources/items.
802

803
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
804
  @ivar fields: List of fields to retrieve
805
  @ivar filter: Query filter
806

807
  """
808
  OP_DSC_FIELD = "what"
809
  OP_PARAMS = [
810
    _PQueryWhat,
811
    _PUseLocking,
812
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
813
     "Requested fields"),
814
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
815
     "Query filter"),
816
    ]
817

    
818

    
819
class OpQueryFields(OpCode):
820
  """Query for available resource/item fields.
821

822
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
823
  @ivar fields: List of fields to retrieve
824

825
  """
826
  OP_DSC_FIELD = "what"
827
  OP_PARAMS = [
828
    _PQueryWhat,
829
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
830
     "Requested fields; if not given, all are returned"),
831
    ]
832

    
833

    
834
class OpOobCommand(OpCode):
835
  """Interact with OOB."""
836
  OP_PARAMS = [
837
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
838
     "List of nodes to run the OOB command against"),
839
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
840
     "OOB command to be run"),
841
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
842
     "Timeout before the OOB helper will be terminated"),
843
    ("ignore_status", False, ht.TBool,
844
     "Ignores the node offline status for power off"),
845
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
846
     "Time in seconds to wait between powering on nodes"),
847
    ]
848

    
849

    
850
# node opcodes
851

    
852
class OpNodeRemove(OpCode):
853
  """Remove a node.
854

855
  @type node_name: C{str}
856
  @ivar node_name: The name of the node to remove. If the node still has
857
                   instances on it, the operation will fail.
858

859
  """
860
  OP_DSC_FIELD = "node_name"
861
  OP_PARAMS = [
862
    _PNodeName,
863
    ]
864

    
865

    
866
class OpNodeAdd(OpCode):
867
  """Add a node to the cluster.
868

869
  @type node_name: C{str}
870
  @ivar node_name: The name of the node to add. This can be a short name,
871
                   but it will be expanded to the FQDN.
872
  @type primary_ip: IP address
873
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
874
                    opcode is submitted, but will be filled during the node
875
                    add (so it will be visible in the job query).
876
  @type secondary_ip: IP address
877
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
878
                      if the cluster has been initialized in 'dual-network'
879
                      mode, otherwise it must not be given.
880
  @type readd: C{bool}
881
  @ivar readd: Whether to re-add an existing node to the cluster. If
882
               this is not passed, then the operation will abort if the node
883
               name is already in the cluster; use this parameter to 'repair'
884
               a node that had its configuration broken, or was reinstalled
885
               without removal from the cluster.
886
  @type group: C{str}
887
  @ivar group: The node group to which this node will belong.
888
  @type vm_capable: C{bool}
889
  @ivar vm_capable: The vm_capable node attribute
890
  @type master_capable: C{bool}
891
  @ivar master_capable: The master_capable node attribute
892

893
  """
894
  OP_DSC_FIELD = "node_name"
895
  OP_PARAMS = [
896
    _PNodeName,
897
    ("primary_ip", None, ht.NoType, "Primary IP address"),
898
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
899
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
900
    ("group", None, ht.TMaybeString, "Initial node group"),
901
    ("master_capable", None, ht.TMaybeBool,
902
     "Whether node can become master or master candidate"),
903
    ("vm_capable", None, ht.TMaybeBool,
904
     "Whether node can host instances"),
905
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
906
    ]
907

    
908

    
909
class OpNodeQuery(OpCode):
910
  """Compute the list of nodes."""
911
  OP_PARAMS = [
912
    _POutputFields,
913
    _PUseLocking,
914
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
915
     "Empty list to query all nodes, node names otherwise"),
916
    ]
917

    
918

    
919
class OpNodeQueryvols(OpCode):
920
  """Get list of volumes on node."""
921
  OP_PARAMS = [
922
    _POutputFields,
923
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
924
     "Empty list to query all nodes, node names otherwise"),
925
    ]
926

    
927

    
928
class OpNodeQueryStorage(OpCode):
929
  """Get information on storage for node(s)."""
930
  OP_PARAMS = [
931
    _POutputFields,
932
    _PStorageType,
933
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
934
    ("name", None, ht.TMaybeString, "Storage name"),
935
    ]
936

    
937

    
938
class OpNodeModifyStorage(OpCode):
939
  """Modifies the properies of a storage unit"""
940
  OP_PARAMS = [
941
    _PNodeName,
942
    _PStorageType,
943
    _PStorageName,
944
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
945
    ]
946

    
947

    
948
class OpRepairNodeStorage(OpCode):
949
  """Repairs the volume group on a node."""
950
  OP_DSC_FIELD = "node_name"
951
  OP_PARAMS = [
952
    _PNodeName,
953
    _PStorageType,
954
    _PStorageName,
955
    _PIgnoreConsistency,
956
    ]
957

    
958

    
959
class OpNodeSetParams(OpCode):
960
  """Change the parameters of a node."""
961
  OP_DSC_FIELD = "node_name"
962
  OP_PARAMS = [
963
    _PNodeName,
964
    _PForce,
965
    ("master_candidate", None, ht.TMaybeBool,
966
     "Whether the node should become a master candidate"),
967
    ("offline", None, ht.TMaybeBool,
968
     "Whether the node should be marked as offline"),
969
    ("drained", None, ht.TMaybeBool,
970
     "Whether the node should be marked as drained"),
971
    ("auto_promote", False, ht.TBool,
972
     "Whether node(s) should be promoted to master candidate if necessary"),
973
    ("master_capable", None, ht.TMaybeBool,
974
     "Denote whether node can become master or master candidate"),
975
    ("vm_capable", None, ht.TMaybeBool,
976
     "Denote whether node can host instances"),
977
    ("secondary_ip", None, ht.TMaybeString,
978
     "Change node's secondary IP address"),
979
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
980
    ("powered", None, ht.TMaybeBool,
981
     "Whether the node should be marked as powered"),
982
    ]
983
  OP_RESULT = _TSetParamsResult
984

    
985

    
986
class OpNodePowercycle(OpCode):
987
  """Tries to powercycle a node."""
988
  OP_DSC_FIELD = "node_name"
989
  OP_PARAMS = [
990
    _PNodeName,
991
    _PForce,
992
    ]
993

    
994

    
995
class OpNodeMigrate(OpCode):
996
  """Migrate all instances from a node."""
997
  OP_DSC_FIELD = "node_name"
998
  OP_PARAMS = [
999
    _PNodeName,
1000
    _PMigrationMode,
1001
    _PMigrationLive,
1002
    _PMigrationTargetNode,
1003
    ("iallocator", None, ht.TMaybeString,
1004
     "Iallocator for deciding the target node for shared-storage instances"),
1005
    ]
1006
  OP_RESULT = TJobIdListOnly
1007

    
1008

    
1009
class OpNodeEvacuate(OpCode):
1010
  """Evacuate instances off a number of nodes."""
1011
  OP_DSC_FIELD = "node_name"
1012
  OP_PARAMS = [
1013
    _PEarlyRelease,
1014
    _PNodeName,
1015
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1016
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1017
    ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1018
     "Node evacuation mode"),
1019
    ]
1020
  OP_RESULT = TJobIdListOnly
1021

    
1022

    
1023
# instance opcodes
1024

    
1025
class OpInstanceCreate(OpCode):
1026
  """Create an instance.
1027

1028
  @ivar instance_name: Instance name
1029
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1030
  @ivar source_handshake: Signed handshake from source (remote import only)
1031
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1032
  @ivar source_instance_name: Previous name of instance (remote import only)
1033
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1034
    (remote import only)
1035

1036
  """
1037
  OP_DSC_FIELD = "instance_name"
1038
  OP_PARAMS = [
1039
    _PInstanceName,
1040
    _PForceVariant,
1041
    _PWaitForSync,
1042
    _PNameCheck,
1043
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1044
    ("disks", ht.NoDefault,
1045
     # TODO: Generate check from constants.IDISK_PARAMS_TYPES
1046
     ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
1047
                           ht.TOr(ht.TNonEmptyString, ht.TInt))),
1048
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1049
     " each disk definition must contain a ``%s`` value and"
1050
     " can contain an optional ``%s`` value denoting the disk access mode"
1051
     " (%s)" %
1052
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1053
      constants.IDISK_MODE,
1054
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1055
    ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
1056
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1057
     "Driver for file-backed disks"),
1058
    ("file_storage_dir", None, ht.TMaybeString,
1059
     "Directory for storing file-backed disks"),
1060
    ("hvparams", ht.EmptyDict, ht.TDict,
1061
     "Hypervisor parameters for instance, hypervisor-dependent"),
1062
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1063
    ("iallocator", None, ht.TMaybeString,
1064
     "Iallocator for deciding which node(s) to use"),
1065
    ("identify_defaults", False, ht.TBool,
1066
     "Reset instance parameters to default if equal"),
1067
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1068
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1069
     "Instance creation mode"),
1070
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1071
     "List of NIC (network interface) definitions, for example"
1072
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1073
     " contain the optional values %s" %
1074
     (constants.INIC_IP,
1075
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1076
    ("no_install", None, ht.TMaybeBool,
1077
     "Do not install the OS (will disable automatic start)"),
1078
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1079
    ("os_type", None, ht.TMaybeString, "Operating system"),
1080
    ("pnode", None, ht.TMaybeString, "Primary node"),
1081
    ("snode", None, ht.TMaybeString, "Secondary node"),
1082
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1083
     "Signed handshake from source (remote import only)"),
1084
    ("source_instance_name", None, ht.TMaybeString,
1085
     "Source instance name (remote import only)"),
1086
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1087
     ht.TPositiveInt,
1088
     "How long source instance was given to shut down (remote import only)"),
1089
    ("source_x509_ca", None, ht.TMaybeString,
1090
     "Source X509 CA in PEM format (remote import only)"),
1091
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1092
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1093
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1094
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1095
    ]
1096
  OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1097

    
1098

    
1099
class OpInstanceReinstall(OpCode):
1100
  """Reinstall an instance's OS."""
1101
  OP_DSC_FIELD = "instance_name"
1102
  OP_PARAMS = [
1103
    _PInstanceName,
1104
    _PForceVariant,
1105
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1106
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1107
    ]
1108

    
1109

    
1110
class OpInstanceRemove(OpCode):
1111
  """Remove an instance."""
1112
  OP_DSC_FIELD = "instance_name"
1113
  OP_PARAMS = [
1114
    _PInstanceName,
1115
    _PShutdownTimeout,
1116
    ("ignore_failures", False, ht.TBool,
1117
     "Whether to ignore failures during removal"),
1118
    ]
1119

    
1120

    
1121
class OpInstanceRename(OpCode):
1122
  """Rename an instance."""
1123
  OP_PARAMS = [
1124
    _PInstanceName,
1125
    _PNameCheck,
1126
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1127
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1128
    ]
1129
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1130

    
1131

    
1132
class OpInstanceStartup(OpCode):
1133
  """Startup an instance."""
1134
  OP_DSC_FIELD = "instance_name"
1135
  OP_PARAMS = [
1136
    _PInstanceName,
1137
    _PForce,
1138
    _PIgnoreOfflineNodes,
1139
    ("hvparams", ht.EmptyDict, ht.TDict,
1140
     "Temporary hypervisor parameters, hypervisor-dependent"),
1141
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1142
    _PNoRemember,
1143
    _PStartupPaused,
1144
    ]
1145

    
1146

    
1147
class OpInstanceShutdown(OpCode):
1148
  """Shutdown an instance."""
1149
  OP_DSC_FIELD = "instance_name"
1150
  OP_PARAMS = [
1151
    _PInstanceName,
1152
    _PIgnoreOfflineNodes,
1153
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1154
     "How long to wait for instance to shut down"),
1155
    _PNoRemember,
1156
    ]
1157

    
1158

    
1159
class OpInstanceReboot(OpCode):
1160
  """Reboot an instance."""
1161
  OP_DSC_FIELD = "instance_name"
1162
  OP_PARAMS = [
1163
    _PInstanceName,
1164
    _PShutdownTimeout,
1165
    ("ignore_secondaries", False, ht.TBool,
1166
     "Whether to start the instance even if secondary disks are failing"),
1167
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1168
     "How to reboot instance"),
1169
    ]
1170

    
1171

    
1172
class OpInstanceReplaceDisks(OpCode):
1173
  """Replace the disks of an instance."""
1174
  OP_DSC_FIELD = "instance_name"
1175
  OP_PARAMS = [
1176
    _PInstanceName,
1177
    _PEarlyRelease,
1178
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1179
     "Replacement mode"),
1180
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1181
     "Disk indexes"),
1182
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1183
    ("iallocator", None, ht.TMaybeString,
1184
     "Iallocator for deciding new secondary node"),
1185
    ]
1186

    
1187

    
1188
class OpInstanceFailover(OpCode):
1189
  """Failover an instance."""
1190
  OP_DSC_FIELD = "instance_name"
1191
  OP_PARAMS = [
1192
    _PInstanceName,
1193
    _PShutdownTimeout,
1194
    _PIgnoreConsistency,
1195
    _PMigrationTargetNode,
1196
    ("iallocator", None, ht.TMaybeString,
1197
     "Iallocator for deciding the target node for shared-storage instances"),
1198
    ]
1199

    
1200

    
1201
class OpInstanceMigrate(OpCode):
1202
  """Migrate an instance.
1203

1204
  This migrates (without shutting down an instance) to its secondary
1205
  node.
1206

1207
  @ivar instance_name: the name of the instance
1208
  @ivar mode: the migration mode (live, non-live or None for auto)
1209

1210
  """
1211
  OP_DSC_FIELD = "instance_name"
1212
  OP_PARAMS = [
1213
    _PInstanceName,
1214
    _PMigrationMode,
1215
    _PMigrationLive,
1216
    _PMigrationTargetNode,
1217
    ("cleanup", False, ht.TBool,
1218
     "Whether a previously failed migration should be cleaned up"),
1219
    ("iallocator", None, ht.TMaybeString,
1220
     "Iallocator for deciding the target node for shared-storage instances"),
1221
    ("allow_failover", False, ht.TBool,
1222
     "Whether we can fallback to failover if migration is not possible"),
1223
    ]
1224

    
1225

    
1226
class OpInstanceMove(OpCode):
1227
  """Move an instance.
1228

1229
  This move (with shutting down an instance and data copying) to an
1230
  arbitrary node.
1231

1232
  @ivar instance_name: the name of the instance
1233
  @ivar target_node: the destination node
1234

1235
  """
1236
  OP_DSC_FIELD = "instance_name"
1237
  OP_PARAMS = [
1238
    _PInstanceName,
1239
    _PShutdownTimeout,
1240
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1241
    _PIgnoreConsistency,
1242
    ]
1243

    
1244

    
1245
class OpInstanceConsole(OpCode):
1246
  """Connect to an instance's console."""
1247
  OP_DSC_FIELD = "instance_name"
1248
  OP_PARAMS = [
1249
    _PInstanceName
1250
    ]
1251

    
1252

    
1253
class OpInstanceActivateDisks(OpCode):
1254
  """Activate an instance's disks."""
1255
  OP_DSC_FIELD = "instance_name"
1256
  OP_PARAMS = [
1257
    _PInstanceName,
1258
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1259
    ]
1260

    
1261

    
1262
class OpInstanceDeactivateDisks(OpCode):
1263
  """Deactivate an instance's disks."""
1264
  OP_DSC_FIELD = "instance_name"
1265
  OP_PARAMS = [
1266
    _PInstanceName,
1267
    _PForce,
1268
    ]
1269

    
1270

    
1271
class OpInstanceRecreateDisks(OpCode):
1272
  """Deactivate an instance's disks."""
1273
  OP_DSC_FIELD = "instance_name"
1274
  OP_PARAMS = [
1275
    _PInstanceName,
1276
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1277
     "List of disk indexes"),
1278
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1279
     "New instance nodes, if relocation is desired"),
1280
    ]
1281

    
1282

    
1283
class OpInstanceQuery(OpCode):
1284
  """Compute the list of instances."""
1285
  OP_PARAMS = [
1286
    _POutputFields,
1287
    _PUseLocking,
1288
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1289
     "Empty list to query all instances, instance names otherwise"),
1290
    ]
1291

    
1292

    
1293
class OpInstanceQueryData(OpCode):
1294
  """Compute the run-time status of instances."""
1295
  OP_PARAMS = [
1296
    _PUseLocking,
1297
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1298
     "Instance names"),
1299
    ("static", False, ht.TBool,
1300
     "Whether to only return configuration data without querying"
1301
     " nodes"),
1302
    ]
1303

    
1304

    
1305
class OpInstanceSetParams(OpCode):
1306
  """Change the parameters of an instance."""
1307
  OP_DSC_FIELD = "instance_name"
1308
  OP_PARAMS = [
1309
    _PInstanceName,
1310
    _PForce,
1311
    _PForceVariant,
1312
    # TODO: Use _TestNicDef
1313
    ("nics", ht.EmptyList, ht.TList,
1314
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1315
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1316
     " ``%s`` to remove the last NIC or a number to modify the settings"
1317
     " of the NIC with that index." %
1318
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1319
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1320
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1321
    ("hvparams", ht.EmptyDict, ht.TDict,
1322
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1323
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1324
     "Disk template for instance"),
1325
    ("remote_node", None, ht.TMaybeString,
1326
     "Secondary node (used when changing disk template)"),
1327
    ("os_name", None, ht.TMaybeString,
1328
     "Change instance's OS name. Does not reinstall the instance."),
1329
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1330
    ("wait_for_sync", True, ht.TBool,
1331
     "Whether to wait for the disk to synchronize, when changing template"),
1332
    ]
1333
  OP_RESULT = _TSetParamsResult
1334

    
1335

    
1336
class OpInstanceGrowDisk(OpCode):
1337
  """Grow a disk of an instance."""
1338
  OP_DSC_FIELD = "instance_name"
1339
  OP_PARAMS = [
1340
    _PInstanceName,
1341
    _PWaitForSync,
1342
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1343
    ("amount", ht.NoDefault, ht.TInt,
1344
     "Amount of disk space to add (megabytes)"),
1345
    ]
1346

    
1347

    
1348
class OpInstanceChangeGroup(OpCode):
1349
  """Moves an instance to another node group."""
1350
  OP_DSC_FIELD = "instance_name"
1351
  OP_PARAMS = [
1352
    _PInstanceName,
1353
    _PEarlyRelease,
1354
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1355
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1356
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1357
    ]
1358
  OP_RESULT = TJobIdListOnly
1359

    
1360

    
1361
# Node group opcodes
1362

    
1363
class OpGroupAdd(OpCode):
1364
  """Add a node group to the cluster."""
1365
  OP_DSC_FIELD = "group_name"
1366
  OP_PARAMS = [
1367
    _PGroupName,
1368
    _PNodeGroupAllocPolicy,
1369
    _PGroupNodeParams,
1370
    ]
1371

    
1372

    
1373
class OpGroupAssignNodes(OpCode):
1374
  """Assign nodes to a node group."""
1375
  OP_DSC_FIELD = "group_name"
1376
  OP_PARAMS = [
1377
    _PGroupName,
1378
    _PForce,
1379
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1380
     "List of nodes to assign"),
1381
    ]
1382

    
1383

    
1384
class OpGroupQuery(OpCode):
1385
  """Compute the list of node groups."""
1386
  OP_PARAMS = [
1387
    _POutputFields,
1388
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1389
     "Empty list to query all groups, group names otherwise"),
1390
    ]
1391

    
1392

    
1393
class OpGroupSetParams(OpCode):
1394
  """Change the parameters of a node group."""
1395
  OP_DSC_FIELD = "group_name"
1396
  OP_PARAMS = [
1397
    _PGroupName,
1398
    _PNodeGroupAllocPolicy,
1399
    _PGroupNodeParams,
1400
    ]
1401
  OP_RESULT = _TSetParamsResult
1402

    
1403

    
1404
class OpGroupRemove(OpCode):
1405
  """Remove a node group from the cluster."""
1406
  OP_DSC_FIELD = "group_name"
1407
  OP_PARAMS = [
1408
    _PGroupName,
1409
    ]
1410

    
1411

    
1412
class OpGroupRename(OpCode):
1413
  """Rename a node group in the cluster."""
1414
  OP_PARAMS = [
1415
    _PGroupName,
1416
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1417
    ]
1418
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1419

    
1420

    
1421
class OpGroupEvacuate(OpCode):
1422
  """Evacuate a node group in the cluster."""
1423
  OP_DSC_FIELD = "group_name"
1424
  OP_PARAMS = [
1425
    _PGroupName,
1426
    _PEarlyRelease,
1427
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1428
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1429
     "Destination group names or UUIDs"),
1430
    ]
1431
  OP_RESULT = TJobIdListOnly
1432

    
1433

    
1434
# OS opcodes
1435
class OpOsDiagnose(OpCode):
1436
  """Compute the list of guest operating systems."""
1437
  OP_PARAMS = [
1438
    _POutputFields,
1439
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1440
     "Which operating systems to diagnose"),
1441
    ]
1442

    
1443

    
1444
# Exports opcodes
1445
class OpBackupQuery(OpCode):
1446
  """Compute the list of exported images."""
1447
  OP_PARAMS = [
1448
    _PUseLocking,
1449
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1450
     "Empty list to query all nodes, node names otherwise"),
1451
    ]
1452

    
1453

    
1454
class OpBackupPrepare(OpCode):
1455
  """Prepares an instance export.
1456

1457
  @ivar instance_name: Instance name
1458
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1459

1460
  """
1461
  OP_DSC_FIELD = "instance_name"
1462
  OP_PARAMS = [
1463
    _PInstanceName,
1464
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1465
     "Export mode"),
1466
    ]
1467

    
1468

    
1469
class OpBackupExport(OpCode):
1470
  """Export an instance.
1471

1472
  For local exports, the export destination is the node name. For remote
1473
  exports, the export destination is a list of tuples, each consisting of
1474
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1475
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1476
  destination X509 CA must be a signed certificate.
1477

1478
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1479
  @ivar target_node: Export destination
1480
  @ivar x509_key_name: X509 key to use (remote export only)
1481
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1482
                             only)
1483

1484
  """
1485
  OP_DSC_FIELD = "instance_name"
1486
  OP_PARAMS = [
1487
    _PInstanceName,
1488
    _PShutdownTimeout,
1489
    # TODO: Rename target_node as it changes meaning for different export modes
1490
    # (e.g. "destination")
1491
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1492
     "Destination information, depends on export mode"),
1493
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1494
    ("remove_instance", False, ht.TBool,
1495
     "Whether to remove instance after export"),
1496
    ("ignore_remove_failures", False, ht.TBool,
1497
     "Whether to ignore failures while removing instances"),
1498
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1499
     "Export mode"),
1500
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1501
     "Name of X509 key (remote export only)"),
1502
    ("destination_x509_ca", None, ht.TMaybeString,
1503
     "Destination X509 CA (remote export only)"),
1504
    ]
1505

    
1506

    
1507
class OpBackupRemove(OpCode):
1508
  """Remove an instance's export."""
1509
  OP_DSC_FIELD = "instance_name"
1510
  OP_PARAMS = [
1511
    _PInstanceName,
1512
    ]
1513

    
1514

    
1515
# Tags opcodes
1516
class OpTagsGet(OpCode):
1517
  """Returns the tags of the given object."""
1518
  OP_DSC_FIELD = "name"
1519
  OP_PARAMS = [
1520
    _PTagKind,
1521
    # Name is only meaningful for nodes and instances
1522
    ("name", ht.NoDefault, ht.TMaybeString, None),
1523
    ]
1524

    
1525

    
1526
class OpTagsSearch(OpCode):
1527
  """Searches the tags in the cluster for a given pattern."""
1528
  OP_DSC_FIELD = "pattern"
1529
  OP_PARAMS = [
1530
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1531
    ]
1532

    
1533

    
1534
class OpTagsSet(OpCode):
1535
  """Add a list of tags on a given object."""
1536
  OP_PARAMS = [
1537
    _PTagKind,
1538
    _PTags,
1539
    # Name is only meaningful for nodes and instances
1540
    ("name", ht.NoDefault, ht.TMaybeString, None),
1541
    ]
1542

    
1543

    
1544
class OpTagsDel(OpCode):
1545
  """Remove a list of tags from a given object."""
1546
  OP_PARAMS = [
1547
    _PTagKind,
1548
    _PTags,
1549
    # Name is only meaningful for nodes and instances
1550
    ("name", ht.NoDefault, ht.TMaybeString, None),
1551
    ]
1552

    
1553

    
1554
# Test opcodes
1555
class OpTestDelay(OpCode):
1556
  """Sleeps for a configured amount of time.
1557

1558
  This is used just for debugging and testing.
1559

1560
  Parameters:
1561
    - duration: the time to sleep
1562
    - on_master: if true, sleep on the master
1563
    - on_nodes: list of nodes in which to sleep
1564

1565
  If the on_master parameter is true, it will execute a sleep on the
1566
  master (before any node sleep).
1567

1568
  If the on_nodes list is not empty, it will sleep on those nodes
1569
  (after the sleep on the master, if that is enabled).
1570

1571
  As an additional feature, the case of duration < 0 will be reported
1572
  as an execution error, so this opcode can be used as a failure
1573
  generator. The case of duration == 0 will not be treated specially.
1574

1575
  """
1576
  OP_DSC_FIELD = "duration"
1577
  OP_PARAMS = [
1578
    ("duration", ht.NoDefault, ht.TNumber, None),
1579
    ("on_master", True, ht.TBool, None),
1580
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1581
    ("repeat", 0, ht.TPositiveInt, None),
1582
    ]
1583

    
1584

    
1585
class OpTestAllocator(OpCode):
1586
  """Allocator framework testing.
1587

1588
  This opcode has two modes:
1589
    - gather and return allocator input for a given mode (allocate new
1590
      or replace secondary) and a given instance definition (direction
1591
      'in')
1592
    - run a selected allocator for a given operation (as above) and
1593
      return the allocator output (direction 'out')
1594

1595
  """
1596
  OP_DSC_FIELD = "allocator"
1597
  OP_PARAMS = [
1598
    ("direction", ht.NoDefault,
1599
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1600
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1601
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1602
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1603
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1604
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1605
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1606
    ("hypervisor", None, ht.TMaybeString, None),
1607
    ("allocator", None, ht.TMaybeString, None),
1608
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1609
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1610
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1611
    ("os", None, ht.TMaybeString, None),
1612
    ("disk_template", None, ht.TMaybeString, None),
1613
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1614
     None),
1615
    ("evac_mode", None,
1616
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1617
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1618
     None),
1619
    ]
1620

    
1621

    
1622
class OpTestJqueue(OpCode):
1623
  """Utility opcode to test some aspects of the job queue.
1624

1625
  """
1626
  OP_PARAMS = [
1627
    ("notify_waitlock", False, ht.TBool, None),
1628
    ("notify_exec", False, ht.TBool, None),
1629
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1630
    ("fail", False, ht.TBool, None),
1631
    ]
1632

    
1633

    
1634
class OpTestDummy(OpCode):
1635
  """Utility opcode used by unittests.
1636

1637
  """
1638
  OP_PARAMS = [
1639
    ("result", ht.NoDefault, ht.NoType, None),
1640
    ("messages", ht.NoDefault, ht.NoType, None),
1641
    ("fail", ht.NoDefault, ht.NoType, None),
1642
    ("submit_jobs", None, ht.NoType, None),
1643
    ]
1644
  WITH_LU = False
1645

    
1646

    
1647
def _GetOpList():
1648
  """Returns list of all defined opcodes.
1649

1650
  Does not eliminate duplicates by C{OP_ID}.
1651

1652
  """
1653
  return [v for v in globals().values()
1654
          if (isinstance(v, type) and issubclass(v, OpCode) and
1655
              hasattr(v, "OP_ID") and v is not OpCode)]
1656

    
1657

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