Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 73e0328b

History | View | Annotate | Download (349.2 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008 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
"""Module implementing the master-side code."""
23

    
24
# pylint: disable-msg=W0201
25

    
26
# W0201 since most LU attributes are defined in CheckPrereq or similar
27
# functions
28

    
29
import os
30
import os.path
31
import time
32
import re
33
import platform
34
import logging
35
import copy
36
import OpenSSL
37

    
38
from ganeti import ssh
39
from ganeti import utils
40
from ganeti import errors
41
from ganeti import hypervisor
42
from ganeti import locking
43
from ganeti import constants
44
from ganeti import objects
45
from ganeti import serializer
46
from ganeti import ssconf
47
from ganeti import uidpool
48
from ganeti import compat
49
from ganeti import masterd
50

    
51
import ganeti.masterd.instance # pylint: disable-msg=W0611
52

    
53

    
54
class LogicalUnit(object):
55
  """Logical Unit base class.
56

57
  Subclasses must follow these rules:
58
    - implement ExpandNames
59
    - implement CheckPrereq (except when tasklets are used)
60
    - implement Exec (except when tasklets are used)
61
    - implement BuildHooksEnv
62
    - redefine HPATH and HTYPE
63
    - optionally redefine their run requirements:
64
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
65

66
  Note that all commands require root permissions.
67

68
  @ivar dry_run_result: the value (if any) that will be returned to the caller
69
      in dry-run mode (signalled by opcode dry_run parameter)
70

71
  """
72
  HPATH = None
73
  HTYPE = None
74
  _OP_REQP = []
75
  REQ_BGL = True
76

    
77
  def __init__(self, processor, op, context, rpc):
78
    """Constructor for LogicalUnit.
79

80
    This needs to be overridden in derived classes in order to check op
81
    validity.
82

83
    """
84
    self.proc = processor
85
    self.op = op
86
    self.cfg = context.cfg
87
    self.context = context
88
    self.rpc = rpc
89
    # Dicts used to declare locking needs to mcpu
90
    self.needed_locks = None
91
    self.acquired_locks = {}
92
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
93
    self.add_locks = {}
94
    self.remove_locks = {}
95
    # Used to force good behavior when calling helper functions
96
    self.recalculate_locks = {}
97
    self.__ssh = None
98
    # logging
99
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
100
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
101
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
102
    # support for dry-run
103
    self.dry_run_result = None
104
    # support for generic debug attribute
105
    if (not hasattr(self.op, "debug_level") or
106
        not isinstance(self.op.debug_level, int)):
107
      self.op.debug_level = 0
108

    
109
    # Tasklets
110
    self.tasklets = None
111

    
112
    for attr_name in self._OP_REQP:
113
      attr_val = getattr(op, attr_name, None)
114
      if attr_val is None:
115
        raise errors.OpPrereqError("Required parameter '%s' missing" %
116
                                   attr_name, errors.ECODE_INVAL)
117

    
118
    self.CheckArguments()
119

    
120
  def __GetSSH(self):
121
    """Returns the SshRunner object
122

123
    """
124
    if not self.__ssh:
125
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
126
    return self.__ssh
127

    
128
  ssh = property(fget=__GetSSH)
129

    
130
  def CheckArguments(self):
131
    """Check syntactic validity for the opcode arguments.
132

133
    This method is for doing a simple syntactic check and ensure
134
    validity of opcode parameters, without any cluster-related
135
    checks. While the same can be accomplished in ExpandNames and/or
136
    CheckPrereq, doing these separate is better because:
137

138
      - ExpandNames is left as as purely a lock-related function
139
      - CheckPrereq is run after we have acquired locks (and possible
140
        waited for them)
141

142
    The function is allowed to change the self.op attribute so that
143
    later methods can no longer worry about missing parameters.
144

145
    """
146
    pass
147

    
148
  def ExpandNames(self):
149
    """Expand names for this LU.
150

151
    This method is called before starting to execute the opcode, and it should
152
    update all the parameters of the opcode to their canonical form (e.g. a
153
    short node name must be fully expanded after this method has successfully
154
    completed). This way locking, hooks, logging, ecc. can work correctly.
155

156
    LUs which implement this method must also populate the self.needed_locks
157
    member, as a dict with lock levels as keys, and a list of needed lock names
158
    as values. Rules:
159

160
      - use an empty dict if you don't need any lock
161
      - if you don't need any lock at a particular level omit that level
162
      - don't put anything for the BGL level
163
      - if you want all locks at a level use locking.ALL_SET as a value
164

165
    If you need to share locks (rather than acquire them exclusively) at one
166
    level you can modify self.share_locks, setting a true value (usually 1) for
167
    that level. By default locks are not shared.
168

169
    This function can also define a list of tasklets, which then will be
170
    executed in order instead of the usual LU-level CheckPrereq and Exec
171
    functions, if those are not defined by the LU.
172

173
    Examples::
174

175
      # Acquire all nodes and one instance
176
      self.needed_locks = {
177
        locking.LEVEL_NODE: locking.ALL_SET,
178
        locking.LEVEL_INSTANCE: ['instance1.example.tld'],
179
      }
180
      # Acquire just two nodes
181
      self.needed_locks = {
182
        locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
183
      }
184
      # Acquire no locks
185
      self.needed_locks = {} # No, you can't leave it to the default value None
186

187
    """
188
    # The implementation of this method is mandatory only if the new LU is
189
    # concurrent, so that old LUs don't need to be changed all at the same
190
    # time.
191
    if self.REQ_BGL:
192
      self.needed_locks = {} # Exclusive LUs don't need locks.
193
    else:
194
      raise NotImplementedError
195

    
196
  def DeclareLocks(self, level):
197
    """Declare LU locking needs for a level
198

199
    While most LUs can just declare their locking needs at ExpandNames time,
200
    sometimes there's the need to calculate some locks after having acquired
201
    the ones before. This function is called just before acquiring locks at a
202
    particular level, but after acquiring the ones at lower levels, and permits
203
    such calculations. It can be used to modify self.needed_locks, and by
204
    default it does nothing.
205

206
    This function is only called if you have something already set in
207
    self.needed_locks for the level.
208

209
    @param level: Locking level which is going to be locked
210
    @type level: member of ganeti.locking.LEVELS
211

212
    """
213

    
214
  def CheckPrereq(self):
215
    """Check prerequisites for this LU.
216

217
    This method should check that the prerequisites for the execution
218
    of this LU are fulfilled. It can do internode communication, but
219
    it should be idempotent - no cluster or system changes are
220
    allowed.
221

222
    The method should raise errors.OpPrereqError in case something is
223
    not fulfilled. Its return value is ignored.
224

225
    This method should also update all the parameters of the opcode to
226
    their canonical form if it hasn't been done by ExpandNames before.
227

228
    """
229
    if self.tasklets is not None:
230
      for (idx, tl) in enumerate(self.tasklets):
231
        logging.debug("Checking prerequisites for tasklet %s/%s",
232
                      idx + 1, len(self.tasklets))
233
        tl.CheckPrereq()
234
    else:
235
      raise NotImplementedError
236

    
237
  def Exec(self, feedback_fn):
238
    """Execute the LU.
239

240
    This method should implement the actual work. It should raise
241
    errors.OpExecError for failures that are somewhat dealt with in
242
    code, or expected.
243

244
    """
245
    if self.tasklets is not None:
246
      for (idx, tl) in enumerate(self.tasklets):
247
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
248
        tl.Exec(feedback_fn)
249
    else:
250
      raise NotImplementedError
251

    
252
  def BuildHooksEnv(self):
253
    """Build hooks environment for this LU.
254

255
    This method should return a three-node tuple consisting of: a dict
256
    containing the environment that will be used for running the
257
    specific hook for this LU, a list of node names on which the hook
258
    should run before the execution, and a list of node names on which
259
    the hook should run after the execution.
260

261
    The keys of the dict must not have 'GANETI_' prefixed as this will
262
    be handled in the hooks runner. Also note additional keys will be
263
    added by the hooks runner. If the LU doesn't define any
264
    environment, an empty dict (and not None) should be returned.
265

266
    No nodes should be returned as an empty list (and not None).
267

268
    Note that if the HPATH for a LU class is None, this function will
269
    not be called.
270

271
    """
272
    raise NotImplementedError
273

    
274
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
275
    """Notify the LU about the results of its hooks.
276

277
    This method is called every time a hooks phase is executed, and notifies
278
    the Logical Unit about the hooks' result. The LU can then use it to alter
279
    its result based on the hooks.  By default the method does nothing and the
280
    previous result is passed back unchanged but any LU can define it if it
281
    wants to use the local cluster hook-scripts somehow.
282

283
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
284
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
285
    @param hook_results: the results of the multi-node hooks rpc call
286
    @param feedback_fn: function used send feedback back to the caller
287
    @param lu_result: the previous Exec result this LU had, or None
288
        in the PRE phase
289
    @return: the new Exec result, based on the previous result
290
        and hook results
291

292
    """
293
    # API must be kept, thus we ignore the unused argument and could
294
    # be a function warnings
295
    # pylint: disable-msg=W0613,R0201
296
    return lu_result
297

    
298
  def _ExpandAndLockInstance(self):
299
    """Helper function to expand and lock an instance.
300

301
    Many LUs that work on an instance take its name in self.op.instance_name
302
    and need to expand it and then declare the expanded name for locking. This
303
    function does it, and then updates self.op.instance_name to the expanded
304
    name. It also initializes needed_locks as a dict, if this hasn't been done
305
    before.
306

307
    """
308
    if self.needed_locks is None:
309
      self.needed_locks = {}
310
    else:
311
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
312
        "_ExpandAndLockInstance called with instance-level locks set"
313
    self.op.instance_name = _ExpandInstanceName(self.cfg,
314
                                                self.op.instance_name)
315
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
316

    
317
  def _LockInstancesNodes(self, primary_only=False):
318
    """Helper function to declare instances' nodes for locking.
319

320
    This function should be called after locking one or more instances to lock
321
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
322
    with all primary or secondary nodes for instances already locked and
323
    present in self.needed_locks[locking.LEVEL_INSTANCE].
324

325
    It should be called from DeclareLocks, and for safety only works if
326
    self.recalculate_locks[locking.LEVEL_NODE] is set.
327

328
    In the future it may grow parameters to just lock some instance's nodes, or
329
    to just lock primaries or secondary nodes, if needed.
330

331
    If should be called in DeclareLocks in a way similar to::
332

333
      if level == locking.LEVEL_NODE:
334
        self._LockInstancesNodes()
335

336
    @type primary_only: boolean
337
    @param primary_only: only lock primary nodes of locked instances
338

339
    """
340
    assert locking.LEVEL_NODE in self.recalculate_locks, \
341
      "_LockInstancesNodes helper function called with no nodes to recalculate"
342

    
343
    # TODO: check if we're really been called with the instance locks held
344

    
345
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
346
    # future we might want to have different behaviors depending on the value
347
    # of self.recalculate_locks[locking.LEVEL_NODE]
348
    wanted_nodes = []
349
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
350
      instance = self.context.cfg.GetInstanceInfo(instance_name)
351
      wanted_nodes.append(instance.primary_node)
352
      if not primary_only:
353
        wanted_nodes.extend(instance.secondary_nodes)
354

    
355
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
356
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
357
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
358
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
359

    
360
    del self.recalculate_locks[locking.LEVEL_NODE]
361

    
362

    
363
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
364
  """Simple LU which runs no hooks.
365

366
  This LU is intended as a parent for other LogicalUnits which will
367
  run no hooks, in order to reduce duplicate code.
368

369
  """
370
  HPATH = None
371
  HTYPE = None
372

    
373
  def BuildHooksEnv(self):
374
    """Empty BuildHooksEnv for NoHooksLu.
375

376
    This just raises an error.
377

378
    """
379
    assert False, "BuildHooksEnv called for NoHooksLUs"
380

    
381

    
382
class Tasklet:
383
  """Tasklet base class.
384

385
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
386
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
387
  tasklets know nothing about locks.
388

389
  Subclasses must follow these rules:
390
    - Implement CheckPrereq
391
    - Implement Exec
392

393
  """
394
  def __init__(self, lu):
395
    self.lu = lu
396

    
397
    # Shortcuts
398
    self.cfg = lu.cfg
399
    self.rpc = lu.rpc
400

    
401
  def CheckPrereq(self):
402
    """Check prerequisites for this tasklets.
403

404
    This method should check whether the prerequisites for the execution of
405
    this tasklet are fulfilled. It can do internode communication, but it
406
    should be idempotent - no cluster or system changes are allowed.
407

408
    The method should raise errors.OpPrereqError in case something is not
409
    fulfilled. Its return value is ignored.
410

411
    This method should also update all parameters to their canonical form if it
412
    hasn't been done before.
413

414
    """
415
    raise NotImplementedError
416

    
417
  def Exec(self, feedback_fn):
418
    """Execute the tasklet.
419

420
    This method should implement the actual work. It should raise
421
    errors.OpExecError for failures that are somewhat dealt with in code, or
422
    expected.
423

424
    """
425
    raise NotImplementedError
426

    
427

    
428
def _GetWantedNodes(lu, nodes):
429
  """Returns list of checked and expanded node names.
430

431
  @type lu: L{LogicalUnit}
432
  @param lu: the logical unit on whose behalf we execute
433
  @type nodes: list
434
  @param nodes: list of node names or None for all nodes
435
  @rtype: list
436
  @return: the list of nodes, sorted
437
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
438

439
  """
440
  if not isinstance(nodes, list):
441
    raise errors.OpPrereqError("Invalid argument type 'nodes'",
442
                               errors.ECODE_INVAL)
443

    
444
  if not nodes:
445
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
446
      " non-empty list of nodes whose name is to be expanded.")
447

    
448
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
449
  return utils.NiceSort(wanted)
450

    
451

    
452
def _GetWantedInstances(lu, instances):
453
  """Returns list of checked and expanded instance names.
454

455
  @type lu: L{LogicalUnit}
456
  @param lu: the logical unit on whose behalf we execute
457
  @type instances: list
458
  @param instances: list of instance names or None for all instances
459
  @rtype: list
460
  @return: the list of instances, sorted
461
  @raise errors.OpPrereqError: if the instances parameter is wrong type
462
  @raise errors.OpPrereqError: if any of the passed instances is not found
463

464
  """
465
  if not isinstance(instances, list):
466
    raise errors.OpPrereqError("Invalid argument type 'instances'",
467
                               errors.ECODE_INVAL)
468

    
469
  if instances:
470
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
471
  else:
472
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
473
  return wanted
474

    
475

    
476
def _CheckOutputFields(static, dynamic, selected):
477
  """Checks whether all selected fields are valid.
478

479
  @type static: L{utils.FieldSet}
480
  @param static: static fields set
481
  @type dynamic: L{utils.FieldSet}
482
  @param dynamic: dynamic fields set
483

484
  """
485
  f = utils.FieldSet()
486
  f.Extend(static)
487
  f.Extend(dynamic)
488

    
489
  delta = f.NonMatching(selected)
490
  if delta:
491
    raise errors.OpPrereqError("Unknown output fields selected: %s"
492
                               % ",".join(delta), errors.ECODE_INVAL)
493

    
494

    
495
def _CheckBooleanOpField(op, name):
496
  """Validates boolean opcode parameters.
497

498
  This will ensure that an opcode parameter is either a boolean value,
499
  or None (but that it always exists).
500

501
  """
502
  val = getattr(op, name, None)
503
  if not (val is None or isinstance(val, bool)):
504
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
505
                               (name, str(val)), errors.ECODE_INVAL)
506
  setattr(op, name, val)
507

    
508

    
509
def _CheckGlobalHvParams(params):
510
  """Validates that given hypervisor params are not global ones.
511

512
  This will ensure that instances don't get customised versions of
513
  global params.
514

515
  """
516
  used_globals = constants.HVC_GLOBALS.intersection(params)
517
  if used_globals:
518
    msg = ("The following hypervisor parameters are global and cannot"
519
           " be customized at instance level, please modify them at"
520
           " cluster level: %s" % utils.CommaJoin(used_globals))
521
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
522

    
523

    
524
def _CheckNodeOnline(lu, node):
525
  """Ensure that a given node is online.
526

527
  @param lu: the LU on behalf of which we make the check
528
  @param node: the node to check
529
  @raise errors.OpPrereqError: if the node is offline
530

531
  """
532
  if lu.cfg.GetNodeInfo(node).offline:
533
    raise errors.OpPrereqError("Can't use offline node %s" % node,
534
                               errors.ECODE_INVAL)
535

    
536

    
537
def _CheckNodeNotDrained(lu, node):
538
  """Ensure that a given node is not drained.
539

540
  @param lu: the LU on behalf of which we make the check
541
  @param node: the node to check
542
  @raise errors.OpPrereqError: if the node is drained
543

544
  """
545
  if lu.cfg.GetNodeInfo(node).drained:
546
    raise errors.OpPrereqError("Can't use drained node %s" % node,
547
                               errors.ECODE_INVAL)
548

    
549

    
550
def _CheckNodeHasOS(lu, node, os_name, force_variant):
551
  """Ensure that a node supports a given OS.
552

553
  @param lu: the LU on behalf of which we make the check
554
  @param node: the node to check
555
  @param os_name: the OS to query about
556
  @param force_variant: whether to ignore variant errors
557
  @raise errors.OpPrereqError: if the node is not supporting the OS
558

559
  """
560
  result = lu.rpc.call_os_get(node, os_name)
561
  result.Raise("OS '%s' not in supported OS list for node %s" %
562
               (os_name, node),
563
               prereq=True, ecode=errors.ECODE_INVAL)
564
  if not force_variant:
565
    _CheckOSVariant(result.payload, os_name)
566

    
567

    
568
def _RequireFileStorage():
569
  """Checks that file storage is enabled.
570

571
  @raise errors.OpPrereqError: when file storage is disabled
572

573
  """
574
  if not constants.ENABLE_FILE_STORAGE:
575
    raise errors.OpPrereqError("File storage disabled at configure time",
576
                               errors.ECODE_INVAL)
577

    
578

    
579
def _CheckDiskTemplate(template):
580
  """Ensure a given disk template is valid.
581

582
  """
583
  if template not in constants.DISK_TEMPLATES:
584
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
585
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
586
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
587
  if template == constants.DT_FILE:
588
    _RequireFileStorage()
589

    
590

    
591
def _CheckStorageType(storage_type):
592
  """Ensure a given storage type is valid.
593

594
  """
595
  if storage_type not in constants.VALID_STORAGE_TYPES:
596
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
597
                               errors.ECODE_INVAL)
598
  if storage_type == constants.ST_FILE:
599
    _RequireFileStorage()
600

    
601

    
602
def _GetClusterDomainSecret():
603
  """Reads the cluster domain secret.
604

605
  """
606
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
607
                               strict=True)
608

    
609

    
610
def _CheckInstanceDown(lu, instance, reason):
611
  """Ensure that an instance is not running."""
612
  if instance.admin_up:
613
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
614
                               (instance.name, reason), errors.ECODE_STATE)
615

    
616
  pnode = instance.primary_node
617
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
618
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
619
              prereq=True, ecode=errors.ECODE_ENVIRON)
620

    
621
  if instance.name in ins_l.payload:
622
    raise errors.OpPrereqError("Instance %s is running, %s" %
623
                               (instance.name, reason), errors.ECODE_STATE)
624

    
625

    
626
def _ExpandItemName(fn, name, kind):
627
  """Expand an item name.
628

629
  @param fn: the function to use for expansion
630
  @param name: requested item name
631
  @param kind: text description ('Node' or 'Instance')
632
  @return: the resolved (full) name
633
  @raise errors.OpPrereqError: if the item is not found
634

635
  """
636
  full_name = fn(name)
637
  if full_name is None:
638
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
639
                               errors.ECODE_NOENT)
640
  return full_name
641

    
642

    
643
def _ExpandNodeName(cfg, name):
644
  """Wrapper over L{_ExpandItemName} for nodes."""
645
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
646

    
647

    
648
def _ExpandInstanceName(cfg, name):
649
  """Wrapper over L{_ExpandItemName} for instance."""
650
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
651

    
652

    
653
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
654
                          memory, vcpus, nics, disk_template, disks,
655
                          bep, hvp, hypervisor_name):
656
  """Builds instance related env variables for hooks
657

658
  This builds the hook environment from individual variables.
659

660
  @type name: string
661
  @param name: the name of the instance
662
  @type primary_node: string
663
  @param primary_node: the name of the instance's primary node
664
  @type secondary_nodes: list
665
  @param secondary_nodes: list of secondary nodes as strings
666
  @type os_type: string
667
  @param os_type: the name of the instance's OS
668
  @type status: boolean
669
  @param status: the should_run status of the instance
670
  @type memory: string
671
  @param memory: the memory size of the instance
672
  @type vcpus: string
673
  @param vcpus: the count of VCPUs the instance has
674
  @type nics: list
675
  @param nics: list of tuples (ip, mac, mode, link) representing
676
      the NICs the instance has
677
  @type disk_template: string
678
  @param disk_template: the disk template of the instance
679
  @type disks: list
680
  @param disks: the list of (size, mode) pairs
681
  @type bep: dict
682
  @param bep: the backend parameters for the instance
683
  @type hvp: dict
684
  @param hvp: the hypervisor parameters for the instance
685
  @type hypervisor_name: string
686
  @param hypervisor_name: the hypervisor for the instance
687
  @rtype: dict
688
  @return: the hook environment for this instance
689

690
  """
691
  if status:
692
    str_status = "up"
693
  else:
694
    str_status = "down"
695
  env = {
696
    "OP_TARGET": name,
697
    "INSTANCE_NAME": name,
698
    "INSTANCE_PRIMARY": primary_node,
699
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
700
    "INSTANCE_OS_TYPE": os_type,
701
    "INSTANCE_STATUS": str_status,
702
    "INSTANCE_MEMORY": memory,
703
    "INSTANCE_VCPUS": vcpus,
704
    "INSTANCE_DISK_TEMPLATE": disk_template,
705
    "INSTANCE_HYPERVISOR": hypervisor_name,
706
  }
707

    
708
  if nics:
709
    nic_count = len(nics)
710
    for idx, (ip, mac, mode, link) in enumerate(nics):
711
      if ip is None:
712
        ip = ""
713
      env["INSTANCE_NIC%d_IP" % idx] = ip
714
      env["INSTANCE_NIC%d_MAC" % idx] = mac
715
      env["INSTANCE_NIC%d_MODE" % idx] = mode
716
      env["INSTANCE_NIC%d_LINK" % idx] = link
717
      if mode == constants.NIC_MODE_BRIDGED:
718
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
719
  else:
720
    nic_count = 0
721

    
722
  env["INSTANCE_NIC_COUNT"] = nic_count
723

    
724
  if disks:
725
    disk_count = len(disks)
726
    for idx, (size, mode) in enumerate(disks):
727
      env["INSTANCE_DISK%d_SIZE" % idx] = size
728
      env["INSTANCE_DISK%d_MODE" % idx] = mode
729
  else:
730
    disk_count = 0
731

    
732
  env["INSTANCE_DISK_COUNT"] = disk_count
733

    
734
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
735
    for key, value in source.items():
736
      env["INSTANCE_%s_%s" % (kind, key)] = value
737

    
738
  return env
739

    
740

    
741
def _NICListToTuple(lu, nics):
742
  """Build a list of nic information tuples.
743

744
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
745
  value in LUQueryInstanceData.
746

747
  @type lu:  L{LogicalUnit}
748
  @param lu: the logical unit on whose behalf we execute
749
  @type nics: list of L{objects.NIC}
750
  @param nics: list of nics to convert to hooks tuples
751

752
  """
753
  hooks_nics = []
754
  cluster = lu.cfg.GetClusterInfo()
755
  for nic in nics:
756
    ip = nic.ip
757
    mac = nic.mac
758
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
759
    mode = filled_params[constants.NIC_MODE]
760
    link = filled_params[constants.NIC_LINK]
761
    hooks_nics.append((ip, mac, mode, link))
762
  return hooks_nics
763

    
764

    
765
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
766
  """Builds instance related env variables for hooks from an object.
767

768
  @type lu: L{LogicalUnit}
769
  @param lu: the logical unit on whose behalf we execute
770
  @type instance: L{objects.Instance}
771
  @param instance: the instance for which we should build the
772
      environment
773
  @type override: dict
774
  @param override: dictionary with key/values that will override
775
      our values
776
  @rtype: dict
777
  @return: the hook environment dictionary
778

779
  """
780
  cluster = lu.cfg.GetClusterInfo()
781
  bep = cluster.FillBE(instance)
782
  hvp = cluster.FillHV(instance)
783
  args = {
784
    'name': instance.name,
785
    'primary_node': instance.primary_node,
786
    'secondary_nodes': instance.secondary_nodes,
787
    'os_type': instance.os,
788
    'status': instance.admin_up,
789
    'memory': bep[constants.BE_MEMORY],
790
    'vcpus': bep[constants.BE_VCPUS],
791
    'nics': _NICListToTuple(lu, instance.nics),
792
    'disk_template': instance.disk_template,
793
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
794
    'bep': bep,
795
    'hvp': hvp,
796
    'hypervisor_name': instance.hypervisor,
797
  }
798
  if override:
799
    args.update(override)
800
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
801

    
802

    
803
def _AdjustCandidatePool(lu, exceptions):
804
  """Adjust the candidate pool after node operations.
805

806
  """
807
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
808
  if mod_list:
809
    lu.LogInfo("Promoted nodes to master candidate role: %s",
810
               utils.CommaJoin(node.name for node in mod_list))
811
    for name in mod_list:
812
      lu.context.ReaddNode(name)
813
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
814
  if mc_now > mc_max:
815
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
816
               (mc_now, mc_max))
817

    
818

    
819
def _DecideSelfPromotion(lu, exceptions=None):
820
  """Decide whether I should promote myself as a master candidate.
821

822
  """
823
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
824
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
825
  # the new node will increase mc_max with one, so:
826
  mc_should = min(mc_should + 1, cp_size)
827
  return mc_now < mc_should
828

    
829

    
830
def _CheckNicsBridgesExist(lu, target_nics, target_node):
831
  """Check that the brigdes needed by a list of nics exist.
832

833
  """
834
  cluster = lu.cfg.GetClusterInfo()
835
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
836
  brlist = [params[constants.NIC_LINK] for params in paramslist
837
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
838
  if brlist:
839
    result = lu.rpc.call_bridges_exist(target_node, brlist)
840
    result.Raise("Error checking bridges on destination node '%s'" %
841
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
842

    
843

    
844
def _CheckInstanceBridgesExist(lu, instance, node=None):
845
  """Check that the brigdes needed by an instance exist.
846

847
  """
848
  if node is None:
849
    node = instance.primary_node
850
  _CheckNicsBridgesExist(lu, instance.nics, node)
851

    
852

    
853
def _CheckOSVariant(os_obj, name):
854
  """Check whether an OS name conforms to the os variants specification.
855

856
  @type os_obj: L{objects.OS}
857
  @param os_obj: OS object to check
858
  @type name: string
859
  @param name: OS name passed by the user, to check for validity
860

861
  """
862
  if not os_obj.supported_variants:
863
    return
864
  try:
865
    variant = name.split("+", 1)[1]
866
  except IndexError:
867
    raise errors.OpPrereqError("OS name must include a variant",
868
                               errors.ECODE_INVAL)
869

    
870
  if variant not in os_obj.supported_variants:
871
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
872

    
873

    
874
def _GetNodeInstancesInner(cfg, fn):
875
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
876

    
877

    
878
def _GetNodeInstances(cfg, node_name):
879
  """Returns a list of all primary and secondary instances on a node.
880

881
  """
882

    
883
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
884

    
885

    
886
def _GetNodePrimaryInstances(cfg, node_name):
887
  """Returns primary instances on a node.
888

889
  """
890
  return _GetNodeInstancesInner(cfg,
891
                                lambda inst: node_name == inst.primary_node)
892

    
893

    
894
def _GetNodeSecondaryInstances(cfg, node_name):
895
  """Returns secondary instances on a node.
896

897
  """
898
  return _GetNodeInstancesInner(cfg,
899
                                lambda inst: node_name in inst.secondary_nodes)
900

    
901

    
902
def _GetStorageTypeArgs(cfg, storage_type):
903
  """Returns the arguments for a storage type.
904

905
  """
906
  # Special case for file storage
907
  if storage_type == constants.ST_FILE:
908
    # storage.FileStorage wants a list of storage directories
909
    return [[cfg.GetFileStorageDir()]]
910

    
911
  return []
912

    
913

    
914
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
915
  faulty = []
916

    
917
  for dev in instance.disks:
918
    cfg.SetDiskID(dev, node_name)
919

    
920
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
921
  result.Raise("Failed to get disk status from node %s" % node_name,
922
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
923

    
924
  for idx, bdev_status in enumerate(result.payload):
925
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
926
      faulty.append(idx)
927

    
928
  return faulty
929

    
930

    
931
class LUPostInitCluster(LogicalUnit):
932
  """Logical unit for running hooks after cluster initialization.
933

934
  """
935
  HPATH = "cluster-init"
936
  HTYPE = constants.HTYPE_CLUSTER
937
  _OP_REQP = []
938

    
939
  def BuildHooksEnv(self):
940
    """Build hooks env.
941

942
    """
943
    env = {"OP_TARGET": self.cfg.GetClusterName()}
944
    mn = self.cfg.GetMasterNode()
945
    return env, [], [mn]
946

    
947
  def CheckPrereq(self):
948
    """No prerequisites to check.
949

950
    """
951
    return True
952

    
953
  def Exec(self, feedback_fn):
954
    """Nothing to do.
955

956
    """
957
    return True
958

    
959

    
960
class LUDestroyCluster(LogicalUnit):
961
  """Logical unit for destroying the cluster.
962

963
  """
964
  HPATH = "cluster-destroy"
965
  HTYPE = constants.HTYPE_CLUSTER
966
  _OP_REQP = []
967

    
968
  def BuildHooksEnv(self):
969
    """Build hooks env.
970

971
    """
972
    env = {"OP_TARGET": self.cfg.GetClusterName()}
973
    return env, [], []
974

    
975
  def CheckPrereq(self):
976
    """Check prerequisites.
977

978
    This checks whether the cluster is empty.
979

980
    Any errors are signaled by raising errors.OpPrereqError.
981

982
    """
983
    master = self.cfg.GetMasterNode()
984

    
985
    nodelist = self.cfg.GetNodeList()
986
    if len(nodelist) != 1 or nodelist[0] != master:
987
      raise errors.OpPrereqError("There are still %d node(s) in"
988
                                 " this cluster." % (len(nodelist) - 1),
989
                                 errors.ECODE_INVAL)
990
    instancelist = self.cfg.GetInstanceList()
991
    if instancelist:
992
      raise errors.OpPrereqError("There are still %d instance(s) in"
993
                                 " this cluster." % len(instancelist),
994
                                 errors.ECODE_INVAL)
995

    
996
  def Exec(self, feedback_fn):
997
    """Destroys the cluster.
998

999
    """
1000
    master = self.cfg.GetMasterNode()
1001
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
1002

    
1003
    # Run post hooks on master node before it's removed
1004
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1005
    try:
1006
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1007
    except:
1008
      # pylint: disable-msg=W0702
1009
      self.LogWarning("Errors occurred running hooks on %s" % master)
1010

    
1011
    result = self.rpc.call_node_stop_master(master, False)
1012
    result.Raise("Could not disable the master role")
1013

    
1014
    if modify_ssh_setup:
1015
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1016
      utils.CreateBackup(priv_key)
1017
      utils.CreateBackup(pub_key)
1018

    
1019
    return master
1020

    
1021

    
1022
def _VerifyCertificate(filename):
1023
  """Verifies a certificate for LUVerifyCluster.
1024

1025
  @type filename: string
1026
  @param filename: Path to PEM file
1027

1028
  """
1029
  try:
1030
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1031
                                           utils.ReadFile(filename))
1032
  except Exception, err: # pylint: disable-msg=W0703
1033
    return (LUVerifyCluster.ETYPE_ERROR,
1034
            "Failed to load X509 certificate %s: %s" % (filename, err))
1035

    
1036
  (errcode, msg) = \
1037
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1038
                                constants.SSL_CERT_EXPIRATION_ERROR)
1039

    
1040
  if msg:
1041
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1042
  else:
1043
    fnamemsg = None
1044

    
1045
  if errcode is None:
1046
    return (None, fnamemsg)
1047
  elif errcode == utils.CERT_WARNING:
1048
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1049
  elif errcode == utils.CERT_ERROR:
1050
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1051

    
1052
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1053

    
1054

    
1055
class LUVerifyCluster(LogicalUnit):
1056
  """Verifies the cluster status.
1057

1058
  """
1059
  HPATH = "cluster-verify"
1060
  HTYPE = constants.HTYPE_CLUSTER
1061
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
1062
  REQ_BGL = False
1063

    
1064
  TCLUSTER = "cluster"
1065
  TNODE = "node"
1066
  TINSTANCE = "instance"
1067

    
1068
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1069
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1070
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1071
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1072
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1073
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1074
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1075
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1076
  ENODEDRBD = (TNODE, "ENODEDRBD")
1077
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1078
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1079
  ENODEHV = (TNODE, "ENODEHV")
1080
  ENODELVM = (TNODE, "ENODELVM")
1081
  ENODEN1 = (TNODE, "ENODEN1")
1082
  ENODENET = (TNODE, "ENODENET")
1083
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1084
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1085
  ENODERPC = (TNODE, "ENODERPC")
1086
  ENODESSH = (TNODE, "ENODESSH")
1087
  ENODEVERSION = (TNODE, "ENODEVERSION")
1088
  ENODESETUP = (TNODE, "ENODESETUP")
1089
  ENODETIME = (TNODE, "ENODETIME")
1090

    
1091
  ETYPE_FIELD = "code"
1092
  ETYPE_ERROR = "ERROR"
1093
  ETYPE_WARNING = "WARNING"
1094

    
1095
  class NodeImage(object):
1096
    """A class representing the logical and physical status of a node.
1097

1098
    @ivar volumes: a structure as returned from
1099
        L{ganeti.backend.GetVolumeList} (runtime)
1100
    @ivar instances: a list of running instances (runtime)
1101
    @ivar pinst: list of configured primary instances (config)
1102
    @ivar sinst: list of configured secondary instances (config)
1103
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1104
        of this node (config)
1105
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1106
    @ivar dfree: free disk, as reported by the node (runtime)
1107
    @ivar offline: the offline status (config)
1108
    @type rpc_fail: boolean
1109
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1110
        not whether the individual keys were correct) (runtime)
1111
    @type lvm_fail: boolean
1112
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1113
    @type hyp_fail: boolean
1114
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1115
    @type ghost: boolean
1116
    @ivar ghost: whether this is a known node or not (config)
1117

1118
    """
1119
    def __init__(self, offline=False):
1120
      self.volumes = {}
1121
      self.instances = []
1122
      self.pinst = []
1123
      self.sinst = []
1124
      self.sbp = {}
1125
      self.mfree = 0
1126
      self.dfree = 0
1127
      self.offline = offline
1128
      self.rpc_fail = False
1129
      self.lvm_fail = False
1130
      self.hyp_fail = False
1131
      self.ghost = False
1132

    
1133
  def ExpandNames(self):
1134
    self.needed_locks = {
1135
      locking.LEVEL_NODE: locking.ALL_SET,
1136
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1137
    }
1138
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1139

    
1140
  def _Error(self, ecode, item, msg, *args, **kwargs):
1141
    """Format an error message.
1142

1143
    Based on the opcode's error_codes parameter, either format a
1144
    parseable error code, or a simpler error string.
1145

1146
    This must be called only from Exec and functions called from Exec.
1147

1148
    """
1149
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1150
    itype, etxt = ecode
1151
    # first complete the msg
1152
    if args:
1153
      msg = msg % args
1154
    # then format the whole message
1155
    if self.op.error_codes:
1156
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1157
    else:
1158
      if item:
1159
        item = " " + item
1160
      else:
1161
        item = ""
1162
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1163
    # and finally report it via the feedback_fn
1164
    self._feedback_fn("  - %s" % msg)
1165

    
1166
  def _ErrorIf(self, cond, *args, **kwargs):
1167
    """Log an error message if the passed condition is True.
1168

1169
    """
1170
    cond = bool(cond) or self.op.debug_simulate_errors
1171
    if cond:
1172
      self._Error(*args, **kwargs)
1173
    # do not mark the operation as failed for WARN cases only
1174
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1175
      self.bad = self.bad or cond
1176

    
1177
  def _VerifyNode(self, ninfo, nresult):
1178
    """Run multiple tests against a node.
1179

1180
    Test list:
1181

1182
      - compares ganeti version
1183
      - checks vg existence and size > 20G
1184
      - checks config file checksum
1185
      - checks ssh to other nodes
1186

1187
    @type ninfo: L{objects.Node}
1188
    @param ninfo: the node to check
1189
    @param nresult: the results from the node
1190
    @rtype: boolean
1191
    @return: whether overall this call was successful (and we can expect
1192
         reasonable values in the respose)
1193

1194
    """
1195
    node = ninfo.name
1196
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1197

    
1198
    # main result, nresult should be a non-empty dict
1199
    test = not nresult or not isinstance(nresult, dict)
1200
    _ErrorIf(test, self.ENODERPC, node,
1201
                  "unable to verify node: no data returned")
1202
    if test:
1203
      return False
1204

    
1205
    # compares ganeti version
1206
    local_version = constants.PROTOCOL_VERSION
1207
    remote_version = nresult.get("version", None)
1208
    test = not (remote_version and
1209
                isinstance(remote_version, (list, tuple)) and
1210
                len(remote_version) == 2)
1211
    _ErrorIf(test, self.ENODERPC, node,
1212
             "connection to node returned invalid data")
1213
    if test:
1214
      return False
1215

    
1216
    test = local_version != remote_version[0]
1217
    _ErrorIf(test, self.ENODEVERSION, node,
1218
             "incompatible protocol versions: master %s,"
1219
             " node %s", local_version, remote_version[0])
1220
    if test:
1221
      return False
1222

    
1223
    # node seems compatible, we can actually try to look into its results
1224

    
1225
    # full package version
1226
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1227
                  self.ENODEVERSION, node,
1228
                  "software version mismatch: master %s, node %s",
1229
                  constants.RELEASE_VERSION, remote_version[1],
1230
                  code=self.ETYPE_WARNING)
1231

    
1232
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1233
    if isinstance(hyp_result, dict):
1234
      for hv_name, hv_result in hyp_result.iteritems():
1235
        test = hv_result is not None
1236
        _ErrorIf(test, self.ENODEHV, node,
1237
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1238

    
1239

    
1240
    test = nresult.get(constants.NV_NODESETUP,
1241
                           ["Missing NODESETUP results"])
1242
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1243
             "; ".join(test))
1244

    
1245
    return True
1246

    
1247
  def _VerifyNodeTime(self, ninfo, nresult,
1248
                      nvinfo_starttime, nvinfo_endtime):
1249
    """Check the node time.
1250

1251
    @type ninfo: L{objects.Node}
1252
    @param ninfo: the node to check
1253
    @param nresult: the remote results for the node
1254
    @param nvinfo_starttime: the start time of the RPC call
1255
    @param nvinfo_endtime: the end time of the RPC call
1256

1257
    """
1258
    node = ninfo.name
1259
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1260

    
1261
    ntime = nresult.get(constants.NV_TIME, None)
1262
    try:
1263
      ntime_merged = utils.MergeTime(ntime)
1264
    except (ValueError, TypeError):
1265
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1266
      return
1267

    
1268
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1269
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1270
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1271
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1272
    else:
1273
      ntime_diff = None
1274

    
1275
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1276
             "Node time diverges by at least %s from master node time",
1277
             ntime_diff)
1278

    
1279
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1280
    """Check the node time.
1281

1282
    @type ninfo: L{objects.Node}
1283
    @param ninfo: the node to check
1284
    @param nresult: the remote results for the node
1285
    @param vg_name: the configured VG name
1286

1287
    """
1288
    if vg_name is None:
1289
      return
1290

    
1291
    node = ninfo.name
1292
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1293

    
1294
    # checks vg existence and size > 20G
1295
    vglist = nresult.get(constants.NV_VGLIST, None)
1296
    test = not vglist
1297
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1298
    if not test:
1299
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1300
                                            constants.MIN_VG_SIZE)
1301
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1302

    
1303
    # check pv names
1304
    pvlist = nresult.get(constants.NV_PVLIST, None)
1305
    test = pvlist is None
1306
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1307
    if not test:
1308
      # check that ':' is not present in PV names, since it's a
1309
      # special character for lvcreate (denotes the range of PEs to
1310
      # use on the PV)
1311
      for _, pvname, owner_vg in pvlist:
1312
        test = ":" in pvname
1313
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1314
                 " '%s' of VG '%s'", pvname, owner_vg)
1315

    
1316
  def _VerifyNodeNetwork(self, ninfo, nresult):
1317
    """Check the node time.
1318

1319
    @type ninfo: L{objects.Node}
1320
    @param ninfo: the node to check
1321
    @param nresult: the remote results for the node
1322

1323
    """
1324
    node = ninfo.name
1325
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1326

    
1327
    test = constants.NV_NODELIST not in nresult
1328
    _ErrorIf(test, self.ENODESSH, node,
1329
             "node hasn't returned node ssh connectivity data")
1330
    if not test:
1331
      if nresult[constants.NV_NODELIST]:
1332
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1333
          _ErrorIf(True, self.ENODESSH, node,
1334
                   "ssh communication with node '%s': %s", a_node, a_msg)
1335

    
1336
    test = constants.NV_NODENETTEST not in nresult
1337
    _ErrorIf(test, self.ENODENET, node,
1338
             "node hasn't returned node tcp connectivity data")
1339
    if not test:
1340
      if nresult[constants.NV_NODENETTEST]:
1341
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1342
        for anode in nlist:
1343
          _ErrorIf(True, self.ENODENET, node,
1344
                   "tcp communication with node '%s': %s",
1345
                   anode, nresult[constants.NV_NODENETTEST][anode])
1346

    
1347
    test = constants.NV_MASTERIP not in nresult
1348
    _ErrorIf(test, self.ENODENET, node,
1349
             "node hasn't returned node master IP reachability data")
1350
    if not test:
1351
      if not nresult[constants.NV_MASTERIP]:
1352
        if node == self.master_node:
1353
          msg = "the master node cannot reach the master IP (not configured?)"
1354
        else:
1355
          msg = "cannot reach the master IP"
1356
        _ErrorIf(True, self.ENODENET, node, msg)
1357

    
1358

    
1359
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1360
    """Verify an instance.
1361

1362
    This function checks to see if the required block devices are
1363
    available on the instance's node.
1364

1365
    """
1366
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1367
    node_current = instanceconfig.primary_node
1368

    
1369
    node_vol_should = {}
1370
    instanceconfig.MapLVsByNode(node_vol_should)
1371

    
1372
    for node in node_vol_should:
1373
      n_img = node_image[node]
1374
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1375
        # ignore missing volumes on offline or broken nodes
1376
        continue
1377
      for volume in node_vol_should[node]:
1378
        test = volume not in n_img.volumes
1379
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1380
                 "volume %s missing on node %s", volume, node)
1381

    
1382
    if instanceconfig.admin_up:
1383
      pri_img = node_image[node_current]
1384
      test = instance not in pri_img.instances and not pri_img.offline
1385
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1386
               "instance not running on its primary node %s",
1387
               node_current)
1388

    
1389
    for node, n_img in node_image.items():
1390
      if (not node == node_current):
1391
        test = instance in n_img.instances
1392
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1393
                 "instance should not run on node %s", node)
1394

    
1395
  def _VerifyOrphanVolumes(self, node_vol_should, node_image):
1396
    """Verify if there are any unknown volumes in the cluster.
1397

1398
    The .os, .swap and backup volumes are ignored. All other volumes are
1399
    reported as unknown.
1400

1401
    """
1402
    for node, n_img in node_image.items():
1403
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1404
        # skip non-healthy nodes
1405
        continue
1406
      for volume in n_img.volumes:
1407
        test = (node not in node_vol_should or
1408
                volume not in node_vol_should[node])
1409
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1410
                      "volume %s is unknown", volume)
1411

    
1412
  def _VerifyOrphanInstances(self, instancelist, node_image):
1413
    """Verify the list of running instances.
1414

1415
    This checks what instances are running but unknown to the cluster.
1416

1417
    """
1418
    for node, n_img in node_image.items():
1419
      for o_inst in n_img.instances:
1420
        test = o_inst not in instancelist
1421
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1422
                      "instance %s on node %s should not exist", o_inst, node)
1423

    
1424
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1425
    """Verify N+1 Memory Resilience.
1426

1427
    Check that if one single node dies we can still start all the
1428
    instances it was primary for.
1429

1430
    """
1431
    for node, n_img in node_image.items():
1432
      # This code checks that every node which is now listed as
1433
      # secondary has enough memory to host all instances it is
1434
      # supposed to should a single other node in the cluster fail.
1435
      # FIXME: not ready for failover to an arbitrary node
1436
      # FIXME: does not support file-backed instances
1437
      # WARNING: we currently take into account down instances as well
1438
      # as up ones, considering that even if they're down someone
1439
      # might want to start them even in the event of a node failure.
1440
      for prinode, instances in n_img.sbp.items():
1441
        needed_mem = 0
1442
        for instance in instances:
1443
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1444
          if bep[constants.BE_AUTO_BALANCE]:
1445
            needed_mem += bep[constants.BE_MEMORY]
1446
        test = n_img.mfree < needed_mem
1447
        self._ErrorIf(test, self.ENODEN1, node,
1448
                      "not enough memory on to accommodate"
1449
                      " failovers should peer node %s fail", prinode)
1450

    
1451
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1452
                       master_files):
1453
    """Verifies and computes the node required file checksums.
1454

1455
    @type ninfo: L{objects.Node}
1456
    @param ninfo: the node to check
1457
    @param nresult: the remote results for the node
1458
    @param file_list: required list of files
1459
    @param local_cksum: dictionary of local files and their checksums
1460
    @param master_files: list of files that only masters should have
1461

1462
    """
1463
    node = ninfo.name
1464
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1465

    
1466
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1467
    test = not isinstance(remote_cksum, dict)
1468
    _ErrorIf(test, self.ENODEFILECHECK, node,
1469
             "node hasn't returned file checksum data")
1470
    if test:
1471
      return
1472

    
1473
    for file_name in file_list:
1474
      node_is_mc = ninfo.master_candidate
1475
      must_have = (file_name not in master_files) or node_is_mc
1476
      # missing
1477
      test1 = file_name not in remote_cksum
1478
      # invalid checksum
1479
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1480
      # existing and good
1481
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1482
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1483
               "file '%s' missing", file_name)
1484
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1485
               "file '%s' has wrong checksum", file_name)
1486
      # not candidate and this is not a must-have file
1487
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1488
               "file '%s' should not exist on non master"
1489
               " candidates (and the file is outdated)", file_name)
1490
      # all good, except non-master/non-must have combination
1491
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1492
               "file '%s' should not exist"
1493
               " on non master candidates", file_name)
1494

    
1495
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_map):
1496
    """Verifies and the node DRBD status.
1497

1498
    @type ninfo: L{objects.Node}
1499
    @param ninfo: the node to check
1500
    @param nresult: the remote results for the node
1501
    @param instanceinfo: the dict of instances
1502
    @param drbd_map: the DRBD map as returned by
1503
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1504

1505
    """
1506
    node = ninfo.name
1507
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1508

    
1509
    # compute the DRBD minors
1510
    node_drbd = {}
1511
    for minor, instance in drbd_map[node].items():
1512
      test = instance not in instanceinfo
1513
      _ErrorIf(test, self.ECLUSTERCFG, None,
1514
               "ghost instance '%s' in temporary DRBD map", instance)
1515
        # ghost instance should not be running, but otherwise we
1516
        # don't give double warnings (both ghost instance and
1517
        # unallocated minor in use)
1518
      if test:
1519
        node_drbd[minor] = (instance, False)
1520
      else:
1521
        instance = instanceinfo[instance]
1522
        node_drbd[minor] = (instance.name, instance.admin_up)
1523

    
1524
    # and now check them
1525
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1526
    test = not isinstance(used_minors, (tuple, list))
1527
    _ErrorIf(test, self.ENODEDRBD, node,
1528
             "cannot parse drbd status file: %s", str(used_minors))
1529
    if test:
1530
      # we cannot check drbd status
1531
      return
1532

    
1533
    for minor, (iname, must_exist) in node_drbd.items():
1534
      test = minor not in used_minors and must_exist
1535
      _ErrorIf(test, self.ENODEDRBD, node,
1536
               "drbd minor %d of instance %s is not active", minor, iname)
1537
    for minor in used_minors:
1538
      test = minor not in node_drbd
1539
      _ErrorIf(test, self.ENODEDRBD, node,
1540
               "unallocated drbd minor %d is in use", minor)
1541

    
1542
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1543
    """Verifies and updates the node volume data.
1544

1545
    This function will update a L{NodeImage}'s internal structures
1546
    with data from the remote call.
1547

1548
    @type ninfo: L{objects.Node}
1549
    @param ninfo: the node to check
1550
    @param nresult: the remote results for the node
1551
    @param nimg: the node image object
1552
    @param vg_name: the configured VG name
1553

1554
    """
1555
    node = ninfo.name
1556
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1557

    
1558
    nimg.lvm_fail = True
1559
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1560
    if vg_name is None:
1561
      pass
1562
    elif isinstance(lvdata, basestring):
1563
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1564
               utils.SafeEncode(lvdata))
1565
    elif not isinstance(lvdata, dict):
1566
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1567
    else:
1568
      nimg.volumes = lvdata
1569
      nimg.lvm_fail = False
1570

    
1571
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1572
    """Verifies and updates the node instance list.
1573

1574
    If the listing was successful, then updates this node's instance
1575
    list. Otherwise, it marks the RPC call as failed for the instance
1576
    list key.
1577

1578
    @type ninfo: L{objects.Node}
1579
    @param ninfo: the node to check
1580
    @param nresult: the remote results for the node
1581
    @param nimg: the node image object
1582

1583
    """
1584
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1585
    test = not isinstance(idata, list)
1586
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1587
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1588
    if test:
1589
      nimg.hyp_fail = True
1590
    else:
1591
      nimg.instances = idata
1592

    
1593
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1594
    """Verifies and computes a node information map
1595

1596
    @type ninfo: L{objects.Node}
1597
    @param ninfo: the node to check
1598
    @param nresult: the remote results for the node
1599
    @param nimg: the node image object
1600
    @param vg_name: the configured VG name
1601

1602
    """
1603
    node = ninfo.name
1604
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1605

    
1606
    # try to read free memory (from the hypervisor)
1607
    hv_info = nresult.get(constants.NV_HVINFO, None)
1608
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1609
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1610
    if not test:
1611
      try:
1612
        nimg.mfree = int(hv_info["memory_free"])
1613
      except (ValueError, TypeError):
1614
        _ErrorIf(True, self.ENODERPC, node,
1615
                 "node returned invalid nodeinfo, check hypervisor")
1616

    
1617
    # FIXME: devise a free space model for file based instances as well
1618
    if vg_name is not None:
1619
      test = (constants.NV_VGLIST not in nresult or
1620
              vg_name not in nresult[constants.NV_VGLIST])
1621
      _ErrorIf(test, self.ENODELVM, node,
1622
               "node didn't return data for the volume group '%s'"
1623
               " - it is either missing or broken", vg_name)
1624
      if not test:
1625
        try:
1626
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1627
        except (ValueError, TypeError):
1628
          _ErrorIf(True, self.ENODERPC, node,
1629
                   "node returned invalid LVM info, check LVM status")
1630

    
1631
  def CheckPrereq(self):
1632
    """Check prerequisites.
1633

1634
    Transform the list of checks we're going to skip into a set and check that
1635
    all its members are valid.
1636

1637
    """
1638
    self.skip_set = frozenset(self.op.skip_checks)
1639
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1640
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1641
                                 errors.ECODE_INVAL)
1642

    
1643
  def BuildHooksEnv(self):
1644
    """Build hooks env.
1645

1646
    Cluster-Verify hooks just ran in the post phase and their failure makes
1647
    the output be logged in the verify output and the verification to fail.
1648

1649
    """
1650
    all_nodes = self.cfg.GetNodeList()
1651
    env = {
1652
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1653
      }
1654
    for node in self.cfg.GetAllNodesInfo().values():
1655
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1656

    
1657
    return env, [], all_nodes
1658

    
1659
  def Exec(self, feedback_fn):
1660
    """Verify integrity of cluster, performing various test on nodes.
1661

1662
    """
1663
    self.bad = False
1664
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1665
    verbose = self.op.verbose
1666
    self._feedback_fn = feedback_fn
1667
    feedback_fn("* Verifying global settings")
1668
    for msg in self.cfg.VerifyConfig():
1669
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1670

    
1671
    # Check the cluster certificates
1672
    for cert_filename in constants.ALL_CERT_FILES:
1673
      (errcode, msg) = _VerifyCertificate(cert_filename)
1674
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1675

    
1676
    vg_name = self.cfg.GetVGName()
1677
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1678
    cluster = self.cfg.GetClusterInfo()
1679
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1680
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1681
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1682
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1683
                        for iname in instancelist)
1684
    i_non_redundant = [] # Non redundant instances
1685
    i_non_a_balanced = [] # Non auto-balanced instances
1686
    n_offline = 0 # Count of offline nodes
1687
    n_drained = 0 # Count of nodes being drained
1688
    node_vol_should = {}
1689

    
1690
    # FIXME: verify OS list
1691
    # do local checksums
1692
    master_files = [constants.CLUSTER_CONF_FILE]
1693
    master_node = self.master_node = self.cfg.GetMasterNode()
1694
    master_ip = self.cfg.GetMasterIP()
1695

    
1696
    file_names = ssconf.SimpleStore().GetFileList()
1697
    file_names.extend(constants.ALL_CERT_FILES)
1698
    file_names.extend(master_files)
1699
    if cluster.modify_etc_hosts:
1700
      file_names.append(constants.ETC_HOSTS)
1701

    
1702
    local_checksums = utils.FingerprintFiles(file_names)
1703

    
1704
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1705
    node_verify_param = {
1706
      constants.NV_FILELIST: file_names,
1707
      constants.NV_NODELIST: [node.name for node in nodeinfo
1708
                              if not node.offline],
1709
      constants.NV_HYPERVISOR: hypervisors,
1710
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1711
                                  node.secondary_ip) for node in nodeinfo
1712
                                 if not node.offline],
1713
      constants.NV_INSTANCELIST: hypervisors,
1714
      constants.NV_VERSION: None,
1715
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1716
      constants.NV_NODESETUP: None,
1717
      constants.NV_TIME: None,
1718
      constants.NV_MASTERIP: (master_node, master_ip),
1719
      }
1720

    
1721
    if vg_name is not None:
1722
      node_verify_param[constants.NV_VGLIST] = None
1723
      node_verify_param[constants.NV_LVLIST] = vg_name
1724
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1725
      node_verify_param[constants.NV_DRBDLIST] = None
1726

    
1727
    # Build our expected cluster state
1728
    node_image = dict((node.name, self.NodeImage(offline=node.offline))
1729
                      for node in nodeinfo)
1730

    
1731
    for instance in instancelist:
1732
      inst_config = instanceinfo[instance]
1733

    
1734
      for nname in inst_config.all_nodes:
1735
        if nname not in node_image:
1736
          # ghost node
1737
          gnode = self.NodeImage()
1738
          gnode.ghost = True
1739
          node_image[nname] = gnode
1740

    
1741
      inst_config.MapLVsByNode(node_vol_should)
1742

    
1743
      pnode = inst_config.primary_node
1744
      node_image[pnode].pinst.append(instance)
1745

    
1746
      for snode in inst_config.secondary_nodes:
1747
        nimg = node_image[snode]
1748
        nimg.sinst.append(instance)
1749
        if pnode not in nimg.sbp:
1750
          nimg.sbp[pnode] = []
1751
        nimg.sbp[pnode].append(instance)
1752

    
1753
    # At this point, we have the in-memory data structures complete,
1754
    # except for the runtime information, which we'll gather next
1755

    
1756
    # Due to the way our RPC system works, exact response times cannot be
1757
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
1758
    # time before and after executing the request, we can at least have a time
1759
    # window.
1760
    nvinfo_starttime = time.time()
1761
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1762
                                           self.cfg.GetClusterName())
1763
    nvinfo_endtime = time.time()
1764

    
1765
    all_drbd_map = self.cfg.ComputeDRBDMap()
1766

    
1767
    feedback_fn("* Verifying node status")
1768
    for node_i in nodeinfo:
1769
      node = node_i.name
1770
      nimg = node_image[node]
1771

    
1772
      if node_i.offline:
1773
        if verbose:
1774
          feedback_fn("* Skipping offline node %s" % (node,))
1775
        n_offline += 1
1776
        continue
1777

    
1778
      if node == master_node:
1779
        ntype = "master"
1780
      elif node_i.master_candidate:
1781
        ntype = "master candidate"
1782
      elif node_i.drained:
1783
        ntype = "drained"
1784
        n_drained += 1
1785
      else:
1786
        ntype = "regular"
1787
      if verbose:
1788
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1789

    
1790
      msg = all_nvinfo[node].fail_msg
1791
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1792
      if msg:
1793
        nimg.rpc_fail = True
1794
        continue
1795

    
1796
      nresult = all_nvinfo[node].payload
1797

    
1798
      nimg.call_ok = self._VerifyNode(node_i, nresult)
1799
      self._VerifyNodeNetwork(node_i, nresult)
1800
      self._VerifyNodeLVM(node_i, nresult, vg_name)
1801
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
1802
                            master_files)
1803
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, all_drbd_map)
1804
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
1805

    
1806
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
1807
      self._UpdateNodeInstances(node_i, nresult, nimg)
1808
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
1809

    
1810
    feedback_fn("* Verifying instance status")
1811
    for instance in instancelist:
1812
      if verbose:
1813
        feedback_fn("* Verifying instance %s" % instance)
1814
      inst_config = instanceinfo[instance]
1815
      self._VerifyInstance(instance, inst_config, node_image)
1816
      inst_nodes_offline = []
1817

    
1818
      pnode = inst_config.primary_node
1819
      pnode_img = node_image[pnode]
1820
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
1821
               self.ENODERPC, pnode, "instance %s, connection to"
1822
               " primary node failed", instance)
1823

    
1824
      if pnode_img.offline:
1825
        inst_nodes_offline.append(pnode)
1826

    
1827
      # If the instance is non-redundant we cannot survive losing its primary
1828
      # node, so we are not N+1 compliant. On the other hand we have no disk
1829
      # templates with more than one secondary so that situation is not well
1830
      # supported either.
1831
      # FIXME: does not support file-backed instances
1832
      if not inst_config.secondary_nodes:
1833
        i_non_redundant.append(instance)
1834
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
1835
               instance, "instance has multiple secondary nodes: %s",
1836
               utils.CommaJoin(inst_config.secondary_nodes),
1837
               code=self.ETYPE_WARNING)
1838

    
1839
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1840
        i_non_a_balanced.append(instance)
1841

    
1842
      for snode in inst_config.secondary_nodes:
1843
        s_img = node_image[snode]
1844
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
1845
                 "instance %s, connection to secondary node failed", instance)
1846

    
1847
        if s_img.offline:
1848
          inst_nodes_offline.append(snode)
1849

    
1850
      # warn that the instance lives on offline nodes
1851
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1852
               "instance lives on offline node(s) %s",
1853
               utils.CommaJoin(inst_nodes_offline))
1854
      # ... or ghost nodes
1855
      for node in inst_config.all_nodes:
1856
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
1857
                 "instance lives on ghost node %s", node)
1858

    
1859
    feedback_fn("* Verifying orphan volumes")
1860
    self._VerifyOrphanVolumes(node_vol_should, node_image)
1861

    
1862
    feedback_fn("* Verifying orphan instances")
1863
    self._VerifyOrphanInstances(instancelist, node_image)
1864

    
1865
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1866
      feedback_fn("* Verifying N+1 Memory redundancy")
1867
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
1868

    
1869
    feedback_fn("* Other Notes")
1870
    if i_non_redundant:
1871
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1872
                  % len(i_non_redundant))
1873

    
1874
    if i_non_a_balanced:
1875
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1876
                  % len(i_non_a_balanced))
1877

    
1878
    if n_offline:
1879
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
1880

    
1881
    if n_drained:
1882
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
1883

    
1884
    return not self.bad
1885

    
1886
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1887
    """Analyze the post-hooks' result
1888

1889
    This method analyses the hook result, handles it, and sends some
1890
    nicely-formatted feedback back to the user.
1891

1892
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1893
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1894
    @param hooks_results: the results of the multi-node hooks rpc call
1895
    @param feedback_fn: function used send feedback back to the caller
1896
    @param lu_result: previous Exec result
1897
    @return: the new Exec result, based on the previous result
1898
        and hook results
1899

1900
    """
1901
    # We only really run POST phase hooks, and are only interested in
1902
    # their results
1903
    if phase == constants.HOOKS_PHASE_POST:
1904
      # Used to change hooks' output to proper indentation
1905
      indent_re = re.compile('^', re.M)
1906
      feedback_fn("* Hooks Results")
1907
      assert hooks_results, "invalid result from hooks"
1908

    
1909
      for node_name in hooks_results:
1910
        res = hooks_results[node_name]
1911
        msg = res.fail_msg
1912
        test = msg and not res.offline
1913
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1914
                      "Communication failure in hooks execution: %s", msg)
1915
        if res.offline or msg:
1916
          # No need to investigate payload if node is offline or gave an error.
1917
          # override manually lu_result here as _ErrorIf only
1918
          # overrides self.bad
1919
          lu_result = 1
1920
          continue
1921
        for script, hkr, output in res.payload:
1922
          test = hkr == constants.HKR_FAIL
1923
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1924
                        "Script %s failed, output:", script)
1925
          if test:
1926
            output = indent_re.sub('      ', output)
1927
            feedback_fn("%s" % output)
1928
            lu_result = 0
1929

    
1930
      return lu_result
1931

    
1932

    
1933
class LUVerifyDisks(NoHooksLU):
1934
  """Verifies the cluster disks status.
1935

1936
  """
1937
  _OP_REQP = []
1938
  REQ_BGL = False
1939

    
1940
  def ExpandNames(self):
1941
    self.needed_locks = {
1942
      locking.LEVEL_NODE: locking.ALL_SET,
1943
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1944
    }
1945
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1946

    
1947
  def CheckPrereq(self):
1948
    """Check prerequisites.
1949

1950
    This has no prerequisites.
1951

1952
    """
1953
    pass
1954

    
1955
  def Exec(self, feedback_fn):
1956
    """Verify integrity of cluster disks.
1957

1958
    @rtype: tuple of three items
1959
    @return: a tuple of (dict of node-to-node_error, list of instances
1960
        which need activate-disks, dict of instance: (node, volume) for
1961
        missing volumes
1962

1963
    """
1964
    result = res_nodes, res_instances, res_missing = {}, [], {}
1965

    
1966
    vg_name = self.cfg.GetVGName()
1967
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1968
    instances = [self.cfg.GetInstanceInfo(name)
1969
                 for name in self.cfg.GetInstanceList()]
1970

    
1971
    nv_dict = {}
1972
    for inst in instances:
1973
      inst_lvs = {}
1974
      if (not inst.admin_up or
1975
          inst.disk_template not in constants.DTS_NET_MIRROR):
1976
        continue
1977
      inst.MapLVsByNode(inst_lvs)
1978
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1979
      for node, vol_list in inst_lvs.iteritems():
1980
        for vol in vol_list:
1981
          nv_dict[(node, vol)] = inst
1982

    
1983
    if not nv_dict:
1984
      return result
1985

    
1986
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1987

    
1988
    for node in nodes:
1989
      # node_volume
1990
      node_res = node_lvs[node]
1991
      if node_res.offline:
1992
        continue
1993
      msg = node_res.fail_msg
1994
      if msg:
1995
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1996
        res_nodes[node] = msg
1997
        continue
1998

    
1999
      lvs = node_res.payload
2000
      for lv_name, (_, _, lv_online) in lvs.items():
2001
        inst = nv_dict.pop((node, lv_name), None)
2002
        if (not lv_online and inst is not None
2003
            and inst.name not in res_instances):
2004
          res_instances.append(inst.name)
2005

    
2006
    # any leftover items in nv_dict are missing LVs, let's arrange the
2007
    # data better
2008
    for key, inst in nv_dict.iteritems():
2009
      if inst.name not in res_missing:
2010
        res_missing[inst.name] = []
2011
      res_missing[inst.name].append(key)
2012

    
2013
    return result
2014

    
2015

    
2016
class LURepairDiskSizes(NoHooksLU):
2017
  """Verifies the cluster disks sizes.
2018

2019
  """
2020
  _OP_REQP = ["instances"]
2021
  REQ_BGL = False
2022

    
2023
  def ExpandNames(self):
2024
    if not isinstance(self.op.instances, list):
2025
      raise errors.OpPrereqError("Invalid argument type 'instances'",
2026
                                 errors.ECODE_INVAL)
2027

    
2028
    if self.op.instances:
2029
      self.wanted_names = []
2030
      for name in self.op.instances:
2031
        full_name = _ExpandInstanceName(self.cfg, name)
2032
        self.wanted_names.append(full_name)
2033
      self.needed_locks = {
2034
        locking.LEVEL_NODE: [],
2035
        locking.LEVEL_INSTANCE: self.wanted_names,
2036
        }
2037
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2038
    else:
2039
      self.wanted_names = None
2040
      self.needed_locks = {
2041
        locking.LEVEL_NODE: locking.ALL_SET,
2042
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2043
        }
2044
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2045

    
2046
  def DeclareLocks(self, level):
2047
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2048
      self._LockInstancesNodes(primary_only=True)
2049

    
2050
  def CheckPrereq(self):
2051
    """Check prerequisites.
2052

2053
    This only checks the optional instance list against the existing names.
2054

2055
    """
2056
    if self.wanted_names is None:
2057
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2058

    
2059
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2060
                             in self.wanted_names]
2061

    
2062
  def _EnsureChildSizes(self, disk):
2063
    """Ensure children of the disk have the needed disk size.
2064

2065
    This is valid mainly for DRBD8 and fixes an issue where the
2066
    children have smaller disk size.
2067

2068
    @param disk: an L{ganeti.objects.Disk} object
2069

2070
    """
2071
    if disk.dev_type == constants.LD_DRBD8:
2072
      assert disk.children, "Empty children for DRBD8?"
2073
      fchild = disk.children[0]
2074
      mismatch = fchild.size < disk.size
2075
      if mismatch:
2076
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2077
                     fchild.size, disk.size)
2078
        fchild.size = disk.size
2079

    
2080
      # and we recurse on this child only, not on the metadev
2081
      return self._EnsureChildSizes(fchild) or mismatch
2082
    else:
2083
      return False
2084

    
2085
  def Exec(self, feedback_fn):
2086
    """Verify the size of cluster disks.
2087

2088
    """
2089
    # TODO: check child disks too
2090
    # TODO: check differences in size between primary/secondary nodes
2091
    per_node_disks = {}
2092
    for instance in self.wanted_instances:
2093
      pnode = instance.primary_node
2094
      if pnode not in per_node_disks:
2095
        per_node_disks[pnode] = []
2096
      for idx, disk in enumerate(instance.disks):
2097
        per_node_disks[pnode].append((instance, idx, disk))
2098

    
2099
    changed = []
2100
    for node, dskl in per_node_disks.items():
2101
      newl = [v[2].Copy() for v in dskl]
2102
      for dsk in newl:
2103
        self.cfg.SetDiskID(dsk, node)
2104
      result = self.rpc.call_blockdev_getsizes(node, newl)
2105
      if result.fail_msg:
2106
        self.LogWarning("Failure in blockdev_getsizes call to node"
2107
                        " %s, ignoring", node)
2108
        continue
2109
      if len(result.data) != len(dskl):
2110
        self.LogWarning("Invalid result from node %s, ignoring node results",
2111
                        node)
2112
        continue
2113
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2114
        if size is None:
2115
          self.LogWarning("Disk %d of instance %s did not return size"
2116
                          " information, ignoring", idx, instance.name)
2117
          continue
2118
        if not isinstance(size, (int, long)):
2119
          self.LogWarning("Disk %d of instance %s did not return valid"
2120
                          " size information, ignoring", idx, instance.name)
2121
          continue
2122
        size = size >> 20
2123
        if size != disk.size:
2124
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2125
                       " correcting: recorded %d, actual %d", idx,
2126
                       instance.name, disk.size, size)
2127
          disk.size = size
2128
          self.cfg.Update(instance, feedback_fn)
2129
          changed.append((instance.name, idx, size))
2130
        if self._EnsureChildSizes(disk):
2131
          self.cfg.Update(instance, feedback_fn)
2132
          changed.append((instance.name, idx, disk.size))
2133
    return changed
2134

    
2135

    
2136
class LURenameCluster(LogicalUnit):
2137
  """Rename the cluster.
2138

2139
  """
2140
  HPATH = "cluster-rename"
2141
  HTYPE = constants.HTYPE_CLUSTER
2142
  _OP_REQP = ["name"]
2143

    
2144
  def BuildHooksEnv(self):
2145
    """Build hooks env.
2146

2147
    """
2148
    env = {
2149
      "OP_TARGET": self.cfg.GetClusterName(),
2150
      "NEW_NAME": self.op.name,
2151
      }
2152
    mn = self.cfg.GetMasterNode()
2153
    all_nodes = self.cfg.GetNodeList()
2154
    return env, [mn], all_nodes
2155

    
2156
  def CheckPrereq(self):
2157
    """Verify that the passed name is a valid one.
2158

2159
    """
2160
    hostname = utils.GetHostInfo(self.op.name)
2161

    
2162
    new_name = hostname.name
2163
    self.ip = new_ip = hostname.ip
2164
    old_name = self.cfg.GetClusterName()
2165
    old_ip = self.cfg.GetMasterIP()
2166
    if new_name == old_name and new_ip == old_ip:
2167
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2168
                                 " cluster has changed",
2169
                                 errors.ECODE_INVAL)
2170
    if new_ip != old_ip:
2171
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2172
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2173
                                   " reachable on the network. Aborting." %
2174
                                   new_ip, errors.ECODE_NOTUNIQUE)
2175

    
2176
    self.op.name = new_name
2177

    
2178
  def Exec(self, feedback_fn):
2179
    """Rename the cluster.
2180

2181
    """
2182
    clustername = self.op.name
2183
    ip = self.ip
2184

    
2185
    # shutdown the master IP
2186
    master = self.cfg.GetMasterNode()
2187
    result = self.rpc.call_node_stop_master(master, False)
2188
    result.Raise("Could not disable the master role")
2189

    
2190
    try:
2191
      cluster = self.cfg.GetClusterInfo()
2192
      cluster.cluster_name = clustername
2193
      cluster.master_ip = ip
2194
      self.cfg.Update(cluster, feedback_fn)
2195

    
2196
      # update the known hosts file
2197
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2198
      node_list = self.cfg.GetNodeList()
2199
      try:
2200
        node_list.remove(master)
2201
      except ValueError:
2202
        pass
2203
      result = self.rpc.call_upload_file(node_list,
2204
                                         constants.SSH_KNOWN_HOSTS_FILE)
2205
      for to_node, to_result in result.iteritems():
2206
        msg = to_result.fail_msg
2207
        if msg:
2208
          msg = ("Copy of file %s to node %s failed: %s" %
2209
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2210
          self.proc.LogWarning(msg)
2211

    
2212
    finally:
2213
      result = self.rpc.call_node_start_master(master, False, False)
2214
      msg = result.fail_msg
2215
      if msg:
2216
        self.LogWarning("Could not re-enable the master role on"
2217
                        " the master, please restart manually: %s", msg)
2218

    
2219

    
2220
def _RecursiveCheckIfLVMBased(disk):
2221
  """Check if the given disk or its children are lvm-based.
2222

2223
  @type disk: L{objects.Disk}
2224
  @param disk: the disk to check
2225
  @rtype: boolean
2226
  @return: boolean indicating whether a LD_LV dev_type was found or not
2227

2228
  """
2229
  if disk.children:
2230
    for chdisk in disk.children:
2231
      if _RecursiveCheckIfLVMBased(chdisk):
2232
        return True
2233
  return disk.dev_type == constants.LD_LV
2234

    
2235

    
2236
class LUSetClusterParams(LogicalUnit):
2237
  """Change the parameters of the cluster.
2238

2239
  """
2240
  HPATH = "cluster-modify"
2241
  HTYPE = constants.HTYPE_CLUSTER
2242
  _OP_REQP = []
2243
  REQ_BGL = False
2244

    
2245
  def CheckArguments(self):
2246
    """Check parameters
2247

2248
    """
2249
    for attr in ["candidate_pool_size",
2250
                 "uid_pool", "add_uids", "remove_uids"]:
2251
      if not hasattr(self.op, attr):
2252
        setattr(self.op, attr, None)
2253

    
2254
    if self.op.candidate_pool_size is not None:
2255
      try:
2256
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
2257
      except (ValueError, TypeError), err:
2258
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
2259
                                   str(err), errors.ECODE_INVAL)
2260
      if self.op.candidate_pool_size < 1:
2261
        raise errors.OpPrereqError("At least one master candidate needed",
2262
                                   errors.ECODE_INVAL)
2263

    
2264
    _CheckBooleanOpField(self.op, "maintain_node_health")
2265

    
2266
    if self.op.uid_pool:
2267
      uidpool.CheckUidPool(self.op.uid_pool)
2268

    
2269
    if self.op.add_uids:
2270
      uidpool.CheckUidPool(self.op.add_uids)
2271

    
2272
    if self.op.remove_uids:
2273
      uidpool.CheckUidPool(self.op.remove_uids)
2274

    
2275
  def ExpandNames(self):
2276
    # FIXME: in the future maybe other cluster params won't require checking on
2277
    # all nodes to be modified.
2278
    self.needed_locks = {
2279
      locking.LEVEL_NODE: locking.ALL_SET,
2280
    }
2281
    self.share_locks[locking.LEVEL_NODE] = 1
2282

    
2283
  def BuildHooksEnv(self):
2284
    """Build hooks env.
2285

2286
    """
2287
    env = {
2288
      "OP_TARGET": self.cfg.GetClusterName(),
2289
      "NEW_VG_NAME": self.op.vg_name,
2290
      }
2291
    mn = self.cfg.GetMasterNode()
2292
    return env, [mn], [mn]
2293

    
2294
  def CheckPrereq(self):
2295
    """Check prerequisites.
2296

2297
    This checks whether the given params don't conflict and
2298
    if the given volume group is valid.
2299

2300
    """
2301
    if self.op.vg_name is not None and not self.op.vg_name:
2302
      instances = self.cfg.GetAllInstancesInfo().values()
2303
      for inst in instances:
2304
        for disk in inst.disks:
2305
          if _RecursiveCheckIfLVMBased(disk):
2306
            raise errors.OpPrereqError("Cannot disable lvm storage while"
2307
                                       " lvm-based instances exist",
2308
                                       errors.ECODE_INVAL)
2309

    
2310
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2311

    
2312
    # if vg_name not None, checks given volume group on all nodes
2313
    if self.op.vg_name:
2314
      vglist = self.rpc.call_vg_list(node_list)
2315
      for node in node_list:
2316
        msg = vglist[node].fail_msg
2317
        if msg:
2318
          # ignoring down node
2319
          self.LogWarning("Error while gathering data on node %s"
2320
                          " (ignoring node): %s", node, msg)
2321
          continue
2322
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2323
                                              self.op.vg_name,
2324
                                              constants.MIN_VG_SIZE)
2325
        if vgstatus:
2326
          raise errors.OpPrereqError("Error on node '%s': %s" %
2327
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2328

    
2329
    self.cluster = cluster = self.cfg.GetClusterInfo()
2330
    # validate params changes
2331
    if self.op.beparams:
2332
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2333
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2334

    
2335
    if self.op.nicparams:
2336
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2337
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2338
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2339
      nic_errors = []
2340

    
2341
      # check all instances for consistency
2342
      for instance in self.cfg.GetAllInstancesInfo().values():
2343
        for nic_idx, nic in enumerate(instance.nics):
2344
          params_copy = copy.deepcopy(nic.nicparams)
2345
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2346

    
2347
          # check parameter syntax
2348
          try:
2349
            objects.NIC.CheckParameterSyntax(params_filled)
2350
          except errors.ConfigurationError, err:
2351
            nic_errors.append("Instance %s, nic/%d: %s" %
2352
                              (instance.name, nic_idx, err))
2353

    
2354
          # if we're moving instances to routed, check that they have an ip
2355
          target_mode = params_filled[constants.NIC_MODE]
2356
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2357
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2358
                              (instance.name, nic_idx))
2359
      if nic_errors:
2360
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2361
                                   "\n".join(nic_errors))
2362

    
2363
    # hypervisor list/parameters
2364
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2365
    if self.op.hvparams:
2366
      if not isinstance(self.op.hvparams, dict):
2367
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
2368
                                   errors.ECODE_INVAL)
2369
      for hv_name, hv_dict in self.op.hvparams.items():
2370
        if hv_name not in self.new_hvparams:
2371
          self.new_hvparams[hv_name] = hv_dict
2372
        else:
2373
          self.new_hvparams[hv_name].update(hv_dict)
2374

    
2375
    # os hypervisor parameters
2376
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2377
    if self.op.os_hvp:
2378
      if not isinstance(self.op.os_hvp, dict):
2379
        raise errors.OpPrereqError("Invalid 'os_hvp' parameter on input",
2380
                                   errors.ECODE_INVAL)
2381
      for os_name, hvs in self.op.os_hvp.items():
2382
        if not isinstance(hvs, dict):
2383
          raise errors.OpPrereqError(("Invalid 'os_hvp' parameter on"
2384
                                      " input"), errors.ECODE_INVAL)
2385
        if os_name not in self.new_os_hvp:
2386
          self.new_os_hvp[os_name] = hvs
2387
        else:
2388
          for hv_name, hv_dict in hvs.items():
2389
            if hv_name not in self.new_os_hvp[os_name]:
2390
              self.new_os_hvp[os_name][hv_name] = hv_dict
2391
            else:
2392
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2393

    
2394
    # changes to the hypervisor list
2395
    if self.op.enabled_hypervisors is not None:
2396
      self.hv_list = self.op.enabled_hypervisors
2397
      if not self.hv_list:
2398
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
2399
                                   " least one member",
2400
                                   errors.ECODE_INVAL)
2401
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
2402
      if invalid_hvs:
2403
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
2404
                                   " entries: %s" %
2405
                                   utils.CommaJoin(invalid_hvs),
2406
                                   errors.ECODE_INVAL)
2407
      for hv in self.hv_list:
2408
        # if the hypervisor doesn't already exist in the cluster
2409
        # hvparams, we initialize it to empty, and then (in both
2410
        # cases) we make sure to fill the defaults, as we might not
2411
        # have a complete defaults list if the hypervisor wasn't
2412
        # enabled before
2413
        if hv not in new_hvp:
2414
          new_hvp[hv] = {}
2415
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2416
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2417
    else:
2418
      self.hv_list = cluster.enabled_hypervisors
2419

    
2420
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2421
      # either the enabled list has changed, or the parameters have, validate
2422
      for hv_name, hv_params in self.new_hvparams.items():
2423
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2424
            (self.op.enabled_hypervisors and
2425
             hv_name in self.op.enabled_hypervisors)):
2426
          # either this is a new hypervisor, or its parameters have changed
2427
          hv_class = hypervisor.GetHypervisor(hv_name)
2428
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2429
          hv_class.CheckParameterSyntax(hv_params)
2430
          _CheckHVParams(self, node_list, hv_name, hv_params)
2431

    
2432
    if self.op.os_hvp:
2433
      # no need to check any newly-enabled hypervisors, since the
2434
      # defaults have already been checked in the above code-block
2435
      for os_name, os_hvp in self.new_os_hvp.items():
2436
        for hv_name, hv_params in os_hvp.items():
2437
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2438
          # we need to fill in the new os_hvp on top of the actual hv_p
2439
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2440
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2441
          hv_class = hypervisor.GetHypervisor(hv_name)
2442
          hv_class.CheckParameterSyntax(new_osp)
2443
          _CheckHVParams(self, node_list, hv_name, new_osp)
2444

    
2445

    
2446
  def Exec(self, feedback_fn):
2447
    """Change the parameters of the cluster.
2448

2449
    """
2450
    if self.op.vg_name is not None:
2451
      new_volume = self.op.vg_name
2452
      if not new_volume:
2453
        new_volume = None
2454
      if new_volume != self.cfg.GetVGName():
2455
        self.cfg.SetVGName(new_volume)
2456
      else:
2457
        feedback_fn("Cluster LVM configuration already in desired"
2458
                    " state, not changing")
2459
    if self.op.hvparams:
2460
      self.cluster.hvparams = self.new_hvparams
2461
    if self.op.os_hvp:
2462
      self.cluster.os_hvp = self.new_os_hvp
2463
    if self.op.enabled_hypervisors is not None:
2464
      self.cluster.hvparams = self.new_hvparams
2465
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2466
    if self.op.beparams:
2467
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2468
    if self.op.nicparams:
2469
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2470

    
2471
    if self.op.candidate_pool_size is not None:
2472
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2473
      # we need to update the pool size here, otherwise the save will fail
2474
      _AdjustCandidatePool(self, [])
2475

    
2476
    if self.op.maintain_node_health is not None:
2477
      self.cluster.maintain_node_health = self.op.maintain_node_health
2478

    
2479
    if self.op.add_uids is not None:
2480
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2481

    
2482
    if self.op.remove_uids is not None:
2483
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2484

    
2485
    if self.op.uid_pool is not None:
2486
      self.cluster.uid_pool = self.op.uid_pool
2487

    
2488
    self.cfg.Update(self.cluster, feedback_fn)
2489

    
2490

    
2491
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2492
  """Distribute additional files which are part of the cluster configuration.
2493

2494
  ConfigWriter takes care of distributing the config and ssconf files, but
2495
  there are more files which should be distributed to all nodes. This function
2496
  makes sure those are copied.
2497

2498
  @param lu: calling logical unit
2499
  @param additional_nodes: list of nodes not in the config to distribute to
2500

2501
  """
2502
  # 1. Gather target nodes
2503
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2504
  dist_nodes = lu.cfg.GetOnlineNodeList()
2505
  if additional_nodes is not None:
2506
    dist_nodes.extend(additional_nodes)
2507
  if myself.name in dist_nodes:
2508
    dist_nodes.remove(myself.name)
2509

    
2510
  # 2. Gather files to distribute
2511
  dist_files = set([constants.ETC_HOSTS,
2512
                    constants.SSH_KNOWN_HOSTS_FILE,
2513
                    constants.RAPI_CERT_FILE,
2514
                    constants.RAPI_USERS_FILE,
2515
                    constants.CONFD_HMAC_KEY,
2516
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2517
                   ])
2518

    
2519
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2520
  for hv_name in enabled_hypervisors:
2521
    hv_class = hypervisor.GetHypervisor(hv_name)
2522
    dist_files.update(hv_class.GetAncillaryFiles())
2523

    
2524
  # 3. Perform the files upload
2525
  for fname in dist_files:
2526
    if os.path.exists(fname):
2527
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2528
      for to_node, to_result in result.items():
2529
        msg = to_result.fail_msg
2530
        if msg:
2531
          msg = ("Copy of file %s to node %s failed: %s" %
2532
                 (fname, to_node, msg))
2533
          lu.proc.LogWarning(msg)
2534

    
2535

    
2536
class LURedistributeConfig(NoHooksLU):
2537
  """Force the redistribution of cluster configuration.
2538

2539
  This is a very simple LU.
2540

2541
  """
2542
  _OP_REQP = []
2543
  REQ_BGL = False
2544

    
2545
  def ExpandNames(self):
2546
    self.needed_locks = {
2547
      locking.LEVEL_NODE: locking.ALL_SET,
2548
    }
2549
    self.share_locks[locking.LEVEL_NODE] = 1
2550

    
2551
  def CheckPrereq(self):
2552
    """Check prerequisites.
2553

2554
    """
2555

    
2556
  def Exec(self, feedback_fn):
2557
    """Redistribute the configuration.
2558

2559
    """
2560
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2561
    _RedistributeAncillaryFiles(self)
2562

    
2563

    
2564
def _WaitForSync(lu, instance, disks=None, oneshot=False):
2565
  """Sleep and poll for an instance's disk to sync.
2566

2567
  """
2568
  if not instance.disks or disks is not None and not disks:
2569
    return True
2570

    
2571
  disks = _ExpandCheckDisks(instance, disks)
2572

    
2573
  if not oneshot:
2574
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2575

    
2576
  node = instance.primary_node
2577

    
2578
  for dev in disks:
2579
    lu.cfg.SetDiskID(dev, node)
2580

    
2581
  # TODO: Convert to utils.Retry
2582

    
2583
  retries = 0
2584
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2585
  while True:
2586
    max_time = 0
2587
    done = True
2588
    cumul_degraded = False
2589
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2590
    msg = rstats.fail_msg
2591
    if msg:
2592
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2593
      retries += 1
2594
      if retries >= 10:
2595
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2596
                                 " aborting." % node)
2597
      time.sleep(6)
2598
      continue
2599
    rstats = rstats.payload
2600
    retries = 0
2601
    for i, mstat in enumerate(rstats):
2602
      if mstat is None:
2603
        lu.LogWarning("Can't compute data for node %s/%s",
2604
                           node, disks[i].iv_name)
2605
        continue
2606

    
2607
      cumul_degraded = (cumul_degraded or
2608
                        (mstat.is_degraded and mstat.sync_percent is None))
2609
      if mstat.sync_percent is not None:
2610
        done = False
2611
        if mstat.estimated_time is not None:
2612
          rem_time = ("%s remaining (estimated)" %
2613
                      utils.FormatSeconds(mstat.estimated_time))
2614
          max_time = mstat.estimated_time
2615
        else:
2616
          rem_time = "no time estimate"
2617
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2618
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
2619

    
2620
    # if we're done but degraded, let's do a few small retries, to
2621
    # make sure we see a stable and not transient situation; therefore
2622
    # we force restart of the loop
2623
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2624
      logging.info("Degraded disks found, %d retries left", degr_retries)
2625
      degr_retries -= 1
2626
      time.sleep(1)
2627
      continue
2628

    
2629
    if done or oneshot:
2630
      break
2631

    
2632
    time.sleep(min(60, max_time))
2633

    
2634
  if done:
2635
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2636
  return not cumul_degraded
2637

    
2638

    
2639
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2640
  """Check that mirrors are not degraded.
2641

2642
  The ldisk parameter, if True, will change the test from the
2643
  is_degraded attribute (which represents overall non-ok status for
2644
  the device(s)) to the ldisk (representing the local storage status).
2645

2646
  """
2647
  lu.cfg.SetDiskID(dev, node)
2648

    
2649
  result = True
2650

    
2651
  if on_primary or dev.AssembleOnSecondary():
2652
    rstats = lu.rpc.call_blockdev_find(node, dev)
2653
    msg = rstats.fail_msg
2654
    if msg:
2655
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2656
      result = False
2657
    elif not rstats.payload:
2658
      lu.LogWarning("Can't find disk on node %s", node)
2659
      result = False
2660
    else:
2661
      if ldisk:
2662
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2663
      else:
2664
        result = result and not rstats.payload.is_degraded
2665

    
2666
  if dev.children:
2667
    for child in dev.children:
2668
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2669

    
2670
  return result
2671

    
2672

    
2673
class LUDiagnoseOS(NoHooksLU):
2674
  """Logical unit for OS diagnose/query.
2675

2676
  """
2677
  _OP_REQP = ["output_fields", "names"]
2678
  REQ_BGL = False
2679
  _FIELDS_STATIC = utils.FieldSet()
2680
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2681
  # Fields that need calculation of global os validity
2682
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2683

    
2684
  def ExpandNames(self):
2685
    if self.op.names:
2686
      raise errors.OpPrereqError("Selective OS query not supported",
2687
                                 errors.ECODE_INVAL)
2688

    
2689
    _CheckOutputFields(static=self._FIELDS_STATIC,
2690
                       dynamic=self._FIELDS_DYNAMIC,
2691
                       selected=self.op.output_fields)
2692

    
2693
    # Lock all nodes, in shared mode
2694
    # Temporary removal of locks, should be reverted later
2695
    # TODO: reintroduce locks when they are lighter-weight
2696
    self.needed_locks = {}
2697
    #self.share_locks[locking.LEVEL_NODE] = 1
2698
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2699

    
2700
  def CheckPrereq(self):
2701
    """Check prerequisites.
2702

2703
    """
2704

    
2705
  @staticmethod
2706
  def _DiagnoseByOS(rlist):
2707
    """Remaps a per-node return list into an a per-os per-node dictionary
2708

2709
    @param rlist: a map with node names as keys and OS objects as values
2710

2711
    @rtype: dict
2712
    @return: a dictionary with osnames as keys and as value another map, with
2713
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2714

2715
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2716
                                     (/srv/..., False, "invalid api")],
2717
                           "node2": [(/srv/..., True, "")]}
2718
          }
2719

2720
    """
2721
    all_os = {}
2722
    # we build here the list of nodes that didn't fail the RPC (at RPC
2723
    # level), so that nodes with a non-responding node daemon don't
2724
    # make all OSes invalid
2725
    good_nodes = [node_name for node_name in rlist
2726
                  if not rlist[node_name].fail_msg]
2727
    for node_name, nr in rlist.items():
2728
      if nr.fail_msg or not nr.payload:
2729
        continue
2730
      for name, path, status, diagnose, variants in nr.payload:
2731
        if name not in all_os:
2732
          # build a list of nodes for this os containing empty lists
2733
          # for each node in node_list
2734
          all_os[name] = {}
2735
          for nname in good_nodes:
2736
            all_os[name][nname] = []
2737
        all_os[name][node_name].append((path, status, diagnose, variants))
2738
    return all_os
2739

    
2740
  def Exec(self, feedback_fn):
2741
    """Compute the list of OSes.
2742

2743
    """
2744
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2745
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2746
    pol = self._DiagnoseByOS(node_data)
2747
    output = []
2748
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2749
    calc_variants = "variants" in self.op.output_fields
2750

    
2751
    for os_name, os_data in pol.items():
2752
      row = []
2753
      if calc_valid:
2754
        valid = True
2755
        variants = None
2756
        for osl in os_data.values():
2757
          valid = valid and osl and osl[0][1]
2758
          if not valid:
2759
            variants = set()
2760
            break
2761
          if calc_variants:
2762
            node_variants = osl[0][3]
2763
            if variants is None:
2764
              variants = set(node_variants)
2765
            else:
2766
              variants.intersection_update(node_variants)
2767

    
2768
      for field in self.op.output_fields:
2769
        if field == "name":
2770
          val = os_name
2771
        elif field == "valid":
2772
          val = valid
2773
        elif field == "node_status":
2774
          # this is just a copy of the dict
2775
          val = {}
2776
          for node_name, nos_list in os_data.items():
2777
            val[node_name] = nos_list
2778
        elif field == "variants":
2779
          val = list(variants)
2780
        else:
2781
          raise errors.ParameterError(field)
2782
        row.append(val)
2783
      output.append(row)
2784

    
2785
    return output
2786

    
2787

    
2788
class LURemoveNode(LogicalUnit):
2789
  """Logical unit for removing a node.
2790

2791
  """
2792
  HPATH = "node-remove"
2793
  HTYPE = constants.HTYPE_NODE
2794
  _OP_REQP = ["node_name"]
2795

    
2796
  def BuildHooksEnv(self):
2797
    """Build hooks env.
2798

2799
    This doesn't run on the target node in the pre phase as a failed
2800
    node would then be impossible to remove.
2801

2802
    """
2803
    env = {
2804
      "OP_TARGET": self.op.node_name,
2805
      "NODE_NAME": self.op.node_name,
2806
      }
2807
    all_nodes = self.cfg.GetNodeList()
2808
    try:
2809
      all_nodes.remove(self.op.node_name)
2810
    except ValueError:
2811
      logging.warning("Node %s which is about to be removed not found"
2812
                      " in the all nodes list", self.op.node_name)
2813
    return env, all_nodes, all_nodes
2814

    
2815
  def CheckPrereq(self):
2816
    """Check prerequisites.
2817

2818
    This checks:
2819
     - the node exists in the configuration
2820
     - it does not have primary or secondary instances
2821
     - it's not the master
2822

2823
    Any errors are signaled by raising errors.OpPrereqError.
2824

2825
    """
2826
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
2827
    node = self.cfg.GetNodeInfo(self.op.node_name)
2828
    assert node is not None
2829

    
2830
    instance_list = self.cfg.GetInstanceList()
2831

    
2832
    masternode = self.cfg.GetMasterNode()
2833
    if node.name == masternode:
2834
      raise errors.OpPrereqError("Node is the master node,"
2835
                                 " you need to failover first.",
2836
                                 errors.ECODE_INVAL)
2837

    
2838
    for instance_name in instance_list:
2839
      instance = self.cfg.GetInstanceInfo(instance_name)
2840
      if node.name in instance.all_nodes:
2841
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2842
                                   " please remove first." % instance_name,
2843
                                   errors.ECODE_INVAL)
2844
    self.op.node_name = node.name
2845
    self.node = node
2846

    
2847
  def Exec(self, feedback_fn):
2848
    """Removes the node from the cluster.
2849

2850
    """
2851
    node = self.node
2852
    logging.info("Stopping the node daemon and removing configs from node %s",
2853
                 node.name)
2854

    
2855
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2856

    
2857
    # Promote nodes to master candidate as needed
2858
    _AdjustCandidatePool(self, exceptions=[node.name])
2859
    self.context.RemoveNode(node.name)
2860

    
2861
    # Run post hooks on the node before it's removed
2862
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2863
    try:
2864
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2865
    except:
2866
      # pylint: disable-msg=W0702
2867
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2868

    
2869
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2870
    msg = result.fail_msg
2871
    if msg:
2872
      self.LogWarning("Errors encountered on the remote node while leaving"
2873
                      " the cluster: %s", msg)
2874

    
2875
    # Remove node from our /etc/hosts
2876
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2877
      # FIXME: this should be done via an rpc call to node daemon
2878
      utils.RemoveHostFromEtcHosts(node.name)
2879
      _RedistributeAncillaryFiles(self)
2880

    
2881

    
2882
class LUQueryNodes(NoHooksLU):
2883
  """Logical unit for querying nodes.
2884

2885
  """
2886
  # pylint: disable-msg=W0142
2887
  _OP_REQP = ["output_fields", "names", "use_locking"]
2888
  REQ_BGL = False
2889

    
2890
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2891
                    "master_candidate", "offline", "drained"]
2892

    
2893
  _FIELDS_DYNAMIC = utils.FieldSet(
2894
    "dtotal", "dfree",
2895
    "mtotal", "mnode", "mfree",
2896
    "bootid",
2897
    "ctotal", "cnodes", "csockets",
2898
    )
2899

    
2900
  _FIELDS_STATIC = utils.FieldSet(*[
2901
    "pinst_cnt", "sinst_cnt",
2902
    "pinst_list", "sinst_list",
2903
    "pip", "sip", "tags",
2904
    "master",
2905
    "role"] + _SIMPLE_FIELDS
2906
    )
2907

    
2908
  def ExpandNames(self):
2909
    _CheckOutputFields(static=self._FIELDS_STATIC,
2910
                       dynamic=self._FIELDS_DYNAMIC,
2911
                       selected=self.op.output_fields)
2912

    
2913
    self.needed_locks = {}
2914
    self.share_locks[locking.LEVEL_NODE] = 1
2915

    
2916
    if self.op.names:
2917
      self.wanted = _GetWantedNodes(self, self.op.names)
2918
    else:
2919
      self.wanted = locking.ALL_SET
2920

    
2921
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2922
    self.do_locking = self.do_node_query and self.op.use_locking
2923
    if self.do_locking:
2924
      # if we don't request only static fields, we need to lock the nodes
2925
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2926

    
2927
  def CheckPrereq(self):
2928
    """Check prerequisites.
2929

2930
    """
2931
    # The validation of the node list is done in the _GetWantedNodes,
2932
    # if non empty, and if empty, there's no validation to do
2933
    pass
2934

    
2935
  def Exec(self, feedback_fn):
2936
    """Computes the list of nodes and their attributes.
2937

2938
    """
2939
    all_info = self.cfg.GetAllNodesInfo()
2940
    if self.do_locking:
2941
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2942
    elif self.wanted != locking.ALL_SET:
2943
      nodenames = self.wanted
2944
      missing = set(nodenames).difference(all_info.keys())
2945
      if missing:
2946
        raise errors.OpExecError(
2947
          "Some nodes were removed before retrieving their data: %s" % missing)
2948
    else:
2949
      nodenames = all_info.keys()
2950

    
2951
    nodenames = utils.NiceSort(nodenames)
2952
    nodelist = [all_info[name] for name in nodenames]
2953

    
2954
    # begin data gathering
2955

    
2956
    if self.do_node_query:
2957
      live_data = {}
2958
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2959
                                          self.cfg.GetHypervisorType())
2960
      for name in nodenames:
2961
        nodeinfo = node_data[name]
2962
        if not nodeinfo.fail_msg and nodeinfo.payload:
2963
          nodeinfo = nodeinfo.payload
2964
          fn = utils.TryConvert
2965
          live_data[name] = {
2966
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2967
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2968
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2969
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2970
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2971
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2972
            "bootid": nodeinfo.get('bootid', None),
2973
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2974
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2975
            }
2976
        else:
2977
          live_data[name] = {}
2978
    else:
2979
      live_data = dict.fromkeys(nodenames, {})
2980

    
2981
    node_to_primary = dict([(name, set()) for name in nodenames])
2982
    node_to_secondary = dict([(name, set()) for name in nodenames])
2983

    
2984
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2985
                             "sinst_cnt", "sinst_list"))
2986
    if inst_fields & frozenset(self.op.output_fields):
2987
      inst_data = self.cfg.GetAllInstancesInfo()
2988

    
2989
      for inst in inst_data.values():
2990
        if inst.primary_node in node_to_primary:
2991
          node_to_primary[inst.primary_node].add(inst.name)
2992
        for secnode in inst.secondary_nodes:
2993
          if secnode in node_to_secondary:
2994
            node_to_secondary[secnode].add(inst.name)
2995

    
2996
    master_node = self.cfg.GetMasterNode()
2997

    
2998
    # end data gathering
2999

    
3000
    output = []
3001
    for node in nodelist:
3002
      node_output = []
3003
      for field in self.op.output_fields:
3004
        if field in self._SIMPLE_FIELDS:
3005
          val = getattr(node, field)
3006
        elif field == "pinst_list":
3007
          val = list(node_to_primary[node.name])
3008
        elif field == "sinst_list":
3009
          val = list(node_to_secondary[node.name])
3010
        elif field == "pinst_cnt":
3011
          val = len(node_to_primary[node.name])
3012
        elif field == "sinst_cnt":
3013
          val = len(node_to_secondary[node.name])
3014
        elif field == "pip":
3015
          val = node.primary_ip
3016
        elif field == "sip":
3017
          val = node.secondary_ip
3018
        elif field == "tags":
3019
          val = list(node.GetTags())
3020
        elif field == "master":
3021
          val = node.name == master_node
3022
        elif self._FIELDS_DYNAMIC.Matches(field):
3023
          val = live_data[node.name].get(field, None)
3024
        elif field == "role":
3025
          if node.name == master_node:
3026
            val = "M"
3027
          elif node.master_candidate:
3028
            val = "C"
3029
          elif node.drained:
3030
            val = "D"
3031
          elif node.offline:
3032
            val = "O"
3033
          else:
3034
            val = "R"
3035
        else:
3036
          raise errors.ParameterError(field)
3037
        node_output.append(val)
3038
      output.append(node_output)
3039

    
3040
    return output
3041

    
3042

    
3043
class LUQueryNodeVolumes(NoHooksLU):
3044
  """Logical unit for getting volumes on node(s).
3045

3046
  """
3047
  _OP_REQP = ["nodes", "output_fields"]
3048
  REQ_BGL = False
3049
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3050
  _FIELDS_STATIC = utils.FieldSet("node")
3051

    
3052
  def ExpandNames(self):
3053
    _CheckOutputFields(static=self._FIELDS_STATIC,
3054
                       dynamic=self._FIELDS_DYNAMIC,
3055
                       selected=self.op.output_fields)
3056

    
3057
    self.needed_locks = {}
3058
    self.share_locks[locking.LEVEL_NODE] = 1
3059
    if not self.op.nodes:
3060
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3061
    else:
3062
      self.needed_locks[locking.LEVEL_NODE] = \
3063
        _GetWantedNodes(self, self.op.nodes)
3064

    
3065
  def CheckPrereq(self):
3066
    """Check prerequisites.
3067

3068
    This checks that the fields required are valid output fields.
3069

3070
    """
3071
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3072

    
3073
  def Exec(self, feedback_fn):
3074
    """Computes the list of nodes and their attributes.
3075

3076
    """
3077
    nodenames = self.nodes
3078
    volumes = self.rpc.call_node_volumes(nodenames)
3079

    
3080
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3081
             in self.cfg.GetInstanceList()]
3082

    
3083
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3084

    
3085
    output = []
3086
    for node in nodenames:
3087
      nresult = volumes[node]
3088
      if nresult.offline:
3089
        continue
3090
      msg = nresult.fail_msg
3091
      if msg:
3092
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3093
        continue
3094

    
3095
      node_vols = nresult.payload[:]
3096
      node_vols.sort(key=lambda vol: vol['dev'])
3097

    
3098
      for vol in node_vols:
3099
        node_output = []
3100
        for field in self.op.output_fields:
3101
          if field == "node":
3102
            val = node
3103
          elif field == "phys":
3104
            val = vol['dev']
3105
          elif field == "vg":
3106
            val = vol['vg']
3107
          elif field == "name":
3108
            val = vol['name']
3109
          elif field == "size":
3110
            val = int(float(vol['size']))
3111
          elif field == "instance":
3112
            for inst in ilist:
3113
              if node not in lv_by_node[inst]:
3114
                continue
3115
              if vol['name'] in lv_by_node[inst][node]:
3116
                val = inst.name
3117
                break
3118
            else:
3119
              val = '-'
3120
          else:
3121
            raise errors.ParameterError(field)
3122
          node_output.append(str(val))
3123

    
3124
        output.append(node_output)
3125

    
3126
    return output
3127

    
3128

    
3129
class LUQueryNodeStorage(NoHooksLU):
3130
  """Logical unit for getting information on storage units on node(s).
3131

3132
  """
3133
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
3134
  REQ_BGL = False
3135
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3136

    
3137
  def CheckArguments(self):
3138
    _CheckStorageType(self.op.storage_type)
3139

    
3140
    _CheckOutputFields(static=self._FIELDS_STATIC,
3141
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3142
                       selected=self.op.output_fields)
3143

    
3144
  def ExpandNames(self):
3145
    self.needed_locks = {}
3146
    self.share_locks[locking.LEVEL_NODE] = 1
3147

    
3148
    if self.op.nodes:
3149
      self.needed_locks[locking.LEVEL_NODE] = \
3150
        _GetWantedNodes(self, self.op.nodes)
3151
    else:
3152
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3153

    
3154
  def CheckPrereq(self):
3155
    """Check prerequisites.
3156

3157
    This checks that the fields required are valid output fields.
3158

3159
    """
3160
    self.op.name = getattr(self.op, "name", None)
3161

    
3162
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3163

    
3164
  def Exec(self, feedback_fn):
3165
    """Computes the list of nodes and their attributes.
3166

3167
    """
3168
    # Always get name to sort by
3169
    if constants.SF_NAME in self.op.output_fields:
3170
      fields = self.op.output_fields[:]
3171
    else:
3172
      fields = [constants.SF_NAME] + self.op.output_fields
3173

    
3174
    # Never ask for node or type as it's only known to the LU
3175
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3176
      while extra in fields:
3177
        fields.remove(extra)
3178

    
3179
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3180
    name_idx = field_idx[constants.SF_NAME]
3181

    
3182
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3183
    data = self.rpc.call_storage_list(self.nodes,
3184
                                      self.op.storage_type, st_args,
3185
                                      self.op.name, fields)
3186

    
3187
    result = []
3188

    
3189
    for node in utils.NiceSort(self.nodes):
3190
      nresult = data[node]
3191
      if nresult.offline:
3192
        continue
3193

    
3194
      msg = nresult.fail_msg
3195
      if msg:
3196
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3197
        continue
3198

    
3199
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3200

    
3201
      for name in utils.NiceSort(rows.keys()):
3202
        row = rows[name]
3203

    
3204
        out = []
3205

    
3206
        for field in self.op.output_fields:
3207
          if field == constants.SF_NODE:
3208
            val = node
3209
          elif field == constants.SF_TYPE:
3210
            val = self.op.storage_type
3211
          elif field in field_idx:
3212
            val = row[field_idx[field]]
3213
          else:
3214
            raise errors.ParameterError(field)
3215

    
3216
          out.append(val)
3217

    
3218
        result.append(out)
3219

    
3220
    return result
3221

    
3222

    
3223
class LUModifyNodeStorage(NoHooksLU):
3224
  """Logical unit for modifying a storage volume on a node.
3225

3226
  """
3227
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
3228
  REQ_BGL = False
3229

    
3230
  def CheckArguments(self):
3231
    self.opnode_name = _ExpandNodeName(self.cfg, self.op.node_name)
3232

    
3233
    _CheckStorageType(self.op.storage_type)
3234

    
3235
  def ExpandNames(self):
3236
    self.needed_locks = {
3237
      locking.LEVEL_NODE: self.op.node_name,
3238
      }
3239

    
3240
  def CheckPrereq(self):
3241
    """Check prerequisites.
3242

3243
    """
3244
    storage_type = self.op.storage_type
3245

    
3246
    try:
3247
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3248
    except KeyError:
3249
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3250
                                 " modified" % storage_type,
3251
                                 errors.ECODE_INVAL)
3252

    
3253
    diff = set(self.op.changes.keys()) - modifiable
3254
    if diff:
3255
      raise errors.OpPrereqError("The following fields can not be modified for"
3256
                                 " storage units of type '%s': %r" %
3257
                                 (storage_type, list(diff)),
3258
                                 errors.ECODE_INVAL)
3259

    
3260
  def Exec(self, feedback_fn):
3261
    """Computes the list of nodes and their attributes.
3262

3263
    """
3264
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3265
    result = self.rpc.call_storage_modify(self.op.node_name,
3266
                                          self.op.storage_type, st_args,
3267
                                          self.op.name, self.op.changes)
3268
    result.Raise("Failed to modify storage unit '%s' on %s" %
3269
                 (self.op.name, self.op.node_name))
3270

    
3271

    
3272
class LUAddNode(LogicalUnit):
3273
  """Logical unit for adding node to the cluster.
3274

3275
  """
3276
  HPATH = "node-add"
3277
  HTYPE = constants.HTYPE_NODE
3278
  _OP_REQP = ["node_name"]
3279

    
3280
  def CheckArguments(self):
3281
    # validate/normalize the node name
3282
    self.op.node_name = utils.HostInfo.NormalizeName(self.op.node_name)
3283

    
3284
  def BuildHooksEnv(self):
3285
    """Build hooks env.
3286

3287
    This will run on all nodes before, and on all nodes + the new node after.
3288

3289
    """
3290
    env = {
3291
      "OP_TARGET": self.op.node_name,
3292
      "NODE_NAME": self.op.node_name,
3293
      "NODE_PIP": self.op.primary_ip,
3294
      "NODE_SIP": self.op.secondary_ip,
3295
      }
3296
    nodes_0 = self.cfg.GetNodeList()
3297
    nodes_1 = nodes_0 + [self.op.node_name, ]
3298
    return env, nodes_0, nodes_1
3299

    
3300
  def CheckPrereq(self):
3301
    """Check prerequisites.
3302

3303
    This checks:
3304
     - the new node is not already in the config
3305
     - it is resolvable
3306
     - its parameters (single/dual homed) matches the cluster
3307

3308
    Any errors are signaled by raising errors.OpPrereqError.
3309

3310
    """
3311
    node_name = self.op.node_name
3312
    cfg = self.cfg
3313

    
3314
    dns_data = utils.GetHostInfo(node_name)
3315

    
3316
    node = dns_data.name
3317
    primary_ip = self.op.primary_ip = dns_data.ip
3318
    secondary_ip = getattr(self.op, "secondary_ip", None)
3319
    if secondary_ip is None:
3320
      secondary_ip = primary_ip
3321
    if not utils.IsValidIP(secondary_ip):
3322
      raise errors.OpPrereqError("Invalid secondary IP given",
3323
                                 errors.ECODE_INVAL)
3324
    self.op.secondary_ip = secondary_ip
3325

    
3326
    node_list = cfg.GetNodeList()
3327
    if not self.op.readd and node in node_list:
3328
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3329
                                 node, errors.ECODE_EXISTS)
3330
    elif self.op.readd and node not in node_list:
3331
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3332
                                 errors.ECODE_NOENT)
3333

    
3334
    self.changed_primary_ip = False
3335

    
3336
    for existing_node_name in node_list:
3337
      existing_node = cfg.GetNodeInfo(existing_node_name)
3338

    
3339
      if self.op.readd and node == existing_node_name:
3340
        if existing_node.secondary_ip != secondary_ip:
3341
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3342
                                     " address configuration as before",
3343
                                     errors.ECODE_INVAL)
3344
        if existing_node.primary_ip != primary_ip:
3345
          self.changed_primary_ip = True
3346

    
3347
        continue
3348

    
3349
      if (existing_node.primary_ip == primary_ip or
3350
          existing_node.secondary_ip == primary_ip or
3351
          existing_node.primary_ip == secondary_ip or
3352
          existing_node.secondary_ip == secondary_ip):
3353
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3354
                                   " existing node %s" % existing_node.name,
3355
                                   errors.ECODE_NOTUNIQUE)
3356

    
3357
    # check that the type of the node (single versus dual homed) is the
3358
    # same as for the master
3359
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3360
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3361
    newbie_singlehomed = secondary_ip == primary_ip
3362
    if master_singlehomed != newbie_singlehomed:
3363
      if master_singlehomed:
3364
        raise errors.OpPrereqError("The master has no private ip but the"
3365
                                   " new node has one",
3366
                                   errors.ECODE_INVAL)
3367
      else:
3368
        raise errors.OpPrereqError("The master has a private ip but the"
3369
                                   " new node doesn't have one",
3370
                                   errors.ECODE_INVAL)
3371

    
3372
    # checks reachability
3373
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3374
      raise errors.OpPrereqError("Node not reachable by ping",
3375
                                 errors.ECODE_ENVIRON)
3376

    
3377
    if not newbie_singlehomed:
3378
      # check reachability from my secondary ip to newbie's secondary ip
3379
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3380
                           source=myself.secondary_ip):
3381
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3382
                                   " based ping to noded port",
3383
                                   errors.ECODE_ENVIRON)
3384

    
3385
    if self.op.readd:
3386
      exceptions = [node]
3387
    else:
3388
      exceptions = []
3389

    
3390
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3391

    
3392
    if self.op.readd:
3393
      self.new_node = self.cfg.GetNodeInfo(node)
3394
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3395
    else:
3396
      self.new_node = objects.Node(name=node,
3397
                                   primary_ip=primary_ip,
3398
                                   secondary_ip=secondary_ip,
3399
                                   master_candidate=self.master_candidate,
3400
                                   offline=False, drained=False)
3401

    
3402
  def Exec(self, feedback_fn):
3403
    """Adds the new node to the cluster.
3404

3405
    """
3406
    new_node = self.new_node
3407
    node = new_node.name
3408

    
3409
    # for re-adds, reset the offline/drained/master-candidate flags;
3410
    # we need to reset here, otherwise offline would prevent RPC calls
3411
    # later in the procedure; this also means that if the re-add
3412
    # fails, we are left with a non-offlined, broken node
3413
    if self.op.readd:
3414
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3415
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3416
      # if we demote the node, we do cleanup later in the procedure
3417
      new_node.master_candidate = self.master_candidate
3418
      if self.changed_primary_ip:
3419
        new_node.primary_ip = self.op.primary_ip
3420

    
3421
    # notify the user about any possible mc promotion
3422
    if new_node.master_candidate:
3423
      self.LogInfo("Node will be a master candidate")
3424

    
3425
    # check connectivity
3426
    result = self.rpc.call_version([node])[node]
3427
    result.Raise("Can't get version information from node %s" % node)
3428
    if constants.PROTOCOL_VERSION == result.payload:
3429
      logging.info("Communication to node %s fine, sw version %s match",
3430
                   node, result.payload)
3431
    else:
3432
      raise errors.OpExecError("Version mismatch master version %s,"
3433
                               " node version %s" %
3434
                               (constants.PROTOCOL_VERSION, result.payload))
3435

    
3436
    # setup ssh on node
3437
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3438
      logging.info("Copy ssh key to node %s", node)
3439
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3440
      keyarray = []
3441
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3442
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3443
                  priv_key, pub_key]
3444

    
3445
      for i in keyfiles:
3446
        keyarray.append(utils.ReadFile(i))
3447

    
3448
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3449
                                      keyarray[2], keyarray[3], keyarray[4],
3450
                                      keyarray[5])
3451
      result.Raise("Cannot transfer ssh keys to the new node")
3452

    
3453
    # Add node to our /etc/hosts, and add key to known_hosts
3454
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3455
      # FIXME: this should be done via an rpc call to node daemon
3456
      utils.AddHostToEtcHosts(new_node.name)
3457

    
3458
    if new_node.secondary_ip != new_node.primary_ip:
3459
      result = self.rpc.call_node_has_ip_address(new_node.name,
3460
                                                 new_node.secondary_ip)
3461
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3462
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3463
      if not result.payload:
3464
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3465
                                 " you gave (%s). Please fix and re-run this"
3466
                                 " command." % new_node.secondary_ip)
3467

    
3468
    node_verify_list = [self.cfg.GetMasterNode()]
3469
    node_verify_param = {
3470
      constants.NV_NODELIST: [node],
3471
      # TODO: do a node-net-test as well?
3472
    }
3473

    
3474
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3475
                                       self.cfg.GetClusterName())
3476
    for verifier in node_verify_list:
3477
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3478
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3479
      if nl_payload:
3480
        for failed in nl_payload:
3481
          feedback_fn("ssh/hostname verification failed"
3482
                      " (checking from %s): %s" %
3483
                      (verifier, nl_payload[failed]))
3484
        raise errors.OpExecError("ssh/hostname verification failed.")
3485

    
3486
    if self.op.readd:
3487
      _RedistributeAncillaryFiles(self)
3488
      self.context.ReaddNode(new_node)
3489
      # make sure we redistribute the config
3490
      self.cfg.Update(new_node, feedback_fn)
3491
      # and make sure the new node will not have old files around
3492
      if not new_node.master_candidate:
3493
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3494
        msg = result.fail_msg
3495
        if msg:
3496
          self.LogWarning("Node failed to demote itself from master"
3497
                          " candidate status: %s" % msg)
3498
    else:
3499
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3500
      self.context.AddNode(new_node, self.proc.GetECId())
3501

    
3502

    
3503
class LUSetNodeParams(LogicalUnit):
3504
  """Modifies the parameters of a node.
3505

3506
  """
3507
  HPATH = "node-modify"
3508
  HTYPE = constants.HTYPE_NODE
3509
  _OP_REQP = ["node_name"]
3510
  REQ_BGL = False
3511

    
3512
  def CheckArguments(self):
3513
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3514
    _CheckBooleanOpField(self.op, 'master_candidate')
3515
    _CheckBooleanOpField(self.op, 'offline')
3516
    _CheckBooleanOpField(self.op, 'drained')
3517
    _CheckBooleanOpField(self.op, 'auto_promote')
3518
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3519
    if all_mods.count(None) == 3:
3520
      raise errors.OpPrereqError("Please pass at least one modification",
3521
                                 errors.ECODE_INVAL)
3522
    if all_mods.count(True) > 1:
3523
      raise errors.OpPrereqError("Can't set the node into more than one"
3524
                                 " state at the same time",
3525
                                 errors.ECODE_INVAL)
3526

    
3527
    # Boolean value that tells us whether we're offlining or draining the node
3528
    self.offline_or_drain = (self.op.offline == True or
3529
                             self.op.drained == True)
3530
    self.deoffline_or_drain = (self.op.offline == False or
3531
                               self.op.drained == False)
3532
    self.might_demote = (self.op.master_candidate == False or
3533
                         self.offline_or_drain)
3534

    
3535
    self.lock_all = self.op.auto_promote and self.might_demote
3536

    
3537

    
3538
  def ExpandNames(self):
3539
    if self.lock_all:
3540
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3541
    else:
3542
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3543

    
3544
  def BuildHooksEnv(self):
3545
    """Build hooks env.
3546

3547
    This runs on the master node.
3548

3549
    """
3550
    env = {
3551
      "OP_TARGET": self.op.node_name,
3552
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3553
      "OFFLINE": str(self.op.offline),
3554
      "DRAINED": str(self.op.drained),
3555
      }
3556
    nl = [self.cfg.GetMasterNode(),
3557
          self.op.node_name]
3558
    return env, nl, nl
3559

    
3560
  def CheckPrereq(self):
3561
    """Check prerequisites.
3562

3563
    This only checks the instance list against the existing names.
3564

3565
    """
3566
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3567

    
3568
    if (self.op.master_candidate is not None or
3569
        self.op.drained is not None or
3570
        self.op.offline is not None):
3571
      # we can't change the master's node flags
3572
      if self.op.node_name == self.cfg.GetMasterNode():
3573
        raise errors.OpPrereqError("The master role can be changed"
3574
                                   " only via masterfailover",
3575
                                   errors.ECODE_INVAL)
3576

    
3577

    
3578
    if node.master_candidate and self.might_demote and not self.lock_all:
3579
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3580
      # check if after removing the current node, we're missing master
3581
      # candidates
3582
      (mc_remaining, mc_should, _) = \
3583
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3584
      if mc_remaining < mc_should:
3585
        raise errors.OpPrereqError("Not enough master candidates, please"
3586
                                   " pass auto_promote to allow promotion",
3587
                                   errors.ECODE_INVAL)
3588

    
3589
    if (self.op.master_candidate == True and
3590
        ((node.offline and not self.op.offline == False) or
3591
         (node.drained and not self.op.drained == False))):
3592
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3593
                                 " to master_candidate" % node.name,
3594
                                 errors.ECODE_INVAL)
3595

    
3596
    # If we're being deofflined/drained, we'll MC ourself if needed
3597
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3598
        self.op.master_candidate == True and not node.master_candidate):
3599
      self.op.master_candidate = _DecideSelfPromotion(self)
3600
      if self.op.master_candidate:
3601
        self.LogInfo("Autopromoting node to master candidate")
3602

    
3603
    return
3604

    
3605
  def Exec(self, feedback_fn):
3606
    """Modifies a node.
3607

3608
    """
3609
    node = self.node
3610

    
3611
    result = []
3612
    changed_mc = False
3613

    
3614
    if self.op.offline is not None:
3615
      node.offline = self.op.offline
3616
      result.append(("offline", str(self.op.offline)))
3617
      if self.op.offline == True:
3618
        if node.master_candidate:
3619
          node.master_candidate = False
3620
          changed_mc = True
3621
          result.append(("master_candidate", "auto-demotion due to offline"))
3622
        if node.drained:
3623
          node.drained = False
3624
          result.append(("drained", "clear drained status due to offline"))
3625

    
3626
    if self.op.master_candidate is not None:
3627
      node.master_candidate = self.op.master_candidate
3628
      changed_mc = True
3629
      result.append(("master_candidate", str(self.op.master_candidate)))
3630
      if self.op.master_candidate == False:
3631
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3632
        msg = rrc.fail_msg
3633
        if msg:
3634
          self.LogWarning("Node failed to demote itself: %s" % msg)
3635

    
3636
    if self.op.drained is not None:
3637
      node.drained = self.op.drained
3638
      result.append(("drained", str(self.op.drained)))
3639
      if self.op.drained == True:
3640
        if node.master_candidate:
3641
          node.master_candidate = False
3642
          changed_mc = True
3643
          result.append(("master_candidate", "auto-demotion due to drain"))
3644
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3645
          msg = rrc.fail_msg
3646
          if msg:
3647
            self.LogWarning("Node failed to demote itself: %s" % msg)
3648
        if node.offline:
3649
          node.offline = False
3650
          result.append(("offline", "clear offline status due to drain"))
3651

    
3652
    # we locked all nodes, we adjust the CP before updating this node
3653
    if self.lock_all:
3654
      _AdjustCandidatePool(self, [node.name])
3655

    
3656
    # this will trigger configuration file update, if needed
3657
    self.cfg.Update(node, feedback_fn)
3658

    
3659
    # this will trigger job queue propagation or cleanup
3660
    if changed_mc:
3661
      self.context.ReaddNode(node)
3662

    
3663
    return result
3664

    
3665

    
3666
class LUPowercycleNode(NoHooksLU):
3667
  """Powercycles a node.
3668

3669
  """
3670
  _OP_REQP = ["node_name", "force"]
3671
  REQ_BGL = False
3672

    
3673
  def CheckArguments(self):
3674
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3675
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
3676
      raise errors.OpPrereqError("The node is the master and the force"
3677
                                 " parameter was not set",
3678
                                 errors.ECODE_INVAL)
3679

    
3680
  def ExpandNames(self):
3681
    """Locking for PowercycleNode.
3682

3683
    This is a last-resort option and shouldn't block on other
3684
    jobs. Therefore, we grab no locks.
3685

3686
    """
3687
    self.needed_locks = {}
3688

    
3689
  def CheckPrereq(self):
3690
    """Check prerequisites.
3691

3692
    This LU has no prereqs.
3693

3694
    """
3695
    pass
3696

    
3697
  def Exec(self, feedback_fn):
3698
    """Reboots a node.
3699

3700
    """
3701
    result = self.rpc.call_node_powercycle(self.op.node_name,
3702
                                           self.cfg.GetHypervisorType())
3703
    result.Raise("Failed to schedule the reboot")
3704
    return result.payload
3705

    
3706

    
3707
class LUQueryClusterInfo(NoHooksLU):
3708
  """Query cluster configuration.
3709

3710
  """
3711
  _OP_REQP = []
3712
  REQ_BGL = False
3713

    
3714
  def ExpandNames(self):
3715
    self.needed_locks = {}
3716

    
3717
  def CheckPrereq(self):
3718
    """No prerequsites needed for this LU.
3719

3720
    """
3721
    pass
3722

    
3723
  def Exec(self, feedback_fn):
3724
    """Return cluster config.
3725

3726
    """
3727
    cluster = self.cfg.GetClusterInfo()
3728
    os_hvp = {}
3729

    
3730
    # Filter just for enabled hypervisors
3731
    for os_name, hv_dict in cluster.os_hvp.items():
3732
      os_hvp[os_name] = {}
3733
      for hv_name, hv_params in hv_dict.items():
3734
        if hv_name in cluster.enabled_hypervisors:
3735
          os_hvp[os_name][hv_name] = hv_params
3736

    
3737
    result = {
3738
      "software_version": constants.RELEASE_VERSION,
3739
      "protocol_version": constants.PROTOCOL_VERSION,
3740
      "config_version": constants.CONFIG_VERSION,
3741
      "os_api_version": max(constants.OS_API_VERSIONS),
3742
      "export_version": constants.EXPORT_VERSION,
3743
      "architecture": (platform.architecture()[0], platform.machine()),
3744
      "name": cluster.cluster_name,
3745
      "master": cluster.master_node,
3746
      "default_hypervisor": cluster.enabled_hypervisors[0],
3747
      "enabled_hypervisors": cluster.enabled_hypervisors,
3748
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3749
                        for hypervisor_name in cluster.enabled_hypervisors]),
3750
      "os_hvp": os_hvp,
3751
      "beparams": cluster.beparams,
3752
      "nicparams": cluster.nicparams,
3753
      "candidate_pool_size": cluster.candidate_pool_size,
3754
      "master_netdev": cluster.master_netdev,
3755
      "volume_group_name": cluster.volume_group_name,
3756
      "file_storage_dir": cluster.file_storage_dir,
3757
      "maintain_node_health": cluster.maintain_node_health,
3758
      "ctime": cluster.ctime,
3759
      "mtime": cluster.mtime,
3760
      "uuid": cluster.uuid,
3761
      "tags": list(cluster.GetTags()),
3762
      "uid_pool": cluster.uid_pool,
3763
      }
3764

    
3765
    return result
3766

    
3767

    
3768
class LUQueryConfigValues(NoHooksLU):
3769
  """Return configuration values.
3770

3771
  """
3772
  _OP_REQP = []
3773
  REQ_BGL = False
3774
  _FIELDS_DYNAMIC = utils.FieldSet()
3775
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3776
                                  "watcher_pause")
3777

    
3778
  def ExpandNames(self):
3779
    self.needed_locks = {}
3780

    
3781
    _CheckOutputFields(static=self._FIELDS_STATIC,
3782
                       dynamic=self._FIELDS_DYNAMIC,
3783
                       selected=self.op.output_fields)
3784

    
3785
  def CheckPrereq(self):
3786
    """No prerequisites.
3787

3788
    """
3789
    pass
3790

    
3791
  def Exec(self, feedback_fn):
3792
    """Dump a representation of the cluster config to the standard output.
3793

3794
    """
3795
    values = []
3796
    for field in self.op.output_fields:
3797
      if field == "cluster_name":
3798
        entry = self.cfg.GetClusterName()
3799
      elif field == "master_node":
3800
        entry = self.cfg.GetMasterNode()
3801
      elif field == "drain_flag":
3802
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3803
      elif field == "watcher_pause":
3804
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3805
      else:
3806
        raise errors.ParameterError(field)
3807
      values.append(entry)
3808
    return values
3809

    
3810

    
3811
class LUActivateInstanceDisks(NoHooksLU):
3812
  """Bring up an instance's disks.
3813

3814
  """
3815
  _OP_REQP = ["instance_name"]
3816
  REQ_BGL = False
3817

    
3818
  def ExpandNames(self):
3819
    self._ExpandAndLockInstance()
3820
    self.needed_locks[locking.LEVEL_NODE] = []
3821
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3822

    
3823
  def DeclareLocks(self, level):
3824
    if level == locking.LEVEL_NODE:
3825
      self._LockInstancesNodes()
3826

    
3827
  def CheckPrereq(self):
3828
    """Check prerequisites.
3829

3830
    This checks that the instance is in the cluster.
3831

3832
    """
3833
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3834
    assert self.instance is not None, \
3835
      "Cannot retrieve locked instance %s" % self.op.instance_name
3836
    _CheckNodeOnline(self, self.instance.primary_node)
3837
    if not hasattr(self.op, "ignore_size"):
3838
      self.op.ignore_size = False
3839

    
3840
  def Exec(self, feedback_fn):
3841
    """Activate the disks.
3842

3843
    """
3844
    disks_ok, disks_info = \
3845
              _AssembleInstanceDisks(self, self.instance,
3846
                                     ignore_size=self.op.ignore_size)
3847
    if not disks_ok:
3848
      raise errors.OpExecError("Cannot activate block devices")
3849

    
3850
    return disks_info
3851

    
3852

    
3853
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
3854
                           ignore_size=False):
3855
  """Prepare the block devices for an instance.
3856

3857
  This sets up the block devices on all nodes.
3858

3859
  @type lu: L{LogicalUnit}
3860
  @param lu: the logical unit on whose behalf we execute
3861
  @type instance: L{objects.Instance}
3862
  @param instance: the instance for whose disks we assemble
3863
  @type disks: list of L{objects.Disk} or None
3864
  @param disks: which disks to assemble (or all, if None)
3865
  @type ignore_secondaries: boolean
3866
  @param ignore_secondaries: if true, errors on secondary nodes
3867
      won't result in an error return from the function
3868
  @type ignore_size: boolean
3869
  @param ignore_size: if true, the current known size of the disk
3870
      will not be used during the disk activation, useful for cases
3871
      when the size is wrong
3872
  @return: False if the operation failed, otherwise a list of
3873
      (host, instance_visible_name, node_visible_name)
3874
      with the mapping from node devices to instance devices
3875

3876
  """
3877
  device_info = []
3878
  disks_ok = True
3879
  iname = instance.name
3880
  disks = _ExpandCheckDisks(instance, disks)
3881

    
3882
  # With the two passes mechanism we try to reduce the window of
3883
  # opportunity for the race condition of switching DRBD to primary
3884
  # before handshaking occured, but we do not eliminate it
3885

    
3886
  # The proper fix would be to wait (with some limits) until the
3887
  # connection has been made and drbd transitions from WFConnection
3888
  # into any other network-connected state (Connected, SyncTarget,
3889
  # SyncSource, etc.)
3890

    
3891
  # 1st pass, assemble on all nodes in secondary mode
3892
  for inst_disk in disks:
3893
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3894
      if ignore_size:
3895
        node_disk = node_disk.Copy()
3896
        node_disk.UnsetSize()
3897
      lu.cfg.SetDiskID(node_disk, node)
3898
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3899
      msg = result.fail_msg
3900
      if msg:
3901
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3902
                           " (is_primary=False, pass=1): %s",
3903
                           inst_disk.iv_name, node, msg)
3904
        if not ignore_secondaries:
3905
          disks_ok = False
3906

    
3907
  # FIXME: race condition on drbd migration to primary
3908

    
3909
  # 2nd pass, do only the primary node
3910
  for inst_disk in disks:
3911
    dev_path = None
3912

    
3913
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3914
      if node != instance.primary_node:
3915
        continue
3916
      if ignore_size:
3917
        node_disk = node_disk.Copy()
3918
        node_disk.UnsetSize()
3919
      lu.cfg.SetDiskID(node_disk, node)
3920
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3921
      msg = result.fail_msg
3922
      if msg:
3923
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3924
                           " (is_primary=True, pass=2): %s",
3925
                           inst_disk.iv_name, node, msg)
3926
        disks_ok = False
3927
      else:
3928
        dev_path = result.payload
3929

    
3930
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3931

    
3932
  # leave the disks configured for the primary node
3933
  # this is a workaround that would be fixed better by
3934
  # improving the logical/physical id handling
3935
  for disk in disks:
3936
    lu.cfg.SetDiskID(disk, instance.primary_node)
3937

    
3938
  return disks_ok, device_info
3939

    
3940

    
3941
def _StartInstanceDisks(lu, instance, force):
3942
  """Start the disks of an instance.
3943

3944
  """
3945
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3946
                                           ignore_secondaries=force)
3947
  if not disks_ok:
3948
    _ShutdownInstanceDisks(lu, instance)
3949
    if force is not None and not force:
3950
      lu.proc.LogWarning("", hint="If the message above refers to a"
3951
                         " secondary node,"
3952
                         " you can retry the operation using '--force'.")
3953
    raise errors.OpExecError("Disk consistency error")
3954

    
3955

    
3956
class LUDeactivateInstanceDisks(NoHooksLU):
3957
  """Shutdown an instance's disks.
3958

3959
  """
3960
  _OP_REQP = ["instance_name"]
3961
  REQ_BGL = False
3962

    
3963
  def ExpandNames(self):
3964
    self._ExpandAndLockInstance()
3965
    self.needed_locks[locking.LEVEL_NODE] = []
3966
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3967

    
3968
  def DeclareLocks(self, level):
3969
    if level == locking.LEVEL_NODE:
3970
      self._LockInstancesNodes()
3971

    
3972
  def CheckPrereq(self):
3973
    """Check prerequisites.
3974

3975
    This checks that the instance is in the cluster.
3976

3977
    """
3978
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3979
    assert self.instance is not None, \
3980
      "Cannot retrieve locked instance %s" % self.op.instance_name
3981

    
3982
  def Exec(self, feedback_fn):
3983
    """Deactivate the disks
3984

3985
    """
3986
    instance = self.instance
3987
    _SafeShutdownInstanceDisks(self, instance)
3988

    
3989

    
3990
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
3991
  """Shutdown block devices of an instance.
3992

3993
  This function checks if an instance is running, before calling
3994
  _ShutdownInstanceDisks.
3995

3996
  """
3997
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
3998
  _ShutdownInstanceDisks(lu, instance, disks=disks)
3999

    
4000

    
4001
def _ExpandCheckDisks(instance, disks):
4002
  """Return the instance disks selected by the disks list
4003

4004
  @type disks: list of L{objects.Disk} or None
4005
  @param disks: selected disks
4006
  @rtype: list of L{objects.Disk}
4007
  @return: selected instance disks to act on
4008

4009
  """
4010
  if disks is None:
4011
    return instance.disks
4012
  else:
4013
    if not set(disks).issubset(instance.disks):
4014
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4015
                                   " target instance")
4016
    return disks
4017

    
4018

    
4019
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4020
  """Shutdown block devices of an instance.
4021

4022
  This does the shutdown on all nodes of the instance.
4023

4024
  If the ignore_primary is false, errors on the primary node are
4025
  ignored.
4026

4027
  """
4028
  all_result = True
4029
  disks = _ExpandCheckDisks(instance, disks)
4030

    
4031
  for disk in disks:
4032
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4033
      lu.cfg.SetDiskID(top_disk, node)
4034
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4035
      msg = result.fail_msg
4036
      if msg:
4037
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4038
                      disk.iv_name, node, msg)
4039
        if not ignore_primary or node != instance.primary_node:
4040
          all_result = False
4041
  return all_result
4042

    
4043

    
4044
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4045
  """Checks if a node has enough free memory.
4046

4047
  This function check if a given node has the needed amount of free
4048
  memory. In case the node has less memory or we cannot get the
4049
  information from the node, this function raise an OpPrereqError
4050
  exception.
4051

4052
  @type lu: C{LogicalUnit}
4053
  @param lu: a logical unit from which we get configuration data
4054
  @type node: C{str}
4055
  @param node: the node to check
4056
  @type reason: C{str}
4057
  @param reason: string to use in the error message
4058
  @type requested: C{int}
4059
  @param requested: the amount of memory in MiB to check for
4060
  @type hypervisor_name: C{str}
4061
  @param hypervisor_name: the hypervisor to ask for memory stats
4062
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4063
      we cannot check the node
4064

4065
  """
4066
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4067
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4068
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4069
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4070
  if not isinstance(free_mem, int):
4071
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4072
                               " was '%s'" % (node, free_mem),
4073
                               errors.ECODE_ENVIRON)
4074
  if requested > free_mem:
4075
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4076
                               " needed %s MiB, available %s MiB" %
4077
                               (node, reason, requested, free_mem),
4078
                               errors.ECODE_NORES)
4079

    
4080

    
4081
def _CheckNodesFreeDisk(lu, nodenames, requested):
4082
  """Checks if nodes have enough free disk space in the default VG.
4083

4084
  This function check if all given nodes have the needed amount of
4085
  free disk. In case any node has less disk or we cannot get the
4086
  information from the node, this function raise an OpPrereqError
4087
  exception.
4088

4089
  @type lu: C{LogicalUnit}
4090
  @param lu: a logical unit from which we get configuration data
4091
  @type nodenames: C{list}
4092
  @param nodenames: the list of node names to check
4093
  @type requested: C{int}
4094
  @param requested: the amount of disk in MiB to check for
4095
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4096
      we cannot check the node
4097

4098
  """
4099
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4100
                                   lu.cfg.GetHypervisorType())
4101
  for node in nodenames:
4102
    info = nodeinfo[node]
4103
    info.Raise("Cannot get current information from node %s" % node,
4104
               prereq=True, ecode=errors.ECODE_ENVIRON)
4105
    vg_free = info.payload.get("vg_free", None)
4106
    if not isinstance(vg_free, int):
4107
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4108
                                 " result was '%s'" % (node, vg_free),
4109
                                 errors.ECODE_ENVIRON)
4110
    if requested > vg_free:
4111
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4112
                                 " required %d MiB, available %d MiB" %
4113
                                 (node, requested, vg_free),
4114
                                 errors.ECODE_NORES)
4115

    
4116

    
4117
class LUStartupInstance(LogicalUnit):
4118
  """Starts an instance.
4119

4120
  """
4121
  HPATH = "instance-start"
4122
  HTYPE = constants.HTYPE_INSTANCE
4123
  _OP_REQP = ["instance_name", "force"]
4124
  REQ_BGL = False
4125

    
4126
  def ExpandNames(self):
4127
    self._ExpandAndLockInstance()
4128

    
4129
  def BuildHooksEnv(self):
4130
    """Build hooks env.
4131

4132
    This runs on master, primary and secondary nodes of the instance.
4133

4134
    """
4135
    env = {
4136
      "FORCE": self.op.force,
4137
      }
4138
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4139
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4140
    return env, nl, nl
4141

    
4142
  def CheckPrereq(self):
4143
    """Check prerequisites.
4144

4145
    This checks that the instance is in the cluster.
4146

4147
    """
4148
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4149
    assert self.instance is not None, \
4150
      "Cannot retrieve locked instance %s" % self.op.instance_name
4151

    
4152
    # extra beparams
4153
    self.beparams = getattr(self.op, "beparams", {})
4154
    if self.beparams:
4155
      if not isinstance(self.beparams, dict):
4156
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
4157
                                   " dict" % (type(self.beparams), ),
4158
                                   errors.ECODE_INVAL)
4159
      # fill the beparams dict
4160
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
4161
      self.op.beparams = self.beparams
4162

    
4163
    # extra hvparams
4164
    self.hvparams = getattr(self.op, "hvparams", {})
4165
    if self.hvparams:
4166
      if not isinstance(self.hvparams, dict):
4167
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
4168
                                   " dict" % (type(self.hvparams), ),
4169
                                   errors.ECODE_INVAL)
4170

    
4171
      # check hypervisor parameter syntax (locally)
4172
      cluster = self.cfg.GetClusterInfo()
4173
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
4174
      filled_hvp = cluster.FillHV(instance)
4175
      filled_hvp.update(self.hvparams)
4176
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4177
      hv_type.CheckParameterSyntax(filled_hvp)
4178
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4179
      self.op.hvparams = self.hvparams
4180

    
4181
    _CheckNodeOnline(self, instance.primary_node)
4182

    
4183
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4184
    # check bridges existence
4185
    _CheckInstanceBridgesExist(self, instance)
4186

    
4187
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4188
                                              instance.name,
4189
                                              instance.hypervisor)
4190
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4191
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4192
    if not remote_info.payload: # not running already
4193
      _CheckNodeFreeMemory(self, instance.primary_node,
4194
                           "starting instance %s" % instance.name,
4195
                           bep[constants.BE_MEMORY], instance.hypervisor)
4196

    
4197
  def Exec(self, feedback_fn):
4198
    """Start the instance.
4199

4200
    """
4201
    instance = self.instance
4202
    force = self.op.force
4203

    
4204
    self.cfg.MarkInstanceUp(instance.name)
4205

    
4206
    node_current = instance.primary_node
4207

    
4208
    _StartInstanceDisks(self, instance, force)
4209

    
4210
    result = self.rpc.call_instance_start(node_current, instance,
4211
                                          self.hvparams, self.beparams)
4212
    msg = result.fail_msg
4213
    if msg:
4214
      _ShutdownInstanceDisks(self, instance)
4215
      raise errors.OpExecError("Could not start instance: %s" % msg)
4216

    
4217

    
4218
class LURebootInstance(LogicalUnit):
4219
  """Reboot an instance.
4220

4221
  """
4222
  HPATH = "instance-reboot"
4223
  HTYPE = constants.HTYPE_INSTANCE
4224
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
4225
  REQ_BGL = False
4226

    
4227
  def CheckArguments(self):
4228
    """Check the arguments.
4229

4230
    """
4231
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4232
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4233

    
4234
  def ExpandNames(self):
4235
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
4236
                                   constants.INSTANCE_REBOOT_HARD,
4237
                                   constants.INSTANCE_REBOOT_FULL]:
4238
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
4239
                                  (constants.INSTANCE_REBOOT_SOFT,
4240
                                   constants.INSTANCE_REBOOT_HARD,
4241
                                   constants.INSTANCE_REBOOT_FULL))
4242
    self._ExpandAndLockInstance()
4243

    
4244
  def BuildHooksEnv(self):
4245
    """Build hooks env.
4246

4247
    This runs on master, primary and secondary nodes of the instance.
4248

4249
    """
4250
    env = {
4251
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4252
      "REBOOT_TYPE": self.op.reboot_type,
4253
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4254
      }
4255
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4256
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4257
    return env, nl, nl
4258

    
4259
  def CheckPrereq(self):
4260
    """Check prerequisites.
4261

4262
    This checks that the instance is in the cluster.
4263

4264
    """
4265
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4266
    assert self.instance is not None, \
4267
      "Cannot retrieve locked instance %s" % self.op.instance_name
4268

    
4269
    _CheckNodeOnline(self, instance.primary_node)
4270

    
4271
    # check bridges existence
4272
    _CheckInstanceBridgesExist(self, instance)
4273

    
4274
  def Exec(self, feedback_fn):
4275
    """Reboot the instance.
4276

4277
    """
4278
    instance = self.instance
4279
    ignore_secondaries = self.op.ignore_secondaries
4280
    reboot_type = self.op.reboot_type
4281

    
4282
    node_current = instance.primary_node
4283

    
4284
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4285
                       constants.INSTANCE_REBOOT_HARD]:
4286
      for disk in instance.disks:
4287
        self.cfg.SetDiskID(disk, node_current)
4288
      result = self.rpc.call_instance_reboot(node_current, instance,
4289
                                             reboot_type,
4290
                                             self.shutdown_timeout)
4291
      result.Raise("Could not reboot instance")
4292
    else:
4293
      result = self.rpc.call_instance_shutdown(node_current, instance,
4294
                                               self.shutdown_timeout)
4295
      result.Raise("Could not shutdown instance for full reboot")
4296
      _ShutdownInstanceDisks(self, instance)
4297
      _StartInstanceDisks(self, instance, ignore_secondaries)
4298
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4299
      msg = result.fail_msg
4300
      if msg:
4301
        _ShutdownInstanceDisks(self, instance)
4302
        raise errors.OpExecError("Could not start instance for"
4303
                                 " full reboot: %s" % msg)
4304

    
4305
    self.cfg.MarkInstanceUp(instance.name)
4306

    
4307

    
4308
class LUShutdownInstance(LogicalUnit):
4309
  """Shutdown an instance.
4310

4311
  """
4312
  HPATH = "instance-stop"
4313
  HTYPE = constants.HTYPE_INSTANCE
4314
  _OP_REQP = ["instance_name"]
4315
  REQ_BGL = False
4316

    
4317
  def CheckArguments(self):
4318
    """Check the arguments.
4319

4320
    """
4321
    self.timeout = getattr(self.op, "timeout",
4322
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
4323

    
4324
  def ExpandNames(self):
4325
    self._ExpandAndLockInstance()
4326

    
4327
  def BuildHooksEnv(self):
4328
    """Build hooks env.
4329

4330
    This runs on master, primary and secondary nodes of the instance.
4331

4332
    """
4333
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4334
    env["TIMEOUT"] = self.timeout
4335
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4336
    return env, nl, nl
4337

    
4338
  def CheckPrereq(self):
4339
    """Check prerequisites.
4340

4341
    This checks that the instance is in the cluster.
4342

4343
    """
4344
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4345
    assert self.instance is not None, \
4346
      "Cannot retrieve locked instance %s" % self.op.instance_name
4347
    _CheckNodeOnline(self, self.instance.primary_node)
4348

    
4349
  def Exec(self, feedback_fn):
4350
    """Shutdown the instance.
4351

4352
    """
4353
    instance = self.instance
4354
    node_current = instance.primary_node
4355
    timeout = self.timeout
4356
    self.cfg.MarkInstanceDown(instance.name)
4357
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4358
    msg = result.fail_msg
4359
    if msg:
4360
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4361

    
4362
    _ShutdownInstanceDisks(self, instance)
4363

    
4364

    
4365
class LUReinstallInstance(LogicalUnit):
4366
  """Reinstall an instance.
4367

4368
  """
4369
  HPATH = "instance-reinstall"
4370
  HTYPE = constants.HTYPE_INSTANCE
4371
  _OP_REQP = ["instance_name"]
4372
  REQ_BGL = False
4373

    
4374
  def ExpandNames(self):
4375
    self._ExpandAndLockInstance()
4376

    
4377
  def BuildHooksEnv(self):
4378
    """Build hooks env.
4379

4380
    This runs on master, primary and secondary nodes of the instance.
4381

4382
    """
4383
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4384
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4385
    return env, nl, nl
4386

    
4387
  def CheckPrereq(self):
4388
    """Check prerequisites.
4389

4390
    This checks that the instance is in the cluster and is not running.
4391

4392
    """
4393
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4394
    assert instance is not None, \
4395
      "Cannot retrieve locked instance %s" % self.op.instance_name
4396
    _CheckNodeOnline(self, instance.primary_node)
4397

    
4398
    if instance.disk_template == constants.DT_DISKLESS:
4399
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4400
                                 self.op.instance_name,
4401
                                 errors.ECODE_INVAL)
4402
    _CheckInstanceDown(self, instance, "cannot reinstall")
4403

    
4404
    self.op.os_type = getattr(self.op, "os_type", None)
4405
    self.op.force_variant = getattr(self.op, "force_variant", False)
4406
    if self.op.os_type is not None:
4407
      # OS verification
4408
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4409
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4410

    
4411
    self.instance = instance
4412

    
4413
  def Exec(self, feedback_fn):
4414
    """Reinstall the instance.
4415

4416
    """
4417
    inst = self.instance
4418

    
4419
    if self.op.os_type is not None:
4420
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4421
      inst.os = self.op.os_type
4422
      self.cfg.Update(inst, feedback_fn)
4423

    
4424
    _StartInstanceDisks(self, inst, None)
4425
    try:
4426
      feedback_fn("Running the instance OS create scripts...")
4427
      # FIXME: pass debug option from opcode to backend
4428
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4429
                                             self.op.debug_level)
4430
      result.Raise("Could not install OS for instance %s on node %s" %
4431
                   (inst.name, inst.primary_node))
4432
    finally:
4433
      _ShutdownInstanceDisks(self, inst)
4434

    
4435

    
4436
class LURecreateInstanceDisks(LogicalUnit):
4437
  """Recreate an instance's missing disks.
4438

4439
  """
4440
  HPATH = "instance-recreate-disks"
4441
  HTYPE = constants.HTYPE_INSTANCE
4442
  _OP_REQP = ["instance_name", "disks"]
4443
  REQ_BGL = False
4444

    
4445
  def CheckArguments(self):
4446
    """Check the arguments.
4447

4448
    """
4449
    if not isinstance(self.op.disks, list):
4450
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
4451
    for item in self.op.disks:
4452
      if (not isinstance(item, int) or
4453
          item < 0):
4454
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
4455
                                   str(item), errors.ECODE_INVAL)
4456

    
4457
  def ExpandNames(self):
4458
    self._ExpandAndLockInstance()
4459

    
4460
  def BuildHooksEnv(self):
4461
    """Build hooks env.
4462

4463
    This runs on master, primary and secondary nodes of the instance.
4464

4465
    """
4466
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4467
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4468
    return env, nl, nl
4469

    
4470
  def CheckPrereq(self):
4471
    """Check prerequisites.
4472

4473
    This checks that the instance is in the cluster and is not running.
4474

4475
    """
4476
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4477
    assert instance is not None, \
4478
      "Cannot retrieve locked instance %s" % self.op.instance_name
4479
    _CheckNodeOnline(self, instance.primary_node)
4480

    
4481
    if instance.disk_template == constants.DT_DISKLESS:
4482
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4483
                                 self.op.instance_name, errors.ECODE_INVAL)
4484
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4485

    
4486
    if not self.op.disks:
4487
      self.op.disks = range(len(instance.disks))
4488
    else:
4489
      for idx in self.op.disks:
4490
        if idx >= len(instance.disks):
4491
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4492
                                     errors.ECODE_INVAL)
4493

    
4494
    self.instance = instance
4495

    
4496
  def Exec(self, feedback_fn):
4497
    """Recreate the disks.
4498

4499
    """
4500
    to_skip = []
4501
    for idx, _ in enumerate(self.instance.disks):
4502
      if idx not in self.op.disks: # disk idx has not been passed in
4503
        to_skip.append(idx)
4504
        continue
4505

    
4506
    _CreateDisks(self, self.instance, to_skip=to_skip)
4507

    
4508

    
4509
class LURenameInstance(LogicalUnit):
4510
  """Rename an instance.
4511

4512
  """
4513
  HPATH = "instance-rename"
4514
  HTYPE = constants.HTYPE_INSTANCE
4515
  _OP_REQP = ["instance_name", "new_name"]
4516

    
4517
  def BuildHooksEnv(self):
4518
    """Build hooks env.
4519

4520
    This runs on master, primary and secondary nodes of the instance.
4521

4522
    """
4523
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4524
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4525
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4526
    return env, nl, nl
4527

    
4528
  def CheckPrereq(self):
4529
    """Check prerequisites.
4530

4531
    This checks that the instance is in the cluster and is not running.
4532

4533
    """
4534
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4535
                                                self.op.instance_name)
4536
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4537
    assert instance is not None
4538
    _CheckNodeOnline(self, instance.primary_node)
4539
    _CheckInstanceDown(self, instance, "cannot rename")
4540
    self.instance = instance
4541

    
4542
    # new name verification
4543
    name_info = utils.GetHostInfo(self.op.new_name)
4544

    
4545
    self.op.new_name = new_name = name_info.name
4546
    instance_list = self.cfg.GetInstanceList()
4547
    if new_name in instance_list:
4548
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4549
                                 new_name, errors.ECODE_EXISTS)
4550

    
4551
    if not getattr(self.op, "ignore_ip", False):
4552
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4553
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4554
                                   (name_info.ip, new_name),
4555
                                   errors.ECODE_NOTUNIQUE)
4556

    
4557

    
4558
  def Exec(self, feedback_fn):
4559
    """Reinstall the instance.
4560

4561
    """
4562
    inst = self.instance
4563
    old_name = inst.name
4564

    
4565
    if inst.disk_template == constants.DT_FILE:
4566
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4567

    
4568
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4569
    # Change the instance lock. This is definitely safe while we hold the BGL
4570
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4571
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4572

    
4573
    # re-read the instance from the configuration after rename
4574
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4575

    
4576
    if inst.disk_template == constants.DT_FILE:
4577
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4578
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4579
                                                     old_file_storage_dir,
4580
                                                     new_file_storage_dir)
4581
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4582
                   " (but the instance has been renamed in Ganeti)" %
4583
                   (inst.primary_node, old_file_storage_dir,
4584
                    new_file_storage_dir))
4585

    
4586
    _StartInstanceDisks(self, inst, None)
4587
    try:
4588
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4589
                                                 old_name, self.op.debug_level)
4590
      msg = result.fail_msg
4591
      if msg:
4592
        msg = ("Could not run OS rename script for instance %s on node %s"
4593
               " (but the instance has been renamed in Ganeti): %s" %
4594
               (inst.name, inst.primary_node, msg))
4595
        self.proc.LogWarning(msg)
4596
    finally:
4597
      _ShutdownInstanceDisks(self, inst)
4598

    
4599

    
4600
class LURemoveInstance(LogicalUnit):
4601
  """Remove an instance.
4602

4603
  """
4604
  HPATH = "instance-remove"
4605
  HTYPE = constants.HTYPE_INSTANCE
4606
  _OP_REQP = ["instance_name", "ignore_failures"]
4607
  REQ_BGL = False
4608

    
4609
  def CheckArguments(self):
4610
    """Check the arguments.
4611

4612
    """
4613
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4614
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4615

    
4616
  def ExpandNames(self):
4617
    self._ExpandAndLockInstance()
4618
    self.needed_locks[locking.LEVEL_NODE] = []
4619
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4620

    
4621
  def DeclareLocks(self, level):
4622
    if level == locking.LEVEL_NODE:
4623
      self._LockInstancesNodes()
4624

    
4625
  def BuildHooksEnv(self):
4626
    """Build hooks env.
4627

4628
    This runs on master, primary and secondary nodes of the instance.
4629

4630
    """
4631
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4632
    env["SHUTDOWN_TIMEOUT"] = self.shutdown_timeout
4633
    nl = [self.cfg.GetMasterNode()]
4634
    nl_post = list(self.instance.all_nodes) + nl
4635
    return env, nl, nl_post
4636

    
4637
  def CheckPrereq(self):
4638
    """Check prerequisites.
4639

4640
    This checks that the instance is in the cluster.
4641

4642
    """
4643
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4644
    assert self.instance is not None, \
4645
      "Cannot retrieve locked instance %s" % self.op.instance_name
4646

    
4647
  def Exec(self, feedback_fn):
4648
    """Remove the instance.
4649

4650
    """
4651
    instance = self.instance
4652
    logging.info("Shutting down instance %s on node %s",
4653
                 instance.name, instance.primary_node)
4654

    
4655
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4656
                                             self.shutdown_timeout)
4657
    msg = result.fail_msg
4658
    if msg:
4659
      if self.op.ignore_failures:
4660
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4661
      else:
4662
        raise errors.OpExecError("Could not shutdown instance %s on"
4663
                                 " node %s: %s" %
4664
                                 (instance.name, instance.primary_node, msg))
4665

    
4666
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
4667

    
4668

    
4669
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
4670
  """Utility function to remove an instance.
4671

4672
  """
4673
  logging.info("Removing block devices for instance %s", instance.name)
4674

    
4675
  if not _RemoveDisks(lu, instance):
4676
    if not ignore_failures:
4677
      raise errors.OpExecError("Can't remove instance's disks")
4678
    feedback_fn("Warning: can't remove instance's disks")
4679

    
4680
  logging.info("Removing instance %s out of cluster config", instance.name)
4681

    
4682
  lu.cfg.RemoveInstance(instance.name)
4683

    
4684
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
4685
    "Instance lock removal conflict"
4686

    
4687
  # Remove lock for the instance
4688
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4689

    
4690

    
4691
class LUQueryInstances(NoHooksLU):
4692
  """Logical unit for querying instances.
4693

4694
  """
4695
  # pylint: disable-msg=W0142
4696
  _OP_REQP = ["output_fields", "names", "use_locking"]
4697
  REQ_BGL = False
4698
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4699
                    "serial_no", "ctime", "mtime", "uuid"]
4700
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4701
                                    "admin_state",
4702
                                    "disk_template", "ip", "mac", "bridge",
4703
                                    "nic_mode", "nic_link",
4704
                                    "sda_size", "sdb_size", "vcpus", "tags",
4705
                                    "network_port", "beparams",
4706
                                    r"(disk)\.(size)/([0-9]+)",
4707
                                    r"(disk)\.(sizes)", "disk_usage",
4708
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4709
                                    r"(nic)\.(bridge)/([0-9]+)",
4710
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4711
                                    r"(disk|nic)\.(count)",
4712
                                    "hvparams",
4713
                                    ] + _SIMPLE_FIELDS +
4714
                                  ["hv/%s" % name
4715
                                   for name in constants.HVS_PARAMETERS
4716
                                   if name not in constants.HVC_GLOBALS] +
4717
                                  ["be/%s" % name
4718
                                   for name in constants.BES_PARAMETERS])
4719
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4720

    
4721

    
4722
  def ExpandNames(self):
4723
    _CheckOutputFields(static=self._FIELDS_STATIC,
4724
                       dynamic=self._FIELDS_DYNAMIC,
4725
                       selected=self.op.output_fields)
4726

    
4727
    self.needed_locks = {}
4728
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4729
    self.share_locks[locking.LEVEL_NODE] = 1
4730

    
4731
    if self.op.names:
4732
      self.wanted = _GetWantedInstances(self, self.op.names)
4733
    else:
4734
      self.wanted = locking.ALL_SET
4735

    
4736
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4737
    self.do_locking = self.do_node_query and self.op.use_locking
4738
    if self.do_locking:
4739
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4740
      self.needed_locks[locking.LEVEL_NODE] = []
4741
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4742

    
4743
  def DeclareLocks(self, level):
4744
    if level == locking.LEVEL_NODE and self.do_locking:
4745
      self._LockInstancesNodes()
4746

    
4747
  def CheckPrereq(self):
4748
    """Check prerequisites.
4749

4750
    """
4751
    pass
4752

    
4753
  def Exec(self, feedback_fn):
4754
    """Computes the list of nodes and their attributes.
4755

4756
    """
4757
    # pylint: disable-msg=R0912
4758
    # way too many branches here
4759
    all_info = self.cfg.GetAllInstancesInfo()
4760
    if self.wanted == locking.ALL_SET:
4761
      # caller didn't specify instance names, so ordering is not important
4762
      if self.do_locking:
4763
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4764
      else:
4765
        instance_names = all_info.keys()
4766
      instance_names = utils.NiceSort(instance_names)
4767
    else:
4768
      # caller did specify names, so we must keep the ordering
4769
      if self.do_locking:
4770
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4771
      else:
4772
        tgt_set = all_info.keys()
4773
      missing = set(self.wanted).difference(tgt_set)
4774
      if missing:
4775
        raise errors.OpExecError("Some instances were removed before"
4776
                                 " retrieving their data: %s" % missing)
4777
      instance_names = self.wanted
4778

    
4779
    instance_list = [all_info[iname] for iname in instance_names]
4780

    
4781
    # begin data gathering
4782

    
4783
    nodes = frozenset([inst.primary_node for inst in instance_list])
4784
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4785

    
4786
    bad_nodes = []
4787
    off_nodes = []
4788
    if self.do_node_query:
4789
      live_data = {}
4790
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4791
      for name in nodes:
4792
        result = node_data[name]
4793
        if result.offline:
4794
          # offline nodes will be in both lists
4795
          off_nodes.append(name)
4796
        if result.fail_msg:
4797
          bad_nodes.append(name)
4798
        else:
4799
          if result.payload:
4800
            live_data.update(result.payload)
4801
          # else no instance is alive
4802
    else:
4803
      live_data = dict([(name, {}) for name in instance_names])
4804

    
4805
    # end data gathering
4806

    
4807
    HVPREFIX = "hv/"
4808
    BEPREFIX = "be/"
4809
    output = []
4810
    cluster = self.cfg.GetClusterInfo()
4811
    for instance in instance_list:
4812
      iout = []
4813
      i_hv = cluster.FillHV(instance, skip_globals=True)
4814
      i_be = cluster.FillBE(instance)
4815
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
4816
      for field in self.op.output_fields:
4817
        st_match = self._FIELDS_STATIC.Matches(field)
4818
        if field in self._SIMPLE_FIELDS:
4819
          val = getattr(instance, field)
4820
        elif field == "pnode":
4821
          val = instance.primary_node
4822
        elif field == "snodes":
4823
          val = list(instance.secondary_nodes)
4824
        elif field == "admin_state":
4825
          val = instance.admin_up
4826
        elif field == "oper_state":
4827
          if instance.primary_node in bad_nodes:
4828
            val = None
4829
          else:
4830
            val = bool(live_data.get(instance.name))
4831
        elif field == "status":
4832
          if instance.primary_node in off_nodes:
4833
            val = "ERROR_nodeoffline"
4834
          elif instance.primary_node in bad_nodes:
4835
            val = "ERROR_nodedown"
4836
          else:
4837
            running = bool(live_data.get(instance.name))
4838
            if running:
4839
              if instance.admin_up:
4840
                val = "running"
4841
              else:
4842
                val = "ERROR_up"
4843
            else:
4844
              if instance.admin_up:
4845
                val = "ERROR_down"
4846
              else:
4847
                val = "ADMIN_down"
4848
        elif field == "oper_ram":
4849
          if instance.primary_node in bad_nodes:
4850
            val = None
4851
          elif instance.name in live_data:
4852
            val = live_data[instance.name].get("memory", "?")
4853
          else:
4854
            val = "-"
4855
        elif field == "vcpus":
4856
          val = i_be[constants.BE_VCPUS]
4857
        elif field == "disk_template":
4858
          val = instance.disk_template
4859
        elif field == "ip":
4860
          if instance.nics:
4861
            val = instance.nics[0].ip
4862
          else:
4863
            val = None
4864
        elif field == "nic_mode":
4865
          if instance.nics:
4866
            val = i_nicp[0][constants.NIC_MODE]
4867
          else:
4868
            val = None
4869
        elif field == "nic_link":
4870
          if instance.nics:
4871
            val = i_nicp[0][constants.NIC_LINK]
4872
          else:
4873
            val = None
4874
        elif field == "bridge":
4875
          if (instance.nics and
4876
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4877
            val = i_nicp[0][constants.NIC_LINK]
4878
          else:
4879
            val = None
4880
        elif field == "mac":
4881
          if instance.nics:
4882
            val = instance.nics[0].mac
4883
          else:
4884
            val = None
4885
        elif field == "sda_size" or field == "sdb_size":
4886
          idx = ord(field[2]) - ord('a')
4887
          try:
4888
            val = instance.FindDisk(idx).size
4889
          except errors.OpPrereqError:
4890
            val = None
4891
        elif field == "disk_usage": # total disk usage per node
4892
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4893
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4894
        elif field == "tags":
4895
          val = list(instance.GetTags())
4896
        elif field == "hvparams":
4897
          val = i_hv
4898
        elif (field.startswith(HVPREFIX) and
4899
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
4900
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
4901
          val = i_hv.get(field[len(HVPREFIX):], None)
4902
        elif field == "beparams":
4903
          val = i_be
4904
        elif (field.startswith(BEPREFIX) and
4905
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4906
          val = i_be.get(field[len(BEPREFIX):], None)
4907
        elif st_match and st_match.groups():
4908
          # matches a variable list
4909
          st_groups = st_match.groups()
4910
          if st_groups and st_groups[0] == "disk":
4911
            if st_groups[1] == "count":
4912
              val = len(instance.disks)
4913
            elif st_groups[1] == "sizes":
4914
              val = [disk.size for disk in instance.disks]
4915
            elif st_groups[1] == "size":
4916
              try:
4917
                val = instance.FindDisk(st_groups[2]).size
4918
              except errors.OpPrereqError:
4919
                val = None
4920
            else:
4921
              assert False, "Unhandled disk parameter"
4922
          elif st_groups[0] == "nic":
4923
            if st_groups[1] == "count":
4924
              val = len(instance.nics)
4925
            elif st_groups[1] == "macs":
4926
              val = [nic.mac for nic in instance.nics]
4927
            elif st_groups[1] == "ips":
4928
              val = [nic.ip for nic in instance.nics]
4929
            elif st_groups[1] == "modes":
4930
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4931
            elif st_groups[1] == "links":
4932
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4933
            elif st_groups[1] == "bridges":
4934
              val = []
4935
              for nicp in i_nicp:
4936
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4937
                  val.append(nicp[constants.NIC_LINK])
4938
                else:
4939
                  val.append(None)
4940
            else:
4941
              # index-based item
4942
              nic_idx = int(st_groups[2])
4943
              if nic_idx >= len(instance.nics):
4944
                val = None
4945
              else:
4946
                if st_groups[1] == "mac":
4947
                  val = instance.nics[nic_idx].mac
4948
                elif st_groups[1] == "ip":
4949
                  val = instance.nics[nic_idx].ip
4950
                elif st_groups[1] == "mode":
4951
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4952
                elif st_groups[1] == "link":
4953
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4954
                elif st_groups[1] == "bridge":
4955
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4956
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4957
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4958
                  else:
4959
                    val = None
4960
                else:
4961
                  assert False, "Unhandled NIC parameter"
4962
          else:
4963
            assert False, ("Declared but unhandled variable parameter '%s'" %
4964
                           field)
4965
        else:
4966
          assert False, "Declared but unhandled parameter '%s'" % field
4967
        iout.append(val)
4968
      output.append(iout)
4969

    
4970
    return output
4971

    
4972

    
4973
class LUFailoverInstance(LogicalUnit):
4974
  """Failover an instance.
4975

4976
  """
4977
  HPATH = "instance-failover"
4978
  HTYPE = constants.HTYPE_INSTANCE
4979
  _OP_REQP = ["instance_name", "ignore_consistency"]
4980
  REQ_BGL = False
4981

    
4982
  def CheckArguments(self):
4983
    """Check the arguments.
4984

4985
    """
4986
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4987
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4988

    
4989
  def ExpandNames(self):
4990
    self._ExpandAndLockInstance()
4991
    self.needed_locks[locking.LEVEL_NODE] = []
4992
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4993

    
4994
  def DeclareLocks(self, level):
4995
    if level == locking.LEVEL_NODE:
4996
      self._LockInstancesNodes()
4997

    
4998
  def BuildHooksEnv(self):
4999
    """Build hooks env.
5000

5001
    This runs on master, primary and secondary nodes of the instance.
5002

5003
    """
5004
    instance = self.instance
5005
    source_node = instance.primary_node
5006
    target_node = instance.secondary_nodes[0]
5007
    env = {
5008
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5009
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
5010
      "OLD_PRIMARY": source_node,
5011
      "OLD_SECONDARY": target_node,
5012
      "NEW_PRIMARY": target_node,
5013
      "NEW_SECONDARY": source_node,
5014
      }
5015
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5016
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5017
    nl_post = list(nl)
5018
    nl_post.append(source_node)
5019
    return env, nl, nl_post
5020

    
5021
  def CheckPrereq(self):
5022
    """Check prerequisites.
5023

5024
    This checks that the instance is in the cluster.
5025

5026
    """
5027
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5028
    assert self.instance is not None, \
5029
      "Cannot retrieve locked instance %s" % self.op.instance_name
5030

    
5031
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5032
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5033
      raise errors.OpPrereqError("Instance's disk layout is not"
5034
                                 " network mirrored, cannot failover.",
5035
                                 errors.ECODE_STATE)
5036

    
5037
    secondary_nodes = instance.secondary_nodes
5038
    if not secondary_nodes:
5039
      raise errors.ProgrammerError("no secondary node but using "
5040
                                   "a mirrored disk template")
5041

    
5042
    target_node = secondary_nodes[0]
5043
    _CheckNodeOnline(self, target_node)
5044
    _CheckNodeNotDrained(self, target_node)
5045
    if instance.admin_up:
5046
      # check memory requirements on the secondary node
5047
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5048
                           instance.name, bep[constants.BE_MEMORY],
5049
                           instance.hypervisor)
5050
    else:
5051
      self.LogInfo("Not checking memory on the secondary node as"
5052
                   " instance will not be started")
5053

    
5054
    # check bridge existance
5055
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5056

    
5057
  def Exec(self, feedback_fn):
5058
    """Failover an instance.
5059

5060
    The failover is done by shutting it down on its present node and
5061
    starting it on the secondary.
5062

5063
    """
5064
    instance = self.instance
5065

    
5066
    source_node = instance.primary_node
5067
    target_node = instance.secondary_nodes[0]
5068

    
5069
    if instance.admin_up:
5070
      feedback_fn("* checking disk consistency between source and target")
5071
      for dev in instance.disks:
5072
        # for drbd, these are drbd over lvm
5073
        if not _CheckDiskConsistency(self, dev, target_node, False):
5074
          if not self.op.ignore_consistency:
5075
            raise errors.OpExecError("Disk %s is degraded on target node,"
5076
                                     " aborting failover." % dev.iv_name)
5077
    else:
5078
      feedback_fn("* not checking disk consistency as instance is not running")
5079

    
5080
    feedback_fn("* shutting down instance on source node")
5081
    logging.info("Shutting down instance %s on node %s",
5082
                 instance.name, source_node)
5083

    
5084
    result = self.rpc.call_instance_shutdown(source_node, instance,
5085
                                             self.shutdown_timeout)
5086
    msg = result.fail_msg
5087
    if msg:
5088
      if self.op.ignore_consistency:
5089
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5090
                             " Proceeding anyway. Please make sure node"
5091
                             " %s is down. Error details: %s",
5092
                             instance.name, source_node, source_node, msg)
5093
      else:
5094
        raise errors.OpExecError("Could not shutdown instance %s on"
5095
                                 " node %s: %s" %
5096
                                 (instance.name, source_node, msg))
5097

    
5098
    feedback_fn("* deactivating the instance's disks on source node")
5099
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5100
      raise errors.OpExecError("Can't shut down the instance's disks.")
5101

    
5102
    instance.primary_node = target_node
5103
    # distribute new instance config to the other nodes
5104
    self.cfg.Update(instance, feedback_fn)
5105

    
5106
    # Only start the instance if it's marked as up
5107
    if instance.admin_up:
5108
      feedback_fn("* activating the instance's disks on target node")
5109
      logging.info("Starting instance %s on node %s",
5110
                   instance.name, target_node)
5111

    
5112
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5113
                                               ignore_secondaries=True)
5114
      if not disks_ok:
5115
        _ShutdownInstanceDisks(self, instance)
5116
        raise errors.OpExecError("Can't activate the instance's disks")
5117

    
5118
      feedback_fn("* starting the instance on the target node")
5119
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5120
      msg = result.fail_msg
5121
      if msg:
5122
        _ShutdownInstanceDisks(self, instance)
5123
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5124
                                 (instance.name, target_node, msg))
5125

    
5126

    
5127
class LUMigrateInstance(LogicalUnit):
5128
  """Migrate an instance.
5129

5130
  This is migration without shutting down, compared to the failover,
5131
  which is done with shutdown.
5132

5133
  """
5134
  HPATH = "instance-migrate"
5135
  HTYPE = constants.HTYPE_INSTANCE
5136
  _OP_REQP = ["instance_name", "live", "cleanup"]
5137

    
5138
  REQ_BGL = False
5139

    
5140
  def ExpandNames(self):
5141
    self._ExpandAndLockInstance()
5142

    
5143
    self.needed_locks[locking.LEVEL_NODE] = []
5144
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5145

    
5146
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5147
                                       self.op.live, self.op.cleanup)
5148
    self.tasklets = [self._migrater]
5149

    
5150
  def DeclareLocks(self, level):
5151
    if level == locking.LEVEL_NODE:
5152
      self._LockInstancesNodes()
5153

    
5154
  def BuildHooksEnv(self):
5155
    """Build hooks env.
5156

5157
    This runs on master, primary and secondary nodes of the instance.
5158

5159
    """
5160
    instance = self._migrater.instance
5161
    source_node = instance.primary_node
5162
    target_node = instance.secondary_nodes[0]
5163
    env = _BuildInstanceHookEnvByObject(self, instance)
5164
    env["MIGRATE_LIVE"] = self.op.live
5165
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5166
    env.update({
5167
        "OLD_PRIMARY": source_node,
5168
        "OLD_SECONDARY": target_node,
5169
        "NEW_PRIMARY": target_node,
5170
        "NEW_SECONDARY": source_node,
5171
        })
5172
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5173
    nl_post = list(nl)
5174
    nl_post.append(source_node)
5175
    return env, nl, nl_post
5176

    
5177

    
5178
class LUMoveInstance(LogicalUnit):
5179
  """Move an instance by data-copying.
5180

5181
  """
5182
  HPATH = "instance-move"
5183
  HTYPE = constants.HTYPE_INSTANCE
5184
  _OP_REQP = ["instance_name", "target_node"]
5185
  REQ_BGL = False
5186

    
5187
  def CheckArguments(self):
5188
    """Check the arguments.
5189

5190
    """
5191
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
5192
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
5193

    
5194
  def ExpandNames(self):
5195
    self._ExpandAndLockInstance()
5196
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5197
    self.op.target_node = target_node
5198
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5199
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5200

    
5201
  def DeclareLocks(self, level):
5202
    if level == locking.LEVEL_NODE:
5203
      self._LockInstancesNodes(primary_only=True)
5204

    
5205
  def BuildHooksEnv(self):
5206
    """Build hooks env.
5207

5208
    This runs on master, primary and secondary nodes of the instance.
5209

5210
    """
5211
    env = {
5212
      "TARGET_NODE": self.op.target_node,
5213
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
5214
      }
5215
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5216
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5217
                                       self.op.target_node]
5218
    return env, nl, nl
5219

    
5220
  def CheckPrereq(self):
5221
    """Check prerequisites.
5222

5223
    This checks that the instance is in the cluster.
5224

5225
    """
5226
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5227
    assert self.instance is not None, \
5228
      "Cannot retrieve locked instance %s" % self.op.instance_name
5229

    
5230
    node = self.cfg.GetNodeInfo(self.op.target_node)
5231
    assert node is not None, \
5232
      "Cannot retrieve locked node %s" % self.op.target_node
5233

    
5234
    self.target_node = target_node = node.name
5235

    
5236
    if target_node == instance.primary_node:
5237
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5238
                                 (instance.name, target_node),
5239
                                 errors.ECODE_STATE)
5240

    
5241
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5242

    
5243
    for idx, dsk in enumerate(instance.disks):
5244
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5245
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5246
                                   " cannot copy" % idx, errors.ECODE_STATE)
5247

    
5248
    _CheckNodeOnline(self, target_node)
5249
    _CheckNodeNotDrained(self, target_node)
5250

    
5251
    if instance.admin_up:
5252
      # check memory requirements on the secondary node
5253
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5254
                           instance.name, bep[constants.BE_MEMORY],
5255
                           instance.hypervisor)
5256
    else:
5257
      self.LogInfo("Not checking memory on the secondary node as"
5258
                   " instance will not be started")
5259

    
5260
    # check bridge existance
5261
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5262

    
5263
  def Exec(self, feedback_fn):
5264
    """Move an instance.
5265

5266
    The move is done by shutting it down on its present node, copying
5267
    the data over (slow) and starting it on the new node.
5268

5269
    """
5270
    instance = self.instance
5271

    
5272
    source_node = instance.primary_node
5273
    target_node = self.target_node
5274

    
5275
    self.LogInfo("Shutting down instance %s on source node %s",
5276
                 instance.name, source_node)
5277

    
5278
    result = self.rpc.call_instance_shutdown(source_node, instance,
5279
                                             self.shutdown_timeout)
5280
    msg = result.fail_msg
5281
    if msg:
5282
      if self.op.ignore_consistency:
5283
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5284
                             " Proceeding anyway. Please make sure node"
5285
                             " %s is down. Error details: %s",
5286
                             instance.name, source_node, source_node, msg)
5287
      else:
5288
        raise errors.OpExecError("Could not shutdown instance %s on"
5289
                                 " node %s: %s" %
5290
                                 (instance.name, source_node, msg))
5291

    
5292
    # create the target disks
5293
    try:
5294
      _CreateDisks(self, instance, target_node=target_node)
5295
    except errors.OpExecError:
5296
      self.LogWarning("Device creation failed, reverting...")
5297
      try:
5298
        _RemoveDisks(self, instance, target_node=target_node)
5299
      finally:
5300
        self.cfg.ReleaseDRBDMinors(instance.name)
5301
        raise
5302

    
5303
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5304

    
5305
    errs = []
5306
    # activate, get path, copy the data over
5307
    for idx, disk in enumerate(instance.disks):
5308
      self.LogInfo("Copying data for disk %d", idx)
5309
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5310
                                               instance.name, True)
5311
      if result.fail_msg:
5312
        self.LogWarning("Can't assemble newly created disk %d: %s",
5313
                        idx, result.fail_msg)
5314
        errs.append(result.fail_msg)
5315
        break
5316
      dev_path = result.payload
5317
      result = self.rpc.call_blockdev_export(source_node, disk,
5318
                                             target_node, dev_path,
5319
                                             cluster_name)
5320
      if result.fail_msg:
5321
        self.LogWarning("Can't copy data over for disk %d: %s",
5322
                        idx, result.fail_msg)
5323
        errs.append(result.fail_msg)
5324
        break
5325

    
5326
    if errs:
5327
      self.LogWarning("Some disks failed to copy, aborting")
5328
      try:
5329
        _RemoveDisks(self, instance, target_node=target_node)
5330
      finally:
5331
        self.cfg.ReleaseDRBDMinors(instance.name)
5332
        raise errors.OpExecError("Errors during disk copy: %s" %
5333
                                 (",".join(errs),))
5334

    
5335
    instance.primary_node = target_node
5336
    self.cfg.Update(instance, feedback_fn)
5337

    
5338
    self.LogInfo("Removing the disks on the original node")
5339
    _RemoveDisks(self, instance, target_node=source_node)
5340

    
5341
    # Only start the instance if it's marked as up
5342
    if instance.admin_up:
5343
      self.LogInfo("Starting instance %s on node %s",
5344
                   instance.name, target_node)
5345

    
5346
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5347
                                           ignore_secondaries=True)
5348
      if not disks_ok:
5349
        _ShutdownInstanceDisks(self, instance)
5350
        raise errors.OpExecError("Can't activate the instance's disks")
5351

    
5352
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5353
      msg = result.fail_msg
5354
      if msg:
5355
        _ShutdownInstanceDisks(self, instance)
5356
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5357
                                 (instance.name, target_node, msg))
5358

    
5359

    
5360
class LUMigrateNode(LogicalUnit):
5361
  """Migrate all instances from a node.
5362

5363
  """
5364
  HPATH = "node-migrate"
5365
  HTYPE = constants.HTYPE_NODE
5366
  _OP_REQP = ["node_name", "live"]
5367
  REQ_BGL = False
5368

    
5369
  def ExpandNames(self):
5370
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5371

    
5372
    self.needed_locks = {
5373
      locking.LEVEL_NODE: [self.op.node_name],
5374
      }
5375

    
5376
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5377

    
5378
    # Create tasklets for migrating instances for all instances on this node
5379
    names = []
5380
    tasklets = []
5381

    
5382
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5383
      logging.debug("Migrating instance %s", inst.name)
5384
      names.append(inst.name)
5385

    
5386
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
5387

    
5388
    self.tasklets = tasklets
5389

    
5390
    # Declare instance locks
5391
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5392

    
5393
  def DeclareLocks(self, level):
5394
    if level == locking.LEVEL_NODE:
5395
      self._LockInstancesNodes()
5396

    
5397
  def BuildHooksEnv(self):
5398
    """Build hooks env.
5399

5400
    This runs on the master, the primary and all the secondaries.
5401

5402
    """
5403
    env = {
5404
      "NODE_NAME": self.op.node_name,
5405
      }
5406

    
5407
    nl = [self.cfg.GetMasterNode()]
5408

    
5409
    return (env, nl, nl)
5410

    
5411

    
5412
class TLMigrateInstance(Tasklet):
5413
  def __init__(self, lu, instance_name, live, cleanup):
5414
    """Initializes this class.
5415

5416
    """
5417
    Tasklet.__init__(self, lu)
5418

    
5419
    # Parameters
5420
    self.instance_name = instance_name
5421
    self.live = live
5422
    self.cleanup = cleanup
5423

    
5424
  def CheckPrereq(self):
5425
    """Check prerequisites.
5426

5427
    This checks that the instance is in the cluster.
5428

5429
    """
5430
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5431
    instance = self.cfg.GetInstanceInfo(instance_name)
5432
    assert instance is not None
5433

    
5434
    if instance.disk_template != constants.DT_DRBD8:
5435
      raise errors.OpPrereqError("Instance's disk layout is not"
5436
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5437

    
5438
    secondary_nodes = instance.secondary_nodes
5439
    if not secondary_nodes:
5440
      raise errors.ConfigurationError("No secondary node but using"
5441
                                      " drbd8 disk template")
5442

    
5443
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5444

    
5445
    target_node = secondary_nodes[0]
5446
    # check memory requirements on the secondary node
5447
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5448
                         instance.name, i_be[constants.BE_MEMORY],
5449
                         instance.hypervisor)
5450

    
5451
    # check bridge existance
5452
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5453

    
5454
    if not self.cleanup:
5455
      _CheckNodeNotDrained(self.lu, target_node)
5456
      result = self.rpc.call_instance_migratable(instance.primary_node,
5457
                                                 instance)
5458
      result.Raise("Can't migrate, please use failover",
5459
                   prereq=True, ecode=errors.ECODE_STATE)
5460

    
5461
    self.instance = instance
5462

    
5463
  def _WaitUntilSync(self):
5464
    """Poll with custom rpc for disk sync.
5465

5466
    This uses our own step-based rpc call.
5467

5468
    """
5469
    self.feedback_fn("* wait until resync is done")
5470
    all_done = False
5471
    while not all_done:
5472
      all_done = True
5473
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5474
                                            self.nodes_ip,
5475
                                            self.instance.disks)
5476
      min_percent = 100
5477
      for node, nres in result.items():
5478
        nres.Raise("Cannot resync disks on node %s" % node)
5479
        node_done, node_percent = nres.payload
5480
        all_done = all_done and node_done
5481
        if node_percent is not None:
5482
          min_percent = min(min_percent, node_percent)
5483
      if not all_done:
5484
        if min_percent < 100:
5485
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5486
        time.sleep(2)
5487

    
5488
  def _EnsureSecondary(self, node):
5489
    """Demote a node to secondary.
5490

5491
    """
5492
    self.feedback_fn("* switching node %s to secondary mode" % node)
5493

    
5494
    for dev in self.instance.disks:
5495
      self.cfg.SetDiskID(dev, node)
5496

    
5497
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5498
                                          self.instance.disks)
5499
    result.Raise("Cannot change disk to secondary on node %s" % node)
5500

    
5501
  def _GoStandalone(self):
5502
    """Disconnect from the network.
5503

5504
    """
5505
    self.feedback_fn("* changing into standalone mode")
5506
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5507
                                               self.instance.disks)
5508
    for node, nres in result.items():
5509
      nres.Raise("Cannot disconnect disks node %s" % node)
5510

    
5511
  def _GoReconnect(self, multimaster):
5512
    """Reconnect to the network.
5513

5514
    """
5515
    if multimaster:
5516
      msg = "dual-master"
5517
    else:
5518
      msg = "single-master"
5519
    self.feedback_fn("* changing disks into %s mode" % msg)
5520
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5521
                                           self.instance.disks,
5522
                                           self.instance.name, multimaster)
5523
    for node, nres in result.items():
5524
      nres.Raise("Cannot change disks config on node %s" % node)
5525

    
5526
  def _ExecCleanup(self):
5527
    """Try to cleanup after a failed migration.
5528

5529
    The cleanup is done by:
5530
      - check that the instance is running only on one node
5531
        (and update the config if needed)
5532
      - change disks on its secondary node to secondary
5533
      - wait until disks are fully synchronized
5534
      - disconnect from the network
5535
      - change disks into single-master mode
5536
      - wait again until disks are fully synchronized
5537

5538
    """
5539
    instance = self.instance
5540
    target_node = self.target_node
5541
    source_node = self.source_node
5542

    
5543
    # check running on only one node
5544
    self.feedback_fn("* checking where the instance actually runs"
5545
                     " (if this hangs, the hypervisor might be in"
5546
                     " a bad state)")
5547
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5548
    for node, result in ins_l.items():
5549
      result.Raise("Can't contact node %s" % node)
5550

    
5551
    runningon_source = instance.name in ins_l[source_node].payload
5552
    runningon_target = instance.name in ins_l[target_node].payload
5553

    
5554
    if runningon_source and runningon_target:
5555
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5556
                               " or the hypervisor is confused. You will have"
5557
                               " to ensure manually that it runs only on one"
5558
                               " and restart this operation.")
5559

    
5560
    if not (runningon_source or runningon_target):
5561
      raise errors.OpExecError("Instance does not seem to be running at all."
5562
                               " In this case, it's safer to repair by"
5563
                               " running 'gnt-instance stop' to ensure disk"
5564
                               " shutdown, and then restarting it.")
5565

    
5566
    if runningon_target:
5567
      # the migration has actually succeeded, we need to update the config
5568
      self.feedback_fn("* instance running on secondary node (%s),"
5569
                       " updating config" % target_node)
5570
      instance.primary_node = target_node
5571
      self.cfg.Update(instance, self.feedback_fn)
5572
      demoted_node = source_node
5573
    else:
5574
      self.feedback_fn("* instance confirmed to be running on its"
5575
                       " primary node (%s)" % source_node)
5576
      demoted_node = target_node
5577

    
5578
    self._EnsureSecondary(demoted_node)
5579
    try:
5580
      self._WaitUntilSync()
5581
    except errors.OpExecError:
5582
      # we ignore here errors, since if the device is standalone, it
5583
      # won't be able to sync
5584
      pass
5585
    self._GoStandalone()
5586
    self._GoReconnect(False)
5587
    self._WaitUntilSync()
5588

    
5589
    self.feedback_fn("* done")
5590

    
5591
  def _RevertDiskStatus(self):
5592
    """Try to revert the disk status after a failed migration.
5593

5594
    """
5595
    target_node = self.target_node
5596
    try:
5597
      self._EnsureSecondary(target_node)
5598
      self._GoStandalone()
5599
      self._GoReconnect(False)
5600
      self._WaitUntilSync()
5601
    except errors.OpExecError, err:
5602
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5603
                         " drives: error '%s'\n"
5604
                         "Please look and recover the instance status" %
5605
                         str(err))
5606

    
5607
  def _AbortMigration(self):
5608
    """Call the hypervisor code to abort a started migration.
5609

5610
    """
5611
    instance = self.instance
5612
    target_node = self.target_node
5613
    migration_info = self.migration_info
5614

    
5615
    abort_result = self.rpc.call_finalize_migration(target_node,
5616
                                                    instance,
5617
                                                    migration_info,
5618
                                                    False)
5619
    abort_msg = abort_result.fail_msg
5620
    if abort_msg:
5621
      logging.error("Aborting migration failed on target node %s: %s",
5622
                    target_node, abort_msg)
5623
      # Don't raise an exception here, as we stil have to try to revert the
5624
      # disk status, even if this step failed.
5625

    
5626
  def _ExecMigration(self):
5627
    """Migrate an instance.
5628

5629
    The migrate is done by:
5630
      - change the disks into dual-master mode
5631
      - wait until disks are fully synchronized again
5632
      - migrate the instance
5633
      - change disks on the new secondary node (the old primary) to secondary
5634
      - wait until disks are fully synchronized
5635
      - change disks into single-master mode
5636

5637
    """
5638
    instance = self.instance
5639
    target_node = self.target_node
5640
    source_node = self.source_node
5641

    
5642
    self.feedback_fn("* checking disk consistency between source and target")
5643
    for dev in instance.disks:
5644
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
5645
        raise errors.OpExecError("Disk %s is degraded or not fully"
5646
                                 " synchronized on target node,"
5647
                                 " aborting migrate." % dev.iv_name)
5648

    
5649
    # First get the migration information from the remote node
5650
    result = self.rpc.call_migration_info(source_node, instance)
5651
    msg = result.fail_msg
5652
    if msg:
5653
      log_err = ("Failed fetching source migration information from %s: %s" %
5654
                 (source_node, msg))
5655
      logging.error(log_err)
5656
      raise errors.OpExecError(log_err)
5657

    
5658
    self.migration_info = migration_info = result.payload
5659

    
5660
    # Then switch the disks to master/master mode
5661
    self._EnsureSecondary(target_node)
5662
    self._GoStandalone()
5663
    self._GoReconnect(True)
5664
    self._WaitUntilSync()
5665

    
5666
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5667
    result = self.rpc.call_accept_instance(target_node,
5668
                                           instance,
5669
                                           migration_info,
5670
                                           self.nodes_ip[target_node])
5671

    
5672
    msg = result.fail_msg
5673
    if msg:
5674
      logging.error("Instance pre-migration failed, trying to revert"
5675
                    " disk status: %s", msg)
5676
      self.feedback_fn("Pre-migration failed, aborting")
5677
      self._AbortMigration()
5678
      self._RevertDiskStatus()
5679
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5680
                               (instance.name, msg))
5681

    
5682
    self.feedback_fn("* migrating instance to %s" % target_node)
5683
    time.sleep(10)
5684
    result = self.rpc.call_instance_migrate(source_node, instance,
5685
                                            self.nodes_ip[target_node],
5686
                                            self.live)
5687
    msg = result.fail_msg
5688
    if msg:
5689
      logging.error("Instance migration failed, trying to revert"
5690
                    " disk status: %s", msg)
5691
      self.feedback_fn("Migration failed, aborting")
5692
      self._AbortMigration()
5693
      self._RevertDiskStatus()
5694
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5695
                               (instance.name, msg))
5696
    time.sleep(10)
5697

    
5698
    instance.primary_node = target_node
5699
    # distribute new instance config to the other nodes
5700
    self.cfg.Update(instance, self.feedback_fn)
5701

    
5702
    result = self.rpc.call_finalize_migration(target_node,
5703
                                              instance,
5704
                                              migration_info,
5705
                                              True)
5706
    msg = result.fail_msg
5707
    if msg:
5708
      logging.error("Instance migration succeeded, but finalization failed:"
5709
                    " %s", msg)
5710
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5711
                               msg)
5712

    
5713
    self._EnsureSecondary(source_node)
5714
    self._WaitUntilSync()
5715
    self._GoStandalone()
5716
    self._GoReconnect(False)
5717
    self._WaitUntilSync()
5718

    
5719
    self.feedback_fn("* done")
5720

    
5721
  def Exec(self, feedback_fn):
5722
    """Perform the migration.
5723

5724
    """
5725
    feedback_fn("Migrating instance %s" % self.instance.name)
5726

    
5727
    self.feedback_fn = feedback_fn
5728

    
5729
    self.source_node = self.instance.primary_node
5730
    self.target_node = self.instance.secondary_nodes[0]
5731
    self.all_nodes = [self.source_node, self.target_node]
5732
    self.nodes_ip = {
5733
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5734
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5735
      }
5736

    
5737
    if self.cleanup:
5738
      return self._ExecCleanup()
5739
    else:
5740
      return self._ExecMigration()
5741

    
5742

    
5743
def _CreateBlockDev(lu, node, instance, device, force_create,
5744
                    info, force_open):
5745
  """Create a tree of block devices on a given node.
5746

5747
  If this device type has to be created on secondaries, create it and
5748
  all its children.
5749

5750
  If not, just recurse to children keeping the same 'force' value.
5751

5752
  @param lu: the lu on whose behalf we execute
5753
  @param node: the node on which to create the device
5754
  @type instance: L{objects.Instance}
5755
  @param instance: the instance which owns the device
5756
  @type device: L{objects.Disk}
5757
  @param device: the device to create
5758
  @type force_create: boolean
5759
  @param force_create: whether to force creation of this device; this
5760
      will be change to True whenever we find a device which has
5761
      CreateOnSecondary() attribute
5762
  @param info: the extra 'metadata' we should attach to the device
5763
      (this will be represented as a LVM tag)
5764
  @type force_open: boolean
5765
  @param force_open: this parameter will be passes to the
5766
      L{backend.BlockdevCreate} function where it specifies
5767
      whether we run on primary or not, and it affects both
5768
      the child assembly and the device own Open() execution
5769

5770
  """
5771
  if device.CreateOnSecondary():
5772
    force_create = True
5773

    
5774
  if device.children:
5775
    for child in device.children:
5776
      _CreateBlockDev(lu, node, instance, child, force_create,
5777
                      info, force_open)
5778

    
5779
  if not force_create:
5780
    return
5781

    
5782
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5783

    
5784

    
5785
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5786
  """Create a single block device on a given node.
5787

5788
  This will not recurse over children of the device, so they must be
5789
  created in advance.
5790

5791
  @param lu: the lu on whose behalf we execute
5792
  @param node: the node on which to create the device
5793
  @type instance: L{objects.Instance}
5794
  @param instance: the instance which owns the device
5795
  @type device: L{objects.Disk}
5796
  @param device: the device to create
5797
  @param info: the extra 'metadata' we should attach to the device
5798
      (this will be represented as a LVM tag)
5799
  @type force_open: boolean
5800
  @param force_open: this parameter will be passes to the
5801
      L{backend.BlockdevCreate} function where it specifies
5802
      whether we run on primary or not, and it affects both
5803
      the child assembly and the device own Open() execution
5804

5805
  """
5806
  lu.cfg.SetDiskID(device, node)
5807
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5808
                                       instance.name, force_open, info)
5809
  result.Raise("Can't create block device %s on"
5810
               " node %s for instance %s" % (device, node, instance.name))
5811
  if device.physical_id is None:
5812
    device.physical_id = result.payload
5813

    
5814

    
5815
def _GenerateUniqueNames(lu, exts):
5816
  """Generate a suitable LV name.
5817

5818
  This will generate a logical volume name for the given instance.
5819

5820
  """
5821
  results = []
5822
  for val in exts:
5823
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
5824
    results.append("%s%s" % (new_id, val))
5825
  return results
5826

    
5827

    
5828
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5829
                         p_minor, s_minor):
5830
  """Generate a drbd8 device complete with its children.
5831

5832
  """
5833
  port = lu.cfg.AllocatePort()
5834
  vgname = lu.cfg.GetVGName()
5835
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
5836
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5837
                          logical_id=(vgname, names[0]))
5838
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5839
                          logical_id=(vgname, names[1]))
5840
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5841
                          logical_id=(primary, secondary, port,
5842
                                      p_minor, s_minor,
5843
                                      shared_secret),
5844
                          children=[dev_data, dev_meta],
5845
                          iv_name=iv_name)
5846
  return drbd_dev
5847

    
5848

    
5849
def _GenerateDiskTemplate(lu, template_name,
5850
                          instance_name, primary_node,
5851
                          secondary_nodes, disk_info,
5852
                          file_storage_dir, file_driver,
5853
                          base_index):
5854
  """Generate the entire disk layout for a given template type.
5855

5856
  """
5857
  #TODO: compute space requirements
5858

    
5859
  vgname = lu.cfg.GetVGName()
5860
  disk_count = len(disk_info)
5861
  disks = []
5862
  if template_name == constants.DT_DISKLESS:
5863
    pass
5864
  elif template_name == constants.DT_PLAIN:
5865
    if len(secondary_nodes) != 0:
5866
      raise errors.ProgrammerError("Wrong template configuration")
5867

    
5868
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5869
                                      for i in range(disk_count)])
5870
    for idx, disk in enumerate(disk_info):
5871
      disk_index = idx + base_index
5872
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5873
                              logical_id=(vgname, names[idx]),
5874
                              iv_name="disk/%d" % disk_index,
5875
                              mode=disk["mode"])
5876
      disks.append(disk_dev)
5877
  elif template_name == constants.DT_DRBD8:
5878
    if len(secondary_nodes) != 1:
5879
      raise errors.ProgrammerError("Wrong template configuration")
5880
    remote_node = secondary_nodes[0]
5881
    minors = lu.cfg.AllocateDRBDMinor(
5882
      [primary_node, remote_node] * len(disk_info), instance_name)
5883

    
5884
    names = []
5885
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5886
                                               for i in range(disk_count)]):
5887
      names.append(lv_prefix + "_data")
5888
      names.append(lv_prefix + "_meta")
5889
    for idx, disk in enumerate(disk_info):
5890
      disk_index = idx + base_index
5891
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5892
                                      disk["size"], names[idx*2:idx*2+2],
5893
                                      "disk/%d" % disk_index,
5894
                                      minors[idx*2], minors[idx*2+1])
5895
      disk_dev.mode = disk["mode"]
5896
      disks.append(disk_dev)
5897
  elif template_name == constants.DT_FILE:
5898
    if len(secondary_nodes) != 0:
5899
      raise errors.ProgrammerError("Wrong template configuration")
5900

    
5901
    _RequireFileStorage()
5902

    
5903
    for idx, disk in enumerate(disk_info):
5904
      disk_index = idx + base_index
5905
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5906
                              iv_name="disk/%d" % disk_index,
5907
                              logical_id=(file_driver,
5908
                                          "%s/disk%d" % (file_storage_dir,
5909
                                                         disk_index)),
5910
                              mode=disk["mode"])
5911
      disks.append(disk_dev)
5912
  else:
5913
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5914
  return disks
5915

    
5916

    
5917
def _GetInstanceInfoText(instance):
5918
  """Compute that text that should be added to the disk's metadata.
5919

5920
  """
5921
  return "originstname+%s" % instance.name
5922

    
5923

    
5924
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5925
  """Create all disks for an instance.
5926

5927
  This abstracts away some work from AddInstance.
5928

5929
  @type lu: L{LogicalUnit}
5930
  @param lu: the logical unit on whose behalf we execute
5931
  @type instance: L{objects.Instance}
5932
  @param instance: the instance whose disks we should create
5933
  @type to_skip: list
5934
  @param to_skip: list of indices to skip
5935
  @type target_node: string
5936
  @param target_node: if passed, overrides the target node for creation
5937
  @rtype: boolean
5938
  @return: the success of the creation
5939

5940
  """
5941
  info = _GetInstanceInfoText(instance)
5942
  if target_node is None:
5943
    pnode = instance.primary_node
5944
    all_nodes = instance.all_nodes
5945
  else:
5946
    pnode = target_node
5947
    all_nodes = [pnode]
5948

    
5949
  if instance.disk_template == constants.DT_FILE:
5950
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5951
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5952

    
5953
    result.Raise("Failed to create directory '%s' on"
5954
                 " node %s" % (file_storage_dir, pnode))
5955

    
5956
  # Note: this needs to be kept in sync with adding of disks in
5957
  # LUSetInstanceParams
5958
  for idx, device in enumerate(instance.disks):
5959
    if to_skip and idx in to_skip:
5960
      continue
5961
    logging.info("Creating volume %s for instance %s",
5962
                 device.iv_name, instance.name)
5963
    #HARDCODE
5964
    for node in all_nodes:
5965
      f_create = node == pnode
5966
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5967

    
5968

    
5969
def _RemoveDisks(lu, instance, target_node=None):
5970
  """Remove all disks for an instance.
5971

5972
  This abstracts away some work from `AddInstance()` and
5973
  `RemoveInstance()`. Note that in case some of the devices couldn't
5974
  be removed, the removal will continue with the other ones (compare
5975
  with `_CreateDisks()`).
5976

5977
  @type lu: L{LogicalUnit}
5978
  @param lu: the logical unit on whose behalf we execute
5979
  @type instance: L{objects.Instance}
5980
  @param instance: the instance whose disks we should remove
5981
  @type target_node: string
5982
  @param target_node: used to override the node on which to remove the disks
5983
  @rtype: boolean
5984
  @return: the success of the removal
5985

5986
  """
5987
  logging.info("Removing block devices for instance %s", instance.name)
5988

    
5989
  all_result = True
5990
  for device in instance.disks:
5991
    if target_node:
5992
      edata = [(target_node, device)]
5993
    else:
5994
      edata = device.ComputeNodeTree(instance.primary_node)
5995
    for node, disk in edata:
5996
      lu.cfg.SetDiskID(disk, node)
5997
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5998
      if msg:
5999
        lu.LogWarning("Could not remove block device %s on node %s,"
6000
                      " continuing anyway: %s", device.iv_name, node, msg)
6001
        all_result = False
6002

    
6003
  if instance.disk_template == constants.DT_FILE:
6004
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6005
    if target_node:
6006
      tgt = target_node
6007
    else:
6008
      tgt = instance.primary_node
6009
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6010
    if result.fail_msg:
6011
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6012
                    file_storage_dir, instance.primary_node, result.fail_msg)
6013
      all_result = False
6014

    
6015
  return all_result
6016

    
6017

    
6018
def _ComputeDiskSize(disk_template, disks):
6019
  """Compute disk size requirements in the volume group
6020

6021
  """
6022
  # Required free disk space as a function of disk and swap space
6023
  req_size_dict = {
6024
    constants.DT_DISKLESS: None,
6025
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6026
    # 128 MB are added for drbd metadata for each disk
6027
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6028
    constants.DT_FILE: None,
6029
  }
6030

    
6031
  if disk_template not in req_size_dict:
6032
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6033
                                 " is unknown" %  disk_template)
6034

    
6035
  return req_size_dict[disk_template]
6036

    
6037

    
6038
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6039
  """Hypervisor parameter validation.
6040

6041
  This function abstract the hypervisor parameter validation to be
6042
  used in both instance create and instance modify.
6043

6044
  @type lu: L{LogicalUnit}
6045
  @param lu: the logical unit for which we check
6046
  @type nodenames: list
6047
  @param nodenames: the list of nodes on which we should check
6048
  @type hvname: string
6049
  @param hvname: the name of the hypervisor we should use
6050
  @type hvparams: dict
6051
  @param hvparams: the parameters which we need to check
6052
  @raise errors.OpPrereqError: if the parameters are not valid
6053

6054
  """
6055
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6056
                                                  hvname,
6057
                                                  hvparams)
6058
  for node in nodenames:
6059
    info = hvinfo[node]
6060
    if info.offline:
6061
      continue
6062
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6063

    
6064

    
6065
class LUCreateInstance(LogicalUnit):
6066
  """Create an instance.
6067

6068
  """
6069
  HPATH = "instance-add"
6070
  HTYPE = constants.HTYPE_INSTANCE
6071
  _OP_REQP = ["instance_name", "disks",
6072
              "mode", "start",
6073
              "wait_for_sync", "ip_check", "nics",
6074
              "hvparams", "beparams"]
6075
  REQ_BGL = False
6076

    
6077
  def CheckArguments(self):
6078
    """Check arguments.
6079

6080
    """
6081
    # set optional parameters to none if they don't exist
6082
    for attr in ["pnode", "snode", "iallocator", "hypervisor",
6083
                 "disk_template", "identify_defaults"]:
6084
      if not hasattr(self.op, attr):
6085
        setattr(self.op, attr, None)
6086

    
6087
    # do not require name_check to ease forward/backward compatibility
6088
    # for tools
6089
    if not hasattr(self.op, "name_check"):
6090
      self.op.name_check = True
6091
    if not hasattr(self.op, "no_install"):
6092
      self.op.no_install = False
6093
    if self.op.no_install and self.op.start:
6094
      self.LogInfo("No-installation mode selected, disabling startup")
6095
      self.op.start = False
6096
    # validate/normalize the instance name
6097
    self.op.instance_name = utils.HostInfo.NormalizeName(self.op.instance_name)
6098
    if self.op.ip_check and not self.op.name_check:
6099
      # TODO: make the ip check more flexible and not depend on the name check
6100
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
6101
                                 errors.ECODE_INVAL)
6102

    
6103
    # check nics' parameter names
6104
    for nic in self.op.nics:
6105
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6106

    
6107
    # check disks. parameter names and consistent adopt/no-adopt strategy
6108
    has_adopt = has_no_adopt = False
6109
    for disk in self.op.disks:
6110
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6111
      if "adopt" in disk:
6112
        has_adopt = True
6113
      else:
6114
        has_no_adopt = True
6115
    if has_adopt and has_no_adopt:
6116
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6117
                                 errors.ECODE_INVAL)
6118
    if has_adopt:
6119
      if self.op.disk_template != constants.DT_PLAIN:
6120
        raise errors.OpPrereqError("Disk adoption is only supported for the"
6121
                                   " 'plain' disk template",
6122
                                   errors.ECODE_INVAL)
6123
      if self.op.iallocator is not None:
6124
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6125
                                   " iallocator script", errors.ECODE_INVAL)
6126
      if self.op.mode == constants.INSTANCE_IMPORT:
6127
        raise errors.OpPrereqError("Disk adoption not allowed for"
6128
                                   " instance import", errors.ECODE_INVAL)
6129

    
6130
    self.adopt_disks = has_adopt
6131

    
6132
    # verify creation mode
6133
    if self.op.mode not in constants.INSTANCE_CREATE_MODES:
6134
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
6135
                                 self.op.mode, errors.ECODE_INVAL)
6136

    
6137
    # instance name verification
6138
    if self.op.name_check:
6139
      self.hostname1 = utils.GetHostInfo(self.op.instance_name)
6140
      self.op.instance_name = self.hostname1.name
6141
      # used in CheckPrereq for ip ping check
6142
      self.check_ip = self.hostname1.ip
6143
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6144
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6145
                                 errors.ECODE_INVAL)
6146
    else:
6147
      self.check_ip = None
6148

    
6149
    # file storage checks
6150
    if (self.op.file_driver and
6151
        not self.op.file_driver in constants.FILE_DRIVER):
6152
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6153
                                 self.op.file_driver, errors.ECODE_INVAL)
6154

    
6155
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6156
      raise errors.OpPrereqError("File storage directory path not absolute",
6157
                                 errors.ECODE_INVAL)
6158

    
6159
    ### Node/iallocator related checks
6160
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
6161
      raise errors.OpPrereqError("One and only one of iallocator and primary"
6162
                                 " node must be given",
6163
                                 errors.ECODE_INVAL)
6164

    
6165
    self._cds = _GetClusterDomainSecret()
6166

    
6167
    if self.op.mode == constants.INSTANCE_IMPORT:
6168
      # On import force_variant must be True, because if we forced it at
6169
      # initial install, our only chance when importing it back is that it
6170
      # works again!
6171
      self.op.force_variant = True
6172

    
6173
      if self.op.no_install:
6174
        self.LogInfo("No-installation mode has no effect during import")
6175

    
6176
    elif self.op.mode == constants.INSTANCE_CREATE:
6177
      if getattr(self.op, "os_type", None) is None:
6178
        raise errors.OpPrereqError("No guest OS specified",
6179
                                   errors.ECODE_INVAL)
6180
      self.op.force_variant = getattr(self.op, "force_variant", False)
6181
      if self.op.disk_template is None:
6182
        raise errors.OpPrereqError("No disk template specified",
6183
                                   errors.ECODE_INVAL)
6184

    
6185
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6186
      # Check handshake to ensure both clusters have the same domain secret
6187
      src_handshake = getattr(self.op, "source_handshake", None)
6188
      if not src_handshake:
6189
        raise errors.OpPrereqError("Missing source handshake",
6190
                                   errors.ECODE_INVAL)
6191

    
6192
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6193
                                                           src_handshake)
6194
      if errmsg:
6195
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6196
                                   errors.ECODE_INVAL)
6197

    
6198
      # Load and check source CA
6199
      self.source_x509_ca_pem = getattr(self.op, "source_x509_ca", None)
6200
      if not self.source_x509_ca_pem:
6201
        raise errors.OpPrereqError("Missing source X509 CA",
6202
                                   errors.ECODE_INVAL)
6203

    
6204
      try:
6205
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6206
                                                    self._cds)
6207
      except OpenSSL.crypto.Error, err:
6208
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6209
                                   (err, ), errors.ECODE_INVAL)
6210

    
6211
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6212
      if errcode is not None:
6213
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6214
                                   errors.ECODE_INVAL)
6215

    
6216
      self.source_x509_ca = cert
6217

    
6218
      src_instance_name = getattr(self.op, "source_instance_name", None)
6219
      if not src_instance_name:
6220
        raise errors.OpPrereqError("Missing source instance name",
6221
                                   errors.ECODE_INVAL)
6222

    
6223
      self.source_instance_name = \
6224
        utils.GetHostInfo(utils.HostInfo.NormalizeName(src_instance_name)).name
6225

    
6226
    else:
6227
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6228
                                 self.op.mode, errors.ECODE_INVAL)
6229

    
6230
  def ExpandNames(self):
6231
    """ExpandNames for CreateInstance.
6232

6233
    Figure out the right locks for instance creation.
6234

6235
    """
6236
    self.needed_locks = {}
6237

    
6238
    instance_name = self.op.instance_name
6239
    # this is just a preventive check, but someone might still add this
6240
    # instance in the meantime, and creation will fail at lock-add time
6241
    if instance_name in self.cfg.GetInstanceList():
6242
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6243
                                 instance_name, errors.ECODE_EXISTS)
6244

    
6245
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6246

    
6247
    if self.op.iallocator:
6248
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6249
    else:
6250
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6251
      nodelist = [self.op.pnode]
6252
      if self.op.snode is not None:
6253
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6254
        nodelist.append(self.op.snode)
6255
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6256

    
6257
    # in case of import lock the source node too
6258
    if self.op.mode == constants.INSTANCE_IMPORT:
6259
      src_node = getattr(self.op, "src_node", None)
6260
      src_path = getattr(self.op, "src_path", None)
6261

    
6262
      if src_path is None:
6263
        self.op.src_path = src_path = self.op.instance_name
6264

    
6265
      if src_node is None:
6266
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6267
        self.op.src_node = None
6268
        if os.path.isabs(src_path):
6269
          raise errors.OpPrereqError("Importing an instance from an absolute"
6270
                                     " path requires a source node option.",
6271
                                     errors.ECODE_INVAL)
6272
      else:
6273
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6274
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6275
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6276
        if not os.path.isabs(src_path):
6277
          self.op.src_path = src_path = \
6278
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6279

    
6280
  def _RunAllocator(self):
6281
    """Run the allocator based on input opcode.
6282

6283
    """
6284
    nics = [n.ToDict() for n in self.nics]
6285
    ial = IAllocator(self.cfg, self.rpc,
6286
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6287
                     name=self.op.instance_name,
6288
                     disk_template=self.op.disk_template,
6289
                     tags=[],
6290
                     os=self.op.os_type,
6291
                     vcpus=self.be_full[constants.BE_VCPUS],
6292
                     mem_size=self.be_full[constants.BE_MEMORY],
6293
                     disks=self.disks,
6294
                     nics=nics,
6295
                     hypervisor=self.op.hypervisor,
6296
                     )
6297

    
6298
    ial.Run(self.op.iallocator)
6299

    
6300
    if not ial.success:
6301
      raise errors.OpPrereqError("Can't compute nodes using"
6302
                                 " iallocator '%s': %s" %
6303
                                 (self.op.iallocator, ial.info),
6304
                                 errors.ECODE_NORES)
6305
    if len(ial.result) != ial.required_nodes:
6306
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6307
                                 " of nodes (%s), required %s" %
6308
                                 (self.op.iallocator, len(ial.result),
6309
                                  ial.required_nodes), errors.ECODE_FAULT)
6310
    self.op.pnode = ial.result[0]
6311
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6312
                 self.op.instance_name, self.op.iallocator,
6313
                 utils.CommaJoin(ial.result))
6314
    if ial.required_nodes == 2:
6315
      self.op.snode = ial.result[1]
6316

    
6317
  def BuildHooksEnv(self):
6318
    """Build hooks env.
6319

6320
    This runs on master, primary and secondary nodes of the instance.
6321

6322
    """
6323
    env = {
6324
      "ADD_MODE": self.op.mode,
6325
      }
6326
    if self.op.mode == constants.INSTANCE_IMPORT:
6327
      env["SRC_NODE"] = self.op.src_node
6328
      env["SRC_PATH"] = self.op.src_path
6329
      env["SRC_IMAGES"] = self.src_images
6330

    
6331
    env.update(_BuildInstanceHookEnv(
6332
      name=self.op.instance_name,
6333
      primary_node=self.op.pnode,
6334
      secondary_nodes=self.secondaries,
6335
      status=self.op.start,
6336
      os_type=self.op.os_type,
6337
      memory=self.be_full[constants.BE_MEMORY],
6338
      vcpus=self.be_full[constants.BE_VCPUS],
6339
      nics=_NICListToTuple(self, self.nics),
6340
      disk_template=self.op.disk_template,
6341
      disks=[(d["size"], d["mode"]) for d in self.disks],
6342
      bep=self.be_full,
6343
      hvp=self.hv_full,
6344
      hypervisor_name=self.op.hypervisor,
6345
    ))
6346

    
6347
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6348
          self.secondaries)
6349
    return env, nl, nl
6350

    
6351
  def _ReadExportInfo(self):
6352
    """Reads the export information from disk.
6353

6354
    It will override the opcode source node and path with the actual
6355
    information, if these two were not specified before.
6356

6357
    @return: the export information
6358

6359
    """
6360
    assert self.op.mode == constants.INSTANCE_IMPORT
6361

    
6362
    src_node = self.op.src_node
6363
    src_path = self.op.src_path
6364

    
6365
    if src_node is None:
6366
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6367
      exp_list = self.rpc.call_export_list(locked_nodes)
6368
      found = False
6369
      for node in exp_list:
6370
        if exp_list[node].fail_msg:
6371
          continue
6372
        if src_path in exp_list[node].payload:
6373
          found = True
6374
          self.op.src_node = src_node = node
6375
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6376
                                                       src_path)
6377
          break
6378
      if not found:
6379
        raise errors.OpPrereqError("No export found for relative path %s" %
6380
                                    src_path, errors.ECODE_INVAL)
6381

    
6382
    _CheckNodeOnline(self, src_node)
6383
    result = self.rpc.call_export_info(src_node, src_path)
6384
    result.Raise("No export or invalid export found in dir %s" % src_path)
6385

    
6386
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6387
    if not export_info.has_section(constants.INISECT_EXP):
6388
      raise errors.ProgrammerError("Corrupted export config",
6389
                                   errors.ECODE_ENVIRON)
6390

    
6391
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6392
    if (int(ei_version) != constants.EXPORT_VERSION):
6393
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6394
                                 (ei_version, constants.EXPORT_VERSION),
6395
                                 errors.ECODE_ENVIRON)
6396
    return export_info
6397

    
6398
  def _ReadExportParams(self, einfo):
6399
    """Use export parameters as defaults.
6400

6401
    In case the opcode doesn't specify (as in override) some instance
6402
    parameters, then try to use them from the export information, if
6403
    that declares them.
6404

6405
    """
6406
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6407

    
6408
    if self.op.disk_template is None:
6409
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6410
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6411
                                          "disk_template")
6412
      else:
6413
        raise errors.OpPrereqError("No disk template specified and the export"
6414
                                   " is missing the disk_template information",
6415
                                   errors.ECODE_INVAL)
6416

    
6417
    if not self.op.disks:
6418
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6419
        disks = []
6420
        # TODO: import the disk iv_name too
6421
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6422
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6423
          disks.append({"size": disk_sz})
6424
        self.op.disks = disks
6425
      else:
6426
        raise errors.OpPrereqError("No disk info specified and the export"
6427
                                   " is missing the disk information",
6428
                                   errors.ECODE_INVAL)
6429

    
6430
    if (not self.op.nics and
6431
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6432
      nics = []
6433
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6434
        ndict = {}
6435
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6436
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6437
          ndict[name] = v
6438
        nics.append(ndict)
6439
      self.op.nics = nics
6440

    
6441
    if (self.op.hypervisor is None and
6442
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6443
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6444
    if einfo.has_section(constants.INISECT_HYP):
6445
      # use the export parameters but do not override the ones
6446
      # specified by the user
6447
      for name, value in einfo.items(constants.INISECT_HYP):
6448
        if name not in self.op.hvparams:
6449
          self.op.hvparams[name] = value
6450

    
6451
    if einfo.has_section(constants.INISECT_BEP):
6452
      # use the parameters, without overriding
6453
      for name, value in einfo.items(constants.INISECT_BEP):
6454
        if name not in self.op.beparams:
6455
          self.op.beparams[name] = value
6456
    else:
6457
      # try to read the parameters old style, from the main section
6458
      for name in constants.BES_PARAMETERS:
6459
        if (name not in self.op.beparams and
6460
            einfo.has_option(constants.INISECT_INS, name)):
6461
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6462

    
6463
  def _RevertToDefaults(self, cluster):
6464
    """Revert the instance parameters to the default values.
6465

6466
    """
6467
    # hvparams
6468
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6469
    for name in self.op.hvparams.keys():
6470
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6471
        del self.op.hvparams[name]
6472
    # beparams
6473
    be_defs = cluster.SimpleFillBE({})
6474
    for name in self.op.beparams.keys():
6475
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6476
        del self.op.beparams[name]
6477
    # nic params
6478
    nic_defs = cluster.SimpleFillNIC({})
6479
    for nic in self.op.nics:
6480
      for name in constants.NICS_PARAMETERS:
6481
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6482
          del nic[name]
6483

    
6484
  def CheckPrereq(self):
6485
    """Check prerequisites.
6486

6487
    """
6488
    if self.op.mode == constants.INSTANCE_IMPORT:
6489
      export_info = self._ReadExportInfo()
6490
      self._ReadExportParams(export_info)
6491

    
6492
    _CheckDiskTemplate(self.op.disk_template)
6493

    
6494
    if (not self.cfg.GetVGName() and
6495
        self.op.disk_template not in constants.DTS_NOT_LVM):
6496
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6497
                                 " instances", errors.ECODE_STATE)
6498

    
6499
    if self.op.hypervisor is None:
6500
      self.op.hypervisor = self.cfg.GetHypervisorType()
6501

    
6502
    cluster = self.cfg.GetClusterInfo()
6503
    enabled_hvs = cluster.enabled_hypervisors
6504
    if self.op.hypervisor not in enabled_hvs:
6505
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6506
                                 " cluster (%s)" % (self.op.hypervisor,
6507
                                  ",".join(enabled_hvs)),
6508
                                 errors.ECODE_STATE)
6509

    
6510
    # check hypervisor parameter syntax (locally)
6511
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6512
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6513
                                      self.op.hvparams)
6514
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6515
    hv_type.CheckParameterSyntax(filled_hvp)
6516
    self.hv_full = filled_hvp
6517
    # check that we don't specify global parameters on an instance
6518
    _CheckGlobalHvParams(self.op.hvparams)
6519

    
6520
    # fill and remember the beparams dict
6521
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6522
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6523

    
6524
    # now that hvp/bep are in final format, let's reset to defaults,
6525
    # if told to do so
6526
    if self.op.identify_defaults:
6527
      self._RevertToDefaults(cluster)
6528

    
6529
    # NIC buildup
6530
    self.nics = []
6531
    for idx, nic in enumerate(self.op.nics):
6532
      nic_mode_req = nic.get("mode", None)
6533
      nic_mode = nic_mode_req
6534
      if nic_mode is None:
6535
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6536

    
6537
      # in routed mode, for the first nic, the default ip is 'auto'
6538
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6539
        default_ip_mode = constants.VALUE_AUTO
6540
      else:
6541
        default_ip_mode = constants.VALUE_NONE
6542

    
6543
      # ip validity checks
6544
      ip = nic.get("ip", default_ip_mode)
6545
      if ip is None or ip.lower() == constants.VALUE_NONE:
6546
        nic_ip = None
6547
      elif ip.lower() == constants.VALUE_AUTO:
6548
        if not self.op.name_check:
6549
          raise errors.OpPrereqError("IP address set to auto but name checks"
6550
                                     " have been skipped. Aborting.",
6551
                                     errors.ECODE_INVAL)
6552
        nic_ip = self.hostname1.ip
6553
      else:
6554
        if not utils.IsValidIP(ip):
6555
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6556
                                     " like a valid IP" % ip,
6557
                                     errors.ECODE_INVAL)
6558
        nic_ip = ip
6559

    
6560
      # TODO: check the ip address for uniqueness
6561
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6562
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6563
                                   errors.ECODE_INVAL)
6564

    
6565
      # MAC address verification
6566
      mac = nic.get("mac", constants.VALUE_AUTO)
6567
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6568
        mac = utils.NormalizeAndValidateMac(mac)
6569

    
6570
        try:
6571
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
6572
        except errors.ReservationError:
6573
          raise errors.OpPrereqError("MAC address %s already in use"
6574
                                     " in cluster" % mac,
6575
                                     errors.ECODE_NOTUNIQUE)
6576

    
6577
      # bridge verification
6578
      bridge = nic.get("bridge", None)
6579
      link = nic.get("link", None)
6580
      if bridge and link:
6581
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
6582
                                   " at the same time", errors.ECODE_INVAL)
6583
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
6584
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
6585
                                   errors.ECODE_INVAL)
6586
      elif bridge:
6587
        link = bridge
6588

    
6589
      nicparams = {}
6590
      if nic_mode_req:
6591
        nicparams[constants.NIC_MODE] = nic_mode_req
6592
      if link:
6593
        nicparams[constants.NIC_LINK] = link
6594

    
6595
      check_params = cluster.SimpleFillNIC(nicparams)
6596
      objects.NIC.CheckParameterSyntax(check_params)
6597
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
6598

    
6599
    # disk checks/pre-build
6600
    self.disks = []
6601
    for disk in self.op.disks:
6602
      mode = disk.get("mode", constants.DISK_RDWR)
6603
      if mode not in constants.DISK_ACCESS_SET:
6604
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
6605
                                   mode, errors.ECODE_INVAL)
6606
      size = disk.get("size", None)
6607
      if size is None:
6608
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
6609
      try:
6610
        size = int(size)
6611
      except (TypeError, ValueError):
6612
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
6613
                                   errors.ECODE_INVAL)
6614
      new_disk = {"size": size, "mode": mode}
6615
      if "adopt" in disk:
6616
        new_disk["adopt"] = disk["adopt"]
6617
      self.disks.append(new_disk)
6618

    
6619
    if self.op.mode == constants.INSTANCE_IMPORT:
6620

    
6621
      # Check that the new instance doesn't have less disks than the export
6622
      instance_disks = len(self.disks)
6623
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6624
      if instance_disks < export_disks:
6625
        raise errors.OpPrereqError("Not enough disks to import."
6626
                                   " (instance: %d, export: %d)" %
6627
                                   (instance_disks, export_disks),
6628
                                   errors.ECODE_INVAL)
6629

    
6630
      disk_images = []
6631
      for idx in range(export_disks):
6632
        option = 'disk%d_dump' % idx
6633
        if export_info.has_option(constants.INISECT_INS, option):
6634
          # FIXME: are the old os-es, disk sizes, etc. useful?
6635
          export_name = export_info.get(constants.INISECT_INS, option)
6636
          image = utils.PathJoin(self.op.src_path, export_name)
6637
          disk_images.append(image)
6638
        else:
6639
          disk_images.append(False)
6640

    
6641
      self.src_images = disk_images
6642

    
6643
      old_name = export_info.get(constants.INISECT_INS, 'name')
6644
      try:
6645
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
6646
      except (TypeError, ValueError), err:
6647
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
6648
                                   " an integer: %s" % str(err),
6649
                                   errors.ECODE_STATE)
6650
      if self.op.instance_name == old_name:
6651
        for idx, nic in enumerate(self.nics):
6652
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
6653
            nic_mac_ini = 'nic%d_mac' % idx
6654
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
6655

    
6656
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
6657

    
6658
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
6659
    if self.op.ip_check:
6660
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
6661
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6662
                                   (self.check_ip, self.op.instance_name),
6663
                                   errors.ECODE_NOTUNIQUE)
6664

    
6665
    #### mac address generation
6666
    # By generating here the mac address both the allocator and the hooks get
6667
    # the real final mac address rather than the 'auto' or 'generate' value.
6668
    # There is a race condition between the generation and the instance object
6669
    # creation, which means that we know the mac is valid now, but we're not
6670
    # sure it will be when we actually add the instance. If things go bad
6671
    # adding the instance will abort because of a duplicate mac, and the
6672
    # creation job will fail.
6673
    for nic in self.nics:
6674
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6675
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
6676

    
6677
    #### allocator run
6678

    
6679
    if self.op.iallocator is not None:
6680
      self._RunAllocator()
6681

    
6682
    #### node related checks
6683

    
6684
    # check primary node
6685
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
6686
    assert self.pnode is not None, \
6687
      "Cannot retrieve locked node %s" % self.op.pnode
6688
    if pnode.offline:
6689
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
6690
                                 pnode.name, errors.ECODE_STATE)
6691
    if pnode.drained:
6692
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
6693
                                 pnode.name, errors.ECODE_STATE)
6694

    
6695
    self.secondaries = []
6696

    
6697
    # mirror node verification
6698
    if self.op.disk_template in constants.DTS_NET_MIRROR:
6699
      if self.op.snode is None:
6700
        raise errors.OpPrereqError("The networked disk templates need"
6701
                                   " a mirror node", errors.ECODE_INVAL)
6702
      if self.op.snode == pnode.name:
6703
        raise errors.OpPrereqError("The secondary node cannot be the"
6704
                                   " primary node.", errors.ECODE_INVAL)
6705
      _CheckNodeOnline(self, self.op.snode)
6706
      _CheckNodeNotDrained(self, self.op.snode)
6707
      self.secondaries.append(self.op.snode)
6708

    
6709
    nodenames = [pnode.name] + self.secondaries
6710

    
6711
    req_size = _ComputeDiskSize(self.op.disk_template,
6712
                                self.disks)
6713

    
6714
    # Check lv size requirements, if not adopting
6715
    if req_size is not None and not self.adopt_disks:
6716
      _CheckNodesFreeDisk(self, nodenames, req_size)
6717

    
6718
    if self.adopt_disks: # instead, we must check the adoption data
6719
      all_lvs = set([i["adopt"] for i in self.disks])
6720
      if len(all_lvs) != len(self.disks):
6721
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
6722
                                   errors.ECODE_INVAL)
6723
      for lv_name in all_lvs:
6724
        try:
6725
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
6726
        except errors.ReservationError:
6727
          raise errors.OpPrereqError("LV named %s used by another instance" %
6728
                                     lv_name, errors.ECODE_NOTUNIQUE)
6729

    
6730
      node_lvs = self.rpc.call_lv_list([pnode.name],
6731
                                       self.cfg.GetVGName())[pnode.name]
6732
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
6733
      node_lvs = node_lvs.payload
6734
      delta = all_lvs.difference(node_lvs.keys())
6735
      if delta:
6736
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
6737
                                   utils.CommaJoin(delta),
6738
                                   errors.ECODE_INVAL)
6739
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
6740
      if online_lvs:
6741
        raise errors.OpPrereqError("Online logical volumes found, cannot"
6742
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
6743
                                   errors.ECODE_STATE)
6744
      # update the size of disk based on what is found
6745
      for dsk in self.disks:
6746
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
6747

    
6748
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
6749

    
6750
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
6751

    
6752
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
6753

    
6754
    # memory check on primary node
6755
    if self.op.start:
6756
      _CheckNodeFreeMemory(self, self.pnode.name,
6757
                           "creating instance %s" % self.op.instance_name,
6758
                           self.be_full[constants.BE_MEMORY],
6759
                           self.op.hypervisor)
6760

    
6761
    self.dry_run_result = list(nodenames)
6762

    
6763
  def Exec(self, feedback_fn):
6764
    """Create and add the instance to the cluster.
6765

6766
    """
6767
    instance = self.op.instance_name
6768
    pnode_name = self.pnode.name
6769

    
6770
    ht_kind = self.op.hypervisor
6771
    if ht_kind in constants.HTS_REQ_PORT:
6772
      network_port = self.cfg.AllocatePort()
6773
    else:
6774
      network_port = None
6775

    
6776
    if constants.ENABLE_FILE_STORAGE:
6777
      # this is needed because os.path.join does not accept None arguments
6778
      if self.op.file_storage_dir is None:
6779
        string_file_storage_dir = ""
6780
      else:
6781
        string_file_storage_dir = self.op.file_storage_dir
6782

    
6783
      # build the full file storage dir path
6784
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
6785
                                        string_file_storage_dir, instance)
6786
    else:
6787
      file_storage_dir = ""
6788

    
6789
    disks = _GenerateDiskTemplate(self,
6790
                                  self.op.disk_template,
6791
                                  instance, pnode_name,
6792
                                  self.secondaries,
6793
                                  self.disks,
6794
                                  file_storage_dir,
6795
                                  self.op.file_driver,
6796
                                  0)
6797

    
6798
    iobj = objects.Instance(name=instance, os=self.op.os_type,
6799
                            primary_node=pnode_name,
6800
                            nics=self.nics, disks=disks,
6801
                            disk_template=self.op.disk_template,
6802
                            admin_up=False,
6803
                            network_port=network_port,
6804
                            beparams=self.op.beparams,
6805
                            hvparams=self.op.hvparams,
6806
                            hypervisor=self.op.hypervisor,
6807
                            )
6808

    
6809
    if self.adopt_disks:
6810
      # rename LVs to the newly-generated names; we need to construct
6811
      # 'fake' LV disks with the old data, plus the new unique_id
6812
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
6813
      rename_to = []
6814
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
6815
        rename_to.append(t_dsk.logical_id)
6816
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
6817
        self.cfg.SetDiskID(t_dsk, pnode_name)
6818
      result = self.rpc.call_blockdev_rename(pnode_name,
6819
                                             zip(tmp_disks, rename_to))
6820
      result.Raise("Failed to rename adoped LVs")
6821
    else:
6822
      feedback_fn("* creating instance disks...")
6823
      try:
6824
        _CreateDisks(self, iobj)
6825
      except errors.OpExecError:
6826
        self.LogWarning("Device creation failed, reverting...")
6827
        try:
6828
          _RemoveDisks(self, iobj)
6829
        finally:
6830
          self.cfg.ReleaseDRBDMinors(instance)
6831
          raise
6832

    
6833
    feedback_fn("adding instance %s to cluster config" % instance)
6834

    
6835
    self.cfg.AddInstance(iobj, self.proc.GetECId())
6836

    
6837
    # Declare that we don't want to remove the instance lock anymore, as we've
6838
    # added the instance to the config
6839
    del self.remove_locks[locking.LEVEL_INSTANCE]
6840
    # Unlock all the nodes
6841
    if self.op.mode == constants.INSTANCE_IMPORT:
6842
      nodes_keep = [self.op.src_node]
6843
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
6844
                       if node != self.op.src_node]
6845
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
6846
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6847
    else:
6848
      self.context.glm.release(locking.LEVEL_NODE)
6849
      del self.acquired_locks[locking.LEVEL_NODE]
6850

    
6851
    if self.op.wait_for_sync:
6852
      disk_abort = not _WaitForSync(self, iobj)
6853
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
6854
      # make sure the disks are not degraded (still sync-ing is ok)
6855
      time.sleep(15)
6856
      feedback_fn("* checking mirrors status")
6857
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
6858
    else:
6859
      disk_abort = False
6860

    
6861
    if disk_abort:
6862
      _RemoveDisks(self, iobj)
6863
      self.cfg.RemoveInstance(iobj.name)
6864
      # Make sure the instance lock gets removed
6865
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
6866
      raise errors.OpExecError("There are some degraded disks for"
6867
                               " this instance")
6868

    
6869
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
6870
      if self.op.mode == constants.INSTANCE_CREATE:
6871
        if not self.op.no_install:
6872
          feedback_fn("* running the instance OS create scripts...")
6873
          # FIXME: pass debug option from opcode to backend
6874
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
6875
                                                 self.op.debug_level)
6876
          result.Raise("Could not add os for instance %s"
6877
                       " on node %s" % (instance, pnode_name))
6878

    
6879
      elif self.op.mode == constants.INSTANCE_IMPORT:
6880
        feedback_fn("* running the instance OS import scripts...")
6881

    
6882
        transfers = []
6883

    
6884
        for idx, image in enumerate(self.src_images):
6885
          if not image:
6886
            continue
6887

    
6888
          # FIXME: pass debug option from opcode to backend
6889
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
6890
                                             constants.IEIO_FILE, (image, ),
6891
                                             constants.IEIO_SCRIPT,
6892
                                             (iobj.disks[idx], idx),
6893
                                             None)
6894
          transfers.append(dt)
6895

    
6896
        import_result = \
6897
          masterd.instance.TransferInstanceData(self, feedback_fn,
6898
                                                self.op.src_node, pnode_name,
6899
                                                self.pnode.secondary_ip,
6900
                                                iobj, transfers)
6901
        if not compat.all(import_result):
6902
          self.LogWarning("Some disks for instance %s on node %s were not"
6903
                          " imported successfully" % (instance, pnode_name))
6904

    
6905
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6906
        feedback_fn("* preparing remote import...")
6907
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
6908
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
6909

    
6910
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
6911
                                                     self.source_x509_ca,
6912
                                                     self._cds, timeouts)
6913
        if not compat.all(disk_results):
6914
          # TODO: Should the instance still be started, even if some disks
6915
          # failed to import (valid for local imports, too)?
6916
          self.LogWarning("Some disks for instance %s on node %s were not"
6917
                          " imported successfully" % (instance, pnode_name))
6918

    
6919
        # Run rename script on newly imported instance
6920
        assert iobj.name == instance
6921
        feedback_fn("Running rename script for %s" % instance)
6922
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
6923
                                                   self.source_instance_name,
6924
                                                   self.op.debug_level)
6925
        if result.fail_msg:
6926
          self.LogWarning("Failed to run rename script for %s on node"
6927
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
6928

    
6929
      else:
6930
        # also checked in the prereq part
6931
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
6932
                                     % self.op.mode)
6933

    
6934
    if self.op.start:
6935
      iobj.admin_up = True
6936
      self.cfg.Update(iobj, feedback_fn)
6937
      logging.info("Starting instance %s on node %s", instance, pnode_name)
6938
      feedback_fn("* starting instance...")
6939
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
6940
      result.Raise("Could not start instance")
6941

    
6942
    return list(iobj.all_nodes)
6943

    
6944

    
6945
class LUConnectConsole(NoHooksLU):
6946
  """Connect to an instance's console.
6947

6948
  This is somewhat special in that it returns the command line that
6949
  you need to run on the master node in order to connect to the
6950
  console.
6951

6952
  """
6953
  _OP_REQP = ["instance_name"]
6954
  REQ_BGL = False
6955

    
6956
  def ExpandNames(self):
6957
    self._ExpandAndLockInstance()
6958

    
6959
  def CheckPrereq(self):
6960
    """Check prerequisites.
6961

6962
    This checks that the instance is in the cluster.
6963

6964
    """
6965
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6966
    assert self.instance is not None, \
6967
      "Cannot retrieve locked instance %s" % self.op.instance_name
6968
    _CheckNodeOnline(self, self.instance.primary_node)
6969

    
6970
  def Exec(self, feedback_fn):
6971
    """Connect to the console of an instance
6972

6973
    """
6974
    instance = self.instance
6975
    node = instance.primary_node
6976

    
6977
    node_insts = self.rpc.call_instance_list([node],
6978
                                             [instance.hypervisor])[node]
6979
    node_insts.Raise("Can't get node information from %s" % node)
6980

    
6981
    if instance.name not in node_insts.payload:
6982
      raise errors.OpExecError("Instance %s is not running." % instance.name)
6983

    
6984
    logging.debug("Connecting to console of %s on %s", instance.name, node)
6985

    
6986
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6987
    cluster = self.cfg.GetClusterInfo()
6988
    # beparams and hvparams are passed separately, to avoid editing the
6989
    # instance and then saving the defaults in the instance itself.
6990
    hvparams = cluster.FillHV(instance)
6991
    beparams = cluster.FillBE(instance)
6992
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6993

    
6994
    # build ssh cmdline
6995
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6996

    
6997

    
6998
class LUReplaceDisks(LogicalUnit):
6999
  """Replace the disks of an instance.
7000

7001
  """
7002
  HPATH = "mirrors-replace"
7003
  HTYPE = constants.HTYPE_INSTANCE
7004
  _OP_REQP = ["instance_name", "mode", "disks"]
7005
  REQ_BGL = False
7006

    
7007
  def CheckArguments(self):
7008
    if not hasattr(self.op, "remote_node"):
7009
      self.op.remote_node = None
7010
    if not hasattr(self.op, "iallocator"):
7011
      self.op.iallocator = None
7012
    if not hasattr(self.op, "early_release"):
7013
      self.op.early_release = False
7014

    
7015
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7016
                                  self.op.iallocator)
7017

    
7018
  def ExpandNames(self):
7019
    self._ExpandAndLockInstance()
7020

    
7021
    if self.op.iallocator is not None:
7022
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7023

    
7024
    elif self.op.remote_node is not None:
7025
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7026
      self.op.remote_node = remote_node
7027

    
7028
      # Warning: do not remove the locking of the new secondary here
7029
      # unless DRBD8.AddChildren is changed to work in parallel;
7030
      # currently it doesn't since parallel invocations of
7031
      # FindUnusedMinor will conflict
7032
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7033
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7034

    
7035
    else:
7036
      self.needed_locks[locking.LEVEL_NODE] = []
7037
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7038

    
7039
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7040
                                   self.op.iallocator, self.op.remote_node,
7041
                                   self.op.disks, False, self.op.early_release)
7042

    
7043
    self.tasklets = [self.replacer]
7044

    
7045
  def DeclareLocks(self, level):
7046
    # If we're not already locking all nodes in the set we have to declare the
7047
    # instance's primary/secondary nodes.
7048
    if (level == locking.LEVEL_NODE and
7049
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7050
      self._LockInstancesNodes()
7051

    
7052
  def BuildHooksEnv(self):
7053
    """Build hooks env.
7054

7055
    This runs on the master, the primary and all the secondaries.
7056

7057
    """
7058
    instance = self.replacer.instance
7059
    env = {
7060
      "MODE": self.op.mode,
7061
      "NEW_SECONDARY": self.op.remote_node,
7062
      "OLD_SECONDARY": instance.secondary_nodes[0],
7063
      }
7064
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7065
    nl = [
7066
      self.cfg.GetMasterNode(),
7067
      instance.primary_node,
7068
      ]
7069
    if self.op.remote_node is not None:
7070
      nl.append(self.op.remote_node)
7071
    return env, nl, nl
7072

    
7073

    
7074
class LUEvacuateNode(LogicalUnit):
7075
  """Relocate the secondary instances from a node.
7076

7077
  """
7078
  HPATH = "node-evacuate"
7079
  HTYPE = constants.HTYPE_NODE
7080
  _OP_REQP = ["node_name"]
7081
  REQ_BGL = False
7082

    
7083
  def CheckArguments(self):
7084
    if not hasattr(self.op, "remote_node"):
7085
      self.op.remote_node = None
7086
    if not hasattr(self.op, "iallocator"):
7087
      self.op.iallocator = None
7088
    if not hasattr(self.op, "early_release"):
7089
      self.op.early_release = False
7090

    
7091
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
7092
                                  self.op.remote_node,
7093
                                  self.op.iallocator)
7094

    
7095
  def ExpandNames(self):
7096
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
7097

    
7098
    self.needed_locks = {}
7099

    
7100
    # Declare node locks
7101
    if self.op.iallocator is not None:
7102
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7103

    
7104
    elif self.op.remote_node is not None:
7105
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7106

    
7107
      # Warning: do not remove the locking of the new secondary here
7108
      # unless DRBD8.AddChildren is changed to work in parallel;
7109
      # currently it doesn't since parallel invocations of
7110
      # FindUnusedMinor will conflict
7111
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
7112
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7113

    
7114
    else:
7115
      raise errors.OpPrereqError("Invalid parameters", errors.ECODE_INVAL)
7116

    
7117
    # Create tasklets for replacing disks for all secondary instances on this
7118
    # node
7119
    names = []
7120
    tasklets = []
7121

    
7122
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
7123
      logging.debug("Replacing disks for instance %s", inst.name)
7124
      names.append(inst.name)
7125

    
7126
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
7127
                                self.op.iallocator, self.op.remote_node, [],
7128
                                True, self.op.early_release)
7129
      tasklets.append(replacer)
7130

    
7131
    self.tasklets = tasklets
7132
    self.instance_names = names
7133

    
7134
    # Declare instance locks
7135
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
7136

    
7137
  def DeclareLocks(self, level):
7138
    # If we're not already locking all nodes in the set we have to declare the
7139
    # instance's primary/secondary nodes.
7140
    if (level == locking.LEVEL_NODE and
7141
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7142
      self._LockInstancesNodes()
7143

    
7144
  def BuildHooksEnv(self):
7145
    """Build hooks env.
7146

7147
    This runs on the master, the primary and all the secondaries.
7148

7149
    """
7150
    env = {
7151
      "NODE_NAME": self.op.node_name,
7152
      }
7153

    
7154
    nl = [self.cfg.GetMasterNode()]
7155

    
7156
    if self.op.remote_node is not None:
7157
      env["NEW_SECONDARY"] = self.op.remote_node
7158
      nl.append(self.op.remote_node)
7159

    
7160
    return (env, nl, nl)
7161

    
7162

    
7163
class TLReplaceDisks(Tasklet):
7164
  """Replaces disks for an instance.
7165

7166
  Note: Locking is not within the scope of this class.
7167

7168
  """
7169
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7170
               disks, delay_iallocator, early_release):
7171
    """Initializes this class.
7172

7173
    """
7174
    Tasklet.__init__(self, lu)
7175

    
7176
    # Parameters
7177
    self.instance_name = instance_name
7178
    self.mode = mode
7179
    self.iallocator_name = iallocator_name
7180
    self.remote_node = remote_node
7181
    self.disks = disks
7182
    self.delay_iallocator = delay_iallocator
7183
    self.early_release = early_release
7184

    
7185
    # Runtime data
7186
    self.instance = None
7187
    self.new_node = None
7188
    self.target_node = None
7189
    self.other_node = None
7190
    self.remote_node_info = None
7191
    self.node_secondary_ip = None
7192

    
7193
  @staticmethod
7194
  def CheckArguments(mode, remote_node, iallocator):
7195
    """Helper function for users of this class.
7196

7197
    """
7198
    # check for valid parameter combination
7199
    if mode == constants.REPLACE_DISK_CHG:
7200
      if remote_node is None and iallocator is None:
7201
        raise errors.OpPrereqError("When changing the secondary either an"
7202
                                   " iallocator script must be used or the"
7203
                                   " new node given", errors.ECODE_INVAL)
7204

    
7205
      if remote_node is not None and iallocator is not None:
7206
        raise errors.OpPrereqError("Give either the iallocator or the new"
7207
                                   " secondary, not both", errors.ECODE_INVAL)
7208

    
7209
    elif remote_node is not None or iallocator is not None:
7210
      # Not replacing the secondary
7211
      raise errors.OpPrereqError("The iallocator and new node options can"
7212
                                 " only be used when changing the"
7213
                                 " secondary node", errors.ECODE_INVAL)
7214

    
7215
  @staticmethod
7216
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7217
    """Compute a new secondary node using an IAllocator.
7218

7219
    """
7220
    ial = IAllocator(lu.cfg, lu.rpc,
7221
                     mode=constants.IALLOCATOR_MODE_RELOC,
7222
                     name=instance_name,
7223
                     relocate_from=relocate_from)
7224

    
7225
    ial.Run(iallocator_name)
7226

    
7227
    if not ial.success:
7228
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7229
                                 " %s" % (iallocator_name, ial.info),
7230
                                 errors.ECODE_NORES)
7231

    
7232
    if len(ial.result) != ial.required_nodes:
7233
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7234
                                 " of nodes (%s), required %s" %
7235
                                 (iallocator_name,
7236
                                  len(ial.result), ial.required_nodes),
7237
                                 errors.ECODE_FAULT)
7238

    
7239
    remote_node_name = ial.result[0]
7240

    
7241
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7242
               instance_name, remote_node_name)
7243

    
7244
    return remote_node_name
7245

    
7246
  def _FindFaultyDisks(self, node_name):
7247
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7248
                                    node_name, True)
7249

    
7250
  def CheckPrereq(self):
7251
    """Check prerequisites.
7252

7253
    This checks that the instance is in the cluster.
7254

7255
    """
7256
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7257
    assert instance is not None, \
7258
      "Cannot retrieve locked instance %s" % self.instance_name
7259

    
7260
    if instance.disk_template != constants.DT_DRBD8:
7261
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7262
                                 " instances", errors.ECODE_INVAL)
7263

    
7264
    if len(instance.secondary_nodes) != 1:
7265
      raise errors.OpPrereqError("The instance has a strange layout,"
7266
                                 " expected one secondary but found %d" %
7267
                                 len(instance.secondary_nodes),
7268
                                 errors.ECODE_FAULT)
7269

    
7270
    if not self.delay_iallocator:
7271
      self._CheckPrereq2()
7272

    
7273
  def _CheckPrereq2(self):
7274
    """Check prerequisites, second part.
7275

7276
    This function should always be part of CheckPrereq. It was separated and is
7277
    now called from Exec because during node evacuation iallocator was only
7278
    called with an unmodified cluster model, not taking planned changes into
7279
    account.
7280

7281
    """
7282
    instance = self.instance
7283
    secondary_node = instance.secondary_nodes[0]
7284

    
7285
    if self.iallocator_name is None:
7286
      remote_node = self.remote_node
7287
    else:
7288
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7289
                                       instance.name, instance.secondary_nodes)
7290

    
7291
    if remote_node is not None:
7292
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7293
      assert self.remote_node_info is not None, \
7294
        "Cannot retrieve locked node %s" % remote_node
7295
    else:
7296
      self.remote_node_info = None
7297

    
7298
    if remote_node == self.instance.primary_node:
7299
      raise errors.OpPrereqError("The specified node is the primary node of"
7300
                                 " the instance.", errors.ECODE_INVAL)
7301

    
7302
    if remote_node == secondary_node:
7303
      raise errors.OpPrereqError("The specified node is already the"
7304
                                 " secondary node of the instance.",
7305
                                 errors.ECODE_INVAL)
7306

    
7307
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7308
                                    constants.REPLACE_DISK_CHG):
7309
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7310
                                 errors.ECODE_INVAL)
7311

    
7312
    if self.mode == constants.REPLACE_DISK_AUTO:
7313
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7314
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7315

    
7316
      if faulty_primary and faulty_secondary:
7317
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7318
                                   " one node and can not be repaired"
7319
                                   " automatically" % self.instance_name,
7320
                                   errors.ECODE_STATE)
7321

    
7322
      if faulty_primary:
7323
        self.disks = faulty_primary
7324
        self.target_node = instance.primary_node
7325
        self.other_node = secondary_node
7326
        check_nodes = [self.target_node, self.other_node]
7327
      elif faulty_secondary:
7328
        self.disks = faulty_secondary
7329
        self.target_node = secondary_node
7330
        self.other_node = instance.primary_node
7331
        check_nodes = [self.target_node, self.other_node]
7332
      else:
7333
        self.disks = []
7334
        check_nodes = []
7335

    
7336
    else:
7337
      # Non-automatic modes
7338
      if self.mode == constants.REPLACE_DISK_PRI:
7339
        self.target_node = instance.primary_node
7340
        self.other_node = secondary_node
7341
        check_nodes = [self.target_node, self.other_node]
7342

    
7343
      elif self.mode == constants.REPLACE_DISK_SEC:
7344
        self.target_node = secondary_node
7345
        self.other_node = instance.primary_node
7346
        check_nodes = [self.target_node, self.other_node]
7347

    
7348
      elif self.mode == constants.REPLACE_DISK_CHG:
7349
        self.new_node = remote_node
7350
        self.other_node = instance.primary_node
7351
        self.target_node = secondary_node
7352
        check_nodes = [self.new_node, self.other_node]
7353

    
7354
        _CheckNodeNotDrained(self.lu, remote_node)
7355

    
7356
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7357
        assert old_node_info is not None
7358
        if old_node_info.offline and not self.early_release:
7359
          # doesn't make sense to delay the release
7360
          self.early_release = True
7361
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7362
                          " early-release mode", secondary_node)
7363

    
7364
      else:
7365
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7366
                                     self.mode)
7367

    
7368
      # If not specified all disks should be replaced
7369
      if not self.disks:
7370
        self.disks = range(len(self.instance.disks))
7371

    
7372
    for node in check_nodes:
7373
      _CheckNodeOnline(self.lu, node)
7374

    
7375
    # Check whether disks are valid
7376
    for disk_idx in self.disks:
7377
      instance.FindDisk(disk_idx)
7378

    
7379
    # Get secondary node IP addresses
7380
    node_2nd_ip = {}
7381

    
7382
    for node_name in [self.target_node, self.other_node, self.new_node]:
7383
      if node_name is not None:
7384
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7385

    
7386
    self.node_secondary_ip = node_2nd_ip
7387

    
7388
  def Exec(self, feedback_fn):
7389
    """Execute disk replacement.
7390

7391
    This dispatches the disk replacement to the appropriate handler.
7392

7393
    """
7394
    if self.delay_iallocator:
7395
      self._CheckPrereq2()
7396

    
7397
    if not self.disks:
7398
      feedback_fn("No disks need replacement")
7399
      return
7400

    
7401
    feedback_fn("Replacing disk(s) %s for %s" %
7402
                (utils.CommaJoin(self.disks), self.instance.name))
7403

    
7404
    activate_disks = (not self.instance.admin_up)
7405

    
7406
    # Activate the instance disks if we're replacing them on a down instance
7407
    if activate_disks:
7408
      _StartInstanceDisks(self.lu, self.instance, True)
7409

    
7410
    try:
7411
      # Should we replace the secondary node?
7412
      if self.new_node is not None:
7413
        fn = self._ExecDrbd8Secondary
7414
      else:
7415
        fn = self._ExecDrbd8DiskOnly
7416

    
7417
      return fn(feedback_fn)
7418

    
7419
    finally:
7420
      # Deactivate the instance disks if we're replacing them on a
7421
      # down instance
7422
      if activate_disks:
7423
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7424

    
7425
  def _CheckVolumeGroup(self, nodes):
7426
    self.lu.LogInfo("Checking volume groups")
7427

    
7428
    vgname = self.cfg.GetVGName()
7429

    
7430
    # Make sure volume group exists on all involved nodes
7431
    results = self.rpc.call_vg_list(nodes)
7432
    if not results:
7433
      raise errors.OpExecError("Can't list volume groups on the nodes")
7434

    
7435
    for node in nodes:
7436
      res = results[node]
7437
      res.Raise("Error checking node %s" % node)
7438
      if vgname not in res.payload:
7439
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7440
                                 (vgname, node))
7441

    
7442
  def _CheckDisksExistence(self, nodes):
7443
    # Check disk existence
7444
    for idx, dev in enumerate(self.instance.disks):
7445
      if idx not in self.disks:
7446
        continue
7447

    
7448
      for node in nodes:
7449
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7450
        self.cfg.SetDiskID(dev, node)
7451

    
7452
        result = self.rpc.call_blockdev_find(node, dev)
7453

    
7454
        msg = result.fail_msg
7455
        if msg or not result.payload:
7456
          if not msg:
7457
            msg = "disk not found"
7458
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7459
                                   (idx, node, msg))
7460

    
7461
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7462
    for idx, dev in enumerate(self.instance.disks):
7463
      if idx not in self.disks:
7464
        continue
7465

    
7466
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7467
                      (idx, node_name))
7468

    
7469
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7470
                                   ldisk=ldisk):
7471
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7472
                                 " replace disks for instance %s" %
7473
                                 (node_name, self.instance.name))
7474

    
7475
  def _CreateNewStorage(self, node_name):
7476
    vgname = self.cfg.GetVGName()
7477
    iv_names = {}
7478

    
7479
    for idx, dev in enumerate(self.instance.disks):
7480
      if idx not in self.disks:
7481
        continue
7482

    
7483
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7484

    
7485
      self.cfg.SetDiskID(dev, node_name)
7486

    
7487
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7488
      names = _GenerateUniqueNames(self.lu, lv_names)
7489

    
7490
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7491
                             logical_id=(vgname, names[0]))
7492
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7493
                             logical_id=(vgname, names[1]))
7494

    
7495
      new_lvs = [lv_data, lv_meta]
7496
      old_lvs = dev.children
7497
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7498

    
7499
      # we pass force_create=True to force the LVM creation
7500
      for new_lv in new_lvs:
7501
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7502
                        _GetInstanceInfoText(self.instance), False)
7503

    
7504
    return iv_names
7505

    
7506
  def _CheckDevices(self, node_name, iv_names):
7507
    for name, (dev, _, _) in iv_names.iteritems():
7508
      self.cfg.SetDiskID(dev, node_name)
7509

    
7510
      result = self.rpc.call_blockdev_find(node_name, dev)
7511

    
7512
      msg = result.fail_msg
7513
      if msg or not result.payload:
7514
        if not msg:
7515
          msg = "disk not found"
7516
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7517
                                 (name, msg))
7518

    
7519
      if result.payload.is_degraded:
7520
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7521

    
7522
  def _RemoveOldStorage(self, node_name, iv_names):
7523
    for name, (_, old_lvs, _) in iv_names.iteritems():
7524
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7525

    
7526
      for lv in old_lvs:
7527
        self.cfg.SetDiskID(lv, node_name)
7528

    
7529
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7530
        if msg:
7531
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7532
                             hint="remove unused LVs manually")
7533

    
7534
  def _ReleaseNodeLock(self, node_name):
7535
    """Releases the lock for a given node."""
7536
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7537

    
7538
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7539
    """Replace a disk on the primary or secondary for DRBD 8.
7540

7541
    The algorithm for replace is quite complicated:
7542

7543
      1. for each disk to be replaced:
7544

7545
        1. create new LVs on the target node with unique names
7546
        1. detach old LVs from the drbd device
7547
        1. rename old LVs to name_replaced.<time_t>
7548
        1. rename new LVs to old LVs
7549
        1. attach the new LVs (with the old names now) to the drbd device
7550

7551
      1. wait for sync across all devices
7552

7553
      1. for each modified disk:
7554

7555
        1. remove old LVs (which have the name name_replaces.<time_t>)
7556

7557
    Failures are not very well handled.
7558

7559
    """
7560
    steps_total = 6
7561

    
7562
    # Step: check device activation
7563
    self.lu.LogStep(1, steps_total, "Check device existence")
7564
    self._CheckDisksExistence([self.other_node, self.target_node])
7565
    self._CheckVolumeGroup([self.target_node, self.other_node])
7566

    
7567
    # Step: check other node consistency
7568
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7569
    self._CheckDisksConsistency(self.other_node,
7570
                                self.other_node == self.instance.primary_node,
7571
                                False)
7572

    
7573
    # Step: create new storage
7574
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7575
    iv_names = self._CreateNewStorage(self.target_node)
7576

    
7577
    # Step: for each lv, detach+rename*2+attach
7578
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7579
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7580
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7581

    
7582
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7583
                                                     old_lvs)
7584
      result.Raise("Can't detach drbd from local storage on node"
7585
                   " %s for device %s" % (self.target_node, dev.iv_name))
7586
      #dev.children = []
7587
      #cfg.Update(instance)
7588

    
7589
      # ok, we created the new LVs, so now we know we have the needed
7590
      # storage; as such, we proceed on the target node to rename
7591
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7592
      # using the assumption that logical_id == physical_id (which in
7593
      # turn is the unique_id on that node)
7594

    
7595
      # FIXME(iustin): use a better name for the replaced LVs
7596
      temp_suffix = int(time.time())
7597
      ren_fn = lambda d, suff: (d.physical_id[0],
7598
                                d.physical_id[1] + "_replaced-%s" % suff)
7599

    
7600
      # Build the rename list based on what LVs exist on the node
7601
      rename_old_to_new = []
7602
      for to_ren in old_lvs:
7603
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7604
        if not result.fail_msg and result.payload:
7605
          # device exists
7606
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7607

    
7608
      self.lu.LogInfo("Renaming the old LVs on the target node")
7609
      result = self.rpc.call_blockdev_rename(self.target_node,
7610
                                             rename_old_to_new)
7611
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7612

    
7613
      # Now we rename the new LVs to the old LVs
7614
      self.lu.LogInfo("Renaming the new LVs on the target node")
7615
      rename_new_to_old = [(new, old.physical_id)
7616
                           for old, new in zip(old_lvs, new_lvs)]
7617
      result = self.rpc.call_blockdev_rename(self.target_node,
7618
                                             rename_new_to_old)
7619
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7620

    
7621
      for old, new in zip(old_lvs, new_lvs):
7622
        new.logical_id = old.logical_id
7623
        self.cfg.SetDiskID(new, self.target_node)
7624

    
7625
      for disk in old_lvs:
7626
        disk.logical_id = ren_fn(disk, temp_suffix)
7627
        self.cfg.SetDiskID(disk, self.target_node)
7628

    
7629
      # Now that the new lvs have the old name, we can add them to the device
7630
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7631
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7632
                                                  new_lvs)
7633
      msg = result.fail_msg
7634
      if msg:
7635
        for new_lv in new_lvs:
7636
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7637
                                               new_lv).fail_msg
7638
          if msg2:
7639
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7640
                               hint=("cleanup manually the unused logical"
7641
                                     "volumes"))
7642
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7643

    
7644
      dev.children = new_lvs
7645

    
7646
      self.cfg.Update(self.instance, feedback_fn)
7647

    
7648
    cstep = 5
7649
    if self.early_release:
7650
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7651
      cstep += 1
7652
      self._RemoveOldStorage(self.target_node, iv_names)
7653
      # WARNING: we release both node locks here, do not do other RPCs
7654
      # than WaitForSync to the primary node
7655
      self._ReleaseNodeLock([self.target_node, self.other_node])
7656

    
7657
    # Wait for sync
7658
    # This can fail as the old devices are degraded and _WaitForSync
7659
    # does a combined result over all disks, so we don't check its return value
7660
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7661
    cstep += 1
7662
    _WaitForSync(self.lu, self.instance)
7663

    
7664
    # Check all devices manually
7665
    self._CheckDevices(self.instance.primary_node, iv_names)
7666

    
7667
    # Step: remove old storage
7668
    if not self.early_release:
7669
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7670
      cstep += 1
7671
      self._RemoveOldStorage(self.target_node, iv_names)
7672

    
7673
  def _ExecDrbd8Secondary(self, feedback_fn):
7674
    """Replace the secondary node for DRBD 8.
7675

7676
    The algorithm for replace is quite complicated:
7677
      - for all disks of the instance:
7678
        - create new LVs on the new node with same names
7679
        - shutdown the drbd device on the old secondary
7680
        - disconnect the drbd network on the primary
7681
        - create the drbd device on the new secondary
7682
        - network attach the drbd on the primary, using an artifice:
7683
          the drbd code for Attach() will connect to the network if it
7684
          finds a device which is connected to the good local disks but
7685
          not network enabled
7686
      - wait for sync across all devices
7687
      - remove all disks from the old secondary
7688

7689
    Failures are not very well handled.
7690

7691
    """
7692
    steps_total = 6
7693

    
7694
    # Step: check device activation
7695
    self.lu.LogStep(1, steps_total, "Check device existence")
7696
    self._CheckDisksExistence([self.instance.primary_node])
7697
    self._CheckVolumeGroup([self.instance.primary_node])
7698

    
7699
    # Step: check other node consistency
7700
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7701
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
7702

    
7703
    # Step: create new storage
7704
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7705
    for idx, dev in enumerate(self.instance.disks):
7706
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
7707
                      (self.new_node, idx))
7708
      # we pass force_create=True to force LVM creation
7709
      for new_lv in dev.children:
7710
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
7711
                        _GetInstanceInfoText(self.instance), False)
7712

    
7713
    # Step 4: dbrd minors and drbd setups changes
7714
    # after this, we must manually remove the drbd minors on both the
7715
    # error and the success paths
7716
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7717
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7718
                                         for dev in self.instance.disks],
7719
                                        self.instance.name)
7720
    logging.debug("Allocated minors %r", minors)
7721

    
7722
    iv_names = {}
7723
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7724
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7725
                      (self.new_node, idx))
7726
      # create new devices on new_node; note that we create two IDs:
7727
      # one without port, so the drbd will be activated without
7728
      # networking information on the new node at this stage, and one
7729
      # with network, for the latter activation in step 4
7730
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7731
      if self.instance.primary_node == o_node1:
7732
        p_minor = o_minor1
7733
      else:
7734
        assert self.instance.primary_node == o_node2, "Three-node instance?"
7735
        p_minor = o_minor2
7736

    
7737
      new_alone_id = (self.instance.primary_node, self.new_node, None,
7738
                      p_minor, new_minor, o_secret)
7739
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
7740
                    p_minor, new_minor, o_secret)
7741

    
7742
      iv_names[idx] = (dev, dev.children, new_net_id)
7743
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
7744
                    new_net_id)
7745
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
7746
                              logical_id=new_alone_id,
7747
                              children=dev.children,
7748
                              size=dev.size)
7749
      try:
7750
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
7751
                              _GetInstanceInfoText(self.instance), False)
7752
      except errors.GenericError:
7753
        self.cfg.ReleaseDRBDMinors(self.instance.name)
7754
        raise
7755

    
7756
    # We have new devices, shutdown the drbd on the old secondary
7757
    for idx, dev in enumerate(self.instance.disks):
7758
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
7759
      self.cfg.SetDiskID(dev, self.target_node)
7760
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
7761
      if msg:
7762
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
7763
                           "node: %s" % (idx, msg),
7764
                           hint=("Please cleanup this device manually as"
7765
                                 " soon as possible"))
7766

    
7767
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
7768
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
7769
                                               self.node_secondary_ip,
7770
                                               self.instance.disks)\
7771
                                              [self.instance.primary_node]
7772

    
7773
    msg = result.fail_msg
7774
    if msg:
7775
      # detaches didn't succeed (unlikely)
7776
      self.cfg.ReleaseDRBDMinors(self.instance.name)
7777
      raise errors.OpExecError("Can't detach the disks from the network on"
7778
                               " old node: %s" % (msg,))
7779

    
7780
    # if we managed to detach at least one, we update all the disks of
7781
    # the instance to point to the new secondary
7782
    self.lu.LogInfo("Updating instance configuration")
7783
    for dev, _, new_logical_id in iv_names.itervalues():
7784
      dev.logical_id = new_logical_id
7785
      self.cfg.SetDiskID(dev, self.instance.primary_node)
7786

    
7787
    self.cfg.Update(self.instance, feedback_fn)
7788

    
7789
    # and now perform the drbd attach
7790
    self.lu.LogInfo("Attaching primary drbds to new secondary"
7791
                    " (standalone => connected)")
7792
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
7793
                                            self.new_node],
7794
                                           self.node_secondary_ip,
7795
                                           self.instance.disks,
7796
                                           self.instance.name,
7797
                                           False)
7798
    for to_node, to_result in result.items():
7799
      msg = to_result.fail_msg
7800
      if msg:
7801
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
7802
                           to_node, msg,
7803
                           hint=("please do a gnt-instance info to see the"
7804
                                 " status of disks"))
7805
    cstep = 5
7806
    if self.early_release:
7807
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7808
      cstep += 1
7809
      self._RemoveOldStorage(self.target_node, iv_names)
7810
      # WARNING: we release all node locks here, do not do other RPCs
7811
      # than WaitForSync to the primary node
7812
      self._ReleaseNodeLock([self.instance.primary_node,
7813
                             self.target_node,
7814
                             self.new_node])
7815

    
7816
    # Wait for sync
7817
    # This can fail as the old devices are degraded and _WaitForSync
7818
    # does a combined result over all disks, so we don't check its return value
7819
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7820
    cstep += 1
7821
    _WaitForSync(self.lu, self.instance)
7822

    
7823
    # Check all devices manually
7824
    self._CheckDevices(self.instance.primary_node, iv_names)
7825

    
7826
    # Step: remove old storage
7827
    if not self.early_release:
7828
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7829
      self._RemoveOldStorage(self.target_node, iv_names)
7830

    
7831

    
7832
class LURepairNodeStorage(NoHooksLU):
7833
  """Repairs the volume group on a node.
7834

7835
  """
7836
  _OP_REQP = ["node_name"]
7837
  REQ_BGL = False
7838

    
7839
  def CheckArguments(self):
7840
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
7841

    
7842
    _CheckStorageType(self.op.storage_type)
7843

    
7844
  def ExpandNames(self):
7845
    self.needed_locks = {
7846
      locking.LEVEL_NODE: [self.op.node_name],
7847
      }
7848

    
7849
  def _CheckFaultyDisks(self, instance, node_name):
7850
    """Ensure faulty disks abort the opcode or at least warn."""
7851
    try:
7852
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
7853
                                  node_name, True):
7854
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
7855
                                   " node '%s'" % (instance.name, node_name),
7856
                                   errors.ECODE_STATE)
7857
    except errors.OpPrereqError, err:
7858
      if self.op.ignore_consistency:
7859
        self.proc.LogWarning(str(err.args[0]))
7860
      else:
7861
        raise
7862

    
7863
  def CheckPrereq(self):
7864
    """Check prerequisites.
7865

7866
    """
7867
    storage_type = self.op.storage_type
7868

    
7869
    if (constants.SO_FIX_CONSISTENCY not in
7870
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
7871
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
7872
                                 " repaired" % storage_type,
7873
                                 errors.ECODE_INVAL)
7874

    
7875
    # Check whether any instance on this node has faulty disks
7876
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
7877
      if not inst.admin_up:
7878
        continue
7879
      check_nodes = set(inst.all_nodes)
7880
      check_nodes.discard(self.op.node_name)
7881
      for inst_node_name in check_nodes:
7882
        self._CheckFaultyDisks(inst, inst_node_name)
7883

    
7884
  def Exec(self, feedback_fn):
7885
    feedback_fn("Repairing storage unit '%s' on %s ..." %
7886
                (self.op.name, self.op.node_name))
7887

    
7888
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
7889
    result = self.rpc.call_storage_execute(self.op.node_name,
7890
                                           self.op.storage_type, st_args,
7891
                                           self.op.name,
7892
                                           constants.SO_FIX_CONSISTENCY)
7893
    result.Raise("Failed to repair storage unit '%s' on %s" %
7894
                 (self.op.name, self.op.node_name))
7895

    
7896

    
7897
class LUNodeEvacuationStrategy(NoHooksLU):
7898
  """Computes the node evacuation strategy.
7899

7900
  """
7901
  _OP_REQP = ["nodes"]
7902
  REQ_BGL = False
7903

    
7904
  def CheckArguments(self):
7905
    if not hasattr(self.op, "remote_node"):
7906
      self.op.remote_node = None
7907
    if not hasattr(self.op, "iallocator"):
7908
      self.op.iallocator = None
7909
    if self.op.remote_node is not None and self.op.iallocator is not None:
7910
      raise errors.OpPrereqError("Give either the iallocator or the new"
7911
                                 " secondary, not both", errors.ECODE_INVAL)
7912

    
7913
  def ExpandNames(self):
7914
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
7915
    self.needed_locks = locks = {}
7916
    if self.op.remote_node is None:
7917
      locks[locking.LEVEL_NODE] = locking.ALL_SET
7918
    else:
7919
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7920
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
7921

    
7922
  def CheckPrereq(self):
7923
    pass
7924

    
7925
  def Exec(self, feedback_fn):
7926
    if self.op.remote_node is not None:
7927
      instances = []
7928
      for node in self.op.nodes:
7929
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
7930
      result = []
7931
      for i in instances:
7932
        if i.primary_node == self.op.remote_node:
7933
          raise errors.OpPrereqError("Node %s is the primary node of"
7934
                                     " instance %s, cannot use it as"
7935
                                     " secondary" %
7936
                                     (self.op.remote_node, i.name),
7937
                                     errors.ECODE_INVAL)
7938
        result.append([i.name, self.op.remote_node])
7939
    else:
7940
      ial = IAllocator(self.cfg, self.rpc,
7941
                       mode=constants.IALLOCATOR_MODE_MEVAC,
7942
                       evac_nodes=self.op.nodes)
7943
      ial.Run(self.op.iallocator, validate=True)
7944
      if not ial.success:
7945
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
7946
                                 errors.ECODE_NORES)
7947
      result = ial.result
7948
    return result
7949

    
7950

    
7951
class LUGrowDisk(LogicalUnit):
7952
  """Grow a disk of an instance.
7953

7954
  """
7955
  HPATH = "disk-grow"
7956
  HTYPE = constants.HTYPE_INSTANCE
7957
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
7958
  REQ_BGL = False
7959

    
7960
  def ExpandNames(self):
7961
    self._ExpandAndLockInstance()
7962
    self.needed_locks[locking.LEVEL_NODE] = []
7963
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7964

    
7965
  def DeclareLocks(self, level):
7966
    if level == locking.LEVEL_NODE:
7967
      self._LockInstancesNodes()
7968

    
7969
  def BuildHooksEnv(self):
7970
    """Build hooks env.
7971

7972
    This runs on the master, the primary and all the secondaries.
7973

7974
    """
7975
    env = {
7976
      "DISK": self.op.disk,
7977
      "AMOUNT": self.op.amount,
7978
      }
7979
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7980
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7981
    return env, nl, nl
7982

    
7983
  def CheckPrereq(self):
7984
    """Check prerequisites.
7985

7986
    This checks that the instance is in the cluster.
7987

7988
    """
7989
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7990
    assert instance is not None, \
7991
      "Cannot retrieve locked instance %s" % self.op.instance_name
7992
    nodenames = list(instance.all_nodes)
7993
    for node in nodenames:
7994
      _CheckNodeOnline(self, node)
7995

    
7996

    
7997
    self.instance = instance
7998

    
7999
    if instance.disk_template not in constants.DTS_GROWABLE:
8000
      raise errors.OpPrereqError("Instance's disk layout does not support"
8001
                                 " growing.", errors.ECODE_INVAL)
8002

    
8003
    self.disk = instance.FindDisk(self.op.disk)
8004

    
8005
    if instance.disk_template != constants.DT_FILE:
8006
      # TODO: check the free disk space for file, when that feature will be
8007
      # supported
8008
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8009

    
8010
  def Exec(self, feedback_fn):
8011
    """Execute disk grow.
8012

8013
    """
8014
    instance = self.instance
8015
    disk = self.disk
8016

    
8017
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8018
    if not disks_ok:
8019
      raise errors.OpExecError("Cannot activate block device to grow")
8020

    
8021
    for node in instance.all_nodes:
8022
      self.cfg.SetDiskID(disk, node)
8023
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8024
      result.Raise("Grow request failed to node %s" % node)
8025

    
8026
      # TODO: Rewrite code to work properly
8027
      # DRBD goes into sync mode for a short amount of time after executing the
8028
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8029
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8030
      # time is a work-around.
8031
      time.sleep(5)
8032

    
8033
    disk.RecordGrow(self.op.amount)
8034
    self.cfg.Update(instance, feedback_fn)
8035
    if self.op.wait_for_sync:
8036
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8037
      if disk_abort:
8038
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8039
                             " status.\nPlease check the instance.")
8040
      if not instance.admin_up:
8041
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8042
    elif not instance.admin_up:
8043
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8044
                           " not supposed to be running because no wait for"
8045
                           " sync mode was requested.")
8046

    
8047

    
8048
class LUQueryInstanceData(NoHooksLU):
8049
  """Query runtime instance data.
8050

8051
  """
8052
  _OP_REQP = ["instances", "static"]
8053
  REQ_BGL = False
8054

    
8055
  def ExpandNames(self):
8056
    self.needed_locks = {}
8057
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8058

    
8059
    if not isinstance(self.op.instances, list):
8060
      raise errors.OpPrereqError("Invalid argument type 'instances'",
8061
                                 errors.ECODE_INVAL)
8062

    
8063
    if self.op.instances:
8064
      self.wanted_names = []
8065
      for name in self.op.instances:
8066
        full_name = _ExpandInstanceName(self.cfg, name)
8067
        self.wanted_names.append(full_name)
8068
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8069
    else:
8070
      self.wanted_names = None
8071
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8072

    
8073
    self.needed_locks[locking.LEVEL_NODE] = []
8074
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8075

    
8076
  def DeclareLocks(self, level):
8077
    if level == locking.LEVEL_NODE:
8078
      self._LockInstancesNodes()
8079

    
8080
  def CheckPrereq(self):
8081
    """Check prerequisites.
8082

8083
    This only checks the optional instance list against the existing names.
8084

8085
    """
8086
    if self.wanted_names is None:
8087
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8088

    
8089
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8090
                             in self.wanted_names]
8091
    return
8092

    
8093
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8094
    """Returns the status of a block device
8095

8096
    """
8097
    if self.op.static or not node:
8098
      return None
8099

    
8100
    self.cfg.SetDiskID(dev, node)
8101

    
8102
    result = self.rpc.call_blockdev_find(node, dev)
8103
    if result.offline:
8104
      return None
8105

    
8106
    result.Raise("Can't compute disk status for %s" % instance_name)
8107

    
8108
    status = result.payload
8109
    if status is None:
8110
      return None
8111

    
8112
    return (status.dev_path, status.major, status.minor,
8113
            status.sync_percent, status.estimated_time,
8114
            status.is_degraded, status.ldisk_status)
8115

    
8116
  def _ComputeDiskStatus(self, instance, snode, dev):
8117
    """Compute block device status.
8118

8119
    """
8120
    if dev.dev_type in constants.LDS_DRBD:
8121
      # we change the snode then (otherwise we use the one passed in)
8122
      if dev.logical_id[0] == instance.primary_node:
8123
        snode = dev.logical_id[1]
8124
      else:
8125
        snode = dev.logical_id[0]
8126

    
8127
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8128
                                              instance.name, dev)
8129
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8130

    
8131
    if dev.children:
8132
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8133
                      for child in dev.children]
8134
    else:
8135
      dev_children = []
8136

    
8137
    data = {
8138
      "iv_name": dev.iv_name,
8139
      "dev_type": dev.dev_type,
8140
      "logical_id": dev.logical_id,
8141
      "physical_id": dev.physical_id,
8142
      "pstatus": dev_pstatus,
8143
      "sstatus": dev_sstatus,
8144
      "children": dev_children,
8145
      "mode": dev.mode,
8146
      "size": dev.size,
8147
      }
8148

    
8149
    return data
8150

    
8151
  def Exec(self, feedback_fn):
8152
    """Gather and return data"""
8153
    result = {}
8154

    
8155
    cluster = self.cfg.GetClusterInfo()
8156

    
8157
    for instance in self.wanted_instances:
8158
      if not self.op.static:
8159
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8160
                                                  instance.name,
8161
                                                  instance.hypervisor)
8162
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8163
        remote_info = remote_info.payload
8164
        if remote_info and "state" in remote_info:
8165
          remote_state = "up"
8166
        else:
8167
          remote_state = "down"
8168
      else:
8169
        remote_state = None
8170
      if instance.admin_up:
8171
        config_state = "up"
8172
      else:
8173
        config_state = "down"
8174

    
8175
      disks = [self._ComputeDiskStatus(instance, None, device)
8176
               for device in instance.disks]
8177

    
8178
      idict = {
8179
        "name": instance.name,
8180
        "config_state": config_state,
8181
        "run_state": remote_state,
8182
        "pnode": instance.primary_node,
8183
        "snodes": instance.secondary_nodes,
8184
        "os": instance.os,
8185
        # this happens to be the same format used for hooks
8186
        "nics": _NICListToTuple(self, instance.nics),
8187
        "disk_template": instance.disk_template,
8188
        "disks": disks,
8189
        "hypervisor": instance.hypervisor,
8190
        "network_port": instance.network_port,
8191
        "hv_instance": instance.hvparams,
8192
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8193
        "be_instance": instance.beparams,
8194
        "be_actual": cluster.FillBE(instance),
8195
        "serial_no": instance.serial_no,
8196
        "mtime": instance.mtime,
8197
        "ctime": instance.ctime,
8198
        "uuid": instance.uuid,
8199
        }
8200

    
8201
      result[instance.name] = idict
8202

    
8203
    return result
8204

    
8205

    
8206
class LUSetInstanceParams(LogicalUnit):
8207
  """Modifies an instances's parameters.
8208

8209
  """
8210
  HPATH = "instance-modify"
8211
  HTYPE = constants.HTYPE_INSTANCE
8212
  _OP_REQP = ["instance_name"]
8213
  REQ_BGL = False
8214

    
8215
  def CheckArguments(self):
8216
    if not hasattr(self.op, 'nics'):
8217
      self.op.nics = []
8218
    if not hasattr(self.op, 'disks'):
8219
      self.op.disks = []
8220
    if not hasattr(self.op, 'beparams'):
8221
      self.op.beparams = {}
8222
    if not hasattr(self.op, 'hvparams'):
8223
      self.op.hvparams = {}
8224
    if not hasattr(self.op, "disk_template"):
8225
      self.op.disk_template = None
8226
    if not hasattr(self.op, "remote_node"):
8227
      self.op.remote_node = None
8228
    if not hasattr(self.op, "os_name"):
8229
      self.op.os_name = None
8230
    if not hasattr(self.op, "force_variant"):
8231
      self.op.force_variant = False
8232
    self.op.force = getattr(self.op, "force", False)
8233
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8234
            self.op.hvparams or self.op.beparams or self.op.os_name):
8235
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8236

    
8237
    if self.op.hvparams:
8238
      _CheckGlobalHvParams(self.op.hvparams)
8239

    
8240
    # Disk validation
8241
    disk_addremove = 0
8242
    for disk_op, disk_dict in self.op.disks:
8243
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8244
      if disk_op == constants.DDM_REMOVE:
8245
        disk_addremove += 1
8246
        continue
8247
      elif disk_op == constants.DDM_ADD:
8248
        disk_addremove += 1
8249
      else:
8250
        if not isinstance(disk_op, int):
8251
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8252
        if not isinstance(disk_dict, dict):
8253
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8254
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8255

    
8256
      if disk_op == constants.DDM_ADD:
8257
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8258
        if mode not in constants.DISK_ACCESS_SET:
8259
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8260
                                     errors.ECODE_INVAL)
8261
        size = disk_dict.get('size', None)
8262
        if size is None:
8263
          raise errors.OpPrereqError("Required disk parameter size missing",
8264
                                     errors.ECODE_INVAL)
8265
        try:
8266
          size = int(size)
8267
        except (TypeError, ValueError), err:
8268
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8269
                                     str(err), errors.ECODE_INVAL)
8270
        disk_dict['size'] = size
8271
      else:
8272
        # modification of disk
8273
        if 'size' in disk_dict:
8274
          raise errors.OpPrereqError("Disk size change not possible, use"
8275
                                     " grow-disk", errors.ECODE_INVAL)
8276

    
8277
    if disk_addremove > 1:
8278
      raise errors.OpPrereqError("Only one disk add or remove operation"
8279
                                 " supported at a time", errors.ECODE_INVAL)
8280

    
8281
    if self.op.disks and self.op.disk_template is not None:
8282
      raise errors.OpPrereqError("Disk template conversion and other disk"
8283
                                 " changes not supported at the same time",
8284
                                 errors.ECODE_INVAL)
8285

    
8286
    if self.op.disk_template:
8287
      _CheckDiskTemplate(self.op.disk_template)
8288
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8289
          self.op.remote_node is None):
8290
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8291
                                   " one requires specifying a secondary node",
8292
                                   errors.ECODE_INVAL)
8293

    
8294
    # NIC validation
8295
    nic_addremove = 0
8296
    for nic_op, nic_dict in self.op.nics:
8297
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8298
      if nic_op == constants.DDM_REMOVE:
8299
        nic_addremove += 1
8300
        continue
8301
      elif nic_op == constants.DDM_ADD:
8302
        nic_addremove += 1
8303
      else:
8304
        if not isinstance(nic_op, int):
8305
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8306
        if not isinstance(nic_dict, dict):
8307
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8308
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8309

    
8310
      # nic_dict should be a dict
8311
      nic_ip = nic_dict.get('ip', None)
8312
      if nic_ip is not None:
8313
        if nic_ip.lower() == constants.VALUE_NONE:
8314
          nic_dict['ip'] = None
8315
        else:
8316
          if not utils.IsValidIP(nic_ip):
8317
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8318
                                       errors.ECODE_INVAL)
8319

    
8320
      nic_bridge = nic_dict.get('bridge', None)
8321
      nic_link = nic_dict.get('link', None)
8322
      if nic_bridge and nic_link:
8323
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8324
                                   " at the same time", errors.ECODE_INVAL)
8325
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8326
        nic_dict['bridge'] = None
8327
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8328
        nic_dict['link'] = None
8329

    
8330
      if nic_op == constants.DDM_ADD:
8331
        nic_mac = nic_dict.get('mac', None)
8332
        if nic_mac is None:
8333
          nic_dict['mac'] = constants.VALUE_AUTO
8334

    
8335
      if 'mac' in nic_dict:
8336
        nic_mac = nic_dict['mac']
8337
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8338
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8339

    
8340
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8341
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8342
                                     " modifying an existing nic",
8343
                                     errors.ECODE_INVAL)
8344

    
8345
    if nic_addremove > 1:
8346
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8347
                                 " supported at a time", errors.ECODE_INVAL)
8348

    
8349
  def ExpandNames(self):
8350
    self._ExpandAndLockInstance()
8351
    self.needed_locks[locking.LEVEL_NODE] = []
8352
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8353

    
8354
  def DeclareLocks(self, level):
8355
    if level == locking.LEVEL_NODE:
8356
      self._LockInstancesNodes()
8357
      if self.op.disk_template and self.op.remote_node:
8358
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8359
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8360

    
8361
  def BuildHooksEnv(self):
8362
    """Build hooks env.
8363

8364
    This runs on the master, primary and secondaries.
8365

8366
    """
8367
    args = dict()
8368
    if constants.BE_MEMORY in self.be_new:
8369
      args['memory'] = self.be_new[constants.BE_MEMORY]
8370
    if constants.BE_VCPUS in self.be_new:
8371
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8372
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8373
    # information at all.
8374
    if self.op.nics:
8375
      args['nics'] = []
8376
      nic_override = dict(self.op.nics)
8377
      for idx, nic in enumerate(self.instance.nics):
8378
        if idx in nic_override:
8379
          this_nic_override = nic_override[idx]
8380
        else:
8381
          this_nic_override = {}
8382
        if 'ip' in this_nic_override:
8383
          ip = this_nic_override['ip']
8384
        else:
8385
          ip = nic.ip
8386
        if 'mac' in this_nic_override:
8387
          mac = this_nic_override['mac']
8388
        else:
8389
          mac = nic.mac
8390
        if idx in self.nic_pnew:
8391
          nicparams = self.nic_pnew[idx]
8392
        else:
8393
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8394
        mode = nicparams[constants.NIC_MODE]
8395
        link = nicparams[constants.NIC_LINK]
8396
        args['nics'].append((ip, mac, mode, link))
8397
      if constants.DDM_ADD in nic_override:
8398
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8399
        mac = nic_override[constants.DDM_ADD]['mac']
8400
        nicparams = self.nic_pnew[constants.DDM_ADD]
8401
        mode = nicparams[constants.NIC_MODE]
8402
        link = nicparams[constants.NIC_LINK]
8403
        args['nics'].append((ip, mac, mode, link))
8404
      elif constants.DDM_REMOVE in nic_override:
8405
        del args['nics'][-1]
8406

    
8407
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8408
    if self.op.disk_template:
8409
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8410
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8411
    return env, nl, nl
8412

    
8413
  @staticmethod
8414
  def _GetUpdatedParams(old_params, update_dict,
8415
                        default_values, parameter_types):
8416
    """Return the new params dict for the given params.
8417

8418
    @type old_params: dict
8419
    @param old_params: old parameters
8420
    @type update_dict: dict
8421
    @param update_dict: dict containing new parameter values,
8422
                        or constants.VALUE_DEFAULT to reset the
8423
                        parameter to its default value
8424
    @type default_values: dict
8425
    @param default_values: default values for the filled parameters
8426
    @type parameter_types: dict
8427
    @param parameter_types: dict mapping target dict keys to types
8428
                            in constants.ENFORCEABLE_TYPES
8429
    @rtype: (dict, dict)
8430
    @return: (new_parameters, filled_parameters)
8431

8432
    """
8433
    params_copy = copy.deepcopy(old_params)
8434
    for key, val in update_dict.iteritems():
8435
      if val == constants.VALUE_DEFAULT:
8436
        try:
8437
          del params_copy[key]
8438
        except KeyError:
8439
          pass
8440
      else:
8441
        params_copy[key] = val
8442
    utils.ForceDictType(params_copy, parameter_types)
8443
    params_filled = objects.FillDict(default_values, params_copy)
8444
    return (params_copy, params_filled)
8445

    
8446
  def CheckPrereq(self):
8447
    """Check prerequisites.
8448

8449
    This only checks the instance list against the existing names.
8450

8451
    """
8452
    self.force = self.op.force
8453

    
8454
    # checking the new params on the primary/secondary nodes
8455

    
8456
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8457
    cluster = self.cluster = self.cfg.GetClusterInfo()
8458
    assert self.instance is not None, \
8459
      "Cannot retrieve locked instance %s" % self.op.instance_name
8460
    pnode = instance.primary_node
8461
    nodelist = list(instance.all_nodes)
8462

    
8463
    if self.op.disk_template:
8464
      if instance.disk_template == self.op.disk_template:
8465
        raise errors.OpPrereqError("Instance already has disk template %s" %
8466
                                   instance.disk_template, errors.ECODE_INVAL)
8467

    
8468
      if (instance.disk_template,
8469
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8470
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8471
                                   " %s to %s" % (instance.disk_template,
8472
                                                  self.op.disk_template),
8473
                                   errors.ECODE_INVAL)
8474
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8475
        _CheckNodeOnline(self, self.op.remote_node)
8476
        _CheckNodeNotDrained(self, self.op.remote_node)
8477
        disks = [{"size": d.size} for d in instance.disks]
8478
        required = _ComputeDiskSize(self.op.disk_template, disks)
8479
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8480
        _CheckInstanceDown(self, instance, "cannot change disk template")
8481

    
8482
    # hvparams processing
8483
    if self.op.hvparams:
8484
      i_hvdict, hv_new = self._GetUpdatedParams(
8485
                             instance.hvparams, self.op.hvparams,
8486
                             cluster.hvparams[instance.hypervisor],
8487
                             constants.HVS_PARAMETER_TYPES)
8488
      # local check
8489
      hypervisor.GetHypervisor(
8490
        instance.hypervisor).CheckParameterSyntax(hv_new)
8491
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8492
      self.hv_new = hv_new # the new actual values
8493
      self.hv_inst = i_hvdict # the new dict (without defaults)
8494
    else:
8495
      self.hv_new = self.hv_inst = {}
8496

    
8497
    # beparams processing
8498
    if self.op.beparams:
8499
      i_bedict, be_new = self._GetUpdatedParams(
8500
                             instance.beparams, self.op.beparams,
8501
                             cluster.beparams[constants.PP_DEFAULT],
8502
                             constants.BES_PARAMETER_TYPES)
8503
      self.be_new = be_new # the new actual values
8504
      self.be_inst = i_bedict # the new dict (without defaults)
8505
    else:
8506
      self.be_new = self.be_inst = {}
8507

    
8508
    self.warn = []
8509

    
8510
    if constants.BE_MEMORY in self.op.beparams and not self.force:
8511
      mem_check_list = [pnode]
8512
      if be_new[constants.BE_AUTO_BALANCE]:
8513
        # either we changed auto_balance to yes or it was from before
8514
        mem_check_list.extend(instance.secondary_nodes)
8515
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8516
                                                  instance.hypervisor)
8517
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8518
                                         instance.hypervisor)
8519
      pninfo = nodeinfo[pnode]
8520
      msg = pninfo.fail_msg
8521
      if msg:
8522
        # Assume the primary node is unreachable and go ahead
8523
        self.warn.append("Can't get info from primary node %s: %s" %
8524
                         (pnode,  msg))
8525
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8526
        self.warn.append("Node data from primary node %s doesn't contain"
8527
                         " free memory information" % pnode)
8528
      elif instance_info.fail_msg:
8529
        self.warn.append("Can't get instance runtime information: %s" %
8530
                        instance_info.fail_msg)
8531
      else:
8532
        if instance_info.payload:
8533
          current_mem = int(instance_info.payload['memory'])
8534
        else:
8535
          # Assume instance not running
8536
          # (there is a slight race condition here, but it's not very probable,
8537
          # and we have no other way to check)
8538
          current_mem = 0
8539
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8540
                    pninfo.payload['memory_free'])
8541
        if miss_mem > 0:
8542
          raise errors.OpPrereqError("This change will prevent the instance"
8543
                                     " from starting, due to %d MB of memory"
8544
                                     " missing on its primary node" % miss_mem,
8545
                                     errors.ECODE_NORES)
8546

    
8547
      if be_new[constants.BE_AUTO_BALANCE]:
8548
        for node, nres in nodeinfo.items():
8549
          if node not in instance.secondary_nodes:
8550
            continue
8551
          msg = nres.fail_msg
8552
          if msg:
8553
            self.warn.append("Can't get info from secondary node %s: %s" %
8554
                             (node, msg))
8555
          elif not isinstance(nres.payload.get('memory_free', None), int):
8556
            self.warn.append("Secondary node %s didn't return free"
8557
                             " memory information" % node)
8558
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8559
            self.warn.append("Not enough memory to failover instance to"
8560
                             " secondary node %s" % node)
8561

    
8562
    # NIC processing
8563
    self.nic_pnew = {}
8564
    self.nic_pinst = {}
8565
    for nic_op, nic_dict in self.op.nics:
8566
      if nic_op == constants.DDM_REMOVE:
8567
        if not instance.nics:
8568
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8569
                                     errors.ECODE_INVAL)
8570
        continue
8571
      if nic_op != constants.DDM_ADD:
8572
        # an existing nic
8573
        if not instance.nics:
8574
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8575
                                     " no NICs" % nic_op,
8576
                                     errors.ECODE_INVAL)
8577
        if nic_op < 0 or nic_op >= len(instance.nics):
8578
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8579
                                     " are 0 to %d" %
8580
                                     (nic_op, len(instance.nics) - 1),
8581
                                     errors.ECODE_INVAL)
8582
        old_nic_params = instance.nics[nic_op].nicparams
8583
        old_nic_ip = instance.nics[nic_op].ip
8584
      else:
8585
        old_nic_params = {}
8586
        old_nic_ip = None
8587

    
8588
      update_params_dict = dict([(key, nic_dict[key])
8589
                                 for key in constants.NICS_PARAMETERS
8590
                                 if key in nic_dict])
8591

    
8592
      if 'bridge' in nic_dict:
8593
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8594

    
8595
      new_nic_params, new_filled_nic_params = \
8596
          self._GetUpdatedParams(old_nic_params, update_params_dict,
8597
                                 cluster.nicparams[constants.PP_DEFAULT],
8598
                                 constants.NICS_PARAMETER_TYPES)
8599
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8600
      self.nic_pinst[nic_op] = new_nic_params
8601
      self.nic_pnew[nic_op] = new_filled_nic_params
8602
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8603

    
8604
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8605
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8606
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8607
        if msg:
8608
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8609
          if self.force:
8610
            self.warn.append(msg)
8611
          else:
8612
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8613
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8614
        if 'ip' in nic_dict:
8615
          nic_ip = nic_dict['ip']
8616
        else:
8617
          nic_ip = old_nic_ip
8618
        if nic_ip is None:
8619
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8620
                                     ' on a routed nic', errors.ECODE_INVAL)
8621
      if 'mac' in nic_dict:
8622
        nic_mac = nic_dict['mac']
8623
        if nic_mac is None:
8624
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8625
                                     errors.ECODE_INVAL)
8626
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8627
          # otherwise generate the mac
8628
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8629
        else:
8630
          # or validate/reserve the current one
8631
          try:
8632
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8633
          except errors.ReservationError:
8634
            raise errors.OpPrereqError("MAC address %s already in use"
8635
                                       " in cluster" % nic_mac,
8636
                                       errors.ECODE_NOTUNIQUE)
8637

    
8638
    # DISK processing
8639
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8640
      raise errors.OpPrereqError("Disk operations not supported for"
8641
                                 " diskless instances",
8642
                                 errors.ECODE_INVAL)
8643
    for disk_op, _ in self.op.disks:
8644
      if disk_op == constants.DDM_REMOVE:
8645
        if len(instance.disks) == 1:
8646
          raise errors.OpPrereqError("Cannot remove the last disk of"
8647
                                     " an instance", errors.ECODE_INVAL)
8648
        _CheckInstanceDown(self, instance, "cannot remove disks")
8649

    
8650
      if (disk_op == constants.DDM_ADD and
8651
          len(instance.nics) >= constants.MAX_DISKS):
8652
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8653
                                   " add more" % constants.MAX_DISKS,
8654
                                   errors.ECODE_STATE)
8655
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8656
        # an existing disk
8657
        if disk_op < 0 or disk_op >= len(instance.disks):
8658
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8659
                                     " are 0 to %d" %
8660
                                     (disk_op, len(instance.disks)),
8661
                                     errors.ECODE_INVAL)
8662

    
8663
    # OS change
8664
    if self.op.os_name and not self.op.force:
8665
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8666
                      self.op.force_variant)
8667

    
8668
    return
8669

    
8670
  def _ConvertPlainToDrbd(self, feedback_fn):
8671
    """Converts an instance from plain to drbd.
8672

8673
    """
8674
    feedback_fn("Converting template to drbd")
8675
    instance = self.instance
8676
    pnode = instance.primary_node
8677
    snode = self.op.remote_node
8678

    
8679
    # create a fake disk info for _GenerateDiskTemplate
8680
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
8681
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
8682
                                      instance.name, pnode, [snode],
8683
                                      disk_info, None, None, 0)
8684
    info = _GetInstanceInfoText(instance)
8685
    feedback_fn("Creating aditional volumes...")
8686
    # first, create the missing data and meta devices
8687
    for disk in new_disks:
8688
      # unfortunately this is... not too nice
8689
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
8690
                            info, True)
8691
      for child in disk.children:
8692
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
8693
    # at this stage, all new LVs have been created, we can rename the
8694
    # old ones
8695
    feedback_fn("Renaming original volumes...")
8696
    rename_list = [(o, n.children[0].logical_id)
8697
                   for (o, n) in zip(instance.disks, new_disks)]
8698
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
8699
    result.Raise("Failed to rename original LVs")
8700

    
8701
    feedback_fn("Initializing DRBD devices...")
8702
    # all child devices are in place, we can now create the DRBD devices
8703
    for disk in new_disks:
8704
      for node in [pnode, snode]:
8705
        f_create = node == pnode
8706
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
8707

    
8708
    # at this point, the instance has been modified
8709
    instance.disk_template = constants.DT_DRBD8
8710
    instance.disks = new_disks
8711
    self.cfg.Update(instance, feedback_fn)
8712

    
8713
    # disks are created, waiting for sync
8714
    disk_abort = not _WaitForSync(self, instance)
8715
    if disk_abort:
8716
      raise errors.OpExecError("There are some degraded disks for"
8717
                               " this instance, please cleanup manually")
8718

    
8719
  def _ConvertDrbdToPlain(self, feedback_fn):
8720
    """Converts an instance from drbd to plain.
8721

8722
    """
8723
    instance = self.instance
8724
    assert len(instance.secondary_nodes) == 1
8725
    pnode = instance.primary_node
8726
    snode = instance.secondary_nodes[0]
8727
    feedback_fn("Converting template to plain")
8728

    
8729
    old_disks = instance.disks
8730
    new_disks = [d.children[0] for d in old_disks]
8731

    
8732
    # copy over size and mode
8733
    for parent, child in zip(old_disks, new_disks):
8734
      child.size = parent.size
8735
      child.mode = parent.mode
8736

    
8737
    # update instance structure
8738
    instance.disks = new_disks
8739
    instance.disk_template = constants.DT_PLAIN
8740
    self.cfg.Update(instance, feedback_fn)
8741

    
8742
    feedback_fn("Removing volumes on the secondary node...")
8743
    for disk in old_disks:
8744
      self.cfg.SetDiskID(disk, snode)
8745
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
8746
      if msg:
8747
        self.LogWarning("Could not remove block device %s on node %s,"
8748
                        " continuing anyway: %s", disk.iv_name, snode, msg)
8749

    
8750
    feedback_fn("Removing unneeded volumes on the primary node...")
8751
    for idx, disk in enumerate(old_disks):
8752
      meta = disk.children[1]
8753
      self.cfg.SetDiskID(meta, pnode)
8754
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
8755
      if msg:
8756
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
8757
                        " continuing anyway: %s", idx, pnode, msg)
8758

    
8759

    
8760
  def Exec(self, feedback_fn):
8761
    """Modifies an instance.
8762

8763
    All parameters take effect only at the next restart of the instance.
8764

8765
    """
8766
    # Process here the warnings from CheckPrereq, as we don't have a
8767
    # feedback_fn there.
8768
    for warn in self.warn:
8769
      feedback_fn("WARNING: %s" % warn)
8770

    
8771
    result = []
8772
    instance = self.instance
8773
    # disk changes
8774
    for disk_op, disk_dict in self.op.disks:
8775
      if disk_op == constants.DDM_REMOVE:
8776
        # remove the last disk
8777
        device = instance.disks.pop()
8778
        device_idx = len(instance.disks)
8779
        for node, disk in device.ComputeNodeTree(instance.primary_node):
8780
          self.cfg.SetDiskID(disk, node)
8781
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
8782
          if msg:
8783
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
8784
                            " continuing anyway", device_idx, node, msg)
8785
        result.append(("disk/%d" % device_idx, "remove"))
8786
      elif disk_op == constants.DDM_ADD:
8787
        # add a new disk
8788
        if instance.disk_template == constants.DT_FILE:
8789
          file_driver, file_path = instance.disks[0].logical_id
8790
          file_path = os.path.dirname(file_path)
8791
        else:
8792
          file_driver = file_path = None
8793
        disk_idx_base = len(instance.disks)
8794
        new_disk = _GenerateDiskTemplate(self,
8795
                                         instance.disk_template,
8796
                                         instance.name, instance.primary_node,
8797
                                         instance.secondary_nodes,
8798
                                         [disk_dict],
8799
                                         file_path,
8800
                                         file_driver,
8801
                                         disk_idx_base)[0]
8802
        instance.disks.append(new_disk)
8803
        info = _GetInstanceInfoText(instance)
8804

    
8805
        logging.info("Creating volume %s for instance %s",
8806
                     new_disk.iv_name, instance.name)
8807
        # Note: this needs to be kept in sync with _CreateDisks
8808
        #HARDCODE
8809
        for node in instance.all_nodes:
8810
          f_create = node == instance.primary_node
8811
          try:
8812
            _CreateBlockDev(self, node, instance, new_disk,
8813
                            f_create, info, f_create)
8814
          except errors.OpExecError, err:
8815
            self.LogWarning("Failed to create volume %s (%s) on"
8816
                            " node %s: %s",
8817
                            new_disk.iv_name, new_disk, node, err)
8818
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
8819
                       (new_disk.size, new_disk.mode)))
8820
      else:
8821
        # change a given disk
8822
        instance.disks[disk_op].mode = disk_dict['mode']
8823
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
8824

    
8825
    if self.op.disk_template:
8826
      r_shut = _ShutdownInstanceDisks(self, instance)
8827
      if not r_shut:
8828
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
8829
                                 " proceed with disk template conversion")
8830
      mode = (instance.disk_template, self.op.disk_template)
8831
      try:
8832
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
8833
      except:
8834
        self.cfg.ReleaseDRBDMinors(instance.name)
8835
        raise
8836
      result.append(("disk_template", self.op.disk_template))
8837

    
8838
    # NIC changes
8839
    for nic_op, nic_dict in self.op.nics:
8840
      if nic_op == constants.DDM_REMOVE:
8841
        # remove the last nic
8842
        del instance.nics[-1]
8843
        result.append(("nic.%d" % len(instance.nics), "remove"))
8844
      elif nic_op == constants.DDM_ADD:
8845
        # mac and bridge should be set, by now
8846
        mac = nic_dict['mac']
8847
        ip = nic_dict.get('ip', None)
8848
        nicparams = self.nic_pinst[constants.DDM_ADD]
8849
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
8850
        instance.nics.append(new_nic)
8851
        result.append(("nic.%d" % (len(instance.nics) - 1),
8852
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
8853
                       (new_nic.mac, new_nic.ip,
8854
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
8855
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
8856
                       )))
8857
      else:
8858
        for key in 'mac', 'ip':
8859
          if key in nic_dict:
8860
            setattr(instance.nics[nic_op], key, nic_dict[key])
8861
        if nic_op in self.nic_pinst:
8862
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
8863
        for key, val in nic_dict.iteritems():
8864
          result.append(("nic.%s/%d" % (key, nic_op), val))
8865

    
8866
    # hvparams changes
8867
    if self.op.hvparams:
8868
      instance.hvparams = self.hv_inst
8869
      for key, val in self.op.hvparams.iteritems():
8870
        result.append(("hv/%s" % key, val))
8871

    
8872
    # beparams changes
8873
    if self.op.beparams:
8874
      instance.beparams = self.be_inst
8875
      for key, val in self.op.beparams.iteritems():
8876
        result.append(("be/%s" % key, val))
8877

    
8878
    # OS change
8879
    if self.op.os_name:
8880
      instance.os = self.op.os_name
8881

    
8882
    self.cfg.Update(instance, feedback_fn)
8883

    
8884
    return result
8885

    
8886
  _DISK_CONVERSIONS = {
8887
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
8888
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
8889
    }
8890

    
8891

    
8892
class LUQueryExports(NoHooksLU):
8893
  """Query the exports list
8894

8895
  """
8896
  _OP_REQP = ['nodes']
8897
  REQ_BGL = False
8898

    
8899
  def ExpandNames(self):
8900
    self.needed_locks = {}
8901
    self.share_locks[locking.LEVEL_NODE] = 1
8902
    if not self.op.nodes:
8903
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8904
    else:
8905
      self.needed_locks[locking.LEVEL_NODE] = \
8906
        _GetWantedNodes(self, self.op.nodes)
8907

    
8908
  def CheckPrereq(self):
8909
    """Check prerequisites.
8910

8911
    """
8912
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
8913

    
8914
  def Exec(self, feedback_fn):
8915
    """Compute the list of all the exported system images.
8916

8917
    @rtype: dict
8918
    @return: a dictionary with the structure node->(export-list)
8919
        where export-list is a list of the instances exported on
8920
        that node.
8921

8922
    """
8923
    rpcresult = self.rpc.call_export_list(self.nodes)
8924
    result = {}
8925
    for node in rpcresult:
8926
      if rpcresult[node].fail_msg:
8927
        result[node] = False
8928
      else:
8929
        result[node] = rpcresult[node].payload
8930

    
8931
    return result
8932

    
8933

    
8934
class LUPrepareExport(NoHooksLU):
8935
  """Prepares an instance for an export and returns useful information.
8936

8937
  """
8938
  _OP_REQP = ["instance_name", "mode"]
8939
  REQ_BGL = False
8940

    
8941
  def CheckArguments(self):
8942
    """Check the arguments.
8943

8944
    """
8945
    if self.op.mode not in constants.EXPORT_MODES:
8946
      raise errors.OpPrereqError("Invalid export mode %r" % self.op.mode,
8947
                                 errors.ECODE_INVAL)
8948

    
8949
  def ExpandNames(self):
8950
    self._ExpandAndLockInstance()
8951

    
8952
  def CheckPrereq(self):
8953
    """Check prerequisites.
8954

8955
    """
8956
    instance_name = self.op.instance_name
8957

    
8958
    self.instance = self.cfg.GetInstanceInfo(instance_name)
8959
    assert self.instance is not None, \
8960
          "Cannot retrieve locked instance %s" % self.op.instance_name
8961
    _CheckNodeOnline(self, self.instance.primary_node)
8962

    
8963
    self._cds = _GetClusterDomainSecret()
8964

    
8965
  def Exec(self, feedback_fn):
8966
    """Prepares an instance for an export.
8967

8968
    """
8969
    instance = self.instance
8970

    
8971
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
8972
      salt = utils.GenerateSecret(8)
8973

    
8974
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
8975
      result = self.rpc.call_x509_cert_create(instance.primary_node,
8976
                                              constants.RIE_CERT_VALIDITY)
8977
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
8978

    
8979
      (name, cert_pem) = result.payload
8980

    
8981
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
8982
                                             cert_pem)
8983

    
8984
      return {
8985
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
8986
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
8987
                          salt),
8988
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
8989
        }
8990

    
8991
    return None
8992

    
8993

    
8994
class LUExportInstance(LogicalUnit):
8995
  """Export an instance to an image in the cluster.
8996

8997
  """
8998
  HPATH = "instance-export"
8999
  HTYPE = constants.HTYPE_INSTANCE
9000
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
9001
  REQ_BGL = False
9002

    
9003
  def CheckArguments(self):
9004
    """Check the arguments.
9005

9006
    """
9007
    _CheckBooleanOpField(self.op, "remove_instance")
9008
    _CheckBooleanOpField(self.op, "ignore_remove_failures")
9009

    
9010
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
9011
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
9012
    self.remove_instance = getattr(self.op, "remove_instance", False)
9013
    self.ignore_remove_failures = getattr(self.op, "ignore_remove_failures",
9014
                                          False)
9015
    self.export_mode = getattr(self.op, "mode", constants.EXPORT_MODE_LOCAL)
9016
    self.x509_key_name = getattr(self.op, "x509_key_name", None)
9017
    self.dest_x509_ca_pem = getattr(self.op, "destination_x509_ca", None)
9018

    
9019
    if self.remove_instance and not self.op.shutdown:
9020
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9021
                                 " down before")
9022

    
9023
    if self.export_mode not in constants.EXPORT_MODES:
9024
      raise errors.OpPrereqError("Invalid export mode %r" % self.export_mode,
9025
                                 errors.ECODE_INVAL)
9026

    
9027
    if self.export_mode == constants.EXPORT_MODE_REMOTE:
9028
      if not self.x509_key_name:
9029
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9030
                                   errors.ECODE_INVAL)
9031

    
9032
      if not self.dest_x509_ca_pem:
9033
        raise errors.OpPrereqError("Missing destination X509 CA",
9034
                                   errors.ECODE_INVAL)
9035

    
9036
  def ExpandNames(self):
9037
    self._ExpandAndLockInstance()
9038

    
9039
    # Lock all nodes for local exports
9040
    if self.export_mode == constants.EXPORT_MODE_LOCAL:
9041
      # FIXME: lock only instance primary and destination node
9042
      #
9043
      # Sad but true, for now we have do lock all nodes, as we don't know where
9044
      # the previous export might be, and in this LU we search for it and
9045
      # remove it from its current node. In the future we could fix this by:
9046
      #  - making a tasklet to search (share-lock all), then create the new one,
9047
      #    then one to remove, after
9048
      #  - removing the removal operation altogether
9049
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9050

    
9051
  def DeclareLocks(self, level):
9052
    """Last minute lock declaration."""
9053
    # All nodes are locked anyway, so nothing to do here.
9054

    
9055
  def BuildHooksEnv(self):
9056
    """Build hooks env.
9057

9058
    This will run on the master, primary node and target node.
9059

9060
    """
9061
    env = {
9062
      "EXPORT_MODE": self.export_mode,
9063
      "EXPORT_NODE": self.op.target_node,
9064
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9065
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
9066
      # TODO: Generic function for boolean env variables
9067
      "REMOVE_INSTANCE": str(bool(self.remove_instance)),
9068
      }
9069

    
9070
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9071

    
9072
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9073

    
9074
    if self.export_mode == constants.EXPORT_MODE_LOCAL:
9075
      nl.append(self.op.target_node)
9076

    
9077
    return env, nl, nl
9078

    
9079
  def CheckPrereq(self):
9080
    """Check prerequisites.
9081

9082
    This checks that the instance and node names are valid.
9083

9084
    """
9085
    instance_name = self.op.instance_name
9086

    
9087
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9088
    assert self.instance is not None, \
9089
          "Cannot retrieve locked instance %s" % self.op.instance_name
9090
    _CheckNodeOnline(self, self.instance.primary_node)
9091

    
9092
    if self.export_mode == constants.EXPORT_MODE_LOCAL:
9093
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9094
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9095
      assert self.dst_node is not None
9096

    
9097
      _CheckNodeOnline(self, self.dst_node.name)
9098
      _CheckNodeNotDrained(self, self.dst_node.name)
9099

    
9100
      self._cds = None
9101
      self.dest_disk_info = None
9102
      self.dest_x509_ca = None
9103

    
9104
    elif self.export_mode == constants.EXPORT_MODE_REMOTE:
9105
      self.dst_node = None
9106

    
9107
      if len(self.op.target_node) != len(self.instance.disks):
9108
        raise errors.OpPrereqError(("Received destination information for %s"
9109
                                    " disks, but instance %s has %s disks") %
9110
                                   (len(self.op.target_node), instance_name,
9111
                                    len(self.instance.disks)),
9112
                                   errors.ECODE_INVAL)
9113

    
9114
      cds = _GetClusterDomainSecret()
9115

    
9116
      # Check X509 key name
9117
      try:
9118
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9119
      except (TypeError, ValueError), err:
9120
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9121

    
9122
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9123
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9124
                                   errors.ECODE_INVAL)
9125

    
9126
      # Load and verify CA
9127
      try:
9128
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9129
      except OpenSSL.crypto.Error, err:
9130
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9131
                                   (err, ), errors.ECODE_INVAL)
9132

    
9133
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9134
      if errcode is not None:
9135
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" % (msg, ),
9136
                                   errors.ECODE_INVAL)
9137

    
9138
      self.dest_x509_ca = cert
9139

    
9140
      # Verify target information
9141
      disk_info = []
9142
      for idx, disk_data in enumerate(self.op.target_node):
9143
        try:
9144
          (host, port, magic) = \
9145
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9146
        except errors.GenericError, err:
9147
          raise errors.OpPrereqError("Target info for disk %s: %s" % (idx, err),
9148
                                     errors.ECODE_INVAL)
9149

    
9150
        disk_info.append((host, port, magic))
9151

    
9152
      assert len(disk_info) == len(self.op.target_node)
9153
      self.dest_disk_info = disk_info
9154

    
9155
    else:
9156
      raise errors.ProgrammerError("Unhandled export mode %r" %
9157
                                   self.export_mode)
9158

    
9159
    # instance disk type verification
9160
    # TODO: Implement export support for file-based disks
9161
    for disk in self.instance.disks:
9162
      if disk.dev_type == constants.LD_FILE:
9163
        raise errors.OpPrereqError("Export not supported for instances with"
9164
                                   " file-based disks", errors.ECODE_INVAL)
9165

    
9166
  def _CleanupExports(self, feedback_fn):
9167
    """Removes exports of current instance from all other nodes.
9168

9169
    If an instance in a cluster with nodes A..D was exported to node C, its
9170
    exports will be removed from the nodes A, B and D.
9171

9172
    """
9173
    assert self.export_mode != constants.EXPORT_MODE_REMOTE
9174

    
9175
    nodelist = self.cfg.GetNodeList()
9176
    nodelist.remove(self.dst_node.name)
9177

    
9178
    # on one-node clusters nodelist will be empty after the removal
9179
    # if we proceed the backup would be removed because OpQueryExports
9180
    # substitutes an empty list with the full cluster node list.
9181
    iname = self.instance.name
9182
    if nodelist:
9183
      feedback_fn("Removing old exports for instance %s" % iname)
9184
      exportlist = self.rpc.call_export_list(nodelist)
9185
      for node in exportlist:
9186
        if exportlist[node].fail_msg:
9187
          continue
9188
        if iname in exportlist[node].payload:
9189
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9190
          if msg:
9191
            self.LogWarning("Could not remove older export for instance %s"
9192
                            " on node %s: %s", iname, node, msg)
9193

    
9194
  def Exec(self, feedback_fn):
9195
    """Export an instance to an image in the cluster.
9196

9197
    """
9198
    assert self.export_mode in constants.EXPORT_MODES
9199

    
9200
    instance = self.instance
9201
    src_node = instance.primary_node
9202

    
9203
    if self.op.shutdown:
9204
      # shutdown the instance, but not the disks
9205
      feedback_fn("Shutting down instance %s" % instance.name)
9206
      result = self.rpc.call_instance_shutdown(src_node, instance,
9207
                                               self.shutdown_timeout)
9208
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9209
      result.Raise("Could not shutdown instance %s on"
9210
                   " node %s" % (instance.name, src_node))
9211

    
9212
    # set the disks ID correctly since call_instance_start needs the
9213
    # correct drbd minor to create the symlinks
9214
    for disk in instance.disks:
9215
      self.cfg.SetDiskID(disk, src_node)
9216

    
9217
    activate_disks = (not instance.admin_up)
9218

    
9219
    if activate_disks:
9220
      # Activate the instance disks if we'exporting a stopped instance
9221
      feedback_fn("Activating disks for %s" % instance.name)
9222
      _StartInstanceDisks(self, instance, None)
9223

    
9224
    try:
9225
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9226
                                                     instance)
9227

    
9228
      helper.CreateSnapshots()
9229
      try:
9230
        if (self.op.shutdown and instance.admin_up and
9231
            not self.remove_instance):
9232
          assert not activate_disks
9233
          feedback_fn("Starting instance %s" % instance.name)
9234
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9235
          msg = result.fail_msg
9236
          if msg:
9237
            feedback_fn("Failed to start instance: %s" % msg)
9238
            _ShutdownInstanceDisks(self, instance)
9239
            raise errors.OpExecError("Could not start instance: %s" % msg)
9240

    
9241
        if self.export_mode == constants.EXPORT_MODE_LOCAL:
9242
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9243
        elif self.export_mode == constants.EXPORT_MODE_REMOTE:
9244
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9245
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9246

    
9247
          (key_name, _, _) = self.x509_key_name
9248

    
9249
          dest_ca_pem = \
9250
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9251
                                            self.dest_x509_ca)
9252

    
9253
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9254
                                                     key_name, dest_ca_pem,
9255
                                                     timeouts)
9256
      finally:
9257
        helper.Cleanup()
9258

    
9259
      # Check for backwards compatibility
9260
      assert len(dresults) == len(instance.disks)
9261
      assert compat.all(isinstance(i, bool) for i in dresults), \
9262
             "Not all results are boolean: %r" % dresults
9263

    
9264
    finally:
9265
      if activate_disks:
9266
        feedback_fn("Deactivating disks for %s" % instance.name)
9267
        _ShutdownInstanceDisks(self, instance)
9268

    
9269
    # Remove instance if requested
9270
    if self.remove_instance:
9271
      if not (compat.all(dresults) and fin_resu):
9272
        feedback_fn("Not removing instance %s as parts of the export failed" %
9273
                    instance.name)
9274
      else:
9275
        feedback_fn("Removing instance %s" % instance.name)
9276
        _RemoveInstance(self, feedback_fn, instance,
9277
                        self.ignore_remove_failures)
9278

    
9279
    if self.export_mode == constants.EXPORT_MODE_LOCAL:
9280
      self._CleanupExports(feedback_fn)
9281

    
9282
    return fin_resu, dresults
9283

    
9284

    
9285
class LURemoveExport(NoHooksLU):
9286
  """Remove exports related to the named instance.
9287

9288
  """
9289
  _OP_REQP = ["instance_name"]
9290
  REQ_BGL = False
9291

    
9292
  def ExpandNames(self):
9293
    self.needed_locks = {}
9294
    # We need all nodes to be locked in order for RemoveExport to work, but we
9295
    # don't need to lock the instance itself, as nothing will happen to it (and
9296
    # we can remove exports also for a removed instance)
9297
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9298

    
9299
  def CheckPrereq(self):
9300
    """Check prerequisites.
9301
    """
9302
    pass
9303

    
9304
  def Exec(self, feedback_fn):
9305
    """Remove any export.
9306

9307
    """
9308
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9309
    # If the instance was not found we'll try with the name that was passed in.
9310
    # This will only work if it was an FQDN, though.
9311
    fqdn_warn = False
9312
    if not instance_name:
9313
      fqdn_warn = True
9314
      instance_name = self.op.instance_name
9315

    
9316
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9317
    exportlist = self.rpc.call_export_list(locked_nodes)
9318
    found = False
9319
    for node in exportlist:
9320
      msg = exportlist[node].fail_msg
9321
      if msg:
9322
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9323
        continue
9324
      if instance_name in exportlist[node].payload:
9325
        found = True
9326
        result = self.rpc.call_export_remove(node, instance_name)
9327
        msg = result.fail_msg
9328
        if msg:
9329
          logging.error("Could not remove export for instance %s"
9330
                        " on node %s: %s", instance_name, node, msg)
9331

    
9332
    if fqdn_warn and not found:
9333
      feedback_fn("Export not found. If trying to remove an export belonging"
9334
                  " to a deleted instance please use its Fully Qualified"
9335
                  " Domain Name.")
9336

    
9337

    
9338
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9339
  """Generic tags LU.
9340

9341
  This is an abstract class which is the parent of all the other tags LUs.
9342

9343
  """
9344

    
9345
  def ExpandNames(self):
9346
    self.needed_locks = {}
9347
    if self.op.kind == constants.TAG_NODE:
9348
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9349
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9350
    elif self.op.kind == constants.TAG_INSTANCE:
9351
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9352
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9353

    
9354
  def CheckPrereq(self):
9355
    """Check prerequisites.
9356

9357
    """
9358
    if self.op.kind == constants.TAG_CLUSTER:
9359
      self.target = self.cfg.GetClusterInfo()
9360
    elif self.op.kind == constants.TAG_NODE:
9361
      self.target = self.cfg.GetNodeInfo(self.op.name)
9362
    elif self.op.kind == constants.TAG_INSTANCE:
9363
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9364
    else:
9365
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9366
                                 str(self.op.kind), errors.ECODE_INVAL)
9367

    
9368

    
9369
class LUGetTags(TagsLU):
9370
  """Returns the tags of a given object.
9371

9372
  """
9373
  _OP_REQP = ["kind", "name"]
9374
  REQ_BGL = False
9375

    
9376
  def Exec(self, feedback_fn):
9377
    """Returns the tag list.
9378

9379
    """
9380
    return list(self.target.GetTags())
9381

    
9382

    
9383
class LUSearchTags(NoHooksLU):
9384
  """Searches the tags for a given pattern.
9385

9386
  """
9387
  _OP_REQP = ["pattern"]
9388
  REQ_BGL = False
9389

    
9390
  def ExpandNames(self):
9391
    self.needed_locks = {}
9392

    
9393
  def CheckPrereq(self):
9394
    """Check prerequisites.
9395

9396
    This checks the pattern passed for validity by compiling it.
9397

9398
    """
9399
    try:
9400
      self.re = re.compile(self.op.pattern)
9401
    except re.error, err:
9402
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9403
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9404

    
9405
  def Exec(self, feedback_fn):
9406
    """Returns the tag list.
9407

9408
    """
9409
    cfg = self.cfg
9410
    tgts = [("/cluster", cfg.GetClusterInfo())]
9411
    ilist = cfg.GetAllInstancesInfo().values()
9412
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9413
    nlist = cfg.GetAllNodesInfo().values()
9414
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9415
    results = []
9416
    for path, target in tgts:
9417
      for tag in target.GetTags():
9418
        if self.re.search(tag):
9419
          results.append((path, tag))
9420
    return results
9421

    
9422

    
9423
class LUAddTags(TagsLU):
9424
  """Sets a tag on a given object.
9425

9426
  """
9427
  _OP_REQP = ["kind", "name", "tags"]
9428
  REQ_BGL = False
9429

    
9430
  def CheckPrereq(self):
9431
    """Check prerequisites.
9432

9433
    This checks the type and length of the tag name and value.
9434

9435
    """
9436
    TagsLU.CheckPrereq(self)
9437
    for tag in self.op.tags:
9438
      objects.TaggableObject.ValidateTag(tag)
9439

    
9440
  def Exec(self, feedback_fn):
9441
    """Sets the tag.
9442

9443
    """
9444
    try:
9445
      for tag in self.op.tags:
9446
        self.target.AddTag(tag)
9447
    except errors.TagError, err:
9448
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9449
    self.cfg.Update(self.target, feedback_fn)
9450

    
9451

    
9452
class LUDelTags(TagsLU):
9453
  """Delete a list of tags from a given object.
9454

9455
  """
9456
  _OP_REQP = ["kind", "name", "tags"]
9457
  REQ_BGL = False
9458

    
9459
  def CheckPrereq(self):
9460
    """Check prerequisites.
9461

9462
    This checks that we have the given tag.
9463

9464
    """
9465
    TagsLU.CheckPrereq(self)
9466
    for tag in self.op.tags:
9467
      objects.TaggableObject.ValidateTag(tag)
9468
    del_tags = frozenset(self.op.tags)
9469
    cur_tags = self.target.GetTags()
9470
    if not del_tags <= cur_tags:
9471
      diff_tags = del_tags - cur_tags
9472
      diff_names = ["'%s'" % tag for tag in diff_tags]
9473
      diff_names.sort()
9474
      raise errors.OpPrereqError("Tag(s) %s not found" %
9475
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9476

    
9477
  def Exec(self, feedback_fn):
9478
    """Remove the tag from the object.
9479

9480
    """
9481
    for tag in self.op.tags:
9482
      self.target.RemoveTag(tag)
9483
    self.cfg.Update(self.target, feedback_fn)
9484

    
9485

    
9486
class LUTestDelay(NoHooksLU):
9487
  """Sleep for a specified amount of time.
9488

9489
  This LU sleeps on the master and/or nodes for a specified amount of
9490
  time.
9491

9492
  """
9493
  _OP_REQP = ["duration", "on_master", "on_nodes"]
9494
  REQ_BGL = False
9495

    
9496
  def ExpandNames(self):
9497
    """Expand names and set required locks.
9498

9499
    This expands the node list, if any.
9500

9501
    """
9502
    self.needed_locks = {}
9503
    if self.op.on_nodes:
9504
      # _GetWantedNodes can be used here, but is not always appropriate to use
9505
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9506
      # more information.
9507
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9508
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9509

    
9510
  def CheckPrereq(self):
9511
    """Check prerequisites.
9512

9513
    """
9514

    
9515
  def Exec(self, feedback_fn):
9516
    """Do the actual sleep.
9517

9518
    """
9519
    if self.op.on_master:
9520
      if not utils.TestDelay(self.op.duration):
9521
        raise errors.OpExecError("Error during master delay test")
9522
    if self.op.on_nodes:
9523
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9524
      for node, node_result in result.items():
9525
        node_result.Raise("Failure during rpc call to node %s" % node)
9526

    
9527

    
9528
class IAllocator(object):
9529
  """IAllocator framework.
9530

9531
  An IAllocator instance has three sets of attributes:
9532
    - cfg that is needed to query the cluster
9533
    - input data (all members of the _KEYS class attribute are required)
9534
    - four buffer attributes (in|out_data|text), that represent the
9535
      input (to the external script) in text and data structure format,
9536
      and the output from it, again in two formats
9537
    - the result variables from the script (success, info, nodes) for
9538
      easy usage
9539

9540
  """
9541
  # pylint: disable-msg=R0902
9542
  # lots of instance attributes
9543
  _ALLO_KEYS = [
9544
    "name", "mem_size", "disks", "disk_template",
9545
    "os", "tags", "nics", "vcpus", "hypervisor",
9546
    ]
9547
  _RELO_KEYS = [
9548
    "name", "relocate_from",
9549
    ]
9550
  _EVAC_KEYS = [
9551
    "evac_nodes",
9552
    ]
9553

    
9554
  def __init__(self, cfg, rpc, mode, **kwargs):
9555
    self.cfg = cfg
9556
    self.rpc = rpc
9557
    # init buffer variables
9558
    self.in_text = self.out_text = self.in_data = self.out_data = None
9559
    # init all input fields so that pylint is happy
9560
    self.mode = mode
9561
    self.mem_size = self.disks = self.disk_template = None
9562
    self.os = self.tags = self.nics = self.vcpus = None
9563
    self.hypervisor = None
9564
    self.relocate_from = None
9565
    self.name = None
9566
    self.evac_nodes = None
9567
    # computed fields
9568
    self.required_nodes = None
9569
    # init result fields
9570
    self.success = self.info = self.result = None
9571
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9572
      keyset = self._ALLO_KEYS
9573
      fn = self._AddNewInstance
9574
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9575
      keyset = self._RELO_KEYS
9576
      fn = self._AddRelocateInstance
9577
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9578
      keyset = self._EVAC_KEYS
9579
      fn = self._AddEvacuateNodes
9580
    else:
9581
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
9582
                                   " IAllocator" % self.mode)
9583
    for key in kwargs:
9584
      if key not in keyset:
9585
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
9586
                                     " IAllocator" % key)
9587
      setattr(self, key, kwargs[key])
9588

    
9589
    for key in keyset:
9590
      if key not in kwargs:
9591
        raise errors.ProgrammerError("Missing input parameter '%s' to"
9592
                                     " IAllocator" % key)
9593
    self._BuildInputData(fn)
9594

    
9595
  def _ComputeClusterData(self):
9596
    """Compute the generic allocator input data.
9597

9598
    This is the data that is independent of the actual operation.
9599

9600
    """
9601
    cfg = self.cfg
9602
    cluster_info = cfg.GetClusterInfo()
9603
    # cluster data
9604
    data = {
9605
      "version": constants.IALLOCATOR_VERSION,
9606
      "cluster_name": cfg.GetClusterName(),
9607
      "cluster_tags": list(cluster_info.GetTags()),
9608
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
9609
      # we don't have job IDs
9610
      }
9611
    iinfo = cfg.GetAllInstancesInfo().values()
9612
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
9613

    
9614
    # node data
9615
    node_results = {}
9616
    node_list = cfg.GetNodeList()
9617

    
9618
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9619
      hypervisor_name = self.hypervisor
9620
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9621
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
9622
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9623
      hypervisor_name = cluster_info.enabled_hypervisors[0]
9624

    
9625
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
9626
                                        hypervisor_name)
9627
    node_iinfo = \
9628
      self.rpc.call_all_instances_info(node_list,
9629
                                       cluster_info.enabled_hypervisors)
9630
    for nname, nresult in node_data.items():
9631
      # first fill in static (config-based) values
9632
      ninfo = cfg.GetNodeInfo(nname)
9633
      pnr = {
9634
        "tags": list(ninfo.GetTags()),
9635
        "primary_ip": ninfo.primary_ip,
9636
        "secondary_ip": ninfo.secondary_ip,
9637
        "offline": ninfo.offline,
9638
        "drained": ninfo.drained,
9639
        "master_candidate": ninfo.master_candidate,
9640
        }
9641

    
9642
      if not (ninfo.offline or ninfo.drained):
9643
        nresult.Raise("Can't get data for node %s" % nname)
9644
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
9645
                                nname)
9646
        remote_info = nresult.payload
9647

    
9648
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
9649
                     'vg_size', 'vg_free', 'cpu_total']:
9650
          if attr not in remote_info:
9651
            raise errors.OpExecError("Node '%s' didn't return attribute"
9652
                                     " '%s'" % (nname, attr))
9653
          if not isinstance(remote_info[attr], int):
9654
            raise errors.OpExecError("Node '%s' returned invalid value"
9655
                                     " for '%s': %s" %
9656
                                     (nname, attr, remote_info[attr]))
9657
        # compute memory used by primary instances
9658
        i_p_mem = i_p_up_mem = 0
9659
        for iinfo, beinfo in i_list:
9660
          if iinfo.primary_node == nname:
9661
            i_p_mem += beinfo[constants.BE_MEMORY]
9662
            if iinfo.name not in node_iinfo[nname].payload:
9663
              i_used_mem = 0
9664
            else:
9665
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
9666
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
9667
            remote_info['memory_free'] -= max(0, i_mem_diff)
9668

    
9669
            if iinfo.admin_up:
9670
              i_p_up_mem += beinfo[constants.BE_MEMORY]
9671

    
9672
        # compute memory used by instances
9673
        pnr_dyn = {
9674
          "total_memory": remote_info['memory_total'],
9675
          "reserved_memory": remote_info['memory_dom0'],
9676
          "free_memory": remote_info['memory_free'],
9677
          "total_disk": remote_info['vg_size'],
9678
          "free_disk": remote_info['vg_free'],
9679
          "total_cpus": remote_info['cpu_total'],
9680
          "i_pri_memory": i_p_mem,
9681
          "i_pri_up_memory": i_p_up_mem,
9682
          }
9683
        pnr.update(pnr_dyn)
9684

    
9685
      node_results[nname] = pnr
9686
    data["nodes"] = node_results
9687

    
9688
    # instance data
9689
    instance_data = {}
9690
    for iinfo, beinfo in i_list:
9691
      nic_data = []
9692
      for nic in iinfo.nics:
9693
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
9694
        nic_dict = {"mac": nic.mac,
9695
                    "ip": nic.ip,
9696
                    "mode": filled_params[constants.NIC_MODE],
9697
                    "link": filled_params[constants.NIC_LINK],
9698
                   }
9699
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
9700
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
9701
        nic_data.append(nic_dict)
9702
      pir = {
9703
        "tags": list(iinfo.GetTags()),
9704
        "admin_up": iinfo.admin_up,
9705
        "vcpus": beinfo[constants.BE_VCPUS],
9706
        "memory": beinfo[constants.BE_MEMORY],
9707
        "os": iinfo.os,
9708
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
9709
        "nics": nic_data,
9710
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
9711
        "disk_template": iinfo.disk_template,
9712
        "hypervisor": iinfo.hypervisor,
9713
        }
9714
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
9715
                                                 pir["disks"])
9716
      instance_data[iinfo.name] = pir
9717

    
9718
    data["instances"] = instance_data
9719

    
9720
    self.in_data = data
9721

    
9722
  def _AddNewInstance(self):
9723
    """Add new instance data to allocator structure.
9724

9725
    This in combination with _AllocatorGetClusterData will create the
9726
    correct structure needed as input for the allocator.
9727

9728
    The checks for the completeness of the opcode must have already been
9729
    done.
9730

9731
    """
9732
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
9733

    
9734
    if self.disk_template in constants.DTS_NET_MIRROR:
9735
      self.required_nodes = 2
9736
    else:
9737
      self.required_nodes = 1
9738
    request = {
9739
      "name": self.name,
9740
      "disk_template": self.disk_template,
9741
      "tags": self.tags,
9742
      "os": self.os,
9743
      "vcpus": self.vcpus,
9744
      "memory": self.mem_size,
9745
      "disks": self.disks,
9746
      "disk_space_total": disk_space,
9747
      "nics": self.nics,
9748
      "required_nodes": self.required_nodes,
9749
      }
9750
    return request
9751

    
9752
  def _AddRelocateInstance(self):
9753
    """Add relocate instance data to allocator structure.
9754

9755
    This in combination with _IAllocatorGetClusterData will create the
9756
    correct structure needed as input for the allocator.
9757

9758
    The checks for the completeness of the opcode must have already been
9759
    done.
9760

9761
    """
9762
    instance = self.cfg.GetInstanceInfo(self.name)
9763
    if instance is None:
9764
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
9765
                                   " IAllocator" % self.name)
9766

    
9767
    if instance.disk_template not in constants.DTS_NET_MIRROR:
9768
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
9769
                                 errors.ECODE_INVAL)
9770

    
9771
    if len(instance.secondary_nodes) != 1:
9772
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
9773
                                 errors.ECODE_STATE)
9774

    
9775
    self.required_nodes = 1
9776
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
9777
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
9778

    
9779
    request = {
9780
      "name": self.name,
9781
      "disk_space_total": disk_space,
9782
      "required_nodes": self.required_nodes,
9783
      "relocate_from": self.relocate_from,
9784
      }
9785
    return request
9786

    
9787
  def _AddEvacuateNodes(self):
9788
    """Add evacuate nodes data to allocator structure.
9789

9790
    """
9791
    request = {
9792
      "evac_nodes": self.evac_nodes
9793
      }
9794
    return request
9795

    
9796
  def _BuildInputData(self, fn):
9797
    """Build input data structures.
9798

9799
    """
9800
    self._ComputeClusterData()
9801

    
9802
    request = fn()
9803
    request["type"] = self.mode
9804
    self.in_data["request"] = request
9805

    
9806
    self.in_text = serializer.Dump(self.in_data)
9807

    
9808
  def Run(self, name, validate=True, call_fn=None):
9809
    """Run an instance allocator and return the results.
9810

9811
    """
9812
    if call_fn is None:
9813
      call_fn = self.rpc.call_iallocator_runner
9814

    
9815
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
9816
    result.Raise("Failure while running the iallocator script")
9817

    
9818
    self.out_text = result.payload
9819
    if validate:
9820
      self._ValidateResult()
9821

    
9822
  def _ValidateResult(self):
9823
    """Process the allocator results.
9824

9825
    This will process and if successful save the result in
9826
    self.out_data and the other parameters.
9827

9828
    """
9829
    try:
9830
      rdict = serializer.Load(self.out_text)
9831
    except Exception, err:
9832
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
9833

    
9834
    if not isinstance(rdict, dict):
9835
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
9836

    
9837
    # TODO: remove backwards compatiblity in later versions
9838
    if "nodes" in rdict and "result" not in rdict:
9839
      rdict["result"] = rdict["nodes"]
9840
      del rdict["nodes"]
9841

    
9842
    for key in "success", "info", "result":
9843
      if key not in rdict:
9844
        raise errors.OpExecError("Can't parse iallocator results:"
9845
                                 " missing key '%s'" % key)
9846
      setattr(self, key, rdict[key])
9847

    
9848
    if not isinstance(rdict["result"], list):
9849
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
9850
                               " is not a list")
9851
    self.out_data = rdict
9852

    
9853

    
9854
class LUTestAllocator(NoHooksLU):
9855
  """Run allocator tests.
9856

9857
  This LU runs the allocator tests
9858

9859
  """
9860
  _OP_REQP = ["direction", "mode", "name"]
9861

    
9862
  def CheckPrereq(self):
9863
    """Check prerequisites.
9864

9865
    This checks the opcode parameters depending on the director and mode test.
9866

9867
    """
9868
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9869
      for attr in ["name", "mem_size", "disks", "disk_template",
9870
                   "os", "tags", "nics", "vcpus"]:
9871
        if not hasattr(self.op, attr):
9872
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
9873
                                     attr, errors.ECODE_INVAL)
9874
      iname = self.cfg.ExpandInstanceName(self.op.name)
9875
      if iname is not None:
9876
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
9877
                                   iname, errors.ECODE_EXISTS)
9878
      if not isinstance(self.op.nics, list):
9879
        raise errors.OpPrereqError("Invalid parameter 'nics'",
9880
                                   errors.ECODE_INVAL)
9881
      for row in self.op.nics:
9882
        if (not isinstance(row, dict) or
9883
            "mac" not in row or
9884
            "ip" not in row or
9885
            "bridge" not in row):
9886
          raise errors.OpPrereqError("Invalid contents of the 'nics'"
9887
                                     " parameter", errors.ECODE_INVAL)
9888
      if not isinstance(self.op.disks, list):
9889
        raise errors.OpPrereqError("Invalid parameter 'disks'",
9890
                                   errors.ECODE_INVAL)
9891
      for row in self.op.disks:
9892
        if (not isinstance(row, dict) or
9893
            "size" not in row or
9894
            not isinstance(row["size"], int) or
9895
            "mode" not in row or
9896
            row["mode"] not in ['r', 'w']):
9897
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
9898
                                     " parameter", errors.ECODE_INVAL)
9899
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
9900
        self.op.hypervisor = self.cfg.GetHypervisorType()
9901
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9902
      if not hasattr(self.op, "name"):
9903
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input",
9904
                                   errors.ECODE_INVAL)
9905
      fname = _ExpandInstanceName(self.cfg, self.op.name)
9906
      self.op.name = fname
9907
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
9908
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9909
      if not hasattr(self.op, "evac_nodes"):
9910
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
9911
                                   " opcode input", errors.ECODE_INVAL)
9912
    else:
9913
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
9914
                                 self.op.mode, errors.ECODE_INVAL)
9915

    
9916
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
9917
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
9918
        raise errors.OpPrereqError("Missing allocator name",
9919
                                   errors.ECODE_INVAL)
9920
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
9921
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
9922
                                 self.op.direction, errors.ECODE_INVAL)
9923

    
9924
  def Exec(self, feedback_fn):
9925
    """Run the allocator test.
9926

9927
    """
9928
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9929
      ial = IAllocator(self.cfg, self.rpc,
9930
                       mode=self.op.mode,
9931
                       name=self.op.name,
9932
                       mem_size=self.op.mem_size,
9933
                       disks=self.op.disks,
9934
                       disk_template=self.op.disk_template,
9935
                       os=self.op.os,
9936
                       tags=self.op.tags,
9937
                       nics=self.op.nics,
9938
                       vcpus=self.op.vcpus,
9939
                       hypervisor=self.op.hypervisor,
9940
                       )
9941
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9942
      ial = IAllocator(self.cfg, self.rpc,
9943
                       mode=self.op.mode,
9944
                       name=self.op.name,
9945
                       relocate_from=list(self.relocate_from),
9946
                       )
9947
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9948
      ial = IAllocator(self.cfg, self.rpc,
9949
                       mode=self.op.mode,
9950
                       evac_nodes=self.op.evac_nodes)
9951
    else:
9952
      raise errors.ProgrammerError("Uncatched mode %s in"
9953
                                   " LUTestAllocator.Exec", self.op.mode)
9954

    
9955
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
9956
      result = ial.in_text
9957
    else:
9958
      ial.Run(self.op.allocator, validate=False)
9959
      result = ial.out_text
9960
    return result