Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 2c42c5df

History | View | Annotate | Download (332.4 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

    
48

    
49
class LogicalUnit(object):
50
  """Logical Unit base class.
51

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

61
  Note that all commands require root permissions.
62

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

66
  """
67
  HPATH = None
68
  HTYPE = None
69
  _OP_REQP = []
70
  REQ_BGL = True
71

    
72
  def __init__(self, processor, op, context, rpc):
73
    """Constructor for LogicalUnit.
74

75
    This needs to be overridden in derived classes in order to check op
76
    validity.
77

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

    
104
    # Tasklets
105
    self.tasklets = None
106

    
107
    for attr_name in self._OP_REQP:
108
      attr_val = getattr(op, attr_name, None)
109
      if attr_val is None:
110
        raise errors.OpPrereqError("Required parameter '%s' missing" %
111
                                   attr_name, errors.ECODE_INVAL)
112

    
113
    self.CheckArguments()
114

    
115
  def __GetSSH(self):
116
    """Returns the SshRunner object
117

118
    """
119
    if not self.__ssh:
120
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
121
    return self.__ssh
122

    
123
  ssh = property(fget=__GetSSH)
124

    
125
  def CheckArguments(self):
126
    """Check syntactic validity for the opcode arguments.
127

128
    This method is for doing a simple syntactic check and ensure
129
    validity of opcode parameters, without any cluster-related
130
    checks. While the same can be accomplished in ExpandNames and/or
131
    CheckPrereq, doing these separate is better because:
132

133
      - ExpandNames is left as as purely a lock-related function
134
      - CheckPrereq is run after we have acquired locks (and possible
135
        waited for them)
136

137
    The function is allowed to change the self.op attribute so that
138
    later methods can no longer worry about missing parameters.
139

140
    """
141
    pass
142

    
143
  def ExpandNames(self):
144
    """Expand names for this LU.
145

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

151
    LUs which implement this method must also populate the self.needed_locks
152
    member, as a dict with lock levels as keys, and a list of needed lock names
153
    as values. Rules:
154

155
      - use an empty dict if you don't need any lock
156
      - if you don't need any lock at a particular level omit that level
157
      - don't put anything for the BGL level
158
      - if you want all locks at a level use locking.ALL_SET as a value
159

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

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

168
    Examples::
169

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

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

    
191
  def DeclareLocks(self, level):
192
    """Declare LU locking needs for a level
193

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

201
    This function is only called if you have something already set in
202
    self.needed_locks for the level.
203

204
    @param level: Locking level which is going to be locked
205
    @type level: member of ganeti.locking.LEVELS
206

207
    """
208

    
209
  def CheckPrereq(self):
210
    """Check prerequisites for this LU.
211

212
    This method should check that the prerequisites for the execution
213
    of this LU are fulfilled. It can do internode communication, but
214
    it should be idempotent - no cluster or system changes are
215
    allowed.
216

217
    The method should raise errors.OpPrereqError in case something is
218
    not fulfilled. Its return value is ignored.
219

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

223
    """
224
    if self.tasklets is not None:
225
      for (idx, tl) in enumerate(self.tasklets):
226
        logging.debug("Checking prerequisites for tasklet %s/%s",
227
                      idx + 1, len(self.tasklets))
228
        tl.CheckPrereq()
229
    else:
230
      raise NotImplementedError
231

    
232
  def Exec(self, feedback_fn):
233
    """Execute the LU.
234

235
    This method should implement the actual work. It should raise
236
    errors.OpExecError for failures that are somewhat dealt with in
237
    code, or expected.
238

239
    """
240
    if self.tasklets is not None:
241
      for (idx, tl) in enumerate(self.tasklets):
242
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
243
        tl.Exec(feedback_fn)
244
    else:
245
      raise NotImplementedError
246

    
247
  def BuildHooksEnv(self):
248
    """Build hooks environment for this LU.
249

250
    This method should return a three-node tuple consisting of: a dict
251
    containing the environment that will be used for running the
252
    specific hook for this LU, a list of node names on which the hook
253
    should run before the execution, and a list of node names on which
254
    the hook should run after the execution.
255

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

261
    No nodes should be returned as an empty list (and not None).
262

263
    Note that if the HPATH for a LU class is None, this function will
264
    not be called.
265

266
    """
267
    raise NotImplementedError
268

    
269
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
270
    """Notify the LU about the results of its hooks.
271

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

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

287
    """
288
    # API must be kept, thus we ignore the unused argument and could
289
    # be a function warnings
290
    # pylint: disable-msg=W0613,R0201
291
    return lu_result
292

    
293
  def _ExpandAndLockInstance(self):
294
    """Helper function to expand and lock an instance.
295

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

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

    
312
  def _LockInstancesNodes(self, primary_only=False):
313
    """Helper function to declare instances' nodes for locking.
314

315
    This function should be called after locking one or more instances to lock
316
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
317
    with all primary or secondary nodes for instances already locked and
318
    present in self.needed_locks[locking.LEVEL_INSTANCE].
319

320
    It should be called from DeclareLocks, and for safety only works if
321
    self.recalculate_locks[locking.LEVEL_NODE] is set.
322

323
    In the future it may grow parameters to just lock some instance's nodes, or
324
    to just lock primaries or secondary nodes, if needed.
325

326
    If should be called in DeclareLocks in a way similar to::
327

328
      if level == locking.LEVEL_NODE:
329
        self._LockInstancesNodes()
330

331
    @type primary_only: boolean
332
    @param primary_only: only lock primary nodes of locked instances
333

334
    """
335
    assert locking.LEVEL_NODE in self.recalculate_locks, \
336
      "_LockInstancesNodes helper function called with no nodes to recalculate"
337

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

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

    
350
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
351
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
352
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
353
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
354

    
355
    del self.recalculate_locks[locking.LEVEL_NODE]
356

    
357

    
358
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
359
  """Simple LU which runs no hooks.
360

361
  This LU is intended as a parent for other LogicalUnits which will
362
  run no hooks, in order to reduce duplicate code.
363

364
  """
365
  HPATH = None
366
  HTYPE = None
367

    
368
  def BuildHooksEnv(self):
369
    """Empty BuildHooksEnv for NoHooksLu.
370

371
    This just raises an error.
372

373
    """
374
    assert False, "BuildHooksEnv called for NoHooksLUs"
375

    
376

    
377
class Tasklet:
378
  """Tasklet base class.
379

380
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
381
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
382
  tasklets know nothing about locks.
383

384
  Subclasses must follow these rules:
385
    - Implement CheckPrereq
386
    - Implement Exec
387

388
  """
389
  def __init__(self, lu):
390
    self.lu = lu
391

    
392
    # Shortcuts
393
    self.cfg = lu.cfg
394
    self.rpc = lu.rpc
395

    
396
  def CheckPrereq(self):
397
    """Check prerequisites for this tasklets.
398

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

403
    The method should raise errors.OpPrereqError in case something is not
404
    fulfilled. Its return value is ignored.
405

406
    This method should also update all parameters to their canonical form if it
407
    hasn't been done before.
408

409
    """
410
    raise NotImplementedError
411

    
412
  def Exec(self, feedback_fn):
413
    """Execute the tasklet.
414

415
    This method should implement the actual work. It should raise
416
    errors.OpExecError for failures that are somewhat dealt with in code, or
417
    expected.
418

419
    """
420
    raise NotImplementedError
421

    
422

    
423
def _GetWantedNodes(lu, nodes):
424
  """Returns list of checked and expanded node names.
425

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

434
  """
435
  if not isinstance(nodes, list):
436
    raise errors.OpPrereqError("Invalid argument type 'nodes'",
437
                               errors.ECODE_INVAL)
438

    
439
  if not nodes:
440
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
441
      " non-empty list of nodes whose name is to be expanded.")
442

    
443
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
444
  return utils.NiceSort(wanted)
445

    
446

    
447
def _GetWantedInstances(lu, instances):
448
  """Returns list of checked and expanded instance names.
449

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

459
  """
460
  if not isinstance(instances, list):
461
    raise errors.OpPrereqError("Invalid argument type 'instances'",
462
                               errors.ECODE_INVAL)
463

    
464
  if instances:
465
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
466
  else:
467
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
468
  return wanted
469

    
470

    
471
def _CheckOutputFields(static, dynamic, selected):
472
  """Checks whether all selected fields are valid.
473

474
  @type static: L{utils.FieldSet}
475
  @param static: static fields set
476
  @type dynamic: L{utils.FieldSet}
477
  @param dynamic: dynamic fields set
478

479
  """
480
  f = utils.FieldSet()
481
  f.Extend(static)
482
  f.Extend(dynamic)
483

    
484
  delta = f.NonMatching(selected)
485
  if delta:
486
    raise errors.OpPrereqError("Unknown output fields selected: %s"
487
                               % ",".join(delta), errors.ECODE_INVAL)
488

    
489

    
490
def _CheckBooleanOpField(op, name):
491
  """Validates boolean opcode parameters.
492

493
  This will ensure that an opcode parameter is either a boolean value,
494
  or None (but that it always exists).
495

496
  """
497
  val = getattr(op, name, None)
498
  if not (val is None or isinstance(val, bool)):
499
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
500
                               (name, str(val)), errors.ECODE_INVAL)
501
  setattr(op, name, val)
502

    
503

    
504
def _CheckGlobalHvParams(params):
505
  """Validates that given hypervisor params are not global ones.
506

507
  This will ensure that instances don't get customised versions of
508
  global params.
509

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

    
518

    
519
def _CheckNodeOnline(lu, node):
520
  """Ensure that a given node is online.
521

522
  @param lu: the LU on behalf of which we make the check
523
  @param node: the node to check
524
  @raise errors.OpPrereqError: if the node is offline
525

526
  """
527
  if lu.cfg.GetNodeInfo(node).offline:
528
    raise errors.OpPrereqError("Can't use offline node %s" % node,
529
                               errors.ECODE_INVAL)
530

    
531

    
532
def _CheckNodeNotDrained(lu, node):
533
  """Ensure that a given node is not drained.
534

535
  @param lu: the LU on behalf of which we make the check
536
  @param node: the node to check
537
  @raise errors.OpPrereqError: if the node is drained
538

539
  """
540
  if lu.cfg.GetNodeInfo(node).drained:
541
    raise errors.OpPrereqError("Can't use drained node %s" % node,
542
                               errors.ECODE_INVAL)
543

    
544

    
545
def _CheckNodeHasOS(lu, node, os_name, force_variant):
546
  """Ensure that a node supports a given OS.
547

548
  @param lu: the LU on behalf of which we make the check
549
  @param node: the node to check
550
  @param os_name: the OS to query about
551
  @param force_variant: whether to ignore variant errors
552
  @raise errors.OpPrereqError: if the node is not supporting the OS
553

554
  """
555
  result = lu.rpc.call_os_get(node, os_name)
556
  result.Raise("OS '%s' not in supported OS list for node %s" %
557
               (os_name, node),
558
               prereq=True, ecode=errors.ECODE_INVAL)
559
  if not force_variant:
560
    _CheckOSVariant(result.payload, os_name)
561

    
562

    
563
def _CheckDiskTemplate(template):
564
  """Ensure a given disk template is valid.
565

566
  """
567
  if template not in constants.DISK_TEMPLATES:
568
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
569
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
570
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
571

    
572

    
573
def _CheckInstanceDown(lu, instance, reason):
574
  """Ensure that an instance is not running."""
575
  if instance.admin_up:
576
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
577
                               (instance.name, reason), errors.ECODE_STATE)
578

    
579
  pnode = instance.primary_node
580
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
581
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
582
              prereq=True, ecode=errors.ECODE_ENVIRON)
583

    
584
  if instance.name in ins_l.payload:
585
    raise errors.OpPrereqError("Instance %s is running, %s" %
586
                               (instance.name, reason), errors.ECODE_STATE)
587

    
588

    
589
def _ExpandItemName(fn, name, kind):
590
  """Expand an item name.
591

592
  @param fn: the function to use for expansion
593
  @param name: requested item name
594
  @param kind: text description ('Node' or 'Instance')
595
  @return: the resolved (full) name
596
  @raise errors.OpPrereqError: if the item is not found
597

598
  """
599
  full_name = fn(name)
600
  if full_name is None:
601
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
602
                               errors.ECODE_NOENT)
603
  return full_name
604

    
605

    
606
def _ExpandNodeName(cfg, name):
607
  """Wrapper over L{_ExpandItemName} for nodes."""
608
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
609

    
610

    
611
def _ExpandInstanceName(cfg, name):
612
  """Wrapper over L{_ExpandItemName} for instance."""
613
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
614

    
615

    
616
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
617
                          memory, vcpus, nics, disk_template, disks,
618
                          bep, hvp, hypervisor_name):
619
  """Builds instance related env variables for hooks
620

621
  This builds the hook environment from individual variables.
622

623
  @type name: string
624
  @param name: the name of the instance
625
  @type primary_node: string
626
  @param primary_node: the name of the instance's primary node
627
  @type secondary_nodes: list
628
  @param secondary_nodes: list of secondary nodes as strings
629
  @type os_type: string
630
  @param os_type: the name of the instance's OS
631
  @type status: boolean
632
  @param status: the should_run status of the instance
633
  @type memory: string
634
  @param memory: the memory size of the instance
635
  @type vcpus: string
636
  @param vcpus: the count of VCPUs the instance has
637
  @type nics: list
638
  @param nics: list of tuples (ip, mac, mode, link) representing
639
      the NICs the instance has
640
  @type disk_template: string
641
  @param disk_template: the disk template of the instance
642
  @type disks: list
643
  @param disks: the list of (size, mode) pairs
644
  @type bep: dict
645
  @param bep: the backend parameters for the instance
646
  @type hvp: dict
647
  @param hvp: the hypervisor parameters for the instance
648
  @type hypervisor_name: string
649
  @param hypervisor_name: the hypervisor for the instance
650
  @rtype: dict
651
  @return: the hook environment for this instance
652

653
  """
654
  if status:
655
    str_status = "up"
656
  else:
657
    str_status = "down"
658
  env = {
659
    "OP_TARGET": name,
660
    "INSTANCE_NAME": name,
661
    "INSTANCE_PRIMARY": primary_node,
662
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
663
    "INSTANCE_OS_TYPE": os_type,
664
    "INSTANCE_STATUS": str_status,
665
    "INSTANCE_MEMORY": memory,
666
    "INSTANCE_VCPUS": vcpus,
667
    "INSTANCE_DISK_TEMPLATE": disk_template,
668
    "INSTANCE_HYPERVISOR": hypervisor_name,
669
  }
670

    
671
  if nics:
672
    nic_count = len(nics)
673
    for idx, (ip, mac, mode, link) in enumerate(nics):
674
      if ip is None:
675
        ip = ""
676
      env["INSTANCE_NIC%d_IP" % idx] = ip
677
      env["INSTANCE_NIC%d_MAC" % idx] = mac
678
      env["INSTANCE_NIC%d_MODE" % idx] = mode
679
      env["INSTANCE_NIC%d_LINK" % idx] = link
680
      if mode == constants.NIC_MODE_BRIDGED:
681
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
682
  else:
683
    nic_count = 0
684

    
685
  env["INSTANCE_NIC_COUNT"] = nic_count
686

    
687
  if disks:
688
    disk_count = len(disks)
689
    for idx, (size, mode) in enumerate(disks):
690
      env["INSTANCE_DISK%d_SIZE" % idx] = size
691
      env["INSTANCE_DISK%d_MODE" % idx] = mode
692
  else:
693
    disk_count = 0
694

    
695
  env["INSTANCE_DISK_COUNT"] = disk_count
696

    
697
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
698
    for key, value in source.items():
699
      env["INSTANCE_%s_%s" % (kind, key)] = value
700

    
701
  return env
702

    
703

    
704
def _NICListToTuple(lu, nics):
705
  """Build a list of nic information tuples.
706

707
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
708
  value in LUQueryInstanceData.
709

710
  @type lu:  L{LogicalUnit}
711
  @param lu: the logical unit on whose behalf we execute
712
  @type nics: list of L{objects.NIC}
713
  @param nics: list of nics to convert to hooks tuples
714

715
  """
716
  hooks_nics = []
717
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
718
  for nic in nics:
719
    ip = nic.ip
720
    mac = nic.mac
721
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
722
    mode = filled_params[constants.NIC_MODE]
723
    link = filled_params[constants.NIC_LINK]
724
    hooks_nics.append((ip, mac, mode, link))
725
  return hooks_nics
726

    
727

    
728
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
729
  """Builds instance related env variables for hooks from an object.
730

731
  @type lu: L{LogicalUnit}
732
  @param lu: the logical unit on whose behalf we execute
733
  @type instance: L{objects.Instance}
734
  @param instance: the instance for which we should build the
735
      environment
736
  @type override: dict
737
  @param override: dictionary with key/values that will override
738
      our values
739
  @rtype: dict
740
  @return: the hook environment dictionary
741

742
  """
743
  cluster = lu.cfg.GetClusterInfo()
744
  bep = cluster.FillBE(instance)
745
  hvp = cluster.FillHV(instance)
746
  args = {
747
    'name': instance.name,
748
    'primary_node': instance.primary_node,
749
    'secondary_nodes': instance.secondary_nodes,
750
    'os_type': instance.os,
751
    'status': instance.admin_up,
752
    'memory': bep[constants.BE_MEMORY],
753
    'vcpus': bep[constants.BE_VCPUS],
754
    'nics': _NICListToTuple(lu, instance.nics),
755
    'disk_template': instance.disk_template,
756
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
757
    'bep': bep,
758
    'hvp': hvp,
759
    'hypervisor_name': instance.hypervisor,
760
  }
761
  if override:
762
    args.update(override)
763
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
764

    
765

    
766
def _AdjustCandidatePool(lu, exceptions):
767
  """Adjust the candidate pool after node operations.
768

769
  """
770
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
771
  if mod_list:
772
    lu.LogInfo("Promoted nodes to master candidate role: %s",
773
               utils.CommaJoin(node.name for node in mod_list))
774
    for name in mod_list:
775
      lu.context.ReaddNode(name)
776
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
777
  if mc_now > mc_max:
778
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
779
               (mc_now, mc_max))
780

    
781

    
782
def _DecideSelfPromotion(lu, exceptions=None):
783
  """Decide whether I should promote myself as a master candidate.
784

785
  """
786
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
787
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
788
  # the new node will increase mc_max with one, so:
789
  mc_should = min(mc_should + 1, cp_size)
790
  return mc_now < mc_should
791

    
792

    
793
def _CheckNicsBridgesExist(lu, target_nics, target_node,
794
                               profile=constants.PP_DEFAULT):
795
  """Check that the brigdes needed by a list of nics exist.
796

797
  """
798
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
799
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
800
                for nic in target_nics]
801
  brlist = [params[constants.NIC_LINK] for params in paramslist
802
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
803
  if brlist:
804
    result = lu.rpc.call_bridges_exist(target_node, brlist)
805
    result.Raise("Error checking bridges on destination node '%s'" %
806
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
807

    
808

    
809
def _CheckInstanceBridgesExist(lu, instance, node=None):
810
  """Check that the brigdes needed by an instance exist.
811

812
  """
813
  if node is None:
814
    node = instance.primary_node
815
  _CheckNicsBridgesExist(lu, instance.nics, node)
816

    
817

    
818
def _CheckOSVariant(os_obj, name):
819
  """Check whether an OS name conforms to the os variants specification.
820

821
  @type os_obj: L{objects.OS}
822
  @param os_obj: OS object to check
823
  @type name: string
824
  @param name: OS name passed by the user, to check for validity
825

826
  """
827
  if not os_obj.supported_variants:
828
    return
829
  try:
830
    variant = name.split("+", 1)[1]
831
  except IndexError:
832
    raise errors.OpPrereqError("OS name must include a variant",
833
                               errors.ECODE_INVAL)
834

    
835
  if variant not in os_obj.supported_variants:
836
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
837

    
838

    
839
def _GetNodeInstancesInner(cfg, fn):
840
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
841

    
842

    
843
def _GetNodeInstances(cfg, node_name):
844
  """Returns a list of all primary and secondary instances on a node.
845

846
  """
847

    
848
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
849

    
850

    
851
def _GetNodePrimaryInstances(cfg, node_name):
852
  """Returns primary instances on a node.
853

854
  """
855
  return _GetNodeInstancesInner(cfg,
856
                                lambda inst: node_name == inst.primary_node)
857

    
858

    
859
def _GetNodeSecondaryInstances(cfg, node_name):
860
  """Returns secondary instances on a node.
861

862
  """
863
  return _GetNodeInstancesInner(cfg,
864
                                lambda inst: node_name in inst.secondary_nodes)
865

    
866

    
867
def _GetStorageTypeArgs(cfg, storage_type):
868
  """Returns the arguments for a storage type.
869

870
  """
871
  # Special case for file storage
872
  if storage_type == constants.ST_FILE:
873
    # storage.FileStorage wants a list of storage directories
874
    return [[cfg.GetFileStorageDir()]]
875

    
876
  return []
877

    
878

    
879
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
880
  faulty = []
881

    
882
  for dev in instance.disks:
883
    cfg.SetDiskID(dev, node_name)
884

    
885
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
886
  result.Raise("Failed to get disk status from node %s" % node_name,
887
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
888

    
889
  for idx, bdev_status in enumerate(result.payload):
890
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
891
      faulty.append(idx)
892

    
893
  return faulty
894

    
895

    
896
def _FormatTimestamp(secs):
897
  """Formats a Unix timestamp with the local timezone.
898

899
  """
900
  return time.strftime("%F %T %Z", time.gmtime(secs))
901

    
902

    
903
class LUPostInitCluster(LogicalUnit):
904
  """Logical unit for running hooks after cluster initialization.
905

906
  """
907
  HPATH = "cluster-init"
908
  HTYPE = constants.HTYPE_CLUSTER
909
  _OP_REQP = []
910

    
911
  def BuildHooksEnv(self):
912
    """Build hooks env.
913

914
    """
915
    env = {"OP_TARGET": self.cfg.GetClusterName()}
916
    mn = self.cfg.GetMasterNode()
917
    return env, [], [mn]
918

    
919
  def CheckPrereq(self):
920
    """No prerequisites to check.
921

922
    """
923
    return True
924

    
925
  def Exec(self, feedback_fn):
926
    """Nothing to do.
927

928
    """
929
    return True
930

    
931

    
932
class LUDestroyCluster(LogicalUnit):
933
  """Logical unit for destroying the cluster.
934

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

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

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

    
947
  def CheckPrereq(self):
948
    """Check prerequisites.
949

950
    This checks whether the cluster is empty.
951

952
    Any errors are signaled by raising errors.OpPrereqError.
953

954
    """
955
    master = self.cfg.GetMasterNode()
956

    
957
    nodelist = self.cfg.GetNodeList()
958
    if len(nodelist) != 1 or nodelist[0] != master:
959
      raise errors.OpPrereqError("There are still %d node(s) in"
960
                                 " this cluster." % (len(nodelist) - 1),
961
                                 errors.ECODE_INVAL)
962
    instancelist = self.cfg.GetInstanceList()
963
    if instancelist:
964
      raise errors.OpPrereqError("There are still %d instance(s) in"
965
                                 " this cluster." % len(instancelist),
966
                                 errors.ECODE_INVAL)
967

    
968
  def Exec(self, feedback_fn):
969
    """Destroys the cluster.
970

971
    """
972
    master = self.cfg.GetMasterNode()
973
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
974

    
975
    # Run post hooks on master node before it's removed
976
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
977
    try:
978
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
979
    except:
980
      # pylint: disable-msg=W0702
981
      self.LogWarning("Errors occurred running hooks on %s" % master)
982

    
983
    result = self.rpc.call_node_stop_master(master, False)
984
    result.Raise("Could not disable the master role")
985

    
986
    if modify_ssh_setup:
987
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
988
      utils.CreateBackup(priv_key)
989
      utils.CreateBackup(pub_key)
990

    
991
    return master
992

    
993

    
994
def _VerifyCertificateInner(filename, expired, not_before, not_after, now,
995
                            warn_days=constants.SSL_CERT_EXPIRATION_WARN,
996
                            error_days=constants.SSL_CERT_EXPIRATION_ERROR):
997
  """Verifies certificate details for LUVerifyCluster.
998

999
  """
1000
  if expired:
1001
    msg = "Certificate %s is expired" % filename
1002

    
1003
    if not_before is not None and not_after is not None:
1004
      msg += (" (valid from %s to %s)" %
1005
              (_FormatTimestamp(not_before),
1006
               _FormatTimestamp(not_after)))
1007
    elif not_before is not None:
1008
      msg += " (valid from %s)" % _FormatTimestamp(not_before)
1009
    elif not_after is not None:
1010
      msg += " (valid until %s)" % _FormatTimestamp(not_after)
1011

    
1012
    return (LUVerifyCluster.ETYPE_ERROR, msg)
1013

    
1014
  elif not_before is not None and not_before > now:
1015
    return (LUVerifyCluster.ETYPE_WARNING,
1016
            "Certificate %s not yet valid (valid from %s)" %
1017
            (filename, _FormatTimestamp(not_before)))
1018

    
1019
  elif not_after is not None:
1020
    remaining_days = int((not_after - now) / (24 * 3600))
1021

    
1022
    msg = ("Certificate %s expires in %d days" % (filename, remaining_days))
1023

    
1024
    if remaining_days <= error_days:
1025
      return (LUVerifyCluster.ETYPE_ERROR, msg)
1026

    
1027
    if remaining_days <= warn_days:
1028
      return (LUVerifyCluster.ETYPE_WARNING, msg)
1029

    
1030
  return (None, None)
1031

    
1032

    
1033
def _VerifyCertificate(filename):
1034
  """Verifies a certificate for LUVerifyCluster.
1035

1036
  @type filename: string
1037
  @param filename: Path to PEM file
1038

1039
  """
1040
  try:
1041
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1042
                                           utils.ReadFile(filename))
1043
  except Exception, err: # pylint: disable-msg=W0703
1044
    return (LUVerifyCluster.ETYPE_ERROR,
1045
            "Failed to load X509 certificate %s: %s" % (filename, err))
1046

    
1047
  # Depending on the pyOpenSSL version, this can just return (None, None)
1048
  (not_before, not_after) = utils.GetX509CertValidity(cert)
1049

    
1050
  return _VerifyCertificateInner(filename, cert.has_expired(),
1051
                                 not_before, not_after, time.time())
1052

    
1053

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1179
    Test list:
1180

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

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

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

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

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

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

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

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

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

    
1238

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

    
1244
    return True
1245

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1346
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1347
    """Verify an instance.
1348

1349
    This function checks to see if the required block devices are
1350
    available on the instance's node.
1351

1352
    """
1353
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1354
    node_current = instanceconfig.primary_node
1355

    
1356
    node_vol_should = {}
1357
    instanceconfig.MapLVsByNode(node_vol_should)
1358

    
1359
    for node in node_vol_should:
1360
      n_img = node_image[node]
1361
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1362
        # ignore missing volumes on offline or broken nodes
1363
        continue
1364
      for volume in node_vol_should[node]:
1365
        test = volume not in n_img.volumes
1366
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1367
                 "volume %s missing on node %s", volume, node)
1368

    
1369
    if instanceconfig.admin_up:
1370
      pri_img = node_image[node_current]
1371
      test = instance not in pri_img.instances and not pri_img.offline
1372
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1373
               "instance not running on its primary node %s",
1374
               node_current)
1375

    
1376
    for node, n_img in node_image.items():
1377
      if (not node == node_current):
1378
        test = instance in n_img.instances
1379
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1380
                 "instance should not run on node %s", node)
1381

    
1382
  def _VerifyOrphanVolumes(self, node_vol_should, node_image):
1383
    """Verify if there are any unknown volumes in the cluster.
1384

1385
    The .os, .swap and backup volumes are ignored. All other volumes are
1386
    reported as unknown.
1387

1388
    """
1389
    for node, n_img in node_image.items():
1390
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1391
        # skip non-healthy nodes
1392
        continue
1393
      for volume in n_img.volumes:
1394
        test = (node not in node_vol_should or
1395
                volume not in node_vol_should[node])
1396
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1397
                      "volume %s is unknown", volume)
1398

    
1399
  def _VerifyOrphanInstances(self, instancelist, node_image):
1400
    """Verify the list of running instances.
1401

1402
    This checks what instances are running but unknown to the cluster.
1403

1404
    """
1405
    for node, n_img in node_image.items():
1406
      for o_inst in n_img.instances:
1407
        test = o_inst not in instancelist
1408
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1409
                      "instance %s on node %s should not exist", o_inst, node)
1410

    
1411
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1412
    """Verify N+1 Memory Resilience.
1413

1414
    Check that if one single node dies we can still start all the
1415
    instances it was primary for.
1416

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

    
1438
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1439
                       master_files):
1440
    """Verifies and computes the node required file checksums.
1441

1442
    @type ninfo: L{objects.Node}
1443
    @param ninfo: the node to check
1444
    @param nresult: the remote results for the node
1445
    @param file_list: required list of files
1446
    @param local_cksum: dictionary of local files and their checksums
1447
    @param master_files: list of files that only masters should have
1448

1449
    """
1450
    node = ninfo.name
1451
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1452

    
1453
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1454
    test = not isinstance(remote_cksum, dict)
1455
    _ErrorIf(test, self.ENODEFILECHECK, node,
1456
             "node hasn't returned file checksum data")
1457
    if test:
1458
      return
1459

    
1460
    for file_name in file_list:
1461
      node_is_mc = ninfo.master_candidate
1462
      must_have = (file_name not in master_files) or node_is_mc
1463
      # missing
1464
      test1 = file_name not in remote_cksum
1465
      # invalid checksum
1466
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1467
      # existing and good
1468
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1469
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1470
               "file '%s' missing", file_name)
1471
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1472
               "file '%s' has wrong checksum", file_name)
1473
      # not candidate and this is not a must-have file
1474
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1475
               "file '%s' should not exist on non master"
1476
               " candidates (and the file is outdated)", file_name)
1477
      # all good, except non-master/non-must have combination
1478
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1479
               "file '%s' should not exist"
1480
               " on non master candidates", file_name)
1481

    
1482
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_map):
1483
    """Verifies and the node DRBD status.
1484

1485
    @type ninfo: L{objects.Node}
1486
    @param ninfo: the node to check
1487
    @param nresult: the remote results for the node
1488
    @param instanceinfo: the dict of instances
1489
    @param drbd_map: the DRBD map as returned by
1490
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1491

1492
    """
1493
    node = ninfo.name
1494
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1495

    
1496
    # compute the DRBD minors
1497
    node_drbd = {}
1498
    for minor, instance in drbd_map[node].items():
1499
      test = instance not in instanceinfo
1500
      _ErrorIf(test, self.ECLUSTERCFG, None,
1501
               "ghost instance '%s' in temporary DRBD map", instance)
1502
        # ghost instance should not be running, but otherwise we
1503
        # don't give double warnings (both ghost instance and
1504
        # unallocated minor in use)
1505
      if test:
1506
        node_drbd[minor] = (instance, False)
1507
      else:
1508
        instance = instanceinfo[instance]
1509
        node_drbd[minor] = (instance.name, instance.admin_up)
1510

    
1511
    # and now check them
1512
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1513
    test = not isinstance(used_minors, (tuple, list))
1514
    _ErrorIf(test, self.ENODEDRBD, node,
1515
             "cannot parse drbd status file: %s", str(used_minors))
1516
    if test:
1517
      # we cannot check drbd status
1518
      return
1519

    
1520
    for minor, (iname, must_exist) in node_drbd.items():
1521
      test = minor not in used_minors and must_exist
1522
      _ErrorIf(test, self.ENODEDRBD, node,
1523
               "drbd minor %d of instance %s is not active", minor, iname)
1524
    for minor in used_minors:
1525
      test = minor not in node_drbd
1526
      _ErrorIf(test, self.ENODEDRBD, node,
1527
               "unallocated drbd minor %d is in use", minor)
1528

    
1529
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1530
    """Verifies and updates the node volume data.
1531

1532
    This function will update a L{NodeImage}'s internal structures
1533
    with data from the remote call.
1534

1535
    @type ninfo: L{objects.Node}
1536
    @param ninfo: the node to check
1537
    @param nresult: the remote results for the node
1538
    @param nimg: the node image object
1539
    @param vg_name: the configured VG name
1540

1541
    """
1542
    node = ninfo.name
1543
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1544

    
1545
    nimg.lvm_fail = True
1546
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1547
    if vg_name is None:
1548
      pass
1549
    elif isinstance(lvdata, basestring):
1550
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1551
               utils.SafeEncode(lvdata))
1552
    elif not isinstance(lvdata, dict):
1553
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1554
    else:
1555
      nimg.volumes = lvdata
1556
      nimg.lvm_fail = False
1557

    
1558
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1559
    """Verifies and updates the node instance list.
1560

1561
    If the listing was successful, then updates this node's instance
1562
    list. Otherwise, it marks the RPC call as failed for the instance
1563
    list key.
1564

1565
    @type ninfo: L{objects.Node}
1566
    @param ninfo: the node to check
1567
    @param nresult: the remote results for the node
1568
    @param nimg: the node image object
1569

1570
    """
1571
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1572
    test = not isinstance(idata, list)
1573
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1574
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1575
    if test:
1576
      nimg.hyp_fail = True
1577
    else:
1578
      nimg.instances = idata
1579

    
1580
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1581
    """Verifies and computes a node information map
1582

1583
    @type ninfo: L{objects.Node}
1584
    @param ninfo: the node to check
1585
    @param nresult: the remote results for the node
1586
    @param nimg: the node image object
1587
    @param vg_name: the configured VG name
1588

1589
    """
1590
    node = ninfo.name
1591
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1592

    
1593
    # try to read free memory (from the hypervisor)
1594
    hv_info = nresult.get(constants.NV_HVINFO, None)
1595
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1596
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1597
    if not test:
1598
      try:
1599
        nimg.mfree = int(hv_info["memory_free"])
1600
      except (ValueError, TypeError):
1601
        _ErrorIf(True, self.ENODERPC, node,
1602
                 "node returned invalid nodeinfo, check hypervisor")
1603

    
1604
    # FIXME: devise a free space model for file based instances as well
1605
    if vg_name is not None:
1606
      test = (constants.NV_VGLIST not in nresult or
1607
              vg_name not in nresult[constants.NV_VGLIST])
1608
      _ErrorIf(test, self.ENODELVM, node,
1609
               "node didn't return data for the volume group '%s'"
1610
               " - it is either missing or broken", vg_name)
1611
      if not test:
1612
        try:
1613
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1614
        except (ValueError, TypeError):
1615
          _ErrorIf(True, self.ENODERPC, node,
1616
                   "node returned invalid LVM info, check LVM status")
1617

    
1618
  def CheckPrereq(self):
1619
    """Check prerequisites.
1620

1621
    Transform the list of checks we're going to skip into a set and check that
1622
    all its members are valid.
1623

1624
    """
1625
    self.skip_set = frozenset(self.op.skip_checks)
1626
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1627
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1628
                                 errors.ECODE_INVAL)
1629

    
1630
  def BuildHooksEnv(self):
1631
    """Build hooks env.
1632

1633
    Cluster-Verify hooks just ran in the post phase and their failure makes
1634
    the output be logged in the verify output and the verification to fail.
1635

1636
    """
1637
    all_nodes = self.cfg.GetNodeList()
1638
    env = {
1639
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1640
      }
1641
    for node in self.cfg.GetAllNodesInfo().values():
1642
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1643

    
1644
    return env, [], all_nodes
1645

    
1646
  def Exec(self, feedback_fn):
1647
    """Verify integrity of cluster, performing various test on nodes.
1648

1649
    """
1650
    self.bad = False
1651
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1652
    verbose = self.op.verbose
1653
    self._feedback_fn = feedback_fn
1654
    feedback_fn("* Verifying global settings")
1655
    for msg in self.cfg.VerifyConfig():
1656
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1657

    
1658
    # Check the cluster certificates
1659
    for cert_filename in constants.ALL_CERT_FILES:
1660
      (errcode, msg) = _VerifyCertificate(cert_filename)
1661
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1662

    
1663
    vg_name = self.cfg.GetVGName()
1664
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1665
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1666
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1667
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1668
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1669
                        for iname in instancelist)
1670
    i_non_redundant = [] # Non redundant instances
1671
    i_non_a_balanced = [] # Non auto-balanced instances
1672
    n_offline = 0 # Count of offline nodes
1673
    n_drained = 0 # Count of nodes being drained
1674
    node_vol_should = {}
1675

    
1676
    # FIXME: verify OS list
1677
    # do local checksums
1678
    master_files = [constants.CLUSTER_CONF_FILE]
1679

    
1680
    file_names = ssconf.SimpleStore().GetFileList()
1681
    file_names.extend(constants.ALL_CERT_FILES)
1682
    file_names.extend(master_files)
1683

    
1684
    local_checksums = utils.FingerprintFiles(file_names)
1685

    
1686
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1687
    node_verify_param = {
1688
      constants.NV_FILELIST: file_names,
1689
      constants.NV_NODELIST: [node.name for node in nodeinfo
1690
                              if not node.offline],
1691
      constants.NV_HYPERVISOR: hypervisors,
1692
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1693
                                  node.secondary_ip) for node in nodeinfo
1694
                                 if not node.offline],
1695
      constants.NV_INSTANCELIST: hypervisors,
1696
      constants.NV_VERSION: None,
1697
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1698
      constants.NV_NODESETUP: None,
1699
      constants.NV_TIME: None,
1700
      }
1701

    
1702
    if vg_name is not None:
1703
      node_verify_param[constants.NV_VGLIST] = None
1704
      node_verify_param[constants.NV_LVLIST] = vg_name
1705
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1706
      node_verify_param[constants.NV_DRBDLIST] = None
1707

    
1708
    # Build our expected cluster state
1709
    node_image = dict((node.name, self.NodeImage(offline=node.offline))
1710
                      for node in nodeinfo)
1711

    
1712
    for instance in instancelist:
1713
      inst_config = instanceinfo[instance]
1714

    
1715
      for nname in inst_config.all_nodes:
1716
        if nname not in node_image:
1717
          # ghost node
1718
          gnode = self.NodeImage()
1719
          gnode.ghost = True
1720
          node_image[nname] = gnode
1721

    
1722
      inst_config.MapLVsByNode(node_vol_should)
1723

    
1724
      pnode = inst_config.primary_node
1725
      node_image[pnode].pinst.append(instance)
1726

    
1727
      for snode in inst_config.secondary_nodes:
1728
        nimg = node_image[snode]
1729
        nimg.sinst.append(instance)
1730
        if pnode not in nimg.sbp:
1731
          nimg.sbp[pnode] = []
1732
        nimg.sbp[pnode].append(instance)
1733

    
1734
    # At this point, we have the in-memory data structures complete,
1735
    # except for the runtime information, which we'll gather next
1736

    
1737
    # Due to the way our RPC system works, exact response times cannot be
1738
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
1739
    # time before and after executing the request, we can at least have a time
1740
    # window.
1741
    nvinfo_starttime = time.time()
1742
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1743
                                           self.cfg.GetClusterName())
1744
    nvinfo_endtime = time.time()
1745

    
1746
    cluster = self.cfg.GetClusterInfo()
1747
    master_node = self.cfg.GetMasterNode()
1748
    all_drbd_map = self.cfg.ComputeDRBDMap()
1749

    
1750
    feedback_fn("* Verifying node status")
1751
    for node_i in nodeinfo:
1752
      node = node_i.name
1753
      nimg = node_image[node]
1754

    
1755
      if node_i.offline:
1756
        if verbose:
1757
          feedback_fn("* Skipping offline node %s" % (node,))
1758
        n_offline += 1
1759
        continue
1760

    
1761
      if node == master_node:
1762
        ntype = "master"
1763
      elif node_i.master_candidate:
1764
        ntype = "master candidate"
1765
      elif node_i.drained:
1766
        ntype = "drained"
1767
        n_drained += 1
1768
      else:
1769
        ntype = "regular"
1770
      if verbose:
1771
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1772

    
1773
      msg = all_nvinfo[node].fail_msg
1774
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1775
      if msg:
1776
        nimg.rpc_fail = True
1777
        continue
1778

    
1779
      nresult = all_nvinfo[node].payload
1780

    
1781
      nimg.call_ok = self._VerifyNode(node_i, nresult)
1782
      self._VerifyNodeNetwork(node_i, nresult)
1783
      self._VerifyNodeLVM(node_i, nresult, vg_name)
1784
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
1785
                            master_files)
1786
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, all_drbd_map)
1787
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
1788

    
1789
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
1790
      self._UpdateNodeInstances(node_i, nresult, nimg)
1791
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
1792

    
1793
    feedback_fn("* Verifying instance status")
1794
    for instance in instancelist:
1795
      if verbose:
1796
        feedback_fn("* Verifying instance %s" % instance)
1797
      inst_config = instanceinfo[instance]
1798
      self._VerifyInstance(instance, inst_config, node_image)
1799
      inst_nodes_offline = []
1800

    
1801
      pnode = inst_config.primary_node
1802
      pnode_img = node_image[pnode]
1803
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
1804
               self.ENODERPC, pnode, "instance %s, connection to"
1805
               " primary node failed", instance)
1806

    
1807
      if pnode_img.offline:
1808
        inst_nodes_offline.append(pnode)
1809

    
1810
      # If the instance is non-redundant we cannot survive losing its primary
1811
      # node, so we are not N+1 compliant. On the other hand we have no disk
1812
      # templates with more than one secondary so that situation is not well
1813
      # supported either.
1814
      # FIXME: does not support file-backed instances
1815
      if not inst_config.secondary_nodes:
1816
        i_non_redundant.append(instance)
1817
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
1818
               instance, "instance has multiple secondary nodes: %s",
1819
               utils.CommaJoin(inst_config.secondary_nodes),
1820
               code=self.ETYPE_WARNING)
1821

    
1822
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1823
        i_non_a_balanced.append(instance)
1824

    
1825
      for snode in inst_config.secondary_nodes:
1826
        s_img = node_image[snode]
1827
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
1828
                 "instance %s, connection to secondary node failed", instance)
1829

    
1830
        if s_img.offline:
1831
          inst_nodes_offline.append(snode)
1832

    
1833
      # warn that the instance lives on offline nodes
1834
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1835
               "instance lives on offline node(s) %s",
1836
               utils.CommaJoin(inst_nodes_offline))
1837
      # ... or ghost nodes
1838
      for node in inst_config.all_nodes:
1839
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
1840
                 "instance lives on ghost node %s", node)
1841

    
1842
    feedback_fn("* Verifying orphan volumes")
1843
    self._VerifyOrphanVolumes(node_vol_should, node_image)
1844

    
1845
    feedback_fn("* Verifying oprhan instances")
1846
    self._VerifyOrphanInstances(instancelist, node_image)
1847

    
1848
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1849
      feedback_fn("* Verifying N+1 Memory redundancy")
1850
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
1851

    
1852
    feedback_fn("* Other Notes")
1853
    if i_non_redundant:
1854
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1855
                  % len(i_non_redundant))
1856

    
1857
    if i_non_a_balanced:
1858
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1859
                  % len(i_non_a_balanced))
1860

    
1861
    if n_offline:
1862
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
1863

    
1864
    if n_drained:
1865
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
1866

    
1867
    return not self.bad
1868

    
1869
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1870
    """Analyze the post-hooks' result
1871

1872
    This method analyses the hook result, handles it, and sends some
1873
    nicely-formatted feedback back to the user.
1874

1875
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1876
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1877
    @param hooks_results: the results of the multi-node hooks rpc call
1878
    @param feedback_fn: function used send feedback back to the caller
1879
    @param lu_result: previous Exec result
1880
    @return: the new Exec result, based on the previous result
1881
        and hook results
1882

1883
    """
1884
    # We only really run POST phase hooks, and are only interested in
1885
    # their results
1886
    if phase == constants.HOOKS_PHASE_POST:
1887
      # Used to change hooks' output to proper indentation
1888
      indent_re = re.compile('^', re.M)
1889
      feedback_fn("* Hooks Results")
1890
      assert hooks_results, "invalid result from hooks"
1891

    
1892
      for node_name in hooks_results:
1893
        res = hooks_results[node_name]
1894
        msg = res.fail_msg
1895
        test = msg and not res.offline
1896
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1897
                      "Communication failure in hooks execution: %s", msg)
1898
        if res.offline or msg:
1899
          # No need to investigate payload if node is offline or gave an error.
1900
          # override manually lu_result here as _ErrorIf only
1901
          # overrides self.bad
1902
          lu_result = 1
1903
          continue
1904
        for script, hkr, output in res.payload:
1905
          test = hkr == constants.HKR_FAIL
1906
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1907
                        "Script %s failed, output:", script)
1908
          if test:
1909
            output = indent_re.sub('      ', output)
1910
            feedback_fn("%s" % output)
1911
            lu_result = 0
1912

    
1913
      return lu_result
1914

    
1915

    
1916
class LUVerifyDisks(NoHooksLU):
1917
  """Verifies the cluster disks status.
1918

1919
  """
1920
  _OP_REQP = []
1921
  REQ_BGL = False
1922

    
1923
  def ExpandNames(self):
1924
    self.needed_locks = {
1925
      locking.LEVEL_NODE: locking.ALL_SET,
1926
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1927
    }
1928
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1929

    
1930
  def CheckPrereq(self):
1931
    """Check prerequisites.
1932

1933
    This has no prerequisites.
1934

1935
    """
1936
    pass
1937

    
1938
  def Exec(self, feedback_fn):
1939
    """Verify integrity of cluster disks.
1940

1941
    @rtype: tuple of three items
1942
    @return: a tuple of (dict of node-to-node_error, list of instances
1943
        which need activate-disks, dict of instance: (node, volume) for
1944
        missing volumes
1945

1946
    """
1947
    result = res_nodes, res_instances, res_missing = {}, [], {}
1948

    
1949
    vg_name = self.cfg.GetVGName()
1950
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1951
    instances = [self.cfg.GetInstanceInfo(name)
1952
                 for name in self.cfg.GetInstanceList()]
1953

    
1954
    nv_dict = {}
1955
    for inst in instances:
1956
      inst_lvs = {}
1957
      if (not inst.admin_up or
1958
          inst.disk_template not in constants.DTS_NET_MIRROR):
1959
        continue
1960
      inst.MapLVsByNode(inst_lvs)
1961
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1962
      for node, vol_list in inst_lvs.iteritems():
1963
        for vol in vol_list:
1964
          nv_dict[(node, vol)] = inst
1965

    
1966
    if not nv_dict:
1967
      return result
1968

    
1969
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1970

    
1971
    for node in nodes:
1972
      # node_volume
1973
      node_res = node_lvs[node]
1974
      if node_res.offline:
1975
        continue
1976
      msg = node_res.fail_msg
1977
      if msg:
1978
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1979
        res_nodes[node] = msg
1980
        continue
1981

    
1982
      lvs = node_res.payload
1983
      for lv_name, (_, _, lv_online) in lvs.items():
1984
        inst = nv_dict.pop((node, lv_name), None)
1985
        if (not lv_online and inst is not None
1986
            and inst.name not in res_instances):
1987
          res_instances.append(inst.name)
1988

    
1989
    # any leftover items in nv_dict are missing LVs, let's arrange the
1990
    # data better
1991
    for key, inst in nv_dict.iteritems():
1992
      if inst.name not in res_missing:
1993
        res_missing[inst.name] = []
1994
      res_missing[inst.name].append(key)
1995

    
1996
    return result
1997

    
1998

    
1999
class LURepairDiskSizes(NoHooksLU):
2000
  """Verifies the cluster disks sizes.
2001

2002
  """
2003
  _OP_REQP = ["instances"]
2004
  REQ_BGL = False
2005

    
2006
  def ExpandNames(self):
2007
    if not isinstance(self.op.instances, list):
2008
      raise errors.OpPrereqError("Invalid argument type 'instances'",
2009
                                 errors.ECODE_INVAL)
2010

    
2011
    if self.op.instances:
2012
      self.wanted_names = []
2013
      for name in self.op.instances:
2014
        full_name = _ExpandInstanceName(self.cfg, name)
2015
        self.wanted_names.append(full_name)
2016
      self.needed_locks = {
2017
        locking.LEVEL_NODE: [],
2018
        locking.LEVEL_INSTANCE: self.wanted_names,
2019
        }
2020
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2021
    else:
2022
      self.wanted_names = None
2023
      self.needed_locks = {
2024
        locking.LEVEL_NODE: locking.ALL_SET,
2025
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2026
        }
2027
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2028

    
2029
  def DeclareLocks(self, level):
2030
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2031
      self._LockInstancesNodes(primary_only=True)
2032

    
2033
  def CheckPrereq(self):
2034
    """Check prerequisites.
2035

2036
    This only checks the optional instance list against the existing names.
2037

2038
    """
2039
    if self.wanted_names is None:
2040
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2041

    
2042
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2043
                             in self.wanted_names]
2044

    
2045
  def _EnsureChildSizes(self, disk):
2046
    """Ensure children of the disk have the needed disk size.
2047

2048
    This is valid mainly for DRBD8 and fixes an issue where the
2049
    children have smaller disk size.
2050

2051
    @param disk: an L{ganeti.objects.Disk} object
2052

2053
    """
2054
    if disk.dev_type == constants.LD_DRBD8:
2055
      assert disk.children, "Empty children for DRBD8?"
2056
      fchild = disk.children[0]
2057
      mismatch = fchild.size < disk.size
2058
      if mismatch:
2059
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2060
                     fchild.size, disk.size)
2061
        fchild.size = disk.size
2062

    
2063
      # and we recurse on this child only, not on the metadev
2064
      return self._EnsureChildSizes(fchild) or mismatch
2065
    else:
2066
      return False
2067

    
2068
  def Exec(self, feedback_fn):
2069
    """Verify the size of cluster disks.
2070

2071
    """
2072
    # TODO: check child disks too
2073
    # TODO: check differences in size between primary/secondary nodes
2074
    per_node_disks = {}
2075
    for instance in self.wanted_instances:
2076
      pnode = instance.primary_node
2077
      if pnode not in per_node_disks:
2078
        per_node_disks[pnode] = []
2079
      for idx, disk in enumerate(instance.disks):
2080
        per_node_disks[pnode].append((instance, idx, disk))
2081

    
2082
    changed = []
2083
    for node, dskl in per_node_disks.items():
2084
      newl = [v[2].Copy() for v in dskl]
2085
      for dsk in newl:
2086
        self.cfg.SetDiskID(dsk, node)
2087
      result = self.rpc.call_blockdev_getsizes(node, newl)
2088
      if result.fail_msg:
2089
        self.LogWarning("Failure in blockdev_getsizes call to node"
2090
                        " %s, ignoring", node)
2091
        continue
2092
      if len(result.data) != len(dskl):
2093
        self.LogWarning("Invalid result from node %s, ignoring node results",
2094
                        node)
2095
        continue
2096
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2097
        if size is None:
2098
          self.LogWarning("Disk %d of instance %s did not return size"
2099
                          " information, ignoring", idx, instance.name)
2100
          continue
2101
        if not isinstance(size, (int, long)):
2102
          self.LogWarning("Disk %d of instance %s did not return valid"
2103
                          " size information, ignoring", idx, instance.name)
2104
          continue
2105
        size = size >> 20
2106
        if size != disk.size:
2107
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2108
                       " correcting: recorded %d, actual %d", idx,
2109
                       instance.name, disk.size, size)
2110
          disk.size = size
2111
          self.cfg.Update(instance, feedback_fn)
2112
          changed.append((instance.name, idx, size))
2113
        if self._EnsureChildSizes(disk):
2114
          self.cfg.Update(instance, feedback_fn)
2115
          changed.append((instance.name, idx, disk.size))
2116
    return changed
2117

    
2118

    
2119
class LURenameCluster(LogicalUnit):
2120
  """Rename the cluster.
2121

2122
  """
2123
  HPATH = "cluster-rename"
2124
  HTYPE = constants.HTYPE_CLUSTER
2125
  _OP_REQP = ["name"]
2126

    
2127
  def BuildHooksEnv(self):
2128
    """Build hooks env.
2129

2130
    """
2131
    env = {
2132
      "OP_TARGET": self.cfg.GetClusterName(),
2133
      "NEW_NAME": self.op.name,
2134
      }
2135
    mn = self.cfg.GetMasterNode()
2136
    all_nodes = self.cfg.GetNodeList()
2137
    return env, [mn], all_nodes
2138

    
2139
  def CheckPrereq(self):
2140
    """Verify that the passed name is a valid one.
2141

2142
    """
2143
    hostname = utils.GetHostInfo(self.op.name)
2144

    
2145
    new_name = hostname.name
2146
    self.ip = new_ip = hostname.ip
2147
    old_name = self.cfg.GetClusterName()
2148
    old_ip = self.cfg.GetMasterIP()
2149
    if new_name == old_name and new_ip == old_ip:
2150
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2151
                                 " cluster has changed",
2152
                                 errors.ECODE_INVAL)
2153
    if new_ip != old_ip:
2154
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2155
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2156
                                   " reachable on the network. Aborting." %
2157
                                   new_ip, errors.ECODE_NOTUNIQUE)
2158

    
2159
    self.op.name = new_name
2160

    
2161
  def Exec(self, feedback_fn):
2162
    """Rename the cluster.
2163

2164
    """
2165
    clustername = self.op.name
2166
    ip = self.ip
2167

    
2168
    # shutdown the master IP
2169
    master = self.cfg.GetMasterNode()
2170
    result = self.rpc.call_node_stop_master(master, False)
2171
    result.Raise("Could not disable the master role")
2172

    
2173
    try:
2174
      cluster = self.cfg.GetClusterInfo()
2175
      cluster.cluster_name = clustername
2176
      cluster.master_ip = ip
2177
      self.cfg.Update(cluster, feedback_fn)
2178

    
2179
      # update the known hosts file
2180
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2181
      node_list = self.cfg.GetNodeList()
2182
      try:
2183
        node_list.remove(master)
2184
      except ValueError:
2185
        pass
2186
      result = self.rpc.call_upload_file(node_list,
2187
                                         constants.SSH_KNOWN_HOSTS_FILE)
2188
      for to_node, to_result in result.iteritems():
2189
        msg = to_result.fail_msg
2190
        if msg:
2191
          msg = ("Copy of file %s to node %s failed: %s" %
2192
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2193
          self.proc.LogWarning(msg)
2194

    
2195
    finally:
2196
      result = self.rpc.call_node_start_master(master, False, False)
2197
      msg = result.fail_msg
2198
      if msg:
2199
        self.LogWarning("Could not re-enable the master role on"
2200
                        " the master, please restart manually: %s", msg)
2201

    
2202

    
2203
def _RecursiveCheckIfLVMBased(disk):
2204
  """Check if the given disk or its children are lvm-based.
2205

2206
  @type disk: L{objects.Disk}
2207
  @param disk: the disk to check
2208
  @rtype: boolean
2209
  @return: boolean indicating whether a LD_LV dev_type was found or not
2210

2211
  """
2212
  if disk.children:
2213
    for chdisk in disk.children:
2214
      if _RecursiveCheckIfLVMBased(chdisk):
2215
        return True
2216
  return disk.dev_type == constants.LD_LV
2217

    
2218

    
2219
class LUSetClusterParams(LogicalUnit):
2220
  """Change the parameters of the cluster.
2221

2222
  """
2223
  HPATH = "cluster-modify"
2224
  HTYPE = constants.HTYPE_CLUSTER
2225
  _OP_REQP = []
2226
  REQ_BGL = False
2227

    
2228
  def CheckArguments(self):
2229
    """Check parameters
2230

2231
    """
2232
    if not hasattr(self.op, "candidate_pool_size"):
2233
      self.op.candidate_pool_size = None
2234
    if self.op.candidate_pool_size is not None:
2235
      try:
2236
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
2237
      except (ValueError, TypeError), err:
2238
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
2239
                                   str(err), errors.ECODE_INVAL)
2240
      if self.op.candidate_pool_size < 1:
2241
        raise errors.OpPrereqError("At least one master candidate needed",
2242
                                   errors.ECODE_INVAL)
2243

    
2244
  def ExpandNames(self):
2245
    # FIXME: in the future maybe other cluster params won't require checking on
2246
    # all nodes to be modified.
2247
    self.needed_locks = {
2248
      locking.LEVEL_NODE: locking.ALL_SET,
2249
    }
2250
    self.share_locks[locking.LEVEL_NODE] = 1
2251

    
2252
  def BuildHooksEnv(self):
2253
    """Build hooks env.
2254

2255
    """
2256
    env = {
2257
      "OP_TARGET": self.cfg.GetClusterName(),
2258
      "NEW_VG_NAME": self.op.vg_name,
2259
      }
2260
    mn = self.cfg.GetMasterNode()
2261
    return env, [mn], [mn]
2262

    
2263
  def CheckPrereq(self):
2264
    """Check prerequisites.
2265

2266
    This checks whether the given params don't conflict and
2267
    if the given volume group is valid.
2268

2269
    """
2270
    if self.op.vg_name is not None and not self.op.vg_name:
2271
      instances = self.cfg.GetAllInstancesInfo().values()
2272
      for inst in instances:
2273
        for disk in inst.disks:
2274
          if _RecursiveCheckIfLVMBased(disk):
2275
            raise errors.OpPrereqError("Cannot disable lvm storage while"
2276
                                       " lvm-based instances exist",
2277
                                       errors.ECODE_INVAL)
2278

    
2279
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2280

    
2281
    # if vg_name not None, checks given volume group on all nodes
2282
    if self.op.vg_name:
2283
      vglist = self.rpc.call_vg_list(node_list)
2284
      for node in node_list:
2285
        msg = vglist[node].fail_msg
2286
        if msg:
2287
          # ignoring down node
2288
          self.LogWarning("Error while gathering data on node %s"
2289
                          " (ignoring node): %s", node, msg)
2290
          continue
2291
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2292
                                              self.op.vg_name,
2293
                                              constants.MIN_VG_SIZE)
2294
        if vgstatus:
2295
          raise errors.OpPrereqError("Error on node '%s': %s" %
2296
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2297

    
2298
    self.cluster = cluster = self.cfg.GetClusterInfo()
2299
    # validate params changes
2300
    if self.op.beparams:
2301
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2302
      self.new_beparams = objects.FillDict(
2303
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
2304

    
2305
    if self.op.nicparams:
2306
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2307
      self.new_nicparams = objects.FillDict(
2308
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
2309
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2310
      nic_errors = []
2311

    
2312
      # check all instances for consistency
2313
      for instance in self.cfg.GetAllInstancesInfo().values():
2314
        for nic_idx, nic in enumerate(instance.nics):
2315
          params_copy = copy.deepcopy(nic.nicparams)
2316
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2317

    
2318
          # check parameter syntax
2319
          try:
2320
            objects.NIC.CheckParameterSyntax(params_filled)
2321
          except errors.ConfigurationError, err:
2322
            nic_errors.append("Instance %s, nic/%d: %s" %
2323
                              (instance.name, nic_idx, err))
2324

    
2325
          # if we're moving instances to routed, check that they have an ip
2326
          target_mode = params_filled[constants.NIC_MODE]
2327
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2328
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2329
                              (instance.name, nic_idx))
2330
      if nic_errors:
2331
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2332
                                   "\n".join(nic_errors))
2333

    
2334
    # hypervisor list/parameters
2335
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
2336
    if self.op.hvparams:
2337
      if not isinstance(self.op.hvparams, dict):
2338
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
2339
                                   errors.ECODE_INVAL)
2340
      for hv_name, hv_dict in self.op.hvparams.items():
2341
        if hv_name not in self.new_hvparams:
2342
          self.new_hvparams[hv_name] = hv_dict
2343
        else:
2344
          self.new_hvparams[hv_name].update(hv_dict)
2345

    
2346
    # os hypervisor parameters
2347
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2348
    if self.op.os_hvp:
2349
      if not isinstance(self.op.os_hvp, dict):
2350
        raise errors.OpPrereqError("Invalid 'os_hvp' parameter on input",
2351
                                   errors.ECODE_INVAL)
2352
      for os_name, hvs in self.op.os_hvp.items():
2353
        if not isinstance(hvs, dict):
2354
          raise errors.OpPrereqError(("Invalid 'os_hvp' parameter on"
2355
                                      " input"), errors.ECODE_INVAL)
2356
        if os_name not in self.new_os_hvp:
2357
          self.new_os_hvp[os_name] = hvs
2358
        else:
2359
          for hv_name, hv_dict in hvs.items():
2360
            if hv_name not in self.new_os_hvp[os_name]:
2361
              self.new_os_hvp[os_name][hv_name] = hv_dict
2362
            else:
2363
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2364

    
2365
    if self.op.enabled_hypervisors is not None:
2366
      self.hv_list = self.op.enabled_hypervisors
2367
      if not self.hv_list:
2368
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
2369
                                   " least one member",
2370
                                   errors.ECODE_INVAL)
2371
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
2372
      if invalid_hvs:
2373
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
2374
                                   " entries: %s" %
2375
                                   utils.CommaJoin(invalid_hvs),
2376
                                   errors.ECODE_INVAL)
2377
    else:
2378
      self.hv_list = cluster.enabled_hypervisors
2379

    
2380
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2381
      # either the enabled list has changed, or the parameters have, validate
2382
      for hv_name, hv_params in self.new_hvparams.items():
2383
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2384
            (self.op.enabled_hypervisors and
2385
             hv_name in self.op.enabled_hypervisors)):
2386
          # either this is a new hypervisor, or its parameters have changed
2387
          hv_class = hypervisor.GetHypervisor(hv_name)
2388
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2389
          hv_class.CheckParameterSyntax(hv_params)
2390
          _CheckHVParams(self, node_list, hv_name, hv_params)
2391

    
2392
    if self.op.os_hvp:
2393
      # no need to check any newly-enabled hypervisors, since the
2394
      # defaults have already been checked in the above code-block
2395
      for os_name, os_hvp in self.new_os_hvp.items():
2396
        for hv_name, hv_params in os_hvp.items():
2397
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2398
          # we need to fill in the new os_hvp on top of the actual hv_p
2399
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2400
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2401
          hv_class = hypervisor.GetHypervisor(hv_name)
2402
          hv_class.CheckParameterSyntax(new_osp)
2403
          _CheckHVParams(self, node_list, hv_name, new_osp)
2404

    
2405

    
2406
  def Exec(self, feedback_fn):
2407
    """Change the parameters of the cluster.
2408

2409
    """
2410
    if self.op.vg_name is not None:
2411
      new_volume = self.op.vg_name
2412
      if not new_volume:
2413
        new_volume = None
2414
      if new_volume != self.cfg.GetVGName():
2415
        self.cfg.SetVGName(new_volume)
2416
      else:
2417
        feedback_fn("Cluster LVM configuration already in desired"
2418
                    " state, not changing")
2419
    if self.op.hvparams:
2420
      self.cluster.hvparams = self.new_hvparams
2421
    if self.op.os_hvp:
2422
      self.cluster.os_hvp = self.new_os_hvp
2423
    if self.op.enabled_hypervisors is not None:
2424
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2425
    if self.op.beparams:
2426
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2427
    if self.op.nicparams:
2428
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2429

    
2430
    if self.op.candidate_pool_size is not None:
2431
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2432
      # we need to update the pool size here, otherwise the save will fail
2433
      _AdjustCandidatePool(self, [])
2434

    
2435
    self.cfg.Update(self.cluster, feedback_fn)
2436

    
2437

    
2438
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2439
  """Distribute additional files which are part of the cluster configuration.
2440

2441
  ConfigWriter takes care of distributing the config and ssconf files, but
2442
  there are more files which should be distributed to all nodes. This function
2443
  makes sure those are copied.
2444

2445
  @param lu: calling logical unit
2446
  @param additional_nodes: list of nodes not in the config to distribute to
2447

2448
  """
2449
  # 1. Gather target nodes
2450
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2451
  dist_nodes = lu.cfg.GetOnlineNodeList()
2452
  if additional_nodes is not None:
2453
    dist_nodes.extend(additional_nodes)
2454
  if myself.name in dist_nodes:
2455
    dist_nodes.remove(myself.name)
2456

    
2457
  # 2. Gather files to distribute
2458
  dist_files = set([constants.ETC_HOSTS,
2459
                    constants.SSH_KNOWN_HOSTS_FILE,
2460
                    constants.RAPI_CERT_FILE,
2461
                    constants.RAPI_USERS_FILE,
2462
                    constants.CONFD_HMAC_KEY,
2463
                   ])
2464

    
2465
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2466
  for hv_name in enabled_hypervisors:
2467
    hv_class = hypervisor.GetHypervisor(hv_name)
2468
    dist_files.update(hv_class.GetAncillaryFiles())
2469

    
2470
  # 3. Perform the files upload
2471
  for fname in dist_files:
2472
    if os.path.exists(fname):
2473
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2474
      for to_node, to_result in result.items():
2475
        msg = to_result.fail_msg
2476
        if msg:
2477
          msg = ("Copy of file %s to node %s failed: %s" %
2478
                 (fname, to_node, msg))
2479
          lu.proc.LogWarning(msg)
2480

    
2481

    
2482
class LURedistributeConfig(NoHooksLU):
2483
  """Force the redistribution of cluster configuration.
2484

2485
  This is a very simple LU.
2486

2487
  """
2488
  _OP_REQP = []
2489
  REQ_BGL = False
2490

    
2491
  def ExpandNames(self):
2492
    self.needed_locks = {
2493
      locking.LEVEL_NODE: locking.ALL_SET,
2494
    }
2495
    self.share_locks[locking.LEVEL_NODE] = 1
2496

    
2497
  def CheckPrereq(self):
2498
    """Check prerequisites.
2499

2500
    """
2501

    
2502
  def Exec(self, feedback_fn):
2503
    """Redistribute the configuration.
2504

2505
    """
2506
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2507
    _RedistributeAncillaryFiles(self)
2508

    
2509

    
2510
def _WaitForSync(lu, instance, oneshot=False):
2511
  """Sleep and poll for an instance's disk to sync.
2512

2513
  """
2514
  if not instance.disks:
2515
    return True
2516

    
2517
  if not oneshot:
2518
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2519

    
2520
  node = instance.primary_node
2521

    
2522
  for dev in instance.disks:
2523
    lu.cfg.SetDiskID(dev, node)
2524

    
2525
  # TODO: Convert to utils.Retry
2526

    
2527
  retries = 0
2528
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2529
  while True:
2530
    max_time = 0
2531
    done = True
2532
    cumul_degraded = False
2533
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2534
    msg = rstats.fail_msg
2535
    if msg:
2536
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2537
      retries += 1
2538
      if retries >= 10:
2539
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2540
                                 " aborting." % node)
2541
      time.sleep(6)
2542
      continue
2543
    rstats = rstats.payload
2544
    retries = 0
2545
    for i, mstat in enumerate(rstats):
2546
      if mstat is None:
2547
        lu.LogWarning("Can't compute data for node %s/%s",
2548
                           node, instance.disks[i].iv_name)
2549
        continue
2550

    
2551
      cumul_degraded = (cumul_degraded or
2552
                        (mstat.is_degraded and mstat.sync_percent is None))
2553
      if mstat.sync_percent is not None:
2554
        done = False
2555
        if mstat.estimated_time is not None:
2556
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2557
          max_time = mstat.estimated_time
2558
        else:
2559
          rem_time = "no time estimate"
2560
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2561
                        (instance.disks[i].iv_name, mstat.sync_percent,
2562
                         rem_time))
2563

    
2564
    # if we're done but degraded, let's do a few small retries, to
2565
    # make sure we see a stable and not transient situation; therefore
2566
    # we force restart of the loop
2567
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2568
      logging.info("Degraded disks found, %d retries left", degr_retries)
2569
      degr_retries -= 1
2570
      time.sleep(1)
2571
      continue
2572

    
2573
    if done or oneshot:
2574
      break
2575

    
2576
    time.sleep(min(60, max_time))
2577

    
2578
  if done:
2579
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2580
  return not cumul_degraded
2581

    
2582

    
2583
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2584
  """Check that mirrors are not degraded.
2585

2586
  The ldisk parameter, if True, will change the test from the
2587
  is_degraded attribute (which represents overall non-ok status for
2588
  the device(s)) to the ldisk (representing the local storage status).
2589

2590
  """
2591
  lu.cfg.SetDiskID(dev, node)
2592

    
2593
  result = True
2594

    
2595
  if on_primary or dev.AssembleOnSecondary():
2596
    rstats = lu.rpc.call_blockdev_find(node, dev)
2597
    msg = rstats.fail_msg
2598
    if msg:
2599
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2600
      result = False
2601
    elif not rstats.payload:
2602
      lu.LogWarning("Can't find disk on node %s", node)
2603
      result = False
2604
    else:
2605
      if ldisk:
2606
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2607
      else:
2608
        result = result and not rstats.payload.is_degraded
2609

    
2610
  if dev.children:
2611
    for child in dev.children:
2612
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2613

    
2614
  return result
2615

    
2616

    
2617
class LUDiagnoseOS(NoHooksLU):
2618
  """Logical unit for OS diagnose/query.
2619

2620
  """
2621
  _OP_REQP = ["output_fields", "names"]
2622
  REQ_BGL = False
2623
  _FIELDS_STATIC = utils.FieldSet()
2624
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2625
  # Fields that need calculation of global os validity
2626
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2627

    
2628
  def ExpandNames(self):
2629
    if self.op.names:
2630
      raise errors.OpPrereqError("Selective OS query not supported",
2631
                                 errors.ECODE_INVAL)
2632

    
2633
    _CheckOutputFields(static=self._FIELDS_STATIC,
2634
                       dynamic=self._FIELDS_DYNAMIC,
2635
                       selected=self.op.output_fields)
2636

    
2637
    # Lock all nodes, in shared mode
2638
    # Temporary removal of locks, should be reverted later
2639
    # TODO: reintroduce locks when they are lighter-weight
2640
    self.needed_locks = {}
2641
    #self.share_locks[locking.LEVEL_NODE] = 1
2642
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2643

    
2644
  def CheckPrereq(self):
2645
    """Check prerequisites.
2646

2647
    """
2648

    
2649
  @staticmethod
2650
  def _DiagnoseByOS(rlist):
2651
    """Remaps a per-node return list into an a per-os per-node dictionary
2652

2653
    @param rlist: a map with node names as keys and OS objects as values
2654

2655
    @rtype: dict
2656
    @return: a dictionary with osnames as keys and as value another map, with
2657
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2658

2659
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2660
                                     (/srv/..., False, "invalid api")],
2661
                           "node2": [(/srv/..., True, "")]}
2662
          }
2663

2664
    """
2665
    all_os = {}
2666
    # we build here the list of nodes that didn't fail the RPC (at RPC
2667
    # level), so that nodes with a non-responding node daemon don't
2668
    # make all OSes invalid
2669
    good_nodes = [node_name for node_name in rlist
2670
                  if not rlist[node_name].fail_msg]
2671
    for node_name, nr in rlist.items():
2672
      if nr.fail_msg or not nr.payload:
2673
        continue
2674
      for name, path, status, diagnose, variants in nr.payload:
2675
        if name not in all_os:
2676
          # build a list of nodes for this os containing empty lists
2677
          # for each node in node_list
2678
          all_os[name] = {}
2679
          for nname in good_nodes:
2680
            all_os[name][nname] = []
2681
        all_os[name][node_name].append((path, status, diagnose, variants))
2682
    return all_os
2683

    
2684
  def Exec(self, feedback_fn):
2685
    """Compute the list of OSes.
2686

2687
    """
2688
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2689
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2690
    pol = self._DiagnoseByOS(node_data)
2691
    output = []
2692
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2693
    calc_variants = "variants" in self.op.output_fields
2694

    
2695
    for os_name, os_data in pol.items():
2696
      row = []
2697
      if calc_valid:
2698
        valid = True
2699
        variants = None
2700
        for osl in os_data.values():
2701
          valid = valid and osl and osl[0][1]
2702
          if not valid:
2703
            variants = None
2704
            break
2705
          if calc_variants:
2706
            node_variants = osl[0][3]
2707
            if variants is None:
2708
              variants = node_variants
2709
            else:
2710
              variants = [v for v in variants if v in node_variants]
2711

    
2712
      for field in self.op.output_fields:
2713
        if field == "name":
2714
          val = os_name
2715
        elif field == "valid":
2716
          val = valid
2717
        elif field == "node_status":
2718
          # this is just a copy of the dict
2719
          val = {}
2720
          for node_name, nos_list in os_data.items():
2721
            val[node_name] = nos_list
2722
        elif field == "variants":
2723
          val =  variants
2724
        else:
2725
          raise errors.ParameterError(field)
2726
        row.append(val)
2727
      output.append(row)
2728

    
2729
    return output
2730

    
2731

    
2732
class LURemoveNode(LogicalUnit):
2733
  """Logical unit for removing a node.
2734

2735
  """
2736
  HPATH = "node-remove"
2737
  HTYPE = constants.HTYPE_NODE
2738
  _OP_REQP = ["node_name"]
2739

    
2740
  def BuildHooksEnv(self):
2741
    """Build hooks env.
2742

2743
    This doesn't run on the target node in the pre phase as a failed
2744
    node would then be impossible to remove.
2745

2746
    """
2747
    env = {
2748
      "OP_TARGET": self.op.node_name,
2749
      "NODE_NAME": self.op.node_name,
2750
      }
2751
    all_nodes = self.cfg.GetNodeList()
2752
    try:
2753
      all_nodes.remove(self.op.node_name)
2754
    except ValueError:
2755
      logging.warning("Node %s which is about to be removed not found"
2756
                      " in the all nodes list", self.op.node_name)
2757
    return env, all_nodes, all_nodes
2758

    
2759
  def CheckPrereq(self):
2760
    """Check prerequisites.
2761

2762
    This checks:
2763
     - the node exists in the configuration
2764
     - it does not have primary or secondary instances
2765
     - it's not the master
2766

2767
    Any errors are signaled by raising errors.OpPrereqError.
2768

2769
    """
2770
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
2771
    node = self.cfg.GetNodeInfo(self.op.node_name)
2772
    assert node is not None
2773

    
2774
    instance_list = self.cfg.GetInstanceList()
2775

    
2776
    masternode = self.cfg.GetMasterNode()
2777
    if node.name == masternode:
2778
      raise errors.OpPrereqError("Node is the master node,"
2779
                                 " you need to failover first.",
2780
                                 errors.ECODE_INVAL)
2781

    
2782
    for instance_name in instance_list:
2783
      instance = self.cfg.GetInstanceInfo(instance_name)
2784
      if node.name in instance.all_nodes:
2785
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2786
                                   " please remove first." % instance_name,
2787
                                   errors.ECODE_INVAL)
2788
    self.op.node_name = node.name
2789
    self.node = node
2790

    
2791
  def Exec(self, feedback_fn):
2792
    """Removes the node from the cluster.
2793

2794
    """
2795
    node = self.node
2796
    logging.info("Stopping the node daemon and removing configs from node %s",
2797
                 node.name)
2798

    
2799
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2800

    
2801
    # Promote nodes to master candidate as needed
2802
    _AdjustCandidatePool(self, exceptions=[node.name])
2803
    self.context.RemoveNode(node.name)
2804

    
2805
    # Run post hooks on the node before it's removed
2806
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2807
    try:
2808
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2809
    except:
2810
      # pylint: disable-msg=W0702
2811
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2812

    
2813
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2814
    msg = result.fail_msg
2815
    if msg:
2816
      self.LogWarning("Errors encountered on the remote node while leaving"
2817
                      " the cluster: %s", msg)
2818

    
2819

    
2820
class LUQueryNodes(NoHooksLU):
2821
  """Logical unit for querying nodes.
2822

2823
  """
2824
  # pylint: disable-msg=W0142
2825
  _OP_REQP = ["output_fields", "names", "use_locking"]
2826
  REQ_BGL = False
2827

    
2828
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2829
                    "master_candidate", "offline", "drained"]
2830

    
2831
  _FIELDS_DYNAMIC = utils.FieldSet(
2832
    "dtotal", "dfree",
2833
    "mtotal", "mnode", "mfree",
2834
    "bootid",
2835
    "ctotal", "cnodes", "csockets",
2836
    )
2837

    
2838
  _FIELDS_STATIC = utils.FieldSet(*[
2839
    "pinst_cnt", "sinst_cnt",
2840
    "pinst_list", "sinst_list",
2841
    "pip", "sip", "tags",
2842
    "master",
2843
    "role"] + _SIMPLE_FIELDS
2844
    )
2845

    
2846
  def ExpandNames(self):
2847
    _CheckOutputFields(static=self._FIELDS_STATIC,
2848
                       dynamic=self._FIELDS_DYNAMIC,
2849
                       selected=self.op.output_fields)
2850

    
2851
    self.needed_locks = {}
2852
    self.share_locks[locking.LEVEL_NODE] = 1
2853

    
2854
    if self.op.names:
2855
      self.wanted = _GetWantedNodes(self, self.op.names)
2856
    else:
2857
      self.wanted = locking.ALL_SET
2858

    
2859
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2860
    self.do_locking = self.do_node_query and self.op.use_locking
2861
    if self.do_locking:
2862
      # if we don't request only static fields, we need to lock the nodes
2863
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2864

    
2865
  def CheckPrereq(self):
2866
    """Check prerequisites.
2867

2868
    """
2869
    # The validation of the node list is done in the _GetWantedNodes,
2870
    # if non empty, and if empty, there's no validation to do
2871
    pass
2872

    
2873
  def Exec(self, feedback_fn):
2874
    """Computes the list of nodes and their attributes.
2875

2876
    """
2877
    all_info = self.cfg.GetAllNodesInfo()
2878
    if self.do_locking:
2879
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2880
    elif self.wanted != locking.ALL_SET:
2881
      nodenames = self.wanted
2882
      missing = set(nodenames).difference(all_info.keys())
2883
      if missing:
2884
        raise errors.OpExecError(
2885
          "Some nodes were removed before retrieving their data: %s" % missing)
2886
    else:
2887
      nodenames = all_info.keys()
2888

    
2889
    nodenames = utils.NiceSort(nodenames)
2890
    nodelist = [all_info[name] for name in nodenames]
2891

    
2892
    # begin data gathering
2893

    
2894
    if self.do_node_query:
2895
      live_data = {}
2896
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2897
                                          self.cfg.GetHypervisorType())
2898
      for name in nodenames:
2899
        nodeinfo = node_data[name]
2900
        if not nodeinfo.fail_msg and nodeinfo.payload:
2901
          nodeinfo = nodeinfo.payload
2902
          fn = utils.TryConvert
2903
          live_data[name] = {
2904
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2905
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2906
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2907
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2908
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2909
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2910
            "bootid": nodeinfo.get('bootid', None),
2911
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2912
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2913
            }
2914
        else:
2915
          live_data[name] = {}
2916
    else:
2917
      live_data = dict.fromkeys(nodenames, {})
2918

    
2919
    node_to_primary = dict([(name, set()) for name in nodenames])
2920
    node_to_secondary = dict([(name, set()) for name in nodenames])
2921

    
2922
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2923
                             "sinst_cnt", "sinst_list"))
2924
    if inst_fields & frozenset(self.op.output_fields):
2925
      inst_data = self.cfg.GetAllInstancesInfo()
2926

    
2927
      for inst in inst_data.values():
2928
        if inst.primary_node in node_to_primary:
2929
          node_to_primary[inst.primary_node].add(inst.name)
2930
        for secnode in inst.secondary_nodes:
2931
          if secnode in node_to_secondary:
2932
            node_to_secondary[secnode].add(inst.name)
2933

    
2934
    master_node = self.cfg.GetMasterNode()
2935

    
2936
    # end data gathering
2937

    
2938
    output = []
2939
    for node in nodelist:
2940
      node_output = []
2941
      for field in self.op.output_fields:
2942
        if field in self._SIMPLE_FIELDS:
2943
          val = getattr(node, field)
2944
        elif field == "pinst_list":
2945
          val = list(node_to_primary[node.name])
2946
        elif field == "sinst_list":
2947
          val = list(node_to_secondary[node.name])
2948
        elif field == "pinst_cnt":
2949
          val = len(node_to_primary[node.name])
2950
        elif field == "sinst_cnt":
2951
          val = len(node_to_secondary[node.name])
2952
        elif field == "pip":
2953
          val = node.primary_ip
2954
        elif field == "sip":
2955
          val = node.secondary_ip
2956
        elif field == "tags":
2957
          val = list(node.GetTags())
2958
        elif field == "master":
2959
          val = node.name == master_node
2960
        elif self._FIELDS_DYNAMIC.Matches(field):
2961
          val = live_data[node.name].get(field, None)
2962
        elif field == "role":
2963
          if node.name == master_node:
2964
            val = "M"
2965
          elif node.master_candidate:
2966
            val = "C"
2967
          elif node.drained:
2968
            val = "D"
2969
          elif node.offline:
2970
            val = "O"
2971
          else:
2972
            val = "R"
2973
        else:
2974
          raise errors.ParameterError(field)
2975
        node_output.append(val)
2976
      output.append(node_output)
2977

    
2978
    return output
2979

    
2980

    
2981
class LUQueryNodeVolumes(NoHooksLU):
2982
  """Logical unit for getting volumes on node(s).
2983

2984
  """
2985
  _OP_REQP = ["nodes", "output_fields"]
2986
  REQ_BGL = False
2987
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2988
  _FIELDS_STATIC = utils.FieldSet("node")
2989

    
2990
  def ExpandNames(self):
2991
    _CheckOutputFields(static=self._FIELDS_STATIC,
2992
                       dynamic=self._FIELDS_DYNAMIC,
2993
                       selected=self.op.output_fields)
2994

    
2995
    self.needed_locks = {}
2996
    self.share_locks[locking.LEVEL_NODE] = 1
2997
    if not self.op.nodes:
2998
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2999
    else:
3000
      self.needed_locks[locking.LEVEL_NODE] = \
3001
        _GetWantedNodes(self, self.op.nodes)
3002

    
3003
  def CheckPrereq(self):
3004
    """Check prerequisites.
3005

3006
    This checks that the fields required are valid output fields.
3007

3008
    """
3009
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3010

    
3011
  def Exec(self, feedback_fn):
3012
    """Computes the list of nodes and their attributes.
3013

3014
    """
3015
    nodenames = self.nodes
3016
    volumes = self.rpc.call_node_volumes(nodenames)
3017

    
3018
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3019
             in self.cfg.GetInstanceList()]
3020

    
3021
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3022

    
3023
    output = []
3024
    for node in nodenames:
3025
      nresult = volumes[node]
3026
      if nresult.offline:
3027
        continue
3028
      msg = nresult.fail_msg
3029
      if msg:
3030
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3031
        continue
3032

    
3033
      node_vols = nresult.payload[:]
3034
      node_vols.sort(key=lambda vol: vol['dev'])
3035

    
3036
      for vol in node_vols:
3037
        node_output = []
3038
        for field in self.op.output_fields:
3039
          if field == "node":
3040
            val = node
3041
          elif field == "phys":
3042
            val = vol['dev']
3043
          elif field == "vg":
3044
            val = vol['vg']
3045
          elif field == "name":
3046
            val = vol['name']
3047
          elif field == "size":
3048
            val = int(float(vol['size']))
3049
          elif field == "instance":
3050
            for inst in ilist:
3051
              if node not in lv_by_node[inst]:
3052
                continue
3053
              if vol['name'] in lv_by_node[inst][node]:
3054
                val = inst.name
3055
                break
3056
            else:
3057
              val = '-'
3058
          else:
3059
            raise errors.ParameterError(field)
3060
          node_output.append(str(val))
3061

    
3062
        output.append(node_output)
3063

    
3064
    return output
3065

    
3066

    
3067
class LUQueryNodeStorage(NoHooksLU):
3068
  """Logical unit for getting information on storage units on node(s).
3069

3070
  """
3071
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
3072
  REQ_BGL = False
3073
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3074

    
3075
  def ExpandNames(self):
3076
    storage_type = self.op.storage_type
3077

    
3078
    if storage_type not in constants.VALID_STORAGE_TYPES:
3079
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
3080
                                 errors.ECODE_INVAL)
3081

    
3082
    _CheckOutputFields(static=self._FIELDS_STATIC,
3083
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3084
                       selected=self.op.output_fields)
3085

    
3086
    self.needed_locks = {}
3087
    self.share_locks[locking.LEVEL_NODE] = 1
3088

    
3089
    if self.op.nodes:
3090
      self.needed_locks[locking.LEVEL_NODE] = \
3091
        _GetWantedNodes(self, self.op.nodes)
3092
    else:
3093
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3094

    
3095
  def CheckPrereq(self):
3096
    """Check prerequisites.
3097

3098
    This checks that the fields required are valid output fields.
3099

3100
    """
3101
    self.op.name = getattr(self.op, "name", None)
3102

    
3103
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3104

    
3105
  def Exec(self, feedback_fn):
3106
    """Computes the list of nodes and their attributes.
3107

3108
    """
3109
    # Always get name to sort by
3110
    if constants.SF_NAME in self.op.output_fields:
3111
      fields = self.op.output_fields[:]
3112
    else:
3113
      fields = [constants.SF_NAME] + self.op.output_fields
3114

    
3115
    # Never ask for node or type as it's only known to the LU
3116
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3117
      while extra in fields:
3118
        fields.remove(extra)
3119

    
3120
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3121
    name_idx = field_idx[constants.SF_NAME]
3122

    
3123
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3124
    data = self.rpc.call_storage_list(self.nodes,
3125
                                      self.op.storage_type, st_args,
3126
                                      self.op.name, fields)
3127

    
3128
    result = []
3129

    
3130
    for node in utils.NiceSort(self.nodes):
3131
      nresult = data[node]
3132
      if nresult.offline:
3133
        continue
3134

    
3135
      msg = nresult.fail_msg
3136
      if msg:
3137
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3138
        continue
3139

    
3140
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3141

    
3142
      for name in utils.NiceSort(rows.keys()):
3143
        row = rows[name]
3144

    
3145
        out = []
3146

    
3147
        for field in self.op.output_fields:
3148
          if field == constants.SF_NODE:
3149
            val = node
3150
          elif field == constants.SF_TYPE:
3151
            val = self.op.storage_type
3152
          elif field in field_idx:
3153
            val = row[field_idx[field]]
3154
          else:
3155
            raise errors.ParameterError(field)
3156

    
3157
          out.append(val)
3158

    
3159
        result.append(out)
3160

    
3161
    return result
3162

    
3163

    
3164
class LUModifyNodeStorage(NoHooksLU):
3165
  """Logical unit for modifying a storage volume on a node.
3166

3167
  """
3168
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
3169
  REQ_BGL = False
3170

    
3171
  def CheckArguments(self):
3172
    self.opnode_name = _ExpandNodeName(self.cfg, self.op.node_name)
3173

    
3174
    storage_type = self.op.storage_type
3175
    if storage_type not in constants.VALID_STORAGE_TYPES:
3176
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
3177
                                 errors.ECODE_INVAL)
3178

    
3179
  def ExpandNames(self):
3180
    self.needed_locks = {
3181
      locking.LEVEL_NODE: self.op.node_name,
3182
      }
3183

    
3184
  def CheckPrereq(self):
3185
    """Check prerequisites.
3186

3187
    """
3188
    storage_type = self.op.storage_type
3189

    
3190
    try:
3191
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3192
    except KeyError:
3193
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3194
                                 " modified" % storage_type,
3195
                                 errors.ECODE_INVAL)
3196

    
3197
    diff = set(self.op.changes.keys()) - modifiable
3198
    if diff:
3199
      raise errors.OpPrereqError("The following fields can not be modified for"
3200
                                 " storage units of type '%s': %r" %
3201
                                 (storage_type, list(diff)),
3202
                                 errors.ECODE_INVAL)
3203

    
3204
  def Exec(self, feedback_fn):
3205
    """Computes the list of nodes and their attributes.
3206

3207
    """
3208
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3209
    result = self.rpc.call_storage_modify(self.op.node_name,
3210
                                          self.op.storage_type, st_args,
3211
                                          self.op.name, self.op.changes)
3212
    result.Raise("Failed to modify storage unit '%s' on %s" %
3213
                 (self.op.name, self.op.node_name))
3214

    
3215

    
3216
class LUAddNode(LogicalUnit):
3217
  """Logical unit for adding node to the cluster.
3218

3219
  """
3220
  HPATH = "node-add"
3221
  HTYPE = constants.HTYPE_NODE
3222
  _OP_REQP = ["node_name"]
3223

    
3224
  def CheckArguments(self):
3225
    # validate/normalize the node name
3226
    self.op.node_name = utils.HostInfo.NormalizeName(self.op.node_name)
3227

    
3228
  def BuildHooksEnv(self):
3229
    """Build hooks env.
3230

3231
    This will run on all nodes before, and on all nodes + the new node after.
3232

3233
    """
3234
    env = {
3235
      "OP_TARGET": self.op.node_name,
3236
      "NODE_NAME": self.op.node_name,
3237
      "NODE_PIP": self.op.primary_ip,
3238
      "NODE_SIP": self.op.secondary_ip,
3239
      }
3240
    nodes_0 = self.cfg.GetNodeList()
3241
    nodes_1 = nodes_0 + [self.op.node_name, ]
3242
    return env, nodes_0, nodes_1
3243

    
3244
  def CheckPrereq(self):
3245
    """Check prerequisites.
3246

3247
    This checks:
3248
     - the new node is not already in the config
3249
     - it is resolvable
3250
     - its parameters (single/dual homed) matches the cluster
3251

3252
    Any errors are signaled by raising errors.OpPrereqError.
3253

3254
    """
3255
    node_name = self.op.node_name
3256
    cfg = self.cfg
3257

    
3258
    dns_data = utils.GetHostInfo(node_name)
3259

    
3260
    node = dns_data.name
3261
    primary_ip = self.op.primary_ip = dns_data.ip
3262
    secondary_ip = getattr(self.op, "secondary_ip", None)
3263
    if secondary_ip is None:
3264
      secondary_ip = primary_ip
3265
    if not utils.IsValidIP(secondary_ip):
3266
      raise errors.OpPrereqError("Invalid secondary IP given",
3267
                                 errors.ECODE_INVAL)
3268
    self.op.secondary_ip = secondary_ip
3269

    
3270
    node_list = cfg.GetNodeList()
3271
    if not self.op.readd and node in node_list:
3272
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3273
                                 node, errors.ECODE_EXISTS)
3274
    elif self.op.readd and node not in node_list:
3275
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3276
                                 errors.ECODE_NOENT)
3277

    
3278
    for existing_node_name in node_list:
3279
      existing_node = cfg.GetNodeInfo(existing_node_name)
3280

    
3281
      if self.op.readd and node == existing_node_name:
3282
        if (existing_node.primary_ip != primary_ip or
3283
            existing_node.secondary_ip != secondary_ip):
3284
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3285
                                     " address configuration as before",
3286
                                     errors.ECODE_INVAL)
3287
        continue
3288

    
3289
      if (existing_node.primary_ip == primary_ip or
3290
          existing_node.secondary_ip == primary_ip or
3291
          existing_node.primary_ip == secondary_ip or
3292
          existing_node.secondary_ip == secondary_ip):
3293
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3294
                                   " existing node %s" % existing_node.name,
3295
                                   errors.ECODE_NOTUNIQUE)
3296

    
3297
    # check that the type of the node (single versus dual homed) is the
3298
    # same as for the master
3299
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3300
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3301
    newbie_singlehomed = secondary_ip == primary_ip
3302
    if master_singlehomed != newbie_singlehomed:
3303
      if master_singlehomed:
3304
        raise errors.OpPrereqError("The master has no private ip but the"
3305
                                   " new node has one",
3306
                                   errors.ECODE_INVAL)
3307
      else:
3308
        raise errors.OpPrereqError("The master has a private ip but the"
3309
                                   " new node doesn't have one",
3310
                                   errors.ECODE_INVAL)
3311

    
3312
    # checks reachability
3313
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3314
      raise errors.OpPrereqError("Node not reachable by ping",
3315
                                 errors.ECODE_ENVIRON)
3316

    
3317
    if not newbie_singlehomed:
3318
      # check reachability from my secondary ip to newbie's secondary ip
3319
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3320
                           source=myself.secondary_ip):
3321
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3322
                                   " based ping to noded port",
3323
                                   errors.ECODE_ENVIRON)
3324

    
3325
    if self.op.readd:
3326
      exceptions = [node]
3327
    else:
3328
      exceptions = []
3329

    
3330
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3331

    
3332
    if self.op.readd:
3333
      self.new_node = self.cfg.GetNodeInfo(node)
3334
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3335
    else:
3336
      self.new_node = objects.Node(name=node,
3337
                                   primary_ip=primary_ip,
3338
                                   secondary_ip=secondary_ip,
3339
                                   master_candidate=self.master_candidate,
3340
                                   offline=False, drained=False)
3341

    
3342
  def Exec(self, feedback_fn):
3343
    """Adds the new node to the cluster.
3344

3345
    """
3346
    new_node = self.new_node
3347
    node = new_node.name
3348

    
3349
    # for re-adds, reset the offline/drained/master-candidate flags;
3350
    # we need to reset here, otherwise offline would prevent RPC calls
3351
    # later in the procedure; this also means that if the re-add
3352
    # fails, we are left with a non-offlined, broken node
3353
    if self.op.readd:
3354
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3355
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3356
      # if we demote the node, we do cleanup later in the procedure
3357
      new_node.master_candidate = self.master_candidate
3358

    
3359
    # notify the user about any possible mc promotion
3360
    if new_node.master_candidate:
3361
      self.LogInfo("Node will be a master candidate")
3362

    
3363
    # check connectivity
3364
    result = self.rpc.call_version([node])[node]
3365
    result.Raise("Can't get version information from node %s" % node)
3366
    if constants.PROTOCOL_VERSION == result.payload:
3367
      logging.info("Communication to node %s fine, sw version %s match",
3368
                   node, result.payload)
3369
    else:
3370
      raise errors.OpExecError("Version mismatch master version %s,"
3371
                               " node version %s" %
3372
                               (constants.PROTOCOL_VERSION, result.payload))
3373

    
3374
    # setup ssh on node
3375
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3376
      logging.info("Copy ssh key to node %s", node)
3377
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3378
      keyarray = []
3379
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3380
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3381
                  priv_key, pub_key]
3382

    
3383
      for i in keyfiles:
3384
        keyarray.append(utils.ReadFile(i))
3385

    
3386
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3387
                                      keyarray[2], keyarray[3], keyarray[4],
3388
                                      keyarray[5])
3389
      result.Raise("Cannot transfer ssh keys to the new node")
3390

    
3391
    # Add node to our /etc/hosts, and add key to known_hosts
3392
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3393
      utils.AddHostToEtcHosts(new_node.name)
3394

    
3395
    if new_node.secondary_ip != new_node.primary_ip:
3396
      result = self.rpc.call_node_has_ip_address(new_node.name,
3397
                                                 new_node.secondary_ip)
3398
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3399
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3400
      if not result.payload:
3401
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3402
                                 " you gave (%s). Please fix and re-run this"
3403
                                 " command." % new_node.secondary_ip)
3404

    
3405
    node_verify_list = [self.cfg.GetMasterNode()]
3406
    node_verify_param = {
3407
      constants.NV_NODELIST: [node],
3408
      # TODO: do a node-net-test as well?
3409
    }
3410

    
3411
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3412
                                       self.cfg.GetClusterName())
3413
    for verifier in node_verify_list:
3414
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3415
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3416
      if nl_payload:
3417
        for failed in nl_payload:
3418
          feedback_fn("ssh/hostname verification failed"
3419
                      " (checking from %s): %s" %
3420
                      (verifier, nl_payload[failed]))
3421
        raise errors.OpExecError("ssh/hostname verification failed.")
3422

    
3423
    if self.op.readd:
3424
      _RedistributeAncillaryFiles(self)
3425
      self.context.ReaddNode(new_node)
3426
      # make sure we redistribute the config
3427
      self.cfg.Update(new_node, feedback_fn)
3428
      # and make sure the new node will not have old files around
3429
      if not new_node.master_candidate:
3430
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3431
        msg = result.fail_msg
3432
        if msg:
3433
          self.LogWarning("Node failed to demote itself from master"
3434
                          " candidate status: %s" % msg)
3435
    else:
3436
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3437
      self.context.AddNode(new_node, self.proc.GetECId())
3438

    
3439

    
3440
class LUSetNodeParams(LogicalUnit):
3441
  """Modifies the parameters of a node.
3442

3443
  """
3444
  HPATH = "node-modify"
3445
  HTYPE = constants.HTYPE_NODE
3446
  _OP_REQP = ["node_name"]
3447
  REQ_BGL = False
3448

    
3449
  def CheckArguments(self):
3450
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3451
    _CheckBooleanOpField(self.op, 'master_candidate')
3452
    _CheckBooleanOpField(self.op, 'offline')
3453
    _CheckBooleanOpField(self.op, 'drained')
3454
    _CheckBooleanOpField(self.op, 'auto_promote')
3455
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3456
    if all_mods.count(None) == 3:
3457
      raise errors.OpPrereqError("Please pass at least one modification",
3458
                                 errors.ECODE_INVAL)
3459
    if all_mods.count(True) > 1:
3460
      raise errors.OpPrereqError("Can't set the node into more than one"
3461
                                 " state at the same time",
3462
                                 errors.ECODE_INVAL)
3463

    
3464
    # Boolean value that tells us whether we're offlining or draining the node
3465
    self.offline_or_drain = (self.op.offline == True or
3466
                             self.op.drained == True)
3467
    self.deoffline_or_drain = (self.op.offline == False or
3468
                               self.op.drained == False)
3469
    self.might_demote = (self.op.master_candidate == False or
3470
                         self.offline_or_drain)
3471

    
3472
    self.lock_all = self.op.auto_promote and self.might_demote
3473

    
3474

    
3475
  def ExpandNames(self):
3476
    if self.lock_all:
3477
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3478
    else:
3479
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3480

    
3481
  def BuildHooksEnv(self):
3482
    """Build hooks env.
3483

3484
    This runs on the master node.
3485

3486
    """
3487
    env = {
3488
      "OP_TARGET": self.op.node_name,
3489
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3490
      "OFFLINE": str(self.op.offline),
3491
      "DRAINED": str(self.op.drained),
3492
      }
3493
    nl = [self.cfg.GetMasterNode(),
3494
          self.op.node_name]
3495
    return env, nl, nl
3496

    
3497
  def CheckPrereq(self):
3498
    """Check prerequisites.
3499

3500
    This only checks the instance list against the existing names.
3501

3502
    """
3503
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3504

    
3505
    if (self.op.master_candidate is not None or
3506
        self.op.drained is not None or
3507
        self.op.offline is not None):
3508
      # we can't change the master's node flags
3509
      if self.op.node_name == self.cfg.GetMasterNode():
3510
        raise errors.OpPrereqError("The master role can be changed"
3511
                                   " only via masterfailover",
3512
                                   errors.ECODE_INVAL)
3513

    
3514

    
3515
    if node.master_candidate and self.might_demote and not self.lock_all:
3516
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3517
      # check if after removing the current node, we're missing master
3518
      # candidates
3519
      (mc_remaining, mc_should, _) = \
3520
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3521
      if mc_remaining < mc_should:
3522
        raise errors.OpPrereqError("Not enough master candidates, please"
3523
                                   " pass auto_promote to allow promotion",
3524
                                   errors.ECODE_INVAL)
3525

    
3526
    if (self.op.master_candidate == True and
3527
        ((node.offline and not self.op.offline == False) or
3528
         (node.drained and not self.op.drained == False))):
3529
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3530
                                 " to master_candidate" % node.name,
3531
                                 errors.ECODE_INVAL)
3532

    
3533
    # If we're being deofflined/drained, we'll MC ourself if needed
3534
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3535
        self.op.master_candidate == True and not node.master_candidate):
3536
      self.op.master_candidate = _DecideSelfPromotion(self)
3537
      if self.op.master_candidate:
3538
        self.LogInfo("Autopromoting node to master candidate")
3539

    
3540
    return
3541

    
3542
  def Exec(self, feedback_fn):
3543
    """Modifies a node.
3544

3545
    """
3546
    node = self.node
3547

    
3548
    result = []
3549
    changed_mc = False
3550

    
3551
    if self.op.offline is not None:
3552
      node.offline = self.op.offline
3553
      result.append(("offline", str(self.op.offline)))
3554
      if self.op.offline == True:
3555
        if node.master_candidate:
3556
          node.master_candidate = False
3557
          changed_mc = True
3558
          result.append(("master_candidate", "auto-demotion due to offline"))
3559
        if node.drained:
3560
          node.drained = False
3561
          result.append(("drained", "clear drained status due to offline"))
3562

    
3563
    if self.op.master_candidate is not None:
3564
      node.master_candidate = self.op.master_candidate
3565
      changed_mc = True
3566
      result.append(("master_candidate", str(self.op.master_candidate)))
3567
      if self.op.master_candidate == False:
3568
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3569
        msg = rrc.fail_msg
3570
        if msg:
3571
          self.LogWarning("Node failed to demote itself: %s" % msg)
3572

    
3573
    if self.op.drained is not None:
3574
      node.drained = self.op.drained
3575
      result.append(("drained", str(self.op.drained)))
3576
      if self.op.drained == True:
3577
        if node.master_candidate:
3578
          node.master_candidate = False
3579
          changed_mc = True
3580
          result.append(("master_candidate", "auto-demotion due to drain"))
3581
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3582
          msg = rrc.fail_msg
3583
          if msg:
3584
            self.LogWarning("Node failed to demote itself: %s" % msg)
3585
        if node.offline:
3586
          node.offline = False
3587
          result.append(("offline", "clear offline status due to drain"))
3588

    
3589
    # we locked all nodes, we adjust the CP before updating this node
3590
    if self.lock_all:
3591
      _AdjustCandidatePool(self, [node.name])
3592

    
3593
    # this will trigger configuration file update, if needed
3594
    self.cfg.Update(node, feedback_fn)
3595

    
3596
    # this will trigger job queue propagation or cleanup
3597
    if changed_mc:
3598
      self.context.ReaddNode(node)
3599

    
3600
    return result
3601

    
3602

    
3603
class LUPowercycleNode(NoHooksLU):
3604
  """Powercycles a node.
3605

3606
  """
3607
  _OP_REQP = ["node_name", "force"]
3608
  REQ_BGL = False
3609

    
3610
  def CheckArguments(self):
3611
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3612
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
3613
      raise errors.OpPrereqError("The node is the master and the force"
3614
                                 " parameter was not set",
3615
                                 errors.ECODE_INVAL)
3616

    
3617
  def ExpandNames(self):
3618
    """Locking for PowercycleNode.
3619

3620
    This is a last-resort option and shouldn't block on other
3621
    jobs. Therefore, we grab no locks.
3622

3623
    """
3624
    self.needed_locks = {}
3625

    
3626
  def CheckPrereq(self):
3627
    """Check prerequisites.
3628

3629
    This LU has no prereqs.
3630

3631
    """
3632
    pass
3633

    
3634
  def Exec(self, feedback_fn):
3635
    """Reboots a node.
3636

3637
    """
3638
    result = self.rpc.call_node_powercycle(self.op.node_name,
3639
                                           self.cfg.GetHypervisorType())
3640
    result.Raise("Failed to schedule the reboot")
3641
    return result.payload
3642

    
3643

    
3644
class LUQueryClusterInfo(NoHooksLU):
3645
  """Query cluster configuration.
3646

3647
  """
3648
  _OP_REQP = []
3649
  REQ_BGL = False
3650

    
3651
  def ExpandNames(self):
3652
    self.needed_locks = {}
3653

    
3654
  def CheckPrereq(self):
3655
    """No prerequsites needed for this LU.
3656

3657
    """
3658
    pass
3659

    
3660
  def Exec(self, feedback_fn):
3661
    """Return cluster config.
3662

3663
    """
3664
    cluster = self.cfg.GetClusterInfo()
3665
    os_hvp = {}
3666

    
3667
    # Filter just for enabled hypervisors
3668
    for os_name, hv_dict in cluster.os_hvp.items():
3669
      os_hvp[os_name] = {}
3670
      for hv_name, hv_params in hv_dict.items():
3671
        if hv_name in cluster.enabled_hypervisors:
3672
          os_hvp[os_name][hv_name] = hv_params
3673

    
3674
    result = {
3675
      "software_version": constants.RELEASE_VERSION,
3676
      "protocol_version": constants.PROTOCOL_VERSION,
3677
      "config_version": constants.CONFIG_VERSION,
3678
      "os_api_version": max(constants.OS_API_VERSIONS),
3679
      "export_version": constants.EXPORT_VERSION,
3680
      "architecture": (platform.architecture()[0], platform.machine()),
3681
      "name": cluster.cluster_name,
3682
      "master": cluster.master_node,
3683
      "default_hypervisor": cluster.enabled_hypervisors[0],
3684
      "enabled_hypervisors": cluster.enabled_hypervisors,
3685
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3686
                        for hypervisor_name in cluster.enabled_hypervisors]),
3687
      "os_hvp": os_hvp,
3688
      "beparams": cluster.beparams,
3689
      "nicparams": cluster.nicparams,
3690
      "candidate_pool_size": cluster.candidate_pool_size,
3691
      "master_netdev": cluster.master_netdev,
3692
      "volume_group_name": cluster.volume_group_name,
3693
      "file_storage_dir": cluster.file_storage_dir,
3694
      "ctime": cluster.ctime,
3695
      "mtime": cluster.mtime,
3696
      "uuid": cluster.uuid,
3697
      "tags": list(cluster.GetTags()),
3698
      }
3699

    
3700
    return result
3701

    
3702

    
3703
class LUQueryConfigValues(NoHooksLU):
3704
  """Return configuration values.
3705

3706
  """
3707
  _OP_REQP = []
3708
  REQ_BGL = False
3709
  _FIELDS_DYNAMIC = utils.FieldSet()
3710
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3711
                                  "watcher_pause")
3712

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

    
3716
    _CheckOutputFields(static=self._FIELDS_STATIC,
3717
                       dynamic=self._FIELDS_DYNAMIC,
3718
                       selected=self.op.output_fields)
3719

    
3720
  def CheckPrereq(self):
3721
    """No prerequisites.
3722

3723
    """
3724
    pass
3725

    
3726
  def Exec(self, feedback_fn):
3727
    """Dump a representation of the cluster config to the standard output.
3728

3729
    """
3730
    values = []
3731
    for field in self.op.output_fields:
3732
      if field == "cluster_name":
3733
        entry = self.cfg.GetClusterName()
3734
      elif field == "master_node":
3735
        entry = self.cfg.GetMasterNode()
3736
      elif field == "drain_flag":
3737
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3738
      elif field == "watcher_pause":
3739
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3740
      else:
3741
        raise errors.ParameterError(field)
3742
      values.append(entry)
3743
    return values
3744

    
3745

    
3746
class LUActivateInstanceDisks(NoHooksLU):
3747
  """Bring up an instance's disks.
3748

3749
  """
3750
  _OP_REQP = ["instance_name"]
3751
  REQ_BGL = False
3752

    
3753
  def ExpandNames(self):
3754
    self._ExpandAndLockInstance()
3755
    self.needed_locks[locking.LEVEL_NODE] = []
3756
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3757

    
3758
  def DeclareLocks(self, level):
3759
    if level == locking.LEVEL_NODE:
3760
      self._LockInstancesNodes()
3761

    
3762
  def CheckPrereq(self):
3763
    """Check prerequisites.
3764

3765
    This checks that the instance is in the cluster.
3766

3767
    """
3768
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3769
    assert self.instance is not None, \
3770
      "Cannot retrieve locked instance %s" % self.op.instance_name
3771
    _CheckNodeOnline(self, self.instance.primary_node)
3772
    if not hasattr(self.op, "ignore_size"):
3773
      self.op.ignore_size = False
3774

    
3775
  def Exec(self, feedback_fn):
3776
    """Activate the disks.
3777

3778
    """
3779
    disks_ok, disks_info = \
3780
              _AssembleInstanceDisks(self, self.instance,
3781
                                     ignore_size=self.op.ignore_size)
3782
    if not disks_ok:
3783
      raise errors.OpExecError("Cannot activate block devices")
3784

    
3785
    return disks_info
3786

    
3787

    
3788
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3789
                           ignore_size=False):
3790
  """Prepare the block devices for an instance.
3791

3792
  This sets up the block devices on all nodes.
3793

3794
  @type lu: L{LogicalUnit}
3795
  @param lu: the logical unit on whose behalf we execute
3796
  @type instance: L{objects.Instance}
3797
  @param instance: the instance for whose disks we assemble
3798
  @type ignore_secondaries: boolean
3799
  @param ignore_secondaries: if true, errors on secondary nodes
3800
      won't result in an error return from the function
3801
  @type ignore_size: boolean
3802
  @param ignore_size: if true, the current known size of the disk
3803
      will not be used during the disk activation, useful for cases
3804
      when the size is wrong
3805
  @return: False if the operation failed, otherwise a list of
3806
      (host, instance_visible_name, node_visible_name)
3807
      with the mapping from node devices to instance devices
3808

3809
  """
3810
  device_info = []
3811
  disks_ok = True
3812
  iname = instance.name
3813
  # With the two passes mechanism we try to reduce the window of
3814
  # opportunity for the race condition of switching DRBD to primary
3815
  # before handshaking occured, but we do not eliminate it
3816

    
3817
  # The proper fix would be to wait (with some limits) until the
3818
  # connection has been made and drbd transitions from WFConnection
3819
  # into any other network-connected state (Connected, SyncTarget,
3820
  # SyncSource, etc.)
3821

    
3822
  # 1st pass, assemble on all nodes in secondary mode
3823
  for inst_disk in instance.disks:
3824
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3825
      if ignore_size:
3826
        node_disk = node_disk.Copy()
3827
        node_disk.UnsetSize()
3828
      lu.cfg.SetDiskID(node_disk, node)
3829
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3830
      msg = result.fail_msg
3831
      if msg:
3832
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3833
                           " (is_primary=False, pass=1): %s",
3834
                           inst_disk.iv_name, node, msg)
3835
        if not ignore_secondaries:
3836
          disks_ok = False
3837

    
3838
  # FIXME: race condition on drbd migration to primary
3839

    
3840
  # 2nd pass, do only the primary node
3841
  for inst_disk in instance.disks:
3842
    dev_path = None
3843

    
3844
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3845
      if node != instance.primary_node:
3846
        continue
3847
      if ignore_size:
3848
        node_disk = node_disk.Copy()
3849
        node_disk.UnsetSize()
3850
      lu.cfg.SetDiskID(node_disk, node)
3851
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3852
      msg = result.fail_msg
3853
      if msg:
3854
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3855
                           " (is_primary=True, pass=2): %s",
3856
                           inst_disk.iv_name, node, msg)
3857
        disks_ok = False
3858
      else:
3859
        dev_path = result.payload
3860

    
3861
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3862

    
3863
  # leave the disks configured for the primary node
3864
  # this is a workaround that would be fixed better by
3865
  # improving the logical/physical id handling
3866
  for disk in instance.disks:
3867
    lu.cfg.SetDiskID(disk, instance.primary_node)
3868

    
3869
  return disks_ok, device_info
3870

    
3871

    
3872
def _StartInstanceDisks(lu, instance, force):
3873
  """Start the disks of an instance.
3874

3875
  """
3876
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3877
                                           ignore_secondaries=force)
3878
  if not disks_ok:
3879
    _ShutdownInstanceDisks(lu, instance)
3880
    if force is not None and not force:
3881
      lu.proc.LogWarning("", hint="If the message above refers to a"
3882
                         " secondary node,"
3883
                         " you can retry the operation using '--force'.")
3884
    raise errors.OpExecError("Disk consistency error")
3885

    
3886

    
3887
class LUDeactivateInstanceDisks(NoHooksLU):
3888
  """Shutdown an instance's disks.
3889

3890
  """
3891
  _OP_REQP = ["instance_name"]
3892
  REQ_BGL = False
3893

    
3894
  def ExpandNames(self):
3895
    self._ExpandAndLockInstance()
3896
    self.needed_locks[locking.LEVEL_NODE] = []
3897
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3898

    
3899
  def DeclareLocks(self, level):
3900
    if level == locking.LEVEL_NODE:
3901
      self._LockInstancesNodes()
3902

    
3903
  def CheckPrereq(self):
3904
    """Check prerequisites.
3905

3906
    This checks that the instance is in the cluster.
3907

3908
    """
3909
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3910
    assert self.instance is not None, \
3911
      "Cannot retrieve locked instance %s" % self.op.instance_name
3912

    
3913
  def Exec(self, feedback_fn):
3914
    """Deactivate the disks
3915

3916
    """
3917
    instance = self.instance
3918
    _SafeShutdownInstanceDisks(self, instance)
3919

    
3920

    
3921
def _SafeShutdownInstanceDisks(lu, instance):
3922
  """Shutdown block devices of an instance.
3923

3924
  This function checks if an instance is running, before calling
3925
  _ShutdownInstanceDisks.
3926

3927
  """
3928
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
3929
  _ShutdownInstanceDisks(lu, instance)
3930

    
3931

    
3932
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3933
  """Shutdown block devices of an instance.
3934

3935
  This does the shutdown on all nodes of the instance.
3936

3937
  If the ignore_primary is false, errors on the primary node are
3938
  ignored.
3939

3940
  """
3941
  all_result = True
3942
  for disk in instance.disks:
3943
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3944
      lu.cfg.SetDiskID(top_disk, node)
3945
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3946
      msg = result.fail_msg
3947
      if msg:
3948
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3949
                      disk.iv_name, node, msg)
3950
        if not ignore_primary or node != instance.primary_node:
3951
          all_result = False
3952
  return all_result
3953

    
3954

    
3955
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3956
  """Checks if a node has enough free memory.
3957

3958
  This function check if a given node has the needed amount of free
3959
  memory. In case the node has less memory or we cannot get the
3960
  information from the node, this function raise an OpPrereqError
3961
  exception.
3962

3963
  @type lu: C{LogicalUnit}
3964
  @param lu: a logical unit from which we get configuration data
3965
  @type node: C{str}
3966
  @param node: the node to check
3967
  @type reason: C{str}
3968
  @param reason: string to use in the error message
3969
  @type requested: C{int}
3970
  @param requested: the amount of memory in MiB to check for
3971
  @type hypervisor_name: C{str}
3972
  @param hypervisor_name: the hypervisor to ask for memory stats
3973
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3974
      we cannot check the node
3975

3976
  """
3977
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3978
  nodeinfo[node].Raise("Can't get data from node %s" % node,
3979
                       prereq=True, ecode=errors.ECODE_ENVIRON)
3980
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3981
  if not isinstance(free_mem, int):
3982
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3983
                               " was '%s'" % (node, free_mem),
3984
                               errors.ECODE_ENVIRON)
3985
  if requested > free_mem:
3986
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3987
                               " needed %s MiB, available %s MiB" %
3988
                               (node, reason, requested, free_mem),
3989
                               errors.ECODE_NORES)
3990

    
3991

    
3992
def _CheckNodesFreeDisk(lu, nodenames, requested):
3993
  """Checks if nodes have enough free disk space in the default VG.
3994

3995
  This function check if all given nodes have the needed amount of
3996
  free disk. In case any node has less disk or we cannot get the
3997
  information from the node, this function raise an OpPrereqError
3998
  exception.
3999

4000
  @type lu: C{LogicalUnit}
4001
  @param lu: a logical unit from which we get configuration data
4002
  @type nodenames: C{list}
4003
  @param nodenames: the list of node names to check
4004
  @type requested: C{int}
4005
  @param requested: the amount of disk in MiB to check for
4006
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4007
      we cannot check the node
4008

4009
  """
4010
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4011
                                   lu.cfg.GetHypervisorType())
4012
  for node in nodenames:
4013
    info = nodeinfo[node]
4014
    info.Raise("Cannot get current information from node %s" % node,
4015
               prereq=True, ecode=errors.ECODE_ENVIRON)
4016
    vg_free = info.payload.get("vg_free", None)
4017
    if not isinstance(vg_free, int):
4018
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4019
                                 " result was '%s'" % (node, vg_free),
4020
                                 errors.ECODE_ENVIRON)
4021
    if requested > vg_free:
4022
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4023
                                 " required %d MiB, available %d MiB" %
4024
                                 (node, requested, vg_free),
4025
                                 errors.ECODE_NORES)
4026

    
4027

    
4028
class LUStartupInstance(LogicalUnit):
4029
  """Starts an instance.
4030

4031
  """
4032
  HPATH = "instance-start"
4033
  HTYPE = constants.HTYPE_INSTANCE
4034
  _OP_REQP = ["instance_name", "force"]
4035
  REQ_BGL = False
4036

    
4037
  def ExpandNames(self):
4038
    self._ExpandAndLockInstance()
4039

    
4040
  def BuildHooksEnv(self):
4041
    """Build hooks env.
4042

4043
    This runs on master, primary and secondary nodes of the instance.
4044

4045
    """
4046
    env = {
4047
      "FORCE": self.op.force,
4048
      }
4049
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4050
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4051
    return env, nl, nl
4052

    
4053
  def CheckPrereq(self):
4054
    """Check prerequisites.
4055

4056
    This checks that the instance is in the cluster.
4057

4058
    """
4059
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4060
    assert self.instance is not None, \
4061
      "Cannot retrieve locked instance %s" % self.op.instance_name
4062

    
4063
    # extra beparams
4064
    self.beparams = getattr(self.op, "beparams", {})
4065
    if self.beparams:
4066
      if not isinstance(self.beparams, dict):
4067
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
4068
                                   " dict" % (type(self.beparams), ),
4069
                                   errors.ECODE_INVAL)
4070
      # fill the beparams dict
4071
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
4072
      self.op.beparams = self.beparams
4073

    
4074
    # extra hvparams
4075
    self.hvparams = getattr(self.op, "hvparams", {})
4076
    if self.hvparams:
4077
      if not isinstance(self.hvparams, dict):
4078
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
4079
                                   " dict" % (type(self.hvparams), ),
4080
                                   errors.ECODE_INVAL)
4081

    
4082
      # check hypervisor parameter syntax (locally)
4083
      cluster = self.cfg.GetClusterInfo()
4084
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
4085
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
4086
                                    instance.hvparams)
4087
      filled_hvp.update(self.hvparams)
4088
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4089
      hv_type.CheckParameterSyntax(filled_hvp)
4090
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4091
      self.op.hvparams = self.hvparams
4092

    
4093
    _CheckNodeOnline(self, instance.primary_node)
4094

    
4095
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4096
    # check bridges existence
4097
    _CheckInstanceBridgesExist(self, instance)
4098

    
4099
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4100
                                              instance.name,
4101
                                              instance.hypervisor)
4102
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4103
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4104
    if not remote_info.payload: # not running already
4105
      _CheckNodeFreeMemory(self, instance.primary_node,
4106
                           "starting instance %s" % instance.name,
4107
                           bep[constants.BE_MEMORY], instance.hypervisor)
4108

    
4109
  def Exec(self, feedback_fn):
4110
    """Start the instance.
4111

4112
    """
4113
    instance = self.instance
4114
    force = self.op.force
4115

    
4116
    self.cfg.MarkInstanceUp(instance.name)
4117

    
4118
    node_current = instance.primary_node
4119

    
4120
    _StartInstanceDisks(self, instance, force)
4121

    
4122
    result = self.rpc.call_instance_start(node_current, instance,
4123
                                          self.hvparams, self.beparams)
4124
    msg = result.fail_msg
4125
    if msg:
4126
      _ShutdownInstanceDisks(self, instance)
4127
      raise errors.OpExecError("Could not start instance: %s" % msg)
4128

    
4129

    
4130
class LURebootInstance(LogicalUnit):
4131
  """Reboot an instance.
4132

4133
  """
4134
  HPATH = "instance-reboot"
4135
  HTYPE = constants.HTYPE_INSTANCE
4136
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
4137
  REQ_BGL = False
4138

    
4139
  def CheckArguments(self):
4140
    """Check the arguments.
4141

4142
    """
4143
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4144
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4145

    
4146
  def ExpandNames(self):
4147
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
4148
                                   constants.INSTANCE_REBOOT_HARD,
4149
                                   constants.INSTANCE_REBOOT_FULL]:
4150
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
4151
                                  (constants.INSTANCE_REBOOT_SOFT,
4152
                                   constants.INSTANCE_REBOOT_HARD,
4153
                                   constants.INSTANCE_REBOOT_FULL))
4154
    self._ExpandAndLockInstance()
4155

    
4156
  def BuildHooksEnv(self):
4157
    """Build hooks env.
4158

4159
    This runs on master, primary and secondary nodes of the instance.
4160

4161
    """
4162
    env = {
4163
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4164
      "REBOOT_TYPE": self.op.reboot_type,
4165
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4166
      }
4167
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4168
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4169
    return env, nl, nl
4170

    
4171
  def CheckPrereq(self):
4172
    """Check prerequisites.
4173

4174
    This checks that the instance is in the cluster.
4175

4176
    """
4177
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4178
    assert self.instance is not None, \
4179
      "Cannot retrieve locked instance %s" % self.op.instance_name
4180

    
4181
    _CheckNodeOnline(self, instance.primary_node)
4182

    
4183
    # check bridges existence
4184
    _CheckInstanceBridgesExist(self, instance)
4185

    
4186
  def Exec(self, feedback_fn):
4187
    """Reboot the instance.
4188

4189
    """
4190
    instance = self.instance
4191
    ignore_secondaries = self.op.ignore_secondaries
4192
    reboot_type = self.op.reboot_type
4193

    
4194
    node_current = instance.primary_node
4195

    
4196
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4197
                       constants.INSTANCE_REBOOT_HARD]:
4198
      for disk in instance.disks:
4199
        self.cfg.SetDiskID(disk, node_current)
4200
      result = self.rpc.call_instance_reboot(node_current, instance,
4201
                                             reboot_type,
4202
                                             self.shutdown_timeout)
4203
      result.Raise("Could not reboot instance")
4204
    else:
4205
      result = self.rpc.call_instance_shutdown(node_current, instance,
4206
                                               self.shutdown_timeout)
4207
      result.Raise("Could not shutdown instance for full reboot")
4208
      _ShutdownInstanceDisks(self, instance)
4209
      _StartInstanceDisks(self, instance, ignore_secondaries)
4210
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4211
      msg = result.fail_msg
4212
      if msg:
4213
        _ShutdownInstanceDisks(self, instance)
4214
        raise errors.OpExecError("Could not start instance for"
4215
                                 " full reboot: %s" % msg)
4216

    
4217
    self.cfg.MarkInstanceUp(instance.name)
4218

    
4219

    
4220
class LUShutdownInstance(LogicalUnit):
4221
  """Shutdown an instance.
4222

4223
  """
4224
  HPATH = "instance-stop"
4225
  HTYPE = constants.HTYPE_INSTANCE
4226
  _OP_REQP = ["instance_name"]
4227
  REQ_BGL = False
4228

    
4229
  def CheckArguments(self):
4230
    """Check the arguments.
4231

4232
    """
4233
    self.timeout = getattr(self.op, "timeout",
4234
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
4235

    
4236
  def ExpandNames(self):
4237
    self._ExpandAndLockInstance()
4238

    
4239
  def BuildHooksEnv(self):
4240
    """Build hooks env.
4241

4242
    This runs on master, primary and secondary nodes of the instance.
4243

4244
    """
4245
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4246
    env["TIMEOUT"] = self.timeout
4247
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4248
    return env, nl, nl
4249

    
4250
  def CheckPrereq(self):
4251
    """Check prerequisites.
4252

4253
    This checks that the instance is in the cluster.
4254

4255
    """
4256
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4257
    assert self.instance is not None, \
4258
      "Cannot retrieve locked instance %s" % self.op.instance_name
4259
    _CheckNodeOnline(self, self.instance.primary_node)
4260

    
4261
  def Exec(self, feedback_fn):
4262
    """Shutdown the instance.
4263

4264
    """
4265
    instance = self.instance
4266
    node_current = instance.primary_node
4267
    timeout = self.timeout
4268
    self.cfg.MarkInstanceDown(instance.name)
4269
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4270
    msg = result.fail_msg
4271
    if msg:
4272
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4273

    
4274
    _ShutdownInstanceDisks(self, instance)
4275

    
4276

    
4277
class LUReinstallInstance(LogicalUnit):
4278
  """Reinstall an instance.
4279

4280
  """
4281
  HPATH = "instance-reinstall"
4282
  HTYPE = constants.HTYPE_INSTANCE
4283
  _OP_REQP = ["instance_name"]
4284
  REQ_BGL = False
4285

    
4286
  def ExpandNames(self):
4287
    self._ExpandAndLockInstance()
4288

    
4289
  def BuildHooksEnv(self):
4290
    """Build hooks env.
4291

4292
    This runs on master, primary and secondary nodes of the instance.
4293

4294
    """
4295
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4296
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4297
    return env, nl, nl
4298

    
4299
  def CheckPrereq(self):
4300
    """Check prerequisites.
4301

4302
    This checks that the instance is in the cluster and is not running.
4303

4304
    """
4305
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4306
    assert instance is not None, \
4307
      "Cannot retrieve locked instance %s" % self.op.instance_name
4308
    _CheckNodeOnline(self, instance.primary_node)
4309

    
4310
    if instance.disk_template == constants.DT_DISKLESS:
4311
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4312
                                 self.op.instance_name,
4313
                                 errors.ECODE_INVAL)
4314
    _CheckInstanceDown(self, instance, "cannot reinstall")
4315

    
4316
    self.op.os_type = getattr(self.op, "os_type", None)
4317
    self.op.force_variant = getattr(self.op, "force_variant", False)
4318
    if self.op.os_type is not None:
4319
      # OS verification
4320
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4321
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4322

    
4323
    self.instance = instance
4324

    
4325
  def Exec(self, feedback_fn):
4326
    """Reinstall the instance.
4327

4328
    """
4329
    inst = self.instance
4330

    
4331
    if self.op.os_type is not None:
4332
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4333
      inst.os = self.op.os_type
4334
      self.cfg.Update(inst, feedback_fn)
4335

    
4336
    _StartInstanceDisks(self, inst, None)
4337
    try:
4338
      feedback_fn("Running the instance OS create scripts...")
4339
      # FIXME: pass debug option from opcode to backend
4340
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4341
                                             self.op.debug_level)
4342
      result.Raise("Could not install OS for instance %s on node %s" %
4343
                   (inst.name, inst.primary_node))
4344
    finally:
4345
      _ShutdownInstanceDisks(self, inst)
4346

    
4347

    
4348
class LURecreateInstanceDisks(LogicalUnit):
4349
  """Recreate an instance's missing disks.
4350

4351
  """
4352
  HPATH = "instance-recreate-disks"
4353
  HTYPE = constants.HTYPE_INSTANCE
4354
  _OP_REQP = ["instance_name", "disks"]
4355
  REQ_BGL = False
4356

    
4357
  def CheckArguments(self):
4358
    """Check the arguments.
4359

4360
    """
4361
    if not isinstance(self.op.disks, list):
4362
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
4363
    for item in self.op.disks:
4364
      if (not isinstance(item, int) or
4365
          item < 0):
4366
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
4367
                                   str(item), errors.ECODE_INVAL)
4368

    
4369
  def ExpandNames(self):
4370
    self._ExpandAndLockInstance()
4371

    
4372
  def BuildHooksEnv(self):
4373
    """Build hooks env.
4374

4375
    This runs on master, primary and secondary nodes of the instance.
4376

4377
    """
4378
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4379
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4380
    return env, nl, nl
4381

    
4382
  def CheckPrereq(self):
4383
    """Check prerequisites.
4384

4385
    This checks that the instance is in the cluster and is not running.
4386

4387
    """
4388
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4389
    assert instance is not None, \
4390
      "Cannot retrieve locked instance %s" % self.op.instance_name
4391
    _CheckNodeOnline(self, instance.primary_node)
4392

    
4393
    if instance.disk_template == constants.DT_DISKLESS:
4394
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4395
                                 self.op.instance_name, errors.ECODE_INVAL)
4396
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4397

    
4398
    if not self.op.disks:
4399
      self.op.disks = range(len(instance.disks))
4400
    else:
4401
      for idx in self.op.disks:
4402
        if idx >= len(instance.disks):
4403
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4404
                                     errors.ECODE_INVAL)
4405

    
4406
    self.instance = instance
4407

    
4408
  def Exec(self, feedback_fn):
4409
    """Recreate the disks.
4410

4411
    """
4412
    to_skip = []
4413
    for idx, _ in enumerate(self.instance.disks):
4414
      if idx not in self.op.disks: # disk idx has not been passed in
4415
        to_skip.append(idx)
4416
        continue
4417

    
4418
    _CreateDisks(self, self.instance, to_skip=to_skip)
4419

    
4420

    
4421
class LURenameInstance(LogicalUnit):
4422
  """Rename an instance.
4423

4424
  """
4425
  HPATH = "instance-rename"
4426
  HTYPE = constants.HTYPE_INSTANCE
4427
  _OP_REQP = ["instance_name", "new_name"]
4428

    
4429
  def BuildHooksEnv(self):
4430
    """Build hooks env.
4431

4432
    This runs on master, primary and secondary nodes of the instance.
4433

4434
    """
4435
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4436
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4437
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4438
    return env, nl, nl
4439

    
4440
  def CheckPrereq(self):
4441
    """Check prerequisites.
4442

4443
    This checks that the instance is in the cluster and is not running.
4444

4445
    """
4446
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4447
                                                self.op.instance_name)
4448
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4449
    assert instance is not None
4450
    _CheckNodeOnline(self, instance.primary_node)
4451
    _CheckInstanceDown(self, instance, "cannot rename")
4452
    self.instance = instance
4453

    
4454
    # new name verification
4455
    name_info = utils.GetHostInfo(self.op.new_name)
4456

    
4457
    self.op.new_name = new_name = name_info.name
4458
    instance_list = self.cfg.GetInstanceList()
4459
    if new_name in instance_list:
4460
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4461
                                 new_name, errors.ECODE_EXISTS)
4462

    
4463
    if not getattr(self.op, "ignore_ip", False):
4464
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4465
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4466
                                   (name_info.ip, new_name),
4467
                                   errors.ECODE_NOTUNIQUE)
4468

    
4469

    
4470
  def Exec(self, feedback_fn):
4471
    """Reinstall the instance.
4472

4473
    """
4474
    inst = self.instance
4475
    old_name = inst.name
4476

    
4477
    if inst.disk_template == constants.DT_FILE:
4478
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4479

    
4480
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4481
    # Change the instance lock. This is definitely safe while we hold the BGL
4482
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4483
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4484

    
4485
    # re-read the instance from the configuration after rename
4486
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4487

    
4488
    if inst.disk_template == constants.DT_FILE:
4489
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4490
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4491
                                                     old_file_storage_dir,
4492
                                                     new_file_storage_dir)
4493
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4494
                   " (but the instance has been renamed in Ganeti)" %
4495
                   (inst.primary_node, old_file_storage_dir,
4496
                    new_file_storage_dir))
4497

    
4498
    _StartInstanceDisks(self, inst, None)
4499
    try:
4500
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4501
                                                 old_name, self.op.debug_level)
4502
      msg = result.fail_msg
4503
      if msg:
4504
        msg = ("Could not run OS rename script for instance %s on node %s"
4505
               " (but the instance has been renamed in Ganeti): %s" %
4506
               (inst.name, inst.primary_node, msg))
4507
        self.proc.LogWarning(msg)
4508
    finally:
4509
      _ShutdownInstanceDisks(self, inst)
4510

    
4511

    
4512
class LURemoveInstance(LogicalUnit):
4513
  """Remove an instance.
4514

4515
  """
4516
  HPATH = "instance-remove"
4517
  HTYPE = constants.HTYPE_INSTANCE
4518
  _OP_REQP = ["instance_name", "ignore_failures"]
4519
  REQ_BGL = False
4520

    
4521
  def CheckArguments(self):
4522
    """Check the arguments.
4523

4524
    """
4525
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4526
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4527

    
4528
  def ExpandNames(self):
4529
    self._ExpandAndLockInstance()
4530
    self.needed_locks[locking.LEVEL_NODE] = []
4531
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4532

    
4533
  def DeclareLocks(self, level):
4534
    if level == locking.LEVEL_NODE:
4535
      self._LockInstancesNodes()
4536

    
4537
  def BuildHooksEnv(self):
4538
    """Build hooks env.
4539

4540
    This runs on master, primary and secondary nodes of the instance.
4541

4542
    """
4543
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4544
    env["SHUTDOWN_TIMEOUT"] = self.shutdown_timeout
4545
    nl = [self.cfg.GetMasterNode()]
4546
    nl_post = list(self.instance.all_nodes) + nl
4547
    return env, nl, nl_post
4548

    
4549
  def CheckPrereq(self):
4550
    """Check prerequisites.
4551

4552
    This checks that the instance is in the cluster.
4553

4554
    """
4555
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4556
    assert self.instance is not None, \
4557
      "Cannot retrieve locked instance %s" % self.op.instance_name
4558

    
4559
  def Exec(self, feedback_fn):
4560
    """Remove the instance.
4561

4562
    """
4563
    instance = self.instance
4564
    logging.info("Shutting down instance %s on node %s",
4565
                 instance.name, instance.primary_node)
4566

    
4567
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4568
                                             self.shutdown_timeout)
4569
    msg = result.fail_msg
4570
    if msg:
4571
      if self.op.ignore_failures:
4572
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4573
      else:
4574
        raise errors.OpExecError("Could not shutdown instance %s on"
4575
                                 " node %s: %s" %
4576
                                 (instance.name, instance.primary_node, msg))
4577

    
4578
    logging.info("Removing block devices for instance %s", instance.name)
4579

    
4580
    if not _RemoveDisks(self, instance):
4581
      if self.op.ignore_failures:
4582
        feedback_fn("Warning: can't remove instance's disks")
4583
      else:
4584
        raise errors.OpExecError("Can't remove instance's disks")
4585

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

    
4588
    self.cfg.RemoveInstance(instance.name)
4589
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4590

    
4591

    
4592
class LUQueryInstances(NoHooksLU):
4593
  """Logical unit for querying instances.
4594

4595
  """
4596
  # pylint: disable-msg=W0142
4597
  _OP_REQP = ["output_fields", "names", "use_locking"]
4598
  REQ_BGL = False
4599
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4600
                    "serial_no", "ctime", "mtime", "uuid"]
4601
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4602
                                    "admin_state",
4603
                                    "disk_template", "ip", "mac", "bridge",
4604
                                    "nic_mode", "nic_link",
4605
                                    "sda_size", "sdb_size", "vcpus", "tags",
4606
                                    "network_port", "beparams",
4607
                                    r"(disk)\.(size)/([0-9]+)",
4608
                                    r"(disk)\.(sizes)", "disk_usage",
4609
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4610
                                    r"(nic)\.(bridge)/([0-9]+)",
4611
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4612
                                    r"(disk|nic)\.(count)",
4613
                                    "hvparams",
4614
                                    ] + _SIMPLE_FIELDS +
4615
                                  ["hv/%s" % name
4616
                                   for name in constants.HVS_PARAMETERS
4617
                                   if name not in constants.HVC_GLOBALS] +
4618
                                  ["be/%s" % name
4619
                                   for name in constants.BES_PARAMETERS])
4620
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4621

    
4622

    
4623
  def ExpandNames(self):
4624
    _CheckOutputFields(static=self._FIELDS_STATIC,
4625
                       dynamic=self._FIELDS_DYNAMIC,
4626
                       selected=self.op.output_fields)
4627

    
4628
    self.needed_locks = {}
4629
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4630
    self.share_locks[locking.LEVEL_NODE] = 1
4631

    
4632
    if self.op.names:
4633
      self.wanted = _GetWantedInstances(self, self.op.names)
4634
    else:
4635
      self.wanted = locking.ALL_SET
4636

    
4637
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4638
    self.do_locking = self.do_node_query and self.op.use_locking
4639
    if self.do_locking:
4640
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4641
      self.needed_locks[locking.LEVEL_NODE] = []
4642
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4643

    
4644
  def DeclareLocks(self, level):
4645
    if level == locking.LEVEL_NODE and self.do_locking:
4646
      self._LockInstancesNodes()
4647

    
4648
  def CheckPrereq(self):
4649
    """Check prerequisites.
4650

4651
    """
4652
    pass
4653

    
4654
  def Exec(self, feedback_fn):
4655
    """Computes the list of nodes and their attributes.
4656

4657
    """
4658
    # pylint: disable-msg=R0912
4659
    # way too many branches here
4660
    all_info = self.cfg.GetAllInstancesInfo()
4661
    if self.wanted == locking.ALL_SET:
4662
      # caller didn't specify instance names, so ordering is not important
4663
      if self.do_locking:
4664
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4665
      else:
4666
        instance_names = all_info.keys()
4667
      instance_names = utils.NiceSort(instance_names)
4668
    else:
4669
      # caller did specify names, so we must keep the ordering
4670
      if self.do_locking:
4671
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4672
      else:
4673
        tgt_set = all_info.keys()
4674
      missing = set(self.wanted).difference(tgt_set)
4675
      if missing:
4676
        raise errors.OpExecError("Some instances were removed before"
4677
                                 " retrieving their data: %s" % missing)
4678
      instance_names = self.wanted
4679

    
4680
    instance_list = [all_info[iname] for iname in instance_names]
4681

    
4682
    # begin data gathering
4683

    
4684
    nodes = frozenset([inst.primary_node for inst in instance_list])
4685
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4686

    
4687
    bad_nodes = []
4688
    off_nodes = []
4689
    if self.do_node_query:
4690
      live_data = {}
4691
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4692
      for name in nodes:
4693
        result = node_data[name]
4694
        if result.offline:
4695
          # offline nodes will be in both lists
4696
          off_nodes.append(name)
4697
        if result.fail_msg:
4698
          bad_nodes.append(name)
4699
        else:
4700
          if result.payload:
4701
            live_data.update(result.payload)
4702
          # else no instance is alive
4703
    else:
4704
      live_data = dict([(name, {}) for name in instance_names])
4705

    
4706
    # end data gathering
4707

    
4708
    HVPREFIX = "hv/"
4709
    BEPREFIX = "be/"
4710
    output = []
4711
    cluster = self.cfg.GetClusterInfo()
4712
    for instance in instance_list:
4713
      iout = []
4714
      i_hv = cluster.FillHV(instance, skip_globals=True)
4715
      i_be = cluster.FillBE(instance)
4716
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
4717
                                 nic.nicparams) for nic in instance.nics]
4718
      for field in self.op.output_fields:
4719
        st_match = self._FIELDS_STATIC.Matches(field)
4720
        if field in self._SIMPLE_FIELDS:
4721
          val = getattr(instance, field)
4722
        elif field == "pnode":
4723
          val = instance.primary_node
4724
        elif field == "snodes":
4725
          val = list(instance.secondary_nodes)
4726
        elif field == "admin_state":
4727
          val = instance.admin_up
4728
        elif field == "oper_state":
4729
          if instance.primary_node in bad_nodes:
4730
            val = None
4731
          else:
4732
            val = bool(live_data.get(instance.name))
4733
        elif field == "status":
4734
          if instance.primary_node in off_nodes:
4735
            val = "ERROR_nodeoffline"
4736
          elif instance.primary_node in bad_nodes:
4737
            val = "ERROR_nodedown"
4738
          else:
4739
            running = bool(live_data.get(instance.name))
4740
            if running:
4741
              if instance.admin_up:
4742
                val = "running"
4743
              else:
4744
                val = "ERROR_up"
4745
            else:
4746
              if instance.admin_up:
4747
                val = "ERROR_down"
4748
              else:
4749
                val = "ADMIN_down"
4750
        elif field == "oper_ram":
4751
          if instance.primary_node in bad_nodes:
4752
            val = None
4753
          elif instance.name in live_data:
4754
            val = live_data[instance.name].get("memory", "?")
4755
          else:
4756
            val = "-"
4757
        elif field == "vcpus":
4758
          val = i_be[constants.BE_VCPUS]
4759
        elif field == "disk_template":
4760
          val = instance.disk_template
4761
        elif field == "ip":
4762
          if instance.nics:
4763
            val = instance.nics[0].ip
4764
          else:
4765
            val = None
4766
        elif field == "nic_mode":
4767
          if instance.nics:
4768
            val = i_nicp[0][constants.NIC_MODE]
4769
          else:
4770
            val = None
4771
        elif field == "nic_link":
4772
          if instance.nics:
4773
            val = i_nicp[0][constants.NIC_LINK]
4774
          else:
4775
            val = None
4776
        elif field == "bridge":
4777
          if (instance.nics and
4778
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4779
            val = i_nicp[0][constants.NIC_LINK]
4780
          else:
4781
            val = None
4782
        elif field == "mac":
4783
          if instance.nics:
4784
            val = instance.nics[0].mac
4785
          else:
4786
            val = None
4787
        elif field == "sda_size" or field == "sdb_size":
4788
          idx = ord(field[2]) - ord('a')
4789
          try:
4790
            val = instance.FindDisk(idx).size
4791
          except errors.OpPrereqError:
4792
            val = None
4793
        elif field == "disk_usage": # total disk usage per node
4794
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4795
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4796
        elif field == "tags":
4797
          val = list(instance.GetTags())
4798
        elif field == "hvparams":
4799
          val = i_hv
4800
        elif (field.startswith(HVPREFIX) and
4801
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
4802
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
4803
          val = i_hv.get(field[len(HVPREFIX):], None)
4804
        elif field == "beparams":
4805
          val = i_be
4806
        elif (field.startswith(BEPREFIX) and
4807
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4808
          val = i_be.get(field[len(BEPREFIX):], None)
4809
        elif st_match and st_match.groups():
4810
          # matches a variable list
4811
          st_groups = st_match.groups()
4812
          if st_groups and st_groups[0] == "disk":
4813
            if st_groups[1] == "count":
4814
              val = len(instance.disks)
4815
            elif st_groups[1] == "sizes":
4816
              val = [disk.size for disk in instance.disks]
4817
            elif st_groups[1] == "size":
4818
              try:
4819
                val = instance.FindDisk(st_groups[2]).size
4820
              except errors.OpPrereqError:
4821
                val = None
4822
            else:
4823
              assert False, "Unhandled disk parameter"
4824
          elif st_groups[0] == "nic":
4825
            if st_groups[1] == "count":
4826
              val = len(instance.nics)
4827
            elif st_groups[1] == "macs":
4828
              val = [nic.mac for nic in instance.nics]
4829
            elif st_groups[1] == "ips":
4830
              val = [nic.ip for nic in instance.nics]
4831
            elif st_groups[1] == "modes":
4832
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4833
            elif st_groups[1] == "links":
4834
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4835
            elif st_groups[1] == "bridges":
4836
              val = []
4837
              for nicp in i_nicp:
4838
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4839
                  val.append(nicp[constants.NIC_LINK])
4840
                else:
4841
                  val.append(None)
4842
            else:
4843
              # index-based item
4844
              nic_idx = int(st_groups[2])
4845
              if nic_idx >= len(instance.nics):
4846
                val = None
4847
              else:
4848
                if st_groups[1] == "mac":
4849
                  val = instance.nics[nic_idx].mac
4850
                elif st_groups[1] == "ip":
4851
                  val = instance.nics[nic_idx].ip
4852
                elif st_groups[1] == "mode":
4853
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4854
                elif st_groups[1] == "link":
4855
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4856
                elif st_groups[1] == "bridge":
4857
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4858
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4859
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4860
                  else:
4861
                    val = None
4862
                else:
4863
                  assert False, "Unhandled NIC parameter"
4864
          else:
4865
            assert False, ("Declared but unhandled variable parameter '%s'" %
4866
                           field)
4867
        else:
4868
          assert False, "Declared but unhandled parameter '%s'" % field
4869
        iout.append(val)
4870
      output.append(iout)
4871

    
4872
    return output
4873

    
4874

    
4875
class LUFailoverInstance(LogicalUnit):
4876
  """Failover an instance.
4877

4878
  """
4879
  HPATH = "instance-failover"
4880
  HTYPE = constants.HTYPE_INSTANCE
4881
  _OP_REQP = ["instance_name", "ignore_consistency"]
4882
  REQ_BGL = False
4883

    
4884
  def CheckArguments(self):
4885
    """Check the arguments.
4886

4887
    """
4888
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4889
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4890

    
4891
  def ExpandNames(self):
4892
    self._ExpandAndLockInstance()
4893
    self.needed_locks[locking.LEVEL_NODE] = []
4894
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4895

    
4896
  def DeclareLocks(self, level):
4897
    if level == locking.LEVEL_NODE:
4898
      self._LockInstancesNodes()
4899

    
4900
  def BuildHooksEnv(self):
4901
    """Build hooks env.
4902

4903
    This runs on master, primary and secondary nodes of the instance.
4904

4905
    """
4906
    instance = self.instance
4907
    source_node = instance.primary_node
4908
    target_node = instance.secondary_nodes[0]
4909
    env = {
4910
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4911
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4912
      "OLD_PRIMARY": source_node,
4913
      "OLD_SECONDARY": target_node,
4914
      "NEW_PRIMARY": target_node,
4915
      "NEW_SECONDARY": source_node,
4916
      }
4917
    env.update(_BuildInstanceHookEnvByObject(self, instance))
4918
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4919
    nl_post = list(nl)
4920
    nl_post.append(source_node)
4921
    return env, nl, nl_post
4922

    
4923
  def CheckPrereq(self):
4924
    """Check prerequisites.
4925

4926
    This checks that the instance is in the cluster.
4927

4928
    """
4929
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4930
    assert self.instance is not None, \
4931
      "Cannot retrieve locked instance %s" % self.op.instance_name
4932

    
4933
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4934
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4935
      raise errors.OpPrereqError("Instance's disk layout is not"
4936
                                 " network mirrored, cannot failover.",
4937
                                 errors.ECODE_STATE)
4938

    
4939
    secondary_nodes = instance.secondary_nodes
4940
    if not secondary_nodes:
4941
      raise errors.ProgrammerError("no secondary node but using "
4942
                                   "a mirrored disk template")
4943

    
4944
    target_node = secondary_nodes[0]
4945
    _CheckNodeOnline(self, target_node)
4946
    _CheckNodeNotDrained(self, target_node)
4947
    if instance.admin_up:
4948
      # check memory requirements on the secondary node
4949
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4950
                           instance.name, bep[constants.BE_MEMORY],
4951
                           instance.hypervisor)
4952
    else:
4953
      self.LogInfo("Not checking memory on the secondary node as"
4954
                   " instance will not be started")
4955

    
4956
    # check bridge existance
4957
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4958

    
4959
  def Exec(self, feedback_fn):
4960
    """Failover an instance.
4961

4962
    The failover is done by shutting it down on its present node and
4963
    starting it on the secondary.
4964

4965
    """
4966
    instance = self.instance
4967

    
4968
    source_node = instance.primary_node
4969
    target_node = instance.secondary_nodes[0]
4970

    
4971
    if instance.admin_up:
4972
      feedback_fn("* checking disk consistency between source and target")
4973
      for dev in instance.disks:
4974
        # for drbd, these are drbd over lvm
4975
        if not _CheckDiskConsistency(self, dev, target_node, False):
4976
          if not self.op.ignore_consistency:
4977
            raise errors.OpExecError("Disk %s is degraded on target node,"
4978
                                     " aborting failover." % dev.iv_name)
4979
    else:
4980
      feedback_fn("* not checking disk consistency as instance is not running")
4981

    
4982
    feedback_fn("* shutting down instance on source node")
4983
    logging.info("Shutting down instance %s on node %s",
4984
                 instance.name, source_node)
4985

    
4986
    result = self.rpc.call_instance_shutdown(source_node, instance,
4987
                                             self.shutdown_timeout)
4988
    msg = result.fail_msg
4989
    if msg:
4990
      if self.op.ignore_consistency:
4991
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4992
                             " Proceeding anyway. Please make sure node"
4993
                             " %s is down. Error details: %s",
4994
                             instance.name, source_node, source_node, msg)
4995
      else:
4996
        raise errors.OpExecError("Could not shutdown instance %s on"
4997
                                 " node %s: %s" %
4998
                                 (instance.name, source_node, msg))
4999

    
5000
    feedback_fn("* deactivating the instance's disks on source node")
5001
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5002
      raise errors.OpExecError("Can't shut down the instance's disks.")
5003

    
5004
    instance.primary_node = target_node
5005
    # distribute new instance config to the other nodes
5006
    self.cfg.Update(instance, feedback_fn)
5007

    
5008
    # Only start the instance if it's marked as up
5009
    if instance.admin_up:
5010
      feedback_fn("* activating the instance's disks on target node")
5011
      logging.info("Starting instance %s on node %s",
5012
                   instance.name, target_node)
5013

    
5014
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5015
                                               ignore_secondaries=True)
5016
      if not disks_ok:
5017
        _ShutdownInstanceDisks(self, instance)
5018
        raise errors.OpExecError("Can't activate the instance's disks")
5019

    
5020
      feedback_fn("* starting the instance on the target node")
5021
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5022
      msg = result.fail_msg
5023
      if msg:
5024
        _ShutdownInstanceDisks(self, instance)
5025
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5026
                                 (instance.name, target_node, msg))
5027

    
5028

    
5029
class LUMigrateInstance(LogicalUnit):
5030
  """Migrate an instance.
5031

5032
  This is migration without shutting down, compared to the failover,
5033
  which is done with shutdown.
5034

5035
  """
5036
  HPATH = "instance-migrate"
5037
  HTYPE = constants.HTYPE_INSTANCE
5038
  _OP_REQP = ["instance_name", "live", "cleanup"]
5039

    
5040
  REQ_BGL = False
5041

    
5042
  def ExpandNames(self):
5043
    self._ExpandAndLockInstance()
5044

    
5045
    self.needed_locks[locking.LEVEL_NODE] = []
5046
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5047

    
5048
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5049
                                       self.op.live, self.op.cleanup)
5050
    self.tasklets = [self._migrater]
5051

    
5052
  def DeclareLocks(self, level):
5053
    if level == locking.LEVEL_NODE:
5054
      self._LockInstancesNodes()
5055

    
5056
  def BuildHooksEnv(self):
5057
    """Build hooks env.
5058

5059
    This runs on master, primary and secondary nodes of the instance.
5060

5061
    """
5062
    instance = self._migrater.instance
5063
    source_node = instance.primary_node
5064
    target_node = instance.secondary_nodes[0]
5065
    env = _BuildInstanceHookEnvByObject(self, instance)
5066
    env["MIGRATE_LIVE"] = self.op.live
5067
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5068
    env.update({
5069
        "OLD_PRIMARY": source_node,
5070
        "OLD_SECONDARY": target_node,
5071
        "NEW_PRIMARY": target_node,
5072
        "NEW_SECONDARY": source_node,
5073
        })
5074
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5075
    nl_post = list(nl)
5076
    nl_post.append(source_node)
5077
    return env, nl, nl_post
5078

    
5079

    
5080
class LUMoveInstance(LogicalUnit):
5081
  """Move an instance by data-copying.
5082

5083
  """
5084
  HPATH = "instance-move"
5085
  HTYPE = constants.HTYPE_INSTANCE
5086
  _OP_REQP = ["instance_name", "target_node"]
5087
  REQ_BGL = False
5088

    
5089
  def CheckArguments(self):
5090
    """Check the arguments.
5091

5092
    """
5093
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
5094
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
5095

    
5096
  def ExpandNames(self):
5097
    self._ExpandAndLockInstance()
5098
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5099
    self.op.target_node = target_node
5100
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5101
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5102

    
5103
  def DeclareLocks(self, level):
5104
    if level == locking.LEVEL_NODE:
5105
      self._LockInstancesNodes(primary_only=True)
5106

    
5107
  def BuildHooksEnv(self):
5108
    """Build hooks env.
5109

5110
    This runs on master, primary and secondary nodes of the instance.
5111

5112
    """
5113
    env = {
5114
      "TARGET_NODE": self.op.target_node,
5115
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
5116
      }
5117
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5118
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5119
                                       self.op.target_node]
5120
    return env, nl, nl
5121

    
5122
  def CheckPrereq(self):
5123
    """Check prerequisites.
5124

5125
    This checks that the instance is in the cluster.
5126

5127
    """
5128
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5129
    assert self.instance is not None, \
5130
      "Cannot retrieve locked instance %s" % self.op.instance_name
5131

    
5132
    node = self.cfg.GetNodeInfo(self.op.target_node)
5133
    assert node is not None, \
5134
      "Cannot retrieve locked node %s" % self.op.target_node
5135

    
5136
    self.target_node = target_node = node.name
5137

    
5138
    if target_node == instance.primary_node:
5139
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5140
                                 (instance.name, target_node),
5141
                                 errors.ECODE_STATE)
5142

    
5143
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5144

    
5145
    for idx, dsk in enumerate(instance.disks):
5146
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5147
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5148
                                   " cannot copy" % idx, errors.ECODE_STATE)
5149

    
5150
    _CheckNodeOnline(self, target_node)
5151
    _CheckNodeNotDrained(self, target_node)
5152

    
5153
    if instance.admin_up:
5154
      # check memory requirements on the secondary node
5155
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5156
                           instance.name, bep[constants.BE_MEMORY],
5157
                           instance.hypervisor)
5158
    else:
5159
      self.LogInfo("Not checking memory on the secondary node as"
5160
                   " instance will not be started")
5161

    
5162
    # check bridge existance
5163
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5164

    
5165
  def Exec(self, feedback_fn):
5166
    """Move an instance.
5167

5168
    The move is done by shutting it down on its present node, copying
5169
    the data over (slow) and starting it on the new node.
5170

5171
    """
5172
    instance = self.instance
5173

    
5174
    source_node = instance.primary_node
5175
    target_node = self.target_node
5176

    
5177
    self.LogInfo("Shutting down instance %s on source node %s",
5178
                 instance.name, source_node)
5179

    
5180
    result = self.rpc.call_instance_shutdown(source_node, instance,
5181
                                             self.shutdown_timeout)
5182
    msg = result.fail_msg
5183
    if msg:
5184
      if self.op.ignore_consistency:
5185
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5186
                             " Proceeding anyway. Please make sure node"
5187
                             " %s is down. Error details: %s",
5188
                             instance.name, source_node, source_node, msg)
5189
      else:
5190
        raise errors.OpExecError("Could not shutdown instance %s on"
5191
                                 " node %s: %s" %
5192
                                 (instance.name, source_node, msg))
5193

    
5194
    # create the target disks
5195
    try:
5196
      _CreateDisks(self, instance, target_node=target_node)
5197
    except errors.OpExecError:
5198
      self.LogWarning("Device creation failed, reverting...")
5199
      try:
5200
        _RemoveDisks(self, instance, target_node=target_node)
5201
      finally:
5202
        self.cfg.ReleaseDRBDMinors(instance.name)
5203
        raise
5204

    
5205
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5206

    
5207
    errs = []
5208
    # activate, get path, copy the data over
5209
    for idx, disk in enumerate(instance.disks):
5210
      self.LogInfo("Copying data for disk %d", idx)
5211
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5212
                                               instance.name, True)
5213
      if result.fail_msg:
5214
        self.LogWarning("Can't assemble newly created disk %d: %s",
5215
                        idx, result.fail_msg)
5216
        errs.append(result.fail_msg)
5217
        break
5218
      dev_path = result.payload
5219
      result = self.rpc.call_blockdev_export(source_node, disk,
5220
                                             target_node, dev_path,
5221
                                             cluster_name)
5222
      if result.fail_msg:
5223
        self.LogWarning("Can't copy data over for disk %d: %s",
5224
                        idx, result.fail_msg)
5225
        errs.append(result.fail_msg)
5226
        break
5227

    
5228
    if errs:
5229
      self.LogWarning("Some disks failed to copy, aborting")
5230
      try:
5231
        _RemoveDisks(self, instance, target_node=target_node)
5232
      finally:
5233
        self.cfg.ReleaseDRBDMinors(instance.name)
5234
        raise errors.OpExecError("Errors during disk copy: %s" %
5235
                                 (",".join(errs),))
5236

    
5237
    instance.primary_node = target_node
5238
    self.cfg.Update(instance, feedback_fn)
5239

    
5240
    self.LogInfo("Removing the disks on the original node")
5241
    _RemoveDisks(self, instance, target_node=source_node)
5242

    
5243
    # Only start the instance if it's marked as up
5244
    if instance.admin_up:
5245
      self.LogInfo("Starting instance %s on node %s",
5246
                   instance.name, target_node)
5247

    
5248
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5249
                                           ignore_secondaries=True)
5250
      if not disks_ok:
5251
        _ShutdownInstanceDisks(self, instance)
5252
        raise errors.OpExecError("Can't activate the instance's disks")
5253

    
5254
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5255
      msg = result.fail_msg
5256
      if msg:
5257
        _ShutdownInstanceDisks(self, instance)
5258
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5259
                                 (instance.name, target_node, msg))
5260

    
5261

    
5262
class LUMigrateNode(LogicalUnit):
5263
  """Migrate all instances from a node.
5264

5265
  """
5266
  HPATH = "node-migrate"
5267
  HTYPE = constants.HTYPE_NODE
5268
  _OP_REQP = ["node_name", "live"]
5269
  REQ_BGL = False
5270

    
5271
  def ExpandNames(self):
5272
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5273

    
5274
    self.needed_locks = {
5275
      locking.LEVEL_NODE: [self.op.node_name],
5276
      }
5277

    
5278
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5279

    
5280
    # Create tasklets for migrating instances for all instances on this node
5281
    names = []
5282
    tasklets = []
5283

    
5284
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5285
      logging.debug("Migrating instance %s", inst.name)
5286
      names.append(inst.name)
5287

    
5288
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
5289

    
5290
    self.tasklets = tasklets
5291

    
5292
    # Declare instance locks
5293
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5294

    
5295
  def DeclareLocks(self, level):
5296
    if level == locking.LEVEL_NODE:
5297
      self._LockInstancesNodes()
5298

    
5299
  def BuildHooksEnv(self):
5300
    """Build hooks env.
5301

5302
    This runs on the master, the primary and all the secondaries.
5303

5304
    """
5305
    env = {
5306
      "NODE_NAME": self.op.node_name,
5307
      }
5308

    
5309
    nl = [self.cfg.GetMasterNode()]
5310

    
5311
    return (env, nl, nl)
5312

    
5313

    
5314
class TLMigrateInstance(Tasklet):
5315
  def __init__(self, lu, instance_name, live, cleanup):
5316
    """Initializes this class.
5317

5318
    """
5319
    Tasklet.__init__(self, lu)
5320

    
5321
    # Parameters
5322
    self.instance_name = instance_name
5323
    self.live = live
5324
    self.cleanup = cleanup
5325

    
5326
  def CheckPrereq(self):
5327
    """Check prerequisites.
5328

5329
    This checks that the instance is in the cluster.
5330

5331
    """
5332
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5333
    instance = self.cfg.GetInstanceInfo(instance_name)
5334
    assert instance is not None
5335

    
5336
    if instance.disk_template != constants.DT_DRBD8:
5337
      raise errors.OpPrereqError("Instance's disk layout is not"
5338
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5339

    
5340
    secondary_nodes = instance.secondary_nodes
5341
    if not secondary_nodes:
5342
      raise errors.ConfigurationError("No secondary node but using"
5343
                                      " drbd8 disk template")
5344

    
5345
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5346

    
5347
    target_node = secondary_nodes[0]
5348
    # check memory requirements on the secondary node
5349
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
5350
                         instance.name, i_be[constants.BE_MEMORY],
5351
                         instance.hypervisor)
5352

    
5353
    # check bridge existance
5354
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5355

    
5356
    if not self.cleanup:
5357
      _CheckNodeNotDrained(self, target_node)
5358
      result = self.rpc.call_instance_migratable(instance.primary_node,
5359
                                                 instance)
5360
      result.Raise("Can't migrate, please use failover",
5361
                   prereq=True, ecode=errors.ECODE_STATE)
5362

    
5363
    self.instance = instance
5364

    
5365
  def _WaitUntilSync(self):
5366
    """Poll with custom rpc for disk sync.
5367

5368
    This uses our own step-based rpc call.
5369

5370
    """
5371
    self.feedback_fn("* wait until resync is done")
5372
    all_done = False
5373
    while not all_done:
5374
      all_done = True
5375
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5376
                                            self.nodes_ip,
5377
                                            self.instance.disks)
5378
      min_percent = 100
5379
      for node, nres in result.items():
5380
        nres.Raise("Cannot resync disks on node %s" % node)
5381
        node_done, node_percent = nres.payload
5382
        all_done = all_done and node_done
5383
        if node_percent is not None:
5384
          min_percent = min(min_percent, node_percent)
5385
      if not all_done:
5386
        if min_percent < 100:
5387
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5388
        time.sleep(2)
5389

    
5390
  def _EnsureSecondary(self, node):
5391
    """Demote a node to secondary.
5392

5393
    """
5394
    self.feedback_fn("* switching node %s to secondary mode" % node)
5395

    
5396
    for dev in self.instance.disks:
5397
      self.cfg.SetDiskID(dev, node)
5398

    
5399
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5400
                                          self.instance.disks)
5401
    result.Raise("Cannot change disk to secondary on node %s" % node)
5402

    
5403
  def _GoStandalone(self):
5404
    """Disconnect from the network.
5405

5406
    """
5407
    self.feedback_fn("* changing into standalone mode")
5408
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5409
                                               self.instance.disks)
5410
    for node, nres in result.items():
5411
      nres.Raise("Cannot disconnect disks node %s" % node)
5412

    
5413
  def _GoReconnect(self, multimaster):
5414
    """Reconnect to the network.
5415

5416
    """
5417
    if multimaster:
5418
      msg = "dual-master"
5419
    else:
5420
      msg = "single-master"
5421
    self.feedback_fn("* changing disks into %s mode" % msg)
5422
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5423
                                           self.instance.disks,
5424
                                           self.instance.name, multimaster)
5425
    for node, nres in result.items():
5426
      nres.Raise("Cannot change disks config on node %s" % node)
5427

    
5428
  def _ExecCleanup(self):
5429
    """Try to cleanup after a failed migration.
5430

5431
    The cleanup is done by:
5432
      - check that the instance is running only on one node
5433
        (and update the config if needed)
5434
      - change disks on its secondary node to secondary
5435
      - wait until disks are fully synchronized
5436
      - disconnect from the network
5437
      - change disks into single-master mode
5438
      - wait again until disks are fully synchronized
5439

5440
    """
5441
    instance = self.instance
5442
    target_node = self.target_node
5443
    source_node = self.source_node
5444

    
5445
    # check running on only one node
5446
    self.feedback_fn("* checking where the instance actually runs"
5447
                     " (if this hangs, the hypervisor might be in"
5448
                     " a bad state)")
5449
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5450
    for node, result in ins_l.items():
5451
      result.Raise("Can't contact node %s" % node)
5452

    
5453
    runningon_source = instance.name in ins_l[source_node].payload
5454
    runningon_target = instance.name in ins_l[target_node].payload
5455

    
5456
    if runningon_source and runningon_target:
5457
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5458
                               " or the hypervisor is confused. You will have"
5459
                               " to ensure manually that it runs only on one"
5460
                               " and restart this operation.")
5461

    
5462
    if not (runningon_source or runningon_target):
5463
      raise errors.OpExecError("Instance does not seem to be running at all."
5464
                               " In this case, it's safer to repair by"
5465
                               " running 'gnt-instance stop' to ensure disk"
5466
                               " shutdown, and then restarting it.")
5467

    
5468
    if runningon_target:
5469
      # the migration has actually succeeded, we need to update the config
5470
      self.feedback_fn("* instance running on secondary node (%s),"
5471
                       " updating config" % target_node)
5472
      instance.primary_node = target_node
5473
      self.cfg.Update(instance, self.feedback_fn)
5474
      demoted_node = source_node
5475
    else:
5476
      self.feedback_fn("* instance confirmed to be running on its"
5477
                       " primary node (%s)" % source_node)
5478
      demoted_node = target_node
5479

    
5480
    self._EnsureSecondary(demoted_node)
5481
    try:
5482
      self._WaitUntilSync()
5483
    except errors.OpExecError:
5484
      # we ignore here errors, since if the device is standalone, it
5485
      # won't be able to sync
5486
      pass
5487
    self._GoStandalone()
5488
    self._GoReconnect(False)
5489
    self._WaitUntilSync()
5490

    
5491
    self.feedback_fn("* done")
5492

    
5493
  def _RevertDiskStatus(self):
5494
    """Try to revert the disk status after a failed migration.
5495

5496
    """
5497
    target_node = self.target_node
5498
    try:
5499
      self._EnsureSecondary(target_node)
5500
      self._GoStandalone()
5501
      self._GoReconnect(False)
5502
      self._WaitUntilSync()
5503
    except errors.OpExecError, err:
5504
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5505
                         " drives: error '%s'\n"
5506
                         "Please look and recover the instance status" %
5507
                         str(err))
5508

    
5509
  def _AbortMigration(self):
5510
    """Call the hypervisor code to abort a started migration.
5511

5512
    """
5513
    instance = self.instance
5514
    target_node = self.target_node
5515
    migration_info = self.migration_info
5516

    
5517
    abort_result = self.rpc.call_finalize_migration(target_node,
5518
                                                    instance,
5519
                                                    migration_info,
5520
                                                    False)
5521
    abort_msg = abort_result.fail_msg
5522
    if abort_msg:
5523
      logging.error("Aborting migration failed on target node %s: %s",
5524
                    target_node, abort_msg)
5525
      # Don't raise an exception here, as we stil have to try to revert the
5526
      # disk status, even if this step failed.
5527

    
5528
  def _ExecMigration(self):
5529
    """Migrate an instance.
5530

5531
    The migrate is done by:
5532
      - change the disks into dual-master mode
5533
      - wait until disks are fully synchronized again
5534
      - migrate the instance
5535
      - change disks on the new secondary node (the old primary) to secondary
5536
      - wait until disks are fully synchronized
5537
      - change disks into single-master mode
5538

5539
    """
5540
    instance = self.instance
5541
    target_node = self.target_node
5542
    source_node = self.source_node
5543

    
5544
    self.feedback_fn("* checking disk consistency between source and target")
5545
    for dev in instance.disks:
5546
      if not _CheckDiskConsistency(self, dev, target_node, False):
5547
        raise errors.OpExecError("Disk %s is degraded or not fully"
5548
                                 " synchronized on target node,"
5549
                                 " aborting migrate." % dev.iv_name)
5550

    
5551
    # First get the migration information from the remote node
5552
    result = self.rpc.call_migration_info(source_node, instance)
5553
    msg = result.fail_msg
5554
    if msg:
5555
      log_err = ("Failed fetching source migration information from %s: %s" %
5556
                 (source_node, msg))
5557
      logging.error(log_err)
5558
      raise errors.OpExecError(log_err)
5559

    
5560
    self.migration_info = migration_info = result.payload
5561

    
5562
    # Then switch the disks to master/master mode
5563
    self._EnsureSecondary(target_node)
5564
    self._GoStandalone()
5565
    self._GoReconnect(True)
5566
    self._WaitUntilSync()
5567

    
5568
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5569
    result = self.rpc.call_accept_instance(target_node,
5570
                                           instance,
5571
                                           migration_info,
5572
                                           self.nodes_ip[target_node])
5573

    
5574
    msg = result.fail_msg
5575
    if msg:
5576
      logging.error("Instance pre-migration failed, trying to revert"
5577
                    " disk status: %s", msg)
5578
      self.feedback_fn("Pre-migration failed, aborting")
5579
      self._AbortMigration()
5580
      self._RevertDiskStatus()
5581
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5582
                               (instance.name, msg))
5583

    
5584
    self.feedback_fn("* migrating instance to %s" % target_node)
5585
    time.sleep(10)
5586
    result = self.rpc.call_instance_migrate(source_node, instance,
5587
                                            self.nodes_ip[target_node],
5588
                                            self.live)
5589
    msg = result.fail_msg
5590
    if msg:
5591
      logging.error("Instance migration failed, trying to revert"
5592
                    " disk status: %s", msg)
5593
      self.feedback_fn("Migration failed, aborting")
5594
      self._AbortMigration()
5595
      self._RevertDiskStatus()
5596
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5597
                               (instance.name, msg))
5598
    time.sleep(10)
5599

    
5600
    instance.primary_node = target_node
5601
    # distribute new instance config to the other nodes
5602
    self.cfg.Update(instance, self.feedback_fn)
5603

    
5604
    result = self.rpc.call_finalize_migration(target_node,
5605
                                              instance,
5606
                                              migration_info,
5607
                                              True)
5608
    msg = result.fail_msg
5609
    if msg:
5610
      logging.error("Instance migration succeeded, but finalization failed:"
5611
                    " %s", msg)
5612
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5613
                               msg)
5614

    
5615
    self._EnsureSecondary(source_node)
5616
    self._WaitUntilSync()
5617
    self._GoStandalone()
5618
    self._GoReconnect(False)
5619
    self._WaitUntilSync()
5620

    
5621
    self.feedback_fn("* done")
5622

    
5623
  def Exec(self, feedback_fn):
5624
    """Perform the migration.
5625

5626
    """
5627
    feedback_fn("Migrating instance %s" % self.instance.name)
5628

    
5629
    self.feedback_fn = feedback_fn
5630

    
5631
    self.source_node = self.instance.primary_node
5632
    self.target_node = self.instance.secondary_nodes[0]
5633
    self.all_nodes = [self.source_node, self.target_node]
5634
    self.nodes_ip = {
5635
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5636
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5637
      }
5638

    
5639
    if self.cleanup:
5640
      return self._ExecCleanup()
5641
    else:
5642
      return self._ExecMigration()
5643

    
5644

    
5645
def _CreateBlockDev(lu, node, instance, device, force_create,
5646
                    info, force_open):
5647
  """Create a tree of block devices on a given node.
5648

5649
  If this device type has to be created on secondaries, create it and
5650
  all its children.
5651

5652
  If not, just recurse to children keeping the same 'force' value.
5653

5654
  @param lu: the lu on whose behalf we execute
5655
  @param node: the node on which to create the device
5656
  @type instance: L{objects.Instance}
5657
  @param instance: the instance which owns the device
5658
  @type device: L{objects.Disk}
5659
  @param device: the device to create
5660
  @type force_create: boolean
5661
  @param force_create: whether to force creation of this device; this
5662
      will be change to True whenever we find a device which has
5663
      CreateOnSecondary() attribute
5664
  @param info: the extra 'metadata' we should attach to the device
5665
      (this will be represented as a LVM tag)
5666
  @type force_open: boolean
5667
  @param force_open: this parameter will be passes to the
5668
      L{backend.BlockdevCreate} function where it specifies
5669
      whether we run on primary or not, and it affects both
5670
      the child assembly and the device own Open() execution
5671

5672
  """
5673
  if device.CreateOnSecondary():
5674
    force_create = True
5675

    
5676
  if device.children:
5677
    for child in device.children:
5678
      _CreateBlockDev(lu, node, instance, child, force_create,
5679
                      info, force_open)
5680

    
5681
  if not force_create:
5682
    return
5683

    
5684
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5685

    
5686

    
5687
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5688
  """Create a single block device on a given node.
5689

5690
  This will not recurse over children of the device, so they must be
5691
  created in advance.
5692

5693
  @param lu: the lu on whose behalf we execute
5694
  @param node: the node on which to create the device
5695
  @type instance: L{objects.Instance}
5696
  @param instance: the instance which owns the device
5697
  @type device: L{objects.Disk}
5698
  @param device: the device to create
5699
  @param info: the extra 'metadata' we should attach to the device
5700
      (this will be represented as a LVM tag)
5701
  @type force_open: boolean
5702
  @param force_open: this parameter will be passes to the
5703
      L{backend.BlockdevCreate} function where it specifies
5704
      whether we run on primary or not, and it affects both
5705
      the child assembly and the device own Open() execution
5706

5707
  """
5708
  lu.cfg.SetDiskID(device, node)
5709
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5710
                                       instance.name, force_open, info)
5711
  result.Raise("Can't create block device %s on"
5712
               " node %s for instance %s" % (device, node, instance.name))
5713
  if device.physical_id is None:
5714
    device.physical_id = result.payload
5715

    
5716

    
5717
def _GenerateUniqueNames(lu, exts):
5718
  """Generate a suitable LV name.
5719

5720
  This will generate a logical volume name for the given instance.
5721

5722
  """
5723
  results = []
5724
  for val in exts:
5725
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
5726
    results.append("%s%s" % (new_id, val))
5727
  return results
5728

    
5729

    
5730
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5731
                         p_minor, s_minor):
5732
  """Generate a drbd8 device complete with its children.
5733

5734
  """
5735
  port = lu.cfg.AllocatePort()
5736
  vgname = lu.cfg.GetVGName()
5737
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
5738
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5739
                          logical_id=(vgname, names[0]))
5740
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5741
                          logical_id=(vgname, names[1]))
5742
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5743
                          logical_id=(primary, secondary, port,
5744
                                      p_minor, s_minor,
5745
                                      shared_secret),
5746
                          children=[dev_data, dev_meta],
5747
                          iv_name=iv_name)
5748
  return drbd_dev
5749

    
5750

    
5751
def _GenerateDiskTemplate(lu, template_name,
5752
                          instance_name, primary_node,
5753
                          secondary_nodes, disk_info,
5754
                          file_storage_dir, file_driver,
5755
                          base_index):
5756
  """Generate the entire disk layout for a given template type.
5757

5758
  """
5759
  #TODO: compute space requirements
5760

    
5761
  vgname = lu.cfg.GetVGName()
5762
  disk_count = len(disk_info)
5763
  disks = []
5764
  if template_name == constants.DT_DISKLESS:
5765
    pass
5766
  elif template_name == constants.DT_PLAIN:
5767
    if len(secondary_nodes) != 0:
5768
      raise errors.ProgrammerError("Wrong template configuration")
5769

    
5770
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5771
                                      for i in range(disk_count)])
5772
    for idx, disk in enumerate(disk_info):
5773
      disk_index = idx + base_index
5774
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5775
                              logical_id=(vgname, names[idx]),
5776
                              iv_name="disk/%d" % disk_index,
5777
                              mode=disk["mode"])
5778
      disks.append(disk_dev)
5779
  elif template_name == constants.DT_DRBD8:
5780
    if len(secondary_nodes) != 1:
5781
      raise errors.ProgrammerError("Wrong template configuration")
5782
    remote_node = secondary_nodes[0]
5783
    minors = lu.cfg.AllocateDRBDMinor(
5784
      [primary_node, remote_node] * len(disk_info), instance_name)
5785

    
5786
    names = []
5787
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5788
                                               for i in range(disk_count)]):
5789
      names.append(lv_prefix + "_data")
5790
      names.append(lv_prefix + "_meta")
5791
    for idx, disk in enumerate(disk_info):
5792
      disk_index = idx + base_index
5793
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5794
                                      disk["size"], names[idx*2:idx*2+2],
5795
                                      "disk/%d" % disk_index,
5796
                                      minors[idx*2], minors[idx*2+1])
5797
      disk_dev.mode = disk["mode"]
5798
      disks.append(disk_dev)
5799
  elif template_name == constants.DT_FILE:
5800
    if len(secondary_nodes) != 0:
5801
      raise errors.ProgrammerError("Wrong template configuration")
5802

    
5803
    for idx, disk in enumerate(disk_info):
5804
      disk_index = idx + base_index
5805
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5806
                              iv_name="disk/%d" % disk_index,
5807
                              logical_id=(file_driver,
5808
                                          "%s/disk%d" % (file_storage_dir,
5809
                                                         disk_index)),
5810
                              mode=disk["mode"])
5811
      disks.append(disk_dev)
5812
  else:
5813
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5814
  return disks
5815

    
5816

    
5817
def _GetInstanceInfoText(instance):
5818
  """Compute that text that should be added to the disk's metadata.
5819

5820
  """
5821
  return "originstname+%s" % instance.name
5822

    
5823

    
5824
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5825
  """Create all disks for an instance.
5826

5827
  This abstracts away some work from AddInstance.
5828

5829
  @type lu: L{LogicalUnit}
5830
  @param lu: the logical unit on whose behalf we execute
5831
  @type instance: L{objects.Instance}
5832
  @param instance: the instance whose disks we should create
5833
  @type to_skip: list
5834
  @param to_skip: list of indices to skip
5835
  @type target_node: string
5836
  @param target_node: if passed, overrides the target node for creation
5837
  @rtype: boolean
5838
  @return: the success of the creation
5839

5840
  """
5841
  info = _GetInstanceInfoText(instance)
5842
  if target_node is None:
5843
    pnode = instance.primary_node
5844
    all_nodes = instance.all_nodes
5845
  else:
5846
    pnode = target_node
5847
    all_nodes = [pnode]
5848

    
5849
  if instance.disk_template == constants.DT_FILE:
5850
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5851
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5852

    
5853
    result.Raise("Failed to create directory '%s' on"
5854
                 " node %s" % (file_storage_dir, pnode))
5855

    
5856
  # Note: this needs to be kept in sync with adding of disks in
5857
  # LUSetInstanceParams
5858
  for idx, device in enumerate(instance.disks):
5859
    if to_skip and idx in to_skip:
5860
      continue
5861
    logging.info("Creating volume %s for instance %s",
5862
                 device.iv_name, instance.name)
5863
    #HARDCODE
5864
    for node in all_nodes:
5865
      f_create = node == pnode
5866
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5867

    
5868

    
5869
def _RemoveDisks(lu, instance, target_node=None):
5870
  """Remove all disks for an instance.
5871

5872
  This abstracts away some work from `AddInstance()` and
5873
  `RemoveInstance()`. Note that in case some of the devices couldn't
5874
  be removed, the removal will continue with the other ones (compare
5875
  with `_CreateDisks()`).
5876

5877
  @type lu: L{LogicalUnit}
5878
  @param lu: the logical unit on whose behalf we execute
5879
  @type instance: L{objects.Instance}
5880
  @param instance: the instance whose disks we should remove
5881
  @type target_node: string
5882
  @param target_node: used to override the node on which to remove the disks
5883
  @rtype: boolean
5884
  @return: the success of the removal
5885

5886
  """
5887
  logging.info("Removing block devices for instance %s", instance.name)
5888

    
5889
  all_result = True
5890
  for device in instance.disks:
5891
    if target_node:
5892
      edata = [(target_node, device)]
5893
    else:
5894
      edata = device.ComputeNodeTree(instance.primary_node)
5895
    for node, disk in edata:
5896
      lu.cfg.SetDiskID(disk, node)
5897
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5898
      if msg:
5899
        lu.LogWarning("Could not remove block device %s on node %s,"
5900
                      " continuing anyway: %s", device.iv_name, node, msg)
5901
        all_result = False
5902

    
5903
  if instance.disk_template == constants.DT_FILE:
5904
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5905
    if target_node:
5906
      tgt = target_node
5907
    else:
5908
      tgt = instance.primary_node
5909
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5910
    if result.fail_msg:
5911
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5912
                    file_storage_dir, instance.primary_node, result.fail_msg)
5913
      all_result = False
5914

    
5915
  return all_result
5916

    
5917

    
5918
def _ComputeDiskSize(disk_template, disks):
5919
  """Compute disk size requirements in the volume group
5920

5921
  """
5922
  # Required free disk space as a function of disk and swap space
5923
  req_size_dict = {
5924
    constants.DT_DISKLESS: None,
5925
    constants.DT_PLAIN: sum(d["size"] for d in disks),
5926
    # 128 MB are added for drbd metadata for each disk
5927
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
5928
    constants.DT_FILE: None,
5929
  }
5930

    
5931
  if disk_template not in req_size_dict:
5932
    raise errors.ProgrammerError("Disk template '%s' size requirement"
5933
                                 " is unknown" %  disk_template)
5934

    
5935
  return req_size_dict[disk_template]
5936

    
5937

    
5938
def _CheckHVParams(lu, nodenames, hvname, hvparams):
5939
  """Hypervisor parameter validation.
5940

5941
  This function abstract the hypervisor parameter validation to be
5942
  used in both instance create and instance modify.
5943

5944
  @type lu: L{LogicalUnit}
5945
  @param lu: the logical unit for which we check
5946
  @type nodenames: list
5947
  @param nodenames: the list of nodes on which we should check
5948
  @type hvname: string
5949
  @param hvname: the name of the hypervisor we should use
5950
  @type hvparams: dict
5951
  @param hvparams: the parameters which we need to check
5952
  @raise errors.OpPrereqError: if the parameters are not valid
5953

5954
  """
5955
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
5956
                                                  hvname,
5957
                                                  hvparams)
5958
  for node in nodenames:
5959
    info = hvinfo[node]
5960
    if info.offline:
5961
      continue
5962
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
5963

    
5964

    
5965
class LUCreateInstance(LogicalUnit):
5966
  """Create an instance.
5967

5968
  """
5969
  HPATH = "instance-add"
5970
  HTYPE = constants.HTYPE_INSTANCE
5971
  _OP_REQP = ["instance_name", "disks", "disk_template",
5972
              "mode", "start",
5973
              "wait_for_sync", "ip_check", "nics",
5974
              "hvparams", "beparams"]
5975
  REQ_BGL = False
5976

    
5977
  def CheckArguments(self):
5978
    """Check arguments.
5979

5980
    """
5981
    # set optional parameters to none if they don't exist
5982
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
5983
      if not hasattr(self.op, attr):
5984
        setattr(self.op, attr, None)
5985

    
5986
    # do not require name_check to ease forward/backward compatibility
5987
    # for tools
5988
    if not hasattr(self.op, "name_check"):
5989
      self.op.name_check = True
5990
    if not hasattr(self.op, "no_install"):
5991
      self.op.no_install = False
5992
    if self.op.no_install and self.op.start:
5993
      self.LogInfo("No-installation mode selected, disabling startup")
5994
      self.op.start = False
5995
    # validate/normalize the instance name
5996
    self.op.instance_name = utils.HostInfo.NormalizeName(self.op.instance_name)
5997
    if self.op.ip_check and not self.op.name_check:
5998
      # TODO: make the ip check more flexible and not depend on the name check
5999
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
6000
                                 errors.ECODE_INVAL)
6001
    if (self.op.disk_template == constants.DT_FILE and
6002
        not constants.ENABLE_FILE_STORAGE):
6003
      raise errors.OpPrereqError("File storage disabled at configure time",
6004
                                 errors.ECODE_INVAL)
6005
    # check disk information: either all adopt, or no adopt
6006
    has_adopt = has_no_adopt = False
6007
    for disk in self.op.disks:
6008
      if "adopt" in disk:
6009
        has_adopt = True
6010
      else:
6011
        has_no_adopt = True
6012
    if has_adopt and has_no_adopt:
6013
      raise errors.OpPrereqError("Either all disks have are adoped or none is",
6014
                                 errors.ECODE_INVAL)
6015
    if has_adopt:
6016
      if self.op.disk_template != constants.DT_PLAIN:
6017
        raise errors.OpPrereqError("Disk adoption is only supported for the"
6018
                                   " 'plain' disk template",
6019
                                   errors.ECODE_INVAL)
6020
      if self.op.iallocator is not None:
6021
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6022
                                   " iallocator script", errors.ECODE_INVAL)
6023
      if self.op.mode == constants.INSTANCE_IMPORT:
6024
        raise errors.OpPrereqError("Disk adoption not allowed for"
6025
                                   " instance import", errors.ECODE_INVAL)
6026

    
6027
    self.adopt_disks = has_adopt
6028

    
6029
  def ExpandNames(self):
6030
    """ExpandNames for CreateInstance.
6031

6032
    Figure out the right locks for instance creation.
6033

6034
    """
6035
    self.needed_locks = {}
6036

    
6037
    # cheap checks, mostly valid constants given
6038

    
6039
    # verify creation mode
6040
    if self.op.mode not in (constants.INSTANCE_CREATE,
6041
                            constants.INSTANCE_IMPORT):
6042
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
6043
                                 self.op.mode, errors.ECODE_INVAL)
6044

    
6045
    # disk template and mirror node verification
6046
    _CheckDiskTemplate(self.op.disk_template)
6047

    
6048
    if self.op.hypervisor is None:
6049
      self.op.hypervisor = self.cfg.GetHypervisorType()
6050

    
6051
    cluster = self.cfg.GetClusterInfo()
6052
    enabled_hvs = cluster.enabled_hypervisors
6053
    if self.op.hypervisor not in enabled_hvs:
6054
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6055
                                 " cluster (%s)" % (self.op.hypervisor,
6056
                                  ",".join(enabled_hvs)),
6057
                                 errors.ECODE_STATE)
6058

    
6059
    # check hypervisor parameter syntax (locally)
6060
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6061
    filled_hvp = objects.FillDict(cluster.hvparams[self.op.hypervisor],
6062
                                  self.op.hvparams)
6063
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6064
    hv_type.CheckParameterSyntax(filled_hvp)
6065
    self.hv_full = filled_hvp
6066
    # check that we don't specify global parameters on an instance
6067
    _CheckGlobalHvParams(self.op.hvparams)
6068

    
6069
    # fill and remember the beparams dict
6070
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6071
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
6072
                                    self.op.beparams)
6073

    
6074
    #### instance parameters check
6075

    
6076
    # instance name verification
6077
    if self.op.name_check:
6078
      hostname1 = utils.GetHostInfo(self.op.instance_name)
6079
      self.op.instance_name = instance_name = hostname1.name
6080
      # used in CheckPrereq for ip ping check
6081
      self.check_ip = hostname1.ip
6082
    else:
6083
      instance_name = self.op.instance_name
6084
      self.check_ip = None
6085

    
6086
    # this is just a preventive check, but someone might still add this
6087
    # instance in the meantime, and creation will fail at lock-add time
6088
    if instance_name in self.cfg.GetInstanceList():
6089
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6090
                                 instance_name, errors.ECODE_EXISTS)
6091

    
6092
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6093

    
6094
    # NIC buildup
6095
    self.nics = []
6096
    for idx, nic in enumerate(self.op.nics):
6097
      nic_mode_req = nic.get("mode", None)
6098
      nic_mode = nic_mode_req
6099
      if nic_mode is None:
6100
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6101

    
6102
      # in routed mode, for the first nic, the default ip is 'auto'
6103
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6104
        default_ip_mode = constants.VALUE_AUTO
6105
      else:
6106
        default_ip_mode = constants.VALUE_NONE
6107

    
6108
      # ip validity checks
6109
      ip = nic.get("ip", default_ip_mode)
6110
      if ip is None or ip.lower() == constants.VALUE_NONE:
6111
        nic_ip = None
6112
      elif ip.lower() == constants.VALUE_AUTO:
6113
        if not self.op.name_check:
6114
          raise errors.OpPrereqError("IP address set to auto but name checks"
6115
                                     " have been skipped. Aborting.",
6116
                                     errors.ECODE_INVAL)
6117
        nic_ip = hostname1.ip
6118
      else:
6119
        if not utils.IsValidIP(ip):
6120
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6121
                                     " like a valid IP" % ip,
6122
                                     errors.ECODE_INVAL)
6123
        nic_ip = ip
6124

    
6125
      # TODO: check the ip address for uniqueness
6126
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6127
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6128
                                   errors.ECODE_INVAL)
6129

    
6130
      # MAC address verification
6131
      mac = nic.get("mac", constants.VALUE_AUTO)
6132
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6133
        mac = utils.NormalizeAndValidateMac(mac)
6134

    
6135
        try:
6136
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
6137
        except errors.ReservationError:
6138
          raise errors.OpPrereqError("MAC address %s already in use"
6139
                                     " in cluster" % mac,
6140
                                     errors.ECODE_NOTUNIQUE)
6141

    
6142
      # bridge verification
6143
      bridge = nic.get("bridge", None)
6144
      link = nic.get("link", None)
6145
      if bridge and link:
6146
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
6147
                                   " at the same time", errors.ECODE_INVAL)
6148
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
6149
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
6150
                                   errors.ECODE_INVAL)
6151
      elif bridge:
6152
        link = bridge
6153

    
6154
      nicparams = {}
6155
      if nic_mode_req:
6156
        nicparams[constants.NIC_MODE] = nic_mode_req
6157
      if link:
6158
        nicparams[constants.NIC_LINK] = link
6159

    
6160
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
6161
                                      nicparams)
6162
      objects.NIC.CheckParameterSyntax(check_params)
6163
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
6164

    
6165
    # disk checks/pre-build
6166
    self.disks = []
6167
    for disk in self.op.disks:
6168
      mode = disk.get("mode", constants.DISK_RDWR)
6169
      if mode not in constants.DISK_ACCESS_SET:
6170
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
6171
                                   mode, errors.ECODE_INVAL)
6172
      size = disk.get("size", None)
6173
      if size is None:
6174
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
6175
      try:
6176
        size = int(size)
6177
      except (TypeError, ValueError):
6178
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
6179
                                   errors.ECODE_INVAL)
6180
      new_disk = {"size": size, "mode": mode}
6181
      if "adopt" in disk:
6182
        new_disk["adopt"] = disk["adopt"]
6183
      self.disks.append(new_disk)
6184

    
6185
    # file storage checks
6186
    if (self.op.file_driver and
6187
        not self.op.file_driver in constants.FILE_DRIVER):
6188
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6189
                                 self.op.file_driver, errors.ECODE_INVAL)
6190

    
6191
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6192
      raise errors.OpPrereqError("File storage directory path not absolute",
6193
                                 errors.ECODE_INVAL)
6194

    
6195
    ### Node/iallocator related checks
6196
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
6197
      raise errors.OpPrereqError("One and only one of iallocator and primary"
6198
                                 " node must be given",
6199
                                 errors.ECODE_INVAL)
6200

    
6201
    if self.op.iallocator:
6202
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6203
    else:
6204
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6205
      nodelist = [self.op.pnode]
6206
      if self.op.snode is not None:
6207
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6208
        nodelist.append(self.op.snode)
6209
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6210

    
6211
    # in case of import lock the source node too
6212
    if self.op.mode == constants.INSTANCE_IMPORT:
6213
      src_node = getattr(self.op, "src_node", None)
6214
      src_path = getattr(self.op, "src_path", None)
6215

    
6216
      if src_path is None:
6217
        self.op.src_path = src_path = self.op.instance_name
6218

    
6219
      if src_node is None:
6220
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6221
        self.op.src_node = None
6222
        if os.path.isabs(src_path):
6223
          raise errors.OpPrereqError("Importing an instance from an absolute"
6224
                                     " path requires a source node option.",
6225
                                     errors.ECODE_INVAL)
6226
      else:
6227
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6228
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6229
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6230
        if not os.path.isabs(src_path):
6231
          self.op.src_path = src_path = \
6232
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6233

    
6234
      # On import force_variant must be True, because if we forced it at
6235
      # initial install, our only chance when importing it back is that it
6236
      # works again!
6237
      self.op.force_variant = True
6238

    
6239
      if self.op.no_install:
6240
        self.LogInfo("No-installation mode has no effect during import")
6241

    
6242
    else: # INSTANCE_CREATE
6243
      if getattr(self.op, "os_type", None) is None:
6244
        raise errors.OpPrereqError("No guest OS specified",
6245
                                   errors.ECODE_INVAL)
6246
      self.op.force_variant = getattr(self.op, "force_variant", False)
6247

    
6248
  def _RunAllocator(self):
6249
    """Run the allocator based on input opcode.
6250

6251
    """
6252
    nics = [n.ToDict() for n in self.nics]
6253
    ial = IAllocator(self.cfg, self.rpc,
6254
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6255
                     name=self.op.instance_name,
6256
                     disk_template=self.op.disk_template,
6257
                     tags=[],
6258
                     os=self.op.os_type,
6259
                     vcpus=self.be_full[constants.BE_VCPUS],
6260
                     mem_size=self.be_full[constants.BE_MEMORY],
6261
                     disks=self.disks,
6262
                     nics=nics,
6263
                     hypervisor=self.op.hypervisor,
6264
                     )
6265

    
6266
    ial.Run(self.op.iallocator)
6267

    
6268
    if not ial.success:
6269
      raise errors.OpPrereqError("Can't compute nodes using"
6270
                                 " iallocator '%s': %s" %
6271
                                 (self.op.iallocator, ial.info),
6272
                                 errors.ECODE_NORES)
6273
    if len(ial.result) != ial.required_nodes:
6274
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6275
                                 " of nodes (%s), required %s" %
6276
                                 (self.op.iallocator, len(ial.result),
6277
                                  ial.required_nodes), errors.ECODE_FAULT)
6278
    self.op.pnode = ial.result[0]
6279
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6280
                 self.op.instance_name, self.op.iallocator,
6281
                 utils.CommaJoin(ial.result))
6282
    if ial.required_nodes == 2:
6283
      self.op.snode = ial.result[1]
6284

    
6285
  def BuildHooksEnv(self):
6286
    """Build hooks env.
6287

6288
    This runs on master, primary and secondary nodes of the instance.
6289

6290
    """
6291
    env = {
6292
      "ADD_MODE": self.op.mode,
6293
      }
6294
    if self.op.mode == constants.INSTANCE_IMPORT:
6295
      env["SRC_NODE"] = self.op.src_node
6296
      env["SRC_PATH"] = self.op.src_path
6297
      env["SRC_IMAGES"] = self.src_images
6298

    
6299
    env.update(_BuildInstanceHookEnv(
6300
      name=self.op.instance_name,
6301
      primary_node=self.op.pnode,
6302
      secondary_nodes=self.secondaries,
6303
      status=self.op.start,
6304
      os_type=self.op.os_type,
6305
      memory=self.be_full[constants.BE_MEMORY],
6306
      vcpus=self.be_full[constants.BE_VCPUS],
6307
      nics=_NICListToTuple(self, self.nics),
6308
      disk_template=self.op.disk_template,
6309
      disks=[(d["size"], d["mode"]) for d in self.disks],
6310
      bep=self.be_full,
6311
      hvp=self.hv_full,
6312
      hypervisor_name=self.op.hypervisor,
6313
    ))
6314

    
6315
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6316
          self.secondaries)
6317
    return env, nl, nl
6318

    
6319

    
6320
  def CheckPrereq(self):
6321
    """Check prerequisites.
6322

6323
    """
6324
    if (not self.cfg.GetVGName() and
6325
        self.op.disk_template not in constants.DTS_NOT_LVM):
6326
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6327
                                 " instances", errors.ECODE_STATE)
6328

    
6329
    if self.op.mode == constants.INSTANCE_IMPORT:
6330
      src_node = self.op.src_node
6331
      src_path = self.op.src_path
6332

    
6333
      if src_node is None:
6334
        locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6335
        exp_list = self.rpc.call_export_list(locked_nodes)
6336
        found = False
6337
        for node in exp_list:
6338
          if exp_list[node].fail_msg:
6339
            continue
6340
          if src_path in exp_list[node].payload:
6341
            found = True
6342
            self.op.src_node = src_node = node
6343
            self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6344
                                                         src_path)
6345
            break
6346
        if not found:
6347
          raise errors.OpPrereqError("No export found for relative path %s" %
6348
                                      src_path, errors.ECODE_INVAL)
6349

    
6350
      _CheckNodeOnline(self, src_node)
6351
      result = self.rpc.call_export_info(src_node, src_path)
6352
      result.Raise("No export or invalid export found in dir %s" % src_path)
6353

    
6354
      export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6355
      if not export_info.has_section(constants.INISECT_EXP):
6356
        raise errors.ProgrammerError("Corrupted export config",
6357
                                     errors.ECODE_ENVIRON)
6358

    
6359
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
6360
      if (int(ei_version) != constants.EXPORT_VERSION):
6361
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6362
                                   (ei_version, constants.EXPORT_VERSION),
6363
                                   errors.ECODE_ENVIRON)
6364

    
6365
      # Check that the new instance doesn't have less disks than the export
6366
      instance_disks = len(self.disks)
6367
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6368
      if instance_disks < export_disks:
6369
        raise errors.OpPrereqError("Not enough disks to import."
6370
                                   " (instance: %d, export: %d)" %
6371
                                   (instance_disks, export_disks),
6372
                                   errors.ECODE_INVAL)
6373

    
6374
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
6375
      disk_images = []
6376
      for idx in range(export_disks):
6377
        option = 'disk%d_dump' % idx
6378
        if export_info.has_option(constants.INISECT_INS, option):
6379
          # FIXME: are the old os-es, disk sizes, etc. useful?
6380
          export_name = export_info.get(constants.INISECT_INS, option)
6381
          image = utils.PathJoin(src_path, export_name)
6382
          disk_images.append(image)
6383
        else:
6384
          disk_images.append(False)
6385

    
6386
      self.src_images = disk_images
6387

    
6388
      old_name = export_info.get(constants.INISECT_INS, 'name')
6389
      # FIXME: int() here could throw a ValueError on broken exports
6390
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
6391
      if self.op.instance_name == old_name:
6392
        for idx, nic in enumerate(self.nics):
6393
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
6394
            nic_mac_ini = 'nic%d_mac' % idx
6395
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
6396

    
6397
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
6398

    
6399
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
6400
    if self.op.ip_check:
6401
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
6402
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6403
                                   (self.check_ip, self.op.instance_name),
6404
                                   errors.ECODE_NOTUNIQUE)
6405

    
6406
    #### mac address generation
6407
    # By generating here the mac address both the allocator and the hooks get
6408
    # the real final mac address rather than the 'auto' or 'generate' value.
6409
    # There is a race condition between the generation and the instance object
6410
    # creation, which means that we know the mac is valid now, but we're not
6411
    # sure it will be when we actually add the instance. If things go bad
6412
    # adding the instance will abort because of a duplicate mac, and the
6413
    # creation job will fail.
6414
    for nic in self.nics:
6415
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6416
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
6417

    
6418
    #### allocator run
6419

    
6420
    if self.op.iallocator is not None:
6421
      self._RunAllocator()
6422

    
6423
    #### node related checks
6424

    
6425
    # check primary node
6426
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
6427
    assert self.pnode is not None, \
6428
      "Cannot retrieve locked node %s" % self.op.pnode
6429
    if pnode.offline:
6430
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
6431
                                 pnode.name, errors.ECODE_STATE)
6432
    if pnode.drained:
6433
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
6434
                                 pnode.name, errors.ECODE_STATE)
6435

    
6436
    self.secondaries = []
6437

    
6438
    # mirror node verification
6439
    if self.op.disk_template in constants.DTS_NET_MIRROR:
6440
      if self.op.snode is None:
6441
        raise errors.OpPrereqError("The networked disk templates need"
6442
                                   " a mirror node", errors.ECODE_INVAL)
6443
      if self.op.snode == pnode.name:
6444
        raise errors.OpPrereqError("The secondary node cannot be the"
6445
                                   " primary node.", errors.ECODE_INVAL)
6446
      _CheckNodeOnline(self, self.op.snode)
6447
      _CheckNodeNotDrained(self, self.op.snode)
6448
      self.secondaries.append(self.op.snode)
6449

    
6450
    nodenames = [pnode.name] + self.secondaries
6451

    
6452
    req_size = _ComputeDiskSize(self.op.disk_template,
6453
                                self.disks)
6454

    
6455
    # Check lv size requirements, if not adopting
6456
    if req_size is not None and not self.adopt_disks:
6457
      _CheckNodesFreeDisk(self, nodenames, req_size)
6458

    
6459
    if self.adopt_disks: # instead, we must check the adoption data
6460
      all_lvs = set([i["adopt"] for i in self.disks])
6461
      if len(all_lvs) != len(self.disks):
6462
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
6463
                                   errors.ECODE_INVAL)
6464
      for lv_name in all_lvs:
6465
        try:
6466
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
6467
        except errors.ReservationError:
6468
          raise errors.OpPrereqError("LV named %s used by another instance" %
6469
                                     lv_name, errors.ECODE_NOTUNIQUE)
6470

    
6471
      node_lvs = self.rpc.call_lv_list([pnode.name],
6472
                                       self.cfg.GetVGName())[pnode.name]
6473
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
6474
      node_lvs = node_lvs.payload
6475
      delta = all_lvs.difference(node_lvs.keys())
6476
      if delta:
6477
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
6478
                                   utils.CommaJoin(delta),
6479
                                   errors.ECODE_INVAL)
6480
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
6481
      if online_lvs:
6482
        raise errors.OpPrereqError("Online logical volumes found, cannot"
6483
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
6484
                                   errors.ECODE_STATE)
6485
      # update the size of disk based on what is found
6486
      for dsk in self.disks:
6487
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
6488

    
6489
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
6490

    
6491
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
6492

    
6493
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
6494

    
6495
    # memory check on primary node
6496
    if self.op.start:
6497
      _CheckNodeFreeMemory(self, self.pnode.name,
6498
                           "creating instance %s" % self.op.instance_name,
6499
                           self.be_full[constants.BE_MEMORY],
6500
                           self.op.hypervisor)
6501

    
6502
    self.dry_run_result = list(nodenames)
6503

    
6504
  def Exec(self, feedback_fn):
6505
    """Create and add the instance to the cluster.
6506

6507
    """
6508
    instance = self.op.instance_name
6509
    pnode_name = self.pnode.name
6510

    
6511
    ht_kind = self.op.hypervisor
6512
    if ht_kind in constants.HTS_REQ_PORT:
6513
      network_port = self.cfg.AllocatePort()
6514
    else:
6515
      network_port = None
6516

    
6517
    ##if self.op.vnc_bind_address is None:
6518
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
6519

    
6520
    # this is needed because os.path.join does not accept None arguments
6521
    if self.op.file_storage_dir is None:
6522
      string_file_storage_dir = ""
6523
    else:
6524
      string_file_storage_dir = self.op.file_storage_dir
6525

    
6526
    # build the full file storage dir path
6527
    file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
6528
                                      string_file_storage_dir, instance)
6529

    
6530

    
6531
    disks = _GenerateDiskTemplate(self,
6532
                                  self.op.disk_template,
6533
                                  instance, pnode_name,
6534
                                  self.secondaries,
6535
                                  self.disks,
6536
                                  file_storage_dir,
6537
                                  self.op.file_driver,
6538
                                  0)
6539

    
6540
    iobj = objects.Instance(name=instance, os=self.op.os_type,
6541
                            primary_node=pnode_name,
6542
                            nics=self.nics, disks=disks,
6543
                            disk_template=self.op.disk_template,
6544
                            admin_up=False,
6545
                            network_port=network_port,
6546
                            beparams=self.op.beparams,
6547
                            hvparams=self.op.hvparams,
6548
                            hypervisor=self.op.hypervisor,
6549
                            )
6550

    
6551
    if self.adopt_disks:
6552
      # rename LVs to the newly-generated names; we need to construct
6553
      # 'fake' LV disks with the old data, plus the new unique_id
6554
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
6555
      rename_to = []
6556
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
6557
        rename_to.append(t_dsk.logical_id)
6558
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
6559
        self.cfg.SetDiskID(t_dsk, pnode_name)
6560
      result = self.rpc.call_blockdev_rename(pnode_name,
6561
                                             zip(tmp_disks, rename_to))
6562
      result.Raise("Failed to rename adoped LVs")
6563
    else:
6564
      feedback_fn("* creating instance disks...")
6565
      try:
6566
        _CreateDisks(self, iobj)
6567
      except errors.OpExecError:
6568
        self.LogWarning("Device creation failed, reverting...")
6569
        try:
6570
          _RemoveDisks(self, iobj)
6571
        finally:
6572
          self.cfg.ReleaseDRBDMinors(instance)
6573
          raise
6574

    
6575
    feedback_fn("adding instance %s to cluster config" % instance)
6576

    
6577
    self.cfg.AddInstance(iobj, self.proc.GetECId())
6578

    
6579
    # Declare that we don't want to remove the instance lock anymore, as we've
6580
    # added the instance to the config
6581
    del self.remove_locks[locking.LEVEL_INSTANCE]
6582
    # Unlock all the nodes
6583
    if self.op.mode == constants.INSTANCE_IMPORT:
6584
      nodes_keep = [self.op.src_node]
6585
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
6586
                       if node != self.op.src_node]
6587
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
6588
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6589
    else:
6590
      self.context.glm.release(locking.LEVEL_NODE)
6591
      del self.acquired_locks[locking.LEVEL_NODE]
6592

    
6593
    if self.op.wait_for_sync:
6594
      disk_abort = not _WaitForSync(self, iobj)
6595
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
6596
      # make sure the disks are not degraded (still sync-ing is ok)
6597
      time.sleep(15)
6598
      feedback_fn("* checking mirrors status")
6599
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
6600
    else:
6601
      disk_abort = False
6602

    
6603
    if disk_abort:
6604
      _RemoveDisks(self, iobj)
6605
      self.cfg.RemoveInstance(iobj.name)
6606
      # Make sure the instance lock gets removed
6607
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
6608
      raise errors.OpExecError("There are some degraded disks for"
6609
                               " this instance")
6610

    
6611
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
6612
      if self.op.mode == constants.INSTANCE_CREATE:
6613
        if not self.op.no_install:
6614
          feedback_fn("* running the instance OS create scripts...")
6615
          # FIXME: pass debug option from opcode to backend
6616
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
6617
                                                 self.op.debug_level)
6618
          result.Raise("Could not add os for instance %s"
6619
                       " on node %s" % (instance, pnode_name))
6620

    
6621
      elif self.op.mode == constants.INSTANCE_IMPORT:
6622
        feedback_fn("* running the instance OS import scripts...")
6623
        src_node = self.op.src_node
6624
        src_images = self.src_images
6625
        cluster_name = self.cfg.GetClusterName()
6626
        # FIXME: pass debug option from opcode to backend
6627
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
6628
                                                         src_node, src_images,
6629
                                                         cluster_name,
6630
                                                         self.op.debug_level)
6631
        msg = import_result.fail_msg
6632
        if msg:
6633
          self.LogWarning("Error while importing the disk images for instance"
6634
                          " %s on node %s: %s" % (instance, pnode_name, msg))
6635
      else:
6636
        # also checked in the prereq part
6637
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
6638
                                     % self.op.mode)
6639

    
6640
    if self.op.start:
6641
      iobj.admin_up = True
6642
      self.cfg.Update(iobj, feedback_fn)
6643
      logging.info("Starting instance %s on node %s", instance, pnode_name)
6644
      feedback_fn("* starting instance...")
6645
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
6646
      result.Raise("Could not start instance")
6647

    
6648
    return list(iobj.all_nodes)
6649

    
6650

    
6651
class LUConnectConsole(NoHooksLU):
6652
  """Connect to an instance's console.
6653

6654
  This is somewhat special in that it returns the command line that
6655
  you need to run on the master node in order to connect to the
6656
  console.
6657

6658
  """
6659
  _OP_REQP = ["instance_name"]
6660
  REQ_BGL = False
6661

    
6662
  def ExpandNames(self):
6663
    self._ExpandAndLockInstance()
6664

    
6665
  def CheckPrereq(self):
6666
    """Check prerequisites.
6667

6668
    This checks that the instance is in the cluster.
6669

6670
    """
6671
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6672
    assert self.instance is not None, \
6673
      "Cannot retrieve locked instance %s" % self.op.instance_name
6674
    _CheckNodeOnline(self, self.instance.primary_node)
6675

    
6676
  def Exec(self, feedback_fn):
6677
    """Connect to the console of an instance
6678

6679
    """
6680
    instance = self.instance
6681
    node = instance.primary_node
6682

    
6683
    node_insts = self.rpc.call_instance_list([node],
6684
                                             [instance.hypervisor])[node]
6685
    node_insts.Raise("Can't get node information from %s" % node)
6686

    
6687
    if instance.name not in node_insts.payload:
6688
      raise errors.OpExecError("Instance %s is not running." % instance.name)
6689

    
6690
    logging.debug("Connecting to console of %s on %s", instance.name, node)
6691

    
6692
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6693
    cluster = self.cfg.GetClusterInfo()
6694
    # beparams and hvparams are passed separately, to avoid editing the
6695
    # instance and then saving the defaults in the instance itself.
6696
    hvparams = cluster.FillHV(instance)
6697
    beparams = cluster.FillBE(instance)
6698
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6699

    
6700
    # build ssh cmdline
6701
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6702

    
6703

    
6704
class LUReplaceDisks(LogicalUnit):
6705
  """Replace the disks of an instance.
6706

6707
  """
6708
  HPATH = "mirrors-replace"
6709
  HTYPE = constants.HTYPE_INSTANCE
6710
  _OP_REQP = ["instance_name", "mode", "disks"]
6711
  REQ_BGL = False
6712

    
6713
  def CheckArguments(self):
6714
    if not hasattr(self.op, "remote_node"):
6715
      self.op.remote_node = None
6716
    if not hasattr(self.op, "iallocator"):
6717
      self.op.iallocator = None
6718
    if not hasattr(self.op, "early_release"):
6719
      self.op.early_release = False
6720

    
6721
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
6722
                                  self.op.iallocator)
6723

    
6724
  def ExpandNames(self):
6725
    self._ExpandAndLockInstance()
6726

    
6727
    if self.op.iallocator is not None:
6728
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6729

    
6730
    elif self.op.remote_node is not None:
6731
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
6732
      self.op.remote_node = remote_node
6733

    
6734
      # Warning: do not remove the locking of the new secondary here
6735
      # unless DRBD8.AddChildren is changed to work in parallel;
6736
      # currently it doesn't since parallel invocations of
6737
      # FindUnusedMinor will conflict
6738
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6739
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6740

    
6741
    else:
6742
      self.needed_locks[locking.LEVEL_NODE] = []
6743
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6744

    
6745
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
6746
                                   self.op.iallocator, self.op.remote_node,
6747
                                   self.op.disks, False, self.op.early_release)
6748

    
6749
    self.tasklets = [self.replacer]
6750

    
6751
  def DeclareLocks(self, level):
6752
    # If we're not already locking all nodes in the set we have to declare the
6753
    # instance's primary/secondary nodes.
6754
    if (level == locking.LEVEL_NODE and
6755
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6756
      self._LockInstancesNodes()
6757

    
6758
  def BuildHooksEnv(self):
6759
    """Build hooks env.
6760

6761
    This runs on the master, the primary and all the secondaries.
6762

6763
    """
6764
    instance = self.replacer.instance
6765
    env = {
6766
      "MODE": self.op.mode,
6767
      "NEW_SECONDARY": self.op.remote_node,
6768
      "OLD_SECONDARY": instance.secondary_nodes[0],
6769
      }
6770
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6771
    nl = [
6772
      self.cfg.GetMasterNode(),
6773
      instance.primary_node,
6774
      ]
6775
    if self.op.remote_node is not None:
6776
      nl.append(self.op.remote_node)
6777
    return env, nl, nl
6778

    
6779

    
6780
class LUEvacuateNode(LogicalUnit):
6781
  """Relocate the secondary instances from a node.
6782

6783
  """
6784
  HPATH = "node-evacuate"
6785
  HTYPE = constants.HTYPE_NODE
6786
  _OP_REQP = ["node_name"]
6787
  REQ_BGL = False
6788

    
6789
  def CheckArguments(self):
6790
    if not hasattr(self.op, "remote_node"):
6791
      self.op.remote_node = None
6792
    if not hasattr(self.op, "iallocator"):
6793
      self.op.iallocator = None
6794
    if not hasattr(self.op, "early_release"):
6795
      self.op.early_release = False
6796

    
6797
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
6798
                                  self.op.remote_node,
6799
                                  self.op.iallocator)
6800

    
6801
  def ExpandNames(self):
6802
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6803

    
6804
    self.needed_locks = {}
6805

    
6806
    # Declare node locks
6807
    if self.op.iallocator is not None:
6808
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6809

    
6810
    elif self.op.remote_node is not None:
6811
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
6812

    
6813
      # Warning: do not remove the locking of the new secondary here
6814
      # unless DRBD8.AddChildren is changed to work in parallel;
6815
      # currently it doesn't since parallel invocations of
6816
      # FindUnusedMinor will conflict
6817
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
6818
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6819

    
6820
    else:
6821
      raise errors.OpPrereqError("Invalid parameters", errors.ECODE_INVAL)
6822

    
6823
    # Create tasklets for replacing disks for all secondary instances on this
6824
    # node
6825
    names = []
6826
    tasklets = []
6827

    
6828
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
6829
      logging.debug("Replacing disks for instance %s", inst.name)
6830
      names.append(inst.name)
6831

    
6832
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
6833
                                self.op.iallocator, self.op.remote_node, [],
6834
                                True, self.op.early_release)
6835
      tasklets.append(replacer)
6836

    
6837
    self.tasklets = tasklets
6838
    self.instance_names = names
6839

    
6840
    # Declare instance locks
6841
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
6842

    
6843
  def DeclareLocks(self, level):
6844
    # If we're not already locking all nodes in the set we have to declare the
6845
    # instance's primary/secondary nodes.
6846
    if (level == locking.LEVEL_NODE and
6847
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6848
      self._LockInstancesNodes()
6849

    
6850
  def BuildHooksEnv(self):
6851
    """Build hooks env.
6852

6853
    This runs on the master, the primary and all the secondaries.
6854

6855
    """
6856
    env = {
6857
      "NODE_NAME": self.op.node_name,
6858
      }
6859

    
6860
    nl = [self.cfg.GetMasterNode()]
6861

    
6862
    if self.op.remote_node is not None:
6863
      env["NEW_SECONDARY"] = self.op.remote_node
6864
      nl.append(self.op.remote_node)
6865

    
6866
    return (env, nl, nl)
6867

    
6868

    
6869
class TLReplaceDisks(Tasklet):
6870
  """Replaces disks for an instance.
6871

6872
  Note: Locking is not within the scope of this class.
6873

6874
  """
6875
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
6876
               disks, delay_iallocator, early_release):
6877
    """Initializes this class.
6878

6879
    """
6880
    Tasklet.__init__(self, lu)
6881

    
6882
    # Parameters
6883
    self.instance_name = instance_name
6884
    self.mode = mode
6885
    self.iallocator_name = iallocator_name
6886
    self.remote_node = remote_node
6887
    self.disks = disks
6888
    self.delay_iallocator = delay_iallocator
6889
    self.early_release = early_release
6890

    
6891
    # Runtime data
6892
    self.instance = None
6893
    self.new_node = None
6894
    self.target_node = None
6895
    self.other_node = None
6896
    self.remote_node_info = None
6897
    self.node_secondary_ip = None
6898

    
6899
  @staticmethod
6900
  def CheckArguments(mode, remote_node, iallocator):
6901
    """Helper function for users of this class.
6902

6903
    """
6904
    # check for valid parameter combination
6905
    if mode == constants.REPLACE_DISK_CHG:
6906
      if remote_node is None and iallocator is None:
6907
        raise errors.OpPrereqError("When changing the secondary either an"
6908
                                   " iallocator script must be used or the"
6909
                                   " new node given", errors.ECODE_INVAL)
6910

    
6911
      if remote_node is not None and iallocator is not None:
6912
        raise errors.OpPrereqError("Give either the iallocator or the new"
6913
                                   " secondary, not both", errors.ECODE_INVAL)
6914

    
6915
    elif remote_node is not None or iallocator is not None:
6916
      # Not replacing the secondary
6917
      raise errors.OpPrereqError("The iallocator and new node options can"
6918
                                 " only be used when changing the"
6919
                                 " secondary node", errors.ECODE_INVAL)
6920

    
6921
  @staticmethod
6922
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
6923
    """Compute a new secondary node using an IAllocator.
6924

6925
    """
6926
    ial = IAllocator(lu.cfg, lu.rpc,
6927
                     mode=constants.IALLOCATOR_MODE_RELOC,
6928
                     name=instance_name,
6929
                     relocate_from=relocate_from)
6930

    
6931
    ial.Run(iallocator_name)
6932

    
6933
    if not ial.success:
6934
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
6935
                                 " %s" % (iallocator_name, ial.info),
6936
                                 errors.ECODE_NORES)
6937

    
6938
    if len(ial.result) != ial.required_nodes:
6939
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6940
                                 " of nodes (%s), required %s" %
6941
                                 (iallocator_name,
6942
                                  len(ial.result), ial.required_nodes),
6943
                                 errors.ECODE_FAULT)
6944

    
6945
    remote_node_name = ial.result[0]
6946

    
6947
    lu.LogInfo("Selected new secondary for instance '%s': %s",
6948
               instance_name, remote_node_name)
6949

    
6950
    return remote_node_name
6951

    
6952
  def _FindFaultyDisks(self, node_name):
6953
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
6954
                                    node_name, True)
6955

    
6956
  def CheckPrereq(self):
6957
    """Check prerequisites.
6958

6959
    This checks that the instance is in the cluster.
6960

6961
    """
6962
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
6963
    assert instance is not None, \
6964
      "Cannot retrieve locked instance %s" % self.instance_name
6965

    
6966
    if instance.disk_template != constants.DT_DRBD8:
6967
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
6968
                                 " instances", errors.ECODE_INVAL)
6969

    
6970
    if len(instance.secondary_nodes) != 1:
6971
      raise errors.OpPrereqError("The instance has a strange layout,"
6972
                                 " expected one secondary but found %d" %
6973
                                 len(instance.secondary_nodes),
6974
                                 errors.ECODE_FAULT)
6975

    
6976
    if not self.delay_iallocator:
6977
      self._CheckPrereq2()
6978

    
6979
  def _CheckPrereq2(self):
6980
    """Check prerequisites, second part.
6981

6982
    This function should always be part of CheckPrereq. It was separated and is
6983
    now called from Exec because during node evacuation iallocator was only
6984
    called with an unmodified cluster model, not taking planned changes into
6985
    account.
6986

6987
    """
6988
    instance = self.instance
6989
    secondary_node = instance.secondary_nodes[0]
6990

    
6991
    if self.iallocator_name is None:
6992
      remote_node = self.remote_node
6993
    else:
6994
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
6995
                                       instance.name, instance.secondary_nodes)
6996

    
6997
    if remote_node is not None:
6998
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
6999
      assert self.remote_node_info is not None, \
7000
        "Cannot retrieve locked node %s" % remote_node
7001
    else:
7002
      self.remote_node_info = None
7003

    
7004
    if remote_node == self.instance.primary_node:
7005
      raise errors.OpPrereqError("The specified node is the primary node of"
7006
                                 " the instance.", errors.ECODE_INVAL)
7007

    
7008
    if remote_node == secondary_node:
7009
      raise errors.OpPrereqError("The specified node is already the"
7010
                                 " secondary node of the instance.",
7011
                                 errors.ECODE_INVAL)
7012

    
7013
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7014
                                    constants.REPLACE_DISK_CHG):
7015
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7016
                                 errors.ECODE_INVAL)
7017

    
7018
    if self.mode == constants.REPLACE_DISK_AUTO:
7019
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7020
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7021

    
7022
      if faulty_primary and faulty_secondary:
7023
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7024
                                   " one node and can not be repaired"
7025
                                   " automatically" % self.instance_name,
7026
                                   errors.ECODE_STATE)
7027

    
7028
      if faulty_primary:
7029
        self.disks = faulty_primary
7030
        self.target_node = instance.primary_node
7031
        self.other_node = secondary_node
7032
        check_nodes = [self.target_node, self.other_node]
7033
      elif faulty_secondary:
7034
        self.disks = faulty_secondary
7035
        self.target_node = secondary_node
7036
        self.other_node = instance.primary_node
7037
        check_nodes = [self.target_node, self.other_node]
7038
      else:
7039
        self.disks = []
7040
        check_nodes = []
7041

    
7042
    else:
7043
      # Non-automatic modes
7044
      if self.mode == constants.REPLACE_DISK_PRI:
7045
        self.target_node = instance.primary_node
7046
        self.other_node = secondary_node
7047
        check_nodes = [self.target_node, self.other_node]
7048

    
7049
      elif self.mode == constants.REPLACE_DISK_SEC:
7050
        self.target_node = secondary_node
7051
        self.other_node = instance.primary_node
7052
        check_nodes = [self.target_node, self.other_node]
7053

    
7054
      elif self.mode == constants.REPLACE_DISK_CHG:
7055
        self.new_node = remote_node
7056
        self.other_node = instance.primary_node
7057
        self.target_node = secondary_node
7058
        check_nodes = [self.new_node, self.other_node]
7059

    
7060
        _CheckNodeNotDrained(self.lu, remote_node)
7061

    
7062
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7063
        assert old_node_info is not None
7064
        if old_node_info.offline and not self.early_release:
7065
          # doesn't make sense to delay the release
7066
          self.early_release = True
7067
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7068
                          " early-release mode", secondary_node)
7069

    
7070
      else:
7071
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7072
                                     self.mode)
7073

    
7074
      # If not specified all disks should be replaced
7075
      if not self.disks:
7076
        self.disks = range(len(self.instance.disks))
7077

    
7078
    for node in check_nodes:
7079
      _CheckNodeOnline(self.lu, node)
7080

    
7081
    # Check whether disks are valid
7082
    for disk_idx in self.disks:
7083
      instance.FindDisk(disk_idx)
7084

    
7085
    # Get secondary node IP addresses
7086
    node_2nd_ip = {}
7087

    
7088
    for node_name in [self.target_node, self.other_node, self.new_node]:
7089
      if node_name is not None:
7090
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7091

    
7092
    self.node_secondary_ip = node_2nd_ip
7093

    
7094
  def Exec(self, feedback_fn):
7095
    """Execute disk replacement.
7096

7097
    This dispatches the disk replacement to the appropriate handler.
7098

7099
    """
7100
    if self.delay_iallocator:
7101
      self._CheckPrereq2()
7102

    
7103
    if not self.disks:
7104
      feedback_fn("No disks need replacement")
7105
      return
7106

    
7107
    feedback_fn("Replacing disk(s) %s for %s" %
7108
                (utils.CommaJoin(self.disks), self.instance.name))
7109

    
7110
    activate_disks = (not self.instance.admin_up)
7111

    
7112
    # Activate the instance disks if we're replacing them on a down instance
7113
    if activate_disks:
7114
      _StartInstanceDisks(self.lu, self.instance, True)
7115

    
7116
    try:
7117
      # Should we replace the secondary node?
7118
      if self.new_node is not None:
7119
        fn = self._ExecDrbd8Secondary
7120
      else:
7121
        fn = self._ExecDrbd8DiskOnly
7122

    
7123
      return fn(feedback_fn)
7124

    
7125
    finally:
7126
      # Deactivate the instance disks if we're replacing them on a
7127
      # down instance
7128
      if activate_disks:
7129
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7130

    
7131
  def _CheckVolumeGroup(self, nodes):
7132
    self.lu.LogInfo("Checking volume groups")
7133

    
7134
    vgname = self.cfg.GetVGName()
7135

    
7136
    # Make sure volume group exists on all involved nodes
7137
    results = self.rpc.call_vg_list(nodes)
7138
    if not results:
7139
      raise errors.OpExecError("Can't list volume groups on the nodes")
7140

    
7141
    for node in nodes:
7142
      res = results[node]
7143
      res.Raise("Error checking node %s" % node)
7144
      if vgname not in res.payload:
7145
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7146
                                 (vgname, node))
7147

    
7148
  def _CheckDisksExistence(self, nodes):
7149
    # Check disk existence
7150
    for idx, dev in enumerate(self.instance.disks):
7151
      if idx not in self.disks:
7152
        continue
7153

    
7154
      for node in nodes:
7155
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7156
        self.cfg.SetDiskID(dev, node)
7157

    
7158
        result = self.rpc.call_blockdev_find(node, dev)
7159

    
7160
        msg = result.fail_msg
7161
        if msg or not result.payload:
7162
          if not msg:
7163
            msg = "disk not found"
7164
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7165
                                   (idx, node, msg))
7166

    
7167
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7168
    for idx, dev in enumerate(self.instance.disks):
7169
      if idx not in self.disks:
7170
        continue
7171

    
7172
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7173
                      (idx, node_name))
7174

    
7175
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7176
                                   ldisk=ldisk):
7177
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7178
                                 " replace disks for instance %s" %
7179
                                 (node_name, self.instance.name))
7180

    
7181
  def _CreateNewStorage(self, node_name):
7182
    vgname = self.cfg.GetVGName()
7183
    iv_names = {}
7184

    
7185
    for idx, dev in enumerate(self.instance.disks):
7186
      if idx not in self.disks:
7187
        continue
7188

    
7189
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7190

    
7191
      self.cfg.SetDiskID(dev, node_name)
7192

    
7193
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7194
      names = _GenerateUniqueNames(self.lu, lv_names)
7195

    
7196
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7197
                             logical_id=(vgname, names[0]))
7198
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7199
                             logical_id=(vgname, names[1]))
7200

    
7201
      new_lvs = [lv_data, lv_meta]
7202
      old_lvs = dev.children
7203
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7204

    
7205
      # we pass force_create=True to force the LVM creation
7206
      for new_lv in new_lvs:
7207
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7208
                        _GetInstanceInfoText(self.instance), False)
7209

    
7210
    return iv_names
7211

    
7212
  def _CheckDevices(self, node_name, iv_names):
7213
    for name, (dev, _, _) in iv_names.iteritems():
7214
      self.cfg.SetDiskID(dev, node_name)
7215

    
7216
      result = self.rpc.call_blockdev_find(node_name, dev)
7217

    
7218
      msg = result.fail_msg
7219
      if msg or not result.payload:
7220
        if not msg:
7221
          msg = "disk not found"
7222
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7223
                                 (name, msg))
7224

    
7225
      if result.payload.is_degraded:
7226
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7227

    
7228
  def _RemoveOldStorage(self, node_name, iv_names):
7229
    for name, (_, old_lvs, _) in iv_names.iteritems():
7230
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7231

    
7232
      for lv in old_lvs:
7233
        self.cfg.SetDiskID(lv, node_name)
7234

    
7235
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7236
        if msg:
7237
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7238
                             hint="remove unused LVs manually")
7239

    
7240
  def _ReleaseNodeLock(self, node_name):
7241
    """Releases the lock for a given node."""
7242
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7243

    
7244
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7245
    """Replace a disk on the primary or secondary for DRBD 8.
7246

7247
    The algorithm for replace is quite complicated:
7248

7249
      1. for each disk to be replaced:
7250

7251
        1. create new LVs on the target node with unique names
7252
        1. detach old LVs from the drbd device
7253
        1. rename old LVs to name_replaced.<time_t>
7254
        1. rename new LVs to old LVs
7255
        1. attach the new LVs (with the old names now) to the drbd device
7256

7257
      1. wait for sync across all devices
7258

7259
      1. for each modified disk:
7260

7261
        1. remove old LVs (which have the name name_replaces.<time_t>)
7262

7263
    Failures are not very well handled.
7264

7265
    """
7266
    steps_total = 6
7267

    
7268
    # Step: check device activation
7269
    self.lu.LogStep(1, steps_total, "Check device existence")
7270
    self._CheckDisksExistence([self.other_node, self.target_node])
7271
    self._CheckVolumeGroup([self.target_node, self.other_node])
7272

    
7273
    # Step: check other node consistency
7274
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7275
    self._CheckDisksConsistency(self.other_node,
7276
                                self.other_node == self.instance.primary_node,
7277
                                False)
7278

    
7279
    # Step: create new storage
7280
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7281
    iv_names = self._CreateNewStorage(self.target_node)
7282

    
7283
    # Step: for each lv, detach+rename*2+attach
7284
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7285
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7286
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7287

    
7288
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7289
                                                     old_lvs)
7290
      result.Raise("Can't detach drbd from local storage on node"
7291
                   " %s for device %s" % (self.target_node, dev.iv_name))
7292
      #dev.children = []
7293
      #cfg.Update(instance)
7294

    
7295
      # ok, we created the new LVs, so now we know we have the needed
7296
      # storage; as such, we proceed on the target node to rename
7297
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7298
      # using the assumption that logical_id == physical_id (which in
7299
      # turn is the unique_id on that node)
7300

    
7301
      # FIXME(iustin): use a better name for the replaced LVs
7302
      temp_suffix = int(time.time())
7303
      ren_fn = lambda d, suff: (d.physical_id[0],
7304
                                d.physical_id[1] + "_replaced-%s" % suff)
7305

    
7306
      # Build the rename list based on what LVs exist on the node
7307
      rename_old_to_new = []
7308
      for to_ren in old_lvs:
7309
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7310
        if not result.fail_msg and result.payload:
7311
          # device exists
7312
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7313

    
7314
      self.lu.LogInfo("Renaming the old LVs on the target node")
7315
      result = self.rpc.call_blockdev_rename(self.target_node,
7316
                                             rename_old_to_new)
7317
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7318

    
7319
      # Now we rename the new LVs to the old LVs
7320
      self.lu.LogInfo("Renaming the new LVs on the target node")
7321
      rename_new_to_old = [(new, old.physical_id)
7322
                           for old, new in zip(old_lvs, new_lvs)]
7323
      result = self.rpc.call_blockdev_rename(self.target_node,
7324
                                             rename_new_to_old)
7325
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7326

    
7327
      for old, new in zip(old_lvs, new_lvs):
7328
        new.logical_id = old.logical_id
7329
        self.cfg.SetDiskID(new, self.target_node)
7330

    
7331
      for disk in old_lvs:
7332
        disk.logical_id = ren_fn(disk, temp_suffix)
7333
        self.cfg.SetDiskID(disk, self.target_node)
7334

    
7335
      # Now that the new lvs have the old name, we can add them to the device
7336
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7337
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7338
                                                  new_lvs)
7339
      msg = result.fail_msg
7340
      if msg:
7341
        for new_lv in new_lvs:
7342
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7343
                                               new_lv).fail_msg
7344
          if msg2:
7345
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7346
                               hint=("cleanup manually the unused logical"
7347
                                     "volumes"))
7348
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7349

    
7350
      dev.children = new_lvs
7351

    
7352
      self.cfg.Update(self.instance, feedback_fn)
7353

    
7354
    cstep = 5
7355
    if self.early_release:
7356
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7357
      cstep += 1
7358
      self._RemoveOldStorage(self.target_node, iv_names)
7359
      # WARNING: we release both node locks here, do not do other RPCs
7360
      # than WaitForSync to the primary node
7361
      self._ReleaseNodeLock([self.target_node, self.other_node])
7362

    
7363
    # Wait for sync
7364
    # This can fail as the old devices are degraded and _WaitForSync
7365
    # does a combined result over all disks, so we don't check its return value
7366
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7367
    cstep += 1
7368
    _WaitForSync(self.lu, self.instance)
7369

    
7370
    # Check all devices manually
7371
    self._CheckDevices(self.instance.primary_node, iv_names)
7372

    
7373
    # Step: remove old storage
7374
    if not self.early_release:
7375
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7376
      cstep += 1
7377
      self._RemoveOldStorage(self.target_node, iv_names)
7378

    
7379
  def _ExecDrbd8Secondary(self, feedback_fn):
7380
    """Replace the secondary node for DRBD 8.
7381

7382
    The algorithm for replace is quite complicated:
7383
      - for all disks of the instance:
7384
        - create new LVs on the new node with same names
7385
        - shutdown the drbd device on the old secondary
7386
        - disconnect the drbd network on the primary
7387
        - create the drbd device on the new secondary
7388
        - network attach the drbd on the primary, using an artifice:
7389
          the drbd code for Attach() will connect to the network if it
7390
          finds a device which is connected to the good local disks but
7391
          not network enabled
7392
      - wait for sync across all devices
7393
      - remove all disks from the old secondary
7394

7395
    Failures are not very well handled.
7396

7397
    """
7398
    steps_total = 6
7399

    
7400
    # Step: check device activation
7401
    self.lu.LogStep(1, steps_total, "Check device existence")
7402
    self._CheckDisksExistence([self.instance.primary_node])
7403
    self._CheckVolumeGroup([self.instance.primary_node])
7404

    
7405
    # Step: check other node consistency
7406
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7407
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
7408

    
7409
    # Step: create new storage
7410
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7411
    for idx, dev in enumerate(self.instance.disks):
7412
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
7413
                      (self.new_node, idx))
7414
      # we pass force_create=True to force LVM creation
7415
      for new_lv in dev.children:
7416
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
7417
                        _GetInstanceInfoText(self.instance), False)
7418

    
7419
    # Step 4: dbrd minors and drbd setups changes
7420
    # after this, we must manually remove the drbd minors on both the
7421
    # error and the success paths
7422
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7423
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7424
                                         for dev in self.instance.disks],
7425
                                        self.instance.name)
7426
    logging.debug("Allocated minors %r", minors)
7427

    
7428
    iv_names = {}
7429
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7430
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7431
                      (self.new_node, idx))
7432
      # create new devices on new_node; note that we create two IDs:
7433
      # one without port, so the drbd will be activated without
7434
      # networking information on the new node at this stage, and one
7435
      # with network, for the latter activation in step 4
7436
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7437
      if self.instance.primary_node == o_node1:
7438
        p_minor = o_minor1
7439
      else:
7440
        assert self.instance.primary_node == o_node2, "Three-node instance?"
7441
        p_minor = o_minor2
7442

    
7443
      new_alone_id = (self.instance.primary_node, self.new_node, None,
7444
                      p_minor, new_minor, o_secret)
7445
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
7446
                    p_minor, new_minor, o_secret)
7447

    
7448
      iv_names[idx] = (dev, dev.children, new_net_id)
7449
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
7450
                    new_net_id)
7451
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
7452
                              logical_id=new_alone_id,
7453
                              children=dev.children,
7454
                              size=dev.size)
7455
      try:
7456
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
7457
                              _GetInstanceInfoText(self.instance), False)
7458
      except errors.GenericError:
7459
        self.cfg.ReleaseDRBDMinors(self.instance.name)
7460
        raise
7461

    
7462
    # We have new devices, shutdown the drbd on the old secondary
7463
    for idx, dev in enumerate(self.instance.disks):
7464
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
7465
      self.cfg.SetDiskID(dev, self.target_node)
7466
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
7467
      if msg:
7468
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
7469
                           "node: %s" % (idx, msg),
7470
                           hint=("Please cleanup this device manually as"
7471
                                 " soon as possible"))
7472

    
7473
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
7474
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
7475
                                               self.node_secondary_ip,
7476
                                               self.instance.disks)\
7477
                                              [self.instance.primary_node]
7478

    
7479
    msg = result.fail_msg
7480
    if msg:
7481
      # detaches didn't succeed (unlikely)
7482
      self.cfg.ReleaseDRBDMinors(self.instance.name)
7483
      raise errors.OpExecError("Can't detach the disks from the network on"
7484
                               " old node: %s" % (msg,))
7485

    
7486
    # if we managed to detach at least one, we update all the disks of
7487
    # the instance to point to the new secondary
7488
    self.lu.LogInfo("Updating instance configuration")
7489
    for dev, _, new_logical_id in iv_names.itervalues():
7490
      dev.logical_id = new_logical_id
7491
      self.cfg.SetDiskID(dev, self.instance.primary_node)
7492

    
7493
    self.cfg.Update(self.instance, feedback_fn)
7494

    
7495
    # and now perform the drbd attach
7496
    self.lu.LogInfo("Attaching primary drbds to new secondary"
7497
                    " (standalone => connected)")
7498
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
7499
                                            self.new_node],
7500
                                           self.node_secondary_ip,
7501
                                           self.instance.disks,
7502
                                           self.instance.name,
7503
                                           False)
7504
    for to_node, to_result in result.items():
7505
      msg = to_result.fail_msg
7506
      if msg:
7507
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
7508
                           to_node, msg,
7509
                           hint=("please do a gnt-instance info to see the"
7510
                                 " status of disks"))
7511
    cstep = 5
7512
    if self.early_release:
7513
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7514
      cstep += 1
7515
      self._RemoveOldStorage(self.target_node, iv_names)
7516
      # WARNING: we release all node locks here, do not do other RPCs
7517
      # than WaitForSync to the primary node
7518
      self._ReleaseNodeLock([self.instance.primary_node,
7519
                             self.target_node,
7520
                             self.new_node])
7521

    
7522
    # Wait for sync
7523
    # This can fail as the old devices are degraded and _WaitForSync
7524
    # does a combined result over all disks, so we don't check its return value
7525
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7526
    cstep += 1
7527
    _WaitForSync(self.lu, self.instance)
7528

    
7529
    # Check all devices manually
7530
    self._CheckDevices(self.instance.primary_node, iv_names)
7531

    
7532
    # Step: remove old storage
7533
    if not self.early_release:
7534
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7535
      self._RemoveOldStorage(self.target_node, iv_names)
7536

    
7537

    
7538
class LURepairNodeStorage(NoHooksLU):
7539
  """Repairs the volume group on a node.
7540

7541
  """
7542
  _OP_REQP = ["node_name"]
7543
  REQ_BGL = False
7544

    
7545
  def CheckArguments(self):
7546
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
7547

    
7548
  def ExpandNames(self):
7549
    self.needed_locks = {
7550
      locking.LEVEL_NODE: [self.op.node_name],
7551
      }
7552

    
7553
  def _CheckFaultyDisks(self, instance, node_name):
7554
    """Ensure faulty disks abort the opcode or at least warn."""
7555
    try:
7556
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
7557
                                  node_name, True):
7558
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
7559
                                   " node '%s'" % (instance.name, node_name),
7560
                                   errors.ECODE_STATE)
7561
    except errors.OpPrereqError, err:
7562
      if self.op.ignore_consistency:
7563
        self.proc.LogWarning(str(err.args[0]))
7564
      else:
7565
        raise
7566

    
7567
  def CheckPrereq(self):
7568
    """Check prerequisites.
7569

7570
    """
7571
    storage_type = self.op.storage_type
7572

    
7573
    if (constants.SO_FIX_CONSISTENCY not in
7574
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
7575
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
7576
                                 " repaired" % storage_type,
7577
                                 errors.ECODE_INVAL)
7578

    
7579
    # Check whether any instance on this node has faulty disks
7580
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
7581
      if not inst.admin_up:
7582
        continue
7583
      check_nodes = set(inst.all_nodes)
7584
      check_nodes.discard(self.op.node_name)
7585
      for inst_node_name in check_nodes:
7586
        self._CheckFaultyDisks(inst, inst_node_name)
7587

    
7588
  def Exec(self, feedback_fn):
7589
    feedback_fn("Repairing storage unit '%s' on %s ..." %
7590
                (self.op.name, self.op.node_name))
7591

    
7592
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
7593
    result = self.rpc.call_storage_execute(self.op.node_name,
7594
                                           self.op.storage_type, st_args,
7595
                                           self.op.name,
7596
                                           constants.SO_FIX_CONSISTENCY)
7597
    result.Raise("Failed to repair storage unit '%s' on %s" %
7598
                 (self.op.name, self.op.node_name))
7599

    
7600

    
7601
class LUNodeEvacuationStrategy(NoHooksLU):
7602
  """Computes the node evacuation strategy.
7603

7604
  """
7605
  _OP_REQP = ["nodes"]
7606
  REQ_BGL = False
7607

    
7608
  def CheckArguments(self):
7609
    if not hasattr(self.op, "remote_node"):
7610
      self.op.remote_node = None
7611
    if not hasattr(self.op, "iallocator"):
7612
      self.op.iallocator = None
7613
    if self.op.remote_node is not None and self.op.iallocator is not None:
7614
      raise errors.OpPrereqError("Give either the iallocator or the new"
7615
                                 " secondary, not both", errors.ECODE_INVAL)
7616

    
7617
  def ExpandNames(self):
7618
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
7619
    self.needed_locks = locks = {}
7620
    if self.op.remote_node is None:
7621
      locks[locking.LEVEL_NODE] = locking.ALL_SET
7622
    else:
7623
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7624
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
7625

    
7626
  def CheckPrereq(self):
7627
    pass
7628

    
7629
  def Exec(self, feedback_fn):
7630
    if self.op.remote_node is not None:
7631
      instances = []
7632
      for node in self.op.nodes:
7633
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
7634
      result = []
7635
      for i in instances:
7636
        if i.primary_node == self.op.remote_node:
7637
          raise errors.OpPrereqError("Node %s is the primary node of"
7638
                                     " instance %s, cannot use it as"
7639
                                     " secondary" %
7640
                                     (self.op.remote_node, i.name),
7641
                                     errors.ECODE_INVAL)
7642
        result.append([i.name, self.op.remote_node])
7643
    else:
7644
      ial = IAllocator(self.cfg, self.rpc,
7645
                       mode=constants.IALLOCATOR_MODE_MEVAC,
7646
                       evac_nodes=self.op.nodes)
7647
      ial.Run(self.op.iallocator, validate=True)
7648
      if not ial.success:
7649
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
7650
                                 errors.ECODE_NORES)
7651
      result = ial.result
7652
    return result
7653

    
7654

    
7655
class LUGrowDisk(LogicalUnit):
7656
  """Grow a disk of an instance.
7657

7658
  """
7659
  HPATH = "disk-grow"
7660
  HTYPE = constants.HTYPE_INSTANCE
7661
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
7662
  REQ_BGL = False
7663

    
7664
  def ExpandNames(self):
7665
    self._ExpandAndLockInstance()
7666
    self.needed_locks[locking.LEVEL_NODE] = []
7667
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7668

    
7669
  def DeclareLocks(self, level):
7670
    if level == locking.LEVEL_NODE:
7671
      self._LockInstancesNodes()
7672

    
7673
  def BuildHooksEnv(self):
7674
    """Build hooks env.
7675

7676
    This runs on the master, the primary and all the secondaries.
7677

7678
    """
7679
    env = {
7680
      "DISK": self.op.disk,
7681
      "AMOUNT": self.op.amount,
7682
      }
7683
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7684
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7685
    return env, nl, nl
7686

    
7687
  def CheckPrereq(self):
7688
    """Check prerequisites.
7689

7690
    This checks that the instance is in the cluster.
7691

7692
    """
7693
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7694
    assert instance is not None, \
7695
      "Cannot retrieve locked instance %s" % self.op.instance_name
7696
    nodenames = list(instance.all_nodes)
7697
    for node in nodenames:
7698
      _CheckNodeOnline(self, node)
7699

    
7700

    
7701
    self.instance = instance
7702

    
7703
    if instance.disk_template not in constants.DTS_GROWABLE:
7704
      raise errors.OpPrereqError("Instance's disk layout does not support"
7705
                                 " growing.", errors.ECODE_INVAL)
7706

    
7707
    self.disk = instance.FindDisk(self.op.disk)
7708

    
7709
    if instance.disk_template != constants.DT_FILE:
7710
      # TODO: check the free disk space for file, when that feature will be
7711
      # supported
7712
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
7713

    
7714
  def Exec(self, feedback_fn):
7715
    """Execute disk grow.
7716

7717
    """
7718
    instance = self.instance
7719
    disk = self.disk
7720
    for node in instance.all_nodes:
7721
      self.cfg.SetDiskID(disk, node)
7722
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
7723
      result.Raise("Grow request failed to node %s" % node)
7724

    
7725
      # TODO: Rewrite code to work properly
7726
      # DRBD goes into sync mode for a short amount of time after executing the
7727
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
7728
      # calling "resize" in sync mode fails. Sleeping for a short amount of
7729
      # time is a work-around.
7730
      time.sleep(5)
7731

    
7732
    disk.RecordGrow(self.op.amount)
7733
    self.cfg.Update(instance, feedback_fn)
7734
    if self.op.wait_for_sync:
7735
      disk_abort = not _WaitForSync(self, instance)
7736
      if disk_abort:
7737
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
7738
                             " status.\nPlease check the instance.")
7739

    
7740

    
7741
class LUQueryInstanceData(NoHooksLU):
7742
  """Query runtime instance data.
7743

7744
  """
7745
  _OP_REQP = ["instances", "static"]
7746
  REQ_BGL = False
7747

    
7748
  def ExpandNames(self):
7749
    self.needed_locks = {}
7750
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
7751

    
7752
    if not isinstance(self.op.instances, list):
7753
      raise errors.OpPrereqError("Invalid argument type 'instances'",
7754
                                 errors.ECODE_INVAL)
7755

    
7756
    if self.op.instances:
7757
      self.wanted_names = []
7758
      for name in self.op.instances:
7759
        full_name = _ExpandInstanceName(self.cfg, name)
7760
        self.wanted_names.append(full_name)
7761
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
7762
    else:
7763
      self.wanted_names = None
7764
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
7765

    
7766
    self.needed_locks[locking.LEVEL_NODE] = []
7767
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7768

    
7769
  def DeclareLocks(self, level):
7770
    if level == locking.LEVEL_NODE:
7771
      self._LockInstancesNodes()
7772

    
7773
  def CheckPrereq(self):
7774
    """Check prerequisites.
7775

7776
    This only checks the optional instance list against the existing names.
7777

7778
    """
7779
    if self.wanted_names is None:
7780
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
7781

    
7782
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
7783
                             in self.wanted_names]
7784
    return
7785

    
7786
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
7787
    """Returns the status of a block device
7788

7789
    """
7790
    if self.op.static or not node:
7791
      return None
7792

    
7793
    self.cfg.SetDiskID(dev, node)
7794

    
7795
    result = self.rpc.call_blockdev_find(node, dev)
7796
    if result.offline:
7797
      return None
7798

    
7799
    result.Raise("Can't compute disk status for %s" % instance_name)
7800

    
7801
    status = result.payload
7802
    if status is None:
7803
      return None
7804

    
7805
    return (status.dev_path, status.major, status.minor,
7806
            status.sync_percent, status.estimated_time,
7807
            status.is_degraded, status.ldisk_status)
7808

    
7809
  def _ComputeDiskStatus(self, instance, snode, dev):
7810
    """Compute block device status.
7811

7812
    """
7813
    if dev.dev_type in constants.LDS_DRBD:
7814
      # we change the snode then (otherwise we use the one passed in)
7815
      if dev.logical_id[0] == instance.primary_node:
7816
        snode = dev.logical_id[1]
7817
      else:
7818
        snode = dev.logical_id[0]
7819

    
7820
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
7821
                                              instance.name, dev)
7822
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
7823

    
7824
    if dev.children:
7825
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
7826
                      for child in dev.children]
7827
    else:
7828
      dev_children = []
7829

    
7830
    data = {
7831
      "iv_name": dev.iv_name,
7832
      "dev_type": dev.dev_type,
7833
      "logical_id": dev.logical_id,
7834
      "physical_id": dev.physical_id,
7835
      "pstatus": dev_pstatus,
7836
      "sstatus": dev_sstatus,
7837
      "children": dev_children,
7838
      "mode": dev.mode,
7839
      "size": dev.size,
7840
      }
7841

    
7842
    return data
7843

    
7844
  def Exec(self, feedback_fn):
7845
    """Gather and return data"""
7846
    result = {}
7847

    
7848
    cluster = self.cfg.GetClusterInfo()
7849

    
7850
    for instance in self.wanted_instances:
7851
      if not self.op.static:
7852
        remote_info = self.rpc.call_instance_info(instance.primary_node,
7853
                                                  instance.name,
7854
                                                  instance.hypervisor)
7855
        remote_info.Raise("Error checking node %s" % instance.primary_node)
7856
        remote_info = remote_info.payload
7857
        if remote_info and "state" in remote_info:
7858
          remote_state = "up"
7859
        else:
7860
          remote_state = "down"
7861
      else:
7862
        remote_state = None
7863
      if instance.admin_up:
7864
        config_state = "up"
7865
      else:
7866
        config_state = "down"
7867

    
7868
      disks = [self._ComputeDiskStatus(instance, None, device)
7869
               for device in instance.disks]
7870

    
7871
      idict = {
7872
        "name": instance.name,
7873
        "config_state": config_state,
7874
        "run_state": remote_state,
7875
        "pnode": instance.primary_node,
7876
        "snodes": instance.secondary_nodes,
7877
        "os": instance.os,
7878
        # this happens to be the same format used for hooks
7879
        "nics": _NICListToTuple(self, instance.nics),
7880
        "disks": disks,
7881
        "hypervisor": instance.hypervisor,
7882
        "network_port": instance.network_port,
7883
        "hv_instance": instance.hvparams,
7884
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
7885
        "be_instance": instance.beparams,
7886
        "be_actual": cluster.FillBE(instance),
7887
        "serial_no": instance.serial_no,
7888
        "mtime": instance.mtime,
7889
        "ctime": instance.ctime,
7890
        "uuid": instance.uuid,
7891
        }
7892

    
7893
      result[instance.name] = idict
7894

    
7895
    return result
7896

    
7897

    
7898
class LUSetInstanceParams(LogicalUnit):
7899
  """Modifies an instances's parameters.
7900

7901
  """
7902
  HPATH = "instance-modify"
7903
  HTYPE = constants.HTYPE_INSTANCE
7904
  _OP_REQP = ["instance_name"]
7905
  REQ_BGL = False
7906

    
7907
  def CheckArguments(self):
7908
    if not hasattr(self.op, 'nics'):
7909
      self.op.nics = []
7910
    if not hasattr(self.op, 'disks'):
7911
      self.op.disks = []
7912
    if not hasattr(self.op, 'beparams'):
7913
      self.op.beparams = {}
7914
    if not hasattr(self.op, 'hvparams'):
7915
      self.op.hvparams = {}
7916
    if not hasattr(self.op, "disk_template"):
7917
      self.op.disk_template = None
7918
    if not hasattr(self.op, "remote_node"):
7919
      self.op.remote_node = None
7920
    if not hasattr(self.op, "os_name"):
7921
      self.op.os_name = None
7922
    if not hasattr(self.op, "force_variant"):
7923
      self.op.force_variant = False
7924
    self.op.force = getattr(self.op, "force", False)
7925
    if not (self.op.nics or self.op.disks or self.op.disk_template or
7926
            self.op.hvparams or self.op.beparams or self.op.os_name):
7927
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
7928

    
7929
    if self.op.hvparams:
7930
      _CheckGlobalHvParams(self.op.hvparams)
7931

    
7932
    # Disk validation
7933
    disk_addremove = 0
7934
    for disk_op, disk_dict in self.op.disks:
7935
      if disk_op == constants.DDM_REMOVE:
7936
        disk_addremove += 1
7937
        continue
7938
      elif disk_op == constants.DDM_ADD:
7939
        disk_addremove += 1
7940
      else:
7941
        if not isinstance(disk_op, int):
7942
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
7943
        if not isinstance(disk_dict, dict):
7944
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
7945
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7946

    
7947
      if disk_op == constants.DDM_ADD:
7948
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
7949
        if mode not in constants.DISK_ACCESS_SET:
7950
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
7951
                                     errors.ECODE_INVAL)
7952
        size = disk_dict.get('size', None)
7953
        if size is None:
7954
          raise errors.OpPrereqError("Required disk parameter size missing",
7955
                                     errors.ECODE_INVAL)
7956
        try:
7957
          size = int(size)
7958
        except (TypeError, ValueError), err:
7959
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
7960
                                     str(err), errors.ECODE_INVAL)
7961
        disk_dict['size'] = size
7962
      else:
7963
        # modification of disk
7964
        if 'size' in disk_dict:
7965
          raise errors.OpPrereqError("Disk size change not possible, use"
7966
                                     " grow-disk", errors.ECODE_INVAL)
7967

    
7968
    if disk_addremove > 1:
7969
      raise errors.OpPrereqError("Only one disk add or remove operation"
7970
                                 " supported at a time", errors.ECODE_INVAL)
7971

    
7972
    if self.op.disks and self.op.disk_template is not None:
7973
      raise errors.OpPrereqError("Disk template conversion and other disk"
7974
                                 " changes not supported at the same time",
7975
                                 errors.ECODE_INVAL)
7976

    
7977
    if self.op.disk_template:
7978
      _CheckDiskTemplate(self.op.disk_template)
7979
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
7980
          self.op.remote_node is None):
7981
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
7982
                                   " one requires specifying a secondary node",
7983
                                   errors.ECODE_INVAL)
7984

    
7985
    # NIC validation
7986
    nic_addremove = 0
7987
    for nic_op, nic_dict in self.op.nics:
7988
      if nic_op == constants.DDM_REMOVE:
7989
        nic_addremove += 1
7990
        continue
7991
      elif nic_op == constants.DDM_ADD:
7992
        nic_addremove += 1
7993
      else:
7994
        if not isinstance(nic_op, int):
7995
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
7996
        if not isinstance(nic_dict, dict):
7997
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
7998
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7999

    
8000
      # nic_dict should be a dict
8001
      nic_ip = nic_dict.get('ip', None)
8002
      if nic_ip is not None:
8003
        if nic_ip.lower() == constants.VALUE_NONE:
8004
          nic_dict['ip'] = None
8005
        else:
8006
          if not utils.IsValidIP(nic_ip):
8007
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8008
                                       errors.ECODE_INVAL)
8009

    
8010
      nic_bridge = nic_dict.get('bridge', None)
8011
      nic_link = nic_dict.get('link', None)
8012
      if nic_bridge and nic_link:
8013
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8014
                                   " at the same time", errors.ECODE_INVAL)
8015
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8016
        nic_dict['bridge'] = None
8017
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8018
        nic_dict['link'] = None
8019

    
8020
      if nic_op == constants.DDM_ADD:
8021
        nic_mac = nic_dict.get('mac', None)
8022
        if nic_mac is None:
8023
          nic_dict['mac'] = constants.VALUE_AUTO
8024

    
8025
      if 'mac' in nic_dict:
8026
        nic_mac = nic_dict['mac']
8027
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8028
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8029

    
8030
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8031
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8032
                                     " modifying an existing nic",
8033
                                     errors.ECODE_INVAL)
8034

    
8035
    if nic_addremove > 1:
8036
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8037
                                 " supported at a time", errors.ECODE_INVAL)
8038

    
8039
  def ExpandNames(self):
8040
    self._ExpandAndLockInstance()
8041
    self.needed_locks[locking.LEVEL_NODE] = []
8042
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8043

    
8044
  def DeclareLocks(self, level):
8045
    if level == locking.LEVEL_NODE:
8046
      self._LockInstancesNodes()
8047
      if self.op.disk_template and self.op.remote_node:
8048
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8049
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8050

    
8051
  def BuildHooksEnv(self):
8052
    """Build hooks env.
8053

8054
    This runs on the master, primary and secondaries.
8055

8056
    """
8057
    args = dict()
8058
    if constants.BE_MEMORY in self.be_new:
8059
      args['memory'] = self.be_new[constants.BE_MEMORY]
8060
    if constants.BE_VCPUS in self.be_new:
8061
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8062
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8063
    # information at all.
8064
    if self.op.nics:
8065
      args['nics'] = []
8066
      nic_override = dict(self.op.nics)
8067
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
8068
      for idx, nic in enumerate(self.instance.nics):
8069
        if idx in nic_override:
8070
          this_nic_override = nic_override[idx]
8071
        else:
8072
          this_nic_override = {}
8073
        if 'ip' in this_nic_override:
8074
          ip = this_nic_override['ip']
8075
        else:
8076
          ip = nic.ip
8077
        if 'mac' in this_nic_override:
8078
          mac = this_nic_override['mac']
8079
        else:
8080
          mac = nic.mac
8081
        if idx in self.nic_pnew:
8082
          nicparams = self.nic_pnew[idx]
8083
        else:
8084
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
8085
        mode = nicparams[constants.NIC_MODE]
8086
        link = nicparams[constants.NIC_LINK]
8087
        args['nics'].append((ip, mac, mode, link))
8088
      if constants.DDM_ADD in nic_override:
8089
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8090
        mac = nic_override[constants.DDM_ADD]['mac']
8091
        nicparams = self.nic_pnew[constants.DDM_ADD]
8092
        mode = nicparams[constants.NIC_MODE]
8093
        link = nicparams[constants.NIC_LINK]
8094
        args['nics'].append((ip, mac, mode, link))
8095
      elif constants.DDM_REMOVE in nic_override:
8096
        del args['nics'][-1]
8097

    
8098
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8099
    if self.op.disk_template:
8100
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8101
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8102
    return env, nl, nl
8103

    
8104
  @staticmethod
8105
  def _GetUpdatedParams(old_params, update_dict,
8106
                        default_values, parameter_types):
8107
    """Return the new params dict for the given params.
8108

8109
    @type old_params: dict
8110
    @param old_params: old parameters
8111
    @type update_dict: dict
8112
    @param update_dict: dict containing new parameter values,
8113
                        or constants.VALUE_DEFAULT to reset the
8114
                        parameter to its default value
8115
    @type default_values: dict
8116
    @param default_values: default values for the filled parameters
8117
    @type parameter_types: dict
8118
    @param parameter_types: dict mapping target dict keys to types
8119
                            in constants.ENFORCEABLE_TYPES
8120
    @rtype: (dict, dict)
8121
    @return: (new_parameters, filled_parameters)
8122

8123
    """
8124
    params_copy = copy.deepcopy(old_params)
8125
    for key, val in update_dict.iteritems():
8126
      if val == constants.VALUE_DEFAULT:
8127
        try:
8128
          del params_copy[key]
8129
        except KeyError:
8130
          pass
8131
      else:
8132
        params_copy[key] = val
8133
    utils.ForceDictType(params_copy, parameter_types)
8134
    params_filled = objects.FillDict(default_values, params_copy)
8135
    return (params_copy, params_filled)
8136

    
8137
  def CheckPrereq(self):
8138
    """Check prerequisites.
8139

8140
    This only checks the instance list against the existing names.
8141

8142
    """
8143
    self.force = self.op.force
8144

    
8145
    # checking the new params on the primary/secondary nodes
8146

    
8147
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8148
    cluster = self.cluster = self.cfg.GetClusterInfo()
8149
    assert self.instance is not None, \
8150
      "Cannot retrieve locked instance %s" % self.op.instance_name
8151
    pnode = instance.primary_node
8152
    nodelist = list(instance.all_nodes)
8153

    
8154
    if self.op.disk_template:
8155
      if instance.disk_template == self.op.disk_template:
8156
        raise errors.OpPrereqError("Instance already has disk template %s" %
8157
                                   instance.disk_template, errors.ECODE_INVAL)
8158

    
8159
      if (instance.disk_template,
8160
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8161
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8162
                                   " %s to %s" % (instance.disk_template,
8163
                                                  self.op.disk_template),
8164
                                   errors.ECODE_INVAL)
8165
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8166
        _CheckNodeOnline(self, self.op.remote_node)
8167
        _CheckNodeNotDrained(self, self.op.remote_node)
8168
        disks = [{"size": d.size} for d in instance.disks]
8169
        required = _ComputeDiskSize(self.op.disk_template, disks)
8170
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8171
        _CheckInstanceDown(self, instance, "cannot change disk template")
8172

    
8173
    # hvparams processing
8174
    if self.op.hvparams:
8175
      i_hvdict, hv_new = self._GetUpdatedParams(
8176
                             instance.hvparams, self.op.hvparams,
8177
                             cluster.hvparams[instance.hypervisor],
8178
                             constants.HVS_PARAMETER_TYPES)
8179
      # local check
8180
      hypervisor.GetHypervisor(
8181
        instance.hypervisor).CheckParameterSyntax(hv_new)
8182
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8183
      self.hv_new = hv_new # the new actual values
8184
      self.hv_inst = i_hvdict # the new dict (without defaults)
8185
    else:
8186
      self.hv_new = self.hv_inst = {}
8187

    
8188
    # beparams processing
8189
    if self.op.beparams:
8190
      i_bedict, be_new = self._GetUpdatedParams(
8191
                             instance.beparams, self.op.beparams,
8192
                             cluster.beparams[constants.PP_DEFAULT],
8193
                             constants.BES_PARAMETER_TYPES)
8194
      self.be_new = be_new # the new actual values
8195
      self.be_inst = i_bedict # the new dict (without defaults)
8196
    else:
8197
      self.be_new = self.be_inst = {}
8198

    
8199
    self.warn = []
8200

    
8201
    if constants.BE_MEMORY in self.op.beparams and not self.force:
8202
      mem_check_list = [pnode]
8203
      if be_new[constants.BE_AUTO_BALANCE]:
8204
        # either we changed auto_balance to yes or it was from before
8205
        mem_check_list.extend(instance.secondary_nodes)
8206
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8207
                                                  instance.hypervisor)
8208
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8209
                                         instance.hypervisor)
8210
      pninfo = nodeinfo[pnode]
8211
      msg = pninfo.fail_msg
8212
      if msg:
8213
        # Assume the primary node is unreachable and go ahead
8214
        self.warn.append("Can't get info from primary node %s: %s" %
8215
                         (pnode,  msg))
8216
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8217
        self.warn.append("Node data from primary node %s doesn't contain"
8218
                         " free memory information" % pnode)
8219
      elif instance_info.fail_msg:
8220
        self.warn.append("Can't get instance runtime information: %s" %
8221
                        instance_info.fail_msg)
8222
      else:
8223
        if instance_info.payload:
8224
          current_mem = int(instance_info.payload['memory'])
8225
        else:
8226
          # Assume instance not running
8227
          # (there is a slight race condition here, but it's not very probable,
8228
          # and we have no other way to check)
8229
          current_mem = 0
8230
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8231
                    pninfo.payload['memory_free'])
8232
        if miss_mem > 0:
8233
          raise errors.OpPrereqError("This change will prevent the instance"
8234
                                     " from starting, due to %d MB of memory"
8235
                                     " missing on its primary node" % miss_mem,
8236
                                     errors.ECODE_NORES)
8237

    
8238
      if be_new[constants.BE_AUTO_BALANCE]:
8239
        for node, nres in nodeinfo.items():
8240
          if node not in instance.secondary_nodes:
8241
            continue
8242
          msg = nres.fail_msg
8243
          if msg:
8244
            self.warn.append("Can't get info from secondary node %s: %s" %
8245
                             (node, msg))
8246
          elif not isinstance(nres.payload.get('memory_free', None), int):
8247
            self.warn.append("Secondary node %s didn't return free"
8248
                             " memory information" % node)
8249
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8250
            self.warn.append("Not enough memory to failover instance to"
8251
                             " secondary node %s" % node)
8252

    
8253
    # NIC processing
8254
    self.nic_pnew = {}
8255
    self.nic_pinst = {}
8256
    for nic_op, nic_dict in self.op.nics:
8257
      if nic_op == constants.DDM_REMOVE:
8258
        if not instance.nics:
8259
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8260
                                     errors.ECODE_INVAL)
8261
        continue
8262
      if nic_op != constants.DDM_ADD:
8263
        # an existing nic
8264
        if not instance.nics:
8265
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8266
                                     " no NICs" % nic_op,
8267
                                     errors.ECODE_INVAL)
8268
        if nic_op < 0 or nic_op >= len(instance.nics):
8269
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8270
                                     " are 0 to %d" %
8271
                                     (nic_op, len(instance.nics) - 1),
8272
                                     errors.ECODE_INVAL)
8273
        old_nic_params = instance.nics[nic_op].nicparams
8274
        old_nic_ip = instance.nics[nic_op].ip
8275
      else:
8276
        old_nic_params = {}
8277
        old_nic_ip = None
8278

    
8279
      update_params_dict = dict([(key, nic_dict[key])
8280
                                 for key in constants.NICS_PARAMETERS
8281
                                 if key in nic_dict])
8282

    
8283
      if 'bridge' in nic_dict:
8284
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8285

    
8286
      new_nic_params, new_filled_nic_params = \
8287
          self._GetUpdatedParams(old_nic_params, update_params_dict,
8288
                                 cluster.nicparams[constants.PP_DEFAULT],
8289
                                 constants.NICS_PARAMETER_TYPES)
8290
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8291
      self.nic_pinst[nic_op] = new_nic_params
8292
      self.nic_pnew[nic_op] = new_filled_nic_params
8293
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8294

    
8295
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8296
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8297
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8298
        if msg:
8299
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8300
          if self.force:
8301
            self.warn.append(msg)
8302
          else:
8303
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8304
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8305
        if 'ip' in nic_dict:
8306
          nic_ip = nic_dict['ip']
8307
        else:
8308
          nic_ip = old_nic_ip
8309
        if nic_ip is None:
8310
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8311
                                     ' on a routed nic', errors.ECODE_INVAL)
8312
      if 'mac' in nic_dict:
8313
        nic_mac = nic_dict['mac']
8314
        if nic_mac is None:
8315
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8316
                                     errors.ECODE_INVAL)
8317
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8318
          # otherwise generate the mac
8319
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8320
        else:
8321
          # or validate/reserve the current one
8322
          try:
8323
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8324
          except errors.ReservationError:
8325
            raise errors.OpPrereqError("MAC address %s already in use"
8326
                                       " in cluster" % nic_mac,
8327
                                       errors.ECODE_NOTUNIQUE)
8328

    
8329
    # DISK processing
8330
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8331
      raise errors.OpPrereqError("Disk operations not supported for"
8332
                                 " diskless instances",
8333
                                 errors.ECODE_INVAL)
8334
    for disk_op, _ in self.op.disks:
8335
      if disk_op == constants.DDM_REMOVE:
8336
        if len(instance.disks) == 1:
8337
          raise errors.OpPrereqError("Cannot remove the last disk of"
8338
                                     " an instance", errors.ECODE_INVAL)
8339
        _CheckInstanceDown(self, instance, "cannot remove disks")
8340

    
8341
      if (disk_op == constants.DDM_ADD and
8342
          len(instance.nics) >= constants.MAX_DISKS):
8343
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8344
                                   " add more" % constants.MAX_DISKS,
8345
                                   errors.ECODE_STATE)
8346
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8347
        # an existing disk
8348
        if disk_op < 0 or disk_op >= len(instance.disks):
8349
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8350
                                     " are 0 to %d" %
8351
                                     (disk_op, len(instance.disks)),
8352
                                     errors.ECODE_INVAL)
8353

    
8354
    # OS change
8355
    if self.op.os_name and not self.op.force:
8356
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8357
                      self.op.force_variant)
8358

    
8359
    return
8360

    
8361
  def _ConvertPlainToDrbd(self, feedback_fn):
8362
    """Converts an instance from plain to drbd.
8363

8364
    """
8365
    feedback_fn("Converting template to drbd")
8366
    instance = self.instance
8367
    pnode = instance.primary_node
8368
    snode = self.op.remote_node
8369

    
8370
    # create a fake disk info for _GenerateDiskTemplate
8371
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
8372
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
8373
                                      instance.name, pnode, [snode],
8374
                                      disk_info, None, None, 0)
8375
    info = _GetInstanceInfoText(instance)
8376
    feedback_fn("Creating aditional volumes...")
8377
    # first, create the missing data and meta devices
8378
    for disk in new_disks:
8379
      # unfortunately this is... not too nice
8380
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
8381
                            info, True)
8382
      for child in disk.children:
8383
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
8384
    # at this stage, all new LVs have been created, we can rename the
8385
    # old ones
8386
    feedback_fn("Renaming original volumes...")
8387
    rename_list = [(o, n.children[0].logical_id)
8388
                   for (o, n) in zip(instance.disks, new_disks)]
8389
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
8390
    result.Raise("Failed to rename original LVs")
8391

    
8392
    feedback_fn("Initializing DRBD devices...")
8393
    # all child devices are in place, we can now create the DRBD devices
8394
    for disk in new_disks:
8395
      for node in [pnode, snode]:
8396
        f_create = node == pnode
8397
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
8398

    
8399
    # at this point, the instance has been modified
8400
    instance.disk_template = constants.DT_DRBD8
8401
    instance.disks = new_disks
8402
    self.cfg.Update(instance, feedback_fn)
8403

    
8404
    # disks are created, waiting for sync
8405
    disk_abort = not _WaitForSync(self, instance)
8406
    if disk_abort:
8407
      raise errors.OpExecError("There are some degraded disks for"
8408
                               " this instance, please cleanup manually")
8409

    
8410
  def _ConvertDrbdToPlain(self, feedback_fn):
8411
    """Converts an instance from drbd to plain.
8412

8413
    """
8414
    instance = self.instance
8415
    assert len(instance.secondary_nodes) == 1
8416
    pnode = instance.primary_node
8417
    snode = instance.secondary_nodes[0]
8418
    feedback_fn("Converting template to plain")
8419

    
8420
    old_disks = instance.disks
8421
    new_disks = [d.children[0] for d in old_disks]
8422

    
8423
    # copy over size and mode
8424
    for parent, child in zip(old_disks, new_disks):
8425
      child.size = parent.size
8426
      child.mode = parent.mode
8427

    
8428
    # update instance structure
8429
    instance.disks = new_disks
8430
    instance.disk_template = constants.DT_PLAIN
8431
    self.cfg.Update(instance, feedback_fn)
8432

    
8433
    feedback_fn("Removing volumes on the secondary node...")
8434
    for disk in old_disks:
8435
      self.cfg.SetDiskID(disk, snode)
8436
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
8437
      if msg:
8438
        self.LogWarning("Could not remove block device %s on node %s,"
8439
                        " continuing anyway: %s", disk.iv_name, snode, msg)
8440

    
8441
    feedback_fn("Removing unneeded volumes on the primary node...")
8442
    for idx, disk in enumerate(old_disks):
8443
      meta = disk.children[1]
8444
      self.cfg.SetDiskID(meta, pnode)
8445
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
8446
      if msg:
8447
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
8448
                        " continuing anyway: %s", idx, pnode, msg)
8449

    
8450

    
8451
  def Exec(self, feedback_fn):
8452
    """Modifies an instance.
8453

8454
    All parameters take effect only at the next restart of the instance.
8455

8456
    """
8457
    # Process here the warnings from CheckPrereq, as we don't have a
8458
    # feedback_fn there.
8459
    for warn in self.warn:
8460
      feedback_fn("WARNING: %s" % warn)
8461

    
8462
    result = []
8463
    instance = self.instance
8464
    # disk changes
8465
    for disk_op, disk_dict in self.op.disks:
8466
      if disk_op == constants.DDM_REMOVE:
8467
        # remove the last disk
8468
        device = instance.disks.pop()
8469
        device_idx = len(instance.disks)
8470
        for node, disk in device.ComputeNodeTree(instance.primary_node):
8471
          self.cfg.SetDiskID(disk, node)
8472
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
8473
          if msg:
8474
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
8475
                            " continuing anyway", device_idx, node, msg)
8476
        result.append(("disk/%d" % device_idx, "remove"))
8477
      elif disk_op == constants.DDM_ADD:
8478
        # add a new disk
8479
        if instance.disk_template == constants.DT_FILE:
8480
          file_driver, file_path = instance.disks[0].logical_id
8481
          file_path = os.path.dirname(file_path)
8482
        else:
8483
          file_driver = file_path = None
8484
        disk_idx_base = len(instance.disks)
8485
        new_disk = _GenerateDiskTemplate(self,
8486
                                         instance.disk_template,
8487
                                         instance.name, instance.primary_node,
8488
                                         instance.secondary_nodes,
8489
                                         [disk_dict],
8490
                                         file_path,
8491
                                         file_driver,
8492
                                         disk_idx_base)[0]
8493
        instance.disks.append(new_disk)
8494
        info = _GetInstanceInfoText(instance)
8495

    
8496
        logging.info("Creating volume %s for instance %s",
8497
                     new_disk.iv_name, instance.name)
8498
        # Note: this needs to be kept in sync with _CreateDisks
8499
        #HARDCODE
8500
        for node in instance.all_nodes:
8501
          f_create = node == instance.primary_node
8502
          try:
8503
            _CreateBlockDev(self, node, instance, new_disk,
8504
                            f_create, info, f_create)
8505
          except errors.OpExecError, err:
8506
            self.LogWarning("Failed to create volume %s (%s) on"
8507
                            " node %s: %s",
8508
                            new_disk.iv_name, new_disk, node, err)
8509
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
8510
                       (new_disk.size, new_disk.mode)))
8511
      else:
8512
        # change a given disk
8513
        instance.disks[disk_op].mode = disk_dict['mode']
8514
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
8515

    
8516
    if self.op.disk_template:
8517
      r_shut = _ShutdownInstanceDisks(self, instance)
8518
      if not r_shut:
8519
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
8520
                                 " proceed with disk template conversion")
8521
      mode = (instance.disk_template, self.op.disk_template)
8522
      try:
8523
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
8524
      except:
8525
        self.cfg.ReleaseDRBDMinors(instance.name)
8526
        raise
8527
      result.append(("disk_template", self.op.disk_template))
8528

    
8529
    # NIC changes
8530
    for nic_op, nic_dict in self.op.nics:
8531
      if nic_op == constants.DDM_REMOVE:
8532
        # remove the last nic
8533
        del instance.nics[-1]
8534
        result.append(("nic.%d" % len(instance.nics), "remove"))
8535
      elif nic_op == constants.DDM_ADD:
8536
        # mac and bridge should be set, by now
8537
        mac = nic_dict['mac']
8538
        ip = nic_dict.get('ip', None)
8539
        nicparams = self.nic_pinst[constants.DDM_ADD]
8540
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
8541
        instance.nics.append(new_nic)
8542
        result.append(("nic.%d" % (len(instance.nics) - 1),
8543
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
8544
                       (new_nic.mac, new_nic.ip,
8545
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
8546
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
8547
                       )))
8548
      else:
8549
        for key in 'mac', 'ip':
8550
          if key in nic_dict:
8551
            setattr(instance.nics[nic_op], key, nic_dict[key])
8552
        if nic_op in self.nic_pinst:
8553
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
8554
        for key, val in nic_dict.iteritems():
8555
          result.append(("nic.%s/%d" % (key, nic_op), val))
8556

    
8557
    # hvparams changes
8558
    if self.op.hvparams:
8559
      instance.hvparams = self.hv_inst
8560
      for key, val in self.op.hvparams.iteritems():
8561
        result.append(("hv/%s" % key, val))
8562

    
8563
    # beparams changes
8564
    if self.op.beparams:
8565
      instance.beparams = self.be_inst
8566
      for key, val in self.op.beparams.iteritems():
8567
        result.append(("be/%s" % key, val))
8568

    
8569
    # OS change
8570
    if self.op.os_name:
8571
      instance.os = self.op.os_name
8572

    
8573
    self.cfg.Update(instance, feedback_fn)
8574

    
8575
    return result
8576

    
8577
  _DISK_CONVERSIONS = {
8578
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
8579
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
8580
    }
8581

    
8582
class LUQueryExports(NoHooksLU):
8583
  """Query the exports list
8584

8585
  """
8586
  _OP_REQP = ['nodes']
8587
  REQ_BGL = False
8588

    
8589
  def ExpandNames(self):
8590
    self.needed_locks = {}
8591
    self.share_locks[locking.LEVEL_NODE] = 1
8592
    if not self.op.nodes:
8593
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8594
    else:
8595
      self.needed_locks[locking.LEVEL_NODE] = \
8596
        _GetWantedNodes(self, self.op.nodes)
8597

    
8598
  def CheckPrereq(self):
8599
    """Check prerequisites.
8600

8601
    """
8602
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
8603

    
8604
  def Exec(self, feedback_fn):
8605
    """Compute the list of all the exported system images.
8606

8607
    @rtype: dict
8608
    @return: a dictionary with the structure node->(export-list)
8609
        where export-list is a list of the instances exported on
8610
        that node.
8611

8612
    """
8613
    rpcresult = self.rpc.call_export_list(self.nodes)
8614
    result = {}
8615
    for node in rpcresult:
8616
      if rpcresult[node].fail_msg:
8617
        result[node] = False
8618
      else:
8619
        result[node] = rpcresult[node].payload
8620

    
8621
    return result
8622

    
8623

    
8624
class LUExportInstance(LogicalUnit):
8625
  """Export an instance to an image in the cluster.
8626

8627
  """
8628
  HPATH = "instance-export"
8629
  HTYPE = constants.HTYPE_INSTANCE
8630
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
8631
  REQ_BGL = False
8632

    
8633
  def CheckArguments(self):
8634
    """Check the arguments.
8635

8636
    """
8637
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
8638
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
8639

    
8640
  def ExpandNames(self):
8641
    self._ExpandAndLockInstance()
8642
    # FIXME: lock only instance primary and destination node
8643
    #
8644
    # Sad but true, for now we have do lock all nodes, as we don't know where
8645
    # the previous export might be, and and in this LU we search for it and
8646
    # remove it from its current node. In the future we could fix this by:
8647
    #  - making a tasklet to search (share-lock all), then create the new one,
8648
    #    then one to remove, after
8649
    #  - removing the removal operation altogether
8650
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8651

    
8652
  def DeclareLocks(self, level):
8653
    """Last minute lock declaration."""
8654
    # All nodes are locked anyway, so nothing to do here.
8655

    
8656
  def BuildHooksEnv(self):
8657
    """Build hooks env.
8658

8659
    This will run on the master, primary node and target node.
8660

8661
    """
8662
    env = {
8663
      "EXPORT_NODE": self.op.target_node,
8664
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
8665
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
8666
      }
8667
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8668
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
8669
          self.op.target_node]
8670
    return env, nl, nl
8671

    
8672
  def CheckPrereq(self):
8673
    """Check prerequisites.
8674

8675
    This checks that the instance and node names are valid.
8676

8677
    """
8678
    instance_name = self.op.instance_name
8679
    self.instance = self.cfg.GetInstanceInfo(instance_name)
8680
    assert self.instance is not None, \
8681
          "Cannot retrieve locked instance %s" % self.op.instance_name
8682
    _CheckNodeOnline(self, self.instance.primary_node)
8683

    
8684
    self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
8685
    self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
8686
    assert self.dst_node is not None
8687

    
8688
    _CheckNodeOnline(self, self.dst_node.name)
8689
    _CheckNodeNotDrained(self, self.dst_node.name)
8690

    
8691
    # instance disk type verification
8692
    for disk in self.instance.disks:
8693
      if disk.dev_type == constants.LD_FILE:
8694
        raise errors.OpPrereqError("Export not supported for instances with"
8695
                                   " file-based disks", errors.ECODE_INVAL)
8696

    
8697
  def Exec(self, feedback_fn):
8698
    """Export an instance to an image in the cluster.
8699

8700
    """
8701
    instance = self.instance
8702
    dst_node = self.dst_node
8703
    src_node = instance.primary_node
8704

    
8705
    if self.op.shutdown:
8706
      # shutdown the instance, but not the disks
8707
      feedback_fn("Shutting down instance %s" % instance.name)
8708
      result = self.rpc.call_instance_shutdown(src_node, instance,
8709
                                               self.shutdown_timeout)
8710
      result.Raise("Could not shutdown instance %s on"
8711
                   " node %s" % (instance.name, src_node))
8712

    
8713
    vgname = self.cfg.GetVGName()
8714

    
8715
    snap_disks = []
8716

    
8717
    # set the disks ID correctly since call_instance_start needs the
8718
    # correct drbd minor to create the symlinks
8719
    for disk in instance.disks:
8720
      self.cfg.SetDiskID(disk, src_node)
8721

    
8722
    activate_disks = (not instance.admin_up)
8723

    
8724
    if activate_disks:
8725
      # Activate the instance disks if we'exporting a stopped instance
8726
      feedback_fn("Activating disks for %s" % instance.name)
8727
      _StartInstanceDisks(self, instance, None)
8728

    
8729
    try:
8730
      # per-disk results
8731
      dresults = []
8732
      try:
8733
        for idx, disk in enumerate(instance.disks):
8734
          feedback_fn("Creating a snapshot of disk/%s on node %s" %
8735
                      (idx, src_node))
8736

    
8737
          # result.payload will be a snapshot of an lvm leaf of the one we
8738
          # passed
8739
          result = self.rpc.call_blockdev_snapshot(src_node, disk)
8740
          msg = result.fail_msg
8741
          if msg:
8742
            self.LogWarning("Could not snapshot disk/%s on node %s: %s",
8743
                            idx, src_node, msg)
8744
            snap_disks.append(False)
8745
          else:
8746
            disk_id = (vgname, result.payload)
8747
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
8748
                                   logical_id=disk_id, physical_id=disk_id,
8749
                                   iv_name=disk.iv_name)
8750
            snap_disks.append(new_dev)
8751

    
8752
      finally:
8753
        if self.op.shutdown and instance.admin_up:
8754
          feedback_fn("Starting instance %s" % instance.name)
8755
          result = self.rpc.call_instance_start(src_node, instance, None, None)
8756
          msg = result.fail_msg
8757
          if msg:
8758
            _ShutdownInstanceDisks(self, instance)
8759
            raise errors.OpExecError("Could not start instance: %s" % msg)
8760

    
8761
      # TODO: check for size
8762

    
8763
      cluster_name = self.cfg.GetClusterName()
8764
      for idx, dev in enumerate(snap_disks):
8765
        feedback_fn("Exporting snapshot %s from %s to %s" %
8766
                    (idx, src_node, dst_node.name))
8767
        if dev:
8768
          # FIXME: pass debug from opcode to backend
8769
          result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
8770
                                                 instance, cluster_name,
8771
                                                 idx, self.op.debug_level)
8772
          msg = result.fail_msg
8773
          if msg:
8774
            self.LogWarning("Could not export disk/%s from node %s to"
8775
                            " node %s: %s", idx, src_node, dst_node.name, msg)
8776
            dresults.append(False)
8777
          else:
8778
            dresults.append(True)
8779
          msg = self.rpc.call_blockdev_remove(src_node, dev).fail_msg
8780
          if msg:
8781
            self.LogWarning("Could not remove snapshot for disk/%d from node"
8782
                            " %s: %s", idx, src_node, msg)
8783
        else:
8784
          dresults.append(False)
8785

    
8786
      feedback_fn("Finalizing export on %s" % dst_node.name)
8787
      result = self.rpc.call_finalize_export(dst_node.name, instance,
8788
                                             snap_disks)
8789
      fin_resu = True
8790
      msg = result.fail_msg
8791
      if msg:
8792
        self.LogWarning("Could not finalize export for instance %s"
8793
                        " on node %s: %s", instance.name, dst_node.name, msg)
8794
        fin_resu = False
8795

    
8796
    finally:
8797
      if activate_disks:
8798
        feedback_fn("Deactivating disks for %s" % instance.name)
8799
        _ShutdownInstanceDisks(self, instance)
8800

    
8801
    nodelist = self.cfg.GetNodeList()
8802
    nodelist.remove(dst_node.name)
8803

    
8804
    # on one-node clusters nodelist will be empty after the removal
8805
    # if we proceed the backup would be removed because OpQueryExports
8806
    # substitutes an empty list with the full cluster node list.
8807
    iname = instance.name
8808
    if nodelist:
8809
      feedback_fn("Removing old exports for instance %s" % iname)
8810
      exportlist = self.rpc.call_export_list(nodelist)
8811
      for node in exportlist:
8812
        if exportlist[node].fail_msg:
8813
          continue
8814
        if iname in exportlist[node].payload:
8815
          msg = self.rpc.call_export_remove(node, iname).fail_msg
8816
          if msg:
8817
            self.LogWarning("Could not remove older export for instance %s"
8818
                            " on node %s: %s", iname, node, msg)
8819
    return fin_resu, dresults
8820

    
8821

    
8822
class LURemoveExport(NoHooksLU):
8823
  """Remove exports related to the named instance.
8824

8825
  """
8826
  _OP_REQP = ["instance_name"]
8827
  REQ_BGL = False
8828

    
8829
  def ExpandNames(self):
8830
    self.needed_locks = {}
8831
    # We need all nodes to be locked in order for RemoveExport to work, but we
8832
    # don't need to lock the instance itself, as nothing will happen to it (and
8833
    # we can remove exports also for a removed instance)
8834
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8835

    
8836
  def CheckPrereq(self):
8837
    """Check prerequisites.
8838
    """
8839
    pass
8840

    
8841
  def Exec(self, feedback_fn):
8842
    """Remove any export.
8843

8844
    """
8845
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
8846
    # If the instance was not found we'll try with the name that was passed in.
8847
    # This will only work if it was an FQDN, though.
8848
    fqdn_warn = False
8849
    if not instance_name:
8850
      fqdn_warn = True
8851
      instance_name = self.op.instance_name
8852

    
8853
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
8854
    exportlist = self.rpc.call_export_list(locked_nodes)
8855
    found = False
8856
    for node in exportlist:
8857
      msg = exportlist[node].fail_msg
8858
      if msg:
8859
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
8860
        continue
8861
      if instance_name in exportlist[node].payload:
8862
        found = True
8863
        result = self.rpc.call_export_remove(node, instance_name)
8864
        msg = result.fail_msg
8865
        if msg:
8866
          logging.error("Could not remove export for instance %s"
8867
                        " on node %s: %s", instance_name, node, msg)
8868

    
8869
    if fqdn_warn and not found:
8870
      feedback_fn("Export not found. If trying to remove an export belonging"
8871
                  " to a deleted instance please use its Fully Qualified"
8872
                  " Domain Name.")
8873

    
8874

    
8875
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
8876
  """Generic tags LU.
8877

8878
  This is an abstract class which is the parent of all the other tags LUs.
8879

8880
  """
8881

    
8882
  def ExpandNames(self):
8883
    self.needed_locks = {}
8884
    if self.op.kind == constants.TAG_NODE:
8885
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
8886
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
8887
    elif self.op.kind == constants.TAG_INSTANCE:
8888
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
8889
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
8890

    
8891
  def CheckPrereq(self):
8892
    """Check prerequisites.
8893

8894
    """
8895
    if self.op.kind == constants.TAG_CLUSTER:
8896
      self.target = self.cfg.GetClusterInfo()
8897
    elif self.op.kind == constants.TAG_NODE:
8898
      self.target = self.cfg.GetNodeInfo(self.op.name)
8899
    elif self.op.kind == constants.TAG_INSTANCE:
8900
      self.target = self.cfg.GetInstanceInfo(self.op.name)
8901
    else:
8902
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
8903
                                 str(self.op.kind), errors.ECODE_INVAL)
8904

    
8905

    
8906
class LUGetTags(TagsLU):
8907
  """Returns the tags of a given object.
8908

8909
  """
8910
  _OP_REQP = ["kind", "name"]
8911
  REQ_BGL = False
8912

    
8913
  def Exec(self, feedback_fn):
8914
    """Returns the tag list.
8915

8916
    """
8917
    return list(self.target.GetTags())
8918

    
8919

    
8920
class LUSearchTags(NoHooksLU):
8921
  """Searches the tags for a given pattern.
8922

8923
  """
8924
  _OP_REQP = ["pattern"]
8925
  REQ_BGL = False
8926

    
8927
  def ExpandNames(self):
8928
    self.needed_locks = {}
8929

    
8930
  def CheckPrereq(self):
8931
    """Check prerequisites.
8932

8933
    This checks the pattern passed for validity by compiling it.
8934

8935
    """
8936
    try:
8937
      self.re = re.compile(self.op.pattern)
8938
    except re.error, err:
8939
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
8940
                                 (self.op.pattern, err), errors.ECODE_INVAL)
8941

    
8942
  def Exec(self, feedback_fn):
8943
    """Returns the tag list.
8944

8945
    """
8946
    cfg = self.cfg
8947
    tgts = [("/cluster", cfg.GetClusterInfo())]
8948
    ilist = cfg.GetAllInstancesInfo().values()
8949
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
8950
    nlist = cfg.GetAllNodesInfo().values()
8951
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
8952
    results = []
8953
    for path, target in tgts:
8954
      for tag in target.GetTags():
8955
        if self.re.search(tag):
8956
          results.append((path, tag))
8957
    return results
8958

    
8959

    
8960
class LUAddTags(TagsLU):
8961
  """Sets a tag on a given object.
8962

8963
  """
8964
  _OP_REQP = ["kind", "name", "tags"]
8965
  REQ_BGL = False
8966

    
8967
  def CheckPrereq(self):
8968
    """Check prerequisites.
8969

8970
    This checks the type and length of the tag name and value.
8971

8972
    """
8973
    TagsLU.CheckPrereq(self)
8974
    for tag in self.op.tags:
8975
      objects.TaggableObject.ValidateTag(tag)
8976

    
8977
  def Exec(self, feedback_fn):
8978
    """Sets the tag.
8979

8980
    """
8981
    try:
8982
      for tag in self.op.tags:
8983
        self.target.AddTag(tag)
8984
    except errors.TagError, err:
8985
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
8986
    self.cfg.Update(self.target, feedback_fn)
8987

    
8988

    
8989
class LUDelTags(TagsLU):
8990
  """Delete a list of tags from a given object.
8991

8992
  """
8993
  _OP_REQP = ["kind", "name", "tags"]
8994
  REQ_BGL = False
8995

    
8996
  def CheckPrereq(self):
8997
    """Check prerequisites.
8998

8999
    This checks that we have the given tag.
9000

9001
    """
9002
    TagsLU.CheckPrereq(self)
9003
    for tag in self.op.tags:
9004
      objects.TaggableObject.ValidateTag(tag)
9005
    del_tags = frozenset(self.op.tags)
9006
    cur_tags = self.target.GetTags()
9007
    if not del_tags <= cur_tags:
9008
      diff_tags = del_tags - cur_tags
9009
      diff_names = ["'%s'" % tag for tag in diff_tags]
9010
      diff_names.sort()
9011
      raise errors.OpPrereqError("Tag(s) %s not found" %
9012
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9013

    
9014
  def Exec(self, feedback_fn):
9015
    """Remove the tag from the object.
9016

9017
    """
9018
    for tag in self.op.tags:
9019
      self.target.RemoveTag(tag)
9020
    self.cfg.Update(self.target, feedback_fn)
9021

    
9022

    
9023
class LUTestDelay(NoHooksLU):
9024
  """Sleep for a specified amount of time.
9025

9026
  This LU sleeps on the master and/or nodes for a specified amount of
9027
  time.
9028

9029
  """
9030
  _OP_REQP = ["duration", "on_master", "on_nodes"]
9031
  REQ_BGL = False
9032

    
9033
  def ExpandNames(self):
9034
    """Expand names and set required locks.
9035

9036
    This expands the node list, if any.
9037

9038
    """
9039
    self.needed_locks = {}
9040
    if self.op.on_nodes:
9041
      # _GetWantedNodes can be used here, but is not always appropriate to use
9042
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9043
      # more information.
9044
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9045
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9046

    
9047
  def CheckPrereq(self):
9048
    """Check prerequisites.
9049

9050
    """
9051

    
9052
  def Exec(self, feedback_fn):
9053
    """Do the actual sleep.
9054

9055
    """
9056
    if self.op.on_master:
9057
      if not utils.TestDelay(self.op.duration):
9058
        raise errors.OpExecError("Error during master delay test")
9059
    if self.op.on_nodes:
9060
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9061
      for node, node_result in result.items():
9062
        node_result.Raise("Failure during rpc call to node %s" % node)
9063

    
9064

    
9065
class IAllocator(object):
9066
  """IAllocator framework.
9067

9068
  An IAllocator instance has three sets of attributes:
9069
    - cfg that is needed to query the cluster
9070
    - input data (all members of the _KEYS class attribute are required)
9071
    - four buffer attributes (in|out_data|text), that represent the
9072
      input (to the external script) in text and data structure format,
9073
      and the output from it, again in two formats
9074
    - the result variables from the script (success, info, nodes) for
9075
      easy usage
9076

9077
  """
9078
  # pylint: disable-msg=R0902
9079
  # lots of instance attributes
9080
  _ALLO_KEYS = [
9081
    "name", "mem_size", "disks", "disk_template",
9082
    "os", "tags", "nics", "vcpus", "hypervisor",
9083
    ]
9084
  _RELO_KEYS = [
9085
    "name", "relocate_from",
9086
    ]
9087
  _EVAC_KEYS = [
9088
    "evac_nodes",
9089
    ]
9090

    
9091
  def __init__(self, cfg, rpc, mode, **kwargs):
9092
    self.cfg = cfg
9093
    self.rpc = rpc
9094
    # init buffer variables
9095
    self.in_text = self.out_text = self.in_data = self.out_data = None
9096
    # init all input fields so that pylint is happy
9097
    self.mode = mode
9098
    self.mem_size = self.disks = self.disk_template = None
9099
    self.os = self.tags = self.nics = self.vcpus = None
9100
    self.hypervisor = None
9101
    self.relocate_from = None
9102
    self.name = None
9103
    self.evac_nodes = None
9104
    # computed fields
9105
    self.required_nodes = None
9106
    # init result fields
9107
    self.success = self.info = self.result = None
9108
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9109
      keyset = self._ALLO_KEYS
9110
      fn = self._AddNewInstance
9111
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9112
      keyset = self._RELO_KEYS
9113
      fn = self._AddRelocateInstance
9114
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9115
      keyset = self._EVAC_KEYS
9116
      fn = self._AddEvacuateNodes
9117
    else:
9118
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
9119
                                   " IAllocator" % self.mode)
9120
    for key in kwargs:
9121
      if key not in keyset:
9122
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
9123
                                     " IAllocator" % key)
9124
      setattr(self, key, kwargs[key])
9125

    
9126
    for key in keyset:
9127
      if key not in kwargs:
9128
        raise errors.ProgrammerError("Missing input parameter '%s' to"
9129
                                     " IAllocator" % key)
9130
    self._BuildInputData(fn)
9131

    
9132
  def _ComputeClusterData(self):
9133
    """Compute the generic allocator input data.
9134

9135
    This is the data that is independent of the actual operation.
9136

9137
    """
9138
    cfg = self.cfg
9139
    cluster_info = cfg.GetClusterInfo()
9140
    # cluster data
9141
    data = {
9142
      "version": constants.IALLOCATOR_VERSION,
9143
      "cluster_name": cfg.GetClusterName(),
9144
      "cluster_tags": list(cluster_info.GetTags()),
9145
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
9146
      # we don't have job IDs
9147
      }
9148
    iinfo = cfg.GetAllInstancesInfo().values()
9149
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
9150

    
9151
    # node data
9152
    node_results = {}
9153
    node_list = cfg.GetNodeList()
9154

    
9155
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9156
      hypervisor_name = self.hypervisor
9157
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9158
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
9159
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9160
      hypervisor_name = cluster_info.enabled_hypervisors[0]
9161

    
9162
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
9163
                                        hypervisor_name)
9164
    node_iinfo = \
9165
      self.rpc.call_all_instances_info(node_list,
9166
                                       cluster_info.enabled_hypervisors)
9167
    for nname, nresult in node_data.items():
9168
      # first fill in static (config-based) values
9169
      ninfo = cfg.GetNodeInfo(nname)
9170
      pnr = {
9171
        "tags": list(ninfo.GetTags()),
9172
        "primary_ip": ninfo.primary_ip,
9173
        "secondary_ip": ninfo.secondary_ip,
9174
        "offline": ninfo.offline,
9175
        "drained": ninfo.drained,
9176
        "master_candidate": ninfo.master_candidate,
9177
        }
9178

    
9179
      if not (ninfo.offline or ninfo.drained):
9180
        nresult.Raise("Can't get data for node %s" % nname)
9181
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
9182
                                nname)
9183
        remote_info = nresult.payload
9184

    
9185
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
9186
                     'vg_size', 'vg_free', 'cpu_total']:
9187
          if attr not in remote_info:
9188
            raise errors.OpExecError("Node '%s' didn't return attribute"
9189
                                     " '%s'" % (nname, attr))
9190
          if not isinstance(remote_info[attr], int):
9191
            raise errors.OpExecError("Node '%s' returned invalid value"
9192
                                     " for '%s': %s" %
9193
                                     (nname, attr, remote_info[attr]))
9194
        # compute memory used by primary instances
9195
        i_p_mem = i_p_up_mem = 0
9196
        for iinfo, beinfo in i_list:
9197
          if iinfo.primary_node == nname:
9198
            i_p_mem += beinfo[constants.BE_MEMORY]
9199
            if iinfo.name not in node_iinfo[nname].payload:
9200
              i_used_mem = 0
9201
            else:
9202
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
9203
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
9204
            remote_info['memory_free'] -= max(0, i_mem_diff)
9205

    
9206
            if iinfo.admin_up:
9207
              i_p_up_mem += beinfo[constants.BE_MEMORY]
9208

    
9209
        # compute memory used by instances
9210
        pnr_dyn = {
9211
          "total_memory": remote_info['memory_total'],
9212
          "reserved_memory": remote_info['memory_dom0'],
9213
          "free_memory": remote_info['memory_free'],
9214
          "total_disk": remote_info['vg_size'],
9215
          "free_disk": remote_info['vg_free'],
9216
          "total_cpus": remote_info['cpu_total'],
9217
          "i_pri_memory": i_p_mem,
9218
          "i_pri_up_memory": i_p_up_mem,
9219
          }
9220
        pnr.update(pnr_dyn)
9221

    
9222
      node_results[nname] = pnr
9223
    data["nodes"] = node_results
9224

    
9225
    # instance data
9226
    instance_data = {}
9227
    for iinfo, beinfo in i_list:
9228
      nic_data = []
9229
      for nic in iinfo.nics:
9230
        filled_params = objects.FillDict(
9231
            cluster_info.nicparams[constants.PP_DEFAULT],
9232
            nic.nicparams)
9233
        nic_dict = {"mac": nic.mac,
9234
                    "ip": nic.ip,
9235
                    "mode": filled_params[constants.NIC_MODE],
9236
                    "link": filled_params[constants.NIC_LINK],
9237
                   }
9238
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
9239
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
9240
        nic_data.append(nic_dict)
9241
      pir = {
9242
        "tags": list(iinfo.GetTags()),
9243
        "admin_up": iinfo.admin_up,
9244
        "vcpus": beinfo[constants.BE_VCPUS],
9245
        "memory": beinfo[constants.BE_MEMORY],
9246
        "os": iinfo.os,
9247
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
9248
        "nics": nic_data,
9249
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
9250
        "disk_template": iinfo.disk_template,
9251
        "hypervisor": iinfo.hypervisor,
9252
        }
9253
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
9254
                                                 pir["disks"])
9255
      instance_data[iinfo.name] = pir
9256

    
9257
    data["instances"] = instance_data
9258

    
9259
    self.in_data = data
9260

    
9261
  def _AddNewInstance(self):
9262
    """Add new instance data to allocator structure.
9263

9264
    This in combination with _AllocatorGetClusterData will create the
9265
    correct structure needed as input for the allocator.
9266

9267
    The checks for the completeness of the opcode must have already been
9268
    done.
9269

9270
    """
9271
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
9272

    
9273
    if self.disk_template in constants.DTS_NET_MIRROR:
9274
      self.required_nodes = 2
9275
    else:
9276
      self.required_nodes = 1
9277
    request = {
9278
      "name": self.name,
9279
      "disk_template": self.disk_template,
9280
      "tags": self.tags,
9281
      "os": self.os,
9282
      "vcpus": self.vcpus,
9283
      "memory": self.mem_size,
9284
      "disks": self.disks,
9285
      "disk_space_total": disk_space,
9286
      "nics": self.nics,
9287
      "required_nodes": self.required_nodes,
9288
      }
9289
    return request
9290

    
9291
  def _AddRelocateInstance(self):
9292
    """Add relocate instance data to allocator structure.
9293

9294
    This in combination with _IAllocatorGetClusterData will create the
9295
    correct structure needed as input for the allocator.
9296

9297
    The checks for the completeness of the opcode must have already been
9298
    done.
9299

9300
    """
9301
    instance = self.cfg.GetInstanceInfo(self.name)
9302
    if instance is None:
9303
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
9304
                                   " IAllocator" % self.name)
9305

    
9306
    if instance.disk_template not in constants.DTS_NET_MIRROR:
9307
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
9308
                                 errors.ECODE_INVAL)
9309

    
9310
    if len(instance.secondary_nodes) != 1:
9311
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
9312
                                 errors.ECODE_STATE)
9313

    
9314
    self.required_nodes = 1
9315
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
9316
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
9317

    
9318
    request = {
9319
      "name": self.name,
9320
      "disk_space_total": disk_space,
9321
      "required_nodes": self.required_nodes,
9322
      "relocate_from": self.relocate_from,
9323
      }
9324
    return request
9325

    
9326
  def _AddEvacuateNodes(self):
9327
    """Add evacuate nodes data to allocator structure.
9328

9329
    """
9330
    request = {
9331
      "evac_nodes": self.evac_nodes
9332
      }
9333
    return request
9334

    
9335
  def _BuildInputData(self, fn):
9336
    """Build input data structures.
9337

9338
    """
9339
    self._ComputeClusterData()
9340

    
9341
    request = fn()
9342
    request["type"] = self.mode
9343
    self.in_data["request"] = request
9344

    
9345
    self.in_text = serializer.Dump(self.in_data)
9346

    
9347
  def Run(self, name, validate=True, call_fn=None):
9348
    """Run an instance allocator and return the results.
9349

9350
    """
9351
    if call_fn is None:
9352
      call_fn = self.rpc.call_iallocator_runner
9353

    
9354
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
9355
    result.Raise("Failure while running the iallocator script")
9356

    
9357
    self.out_text = result.payload
9358
    if validate:
9359
      self._ValidateResult()
9360

    
9361
  def _ValidateResult(self):
9362
    """Process the allocator results.
9363

9364
    This will process and if successful save the result in
9365
    self.out_data and the other parameters.
9366

9367
    """
9368
    try:
9369
      rdict = serializer.Load(self.out_text)
9370
    except Exception, err:
9371
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
9372

    
9373
    if not isinstance(rdict, dict):
9374
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
9375

    
9376
    # TODO: remove backwards compatiblity in later versions
9377
    if "nodes" in rdict and "result" not in rdict:
9378
      rdict["result"] = rdict["nodes"]
9379
      del rdict["nodes"]
9380

    
9381
    for key in "success", "info", "result":
9382
      if key not in rdict:
9383
        raise errors.OpExecError("Can't parse iallocator results:"
9384
                                 " missing key '%s'" % key)
9385
      setattr(self, key, rdict[key])
9386

    
9387
    if not isinstance(rdict["result"], list):
9388
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
9389
                               " is not a list")
9390
    self.out_data = rdict
9391

    
9392

    
9393
class LUTestAllocator(NoHooksLU):
9394
  """Run allocator tests.
9395

9396
  This LU runs the allocator tests
9397

9398
  """
9399
  _OP_REQP = ["direction", "mode", "name"]
9400

    
9401
  def CheckPrereq(self):
9402
    """Check prerequisites.
9403

9404
    This checks the opcode parameters depending on the director and mode test.
9405

9406
    """
9407
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9408
      for attr in ["name", "mem_size", "disks", "disk_template",
9409
                   "os", "tags", "nics", "vcpus"]:
9410
        if not hasattr(self.op, attr):
9411
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
9412
                                     attr, errors.ECODE_INVAL)
9413
      iname = self.cfg.ExpandInstanceName(self.op.name)
9414
      if iname is not None:
9415
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
9416
                                   iname, errors.ECODE_EXISTS)
9417
      if not isinstance(self.op.nics, list):
9418
        raise errors.OpPrereqError("Invalid parameter 'nics'",
9419
                                   errors.ECODE_INVAL)
9420
      for row in self.op.nics:
9421
        if (not isinstance(row, dict) or
9422
            "mac" not in row or
9423
            "ip" not in row or
9424
            "bridge" not in row):
9425
          raise errors.OpPrereqError("Invalid contents of the 'nics'"
9426
                                     " parameter", errors.ECODE_INVAL)
9427
      if not isinstance(self.op.disks, list):
9428
        raise errors.OpPrereqError("Invalid parameter 'disks'",
9429
                                   errors.ECODE_INVAL)
9430
      for row in self.op.disks:
9431
        if (not isinstance(row, dict) or
9432
            "size" not in row or
9433
            not isinstance(row["size"], int) or
9434
            "mode" not in row or
9435
            row["mode"] not in ['r', 'w']):
9436
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
9437
                                     " parameter", errors.ECODE_INVAL)
9438
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
9439
        self.op.hypervisor = self.cfg.GetHypervisorType()
9440
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9441
      if not hasattr(self.op, "name"):
9442
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input",
9443
                                   errors.ECODE_INVAL)
9444
      fname = _ExpandInstanceName(self.cfg, self.op.name)
9445
      self.op.name = fname
9446
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
9447
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9448
      if not hasattr(self.op, "evac_nodes"):
9449
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
9450
                                   " opcode input", errors.ECODE_INVAL)
9451
    else:
9452
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
9453
                                 self.op.mode, errors.ECODE_INVAL)
9454

    
9455
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
9456
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
9457
        raise errors.OpPrereqError("Missing allocator name",
9458
                                   errors.ECODE_INVAL)
9459
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
9460
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
9461
                                 self.op.direction, errors.ECODE_INVAL)
9462

    
9463
  def Exec(self, feedback_fn):
9464
    """Run the allocator test.
9465

9466
    """
9467
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9468
      ial = IAllocator(self.cfg, self.rpc,
9469
                       mode=self.op.mode,
9470
                       name=self.op.name,
9471
                       mem_size=self.op.mem_size,
9472
                       disks=self.op.disks,
9473
                       disk_template=self.op.disk_template,
9474
                       os=self.op.os,
9475
                       tags=self.op.tags,
9476
                       nics=self.op.nics,
9477
                       vcpus=self.op.vcpus,
9478
                       hypervisor=self.op.hypervisor,
9479
                       )
9480
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9481
      ial = IAllocator(self.cfg, self.rpc,
9482
                       mode=self.op.mode,
9483
                       name=self.op.name,
9484
                       relocate_from=list(self.relocate_from),
9485
                       )
9486
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9487
      ial = IAllocator(self.cfg, self.rpc,
9488
                       mode=self.op.mode,
9489
                       evac_nodes=self.op.evac_nodes)
9490
    else:
9491
      raise errors.ProgrammerError("Uncatched mode %s in"
9492
                                   " LUTestAllocator.Exec", self.op.mode)
9493

    
9494
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
9495
      result = ial.in_text
9496
    else:
9497
      ial.Run(self.op.allocator, validate=False)
9498
      result = ial.out_text
9499
    return result