Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ bdfd7802

History | View | Annotate | Download (49.4 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-msg=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
_SUMMARY_PREFIX = {
157
  "CLUSTER_": "C_",
158
  "GROUP_": "G_",
159
  "NODE_": "N_",
160
  "INSTANCE_": "I_",
161
  }
162

    
163
#: Attribute name for dependencies
164
DEPEND_ATTR = "depends"
165

    
166
#: Attribute name for comment
167
COMMENT_ATTR = "comment"
168

    
169

    
170
def _NameToId(name):
171
  """Convert an opcode class name to an OP_ID.
172

173
  @type name: string
174
  @param name: the class name, as OpXxxYyy
175
  @rtype: string
176
  @return: the name in the OP_XXXX_YYYY format
177

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

    
190

    
191
def RequireFileStorage():
192
  """Checks that file storage is enabled.
193

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

197
  @raise errors.OpPrereqError: when file storage is disabled
198

199
  """
200
  if not constants.ENABLE_FILE_STORAGE:
201
    raise errors.OpPrereqError("File storage disabled at configure time",
202
                               errors.ECODE_INVAL)
203

    
204

    
205
def RequireSharedFileStorage():
206
  """Checks that shared file storage is enabled.
207

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

211
  @raise errors.OpPrereqError: when shared file storage is disabled
212

213
  """
214
  if not constants.ENABLE_SHARED_FILE_STORAGE:
215
    raise errors.OpPrereqError("Shared file storage disabled at"
216
                               " configure time", errors.ECODE_INVAL)
217

    
218

    
219
@ht.WithDesc("CheckFileStorage")
220
def _CheckFileStorage(value):
221
  """Ensures file storage is enabled if used.
222

223
  """
224
  if value == constants.DT_FILE:
225
    RequireFileStorage()
226
  elif value == constants.DT_SHARED_FILE:
227
    RequireSharedFileStorage()
228
  return True
229

    
230

    
231
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
232
                             _CheckFileStorage)
233

    
234

    
235
def _CheckStorageType(storage_type):
236
  """Ensure a given storage type is valid.
237

238
  """
239
  if storage_type not in constants.VALID_STORAGE_TYPES:
240
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
241
                               errors.ECODE_INVAL)
242
  if storage_type == constants.ST_FILE:
243
    RequireFileStorage()
244
  return True
245

    
246

    
247
#: Storage type parameter
248
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
249
                 "Storage type")
250

    
251

    
252
class _AutoOpParamSlots(type):
253
  """Meta class for opcode definitions.
254

255
  """
256
  def __new__(mcs, name, bases, attrs):
257
    """Called when a class should be created.
258

259
    @param mcs: The meta class
260
    @param name: Name of created class
261
    @param bases: Base classes
262
    @type attrs: dict
263
    @param attrs: Class attributes
264

265
    """
266
    assert "__slots__" not in attrs, \
267
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
268
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
269

    
270
    attrs["OP_ID"] = _NameToId(name)
271

    
272
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
273
    params = attrs.setdefault("OP_PARAMS", [])
274

    
275
    # Use parameter names as slots
276
    slots = [pname for (pname, _, _, _) in params]
277

    
278
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
279
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
280

    
281
    attrs["__slots__"] = slots
282

    
283
    return type.__new__(mcs, name, bases, attrs)
284

    
285

    
286
class BaseOpCode(object):
287
  """A simple serializable object.
288

289
  This object serves as a parent class for OpCode without any custom
290
  field handling.
291

292
  """
293
  # pylint: disable-msg=E1101
294
  # as OP_ID is dynamically defined
295
  __metaclass__ = _AutoOpParamSlots
296

    
297
  def __init__(self, **kwargs):
298
    """Constructor for BaseOpCode.
299

300
    The constructor takes only keyword arguments and will set
301
    attributes on this object based on the passed arguments. As such,
302
    it means that you should not pass arguments which are not in the
303
    __slots__ attribute for this class.
304

305
    """
306
    slots = self._all_slots()
307
    for key in kwargs:
308
      if key not in slots:
309
        raise TypeError("Object %s doesn't support the parameter '%s'" %
310
                        (self.__class__.__name__, key))
311
      setattr(self, key, kwargs[key])
312

    
313
  def __getstate__(self):
314
    """Generic serializer.
315

316
    This method just returns the contents of the instance as a
317
    dictionary.
318

319
    @rtype:  C{dict}
320
    @return: the instance attributes and their values
321

322
    """
323
    state = {}
324
    for name in self._all_slots():
325
      if hasattr(self, name):
326
        state[name] = getattr(self, name)
327
    return state
328

    
329
  def __setstate__(self, state):
330
    """Generic unserializer.
331

332
    This method just restores from the serialized state the attributes
333
    of the current instance.
334

335
    @param state: the serialized opcode data
336
    @type state:  C{dict}
337

338
    """
339
    if not isinstance(state, dict):
340
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
341
                       type(state))
342

    
343
    for name in self._all_slots():
344
      if name not in state and hasattr(self, name):
345
        delattr(self, name)
346

    
347
    for name in state:
348
      setattr(self, name, state[name])
349

    
350
  @classmethod
351
  def _all_slots(cls):
352
    """Compute the list of all declared slots for a class.
353

354
    """
355
    slots = []
356
    for parent in cls.__mro__:
357
      slots.extend(getattr(parent, "__slots__", []))
358
    return slots
359

    
360
  @classmethod
361
  def GetAllParams(cls):
362
    """Compute list of all parameters for an opcode.
363

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

    
370
  def Validate(self, set_defaults):
371
    """Validate opcode parameters, optionally setting default values.
372

373
    @type set_defaults: bool
374
    @param set_defaults: Whether to set default values
375
    @raise errors.OpPrereqError: When a parameter value doesn't match
376
                                 requirements
377

378
    """
379
    for (attr_name, default, test, _) in self.GetAllParams():
380
      assert test == ht.NoType or callable(test)
381

    
382
      if not hasattr(self, attr_name):
383
        if default == ht.NoDefault:
384
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
385
                                     (self.OP_ID, attr_name),
386
                                     errors.ECODE_INVAL)
387
        elif set_defaults:
388
          if callable(default):
389
            dval = default()
390
          else:
391
            dval = default
392
          setattr(self, attr_name, dval)
393

    
394
      if test == ht.NoType:
395
        # no tests here
396
        continue
397

    
398
      if set_defaults or hasattr(self, attr_name):
399
        attr_val = getattr(self, attr_name)
400
        if not test(attr_val):
401
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
402
                        self.OP_ID, attr_name, type(attr_val), attr_val)
403
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
404
                                     (self.OP_ID, attr_name),
405
                                     errors.ECODE_INVAL)
406

    
407

    
408
def _BuildJobDepCheck(relative):
409
  """Builds check for job dependencies (L{DEPEND_ATTR}).
410

411
  @type relative: bool
412
  @param relative: Whether to accept relative job IDs (negative)
413
  @rtype: callable
414

415
  """
416
  if relative:
417
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
418
  else:
419
    job_id = ht.TJobId
420

    
421
  job_dep = \
422
    ht.TAnd(ht.TIsLength(2),
423
            ht.TItems([job_id,
424
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
425

    
426
  return ht.TOr(ht.TNone, ht.TListOf(job_dep))
427

    
428

    
429
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
430

    
431
#: List of submission status and job ID as returned by C{SubmitManyJobs}
432
TJobIdList = \
433
  ht.TListOf(ht.TAnd(ht.TIsLength(2),
434
                     ht.TItems([ht.TBool, ht.TOr(ht.TString, ht.TJobId)])))
435

    
436
#: Result containing only list of submitted jobs
437
TJobIdListOnly = ht.TStrictDict(True, True, {
438
  constants.JOB_IDS_KEY: TJobIdList,
439
  })
440

    
441

    
442
class OpCode(BaseOpCode):
443
  """Abstract OpCode.
444

445
  This is the root of the actual OpCode hierarchy. All clases derived
446
  from this class should override OP_ID.
447

448
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
449
               children of this class.
450
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
451
                      string returned by Summary(); see the docstring of that
452
                      method for details).
453
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
454
                   get if not already defined, and types they must match.
455
  @cvar OP_RESULT: Callable to verify opcode result
456
  @cvar WITH_LU: Boolean that specifies whether this should be included in
457
      mcpu's dispatch table
458
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
459
                 the check steps
460
  @ivar priority: Opcode priority for queue
461

462
  """
463
  # pylint: disable-msg=E1101
464
  # as OP_ID is dynamically defined
465
  WITH_LU = True
466
  OP_PARAMS = [
467
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
468
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
469
    ("priority", constants.OP_PRIO_DEFAULT,
470
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
471
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
472
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
473
     " job IDs can be used"),
474
    (COMMENT_ATTR, None, ht.TMaybeString,
475
     "Comment describing the purpose of the opcode"),
476
    ]
477
  OP_RESULT = None
478

    
479
  def __getstate__(self):
480
    """Specialized getstate for opcodes.
481

482
    This method adds to the state dictionary the OP_ID of the class,
483
    so that on unload we can identify the correct class for
484
    instantiating the opcode.
485

486
    @rtype:   C{dict}
487
    @return:  the state as a dictionary
488

489
    """
490
    data = BaseOpCode.__getstate__(self)
491
    data["OP_ID"] = self.OP_ID
492
    return data
493

    
494
  @classmethod
495
  def LoadOpCode(cls, data):
496
    """Generic load opcode method.
497

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

502
    @type data:  C{dict}
503
    @param data: the serialized opcode
504

505
    """
506
    if not isinstance(data, dict):
507
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
508
    if "OP_ID" not in data:
509
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
510
    op_id = data["OP_ID"]
511
    op_class = None
512
    if op_id in OP_MAPPING:
513
      op_class = OP_MAPPING[op_id]
514
    else:
515
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
516
                       op_id)
517
    op = op_class()
518
    new_data = data.copy()
519
    del new_data["OP_ID"]
520
    op.__setstate__(new_data)
521
    return op
522

    
523
  def Summary(self):
524
    """Generates a summary description of this opcode.
525

526
    The summary is the value of the OP_ID attribute (without the "OP_"
527
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
528
    defined; this field should allow to easily identify the operation
529
    (for an instance creation job, e.g., it would be the instance
530
    name).
531

532
    """
533
    assert self.OP_ID is not None and len(self.OP_ID) > 3
534
    # all OP_ID start with OP_, we remove that
535
    txt = self.OP_ID[3:]
536
    field_name = getattr(self, "OP_DSC_FIELD", None)
537
    if field_name:
538
      field_value = getattr(self, field_name, None)
539
      if isinstance(field_value, (list, tuple)):
540
        field_value = ",".join(str(i) for i in field_value)
541
      txt = "%s(%s)" % (txt, field_value)
542
    return txt
543

    
544
  def TinySummary(self):
545
    """Generates a compact summary description of the opcode.
546

547
    """
548
    assert self.OP_ID.startswith("OP_")
549

    
550
    text = self.OP_ID[3:]
551

    
552
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
553
      if text.startswith(prefix):
554
        return supplement + text[len(prefix):]
555

    
556
    return text
557

    
558

    
559
# cluster opcodes
560

    
561
class OpClusterPostInit(OpCode):
562
  """Post cluster initialization.
563

564
  This opcode does not touch the cluster at all. Its purpose is to run hooks
565
  after the cluster has been initialized.
566

567
  """
568

    
569

    
570
class OpClusterDestroy(OpCode):
571
  """Destroy the cluster.
572

573
  This opcode has no other parameters. All the state is irreversibly
574
  lost after the execution of this opcode.
575

576
  """
577

    
578

    
579
class OpClusterQuery(OpCode):
580
  """Query cluster information."""
581

    
582

    
583
class OpClusterVerify(OpCode):
584
  """Submits all jobs necessary to verify the cluster.
585

586
  """
587
  OP_PARAMS = [
588
    _PDebugSimulateErrors,
589
    _PErrorCodes,
590
    _PSkipChecks,
591
    _PVerbose,
592
    ("group_name", None, ht.TMaybeString, "Group to verify")
593
    ]
594
  OP_RESULT = TJobIdListOnly
595

    
596

    
597
class OpClusterVerifyConfig(OpCode):
598
  """Verify the cluster config.
599

600
  """
601
  OP_PARAMS = [
602
    _PDebugSimulateErrors,
603
    _PErrorCodes,
604
    _PVerbose,
605
    ]
606
  OP_RESULT = ht.TBool
607

    
608

    
609
class OpClusterVerifyGroup(OpCode):
610
  """Run verify on a node group from the cluster.
611

612
  @type skip_checks: C{list}
613
  @ivar skip_checks: steps to be skipped from the verify process; this
614
                     needs to be a subset of
615
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
616
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
617

618
  """
619
  OP_DSC_FIELD = "group_name"
620
  OP_PARAMS = [
621
    _PGroupName,
622
    _PDebugSimulateErrors,
623
    _PErrorCodes,
624
    _PSkipChecks,
625
    _PVerbose,
626
    ]
627
  OP_RESULT = ht.TBool
628

    
629

    
630
class OpClusterVerifyDisks(OpCode):
631
  """Verify the cluster disks.
632

633
  """
634
  OP_RESULT = TJobIdListOnly
635

    
636

    
637
class OpGroupVerifyDisks(OpCode):
638
  """Verifies the status of all disks in a node group.
639

640
  Result: a tuple of three elements:
641
    - dict of node names with issues (values: error msg)
642
    - list of instances with degraded disks (that should be activated)
643
    - dict of instances with missing logical volumes (values: (node, vol)
644
      pairs with details about the missing volumes)
645

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

651
  Note that only instances that are drbd-based are taken into
652
  consideration. This might need to be revisited in the future.
653

654
  """
655
  OP_DSC_FIELD = "group_name"
656
  OP_PARAMS = [
657
    _PGroupName,
658
    ]
659
  OP_RESULT = \
660
    ht.TAnd(ht.TIsLength(3),
661
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
662
                       ht.TListOf(ht.TString),
663
                       ht.TDictOf(ht.TString, ht.TListOf(ht.TString))]))
664

    
665

    
666
class OpClusterRepairDiskSizes(OpCode):
667
  """Verify the disk sizes of the instances and fixes configuration
668
  mimatches.
669

670
  Parameters: optional instances list, in case we want to restrict the
671
  checks to only a subset of the instances.
672

673
  Result: a list of tuples, (instance, disk, new-size) for changed
674
  configurations.
675

676
  In normal operation, the list should be empty.
677

678
  @type instances: list
679
  @ivar instances: the list of instances to check, or empty for all instances
680

681
  """
682
  OP_PARAMS = [
683
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
684
    ]
685

    
686

    
687
class OpClusterConfigQuery(OpCode):
688
  """Query cluster configuration values."""
689
  OP_PARAMS = [
690
    _POutputFields
691
    ]
692

    
693

    
694
class OpClusterRename(OpCode):
695
  """Rename the cluster.
696

697
  @type name: C{str}
698
  @ivar name: The new name of the cluster. The name and/or the master IP
699
              address will be changed to match the new name and its IP
700
              address.
701

702
  """
703
  OP_DSC_FIELD = "name"
704
  OP_PARAMS = [
705
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
706
    ]
707

    
708

    
709
class OpClusterSetParams(OpCode):
710
  """Change the parameters of the cluster.
711

712
  @type vg_name: C{str} or C{None}
713
  @ivar vg_name: The new volume group name or None to disable LVM usage.
714

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

    
767

    
768
class OpClusterRedistConf(OpCode):
769
  """Force a full push of the cluster configuration.
770

771
  """
772

    
773

    
774
class OpQuery(OpCode):
775
  """Query for resources/items.
776

777
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
778
  @ivar fields: List of fields to retrieve
779
  @ivar filter: Query filter
780

781
  """
782
  OP_DSC_FIELD = "what"
783
  OP_PARAMS = [
784
    _PQueryWhat,
785
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
786
     "Requested fields"),
787
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
788
     "Query filter"),
789
    ]
790

    
791

    
792
class OpQueryFields(OpCode):
793
  """Query for available resource/item fields.
794

795
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
796
  @ivar fields: List of fields to retrieve
797

798
  """
799
  OP_DSC_FIELD = "what"
800
  OP_PARAMS = [
801
    _PQueryWhat,
802
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
803
     "Requested fields; if not given, all are returned"),
804
    ]
805

    
806

    
807
class OpOobCommand(OpCode):
808
  """Interact with OOB."""
809
  OP_PARAMS = [
810
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
811
     "List of nodes to run the OOB command against"),
812
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
813
     "OOB command to be run"),
814
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
815
     "Timeout before the OOB helper will be terminated"),
816
    ("ignore_status", False, ht.TBool,
817
     "Ignores the node offline status for power off"),
818
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
819
     "Time in seconds to wait between powering on nodes"),
820
    ]
821

    
822

    
823
# node opcodes
824

    
825
class OpNodeRemove(OpCode):
826
  """Remove a node.
827

828
  @type node_name: C{str}
829
  @ivar node_name: The name of the node to remove. If the node still has
830
                   instances on it, the operation will fail.
831

832
  """
833
  OP_DSC_FIELD = "node_name"
834
  OP_PARAMS = [
835
    _PNodeName,
836
    ]
837

    
838

    
839
class OpNodeAdd(OpCode):
840
  """Add a node to the cluster.
841

842
  @type node_name: C{str}
843
  @ivar node_name: The name of the node to add. This can be a short name,
844
                   but it will be expanded to the FQDN.
845
  @type primary_ip: IP address
846
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
847
                    opcode is submitted, but will be filled during the node
848
                    add (so it will be visible in the job query).
849
  @type secondary_ip: IP address
850
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
851
                      if the cluster has been initialized in 'dual-network'
852
                      mode, otherwise it must not be given.
853
  @type readd: C{bool}
854
  @ivar readd: Whether to re-add an existing node to the cluster. If
855
               this is not passed, then the operation will abort if the node
856
               name is already in the cluster; use this parameter to 'repair'
857
               a node that had its configuration broken, or was reinstalled
858
               without removal from the cluster.
859
  @type group: C{str}
860
  @ivar group: The node group to which this node will belong.
861
  @type vm_capable: C{bool}
862
  @ivar vm_capable: The vm_capable node attribute
863
  @type master_capable: C{bool}
864
  @ivar master_capable: The master_capable node attribute
865

866
  """
867
  OP_DSC_FIELD = "node_name"
868
  OP_PARAMS = [
869
    _PNodeName,
870
    ("primary_ip", None, ht.NoType, "Primary IP address"),
871
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
872
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
873
    ("group", None, ht.TMaybeString, "Initial node group"),
874
    ("master_capable", None, ht.TMaybeBool,
875
     "Whether node can become master or master candidate"),
876
    ("vm_capable", None, ht.TMaybeBool,
877
     "Whether node can host instances"),
878
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
879
    ]
880

    
881

    
882
class OpNodeQuery(OpCode):
883
  """Compute the list of nodes."""
884
  OP_PARAMS = [
885
    _POutputFields,
886
    _PUseLocking,
887
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
888
     "Empty list to query all nodes, node names otherwise"),
889
    ]
890

    
891

    
892
class OpNodeQueryvols(OpCode):
893
  """Get list of volumes on node."""
894
  OP_PARAMS = [
895
    _POutputFields,
896
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
897
     "Empty list to query all nodes, node names otherwise"),
898
    ]
899

    
900

    
901
class OpNodeQueryStorage(OpCode):
902
  """Get information on storage for node(s)."""
903
  OP_PARAMS = [
904
    _POutputFields,
905
    _PStorageType,
906
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
907
    ("name", None, ht.TMaybeString, "Storage name"),
908
    ]
909

    
910

    
911
class OpNodeModifyStorage(OpCode):
912
  """Modifies the properies of a storage unit"""
913
  OP_PARAMS = [
914
    _PNodeName,
915
    _PStorageType,
916
    _PStorageName,
917
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
918
    ]
919

    
920

    
921
class OpRepairNodeStorage(OpCode):
922
  """Repairs the volume group on a node."""
923
  OP_DSC_FIELD = "node_name"
924
  OP_PARAMS = [
925
    _PNodeName,
926
    _PStorageType,
927
    _PStorageName,
928
    _PIgnoreConsistency,
929
    ]
930

    
931

    
932
class OpNodeSetParams(OpCode):
933
  """Change the parameters of a node."""
934
  OP_DSC_FIELD = "node_name"
935
  OP_PARAMS = [
936
    _PNodeName,
937
    _PForce,
938
    ("master_candidate", None, ht.TMaybeBool,
939
     "Whether the node should become a master candidate"),
940
    ("offline", None, ht.TMaybeBool,
941
     "Whether the node should be marked as offline"),
942
    ("drained", None, ht.TMaybeBool,
943
     "Whether the node should be marked as drained"),
944
    ("auto_promote", False, ht.TBool,
945
     "Whether node(s) should be promoted to master candidate if necessary"),
946
    ("master_capable", None, ht.TMaybeBool,
947
     "Denote whether node can become master or master candidate"),
948
    ("vm_capable", None, ht.TMaybeBool,
949
     "Denote whether node can host instances"),
950
    ("secondary_ip", None, ht.TMaybeString,
951
     "Change node's secondary IP address"),
952
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
953
    ("powered", None, ht.TMaybeBool,
954
     "Whether the node should be marked as powered"),
955
    ]
956

    
957

    
958
class OpNodePowercycle(OpCode):
959
  """Tries to powercycle a node."""
960
  OP_DSC_FIELD = "node_name"
961
  OP_PARAMS = [
962
    _PNodeName,
963
    _PForce,
964
    ]
965

    
966

    
967
class OpNodeMigrate(OpCode):
968
  """Migrate all instances from a node."""
969
  OP_DSC_FIELD = "node_name"
970
  OP_PARAMS = [
971
    _PNodeName,
972
    _PMigrationMode,
973
    _PMigrationLive,
974
    _PMigrationTargetNode,
975
    ("iallocator", None, ht.TMaybeString,
976
     "Iallocator for deciding the target node for shared-storage instances"),
977
    ]
978

    
979

    
980
class OpNodeEvacuate(OpCode):
981
  """Evacuate instances off a number of nodes."""
982
  OP_DSC_FIELD = "node_name"
983
  OP_PARAMS = [
984
    _PEarlyRelease,
985
    _PNodeName,
986
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
987
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
988
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
989
     "Node evacuation mode"),
990
    ]
991

    
992

    
993
# instance opcodes
994

    
995
class OpInstanceCreate(OpCode):
996
  """Create an instance.
997

998
  @ivar instance_name: Instance name
999
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1000
  @ivar source_handshake: Signed handshake from source (remote import only)
1001
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1002
  @ivar source_instance_name: Previous name of instance (remote import only)
1003
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1004
    (remote import only)
1005

1006
  """
1007
  OP_DSC_FIELD = "instance_name"
1008
  OP_PARAMS = [
1009
    _PInstanceName,
1010
    _PForceVariant,
1011
    _PWaitForSync,
1012
    _PNameCheck,
1013
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1014
    ("disks", ht.NoDefault,
1015
     # TODO: Generate check from constants.IDISK_PARAMS_TYPES
1016
     ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
1017
                           ht.TOr(ht.TNonEmptyString, ht.TInt))),
1018
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1019
     " each disk definition must contain a ``%s`` value and"
1020
     " can contain an optional ``%s`` value denoting the disk access mode"
1021
     " (%s)" %
1022
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1023
      constants.IDISK_MODE,
1024
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1025
    ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
1026
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1027
     "Driver for file-backed disks"),
1028
    ("file_storage_dir", None, ht.TMaybeString,
1029
     "Directory for storing file-backed disks"),
1030
    ("hvparams", ht.EmptyDict, ht.TDict,
1031
     "Hypervisor parameters for instance, hypervisor-dependent"),
1032
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1033
    ("iallocator", None, ht.TMaybeString,
1034
     "Iallocator for deciding which node(s) to use"),
1035
    ("identify_defaults", False, ht.TBool,
1036
     "Reset instance parameters to default if equal"),
1037
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1038
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1039
     "Instance creation mode"),
1040
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1041
     "List of NIC (network interface) definitions, for example"
1042
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1043
     " contain the optional values %s" %
1044
     (constants.INIC_IP,
1045
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1046
    ("no_install", None, ht.TMaybeBool,
1047
     "Do not install the OS (will disable automatic start)"),
1048
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1049
    ("os_type", None, ht.TMaybeString, "Operating system"),
1050
    ("pnode", None, ht.TMaybeString, "Primary node"),
1051
    ("snode", None, ht.TMaybeString, "Secondary node"),
1052
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1053
     "Signed handshake from source (remote import only)"),
1054
    ("source_instance_name", None, ht.TMaybeString,
1055
     "Source instance name (remote import only)"),
1056
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1057
     ht.TPositiveInt,
1058
     "How long source instance was given to shut down (remote import only)"),
1059
    ("source_x509_ca", None, ht.TMaybeString,
1060
     "Source X509 CA in PEM format (remote import only)"),
1061
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1062
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1063
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1064
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1065
    ]
1066

    
1067

    
1068
class OpInstanceReinstall(OpCode):
1069
  """Reinstall an instance's OS."""
1070
  OP_DSC_FIELD = "instance_name"
1071
  OP_PARAMS = [
1072
    _PInstanceName,
1073
    _PForceVariant,
1074
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1075
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1076
    ]
1077

    
1078

    
1079
class OpInstanceRemove(OpCode):
1080
  """Remove an instance."""
1081
  OP_DSC_FIELD = "instance_name"
1082
  OP_PARAMS = [
1083
    _PInstanceName,
1084
    _PShutdownTimeout,
1085
    ("ignore_failures", False, ht.TBool,
1086
     "Whether to ignore failures during removal"),
1087
    ]
1088

    
1089

    
1090
class OpInstanceRename(OpCode):
1091
  """Rename an instance."""
1092
  OP_PARAMS = [
1093
    _PInstanceName,
1094
    _PNameCheck,
1095
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1096
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1097
    ]
1098

    
1099

    
1100
class OpInstanceStartup(OpCode):
1101
  """Startup an instance."""
1102
  OP_DSC_FIELD = "instance_name"
1103
  OP_PARAMS = [
1104
    _PInstanceName,
1105
    _PForce,
1106
    _PIgnoreOfflineNodes,
1107
    ("hvparams", ht.EmptyDict, ht.TDict,
1108
     "Temporary hypervisor parameters, hypervisor-dependent"),
1109
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1110
    _PNoRemember,
1111
    _PStartupPaused,
1112
    ]
1113

    
1114

    
1115
class OpInstanceShutdown(OpCode):
1116
  """Shutdown an instance."""
1117
  OP_DSC_FIELD = "instance_name"
1118
  OP_PARAMS = [
1119
    _PInstanceName,
1120
    _PIgnoreOfflineNodes,
1121
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1122
     "How long to wait for instance to shut down"),
1123
    _PNoRemember,
1124
    ]
1125

    
1126

    
1127
class OpInstanceReboot(OpCode):
1128
  """Reboot an instance."""
1129
  OP_DSC_FIELD = "instance_name"
1130
  OP_PARAMS = [
1131
    _PInstanceName,
1132
    _PShutdownTimeout,
1133
    ("ignore_secondaries", False, ht.TBool,
1134
     "Whether to start the instance even if secondary disks are failing"),
1135
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1136
     "How to reboot instance"),
1137
    ]
1138

    
1139

    
1140
class OpInstanceReplaceDisks(OpCode):
1141
  """Replace the disks of an instance."""
1142
  OP_DSC_FIELD = "instance_name"
1143
  OP_PARAMS = [
1144
    _PInstanceName,
1145
    _PEarlyRelease,
1146
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1147
     "Replacement mode"),
1148
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1149
     "Disk indexes"),
1150
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1151
    ("iallocator", None, ht.TMaybeString,
1152
     "Iallocator for deciding new secondary node"),
1153
    ]
1154

    
1155

    
1156
class OpInstanceFailover(OpCode):
1157
  """Failover an instance."""
1158
  OP_DSC_FIELD = "instance_name"
1159
  OP_PARAMS = [
1160
    _PInstanceName,
1161
    _PShutdownTimeout,
1162
    _PIgnoreConsistency,
1163
    _PMigrationTargetNode,
1164
    ("iallocator", None, ht.TMaybeString,
1165
     "Iallocator for deciding the target node for shared-storage instances"),
1166
    ]
1167

    
1168

    
1169
class OpInstanceMigrate(OpCode):
1170
  """Migrate an instance.
1171

1172
  This migrates (without shutting down an instance) to its secondary
1173
  node.
1174

1175
  @ivar instance_name: the name of the instance
1176
  @ivar mode: the migration mode (live, non-live or None for auto)
1177

1178
  """
1179
  OP_DSC_FIELD = "instance_name"
1180
  OP_PARAMS = [
1181
    _PInstanceName,
1182
    _PMigrationMode,
1183
    _PMigrationLive,
1184
    _PMigrationTargetNode,
1185
    ("cleanup", False, ht.TBool,
1186
     "Whether a previously failed migration should be cleaned up"),
1187
    ("iallocator", None, ht.TMaybeString,
1188
     "Iallocator for deciding the target node for shared-storage instances"),
1189
    ("allow_failover", False, ht.TBool,
1190
     "Whether we can fallback to failover if migration is not possible"),
1191
    ]
1192

    
1193

    
1194
class OpInstanceMove(OpCode):
1195
  """Move an instance.
1196

1197
  This move (with shutting down an instance and data copying) to an
1198
  arbitrary node.
1199

1200
  @ivar instance_name: the name of the instance
1201
  @ivar target_node: the destination node
1202

1203
  """
1204
  OP_DSC_FIELD = "instance_name"
1205
  OP_PARAMS = [
1206
    _PInstanceName,
1207
    _PShutdownTimeout,
1208
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1209
    _PIgnoreConsistency,
1210
    ]
1211

    
1212

    
1213
class OpInstanceConsole(OpCode):
1214
  """Connect to an instance's console."""
1215
  OP_DSC_FIELD = "instance_name"
1216
  OP_PARAMS = [
1217
    _PInstanceName
1218
    ]
1219

    
1220

    
1221
class OpInstanceActivateDisks(OpCode):
1222
  """Activate an instance's disks."""
1223
  OP_DSC_FIELD = "instance_name"
1224
  OP_PARAMS = [
1225
    _PInstanceName,
1226
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1227
    ]
1228

    
1229

    
1230
class OpInstanceDeactivateDisks(OpCode):
1231
  """Deactivate an instance's disks."""
1232
  OP_DSC_FIELD = "instance_name"
1233
  OP_PARAMS = [
1234
    _PInstanceName,
1235
    _PForce,
1236
    ]
1237

    
1238

    
1239
class OpInstanceRecreateDisks(OpCode):
1240
  """Deactivate an instance's disks."""
1241
  OP_DSC_FIELD = "instance_name"
1242
  OP_PARAMS = [
1243
    _PInstanceName,
1244
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1245
     "List of disk indexes"),
1246
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1247
     "New instance nodes, if relocation is desired"),
1248
    ]
1249

    
1250

    
1251
class OpInstanceQuery(OpCode):
1252
  """Compute the list of instances."""
1253
  OP_PARAMS = [
1254
    _POutputFields,
1255
    _PUseLocking,
1256
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1257
     "Empty list to query all instances, instance names otherwise"),
1258
    ]
1259

    
1260

    
1261
class OpInstanceQueryData(OpCode):
1262
  """Compute the run-time status of instances."""
1263
  OP_PARAMS = [
1264
    _PUseLocking,
1265
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1266
     "Instance names"),
1267
    ("static", False, ht.TBool,
1268
     "Whether to only return configuration data without querying"
1269
     " nodes"),
1270
    ]
1271

    
1272

    
1273
class OpInstanceSetParams(OpCode):
1274
  """Change the parameters of an instance."""
1275
  OP_DSC_FIELD = "instance_name"
1276
  OP_PARAMS = [
1277
    _PInstanceName,
1278
    _PForce,
1279
    _PForceVariant,
1280
    # TODO: Use _TestNicDef
1281
    ("nics", ht.EmptyList, ht.TList,
1282
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1283
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1284
     " ``%s`` to remove the last NIC or a number to modify the settings"
1285
     " of the NIC with that index." %
1286
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1287
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1288
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1289
    ("hvparams", ht.EmptyDict, ht.TDict,
1290
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1291
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1292
     "Disk template for instance"),
1293
    ("remote_node", None, ht.TMaybeString,
1294
     "Secondary node (used when changing disk template)"),
1295
    ("os_name", None, ht.TMaybeString,
1296
     "Change instance's OS name. Does not reinstall the instance."),
1297
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1298
    ("wait_for_sync", True, ht.TBool,
1299
     "Whether to wait for the disk to synchronize, when changing template"),
1300
    ]
1301

    
1302

    
1303
class OpInstanceGrowDisk(OpCode):
1304
  """Grow a disk of an instance."""
1305
  OP_DSC_FIELD = "instance_name"
1306
  OP_PARAMS = [
1307
    _PInstanceName,
1308
    _PWaitForSync,
1309
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1310
    ("amount", ht.NoDefault, ht.TInt,
1311
     "Amount of disk space to add (megabytes)"),
1312
    ]
1313

    
1314

    
1315
class OpInstanceChangeGroup(OpCode):
1316
  """Moves an instance to another node group."""
1317
  OP_DSC_FIELD = "instance_name"
1318
  OP_PARAMS = [
1319
    _PInstanceName,
1320
    _PEarlyRelease,
1321
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1322
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1323
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1324
    ]
1325

    
1326

    
1327
# Node group opcodes
1328

    
1329
class OpGroupAdd(OpCode):
1330
  """Add a node group to the cluster."""
1331
  OP_DSC_FIELD = "group_name"
1332
  OP_PARAMS = [
1333
    _PGroupName,
1334
    _PNodeGroupAllocPolicy,
1335
    _PGroupNodeParams,
1336
    ]
1337

    
1338

    
1339
class OpGroupAssignNodes(OpCode):
1340
  """Assign nodes to a node group."""
1341
  OP_DSC_FIELD = "group_name"
1342
  OP_PARAMS = [
1343
    _PGroupName,
1344
    _PForce,
1345
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1346
     "List of nodes to assign"),
1347
    ]
1348

    
1349

    
1350
class OpGroupQuery(OpCode):
1351
  """Compute the list of node groups."""
1352
  OP_PARAMS = [
1353
    _POutputFields,
1354
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1355
     "Empty list to query all groups, group names otherwise"),
1356
    ]
1357

    
1358

    
1359
class OpGroupSetParams(OpCode):
1360
  """Change the parameters of a node group."""
1361
  OP_DSC_FIELD = "group_name"
1362
  OP_PARAMS = [
1363
    _PGroupName,
1364
    _PNodeGroupAllocPolicy,
1365
    _PGroupNodeParams,
1366
    ]
1367

    
1368

    
1369
class OpGroupRemove(OpCode):
1370
  """Remove a node group from the cluster."""
1371
  OP_DSC_FIELD = "group_name"
1372
  OP_PARAMS = [
1373
    _PGroupName,
1374
    ]
1375

    
1376

    
1377
class OpGroupRename(OpCode):
1378
  """Rename a node group in the cluster."""
1379
  OP_PARAMS = [
1380
    _PGroupName,
1381
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1382
    ]
1383

    
1384

    
1385
class OpGroupEvacuate(OpCode):
1386
  """Evacuate a node group in the cluster."""
1387
  OP_DSC_FIELD = "group_name"
1388
  OP_PARAMS = [
1389
    _PGroupName,
1390
    _PEarlyRelease,
1391
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1392
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1393
     "Destination group names or UUIDs"),
1394
    ]
1395

    
1396

    
1397
# OS opcodes
1398
class OpOsDiagnose(OpCode):
1399
  """Compute the list of guest operating systems."""
1400
  OP_PARAMS = [
1401
    _POutputFields,
1402
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1403
     "Which operating systems to diagnose"),
1404
    ]
1405

    
1406

    
1407
# Exports opcodes
1408
class OpBackupQuery(OpCode):
1409
  """Compute the list of exported images."""
1410
  OP_PARAMS = [
1411
    _PUseLocking,
1412
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1413
     "Empty list to query all nodes, node names otherwise"),
1414
    ]
1415

    
1416

    
1417
class OpBackupPrepare(OpCode):
1418
  """Prepares an instance export.
1419

1420
  @ivar instance_name: Instance name
1421
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1422

1423
  """
1424
  OP_DSC_FIELD = "instance_name"
1425
  OP_PARAMS = [
1426
    _PInstanceName,
1427
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1428
     "Export mode"),
1429
    ]
1430

    
1431

    
1432
class OpBackupExport(OpCode):
1433
  """Export an instance.
1434

1435
  For local exports, the export destination is the node name. For remote
1436
  exports, the export destination is a list of tuples, each consisting of
1437
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1438
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1439
  destination X509 CA must be a signed certificate.
1440

1441
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1442
  @ivar target_node: Export destination
1443
  @ivar x509_key_name: X509 key to use (remote export only)
1444
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1445
                             only)
1446

1447
  """
1448
  OP_DSC_FIELD = "instance_name"
1449
  OP_PARAMS = [
1450
    _PInstanceName,
1451
    _PShutdownTimeout,
1452
    # TODO: Rename target_node as it changes meaning for different export modes
1453
    # (e.g. "destination")
1454
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1455
     "Destination information, depends on export mode"),
1456
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1457
    ("remove_instance", False, ht.TBool,
1458
     "Whether to remove instance after export"),
1459
    ("ignore_remove_failures", False, ht.TBool,
1460
     "Whether to ignore failures while removing instances"),
1461
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1462
     "Export mode"),
1463
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1464
     "Name of X509 key (remote export only)"),
1465
    ("destination_x509_ca", None, ht.TMaybeString,
1466
     "Destination X509 CA (remote export only)"),
1467
    ]
1468

    
1469

    
1470
class OpBackupRemove(OpCode):
1471
  """Remove an instance's export."""
1472
  OP_DSC_FIELD = "instance_name"
1473
  OP_PARAMS = [
1474
    _PInstanceName,
1475
    ]
1476

    
1477

    
1478
# Tags opcodes
1479
class OpTagsGet(OpCode):
1480
  """Returns the tags of the given object."""
1481
  OP_DSC_FIELD = "name"
1482
  OP_PARAMS = [
1483
    _PTagKind,
1484
    # Name is only meaningful for nodes and instances
1485
    ("name", ht.NoDefault, ht.TMaybeString, None),
1486
    ]
1487

    
1488

    
1489
class OpTagsSearch(OpCode):
1490
  """Searches the tags in the cluster for a given pattern."""
1491
  OP_DSC_FIELD = "pattern"
1492
  OP_PARAMS = [
1493
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1494
    ]
1495

    
1496

    
1497
class OpTagsSet(OpCode):
1498
  """Add a list of tags on a given object."""
1499
  OP_PARAMS = [
1500
    _PTagKind,
1501
    _PTags,
1502
    # Name is only meaningful for nodes and instances
1503
    ("name", ht.NoDefault, ht.TMaybeString, None),
1504
    ]
1505

    
1506

    
1507
class OpTagsDel(OpCode):
1508
  """Remove a list of tags from a given object."""
1509
  OP_PARAMS = [
1510
    _PTagKind,
1511
    _PTags,
1512
    # Name is only meaningful for nodes and instances
1513
    ("name", ht.NoDefault, ht.TMaybeString, None),
1514
    ]
1515

    
1516
# Test opcodes
1517
class OpTestDelay(OpCode):
1518
  """Sleeps for a configured amount of time.
1519

1520
  This is used just for debugging and testing.
1521

1522
  Parameters:
1523
    - duration: the time to sleep
1524
    - on_master: if true, sleep on the master
1525
    - on_nodes: list of nodes in which to sleep
1526

1527
  If the on_master parameter is true, it will execute a sleep on the
1528
  master (before any node sleep).
1529

1530
  If the on_nodes list is not empty, it will sleep on those nodes
1531
  (after the sleep on the master, if that is enabled).
1532

1533
  As an additional feature, the case of duration < 0 will be reported
1534
  as an execution error, so this opcode can be used as a failure
1535
  generator. The case of duration == 0 will not be treated specially.
1536

1537
  """
1538
  OP_DSC_FIELD = "duration"
1539
  OP_PARAMS = [
1540
    ("duration", ht.NoDefault, ht.TNumber, None),
1541
    ("on_master", True, ht.TBool, None),
1542
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1543
    ("repeat", 0, ht.TPositiveInt, None),
1544
    ]
1545

    
1546

    
1547
class OpTestAllocator(OpCode):
1548
  """Allocator framework testing.
1549

1550
  This opcode has two modes:
1551
    - gather and return allocator input for a given mode (allocate new
1552
      or replace secondary) and a given instance definition (direction
1553
      'in')
1554
    - run a selected allocator for a given operation (as above) and
1555
      return the allocator output (direction 'out')
1556

1557
  """
1558
  OP_DSC_FIELD = "allocator"
1559
  OP_PARAMS = [
1560
    ("direction", ht.NoDefault,
1561
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1562
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1563
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1564
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1565
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1566
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1567
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1568
    ("hypervisor", None, ht.TMaybeString, None),
1569
    ("allocator", None, ht.TMaybeString, None),
1570
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1571
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1572
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1573
    ("os", None, ht.TMaybeString, None),
1574
    ("disk_template", None, ht.TMaybeString, None),
1575
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1576
     None),
1577
    ("evac_mode", None,
1578
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1579
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1580
     None),
1581
    ]
1582

    
1583

    
1584
class OpTestJqueue(OpCode):
1585
  """Utility opcode to test some aspects of the job queue.
1586

1587
  """
1588
  OP_PARAMS = [
1589
    ("notify_waitlock", False, ht.TBool, None),
1590
    ("notify_exec", False, ht.TBool, None),
1591
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1592
    ("fail", False, ht.TBool, None),
1593
    ]
1594

    
1595

    
1596
class OpTestDummy(OpCode):
1597
  """Utility opcode used by unittests.
1598

1599
  """
1600
  OP_PARAMS = [
1601
    ("result", ht.NoDefault, ht.NoType, None),
1602
    ("messages", ht.NoDefault, ht.NoType, None),
1603
    ("fail", ht.NoDefault, ht.NoType, None),
1604
    ("submit_jobs", None, ht.NoType, None),
1605
    ]
1606
  WITH_LU = False
1607

    
1608

    
1609
def _GetOpList():
1610
  """Returns list of all defined opcodes.
1611

1612
  Does not eliminate duplicates by C{OP_ID}.
1613

1614
  """
1615
  return [v for v in globals().values()
1616
          if (isinstance(v, type) and issubclass(v, OpCode) and
1617
              hasattr(v, "OP_ID") and v is not OpCode)]
1618

    
1619

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