Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 57106b74

History | View | Annotate | Download (49 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 = ht.TListOf(ht.TItems([ht.TBool, ht.TOr(ht.TString, ht.TJobId)]))
433

    
434

    
435
class OpCode(BaseOpCode):
436
  """Abstract OpCode.
437

438
  This is the root of the actual OpCode hierarchy. All clases derived
439
  from this class should override OP_ID.
440

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

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

    
472
  def __getstate__(self):
473
    """Specialized getstate for opcodes.
474

475
    This method adds to the state dictionary the OP_ID of the class,
476
    so that on unload we can identify the correct class for
477
    instantiating the opcode.
478

479
    @rtype:   C{dict}
480
    @return:  the state as a dictionary
481

482
    """
483
    data = BaseOpCode.__getstate__(self)
484
    data["OP_ID"] = self.OP_ID
485
    return data
486

    
487
  @classmethod
488
  def LoadOpCode(cls, data):
489
    """Generic load opcode method.
490

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

495
    @type data:  C{dict}
496
    @param data: the serialized opcode
497

498
    """
499
    if not isinstance(data, dict):
500
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
501
    if "OP_ID" not in data:
502
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
503
    op_id = data["OP_ID"]
504
    op_class = None
505
    if op_id in OP_MAPPING:
506
      op_class = OP_MAPPING[op_id]
507
    else:
508
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
509
                       op_id)
510
    op = op_class()
511
    new_data = data.copy()
512
    del new_data["OP_ID"]
513
    op.__setstate__(new_data)
514
    return op
515

    
516
  def Summary(self):
517
    """Generates a summary description of this opcode.
518

519
    The summary is the value of the OP_ID attribute (without the "OP_"
520
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
521
    defined; this field should allow to easily identify the operation
522
    (for an instance creation job, e.g., it would be the instance
523
    name).
524

525
    """
526
    assert self.OP_ID is not None and len(self.OP_ID) > 3
527
    # all OP_ID start with OP_, we remove that
528
    txt = self.OP_ID[3:]
529
    field_name = getattr(self, "OP_DSC_FIELD", None)
530
    if field_name:
531
      field_value = getattr(self, field_name, None)
532
      if isinstance(field_value, (list, tuple)):
533
        field_value = ",".join(str(i) for i in field_value)
534
      txt = "%s(%s)" % (txt, field_value)
535
    return txt
536

    
537
  def TinySummary(self):
538
    """Generates a compact summary description of the opcode.
539

540
    """
541
    assert self.OP_ID.startswith("OP_")
542

    
543
    text = self.OP_ID[3:]
544

    
545
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
546
      if text.startswith(prefix):
547
        return supplement + text[len(prefix):]
548

    
549
    return text
550

    
551

    
552
# cluster opcodes
553

    
554
class OpClusterPostInit(OpCode):
555
  """Post cluster initialization.
556

557
  This opcode does not touch the cluster at all. Its purpose is to run hooks
558
  after the cluster has been initialized.
559

560
  """
561

    
562

    
563
class OpClusterDestroy(OpCode):
564
  """Destroy the cluster.
565

566
  This opcode has no other parameters. All the state is irreversibly
567
  lost after the execution of this opcode.
568

569
  """
570

    
571

    
572
class OpClusterQuery(OpCode):
573
  """Query cluster information."""
574

    
575

    
576
class OpClusterVerifyConfig(OpCode):
577
  """Verify the cluster config.
578

579
  """
580
  OP_PARAMS = [
581
    _PDebugSimulateErrors,
582
    _PErrorCodes,
583
    _PVerbose,
584
    ]
585

    
586

    
587
class OpClusterVerifyGroup(OpCode):
588
  """Run verify on a node group from the cluster.
589

590
  @type skip_checks: C{list}
591
  @ivar skip_checks: steps to be skipped from the verify process; this
592
                     needs to be a subset of
593
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
594
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
595

596
  """
597
  OP_DSC_FIELD = "group_name"
598
  OP_PARAMS = [
599
    _PGroupName,
600
    _PDebugSimulateErrors,
601
    _PErrorCodes,
602
    _PSkipChecks,
603
    _PVerbose,
604
    ]
605

    
606

    
607
class OpClusterVerifyDisks(OpCode):
608
  """Verify the cluster disks.
609

610
  """
611
  OP_RESULT = ht.TStrictDict(True, True, {
612
    constants.JOB_IDS_KEY: TJobIdList,
613
    })
614

    
615

    
616
class OpGroupVerifyDisks(OpCode):
617
  """Verifies the status of all disks in a node group.
618

619
  Result: a tuple of three elements:
620
    - dict of node names with issues (values: error msg)
621
    - list of instances with degraded disks (that should be activated)
622
    - dict of instances with missing logical volumes (values: (node, vol)
623
      pairs with details about the missing volumes)
624

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

630
  Note that only instances that are drbd-based are taken into
631
  consideration. This might need to be revisited in the future.
632

633
  """
634
  OP_DSC_FIELD = "group_name"
635
  OP_PARAMS = [
636
    _PGroupName,
637
    ]
638
  OP_RESULT = \
639
    ht.TAnd(ht.TIsLength(3),
640
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
641
                       ht.TListOf(ht.TString),
642
                       ht.TDictOf(ht.TString, ht.TListOf(ht.TString))]))
643

    
644

    
645
class OpClusterRepairDiskSizes(OpCode):
646
  """Verify the disk sizes of the instances and fixes configuration
647
  mimatches.
648

649
  Parameters: optional instances list, in case we want to restrict the
650
  checks to only a subset of the instances.
651

652
  Result: a list of tuples, (instance, disk, new-size) for changed
653
  configurations.
654

655
  In normal operation, the list should be empty.
656

657
  @type instances: list
658
  @ivar instances: the list of instances to check, or empty for all instances
659

660
  """
661
  OP_PARAMS = [
662
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
663
    ]
664

    
665

    
666
class OpClusterConfigQuery(OpCode):
667
  """Query cluster configuration values."""
668
  OP_PARAMS = [
669
    _POutputFields
670
    ]
671

    
672

    
673
class OpClusterRename(OpCode):
674
  """Rename the cluster.
675

676
  @type name: C{str}
677
  @ivar name: The new name of the cluster. The name and/or the master IP
678
              address will be changed to match the new name and its IP
679
              address.
680

681
  """
682
  OP_DSC_FIELD = "name"
683
  OP_PARAMS = [
684
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
685
    ]
686

    
687

    
688
class OpClusterSetParams(OpCode):
689
  """Change the parameters of the cluster.
690

691
  @type vg_name: C{str} or C{None}
692
  @ivar vg_name: The new volume group name or None to disable LVM usage.
693

694
  """
695
  OP_PARAMS = [
696
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
697
    ("enabled_hypervisors", None,
698
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
699
            ht.TNone),
700
     "List of enabled hypervisors"),
701
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
702
                              ht.TNone),
703
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
704
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
705
     "Cluster-wide backend parameter defaults"),
706
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
707
                            ht.TNone),
708
     "Cluster-wide per-OS hypervisor parameter defaults"),
709
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
710
                              ht.TNone),
711
     "Cluster-wide OS parameter defaults"),
712
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
713
     "Master candidate pool size"),
714
    ("uid_pool", None, ht.NoType,
715
     "Set UID pool, must be list of lists describing UID ranges (two items,"
716
     " start and end inclusive)"),
717
    ("add_uids", None, ht.NoType,
718
     "Extend UID pool, must be list of lists describing UID ranges (two"
719
     " items, start and end inclusive) to be added"),
720
    ("remove_uids", None, ht.NoType,
721
     "Shrink UID pool, must be list of lists describing UID ranges (two"
722
     " items, start and end inclusive) to be removed"),
723
    ("maintain_node_health", None, ht.TMaybeBool,
724
     "Whether to automatically maintain node health"),
725
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
726
     "Whether to wipe disks before allocating them to instances"),
727
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
728
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
729
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
730
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
731
     "Default iallocator for cluster"),
732
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
733
     "Master network device"),
734
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
735
     "List of reserved LVs"),
736
    ("hidden_os", None, _TestClusterOsList,
737
     "Modify list of hidden operating systems. Each modification must have"
738
     " two items, the operation and the OS name. The operation can be"
739
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
740
    ("blacklisted_os", None, _TestClusterOsList,
741
     "Modify list of blacklisted operating systems. Each modification must have"
742
     " two items, the operation and the OS name. The operation can be"
743
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
744
    ]
745

    
746

    
747
class OpClusterRedistConf(OpCode):
748
  """Force a full push of the cluster configuration.
749

750
  """
751

    
752

    
753
class OpQuery(OpCode):
754
  """Query for resources/items.
755

756
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
757
  @ivar fields: List of fields to retrieve
758
  @ivar filter: Query filter
759

760
  """
761
  OP_DSC_FIELD = "what"
762
  OP_PARAMS = [
763
    _PQueryWhat,
764
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
765
     "Requested fields"),
766
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
767
     "Query filter"),
768
    ]
769

    
770

    
771
class OpQueryFields(OpCode):
772
  """Query for available resource/item fields.
773

774
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
775
  @ivar fields: List of fields to retrieve
776

777
  """
778
  OP_DSC_FIELD = "what"
779
  OP_PARAMS = [
780
    _PQueryWhat,
781
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
782
     "Requested fields; if not given, all are returned"),
783
    ]
784

    
785

    
786
class OpOobCommand(OpCode):
787
  """Interact with OOB."""
788
  OP_PARAMS = [
789
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
790
     "List of nodes to run the OOB command against"),
791
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
792
     "OOB command to be run"),
793
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
794
     "Timeout before the OOB helper will be terminated"),
795
    ("ignore_status", False, ht.TBool,
796
     "Ignores the node offline status for power off"),
797
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
798
     "Time in seconds to wait between powering on nodes"),
799
    ]
800

    
801

    
802
# node opcodes
803

    
804
class OpNodeRemove(OpCode):
805
  """Remove a node.
806

807
  @type node_name: C{str}
808
  @ivar node_name: The name of the node to remove. If the node still has
809
                   instances on it, the operation will fail.
810

811
  """
812
  OP_DSC_FIELD = "node_name"
813
  OP_PARAMS = [
814
    _PNodeName,
815
    ]
816

    
817

    
818
class OpNodeAdd(OpCode):
819
  """Add a node to the cluster.
820

821
  @type node_name: C{str}
822
  @ivar node_name: The name of the node to add. This can be a short name,
823
                   but it will be expanded to the FQDN.
824
  @type primary_ip: IP address
825
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
826
                    opcode is submitted, but will be filled during the node
827
                    add (so it will be visible in the job query).
828
  @type secondary_ip: IP address
829
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
830
                      if the cluster has been initialized in 'dual-network'
831
                      mode, otherwise it must not be given.
832
  @type readd: C{bool}
833
  @ivar readd: Whether to re-add an existing node to the cluster. If
834
               this is not passed, then the operation will abort if the node
835
               name is already in the cluster; use this parameter to 'repair'
836
               a node that had its configuration broken, or was reinstalled
837
               without removal from the cluster.
838
  @type group: C{str}
839
  @ivar group: The node group to which this node will belong.
840
  @type vm_capable: C{bool}
841
  @ivar vm_capable: The vm_capable node attribute
842
  @type master_capable: C{bool}
843
  @ivar master_capable: The master_capable node attribute
844

845
  """
846
  OP_DSC_FIELD = "node_name"
847
  OP_PARAMS = [
848
    _PNodeName,
849
    ("primary_ip", None, ht.NoType, "Primary IP address"),
850
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
851
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
852
    ("group", None, ht.TMaybeString, "Initial node group"),
853
    ("master_capable", None, ht.TMaybeBool,
854
     "Whether node can become master or master candidate"),
855
    ("vm_capable", None, ht.TMaybeBool,
856
     "Whether node can host instances"),
857
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
858
    ]
859

    
860

    
861
class OpNodeQuery(OpCode):
862
  """Compute the list of nodes."""
863
  OP_PARAMS = [
864
    _POutputFields,
865
    _PUseLocking,
866
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
867
     "Empty list to query all nodes, node names otherwise"),
868
    ]
869

    
870

    
871
class OpNodeQueryvols(OpCode):
872
  """Get list of volumes on node."""
873
  OP_PARAMS = [
874
    _POutputFields,
875
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
876
     "Empty list to query all nodes, node names otherwise"),
877
    ]
878

    
879

    
880
class OpNodeQueryStorage(OpCode):
881
  """Get information on storage for node(s)."""
882
  OP_PARAMS = [
883
    _POutputFields,
884
    _PStorageType,
885
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
886
    ("name", None, ht.TMaybeString, "Storage name"),
887
    ]
888

    
889

    
890
class OpNodeModifyStorage(OpCode):
891
  """Modifies the properies of a storage unit"""
892
  OP_PARAMS = [
893
    _PNodeName,
894
    _PStorageType,
895
    _PStorageName,
896
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
897
    ]
898

    
899

    
900
class OpRepairNodeStorage(OpCode):
901
  """Repairs the volume group on a node."""
902
  OP_DSC_FIELD = "node_name"
903
  OP_PARAMS = [
904
    _PNodeName,
905
    _PStorageType,
906
    _PStorageName,
907
    _PIgnoreConsistency,
908
    ]
909

    
910

    
911
class OpNodeSetParams(OpCode):
912
  """Change the parameters of a node."""
913
  OP_DSC_FIELD = "node_name"
914
  OP_PARAMS = [
915
    _PNodeName,
916
    _PForce,
917
    ("master_candidate", None, ht.TMaybeBool,
918
     "Whether the node should become a master candidate"),
919
    ("offline", None, ht.TMaybeBool,
920
     "Whether the node should be marked as offline"),
921
    ("drained", None, ht.TMaybeBool,
922
     "Whether the node should be marked as drained"),
923
    ("auto_promote", False, ht.TBool,
924
     "Whether node(s) should be promoted to master candidate if necessary"),
925
    ("master_capable", None, ht.TMaybeBool,
926
     "Denote whether node can become master or master candidate"),
927
    ("vm_capable", None, ht.TMaybeBool,
928
     "Denote whether node can host instances"),
929
    ("secondary_ip", None, ht.TMaybeString,
930
     "Change node's secondary IP address"),
931
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
932
    ("powered", None, ht.TMaybeBool,
933
     "Whether the node should be marked as powered"),
934
    ]
935

    
936

    
937
class OpNodePowercycle(OpCode):
938
  """Tries to powercycle a node."""
939
  OP_DSC_FIELD = "node_name"
940
  OP_PARAMS = [
941
    _PNodeName,
942
    _PForce,
943
    ]
944

    
945

    
946
class OpNodeMigrate(OpCode):
947
  """Migrate all instances from a node."""
948
  OP_DSC_FIELD = "node_name"
949
  OP_PARAMS = [
950
    _PNodeName,
951
    _PMigrationMode,
952
    _PMigrationLive,
953
    _PMigrationTargetNode,
954
    ("iallocator", None, ht.TMaybeString,
955
     "Iallocator for deciding the target node for shared-storage instances"),
956
    ]
957

    
958

    
959
class OpNodeEvacuate(OpCode):
960
  """Evacuate instances off a number of nodes."""
961
  OP_DSC_FIELD = "node_name"
962
  OP_PARAMS = [
963
    _PEarlyRelease,
964
    _PNodeName,
965
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
966
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
967
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
968
     "Node evacuation mode"),
969
    ]
970

    
971

    
972
# instance opcodes
973

    
974
class OpInstanceCreate(OpCode):
975
  """Create an instance.
976

977
  @ivar instance_name: Instance name
978
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
979
  @ivar source_handshake: Signed handshake from source (remote import only)
980
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
981
  @ivar source_instance_name: Previous name of instance (remote import only)
982
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
983
    (remote import only)
984

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

    
1046

    
1047
class OpInstanceReinstall(OpCode):
1048
  """Reinstall an instance's OS."""
1049
  OP_DSC_FIELD = "instance_name"
1050
  OP_PARAMS = [
1051
    _PInstanceName,
1052
    _PForceVariant,
1053
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1054
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1055
    ]
1056

    
1057

    
1058
class OpInstanceRemove(OpCode):
1059
  """Remove an instance."""
1060
  OP_DSC_FIELD = "instance_name"
1061
  OP_PARAMS = [
1062
    _PInstanceName,
1063
    _PShutdownTimeout,
1064
    ("ignore_failures", False, ht.TBool,
1065
     "Whether to ignore failures during removal"),
1066
    ]
1067

    
1068

    
1069
class OpInstanceRename(OpCode):
1070
  """Rename an instance."""
1071
  OP_PARAMS = [
1072
    _PInstanceName,
1073
    _PNameCheck,
1074
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1075
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1076
    ]
1077

    
1078

    
1079
class OpInstanceStartup(OpCode):
1080
  """Startup an instance."""
1081
  OP_DSC_FIELD = "instance_name"
1082
  OP_PARAMS = [
1083
    _PInstanceName,
1084
    _PForce,
1085
    _PIgnoreOfflineNodes,
1086
    ("hvparams", ht.EmptyDict, ht.TDict,
1087
     "Temporary hypervisor parameters, hypervisor-dependent"),
1088
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1089
    _PNoRemember,
1090
    _PStartupPaused,
1091
    ]
1092

    
1093

    
1094
class OpInstanceShutdown(OpCode):
1095
  """Shutdown an instance."""
1096
  OP_DSC_FIELD = "instance_name"
1097
  OP_PARAMS = [
1098
    _PInstanceName,
1099
    _PIgnoreOfflineNodes,
1100
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1101
     "How long to wait for instance to shut down"),
1102
    _PNoRemember,
1103
    ]
1104

    
1105

    
1106
class OpInstanceReboot(OpCode):
1107
  """Reboot an instance."""
1108
  OP_DSC_FIELD = "instance_name"
1109
  OP_PARAMS = [
1110
    _PInstanceName,
1111
    _PShutdownTimeout,
1112
    ("ignore_secondaries", False, ht.TBool,
1113
     "Whether to start the instance even if secondary disks are failing"),
1114
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1115
     "How to reboot instance"),
1116
    ]
1117

    
1118

    
1119
class OpInstanceReplaceDisks(OpCode):
1120
  """Replace the disks of an instance."""
1121
  OP_DSC_FIELD = "instance_name"
1122
  OP_PARAMS = [
1123
    _PInstanceName,
1124
    _PEarlyRelease,
1125
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1126
     "Replacement mode"),
1127
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1128
     "Disk indexes"),
1129
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1130
    ("iallocator", None, ht.TMaybeString,
1131
     "Iallocator for deciding new secondary node"),
1132
    ]
1133

    
1134

    
1135
class OpInstanceFailover(OpCode):
1136
  """Failover an instance."""
1137
  OP_DSC_FIELD = "instance_name"
1138
  OP_PARAMS = [
1139
    _PInstanceName,
1140
    _PShutdownTimeout,
1141
    _PIgnoreConsistency,
1142
    _PMigrationTargetNode,
1143
    ("iallocator", None, ht.TMaybeString,
1144
     "Iallocator for deciding the target node for shared-storage instances"),
1145
    ]
1146

    
1147

    
1148
class OpInstanceMigrate(OpCode):
1149
  """Migrate an instance.
1150

1151
  This migrates (without shutting down an instance) to its secondary
1152
  node.
1153

1154
  @ivar instance_name: the name of the instance
1155
  @ivar mode: the migration mode (live, non-live or None for auto)
1156

1157
  """
1158
  OP_DSC_FIELD = "instance_name"
1159
  OP_PARAMS = [
1160
    _PInstanceName,
1161
    _PMigrationMode,
1162
    _PMigrationLive,
1163
    _PMigrationTargetNode,
1164
    ("cleanup", False, ht.TBool,
1165
     "Whether a previously failed migration should be cleaned up"),
1166
    ("iallocator", None, ht.TMaybeString,
1167
     "Iallocator for deciding the target node for shared-storage instances"),
1168
    ("allow_failover", False, ht.TBool,
1169
     "Whether we can fallback to failover if migration is not possible"),
1170
    ]
1171

    
1172

    
1173
class OpInstanceMove(OpCode):
1174
  """Move an instance.
1175

1176
  This move (with shutting down an instance and data copying) to an
1177
  arbitrary node.
1178

1179
  @ivar instance_name: the name of the instance
1180
  @ivar target_node: the destination node
1181

1182
  """
1183
  OP_DSC_FIELD = "instance_name"
1184
  OP_PARAMS = [
1185
    _PInstanceName,
1186
    _PShutdownTimeout,
1187
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1188
    _PIgnoreConsistency,
1189
    ]
1190

    
1191

    
1192
class OpInstanceConsole(OpCode):
1193
  """Connect to an instance's console."""
1194
  OP_DSC_FIELD = "instance_name"
1195
  OP_PARAMS = [
1196
    _PInstanceName
1197
    ]
1198

    
1199

    
1200
class OpInstanceActivateDisks(OpCode):
1201
  """Activate an instance's disks."""
1202
  OP_DSC_FIELD = "instance_name"
1203
  OP_PARAMS = [
1204
    _PInstanceName,
1205
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1206
    ]
1207

    
1208

    
1209
class OpInstanceDeactivateDisks(OpCode):
1210
  """Deactivate an instance's disks."""
1211
  OP_DSC_FIELD = "instance_name"
1212
  OP_PARAMS = [
1213
    _PInstanceName,
1214
    _PForce,
1215
    ]
1216

    
1217

    
1218
class OpInstanceRecreateDisks(OpCode):
1219
  """Deactivate an instance's disks."""
1220
  OP_DSC_FIELD = "instance_name"
1221
  OP_PARAMS = [
1222
    _PInstanceName,
1223
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1224
     "List of disk indexes"),
1225
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1226
     "New instance nodes, if relocation is desired"),
1227
    ]
1228

    
1229

    
1230
class OpInstanceQuery(OpCode):
1231
  """Compute the list of instances."""
1232
  OP_PARAMS = [
1233
    _POutputFields,
1234
    _PUseLocking,
1235
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1236
     "Empty list to query all instances, instance names otherwise"),
1237
    ]
1238

    
1239

    
1240
class OpInstanceQueryData(OpCode):
1241
  """Compute the run-time status of instances."""
1242
  OP_PARAMS = [
1243
    _PUseLocking,
1244
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1245
     "Instance names"),
1246
    ("static", False, ht.TBool,
1247
     "Whether to only return configuration data without querying"
1248
     " nodes"),
1249
    ]
1250

    
1251

    
1252
class OpInstanceSetParams(OpCode):
1253
  """Change the parameters of an instance."""
1254
  OP_DSC_FIELD = "instance_name"
1255
  OP_PARAMS = [
1256
    _PInstanceName,
1257
    _PForce,
1258
    _PForceVariant,
1259
    # TODO: Use _TestNicDef
1260
    ("nics", ht.EmptyList, ht.TList,
1261
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1262
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1263
     " ``%s`` to remove the last NIC or a number to modify the settings"
1264
     " of the NIC with that index." %
1265
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1266
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1267
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1268
    ("hvparams", ht.EmptyDict, ht.TDict,
1269
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1270
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1271
     "Disk template for instance"),
1272
    ("remote_node", None, ht.TMaybeString,
1273
     "Secondary node (used when changing disk template)"),
1274
    ("os_name", None, ht.TMaybeString,
1275
     "Change instance's OS name. Does not reinstall the instance."),
1276
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1277
    ("wait_for_sync", True, ht.TBool,
1278
     "Whether to wait for the disk to synchronize, when changing template"),
1279
    ]
1280

    
1281

    
1282
class OpInstanceGrowDisk(OpCode):
1283
  """Grow a disk of an instance."""
1284
  OP_DSC_FIELD = "instance_name"
1285
  OP_PARAMS = [
1286
    _PInstanceName,
1287
    _PWaitForSync,
1288
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1289
    ("amount", ht.NoDefault, ht.TInt,
1290
     "Amount of disk space to add (megabytes)"),
1291
    ]
1292

    
1293

    
1294
class OpInstanceChangeGroup(OpCode):
1295
  """Moves an instance to another node group."""
1296
  OP_DSC_FIELD = "instance_name"
1297
  OP_PARAMS = [
1298
    _PInstanceName,
1299
    _PEarlyRelease,
1300
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1301
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1302
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1303
    ]
1304

    
1305

    
1306
# Node group opcodes
1307

    
1308
class OpGroupAdd(OpCode):
1309
  """Add a node group to the cluster."""
1310
  OP_DSC_FIELD = "group_name"
1311
  OP_PARAMS = [
1312
    _PGroupName,
1313
    _PNodeGroupAllocPolicy,
1314
    _PGroupNodeParams,
1315
    ]
1316

    
1317

    
1318
class OpGroupAssignNodes(OpCode):
1319
  """Assign nodes to a node group."""
1320
  OP_DSC_FIELD = "group_name"
1321
  OP_PARAMS = [
1322
    _PGroupName,
1323
    _PForce,
1324
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1325
     "List of nodes to assign"),
1326
    ]
1327

    
1328

    
1329
class OpGroupQuery(OpCode):
1330
  """Compute the list of node groups."""
1331
  OP_PARAMS = [
1332
    _POutputFields,
1333
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1334
     "Empty list to query all groups, group names otherwise"),
1335
    ]
1336

    
1337

    
1338
class OpGroupSetParams(OpCode):
1339
  """Change the parameters of a node group."""
1340
  OP_DSC_FIELD = "group_name"
1341
  OP_PARAMS = [
1342
    _PGroupName,
1343
    _PNodeGroupAllocPolicy,
1344
    _PGroupNodeParams,
1345
    ]
1346

    
1347

    
1348
class OpGroupRemove(OpCode):
1349
  """Remove a node group from the cluster."""
1350
  OP_DSC_FIELD = "group_name"
1351
  OP_PARAMS = [
1352
    _PGroupName,
1353
    ]
1354

    
1355

    
1356
class OpGroupRename(OpCode):
1357
  """Rename a node group in the cluster."""
1358
  OP_PARAMS = [
1359
    _PGroupName,
1360
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1361
    ]
1362

    
1363

    
1364
class OpGroupEvacuate(OpCode):
1365
  """Evacuate a node group in the cluster."""
1366
  OP_DSC_FIELD = "group_name"
1367
  OP_PARAMS = [
1368
    _PGroupName,
1369
    _PEarlyRelease,
1370
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1371
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1372
     "Destination group names or UUIDs"),
1373
    ]
1374

    
1375

    
1376
# OS opcodes
1377
class OpOsDiagnose(OpCode):
1378
  """Compute the list of guest operating systems."""
1379
  OP_PARAMS = [
1380
    _POutputFields,
1381
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1382
     "Which operating systems to diagnose"),
1383
    ]
1384

    
1385

    
1386
# Exports opcodes
1387
class OpBackupQuery(OpCode):
1388
  """Compute the list of exported images."""
1389
  OP_PARAMS = [
1390
    _PUseLocking,
1391
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1392
     "Empty list to query all nodes, node names otherwise"),
1393
    ]
1394

    
1395

    
1396
class OpBackupPrepare(OpCode):
1397
  """Prepares an instance export.
1398

1399
  @ivar instance_name: Instance name
1400
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1401

1402
  """
1403
  OP_DSC_FIELD = "instance_name"
1404
  OP_PARAMS = [
1405
    _PInstanceName,
1406
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1407
     "Export mode"),
1408
    ]
1409

    
1410

    
1411
class OpBackupExport(OpCode):
1412
  """Export an instance.
1413

1414
  For local exports, the export destination is the node name. For remote
1415
  exports, the export destination is a list of tuples, each consisting of
1416
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1417
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1418
  destination X509 CA must be a signed certificate.
1419

1420
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1421
  @ivar target_node: Export destination
1422
  @ivar x509_key_name: X509 key to use (remote export only)
1423
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1424
                             only)
1425

1426
  """
1427
  OP_DSC_FIELD = "instance_name"
1428
  OP_PARAMS = [
1429
    _PInstanceName,
1430
    _PShutdownTimeout,
1431
    # TODO: Rename target_node as it changes meaning for different export modes
1432
    # (e.g. "destination")
1433
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1434
     "Destination information, depends on export mode"),
1435
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1436
    ("remove_instance", False, ht.TBool,
1437
     "Whether to remove instance after export"),
1438
    ("ignore_remove_failures", False, ht.TBool,
1439
     "Whether to ignore failures while removing instances"),
1440
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1441
     "Export mode"),
1442
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1443
     "Name of X509 key (remote export only)"),
1444
    ("destination_x509_ca", None, ht.TMaybeString,
1445
     "Destination X509 CA (remote export only)"),
1446
    ]
1447

    
1448

    
1449
class OpBackupRemove(OpCode):
1450
  """Remove an instance's export."""
1451
  OP_DSC_FIELD = "instance_name"
1452
  OP_PARAMS = [
1453
    _PInstanceName,
1454
    ]
1455

    
1456

    
1457
# Tags opcodes
1458
class OpTagsGet(OpCode):
1459
  """Returns the tags of the given object."""
1460
  OP_DSC_FIELD = "name"
1461
  OP_PARAMS = [
1462
    _PTagKind,
1463
    # Name is only meaningful for nodes and instances
1464
    ("name", ht.NoDefault, ht.TMaybeString, None),
1465
    ]
1466

    
1467

    
1468
class OpTagsSearch(OpCode):
1469
  """Searches the tags in the cluster for a given pattern."""
1470
  OP_DSC_FIELD = "pattern"
1471
  OP_PARAMS = [
1472
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1473
    ]
1474

    
1475

    
1476
class OpTagsSet(OpCode):
1477
  """Add a list of tags on a given object."""
1478
  OP_PARAMS = [
1479
    _PTagKind,
1480
    _PTags,
1481
    # Name is only meaningful for nodes and instances
1482
    ("name", ht.NoDefault, ht.TMaybeString, None),
1483
    ]
1484

    
1485

    
1486
class OpTagsDel(OpCode):
1487
  """Remove a list of tags from a given object."""
1488
  OP_PARAMS = [
1489
    _PTagKind,
1490
    _PTags,
1491
    # Name is only meaningful for nodes and instances
1492
    ("name", ht.NoDefault, ht.TMaybeString, None),
1493
    ]
1494

    
1495
# Test opcodes
1496
class OpTestDelay(OpCode):
1497
  """Sleeps for a configured amount of time.
1498

1499
  This is used just for debugging and testing.
1500

1501
  Parameters:
1502
    - duration: the time to sleep
1503
    - on_master: if true, sleep on the master
1504
    - on_nodes: list of nodes in which to sleep
1505

1506
  If the on_master parameter is true, it will execute a sleep on the
1507
  master (before any node sleep).
1508

1509
  If the on_nodes list is not empty, it will sleep on those nodes
1510
  (after the sleep on the master, if that is enabled).
1511

1512
  As an additional feature, the case of duration < 0 will be reported
1513
  as an execution error, so this opcode can be used as a failure
1514
  generator. The case of duration == 0 will not be treated specially.
1515

1516
  """
1517
  OP_DSC_FIELD = "duration"
1518
  OP_PARAMS = [
1519
    ("duration", ht.NoDefault, ht.TNumber, None),
1520
    ("on_master", True, ht.TBool, None),
1521
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1522
    ("repeat", 0, ht.TPositiveInt, None),
1523
    ]
1524

    
1525

    
1526
class OpTestAllocator(OpCode):
1527
  """Allocator framework testing.
1528

1529
  This opcode has two modes:
1530
    - gather and return allocator input for a given mode (allocate new
1531
      or replace secondary) and a given instance definition (direction
1532
      'in')
1533
    - run a selected allocator for a given operation (as above) and
1534
      return the allocator output (direction 'out')
1535

1536
  """
1537
  OP_DSC_FIELD = "allocator"
1538
  OP_PARAMS = [
1539
    ("direction", ht.NoDefault,
1540
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1541
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1542
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1543
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1544
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1545
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1546
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1547
    ("hypervisor", None, ht.TMaybeString, None),
1548
    ("allocator", None, ht.TMaybeString, None),
1549
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1550
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1551
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1552
    ("os", None, ht.TMaybeString, None),
1553
    ("disk_template", None, ht.TMaybeString, None),
1554
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1555
     None),
1556
    ("evac_mode", None,
1557
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1558
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1559
     None),
1560
    ]
1561

    
1562

    
1563
class OpTestJqueue(OpCode):
1564
  """Utility opcode to test some aspects of the job queue.
1565

1566
  """
1567
  OP_PARAMS = [
1568
    ("notify_waitlock", False, ht.TBool, None),
1569
    ("notify_exec", False, ht.TBool, None),
1570
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1571
    ("fail", False, ht.TBool, None),
1572
    ]
1573

    
1574

    
1575
class OpTestDummy(OpCode):
1576
  """Utility opcode used by unittests.
1577

1578
  """
1579
  OP_PARAMS = [
1580
    ("result", ht.NoDefault, ht.NoType, None),
1581
    ("messages", ht.NoDefault, ht.NoType, None),
1582
    ("fail", ht.NoDefault, ht.NoType, None),
1583
    ("submit_jobs", None, ht.NoType, None),
1584
    ]
1585
  WITH_LU = False
1586

    
1587

    
1588
def _GetOpList():
1589
  """Returns list of all defined opcodes.
1590

1591
  Does not eliminate duplicates by C{OP_ID}.
1592

1593
  """
1594
  return [v for v in globals().values()
1595
          if (isinstance(v, type) and issubclass(v, OpCode) and
1596
              hasattr(v, "OP_ID") and v is not OpCode)]
1597

    
1598

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