Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ fb926117

History | View | Annotate | Download (50.8 kB)

1
#
2
#
3

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

    
21

    
22
"""OpCodes module
23

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

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

30
"""
31

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

    
36
import logging
37
import re
38

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

    
44

    
45
# Common opcode attributes
46

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
133
# Parameters for cluster verification
134
_PDebugSimulateErrors = ("debug_simulate_errors", False, ht.TBool,
135
                         "Whether to simulate errors (useful for debugging)")
136
_PErrorCodes = ("error_codes", False, ht.TBool, "Error codes")
137
_PSkipChecks = ("skip_checks", ht.EmptyList,
138
                ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)),
139
                "Which checks to skip")
140

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

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

    
150

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

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

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

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

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

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

    
178

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

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

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

    
199

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

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

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

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

    
213

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

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

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

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

    
227

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

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

    
239

    
240
def _BuildDiskTemplateCheck(accept_none):
241
  """Builds check for disk template.
242

243
  @type accept_none: bool
244
  @param accept_none: whether to accept None as a correct value
245
  @rtype: callable
246

247
  """
248
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
249

    
250
  if accept_none:
251
    template_check = ht.TOr(template_check, ht.TNone)
252

    
253
  return ht.TAnd(template_check, _CheckFileStorage)
254

    
255

    
256
def _CheckStorageType(storage_type):
257
  """Ensure a given storage type is valid.
258

259
  """
260
  if storage_type not in constants.VALID_STORAGE_TYPES:
261
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
262
                               errors.ECODE_INVAL)
263
  if storage_type == constants.ST_FILE:
264
    RequireFileStorage()
265
  return True
266

    
267

    
268
#: Storage type parameter
269
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
270
                 "Storage type")
271

    
272

    
273
class _AutoOpParamSlots(type):
274
  """Meta class for opcode definitions.
275

276
  """
277
  def __new__(mcs, name, bases, attrs):
278
    """Called when a class should be created.
279

280
    @param mcs: The meta class
281
    @param name: Name of created class
282
    @param bases: Base classes
283
    @type attrs: dict
284
    @param attrs: Class attributes
285

286
    """
287
    assert "__slots__" not in attrs, \
288
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
289
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
290

    
291
    attrs["OP_ID"] = _NameToId(name)
292

    
293
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
294
    params = attrs.setdefault("OP_PARAMS", [])
295

    
296
    # Use parameter names as slots
297
    slots = [pname for (pname, _, _, _) in params]
298

    
299
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
300
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
301

    
302
    attrs["__slots__"] = slots
303

    
304
    return type.__new__(mcs, name, bases, attrs)
305

    
306

    
307
class BaseOpCode(object):
308
  """A simple serializable object.
309

310
  This object serves as a parent class for OpCode without any custom
311
  field handling.
312

313
  """
314
  # pylint: disable=E1101
315
  # as OP_ID is dynamically defined
316
  __metaclass__ = _AutoOpParamSlots
317

    
318
  def __init__(self, **kwargs):
319
    """Constructor for BaseOpCode.
320

321
    The constructor takes only keyword arguments and will set
322
    attributes on this object based on the passed arguments. As such,
323
    it means that you should not pass arguments which are not in the
324
    __slots__ attribute for this class.
325

326
    """
327
    slots = self._all_slots()
328
    for key in kwargs:
329
      if key not in slots:
330
        raise TypeError("Object %s doesn't support the parameter '%s'" %
331
                        (self.__class__.__name__, key))
332
      setattr(self, key, kwargs[key])
333

    
334
  def __getstate__(self):
335
    """Generic serializer.
336

337
    This method just returns the contents of the instance as a
338
    dictionary.
339

340
    @rtype:  C{dict}
341
    @return: the instance attributes and their values
342

343
    """
344
    state = {}
345
    for name in self._all_slots():
346
      if hasattr(self, name):
347
        state[name] = getattr(self, name)
348
    return state
349

    
350
  def __setstate__(self, state):
351
    """Generic unserializer.
352

353
    This method just restores from the serialized state the attributes
354
    of the current instance.
355

356
    @param state: the serialized opcode data
357
    @type state:  C{dict}
358

359
    """
360
    if not isinstance(state, dict):
361
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
362
                       type(state))
363

    
364
    for name in self._all_slots():
365
      if name not in state and hasattr(self, name):
366
        delattr(self, name)
367

    
368
    for name in state:
369
      setattr(self, name, state[name])
370

    
371
  @classmethod
372
  def _all_slots(cls):
373
    """Compute the list of all declared slots for a class.
374

375
    """
376
    slots = []
377
    for parent in cls.__mro__:
378
      slots.extend(getattr(parent, "__slots__", []))
379
    return slots
380

    
381
  @classmethod
382
  def GetAllParams(cls):
383
    """Compute list of all parameters for an opcode.
384

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

    
391
  def Validate(self, set_defaults):
392
    """Validate opcode parameters, optionally setting default values.
393

394
    @type set_defaults: bool
395
    @param set_defaults: Whether to set default values
396
    @raise errors.OpPrereqError: When a parameter value doesn't match
397
                                 requirements
398

399
    """
400
    for (attr_name, default, test, _) in self.GetAllParams():
401
      assert test == ht.NoType or callable(test)
402

    
403
      if not hasattr(self, attr_name):
404
        if default == ht.NoDefault:
405
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
406
                                     (self.OP_ID, attr_name),
407
                                     errors.ECODE_INVAL)
408
        elif set_defaults:
409
          if callable(default):
410
            dval = default()
411
          else:
412
            dval = default
413
          setattr(self, attr_name, dval)
414

    
415
      if test == ht.NoType:
416
        # no tests here
417
        continue
418

    
419
      if set_defaults or hasattr(self, attr_name):
420
        attr_val = getattr(self, attr_name)
421
        if not test(attr_val):
422
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
423
                        self.OP_ID, attr_name, type(attr_val), attr_val)
424
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
425
                                     (self.OP_ID, attr_name),
426
                                     errors.ECODE_INVAL)
427

    
428

    
429
def _BuildJobDepCheck(relative):
430
  """Builds check for job dependencies (L{DEPEND_ATTR}).
431

432
  @type relative: bool
433
  @param relative: Whether to accept relative job IDs (negative)
434
  @rtype: callable
435

436
  """
437
  if relative:
438
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
439
  else:
440
    job_id = ht.TJobId
441

    
442
  job_dep = \
443
    ht.TAnd(ht.TIsLength(2),
444
            ht.TItems([job_id,
445
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
446

    
447
  return ht.TOr(ht.TNone, ht.TListOf(job_dep))
448

    
449

    
450
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
451

    
452
#: List of submission status and job ID as returned by C{SubmitManyJobs}
453
_TJobIdListItem = \
454
  ht.TAnd(ht.TIsLength(2),
455
          ht.TItems([ht.Comment("success")(ht.TBool),
456
                     ht.Comment("Job ID if successful, error message"
457
                                " otherwise")(ht.TOr(ht.TString,
458
                                                     ht.TJobId))]))
459
TJobIdList = ht.TListOf(_TJobIdListItem)
460

    
461
#: Result containing only list of submitted jobs
462
TJobIdListOnly = ht.TStrictDict(True, True, {
463
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
464
  })
465

    
466

    
467
class OpCode(BaseOpCode):
468
  """Abstract OpCode.
469

470
  This is the root of the actual OpCode hierarchy. All clases derived
471
  from this class should override OP_ID.
472

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

487
  """
488
  # pylint: disable=E1101
489
  # as OP_ID is dynamically defined
490
  WITH_LU = True
491
  OP_PARAMS = [
492
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
493
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
494
    ("priority", constants.OP_PRIO_DEFAULT,
495
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
496
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
497
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
498
     " job IDs can be used"),
499
    (COMMENT_ATTR, None, ht.TMaybeString,
500
     "Comment describing the purpose of the opcode"),
501
    ]
502
  OP_RESULT = None
503

    
504
  def __getstate__(self):
505
    """Specialized getstate for opcodes.
506

507
    This method adds to the state dictionary the OP_ID of the class,
508
    so that on unload we can identify the correct class for
509
    instantiating the opcode.
510

511
    @rtype:   C{dict}
512
    @return:  the state as a dictionary
513

514
    """
515
    data = BaseOpCode.__getstate__(self)
516
    data["OP_ID"] = self.OP_ID
517
    return data
518

    
519
  @classmethod
520
  def LoadOpCode(cls, data):
521
    """Generic load opcode method.
522

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

527
    @type data:  C{dict}
528
    @param data: the serialized opcode
529

530
    """
531
    if not isinstance(data, dict):
532
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
533
    if "OP_ID" not in data:
534
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
535
    op_id = data["OP_ID"]
536
    op_class = None
537
    if op_id in OP_MAPPING:
538
      op_class = OP_MAPPING[op_id]
539
    else:
540
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
541
                       op_id)
542
    op = op_class()
543
    new_data = data.copy()
544
    del new_data["OP_ID"]
545
    op.__setstate__(new_data)
546
    return op
547

    
548
  def Summary(self):
549
    """Generates a summary description of this opcode.
550

551
    The summary is the value of the OP_ID attribute (without the "OP_"
552
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
553
    defined; this field should allow to easily identify the operation
554
    (for an instance creation job, e.g., it would be the instance
555
    name).
556

557
    """
558
    assert self.OP_ID is not None and len(self.OP_ID) > 3
559
    # all OP_ID start with OP_, we remove that
560
    txt = self.OP_ID[3:]
561
    field_name = getattr(self, "OP_DSC_FIELD", None)
562
    if field_name:
563
      field_value = getattr(self, field_name, None)
564
      if isinstance(field_value, (list, tuple)):
565
        field_value = ",".join(str(i) for i in field_value)
566
      txt = "%s(%s)" % (txt, field_value)
567
    return txt
568

    
569
  def TinySummary(self):
570
    """Generates a compact summary description of the opcode.
571

572
    """
573
    assert self.OP_ID.startswith("OP_")
574

    
575
    text = self.OP_ID[3:]
576

    
577
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
578
      if text.startswith(prefix):
579
        return supplement + text[len(prefix):]
580

    
581
    return text
582

    
583

    
584
# cluster opcodes
585

    
586
class OpClusterPostInit(OpCode):
587
  """Post cluster initialization.
588

589
  This opcode does not touch the cluster at all. Its purpose is to run hooks
590
  after the cluster has been initialized.
591

592
  """
593

    
594

    
595
class OpClusterDestroy(OpCode):
596
  """Destroy the cluster.
597

598
  This opcode has no other parameters. All the state is irreversibly
599
  lost after the execution of this opcode.
600

601
  """
602

    
603

    
604
class OpClusterQuery(OpCode):
605
  """Query cluster information."""
606

    
607

    
608
class OpClusterVerify(OpCode):
609
  """Submits all jobs necessary to verify the cluster.
610

611
  """
612
  OP_PARAMS = [
613
    _PDebugSimulateErrors,
614
    _PErrorCodes,
615
    _PSkipChecks,
616
    _PVerbose,
617
    ("group_name", None, ht.TMaybeString, "Group to verify")
618
    ]
619
  OP_RESULT = TJobIdListOnly
620

    
621

    
622
class OpClusterVerifyConfig(OpCode):
623
  """Verify the cluster config.
624

625
  """
626
  OP_PARAMS = [
627
    _PDebugSimulateErrors,
628
    _PErrorCodes,
629
    _PVerbose,
630
    ]
631
  OP_RESULT = ht.TBool
632

    
633

    
634
class OpClusterVerifyGroup(OpCode):
635
  """Run verify on a node group from the cluster.
636

637
  @type skip_checks: C{list}
638
  @ivar skip_checks: steps to be skipped from the verify process; this
639
                     needs to be a subset of
640
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
641
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
642

643
  """
644
  OP_DSC_FIELD = "group_name"
645
  OP_PARAMS = [
646
    _PGroupName,
647
    _PDebugSimulateErrors,
648
    _PErrorCodes,
649
    _PSkipChecks,
650
    _PVerbose,
651
    ]
652
  OP_RESULT = ht.TBool
653

    
654

    
655
class OpClusterVerifyDisks(OpCode):
656
  """Verify the cluster disks.
657

658
  """
659
  OP_RESULT = TJobIdListOnly
660

    
661

    
662
class OpGroupVerifyDisks(OpCode):
663
  """Verifies the status of all disks in a node group.
664

665
  Result: a tuple of three elements:
666
    - dict of node names with issues (values: error msg)
667
    - list of instances with degraded disks (that should be activated)
668
    - dict of instances with missing logical volumes (values: (node, vol)
669
      pairs with details about the missing volumes)
670

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

676
  Note that only instances that are drbd-based are taken into
677
  consideration. This might need to be revisited in the future.
678

679
  """
680
  OP_DSC_FIELD = "group_name"
681
  OP_PARAMS = [
682
    _PGroupName,
683
    ]
684
  OP_RESULT = \
685
    ht.TAnd(ht.TIsLength(3),
686
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
687
                       ht.TListOf(ht.TString),
688
                       ht.TDictOf(ht.TString, ht.TListOf(ht.TString))]))
689

    
690

    
691
class OpClusterRepairDiskSizes(OpCode):
692
  """Verify the disk sizes of the instances and fixes configuration
693
  mimatches.
694

695
  Parameters: optional instances list, in case we want to restrict the
696
  checks to only a subset of the instances.
697

698
  Result: a list of tuples, (instance, disk, new-size) for changed
699
  configurations.
700

701
  In normal operation, the list should be empty.
702

703
  @type instances: list
704
  @ivar instances: the list of instances to check, or empty for all instances
705

706
  """
707
  OP_PARAMS = [
708
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
709
    ]
710

    
711

    
712
class OpClusterConfigQuery(OpCode):
713
  """Query cluster configuration values."""
714
  OP_PARAMS = [
715
    _POutputFields
716
    ]
717

    
718

    
719
class OpClusterRename(OpCode):
720
  """Rename the cluster.
721

722
  @type name: C{str}
723
  @ivar name: The new name of the cluster. The name and/or the master IP
724
              address will be changed to match the new name and its IP
725
              address.
726

727
  """
728
  OP_DSC_FIELD = "name"
729
  OP_PARAMS = [
730
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
731
    ]
732

    
733

    
734
class OpClusterSetParams(OpCode):
735
  """Change the parameters of the cluster.
736

737
  @type vg_name: C{str} or C{None}
738
  @ivar vg_name: The new volume group name or None to disable LVM usage.
739

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

    
792

    
793
class OpClusterRedistConf(OpCode):
794
  """Force a full push of the cluster configuration.
795

796
  """
797

    
798

    
799
class OpClusterActivateMasterIp(OpCode):
800
  """Activate the master IP on the master node.
801

802
  """
803

    
804

    
805
class OpClusterDeactivateMasterIp(OpCode):
806
  """Deactivate the master IP on the master node.
807

808
  """
809

    
810

    
811
class OpQuery(OpCode):
812
  """Query for resources/items.
813

814
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
815
  @ivar fields: List of fields to retrieve
816
  @ivar filter: Query filter
817

818
  """
819
  OP_DSC_FIELD = "what"
820
  OP_PARAMS = [
821
    _PQueryWhat,
822
    _PUseLocking,
823
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
824
     "Requested fields"),
825
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
826
     "Query filter"),
827
    ]
828

    
829

    
830
class OpQueryFields(OpCode):
831
  """Query for available resource/item fields.
832

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

836
  """
837
  OP_DSC_FIELD = "what"
838
  OP_PARAMS = [
839
    _PQueryWhat,
840
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
841
     "Requested fields; if not given, all are returned"),
842
    ]
843

    
844

    
845
class OpOobCommand(OpCode):
846
  """Interact with OOB."""
847
  OP_PARAMS = [
848
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
849
     "List of nodes to run the OOB command against"),
850
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
851
     "OOB command to be run"),
852
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
853
     "Timeout before the OOB helper will be terminated"),
854
    ("ignore_status", False, ht.TBool,
855
     "Ignores the node offline status for power off"),
856
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
857
     "Time in seconds to wait between powering on nodes"),
858
    ]
859

    
860

    
861
# node opcodes
862

    
863
class OpNodeRemove(OpCode):
864
  """Remove a node.
865

866
  @type node_name: C{str}
867
  @ivar node_name: The name of the node to remove. If the node still has
868
                   instances on it, the operation will fail.
869

870
  """
871
  OP_DSC_FIELD = "node_name"
872
  OP_PARAMS = [
873
    _PNodeName,
874
    ]
875

    
876

    
877
class OpNodeAdd(OpCode):
878
  """Add a node to the cluster.
879

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

904
  """
905
  OP_DSC_FIELD = "node_name"
906
  OP_PARAMS = [
907
    _PNodeName,
908
    ("primary_ip", None, ht.NoType, "Primary IP address"),
909
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
910
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
911
    ("group", None, ht.TMaybeString, "Initial node group"),
912
    ("master_capable", None, ht.TMaybeBool,
913
     "Whether node can become master or master candidate"),
914
    ("vm_capable", None, ht.TMaybeBool,
915
     "Whether node can host instances"),
916
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
917
    ]
918

    
919

    
920
class OpNodeQuery(OpCode):
921
  """Compute the list of nodes."""
922
  OP_PARAMS = [
923
    _POutputFields,
924
    _PUseLocking,
925
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
926
     "Empty list to query all nodes, node names otherwise"),
927
    ]
928

    
929

    
930
class OpNodeQueryvols(OpCode):
931
  """Get list of volumes on node."""
932
  OP_PARAMS = [
933
    _POutputFields,
934
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
935
     "Empty list to query all nodes, node names otherwise"),
936
    ]
937

    
938

    
939
class OpNodeQueryStorage(OpCode):
940
  """Get information on storage for node(s)."""
941
  OP_PARAMS = [
942
    _POutputFields,
943
    _PStorageType,
944
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
945
    ("name", None, ht.TMaybeString, "Storage name"),
946
    ]
947

    
948

    
949
class OpNodeModifyStorage(OpCode):
950
  """Modifies the properies of a storage unit"""
951
  OP_PARAMS = [
952
    _PNodeName,
953
    _PStorageType,
954
    _PStorageName,
955
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
956
    ]
957

    
958

    
959
class OpRepairNodeStorage(OpCode):
960
  """Repairs the volume group on a node."""
961
  OP_DSC_FIELD = "node_name"
962
  OP_PARAMS = [
963
    _PNodeName,
964
    _PStorageType,
965
    _PStorageName,
966
    _PIgnoreConsistency,
967
    ]
968

    
969

    
970
class OpNodeSetParams(OpCode):
971
  """Change the parameters of a node."""
972
  OP_DSC_FIELD = "node_name"
973
  OP_PARAMS = [
974
    _PNodeName,
975
    _PForce,
976
    ("master_candidate", None, ht.TMaybeBool,
977
     "Whether the node should become a master candidate"),
978
    ("offline", None, ht.TMaybeBool,
979
     "Whether the node should be marked as offline"),
980
    ("drained", None, ht.TMaybeBool,
981
     "Whether the node should be marked as drained"),
982
    ("auto_promote", False, ht.TBool,
983
     "Whether node(s) should be promoted to master candidate if necessary"),
984
    ("master_capable", None, ht.TMaybeBool,
985
     "Denote whether node can become master or master candidate"),
986
    ("vm_capable", None, ht.TMaybeBool,
987
     "Denote whether node can host instances"),
988
    ("secondary_ip", None, ht.TMaybeString,
989
     "Change node's secondary IP address"),
990
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
991
    ("powered", None, ht.TMaybeBool,
992
     "Whether the node should be marked as powered"),
993
    ]
994
  OP_RESULT = _TSetParamsResult
995

    
996

    
997
class OpNodePowercycle(OpCode):
998
  """Tries to powercycle a node."""
999
  OP_DSC_FIELD = "node_name"
1000
  OP_PARAMS = [
1001
    _PNodeName,
1002
    _PForce,
1003
    ]
1004

    
1005

    
1006
class OpNodeMigrate(OpCode):
1007
  """Migrate all instances from a node."""
1008
  OP_DSC_FIELD = "node_name"
1009
  OP_PARAMS = [
1010
    _PNodeName,
1011
    _PMigrationMode,
1012
    _PMigrationLive,
1013
    _PMigrationTargetNode,
1014
    ("iallocator", None, ht.TMaybeString,
1015
     "Iallocator for deciding the target node for shared-storage instances"),
1016
    ]
1017

    
1018

    
1019
class OpNodeEvacuate(OpCode):
1020
  """Evacuate instances off a number of nodes."""
1021
  OP_DSC_FIELD = "node_name"
1022
  OP_PARAMS = [
1023
    _PEarlyRelease,
1024
    _PNodeName,
1025
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1026
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1027
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
1028
     "Node evacuation mode"),
1029
    ]
1030
  OP_RESULT = TJobIdListOnly
1031

    
1032

    
1033
# instance opcodes
1034

    
1035
class OpInstanceCreate(OpCode):
1036
  """Create an instance.
1037

1038
  @ivar instance_name: Instance name
1039
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1040
  @ivar source_handshake: Signed handshake from source (remote import only)
1041
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1042
  @ivar source_instance_name: Previous name of instance (remote import only)
1043
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1044
    (remote import only)
1045

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

    
1109

    
1110
class OpInstanceReinstall(OpCode):
1111
  """Reinstall an instance's OS."""
1112
  OP_DSC_FIELD = "instance_name"
1113
  OP_PARAMS = [
1114
    _PInstanceName,
1115
    _PForceVariant,
1116
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1117
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1118
    ]
1119

    
1120

    
1121
class OpInstanceRemove(OpCode):
1122
  """Remove an instance."""
1123
  OP_DSC_FIELD = "instance_name"
1124
  OP_PARAMS = [
1125
    _PInstanceName,
1126
    _PShutdownTimeout,
1127
    ("ignore_failures", False, ht.TBool,
1128
     "Whether to ignore failures during removal"),
1129
    ]
1130

    
1131

    
1132
class OpInstanceRename(OpCode):
1133
  """Rename an instance."""
1134
  OP_PARAMS = [
1135
    _PInstanceName,
1136
    _PNameCheck,
1137
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1138
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1139
    ]
1140
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1141

    
1142

    
1143
class OpInstanceStartup(OpCode):
1144
  """Startup an instance."""
1145
  OP_DSC_FIELD = "instance_name"
1146
  OP_PARAMS = [
1147
    _PInstanceName,
1148
    _PForce,
1149
    _PIgnoreOfflineNodes,
1150
    ("hvparams", ht.EmptyDict, ht.TDict,
1151
     "Temporary hypervisor parameters, hypervisor-dependent"),
1152
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1153
    _PNoRemember,
1154
    _PStartupPaused,
1155
    ]
1156

    
1157

    
1158
class OpInstanceShutdown(OpCode):
1159
  """Shutdown an instance."""
1160
  OP_DSC_FIELD = "instance_name"
1161
  OP_PARAMS = [
1162
    _PInstanceName,
1163
    _PIgnoreOfflineNodes,
1164
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1165
     "How long to wait for instance to shut down"),
1166
    _PNoRemember,
1167
    ]
1168

    
1169

    
1170
class OpInstanceReboot(OpCode):
1171
  """Reboot an instance."""
1172
  OP_DSC_FIELD = "instance_name"
1173
  OP_PARAMS = [
1174
    _PInstanceName,
1175
    _PShutdownTimeout,
1176
    ("ignore_secondaries", False, ht.TBool,
1177
     "Whether to start the instance even if secondary disks are failing"),
1178
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1179
     "How to reboot instance"),
1180
    ]
1181

    
1182

    
1183
class OpInstanceReplaceDisks(OpCode):
1184
  """Replace the disks of an instance."""
1185
  OP_DSC_FIELD = "instance_name"
1186
  OP_PARAMS = [
1187
    _PInstanceName,
1188
    _PEarlyRelease,
1189
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1190
     "Replacement mode"),
1191
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1192
     "Disk indexes"),
1193
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1194
    ("iallocator", None, ht.TMaybeString,
1195
     "Iallocator for deciding new secondary node"),
1196
    ]
1197

    
1198

    
1199
class OpInstanceFailover(OpCode):
1200
  """Failover an instance."""
1201
  OP_DSC_FIELD = "instance_name"
1202
  OP_PARAMS = [
1203
    _PInstanceName,
1204
    _PShutdownTimeout,
1205
    _PIgnoreConsistency,
1206
    _PMigrationTargetNode,
1207
    ("iallocator", None, ht.TMaybeString,
1208
     "Iallocator for deciding the target node for shared-storage instances"),
1209
    ]
1210

    
1211

    
1212
class OpInstanceMigrate(OpCode):
1213
  """Migrate an instance.
1214

1215
  This migrates (without shutting down an instance) to its secondary
1216
  node.
1217

1218
  @ivar instance_name: the name of the instance
1219
  @ivar mode: the migration mode (live, non-live or None for auto)
1220

1221
  """
1222
  OP_DSC_FIELD = "instance_name"
1223
  OP_PARAMS = [
1224
    _PInstanceName,
1225
    _PMigrationMode,
1226
    _PMigrationLive,
1227
    _PMigrationTargetNode,
1228
    ("cleanup", False, ht.TBool,
1229
     "Whether a previously failed migration should be cleaned up"),
1230
    ("iallocator", None, ht.TMaybeString,
1231
     "Iallocator for deciding the target node for shared-storage instances"),
1232
    ("allow_failover", False, ht.TBool,
1233
     "Whether we can fallback to failover if migration is not possible"),
1234
    ]
1235

    
1236

    
1237
class OpInstanceMove(OpCode):
1238
  """Move an instance.
1239

1240
  This move (with shutting down an instance and data copying) to an
1241
  arbitrary node.
1242

1243
  @ivar instance_name: the name of the instance
1244
  @ivar target_node: the destination node
1245

1246
  """
1247
  OP_DSC_FIELD = "instance_name"
1248
  OP_PARAMS = [
1249
    _PInstanceName,
1250
    _PShutdownTimeout,
1251
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1252
    _PIgnoreConsistency,
1253
    ]
1254

    
1255

    
1256
class OpInstanceConsole(OpCode):
1257
  """Connect to an instance's console."""
1258
  OP_DSC_FIELD = "instance_name"
1259
  OP_PARAMS = [
1260
    _PInstanceName
1261
    ]
1262

    
1263

    
1264
class OpInstanceActivateDisks(OpCode):
1265
  """Activate an instance's disks."""
1266
  OP_DSC_FIELD = "instance_name"
1267
  OP_PARAMS = [
1268
    _PInstanceName,
1269
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1270
    ]
1271

    
1272

    
1273
class OpInstanceDeactivateDisks(OpCode):
1274
  """Deactivate an instance's disks."""
1275
  OP_DSC_FIELD = "instance_name"
1276
  OP_PARAMS = [
1277
    _PInstanceName,
1278
    _PForce,
1279
    ]
1280

    
1281

    
1282
class OpInstanceRecreateDisks(OpCode):
1283
  """Recreate an instance's disks."""
1284
  OP_DSC_FIELD = "instance_name"
1285
  OP_PARAMS = [
1286
    _PInstanceName,
1287
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1288
     "List of disk indexes"),
1289
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1290
     "New instance nodes, if relocation is desired"),
1291
    ]
1292

    
1293

    
1294
class OpInstanceQuery(OpCode):
1295
  """Compute the list of instances."""
1296
  OP_PARAMS = [
1297
    _POutputFields,
1298
    _PUseLocking,
1299
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1300
     "Empty list to query all instances, instance names otherwise"),
1301
    ]
1302

    
1303

    
1304
class OpInstanceQueryData(OpCode):
1305
  """Compute the run-time status of instances."""
1306
  OP_PARAMS = [
1307
    _PUseLocking,
1308
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1309
     "Instance names"),
1310
    ("static", False, ht.TBool,
1311
     "Whether to only return configuration data without querying"
1312
     " nodes"),
1313
    ]
1314

    
1315

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

    
1346

    
1347
class OpInstanceGrowDisk(OpCode):
1348
  """Grow a disk of an instance."""
1349
  OP_DSC_FIELD = "instance_name"
1350
  OP_PARAMS = [
1351
    _PInstanceName,
1352
    _PWaitForSync,
1353
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1354
    ("amount", ht.NoDefault, ht.TInt,
1355
     "Amount of disk space to add (megabytes)"),
1356
    ]
1357

    
1358

    
1359
class OpInstanceChangeGroup(OpCode):
1360
  """Moves an instance to another node group."""
1361
  OP_DSC_FIELD = "instance_name"
1362
  OP_PARAMS = [
1363
    _PInstanceName,
1364
    _PEarlyRelease,
1365
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1366
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1367
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1368
    ]
1369
  OP_RESULT = TJobIdListOnly
1370

    
1371

    
1372
# Node group opcodes
1373

    
1374
class OpGroupAdd(OpCode):
1375
  """Add a node group to the cluster."""
1376
  OP_DSC_FIELD = "group_name"
1377
  OP_PARAMS = [
1378
    _PGroupName,
1379
    _PNodeGroupAllocPolicy,
1380
    _PGroupNodeParams,
1381
    ]
1382

    
1383

    
1384
class OpGroupAssignNodes(OpCode):
1385
  """Assign nodes to a node group."""
1386
  OP_DSC_FIELD = "group_name"
1387
  OP_PARAMS = [
1388
    _PGroupName,
1389
    _PForce,
1390
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1391
     "List of nodes to assign"),
1392
    ]
1393

    
1394

    
1395
class OpGroupQuery(OpCode):
1396
  """Compute the list of node groups."""
1397
  OP_PARAMS = [
1398
    _POutputFields,
1399
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1400
     "Empty list to query all groups, group names otherwise"),
1401
    ]
1402

    
1403

    
1404
class OpGroupSetParams(OpCode):
1405
  """Change the parameters of a node group."""
1406
  OP_DSC_FIELD = "group_name"
1407
  OP_PARAMS = [
1408
    _PGroupName,
1409
    _PNodeGroupAllocPolicy,
1410
    _PGroupNodeParams,
1411
    ]
1412
  OP_RESULT = _TSetParamsResult
1413

    
1414

    
1415
class OpGroupRemove(OpCode):
1416
  """Remove a node group from the cluster."""
1417
  OP_DSC_FIELD = "group_name"
1418
  OP_PARAMS = [
1419
    _PGroupName,
1420
    ]
1421

    
1422

    
1423
class OpGroupRename(OpCode):
1424
  """Rename a node group in the cluster."""
1425
  OP_PARAMS = [
1426
    _PGroupName,
1427
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1428
    ]
1429
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1430

    
1431

    
1432
class OpGroupEvacuate(OpCode):
1433
  """Evacuate a node group in the cluster."""
1434
  OP_DSC_FIELD = "group_name"
1435
  OP_PARAMS = [
1436
    _PGroupName,
1437
    _PEarlyRelease,
1438
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1439
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1440
     "Destination group names or UUIDs"),
1441
    ]
1442
  OP_RESULT = TJobIdListOnly
1443

    
1444

    
1445
# OS opcodes
1446
class OpOsDiagnose(OpCode):
1447
  """Compute the list of guest operating systems."""
1448
  OP_PARAMS = [
1449
    _POutputFields,
1450
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1451
     "Which operating systems to diagnose"),
1452
    ]
1453

    
1454

    
1455
# Exports opcodes
1456
class OpBackupQuery(OpCode):
1457
  """Compute the list of exported images."""
1458
  OP_PARAMS = [
1459
    _PUseLocking,
1460
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1461
     "Empty list to query all nodes, node names otherwise"),
1462
    ]
1463

    
1464

    
1465
class OpBackupPrepare(OpCode):
1466
  """Prepares an instance export.
1467

1468
  @ivar instance_name: Instance name
1469
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1470

1471
  """
1472
  OP_DSC_FIELD = "instance_name"
1473
  OP_PARAMS = [
1474
    _PInstanceName,
1475
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1476
     "Export mode"),
1477
    ]
1478

    
1479

    
1480
class OpBackupExport(OpCode):
1481
  """Export an instance.
1482

1483
  For local exports, the export destination is the node name. For remote
1484
  exports, the export destination is a list of tuples, each consisting of
1485
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1486
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1487
  destination X509 CA must be a signed certificate.
1488

1489
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1490
  @ivar target_node: Export destination
1491
  @ivar x509_key_name: X509 key to use (remote export only)
1492
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1493
                             only)
1494

1495
  """
1496
  OP_DSC_FIELD = "instance_name"
1497
  OP_PARAMS = [
1498
    _PInstanceName,
1499
    _PShutdownTimeout,
1500
    # TODO: Rename target_node as it changes meaning for different export modes
1501
    # (e.g. "destination")
1502
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1503
     "Destination information, depends on export mode"),
1504
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1505
    ("remove_instance", False, ht.TBool,
1506
     "Whether to remove instance after export"),
1507
    ("ignore_remove_failures", False, ht.TBool,
1508
     "Whether to ignore failures while removing instances"),
1509
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1510
     "Export mode"),
1511
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1512
     "Name of X509 key (remote export only)"),
1513
    ("destination_x509_ca", None, ht.TMaybeString,
1514
     "Destination X509 CA (remote export only)"),
1515
    ]
1516

    
1517

    
1518
class OpBackupRemove(OpCode):
1519
  """Remove an instance's export."""
1520
  OP_DSC_FIELD = "instance_name"
1521
  OP_PARAMS = [
1522
    _PInstanceName,
1523
    ]
1524

    
1525

    
1526
# Tags opcodes
1527
class OpTagsGet(OpCode):
1528
  """Returns the tags of the given object."""
1529
  OP_DSC_FIELD = "name"
1530
  OP_PARAMS = [
1531
    _PTagKind,
1532
    # Name is only meaningful for nodes and instances
1533
    ("name", ht.NoDefault, ht.TMaybeString, None),
1534
    ]
1535

    
1536

    
1537
class OpTagsSearch(OpCode):
1538
  """Searches the tags in the cluster for a given pattern."""
1539
  OP_DSC_FIELD = "pattern"
1540
  OP_PARAMS = [
1541
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1542
    ]
1543

    
1544

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

    
1554

    
1555
class OpTagsDel(OpCode):
1556
  """Remove a list of tags from a given object."""
1557
  OP_PARAMS = [
1558
    _PTagKind,
1559
    _PTags,
1560
    # Name is only meaningful for nodes and instances
1561
    ("name", ht.NoDefault, ht.TMaybeString, None),
1562
    ]
1563

    
1564

    
1565
# Test opcodes
1566
class OpTestDelay(OpCode):
1567
  """Sleeps for a configured amount of time.
1568

1569
  This is used just for debugging and testing.
1570

1571
  Parameters:
1572
    - duration: the time to sleep
1573
    - on_master: if true, sleep on the master
1574
    - on_nodes: list of nodes in which to sleep
1575

1576
  If the on_master parameter is true, it will execute a sleep on the
1577
  master (before any node sleep).
1578

1579
  If the on_nodes list is not empty, it will sleep on those nodes
1580
  (after the sleep on the master, if that is enabled).
1581

1582
  As an additional feature, the case of duration < 0 will be reported
1583
  as an execution error, so this opcode can be used as a failure
1584
  generator. The case of duration == 0 will not be treated specially.
1585

1586
  """
1587
  OP_DSC_FIELD = "duration"
1588
  OP_PARAMS = [
1589
    ("duration", ht.NoDefault, ht.TNumber, None),
1590
    ("on_master", True, ht.TBool, None),
1591
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1592
    ("repeat", 0, ht.TPositiveInt, None),
1593
    ]
1594

    
1595

    
1596
class OpTestAllocator(OpCode):
1597
  """Allocator framework testing.
1598

1599
  This opcode has two modes:
1600
    - gather and return allocator input for a given mode (allocate new
1601
      or replace secondary) and a given instance definition (direction
1602
      'in')
1603
    - run a selected allocator for a given operation (as above) and
1604
      return the allocator output (direction 'out')
1605

1606
  """
1607
  OP_DSC_FIELD = "allocator"
1608
  OP_PARAMS = [
1609
    ("direction", ht.NoDefault,
1610
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1611
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1612
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1613
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1614
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1615
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1616
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1617
    ("hypervisor", None, ht.TMaybeString, None),
1618
    ("allocator", None, ht.TMaybeString, None),
1619
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1620
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1621
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1622
    ("os", None, ht.TMaybeString, None),
1623
    ("disk_template", None, ht.TMaybeString, None),
1624
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1625
     None),
1626
    ("evac_mode", None,
1627
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1628
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1629
     None),
1630
    ]
1631

    
1632

    
1633
class OpTestJqueue(OpCode):
1634
  """Utility opcode to test some aspects of the job queue.
1635

1636
  """
1637
  OP_PARAMS = [
1638
    ("notify_waitlock", False, ht.TBool, None),
1639
    ("notify_exec", False, ht.TBool, None),
1640
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1641
    ("fail", False, ht.TBool, None),
1642
    ]
1643

    
1644

    
1645
class OpTestDummy(OpCode):
1646
  """Utility opcode used by unittests.
1647

1648
  """
1649
  OP_PARAMS = [
1650
    ("result", ht.NoDefault, ht.NoType, None),
1651
    ("messages", ht.NoDefault, ht.NoType, None),
1652
    ("fail", ht.NoDefault, ht.NoType, None),
1653
    ("submit_jobs", None, ht.NoType, None),
1654
    ]
1655
  WITH_LU = False
1656

    
1657

    
1658
def _GetOpList():
1659
  """Returns list of all defined opcodes.
1660

1661
  Does not eliminate duplicates by C{OP_ID}.
1662

1663
  """
1664
  return [v for v in globals().values()
1665
          if (isinstance(v, type) and issubclass(v, OpCode) and
1666
              hasattr(v, "OP_ID") and v is not OpCode)]
1667

    
1668

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