Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ c7741319

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

    
43

    
44
# Common opcode attributes
45

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

    
49
#: the shutdown timeout
50
_PShutdownTimeout = ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
51
                     ht.TPositiveInt)
52

    
53
#: the force parameter
54
_PForce = ("force", False, ht.TBool)
55

    
56
#: a required instance name (for single-instance LUs)
57
_PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString)
58

    
59
#: Whether to ignore offline nodes
60
_PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool)
61

    
62
#: a required node name (for single-node LUs)
63
_PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString)
64

    
65
#: a required node group name (for single-group LUs)
66
_PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString)
67

    
68
#: Migration type (live/non-live)
69
_PMigrationMode = ("mode", None,
70
                   ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)))
71

    
72
#: Obsolete 'live' migration mode (boolean)
73
_PMigrationLive = ("live", None, ht.TMaybeBool)
74

    
75
#: Tag type
76
_PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES))
77

    
78
#: List of tag strings
79
_PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString))
80

    
81
#: OP_ID conversion regular expression
82
_OPID_RE = re.compile("([a-z])([A-Z])")
83

    
84

    
85
def _NameToId(name):
86
  """Convert an opcode class name to an OP_ID.
87

88
  @type name: string
89
  @param name: the class name, as OpXxxYyy
90
  @rtype: string
91
  @return: the name in the OP_XXXX_YYYY format
92

93
  """
94
  if not name.startswith("Op"):
95
    return None
96
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
97
  # consume any input, and hence we would just have all the elements
98
  # in the list, one by one; but it seems that split doesn't work on
99
  # non-consuming input, hence we have to process the input string a
100
  # bit
101
  name = _OPID_RE.sub(r"\1,\2", name)
102
  elems = name.split(",")
103
  return "_".join(n.upper() for n in elems)
104

    
105

    
106
def RequireFileStorage():
107
  """Checks that file storage is enabled.
108

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

112
  @raise errors.OpPrereqError: when file storage is disabled
113

114
  """
115
  if not constants.ENABLE_FILE_STORAGE:
116
    raise errors.OpPrereqError("File storage disabled at configure time",
117
                               errors.ECODE_INVAL)
118

    
119

    
120
def RequireSharedFileStorage():
121
  """Checks that shared file storage is enabled.
122

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

126
  @raise errors.OpPrereqError: when shared file storage is disabled
127

128
  """
129
  if not constants.ENABLE_SHARED_FILE_STORAGE:
130
    raise errors.OpPrereqError("Shared file storage disabled at"
131
                               " configure time", errors.ECODE_INVAL)
132

    
133

    
134
def _CheckDiskTemplate(template):
135
  """Ensure a given disk template is valid.
136

137
  """
138
  if template not in constants.DISK_TEMPLATES:
139
    # Using str.join directly to avoid importing utils for CommaJoin
140
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
141
           (template, ", ".join(constants.DISK_TEMPLATES)))
142
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
143
  if template == constants.DT_FILE:
144
    RequireFileStorage()
145
  elif template == constants.DT_SHARED_FILE:
146
    RequireSharedFileStorage()
147
  return True
148

    
149

    
150
def _CheckStorageType(storage_type):
151
  """Ensure a given storage type is valid.
152

153
  """
154
  if storage_type not in constants.VALID_STORAGE_TYPES:
155
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
156
                               errors.ECODE_INVAL)
157
  if storage_type == constants.ST_FILE:
158
    RequireFileStorage()
159
  return True
160

    
161

    
162
#: Storage type parameter
163
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType)
164

    
165

    
166
class _AutoOpParamSlots(type):
167
  """Meta class for opcode definitions.
168

169
  """
170
  def __new__(mcs, name, bases, attrs):
171
    """Called when a class should be created.
172

173
    @param mcs: The meta class
174
    @param name: Name of created class
175
    @param bases: Base classes
176
    @type attrs: dict
177
    @param attrs: Class attributes
178

179
    """
180
    assert "__slots__" not in attrs, \
181
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
182
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
183

    
184
    attrs["OP_ID"] = _NameToId(name)
185

    
186
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
187
    params = attrs.setdefault("OP_PARAMS", [])
188

    
189
    # Use parameter names as slots
190
    slots = [pname for (pname, _, _) in params]
191

    
192
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
193
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
194

    
195
    attrs["__slots__"] = slots
196

    
197
    return type.__new__(mcs, name, bases, attrs)
198

    
199

    
200
class BaseOpCode(object):
201
  """A simple serializable object.
202

203
  This object serves as a parent class for OpCode without any custom
204
  field handling.
205

206
  """
207
  # pylint: disable-msg=E1101
208
  # as OP_ID is dynamically defined
209
  __metaclass__ = _AutoOpParamSlots
210

    
211
  def __init__(self, **kwargs):
212
    """Constructor for BaseOpCode.
213

214
    The constructor takes only keyword arguments and will set
215
    attributes on this object based on the passed arguments. As such,
216
    it means that you should not pass arguments which are not in the
217
    __slots__ attribute for this class.
218

219
    """
220
    slots = self._all_slots()
221
    for key in kwargs:
222
      if key not in slots:
223
        raise TypeError("Object %s doesn't support the parameter '%s'" %
224
                        (self.__class__.__name__, key))
225
      setattr(self, key, kwargs[key])
226

    
227
  def __getstate__(self):
228
    """Generic serializer.
229

230
    This method just returns the contents of the instance as a
231
    dictionary.
232

233
    @rtype:  C{dict}
234
    @return: the instance attributes and their values
235

236
    """
237
    state = {}
238
    for name in self._all_slots():
239
      if hasattr(self, name):
240
        state[name] = getattr(self, name)
241
    return state
242

    
243
  def __setstate__(self, state):
244
    """Generic unserializer.
245

246
    This method just restores from the serialized state the attributes
247
    of the current instance.
248

249
    @param state: the serialized opcode data
250
    @type state:  C{dict}
251

252
    """
253
    if not isinstance(state, dict):
254
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
255
                       type(state))
256

    
257
    for name in self._all_slots():
258
      if name not in state and hasattr(self, name):
259
        delattr(self, name)
260

    
261
    for name in state:
262
      setattr(self, name, state[name])
263

    
264
  @classmethod
265
  def _all_slots(cls):
266
    """Compute the list of all declared slots for a class.
267

268
    """
269
    slots = []
270
    for parent in cls.__mro__:
271
      slots.extend(getattr(parent, "__slots__", []))
272
    return slots
273

    
274
  @classmethod
275
  def GetAllParams(cls):
276
    """Compute list of all parameters for an opcode.
277

278
    """
279
    slots = []
280
    for parent in cls.__mro__:
281
      slots.extend(getattr(parent, "OP_PARAMS", []))
282
    return slots
283

    
284
  def Validate(self, set_defaults):
285
    """Validate opcode parameters, optionally setting default values.
286

287
    @type set_defaults: bool
288
    @param set_defaults: Whether to set default values
289
    @raise errors.OpPrereqError: When a parameter value doesn't match
290
                                 requirements
291

292
    """
293
    for (attr_name, default, test) in self.GetAllParams():
294
      assert test == ht.NoType or callable(test)
295

    
296
      if not hasattr(self, attr_name):
297
        if default == ht.NoDefault:
298
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
299
                                     (self.OP_ID, attr_name),
300
                                     errors.ECODE_INVAL)
301
        elif set_defaults:
302
          if callable(default):
303
            dval = default()
304
          else:
305
            dval = default
306
          setattr(self, attr_name, dval)
307

    
308
      if test == ht.NoType:
309
        # no tests here
310
        continue
311

    
312
      if set_defaults or hasattr(self, attr_name):
313
        attr_val = getattr(self, attr_name)
314
        if not test(attr_val):
315
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
316
                        self.OP_ID, attr_name, type(attr_val), attr_val)
317
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
318
                                     (self.OP_ID, attr_name),
319
                                     errors.ECODE_INVAL)
320

    
321

    
322
class OpCode(BaseOpCode):
323
  """Abstract OpCode.
324

325
  This is the root of the actual OpCode hierarchy. All clases derived
326
  from this class should override OP_ID.
327

328
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
329
               children of this class.
330
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
331
                      string returned by Summary(); see the docstring of that
332
                      method for details).
333
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
334
                   get if not already defined, and types they must match.
335
  @cvar WITH_LU: Boolean that specifies whether this should be included in
336
      mcpu's dispatch table
337
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
338
                 the check steps
339
  @ivar priority: Opcode priority for queue
340

341
  """
342
  # pylint: disable-msg=E1101
343
  # as OP_ID is dynamically defined
344
  WITH_LU = True
345
  OP_PARAMS = [
346
    ("dry_run", None, ht.TMaybeBool),
347
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
348
    ("priority", constants.OP_PRIO_DEFAULT,
349
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID)),
350
    ]
351

    
352
  def __getstate__(self):
353
    """Specialized getstate for opcodes.
354

355
    This method adds to the state dictionary the OP_ID of the class,
356
    so that on unload we can identify the correct class for
357
    instantiating the opcode.
358

359
    @rtype:   C{dict}
360
    @return:  the state as a dictionary
361

362
    """
363
    data = BaseOpCode.__getstate__(self)
364
    data["OP_ID"] = self.OP_ID
365
    return data
366

    
367
  @classmethod
368
  def LoadOpCode(cls, data):
369
    """Generic load opcode method.
370

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

375
    @type data:  C{dict}
376
    @param data: the serialized opcode
377

378
    """
379
    if not isinstance(data, dict):
380
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
381
    if "OP_ID" not in data:
382
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
383
    op_id = data["OP_ID"]
384
    op_class = None
385
    if op_id in OP_MAPPING:
386
      op_class = OP_MAPPING[op_id]
387
    else:
388
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
389
                       op_id)
390
    op = op_class()
391
    new_data = data.copy()
392
    del new_data["OP_ID"]
393
    op.__setstate__(new_data)
394
    return op
395

    
396
  def Summary(self):
397
    """Generates a summary description of this opcode.
398

399
    The summary is the value of the OP_ID attribute (without the "OP_"
400
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
401
    defined; this field should allow to easily identify the operation
402
    (for an instance creation job, e.g., it would be the instance
403
    name).
404

405
    """
406
    assert self.OP_ID is not None and len(self.OP_ID) > 3
407
    # all OP_ID start with OP_, we remove that
408
    txt = self.OP_ID[3:]
409
    field_name = getattr(self, "OP_DSC_FIELD", None)
410
    if field_name:
411
      field_value = getattr(self, field_name, None)
412
      if isinstance(field_value, (list, tuple)):
413
        field_value = ",".join(str(i) for i in field_value)
414
      txt = "%s(%s)" % (txt, field_value)
415
    return txt
416

    
417

    
418
# cluster opcodes
419

    
420
class OpClusterPostInit(OpCode):
421
  """Post cluster initialization.
422

423
  This opcode does not touch the cluster at all. Its purpose is to run hooks
424
  after the cluster has been initialized.
425

426
  """
427

    
428

    
429
class OpClusterDestroy(OpCode):
430
  """Destroy the cluster.
431

432
  This opcode has no other parameters. All the state is irreversibly
433
  lost after the execution of this opcode.
434

435
  """
436

    
437

    
438
class OpClusterQuery(OpCode):
439
  """Query cluster information."""
440

    
441

    
442
class OpClusterVerify(OpCode):
443
  """Verify the cluster state.
444

445
  @type skip_checks: C{list}
446
  @ivar skip_checks: steps to be skipped from the verify process; this
447
                     needs to be a subset of
448
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
449
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
450

451
  """
452
  OP_PARAMS = [
453
    ("skip_checks", ht.EmptyList,
454
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
455
    ("verbose", False, ht.TBool),
456
    ("error_codes", False, ht.TBool),
457
    ("debug_simulate_errors", False, ht.TBool),
458
    ]
459

    
460

    
461
class OpClusterVerifyDisks(OpCode):
462
  """Verify the cluster disks.
463

464
  Parameters: none
465

466
  Result: a tuple of four elements:
467
    - list of node names with bad data returned (unreachable, etc.)
468
    - dict of node names with broken volume groups (values: error msg)
469
    - list of instances with degraded disks (that should be activated)
470
    - dict of instances with missing logical volumes (values: (node, vol)
471
      pairs with details about the missing volumes)
472

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

478
  Note that only instances that are drbd-based are taken into
479
  consideration. This might need to be revisited in the future.
480

481
  """
482

    
483

    
484
class OpClusterRepairDiskSizes(OpCode):
485
  """Verify the disk sizes of the instances and fixes configuration
486
  mimatches.
487

488
  Parameters: optional instances list, in case we want to restrict the
489
  checks to only a subset of the instances.
490

491
  Result: a list of tuples, (instance, disk, new-size) for changed
492
  configurations.
493

494
  In normal operation, the list should be empty.
495

496
  @type instances: list
497
  @ivar instances: the list of instances to check, or empty for all instances
498

499
  """
500
  OP_PARAMS = [
501
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
502
    ]
503

    
504

    
505
class OpClusterConfigQuery(OpCode):
506
  """Query cluster configuration values."""
507
  OP_PARAMS = [
508
    _POutputFields
509
    ]
510

    
511

    
512
class OpClusterRename(OpCode):
513
  """Rename the cluster.
514

515
  @type name: C{str}
516
  @ivar name: The new name of the cluster. The name and/or the master IP
517
              address will be changed to match the new name and its IP
518
              address.
519

520
  """
521
  OP_DSC_FIELD = "name"
522
  OP_PARAMS = [
523
    ("name", ht.NoDefault, ht.TNonEmptyString),
524
    ]
525

    
526

    
527
class OpClusterSetParams(OpCode):
528
  """Change the parameters of the cluster.
529

530
  @type vg_name: C{str} or C{None}
531
  @ivar vg_name: The new volume group name or None to disable LVM usage.
532

533
  """
534
  OP_PARAMS = [
535
    ("vg_name", None, ht.TMaybeString),
536
    ("enabled_hypervisors", None,
537
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
538
            ht.TNone)),
539
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
540
                              ht.TNone)),
541
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone)),
542
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
543
                            ht.TNone)),
544
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
545
                              ht.TNone)),
546
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone)),
547
    ("uid_pool", None, ht.NoType),
548
    ("add_uids", None, ht.NoType),
549
    ("remove_uids", None, ht.NoType),
550
    ("maintain_node_health", None, ht.TMaybeBool),
551
    ("prealloc_wipe_disks", None, ht.TMaybeBool),
552
    ("nicparams", None, ht.TMaybeDict),
553
    ("ndparams", None, ht.TMaybeDict),
554
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone)),
555
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone)),
556
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone)),
557
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone)),
558
    ("hidden_os", None, ht.TOr(ht.TListOf(
559
          ht.TAnd(ht.TList,
560
                ht.TIsLength(2),
561
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
562
          ht.TNone)),
563
    ("blacklisted_os", None, ht.TOr(ht.TListOf(
564
          ht.TAnd(ht.TList,
565
                ht.TIsLength(2),
566
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
567
          ht.TNone)),
568
    ]
569

    
570

    
571
class OpClusterRedistConf(OpCode):
572
  """Force a full push of the cluster configuration.
573

574
  """
575

    
576

    
577
class OpQuery(OpCode):
578
  """Query for resources/items.
579

580
  @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
581
  @ivar fields: List of fields to retrieve
582
  @ivar filter: Query filter
583

584
  """
585
  OP_PARAMS = [
586
    ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY)),
587
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
588
    ("filter", None, ht.TOr(ht.TNone,
589
                            ht.TListOf(ht.TOr(ht.TNonEmptyString, ht.TList)))),
590
    ]
591

    
592

    
593
class OpQueryFields(OpCode):
594
  """Query for available resource/item fields.
595

596
  @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
597
  @ivar fields: List of fields to retrieve
598

599
  """
600
  OP_PARAMS = [
601
    ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY)),
602
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
603
    ]
604

    
605

    
606
class OpOobCommand(OpCode):
607
  """Interact with OOB."""
608
  OP_PARAMS = [
609
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
610
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS)),
611
    ("timeout", constants.OOB_TIMEOUT, ht.TInt),
612
    ]
613

    
614

    
615
# node opcodes
616

    
617
class OpNodeRemove(OpCode):
618
  """Remove a node.
619

620
  @type node_name: C{str}
621
  @ivar node_name: The name of the node to remove. If the node still has
622
                   instances on it, the operation will fail.
623

624
  """
625
  OP_DSC_FIELD = "node_name"
626
  OP_PARAMS = [
627
    _PNodeName,
628
    ]
629

    
630

    
631
class OpNodeAdd(OpCode):
632
  """Add a node to the cluster.
633

634
  @type node_name: C{str}
635
  @ivar node_name: The name of the node to add. This can be a short name,
636
                   but it will be expanded to the FQDN.
637
  @type primary_ip: IP address
638
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
639
                    opcode is submitted, but will be filled during the node
640
                    add (so it will be visible in the job query).
641
  @type secondary_ip: IP address
642
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
643
                      if the cluster has been initialized in 'dual-network'
644
                      mode, otherwise it must not be given.
645
  @type readd: C{bool}
646
  @ivar readd: Whether to re-add an existing node to the cluster. If
647
               this is not passed, then the operation will abort if the node
648
               name is already in the cluster; use this parameter to 'repair'
649
               a node that had its configuration broken, or was reinstalled
650
               without removal from the cluster.
651
  @type group: C{str}
652
  @ivar group: The node group to which this node will belong.
653
  @type vm_capable: C{bool}
654
  @ivar vm_capable: The vm_capable node attribute
655
  @type master_capable: C{bool}
656
  @ivar master_capable: The master_capable node attribute
657

658
  """
659
  OP_DSC_FIELD = "node_name"
660
  OP_PARAMS = [
661
    _PNodeName,
662
    ("primary_ip", None, ht.NoType),
663
    ("secondary_ip", None, ht.TMaybeString),
664
    ("readd", False, ht.TBool),
665
    ("group", None, ht.TMaybeString),
666
    ("master_capable", None, ht.TMaybeBool),
667
    ("vm_capable", None, ht.TMaybeBool),
668
    ("ndparams", None, ht.TMaybeDict),
669
    ]
670

    
671

    
672
class OpNodeQuery(OpCode):
673
  """Compute the list of nodes."""
674
  OP_PARAMS = [
675
    _POutputFields,
676
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
677
    ("use_locking", False, ht.TBool),
678
    ]
679

    
680

    
681
class OpNodeQueryvols(OpCode):
682
  """Get list of volumes on node."""
683
  OP_PARAMS = [
684
    _POutputFields,
685
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
686
    ]
687

    
688

    
689
class OpNodeQueryStorage(OpCode):
690
  """Get information on storage for node(s)."""
691
  OP_PARAMS = [
692
    _POutputFields,
693
    _PStorageType,
694
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
695
    ("name", None, ht.TMaybeString),
696
    ]
697

    
698

    
699
class OpNodeModifyStorage(OpCode):
700
  """Modifies the properies of a storage unit"""
701
  OP_PARAMS = [
702
    _PNodeName,
703
    _PStorageType,
704
    ("name", ht.NoDefault, ht.TNonEmptyString),
705
    ("changes", ht.NoDefault, ht.TDict),
706
    ]
707

    
708

    
709
class OpRepairNodeStorage(OpCode):
710
  """Repairs the volume group on a node."""
711
  OP_DSC_FIELD = "node_name"
712
  OP_PARAMS = [
713
    _PNodeName,
714
    _PStorageType,
715
    ("name", ht.NoDefault, ht.TNonEmptyString),
716
    ("ignore_consistency", False, ht.TBool),
717
    ]
718

    
719

    
720
class OpNodeSetParams(OpCode):
721
  """Change the parameters of a node."""
722
  OP_DSC_FIELD = "node_name"
723
  OP_PARAMS = [
724
    _PNodeName,
725
    _PForce,
726
    ("master_candidate", None, ht.TMaybeBool),
727
    ("offline", None, ht.TMaybeBool),
728
    ("drained", None, ht.TMaybeBool),
729
    ("auto_promote", False, ht.TBool),
730
    ("master_capable", None, ht.TMaybeBool),
731
    ("vm_capable", None, ht.TMaybeBool),
732
    ("secondary_ip", None, ht.TMaybeString),
733
    ("ndparams", None, ht.TMaybeDict),
734
    ("powered", None, ht.TMaybeBool),
735
    ]
736

    
737

    
738
class OpNodePowercycle(OpCode):
739
  """Tries to powercycle a node."""
740
  OP_DSC_FIELD = "node_name"
741
  OP_PARAMS = [
742
    _PNodeName,
743
    _PForce,
744
    ]
745

    
746

    
747
class OpNodeMigrate(OpCode):
748
  """Migrate all instances from a node."""
749
  OP_DSC_FIELD = "node_name"
750
  OP_PARAMS = [
751
    _PNodeName,
752
    _PMigrationMode,
753
    _PMigrationLive,
754
    ("iallocator", None, ht.TMaybeString),
755
    ]
756

    
757

    
758
class OpNodeEvacStrategy(OpCode):
759
  """Compute the evacuation strategy for a list of nodes."""
760
  OP_DSC_FIELD = "nodes"
761
  OP_PARAMS = [
762
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
763
    ("remote_node", None, ht.TMaybeString),
764
    ("iallocator", None, ht.TMaybeString),
765
    ]
766

    
767

    
768
# instance opcodes
769

    
770
class OpInstanceCreate(OpCode):
771
  """Create an instance.
772

773
  @ivar instance_name: Instance name
774
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
775
  @ivar source_handshake: Signed handshake from source (remote import only)
776
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
777
  @ivar source_instance_name: Previous name of instance (remote import only)
778
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
779
    (remote import only)
780

781
  """
782
  OP_DSC_FIELD = "instance_name"
783
  OP_PARAMS = [
784
    _PInstanceName,
785
    ("beparams", ht.EmptyDict, ht.TDict),
786
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
787
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
788
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
789
    ("file_storage_dir", None, ht.TMaybeString),
790
    ("force_variant", False, ht.TBool),
791
    ("hvparams", ht.EmptyDict, ht.TDict),
792
    ("hypervisor", None, ht.TMaybeString),
793
    ("iallocator", None, ht.TMaybeString),
794
    ("identify_defaults", False, ht.TBool),
795
    ("ip_check", True, ht.TBool),
796
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
797
    ("name_check", True, ht.TBool),
798
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
799
    ("no_install", None, ht.TMaybeBool),
800
    ("osparams", ht.EmptyDict, ht.TDict),
801
    ("os_type", None, ht.TMaybeString),
802
    ("pnode", None, ht.TMaybeString),
803
    ("snode", None, ht.TMaybeString),
804
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
805
    ("source_instance_name", None, ht.TMaybeString),
806
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
807
     ht.TPositiveInt),
808
    ("source_x509_ca", None, ht.TMaybeString),
809
    ("src_node", None, ht.TMaybeString),
810
    ("src_path", None, ht.TMaybeString),
811
    ("start", True, ht.TBool),
812
    ("wait_for_sync", True, ht.TBool),
813
    ]
814

    
815

    
816
class OpInstanceReinstall(OpCode):
817
  """Reinstall an instance's OS."""
818
  OP_DSC_FIELD = "instance_name"
819
  OP_PARAMS = [
820
    _PInstanceName,
821
    ("os_type", None, ht.TMaybeString),
822
    ("force_variant", False, ht.TBool),
823
    ("osparams", None, ht.TMaybeDict),
824
    ]
825

    
826

    
827
class OpInstanceRemove(OpCode):
828
  """Remove an instance."""
829
  OP_DSC_FIELD = "instance_name"
830
  OP_PARAMS = [
831
    _PInstanceName,
832
    _PShutdownTimeout,
833
    ("ignore_failures", False, ht.TBool),
834
    ]
835

    
836

    
837
class OpInstanceRename(OpCode):
838
  """Rename an instance."""
839
  OP_PARAMS = [
840
    _PInstanceName,
841
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
842
    ("ip_check", False, ht.TBool),
843
    ("name_check", True, ht.TBool),
844
    ]
845

    
846

    
847
class OpInstanceStartup(OpCode):
848
  """Startup an instance."""
849
  OP_DSC_FIELD = "instance_name"
850
  OP_PARAMS = [
851
    _PInstanceName,
852
    _PForce,
853
    _PIgnoreOfflineNodes,
854
    ("hvparams", ht.EmptyDict, ht.TDict),
855
    ("beparams", ht.EmptyDict, ht.TDict),
856
    ]
857

    
858

    
859
class OpInstanceShutdown(OpCode):
860
  """Shutdown an instance."""
861
  OP_DSC_FIELD = "instance_name"
862
  OP_PARAMS = [
863
    _PInstanceName,
864
    _PIgnoreOfflineNodes,
865
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
866
    ]
867

    
868

    
869
class OpInstanceReboot(OpCode):
870
  """Reboot an instance."""
871
  OP_DSC_FIELD = "instance_name"
872
  OP_PARAMS = [
873
    _PInstanceName,
874
    _PShutdownTimeout,
875
    ("ignore_secondaries", False, ht.TBool),
876
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
877
    ]
878

    
879

    
880
class OpInstanceReplaceDisks(OpCode):
881
  """Replace the disks of an instance."""
882
  OP_DSC_FIELD = "instance_name"
883
  OP_PARAMS = [
884
    _PInstanceName,
885
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
886
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
887
    ("remote_node", None, ht.TMaybeString),
888
    ("iallocator", None, ht.TMaybeString),
889
    ("early_release", False, ht.TBool),
890
    ]
891

    
892

    
893
class OpInstanceFailover(OpCode):
894
  """Failover an instance."""
895
  OP_DSC_FIELD = "instance_name"
896
  OP_PARAMS = [
897
    _PInstanceName,
898
    _PShutdownTimeout,
899
    ("ignore_consistency", False, ht.TBool),
900
    ("iallocator", None, ht.TMaybeString),
901
    ("target_node", None, ht.TMaybeString),
902
    ]
903

    
904

    
905
class OpInstanceMigrate(OpCode):
906
  """Migrate an instance.
907

908
  This migrates (without shutting down an instance) to its secondary
909
  node.
910

911
  @ivar instance_name: the name of the instance
912
  @ivar mode: the migration mode (live, non-live or None for auto)
913

914
  """
915
  OP_DSC_FIELD = "instance_name"
916
  OP_PARAMS = [
917
    _PInstanceName,
918
    _PMigrationMode,
919
    _PMigrationLive,
920
    ("cleanup", False, ht.TBool),
921
    ("iallocator", None, ht.TMaybeString),
922
    ("target_node", None, ht.TMaybeString),
923
    ]
924

    
925

    
926
class OpInstanceMove(OpCode):
927
  """Move an instance.
928

929
  This move (with shutting down an instance and data copying) to an
930
  arbitrary node.
931

932
  @ivar instance_name: the name of the instance
933
  @ivar target_node: the destination node
934

935
  """
936
  OP_DSC_FIELD = "instance_name"
937
  OP_PARAMS = [
938
    _PInstanceName,
939
    _PShutdownTimeout,
940
    ("target_node", ht.NoDefault, ht.TNonEmptyString),
941
    ]
942

    
943

    
944
class OpInstanceConsole(OpCode):
945
  """Connect to an instance's console."""
946
  OP_DSC_FIELD = "instance_name"
947
  OP_PARAMS = [
948
    _PInstanceName
949
    ]
950

    
951

    
952
class OpInstanceActivateDisks(OpCode):
953
  """Activate an instance's disks."""
954
  OP_DSC_FIELD = "instance_name"
955
  OP_PARAMS = [
956
    _PInstanceName,
957
    ("ignore_size", False, ht.TBool),
958
    ]
959

    
960

    
961
class OpInstanceDeactivateDisks(OpCode):
962
  """Deactivate an instance's disks."""
963
  OP_DSC_FIELD = "instance_name"
964
  OP_PARAMS = [
965
    _PInstanceName,
966
    _PForce,
967
    ]
968

    
969

    
970
class OpInstanceRecreateDisks(OpCode):
971
  """Deactivate an instance's disks."""
972
  OP_DSC_FIELD = "instance_name"
973
  OP_PARAMS = [
974
    _PInstanceName,
975
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
976
    ]
977

    
978

    
979
class OpInstanceQuery(OpCode):
980
  """Compute the list of instances."""
981
  OP_PARAMS = [
982
    _POutputFields,
983
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
984
    ("use_locking", False, ht.TBool),
985
    ]
986

    
987

    
988
class OpInstanceQueryData(OpCode):
989
  """Compute the run-time status of instances."""
990
  OP_PARAMS = [
991
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
992
    ("static", False, ht.TBool),
993
    ]
994

    
995

    
996
class OpInstanceSetParams(OpCode):
997
  """Change the parameters of an instance."""
998
  OP_DSC_FIELD = "instance_name"
999
  OP_PARAMS = [
1000
    _PInstanceName,
1001
    _PForce,
1002
    ("nics", ht.EmptyList, ht.TList),
1003
    ("disks", ht.EmptyList, ht.TList),
1004
    ("beparams", ht.EmptyDict, ht.TDict),
1005
    ("hvparams", ht.EmptyDict, ht.TDict),
1006
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate)),
1007
    ("remote_node", None, ht.TMaybeString),
1008
    ("os_name", None, ht.TMaybeString),
1009
    ("force_variant", False, ht.TBool),
1010
    ("osparams", None, ht.TMaybeDict),
1011
    ]
1012

    
1013

    
1014
class OpInstanceGrowDisk(OpCode):
1015
  """Grow a disk of an instance."""
1016
  OP_DSC_FIELD = "instance_name"
1017
  OP_PARAMS = [
1018
    _PInstanceName,
1019
    ("disk", ht.NoDefault, ht.TInt),
1020
    ("amount", ht.NoDefault, ht.TInt),
1021
    ("wait_for_sync", True, ht.TBool),
1022
    ]
1023

    
1024

    
1025
# Node group opcodes
1026

    
1027
class OpGroupAdd(OpCode):
1028
  """Add a node group to the cluster."""
1029
  OP_DSC_FIELD = "group_name"
1030
  OP_PARAMS = [
1031
    _PGroupName,
1032
    ("ndparams", None, ht.TMaybeDict),
1033
    ("alloc_policy", None,
1034
     ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES))),
1035
    ]
1036

    
1037

    
1038
class OpGroupAssignNodes(OpCode):
1039
  """Assign nodes to a node group."""
1040
  OP_DSC_FIELD = "group_name"
1041
  OP_PARAMS = [
1042
    _PGroupName,
1043
    _PForce,
1044
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
1045
    ]
1046

    
1047

    
1048
class OpGroupQuery(OpCode):
1049
  """Compute the list of node groups."""
1050
  OP_PARAMS = [
1051
    _POutputFields,
1052
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1053
    ]
1054

    
1055

    
1056
class OpGroupSetParams(OpCode):
1057
  """Change the parameters of a node group."""
1058
  OP_DSC_FIELD = "group_name"
1059
  OP_PARAMS = [
1060
    _PGroupName,
1061
    ("ndparams", None, ht.TMaybeDict),
1062
    ("alloc_policy", None, ht.TOr(ht.TNone,
1063
                                  ht.TElemOf(constants.VALID_ALLOC_POLICIES))),
1064
    ]
1065

    
1066

    
1067
class OpGroupRemove(OpCode):
1068
  """Remove a node group from the cluster."""
1069
  OP_DSC_FIELD = "group_name"
1070
  OP_PARAMS = [
1071
    _PGroupName,
1072
    ]
1073

    
1074

    
1075
class OpGroupRename(OpCode):
1076
  """Rename a node group in the cluster."""
1077
  OP_DSC_FIELD = "old_name"
1078
  OP_PARAMS = [
1079
    ("old_name", ht.NoDefault, ht.TNonEmptyString),
1080
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
1081
    ]
1082

    
1083

    
1084
# OS opcodes
1085
class OpOsDiagnose(OpCode):
1086
  """Compute the list of guest operating systems."""
1087
  OP_PARAMS = [
1088
    _POutputFields,
1089
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1090
    ]
1091

    
1092

    
1093
# Exports opcodes
1094
class OpBackupQuery(OpCode):
1095
  """Compute the list of exported images."""
1096
  OP_PARAMS = [
1097
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1098
    ("use_locking", False, ht.TBool),
1099
    ]
1100

    
1101

    
1102
class OpBackupPrepare(OpCode):
1103
  """Prepares an instance export.
1104

1105
  @ivar instance_name: Instance name
1106
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1107

1108
  """
1109
  OP_DSC_FIELD = "instance_name"
1110
  OP_PARAMS = [
1111
    _PInstanceName,
1112
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
1113
    ]
1114

    
1115

    
1116
class OpBackupExport(OpCode):
1117
  """Export an instance.
1118

1119
  For local exports, the export destination is the node name. For remote
1120
  exports, the export destination is a list of tuples, each consisting of
1121
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1122
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1123
  destination X509 CA must be a signed certificate.
1124

1125
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1126
  @ivar target_node: Export destination
1127
  @ivar x509_key_name: X509 key to use (remote export only)
1128
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1129
                             only)
1130

1131
  """
1132
  OP_DSC_FIELD = "instance_name"
1133
  OP_PARAMS = [
1134
    _PInstanceName,
1135
    _PShutdownTimeout,
1136
    # TODO: Rename target_node as it changes meaning for different export modes
1137
    # (e.g. "destination")
1138
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
1139
    ("shutdown", True, ht.TBool),
1140
    ("remove_instance", False, ht.TBool),
1141
    ("ignore_remove_failures", False, ht.TBool),
1142
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
1143
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
1144
    ("destination_x509_ca", None, ht.TMaybeString),
1145
    ]
1146

    
1147

    
1148
class OpBackupRemove(OpCode):
1149
  """Remove an instance's export."""
1150
  OP_DSC_FIELD = "instance_name"
1151
  OP_PARAMS = [
1152
    _PInstanceName,
1153
    ]
1154

    
1155

    
1156
# Tags opcodes
1157
class OpTagsGet(OpCode):
1158
  """Returns the tags of the given object."""
1159
  OP_DSC_FIELD = "name"
1160
  OP_PARAMS = [
1161
    _PTagKind,
1162
    # Name is only meaningful for nodes and instances
1163
    ("name", ht.NoDefault, ht.TMaybeString),
1164
    ]
1165

    
1166

    
1167
class OpTagsSearch(OpCode):
1168
  """Searches the tags in the cluster for a given pattern."""
1169
  OP_DSC_FIELD = "pattern"
1170
  OP_PARAMS = [
1171
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
1172
    ]
1173

    
1174

    
1175
class OpTagsSet(OpCode):
1176
  """Add a list of tags on a given object."""
1177
  OP_PARAMS = [
1178
    _PTagKind,
1179
    _PTags,
1180
    # Name is only meaningful for nodes and instances
1181
    ("name", ht.NoDefault, ht.TMaybeString),
1182
    ]
1183

    
1184

    
1185
class OpTagsDel(OpCode):
1186
  """Remove a list of tags from a given object."""
1187
  OP_PARAMS = [
1188
    _PTagKind,
1189
    _PTags,
1190
    # Name is only meaningful for nodes and instances
1191
    ("name", ht.NoDefault, ht.TMaybeString),
1192
    ]
1193

    
1194
# Test opcodes
1195
class OpTestDelay(OpCode):
1196
  """Sleeps for a configured amount of time.
1197

1198
  This is used just for debugging and testing.
1199

1200
  Parameters:
1201
    - duration: the time to sleep
1202
    - on_master: if true, sleep on the master
1203
    - on_nodes: list of nodes in which to sleep
1204

1205
  If the on_master parameter is true, it will execute a sleep on the
1206
  master (before any node sleep).
1207

1208
  If the on_nodes list is not empty, it will sleep on those nodes
1209
  (after the sleep on the master, if that is enabled).
1210

1211
  As an additional feature, the case of duration < 0 will be reported
1212
  as an execution error, so this opcode can be used as a failure
1213
  generator. The case of duration == 0 will not be treated specially.
1214

1215
  """
1216
  OP_DSC_FIELD = "duration"
1217
  OP_PARAMS = [
1218
    ("duration", ht.NoDefault, ht.TFloat),
1219
    ("on_master", True, ht.TBool),
1220
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1221
    ("repeat", 0, ht.TPositiveInt)
1222
    ]
1223

    
1224

    
1225
class OpTestAllocator(OpCode):
1226
  """Allocator framework testing.
1227

1228
  This opcode has two modes:
1229
    - gather and return allocator input for a given mode (allocate new
1230
      or replace secondary) and a given instance definition (direction
1231
      'in')
1232
    - run a selected allocator for a given operation (as above) and
1233
      return the allocator output (direction 'out')
1234

1235
  """
1236
  OP_DSC_FIELD = "allocator"
1237
  OP_PARAMS = [
1238
    ("direction", ht.NoDefault,
1239
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
1240
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
1241
    ("name", ht.NoDefault, ht.TNonEmptyString),
1242
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1243
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
1244
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
1245
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
1246
    ("hypervisor", None, ht.TMaybeString),
1247
    ("allocator", None, ht.TMaybeString),
1248
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1249
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
1250
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
1251
    ("os", None, ht.TMaybeString),
1252
    ("disk_template", None, ht.TMaybeString),
1253
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
1254
    ]
1255

    
1256

    
1257
class OpTestJqueue(OpCode):
1258
  """Utility opcode to test some aspects of the job queue.
1259

1260
  """
1261
  OP_PARAMS = [
1262
    ("notify_waitlock", False, ht.TBool),
1263
    ("notify_exec", False, ht.TBool),
1264
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
1265
    ("fail", False, ht.TBool),
1266
    ]
1267

    
1268

    
1269
class OpTestDummy(OpCode):
1270
  """Utility opcode used by unittests.
1271

1272
  """
1273
  OP_PARAMS = [
1274
    ("result", ht.NoDefault, ht.NoType),
1275
    ("messages", ht.NoDefault, ht.NoType),
1276
    ("fail", ht.NoDefault, ht.NoType),
1277
    ]
1278
  WITH_LU = False
1279

    
1280

    
1281
def _GetOpList():
1282
  """Returns list of all defined opcodes.
1283

1284
  Does not eliminate duplicates by C{OP_ID}.
1285

1286
  """
1287
  return [v for v in globals().values()
1288
          if (isinstance(v, type) and issubclass(v, OpCode) and
1289
              hasattr(v, "OP_ID") and v is not OpCode)]
1290

    
1291

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