Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 6d7e1f20

History | View | Annotate | Download (290.9 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=W0613,W0201
25

    
26
import os
27
import os.path
28
import time
29
import re
30
import platform
31
import logging
32
import copy
33

    
34
from ganeti import ssh
35
from ganeti import utils
36
from ganeti import errors
37
from ganeti import hypervisor
38
from ganeti import locking
39
from ganeti import constants
40
from ganeti import objects
41
from ganeti import serializer
42
from ganeti import ssconf
43

    
44

    
45
class LogicalUnit(object):
46
  """Logical Unit base class.
47

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

57
  Note that all commands require root permissions.
58

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

62
  """
63
  HPATH = None
64
  HTYPE = None
65
  _OP_REQP = []
66
  REQ_BGL = True
67

    
68
  def __init__(self, processor, op, context, rpc):
69
    """Constructor for LogicalUnit.
70

71
    This needs to be overridden in derived classes in order to check op
72
    validity.
73

74
    """
75
    self.proc = processor
76
    self.op = op
77
    self.cfg = context.cfg
78
    self.context = context
79
    self.rpc = rpc
80
    # Dicts used to declare locking needs to mcpu
81
    self.needed_locks = None
82
    self.acquired_locks = {}
83
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
84
    self.add_locks = {}
85
    self.remove_locks = {}
86
    # Used to force good behavior when calling helper functions
87
    self.recalculate_locks = {}
88
    self.__ssh = None
89
    # logging
90
    self.LogWarning = processor.LogWarning
91
    self.LogInfo = processor.LogInfo
92
    self.LogStep = processor.LogStep
93
    # support for dry-run
94
    self.dry_run_result = None
95

    
96
    # Tasklets
97
    self.tasklets = None
98

    
99
    for attr_name in self._OP_REQP:
100
      attr_val = getattr(op, attr_name, None)
101
      if attr_val is None:
102
        raise errors.OpPrereqError("Required parameter '%s' missing" %
103
                                   attr_name)
104

    
105
    self.CheckArguments()
106

    
107
  def __GetSSH(self):
108
    """Returns the SshRunner object
109

110
    """
111
    if not self.__ssh:
112
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
113
    return self.__ssh
114

    
115
  ssh = property(fget=__GetSSH)
116

    
117
  def CheckArguments(self):
118
    """Check syntactic validity for the opcode arguments.
119

120
    This method is for doing a simple syntactic check and ensure
121
    validity of opcode parameters, without any cluster-related
122
    checks. While the same can be accomplished in ExpandNames and/or
123
    CheckPrereq, doing these separate is better because:
124

125
      - ExpandNames is left as as purely a lock-related function
126
      - CheckPrereq is run after we have acquired locks (and possible
127
        waited for them)
128

129
    The function is allowed to change the self.op attribute so that
130
    later methods can no longer worry about missing parameters.
131

132
    """
133
    pass
134

    
135
  def ExpandNames(self):
136
    """Expand names for this LU.
137

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

143
    LUs which implement this method must also populate the self.needed_locks
144
    member, as a dict with lock levels as keys, and a list of needed lock names
145
    as values. Rules:
146

147
      - use an empty dict if you don't need any lock
148
      - if you don't need any lock at a particular level omit that level
149
      - don't put anything for the BGL level
150
      - if you want all locks at a level use locking.ALL_SET as a value
151

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

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

160
    Examples::
161

162
      # Acquire all nodes and one instance
163
      self.needed_locks = {
164
        locking.LEVEL_NODE: locking.ALL_SET,
165
        locking.LEVEL_INSTANCE: ['instance1.example.tld'],
166
      }
167
      # Acquire just two nodes
168
      self.needed_locks = {
169
        locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
170
      }
171
      # Acquire no locks
172
      self.needed_locks = {} # No, you can't leave it to the default value None
173

174
    """
175
    # The implementation of this method is mandatory only if the new LU is
176
    # concurrent, so that old LUs don't need to be changed all at the same
177
    # time.
178
    if self.REQ_BGL:
179
      self.needed_locks = {} # Exclusive LUs don't need locks.
180
    else:
181
      raise NotImplementedError
182

    
183
  def DeclareLocks(self, level):
184
    """Declare LU locking needs for a level
185

186
    While most LUs can just declare their locking needs at ExpandNames time,
187
    sometimes there's the need to calculate some locks after having acquired
188
    the ones before. This function is called just before acquiring locks at a
189
    particular level, but after acquiring the ones at lower levels, and permits
190
    such calculations. It can be used to modify self.needed_locks, and by
191
    default it does nothing.
192

193
    This function is only called if you have something already set in
194
    self.needed_locks for the level.
195

196
    @param level: Locking level which is going to be locked
197
    @type level: member of ganeti.locking.LEVELS
198

199
    """
200

    
201
  def CheckPrereq(self):
202
    """Check prerequisites for this LU.
203

204
    This method should check that the prerequisites for the execution
205
    of this LU are fulfilled. It can do internode communication, but
206
    it should be idempotent - no cluster or system changes are
207
    allowed.
208

209
    The method should raise errors.OpPrereqError in case something is
210
    not fulfilled. Its return value is ignored.
211

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

215
    """
216
    if self.tasklets is not None:
217
      for (idx, tl) in enumerate(self.tasklets):
218
        logging.debug("Checking prerequisites for tasklet %s/%s",
219
                      idx + 1, len(self.tasklets))
220
        tl.CheckPrereq()
221
    else:
222
      raise NotImplementedError
223

    
224
  def Exec(self, feedback_fn):
225
    """Execute the LU.
226

227
    This method should implement the actual work. It should raise
228
    errors.OpExecError for failures that are somewhat dealt with in
229
    code, or expected.
230

231
    """
232
    if self.tasklets is not None:
233
      for (idx, tl) in enumerate(self.tasklets):
234
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
235
        tl.Exec(feedback_fn)
236
    else:
237
      raise NotImplementedError
238

    
239
  def BuildHooksEnv(self):
240
    """Build hooks environment for this LU.
241

242
    This method should return a three-node tuple consisting of: a dict
243
    containing the environment that will be used for running the
244
    specific hook for this LU, a list of node names on which the hook
245
    should run before the execution, and a list of node names on which
246
    the hook should run after the execution.
247

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

253
    No nodes should be returned as an empty list (and not None).
254

255
    Note that if the HPATH for a LU class is None, this function will
256
    not be called.
257

258
    """
259
    raise NotImplementedError
260

    
261
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
262
    """Notify the LU about the results of its hooks.
263

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

270
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
271
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
272
    @param hook_results: the results of the multi-node hooks rpc call
273
    @param feedback_fn: function used send feedback back to the caller
274
    @param lu_result: the previous Exec result this LU had, or None
275
        in the PRE phase
276
    @return: the new Exec result, based on the previous result
277
        and hook results
278

279
    """
280
    return lu_result
281

    
282
  def _ExpandAndLockInstance(self):
283
    """Helper function to expand and lock an instance.
284

285
    Many LUs that work on an instance take its name in self.op.instance_name
286
    and need to expand it and then declare the expanded name for locking. This
287
    function does it, and then updates self.op.instance_name to the expanded
288
    name. It also initializes needed_locks as a dict, if this hasn't been done
289
    before.
290

291
    """
292
    if self.needed_locks is None:
293
      self.needed_locks = {}
294
    else:
295
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
296
        "_ExpandAndLockInstance called with instance-level locks set"
297
    expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name)
298
    if expanded_name is None:
299
      raise errors.OpPrereqError("Instance '%s' not known" %
300
                                  self.op.instance_name)
301
    self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
302
    self.op.instance_name = expanded_name
303

    
304
  def _LockInstancesNodes(self, primary_only=False):
305
    """Helper function to declare instances' nodes for locking.
306

307
    This function should be called after locking one or more instances to lock
308
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
309
    with all primary or secondary nodes for instances already locked and
310
    present in self.needed_locks[locking.LEVEL_INSTANCE].
311

312
    It should be called from DeclareLocks, and for safety only works if
313
    self.recalculate_locks[locking.LEVEL_NODE] is set.
314

315
    In the future it may grow parameters to just lock some instance's nodes, or
316
    to just lock primaries or secondary nodes, if needed.
317

318
    If should be called in DeclareLocks in a way similar to::
319

320
      if level == locking.LEVEL_NODE:
321
        self._LockInstancesNodes()
322

323
    @type primary_only: boolean
324
    @param primary_only: only lock primary nodes of locked instances
325

326
    """
327
    assert locking.LEVEL_NODE in self.recalculate_locks, \
328
      "_LockInstancesNodes helper function called with no nodes to recalculate"
329

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

    
332
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
333
    # future we might want to have different behaviors depending on the value
334
    # of self.recalculate_locks[locking.LEVEL_NODE]
335
    wanted_nodes = []
336
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
337
      instance = self.context.cfg.GetInstanceInfo(instance_name)
338
      wanted_nodes.append(instance.primary_node)
339
      if not primary_only:
340
        wanted_nodes.extend(instance.secondary_nodes)
341

    
342
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
343
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
344
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
345
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
346

    
347
    del self.recalculate_locks[locking.LEVEL_NODE]
348

    
349

    
350
class NoHooksLU(LogicalUnit):
351
  """Simple LU which runs no hooks.
352

353
  This LU is intended as a parent for other LogicalUnits which will
354
  run no hooks, in order to reduce duplicate code.
355

356
  """
357
  HPATH = None
358
  HTYPE = None
359

    
360

    
361
class Tasklet:
362
  """Tasklet base class.
363

364
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
365
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
366
  tasklets know nothing about locks.
367

368
  Subclasses must follow these rules:
369
    - Implement CheckPrereq
370
    - Implement Exec
371

372
  """
373
  def __init__(self, lu):
374
    self.lu = lu
375

    
376
    # Shortcuts
377
    self.cfg = lu.cfg
378
    self.rpc = lu.rpc
379

    
380
  def CheckPrereq(self):
381
    """Check prerequisites for this tasklets.
382

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

387
    The method should raise errors.OpPrereqError in case something is not
388
    fulfilled. Its return value is ignored.
389

390
    This method should also update all parameters to their canonical form if it
391
    hasn't been done before.
392

393
    """
394
    raise NotImplementedError
395

    
396
  def Exec(self, feedback_fn):
397
    """Execute the tasklet.
398

399
    This method should implement the actual work. It should raise
400
    errors.OpExecError for failures that are somewhat dealt with in code, or
401
    expected.
402

403
    """
404
    raise NotImplementedError
405

    
406

    
407
def _GetWantedNodes(lu, nodes):
408
  """Returns list of checked and expanded node names.
409

410
  @type lu: L{LogicalUnit}
411
  @param lu: the logical unit on whose behalf we execute
412
  @type nodes: list
413
  @param nodes: list of node names or None for all nodes
414
  @rtype: list
415
  @return: the list of nodes, sorted
416
  @raise errors.OpProgrammerError: if the nodes parameter is wrong type
417

418
  """
419
  if not isinstance(nodes, list):
420
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
421

    
422
  if not nodes:
423
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
424
      " non-empty list of nodes whose name is to be expanded.")
425

    
426
  wanted = []
427
  for name in nodes:
428
    node = lu.cfg.ExpandNodeName(name)
429
    if node is None:
430
      raise errors.OpPrereqError("No such node name '%s'" % name)
431
    wanted.append(node)
432

    
433
  return utils.NiceSort(wanted)
434

    
435

    
436
def _GetWantedInstances(lu, instances):
437
  """Returns list of checked and expanded instance names.
438

439
  @type lu: L{LogicalUnit}
440
  @param lu: the logical unit on whose behalf we execute
441
  @type instances: list
442
  @param instances: list of instance names or None for all instances
443
  @rtype: list
444
  @return: the list of instances, sorted
445
  @raise errors.OpPrereqError: if the instances parameter is wrong type
446
  @raise errors.OpPrereqError: if any of the passed instances is not found
447

448
  """
449
  if not isinstance(instances, list):
450
    raise errors.OpPrereqError("Invalid argument type 'instances'")
451

    
452
  if instances:
453
    wanted = []
454

    
455
    for name in instances:
456
      instance = lu.cfg.ExpandInstanceName(name)
457
      if instance is None:
458
        raise errors.OpPrereqError("No such instance name '%s'" % name)
459
      wanted.append(instance)
460

    
461
  else:
462
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
463
  return wanted
464

    
465

    
466
def _CheckOutputFields(static, dynamic, selected):
467
  """Checks whether all selected fields are valid.
468

469
  @type static: L{utils.FieldSet}
470
  @param static: static fields set
471
  @type dynamic: L{utils.FieldSet}
472
  @param dynamic: dynamic fields set
473

474
  """
475
  f = utils.FieldSet()
476
  f.Extend(static)
477
  f.Extend(dynamic)
478

    
479
  delta = f.NonMatching(selected)
480
  if delta:
481
    raise errors.OpPrereqError("Unknown output fields selected: %s"
482
                               % ",".join(delta))
483

    
484

    
485
def _CheckBooleanOpField(op, name):
486
  """Validates boolean opcode parameters.
487

488
  This will ensure that an opcode parameter is either a boolean value,
489
  or None (but that it always exists).
490

491
  """
492
  val = getattr(op, name, None)
493
  if not (val is None or isinstance(val, bool)):
494
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
495
                               (name, str(val)))
496
  setattr(op, name, val)
497

    
498

    
499
def _CheckNodeOnline(lu, node):
500
  """Ensure that a given node is online.
501

502
  @param lu: the LU on behalf of which we make the check
503
  @param node: the node to check
504
  @raise errors.OpPrereqError: if the node is offline
505

506
  """
507
  if lu.cfg.GetNodeInfo(node).offline:
508
    raise errors.OpPrereqError("Can't use offline node %s" % node)
509

    
510

    
511
def _CheckNodeNotDrained(lu, node):
512
  """Ensure that a given node is not drained.
513

514
  @param lu: the LU on behalf of which we make the check
515
  @param node: the node to check
516
  @raise errors.OpPrereqError: if the node is drained
517

518
  """
519
  if lu.cfg.GetNodeInfo(node).drained:
520
    raise errors.OpPrereqError("Can't use drained node %s" % node)
521

    
522

    
523
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
524
                          memory, vcpus, nics, disk_template, disks,
525
                          bep, hvp, hypervisor_name):
526
  """Builds instance related env variables for hooks
527

528
  This builds the hook environment from individual variables.
529

530
  @type name: string
531
  @param name: the name of the instance
532
  @type primary_node: string
533
  @param primary_node: the name of the instance's primary node
534
  @type secondary_nodes: list
535
  @param secondary_nodes: list of secondary nodes as strings
536
  @type os_type: string
537
  @param os_type: the name of the instance's OS
538
  @type status: boolean
539
  @param status: the should_run status of the instance
540
  @type memory: string
541
  @param memory: the memory size of the instance
542
  @type vcpus: string
543
  @param vcpus: the count of VCPUs the instance has
544
  @type nics: list
545
  @param nics: list of tuples (ip, mac, mode, link) representing
546
      the NICs the instance has
547
  @type disk_template: string
548
  @param disk_template: the disk template of the instance
549
  @type disks: list
550
  @param disks: the list of (size, mode) pairs
551
  @type bep: dict
552
  @param bep: the backend parameters for the instance
553
  @type hvp: dict
554
  @param hvp: the hypervisor parameters for the instance
555
  @type hypervisor_name: string
556
  @param hypervisor_name: the hypervisor for the instance
557
  @rtype: dict
558
  @return: the hook environment for this instance
559

560
  """
561
  if status:
562
    str_status = "up"
563
  else:
564
    str_status = "down"
565
  env = {
566
    "OP_TARGET": name,
567
    "INSTANCE_NAME": name,
568
    "INSTANCE_PRIMARY": primary_node,
569
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
570
    "INSTANCE_OS_TYPE": os_type,
571
    "INSTANCE_STATUS": str_status,
572
    "INSTANCE_MEMORY": memory,
573
    "INSTANCE_VCPUS": vcpus,
574
    "INSTANCE_DISK_TEMPLATE": disk_template,
575
    "INSTANCE_HYPERVISOR": hypervisor_name,
576
  }
577

    
578
  if nics:
579
    nic_count = len(nics)
580
    for idx, (ip, mac, mode, link) in enumerate(nics):
581
      if ip is None:
582
        ip = ""
583
      env["INSTANCE_NIC%d_IP" % idx] = ip
584
      env["INSTANCE_NIC%d_MAC" % idx] = mac
585
      env["INSTANCE_NIC%d_MODE" % idx] = mode
586
      env["INSTANCE_NIC%d_LINK" % idx] = link
587
      if mode == constants.NIC_MODE_BRIDGED:
588
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
589
  else:
590
    nic_count = 0
591

    
592
  env["INSTANCE_NIC_COUNT"] = nic_count
593

    
594
  if disks:
595
    disk_count = len(disks)
596
    for idx, (size, mode) in enumerate(disks):
597
      env["INSTANCE_DISK%d_SIZE" % idx] = size
598
      env["INSTANCE_DISK%d_MODE" % idx] = mode
599
  else:
600
    disk_count = 0
601

    
602
  env["INSTANCE_DISK_COUNT"] = disk_count
603

    
604
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
605
    for key, value in source.items():
606
      env["INSTANCE_%s_%s" % (kind, key)] = value
607

    
608
  return env
609

    
610

    
611
def _NICListToTuple(lu, nics):
612
  """Build a list of nic information tuples.
613

614
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
615
  value in LUQueryInstanceData.
616

617
  @type lu:  L{LogicalUnit}
618
  @param lu: the logical unit on whose behalf we execute
619
  @type nics: list of L{objects.NIC}
620
  @param nics: list of nics to convert to hooks tuples
621

622
  """
623
  hooks_nics = []
624
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
625
  for nic in nics:
626
    ip = nic.ip
627
    mac = nic.mac
628
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
629
    mode = filled_params[constants.NIC_MODE]
630
    link = filled_params[constants.NIC_LINK]
631
    hooks_nics.append((ip, mac, mode, link))
632
  return hooks_nics
633

    
634

    
635
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
636
  """Builds instance related env variables for hooks from an object.
637

638
  @type lu: L{LogicalUnit}
639
  @param lu: the logical unit on whose behalf we execute
640
  @type instance: L{objects.Instance}
641
  @param instance: the instance for which we should build the
642
      environment
643
  @type override: dict
644
  @param override: dictionary with key/values that will override
645
      our values
646
  @rtype: dict
647
  @return: the hook environment dictionary
648

649
  """
650
  cluster = lu.cfg.GetClusterInfo()
651
  bep = cluster.FillBE(instance)
652
  hvp = cluster.FillHV(instance)
653
  args = {
654
    'name': instance.name,
655
    'primary_node': instance.primary_node,
656
    'secondary_nodes': instance.secondary_nodes,
657
    'os_type': instance.os,
658
    'status': instance.admin_up,
659
    'memory': bep[constants.BE_MEMORY],
660
    'vcpus': bep[constants.BE_VCPUS],
661
    'nics': _NICListToTuple(lu, instance.nics),
662
    'disk_template': instance.disk_template,
663
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
664
    'bep': bep,
665
    'hvp': hvp,
666
    'hypervisor_name': instance.hypervisor,
667
  }
668
  if override:
669
    args.update(override)
670
  return _BuildInstanceHookEnv(**args)
671

    
672

    
673
def _AdjustCandidatePool(lu, exceptions):
674
  """Adjust the candidate pool after node operations.
675

676
  """
677
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
678
  if mod_list:
679
    lu.LogInfo("Promoted nodes to master candidate role: %s",
680
               ", ".join(node.name for node in mod_list))
681
    for name in mod_list:
682
      lu.context.ReaddNode(name)
683
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
684
  if mc_now > mc_max:
685
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
686
               (mc_now, mc_max))
687

    
688

    
689
def _DecideSelfPromotion(lu, exceptions=None):
690
  """Decide whether I should promote myself as a master candidate.
691

692
  """
693
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
694
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
695
  # the new node will increase mc_max with one, so:
696
  mc_should = min(mc_should + 1, cp_size)
697
  return mc_now < mc_should
698

    
699

    
700
def _CheckNicsBridgesExist(lu, target_nics, target_node,
701
                               profile=constants.PP_DEFAULT):
702
  """Check that the brigdes needed by a list of nics exist.
703

704
  """
705
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
706
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
707
                for nic in target_nics]
708
  brlist = [params[constants.NIC_LINK] for params in paramslist
709
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
710
  if brlist:
711
    result = lu.rpc.call_bridges_exist(target_node, brlist)
712
    result.Raise("Error checking bridges on destination node '%s'" %
713
                 target_node, prereq=True)
714

    
715

    
716
def _CheckInstanceBridgesExist(lu, instance, node=None):
717
  """Check that the brigdes needed by an instance exist.
718

719
  """
720
  if node is None:
721
    node = instance.primary_node
722
  _CheckNicsBridgesExist(lu, instance.nics, node)
723

    
724

    
725
def _GetNodeInstancesInner(cfg, fn):
726
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
727

    
728

    
729
def _GetNodeInstances(cfg, node_name):
730
  """Returns a list of all primary and secondary instances on a node.
731

732
  """
733

    
734
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
735

    
736

    
737
def _GetNodePrimaryInstances(cfg, node_name):
738
  """Returns primary instances on a node.
739

740
  """
741
  return _GetNodeInstancesInner(cfg,
742
                                lambda inst: node_name == inst.primary_node)
743

    
744

    
745
def _GetNodeSecondaryInstances(cfg, node_name):
746
  """Returns secondary instances on a node.
747

748
  """
749
  return _GetNodeInstancesInner(cfg,
750
                                lambda inst: node_name in inst.secondary_nodes)
751

    
752

    
753
def _GetStorageTypeArgs(cfg, storage_type):
754
  """Returns the arguments for a storage type.
755

756
  """
757
  # Special case for file storage
758
  if storage_type == constants.ST_FILE:
759
    # storage.FileStorage wants a list of storage directories
760
    return [[cfg.GetFileStorageDir()]]
761

    
762
  return []
763

    
764

    
765
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
766
  faulty = []
767

    
768
  for dev in instance.disks:
769
    cfg.SetDiskID(dev, node_name)
770

    
771
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
772
  result.Raise("Failed to get disk status from node %s" % node_name,
773
               prereq=prereq)
774

    
775
  for idx, bdev_status in enumerate(result.payload):
776
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
777
      faulty.append(idx)
778

    
779
  return faulty
780

    
781

    
782
class LUPostInitCluster(LogicalUnit):
783
  """Logical unit for running hooks after cluster initialization.
784

785
  """
786
  HPATH = "cluster-init"
787
  HTYPE = constants.HTYPE_CLUSTER
788
  _OP_REQP = []
789

    
790
  def BuildHooksEnv(self):
791
    """Build hooks env.
792

793
    """
794
    env = {"OP_TARGET": self.cfg.GetClusterName()}
795
    mn = self.cfg.GetMasterNode()
796
    return env, [], [mn]
797

    
798
  def CheckPrereq(self):
799
    """No prerequisites to check.
800

801
    """
802
    return True
803

    
804
  def Exec(self, feedback_fn):
805
    """Nothing to do.
806

807
    """
808
    return True
809

    
810

    
811
class LUDestroyCluster(LogicalUnit):
812
  """Logical unit for destroying the cluster.
813

814
  """
815
  HPATH = "cluster-destroy"
816
  HTYPE = constants.HTYPE_CLUSTER
817
  _OP_REQP = []
818

    
819
  def BuildHooksEnv(self):
820
    """Build hooks env.
821

822
    """
823
    env = {"OP_TARGET": self.cfg.GetClusterName()}
824
    return env, [], []
825

    
826
  def CheckPrereq(self):
827
    """Check prerequisites.
828

829
    This checks whether the cluster is empty.
830

831
    Any errors are signaled by raising errors.OpPrereqError.
832

833
    """
834
    master = self.cfg.GetMasterNode()
835

    
836
    nodelist = self.cfg.GetNodeList()
837
    if len(nodelist) != 1 or nodelist[0] != master:
838
      raise errors.OpPrereqError("There are still %d node(s) in"
839
                                 " this cluster." % (len(nodelist) - 1))
840
    instancelist = self.cfg.GetInstanceList()
841
    if instancelist:
842
      raise errors.OpPrereqError("There are still %d instance(s) in"
843
                                 " this cluster." % len(instancelist))
844

    
845
  def Exec(self, feedback_fn):
846
    """Destroys the cluster.
847

848
    """
849
    master = self.cfg.GetMasterNode()
850

    
851
    # Run post hooks on master node before it's removed
852
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
853
    try:
854
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
855
    except:
856
      self.LogWarning("Errors occurred running hooks on %s" % master)
857

    
858
    result = self.rpc.call_node_stop_master(master, False)
859
    result.Raise("Could not disable the master role")
860
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
861
    utils.CreateBackup(priv_key)
862
    utils.CreateBackup(pub_key)
863
    return master
864

    
865

    
866
class LUVerifyCluster(LogicalUnit):
867
  """Verifies the cluster status.
868

869
  """
870
  HPATH = "cluster-verify"
871
  HTYPE = constants.HTYPE_CLUSTER
872
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
873
  REQ_BGL = False
874

    
875
  TCLUSTER = "cluster"
876
  TNODE = "node"
877
  TINSTANCE = "instance"
878

    
879
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
880
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
881
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
882
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
883
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
884
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
885
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
886
  ENODEDRBD = (TNODE, "ENODEDRBD")
887
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
888
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
889
  ENODEHV = (TNODE, "ENODEHV")
890
  ENODELVM = (TNODE, "ENODELVM")
891
  ENODEN1 = (TNODE, "ENODEN1")
892
  ENODENET = (TNODE, "ENODENET")
893
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
894
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
895
  ENODERPC = (TNODE, "ENODERPC")
896
  ENODESSH = (TNODE, "ENODESSH")
897
  ENODEVERSION = (TNODE, "ENODEVERSION")
898

    
899
  ETYPE_FIELD = "code"
900
  ETYPE_ERROR = "ERROR"
901
  ETYPE_WARNING = "WARNING"
902

    
903
  def ExpandNames(self):
904
    self.needed_locks = {
905
      locking.LEVEL_NODE: locking.ALL_SET,
906
      locking.LEVEL_INSTANCE: locking.ALL_SET,
907
    }
908
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
909

    
910
  def _Error(self, ecode, item, msg, *args, **kwargs):
911
    """Format an error message.
912

913
    Based on the opcode's error_codes parameter, either format a
914
    parseable error code, or a simpler error string.
915

916
    This must be called only from Exec and functions called from Exec.
917

918
    """
919
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
920
    itype, etxt = ecode
921
    # first complete the msg
922
    if args:
923
      msg = msg % args
924
    # then format the whole message
925
    if self.op.error_codes:
926
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
927
    else:
928
      if item:
929
        item = " " + item
930
      else:
931
        item = ""
932
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
933
    # and finally report it via the feedback_fn
934
    self._feedback_fn("  - %s" % msg)
935

    
936
  def _ErrorIf(self, cond, *args, **kwargs):
937
    """Log an error message if the passed condition is True.
938

939
    """
940
    cond = bool(cond) or self.op.debug_simulate_errors
941
    if cond:
942
      self._Error(*args, **kwargs)
943
    # do not mark the operation as failed for WARN cases only
944
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
945
      self.bad = self.bad or cond
946

    
947
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
948
                  node_result, master_files, drbd_map, vg_name):
949
    """Run multiple tests against a node.
950

951
    Test list:
952

953
      - compares ganeti version
954
      - checks vg existence and size > 20G
955
      - checks config file checksum
956
      - checks ssh to other nodes
957

958
    @type nodeinfo: L{objects.Node}
959
    @param nodeinfo: the node to check
960
    @param file_list: required list of files
961
    @param local_cksum: dictionary of local files and their checksums
962
    @param node_result: the results from the node
963
    @param master_files: list of files that only masters should have
964
    @param drbd_map: the useddrbd minors for this node, in
965
        form of minor: (instance, must_exist) which correspond to instances
966
        and their running status
967
    @param vg_name: Ganeti Volume Group (result of self.cfg.GetVGName())
968

969
    """
970
    node = nodeinfo.name
971
    _ErrorIf = self._ErrorIf
972

    
973
    # main result, node_result should be a non-empty dict
974
    test = not node_result or not isinstance(node_result, dict)
975
    _ErrorIf(test, self.ENODERPC, node,
976
                  "unable to verify node: no data returned")
977
    if test:
978
      return
979

    
980
    # compares ganeti version
981
    local_version = constants.PROTOCOL_VERSION
982
    remote_version = node_result.get('version', None)
983
    test = not (remote_version and
984
                isinstance(remote_version, (list, tuple)) and
985
                len(remote_version) == 2)
986
    _ErrorIf(test, self.ENODERPC, node,
987
             "connection to node returned invalid data")
988
    if test:
989
      return
990

    
991
    test = local_version != remote_version[0]
992
    _ErrorIf(test, self.ENODEVERSION, node,
993
             "incompatible protocol versions: master %s,"
994
             " node %s", local_version, remote_version[0])
995
    if test:
996
      return
997

    
998
    # node seems compatible, we can actually try to look into its results
999

    
1000
    # full package version
1001
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1002
                  self.ENODEVERSION, node,
1003
                  "software version mismatch: master %s, node %s",
1004
                  constants.RELEASE_VERSION, remote_version[1],
1005
                  code=self.ETYPE_WARNING)
1006

    
1007
    # checks vg existence and size > 20G
1008
    if vg_name is not None:
1009
      vglist = node_result.get(constants.NV_VGLIST, None)
1010
      test = not vglist
1011
      _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1012
      if not test:
1013
        vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1014
                                              constants.MIN_VG_SIZE)
1015
        _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1016

    
1017
    # checks config file checksum
1018

    
1019
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
1020
    test = not isinstance(remote_cksum, dict)
1021
    _ErrorIf(test, self.ENODEFILECHECK, node,
1022
             "node hasn't returned file checksum data")
1023
    if not test:
1024
      for file_name in file_list:
1025
        node_is_mc = nodeinfo.master_candidate
1026
        must_have = (file_name not in master_files) or node_is_mc
1027
        # missing
1028
        test1 = file_name not in remote_cksum
1029
        # invalid checksum
1030
        test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1031
        # existing and good
1032
        test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1033
        _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1034
                 "file '%s' missing", file_name)
1035
        _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1036
                 "file '%s' has wrong checksum", file_name)
1037
        # not candidate and this is not a must-have file
1038
        _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1039
                 "file '%s' should not exist on non master"
1040
                 " candidates (and the file is outdated)", file_name)
1041
        # all good, except non-master/non-must have combination
1042
        _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1043
                 "file '%s' should not exist"
1044
                 " on non master candidates", file_name)
1045

    
1046
    # checks ssh to any
1047

    
1048
    test = constants.NV_NODELIST not in node_result
1049
    _ErrorIf(test, self.ENODESSH, node,
1050
             "node hasn't returned node ssh connectivity data")
1051
    if not test:
1052
      if node_result[constants.NV_NODELIST]:
1053
        for a_node, a_msg in node_result[constants.NV_NODELIST].items():
1054
          _ErrorIf(True, self.ENODESSH, node,
1055
                   "ssh communication with node '%s': %s", a_node, a_msg)
1056

    
1057
    test = constants.NV_NODENETTEST not in node_result
1058
    _ErrorIf(test, self.ENODENET, node,
1059
             "node hasn't returned node tcp connectivity data")
1060
    if not test:
1061
      if node_result[constants.NV_NODENETTEST]:
1062
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
1063
        for anode in nlist:
1064
          _ErrorIf(True, self.ENODENET, node,
1065
                   "tcp communication with node '%s': %s",
1066
                   anode, node_result[constants.NV_NODENETTEST][anode])
1067

    
1068
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
1069
    if isinstance(hyp_result, dict):
1070
      for hv_name, hv_result in hyp_result.iteritems():
1071
        test = hv_result is not None
1072
        _ErrorIf(test, self.ENODEHV, node,
1073
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1074

    
1075
    # check used drbd list
1076
    if vg_name is not None:
1077
      used_minors = node_result.get(constants.NV_DRBDLIST, [])
1078
      test = not isinstance(used_minors, (tuple, list))
1079
      _ErrorIf(test, self.ENODEDRBD, node,
1080
               "cannot parse drbd status file: %s", str(used_minors))
1081
      if not test:
1082
        for minor, (iname, must_exist) in drbd_map.items():
1083
          test = minor not in used_minors and must_exist
1084
          _ErrorIf(test, self.ENODEDRBD, node,
1085
                   "drbd minor %d of instance %s is not active",
1086
                   minor, iname)
1087
        for minor in used_minors:
1088
          test = minor not in drbd_map
1089
          _ErrorIf(test, self.ENODEDRBD, node,
1090
                   "unallocated drbd minor %d is in use", minor)
1091

    
1092
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
1093
                      node_instance, n_offline):
1094
    """Verify an instance.
1095

1096
    This function checks to see if the required block devices are
1097
    available on the instance's node.
1098

1099
    """
1100
    _ErrorIf = self._ErrorIf
1101
    node_current = instanceconfig.primary_node
1102

    
1103
    node_vol_should = {}
1104
    instanceconfig.MapLVsByNode(node_vol_should)
1105

    
1106
    for node in node_vol_should:
1107
      if node in n_offline:
1108
        # ignore missing volumes on offline nodes
1109
        continue
1110
      for volume in node_vol_should[node]:
1111
        test = node not in node_vol_is or volume not in node_vol_is[node]
1112
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1113
                 "volume %s missing on node %s", volume, node)
1114

    
1115
    if instanceconfig.admin_up:
1116
      test = ((node_current not in node_instance or
1117
               not instance in node_instance[node_current]) and
1118
              node_current not in n_offline)
1119
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1120
               "instance not running on its primary node %s",
1121
               node_current)
1122

    
1123
    for node in node_instance:
1124
      if (not node == node_current):
1125
        test = instance in node_instance[node]
1126
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1127
                 "instance should not run on node %s", node)
1128

    
1129
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is):
1130
    """Verify if there are any unknown volumes in the cluster.
1131

1132
    The .os, .swap and backup volumes are ignored. All other volumes are
1133
    reported as unknown.
1134

1135
    """
1136
    for node in node_vol_is:
1137
      for volume in node_vol_is[node]:
1138
        test = (node not in node_vol_should or
1139
                volume not in node_vol_should[node])
1140
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1141
                      "volume %s is unknown", volume)
1142

    
1143
  def _VerifyOrphanInstances(self, instancelist, node_instance):
1144
    """Verify the list of running instances.
1145

1146
    This checks what instances are running but unknown to the cluster.
1147

1148
    """
1149
    for node in node_instance:
1150
      for o_inst in node_instance[node]:
1151
        test = o_inst not in instancelist
1152
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1153
                      "instance %s on node %s should not exist", o_inst, node)
1154

    
1155
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg):
1156
    """Verify N+1 Memory Resilience.
1157

1158
    Check that if one single node dies we can still start all the instances it
1159
    was primary for.
1160

1161
    """
1162
    for node, nodeinfo in node_info.iteritems():
1163
      # This code checks that every node which is now listed as secondary has
1164
      # enough memory to host all instances it is supposed to should a single
1165
      # other node in the cluster fail.
1166
      # FIXME: not ready for failover to an arbitrary node
1167
      # FIXME: does not support file-backed instances
1168
      # WARNING: we currently take into account down instances as well as up
1169
      # ones, considering that even if they're down someone might want to start
1170
      # them even in the event of a node failure.
1171
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
1172
        needed_mem = 0
1173
        for instance in instances:
1174
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1175
          if bep[constants.BE_AUTO_BALANCE]:
1176
            needed_mem += bep[constants.BE_MEMORY]
1177
        test = nodeinfo['mfree'] < needed_mem
1178
        self._ErrorIf(test, self.ENODEN1, node,
1179
                      "not enough memory on to accommodate"
1180
                      " failovers should peer node %s fail", prinode)
1181

    
1182
  def CheckPrereq(self):
1183
    """Check prerequisites.
1184

1185
    Transform the list of checks we're going to skip into a set and check that
1186
    all its members are valid.
1187

1188
    """
1189
    self.skip_set = frozenset(self.op.skip_checks)
1190
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1191
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
1192

    
1193
  def BuildHooksEnv(self):
1194
    """Build hooks env.
1195

1196
    Cluster-Verify hooks just ran in the post phase and their failure makes
1197
    the output be logged in the verify output and the verification to fail.
1198

1199
    """
1200
    all_nodes = self.cfg.GetNodeList()
1201
    env = {
1202
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1203
      }
1204
    for node in self.cfg.GetAllNodesInfo().values():
1205
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1206

    
1207
    return env, [], all_nodes
1208

    
1209
  def Exec(self, feedback_fn):
1210
    """Verify integrity of cluster, performing various test on nodes.
1211

1212
    """
1213
    self.bad = False
1214
    _ErrorIf = self._ErrorIf
1215
    verbose = self.op.verbose
1216
    self._feedback_fn = feedback_fn
1217
    feedback_fn("* Verifying global settings")
1218
    for msg in self.cfg.VerifyConfig():
1219
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1220

    
1221
    vg_name = self.cfg.GetVGName()
1222
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1223
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1224
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1225
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1226
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1227
                        for iname in instancelist)
1228
    i_non_redundant = [] # Non redundant instances
1229
    i_non_a_balanced = [] # Non auto-balanced instances
1230
    n_offline = [] # List of offline nodes
1231
    n_drained = [] # List of nodes being drained
1232
    node_volume = {}
1233
    node_instance = {}
1234
    node_info = {}
1235
    instance_cfg = {}
1236

    
1237
    # FIXME: verify OS list
1238
    # do local checksums
1239
    master_files = [constants.CLUSTER_CONF_FILE]
1240

    
1241
    file_names = ssconf.SimpleStore().GetFileList()
1242
    file_names.append(constants.SSL_CERT_FILE)
1243
    file_names.append(constants.RAPI_CERT_FILE)
1244
    file_names.extend(master_files)
1245

    
1246
    local_checksums = utils.FingerprintFiles(file_names)
1247

    
1248
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1249
    node_verify_param = {
1250
      constants.NV_FILELIST: file_names,
1251
      constants.NV_NODELIST: [node.name for node in nodeinfo
1252
                              if not node.offline],
1253
      constants.NV_HYPERVISOR: hypervisors,
1254
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1255
                                  node.secondary_ip) for node in nodeinfo
1256
                                 if not node.offline],
1257
      constants.NV_INSTANCELIST: hypervisors,
1258
      constants.NV_VERSION: None,
1259
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1260
      }
1261
    if vg_name is not None:
1262
      node_verify_param[constants.NV_VGLIST] = None
1263
      node_verify_param[constants.NV_LVLIST] = vg_name
1264
      node_verify_param[constants.NV_DRBDLIST] = None
1265
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1266
                                           self.cfg.GetClusterName())
1267

    
1268
    cluster = self.cfg.GetClusterInfo()
1269
    master_node = self.cfg.GetMasterNode()
1270
    all_drbd_map = self.cfg.ComputeDRBDMap()
1271

    
1272
    feedback_fn("* Verifying node status")
1273
    for node_i in nodeinfo:
1274
      node = node_i.name
1275

    
1276
      if node_i.offline:
1277
        if verbose:
1278
          feedback_fn("* Skipping offline node %s" % (node,))
1279
        n_offline.append(node)
1280
        continue
1281

    
1282
      if node == master_node:
1283
        ntype = "master"
1284
      elif node_i.master_candidate:
1285
        ntype = "master candidate"
1286
      elif node_i.drained:
1287
        ntype = "drained"
1288
        n_drained.append(node)
1289
      else:
1290
        ntype = "regular"
1291
      if verbose:
1292
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1293

    
1294
      msg = all_nvinfo[node].fail_msg
1295
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1296
      if msg:
1297
        continue
1298

    
1299
      nresult = all_nvinfo[node].payload
1300
      node_drbd = {}
1301
      for minor, instance in all_drbd_map[node].items():
1302
        test = instance not in instanceinfo
1303
        _ErrorIf(test, self.ECLUSTERCFG, None,
1304
                 "ghost instance '%s' in temporary DRBD map", instance)
1305
          # ghost instance should not be running, but otherwise we
1306
          # don't give double warnings (both ghost instance and
1307
          # unallocated minor in use)
1308
        if test:
1309
          node_drbd[minor] = (instance, False)
1310
        else:
1311
          instance = instanceinfo[instance]
1312
          node_drbd[minor] = (instance.name, instance.admin_up)
1313
      self._VerifyNode(node_i, file_names, local_checksums,
1314
                       nresult, master_files, node_drbd, vg_name)
1315

    
1316
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1317
      if vg_name is None:
1318
        node_volume[node] = {}
1319
      elif isinstance(lvdata, basestring):
1320
        _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1321
                 utils.SafeEncode(lvdata))
1322
        node_volume[node] = {}
1323
      elif not isinstance(lvdata, dict):
1324
        _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1325
        continue
1326
      else:
1327
        node_volume[node] = lvdata
1328

    
1329
      # node_instance
1330
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1331
      test = not isinstance(idata, list)
1332
      _ErrorIf(test, self.ENODEHV, node,
1333
               "rpc call to node failed (instancelist)")
1334
      if test:
1335
        continue
1336

    
1337
      node_instance[node] = idata
1338

    
1339
      # node_info
1340
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1341
      test = not isinstance(nodeinfo, dict)
1342
      _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1343
      if test:
1344
        continue
1345

    
1346
      try:
1347
        node_info[node] = {
1348
          "mfree": int(nodeinfo['memory_free']),
1349
          "pinst": [],
1350
          "sinst": [],
1351
          # dictionary holding all instances this node is secondary for,
1352
          # grouped by their primary node. Each key is a cluster node, and each
1353
          # value is a list of instances which have the key as primary and the
1354
          # current node as secondary.  this is handy to calculate N+1 memory
1355
          # availability if you can only failover from a primary to its
1356
          # secondary.
1357
          "sinst-by-pnode": {},
1358
        }
1359
        # FIXME: devise a free space model for file based instances as well
1360
        if vg_name is not None:
1361
          test = (constants.NV_VGLIST not in nresult or
1362
                  vg_name not in nresult[constants.NV_VGLIST])
1363
          _ErrorIf(test, self.ENODELVM, node,
1364
                   "node didn't return data for the volume group '%s'"
1365
                   " - it is either missing or broken", vg_name)
1366
          if test:
1367
            continue
1368
          node_info[node]["dfree"] = int(nresult[constants.NV_VGLIST][vg_name])
1369
      except (ValueError, KeyError):
1370
        _ErrorIf(True, self.ENODERPC, node,
1371
                 "node returned invalid nodeinfo, check lvm/hypervisor")
1372
        continue
1373

    
1374
    node_vol_should = {}
1375

    
1376
    feedback_fn("* Verifying instance status")
1377
    for instance in instancelist:
1378
      if verbose:
1379
        feedback_fn("* Verifying instance %s" % instance)
1380
      inst_config = instanceinfo[instance]
1381
      self._VerifyInstance(instance, inst_config, node_volume,
1382
                           node_instance, n_offline)
1383
      inst_nodes_offline = []
1384

    
1385
      inst_config.MapLVsByNode(node_vol_should)
1386

    
1387
      instance_cfg[instance] = inst_config
1388

    
1389
      pnode = inst_config.primary_node
1390
      _ErrorIf(pnode not in node_info and pnode not in n_offline,
1391
               self.ENODERPC, pnode, "instance %s, connection to"
1392
               " primary node failed", instance)
1393
      if pnode in node_info:
1394
        node_info[pnode]['pinst'].append(instance)
1395

    
1396
      if pnode in n_offline:
1397
        inst_nodes_offline.append(pnode)
1398

    
1399
      # If the instance is non-redundant we cannot survive losing its primary
1400
      # node, so we are not N+1 compliant. On the other hand we have no disk
1401
      # templates with more than one secondary so that situation is not well
1402
      # supported either.
1403
      # FIXME: does not support file-backed instances
1404
      if len(inst_config.secondary_nodes) == 0:
1405
        i_non_redundant.append(instance)
1406
      _ErrorIf(len(inst_config.secondary_nodes) > 1,
1407
               self.EINSTANCELAYOUT, instance,
1408
               "instance has multiple secondary nodes", code="WARNING")
1409

    
1410
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1411
        i_non_a_balanced.append(instance)
1412

    
1413
      for snode in inst_config.secondary_nodes:
1414
        _ErrorIf(snode not in node_info and snode not in n_offline,
1415
                 self.ENODERPC, snode,
1416
                 "instance %s, connection to secondary node"
1417
                 "failed", instance)
1418

    
1419
        if snode in node_info:
1420
          node_info[snode]['sinst'].append(instance)
1421
          if pnode not in node_info[snode]['sinst-by-pnode']:
1422
            node_info[snode]['sinst-by-pnode'][pnode] = []
1423
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1424

    
1425
        if snode in n_offline:
1426
          inst_nodes_offline.append(snode)
1427

    
1428
      # warn that the instance lives on offline nodes
1429
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1430
               "instance lives on offline node(s) %s",
1431
               ", ".join(inst_nodes_offline))
1432

    
1433
    feedback_fn("* Verifying orphan volumes")
1434
    self._VerifyOrphanVolumes(node_vol_should, node_volume)
1435

    
1436
    feedback_fn("* Verifying remaining instances")
1437
    self._VerifyOrphanInstances(instancelist, node_instance)
1438

    
1439
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1440
      feedback_fn("* Verifying N+1 Memory redundancy")
1441
      self._VerifyNPlusOneMemory(node_info, instance_cfg)
1442

    
1443
    feedback_fn("* Other Notes")
1444
    if i_non_redundant:
1445
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1446
                  % len(i_non_redundant))
1447

    
1448
    if i_non_a_balanced:
1449
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1450
                  % len(i_non_a_balanced))
1451

    
1452
    if n_offline:
1453
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1454

    
1455
    if n_drained:
1456
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1457

    
1458
    return not self.bad
1459

    
1460
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1461
    """Analyze the post-hooks' result
1462

1463
    This method analyses the hook result, handles it, and sends some
1464
    nicely-formatted feedback back to the user.
1465

1466
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1467
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1468
    @param hooks_results: the results of the multi-node hooks rpc call
1469
    @param feedback_fn: function used send feedback back to the caller
1470
    @param lu_result: previous Exec result
1471
    @return: the new Exec result, based on the previous result
1472
        and hook results
1473

1474
    """
1475
    # We only really run POST phase hooks, and are only interested in
1476
    # their results
1477
    if phase == constants.HOOKS_PHASE_POST:
1478
      # Used to change hooks' output to proper indentation
1479
      indent_re = re.compile('^', re.M)
1480
      feedback_fn("* Hooks Results")
1481
      assert hooks_results, "invalid result from hooks"
1482

    
1483
      for node_name in hooks_results:
1484
        show_node_header = True
1485
        res = hooks_results[node_name]
1486
        msg = res.fail_msg
1487
        test = msg and not res.offline
1488
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1489
                      "Communication failure in hooks execution: %s", msg)
1490
        if test:
1491
          # override manually lu_result here as _ErrorIf only
1492
          # overrides self.bad
1493
          lu_result = 1
1494
          continue
1495
        for script, hkr, output in res.payload:
1496
          test = hkr == constants.HKR_FAIL
1497
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1498
                        "Script %s failed, output:", script)
1499
          if test:
1500
            output = indent_re.sub('      ', output)
1501
            feedback_fn("%s" % output)
1502
            lu_result = 1
1503

    
1504
      return lu_result
1505

    
1506

    
1507
class LUVerifyDisks(NoHooksLU):
1508
  """Verifies the cluster disks status.
1509

1510
  """
1511
  _OP_REQP = []
1512
  REQ_BGL = False
1513

    
1514
  def ExpandNames(self):
1515
    self.needed_locks = {
1516
      locking.LEVEL_NODE: locking.ALL_SET,
1517
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1518
    }
1519
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1520

    
1521
  def CheckPrereq(self):
1522
    """Check prerequisites.
1523

1524
    This has no prerequisites.
1525

1526
    """
1527
    pass
1528

    
1529
  def Exec(self, feedback_fn):
1530
    """Verify integrity of cluster disks.
1531

1532
    @rtype: tuple of three items
1533
    @return: a tuple of (dict of node-to-node_error, list of instances
1534
        which need activate-disks, dict of instance: (node, volume) for
1535
        missing volumes
1536

1537
    """
1538
    result = res_nodes, res_instances, res_missing = {}, [], {}
1539

    
1540
    vg_name = self.cfg.GetVGName()
1541
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1542
    instances = [self.cfg.GetInstanceInfo(name)
1543
                 for name in self.cfg.GetInstanceList()]
1544

    
1545
    nv_dict = {}
1546
    for inst in instances:
1547
      inst_lvs = {}
1548
      if (not inst.admin_up or
1549
          inst.disk_template not in constants.DTS_NET_MIRROR):
1550
        continue
1551
      inst.MapLVsByNode(inst_lvs)
1552
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1553
      for node, vol_list in inst_lvs.iteritems():
1554
        for vol in vol_list:
1555
          nv_dict[(node, vol)] = inst
1556

    
1557
    if not nv_dict:
1558
      return result
1559

    
1560
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1561

    
1562
    for node in nodes:
1563
      # node_volume
1564
      node_res = node_lvs[node]
1565
      if node_res.offline:
1566
        continue
1567
      msg = node_res.fail_msg
1568
      if msg:
1569
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1570
        res_nodes[node] = msg
1571
        continue
1572

    
1573
      lvs = node_res.payload
1574
      for lv_name, (_, lv_inactive, lv_online) in lvs.items():
1575
        inst = nv_dict.pop((node, lv_name), None)
1576
        if (not lv_online and inst is not None
1577
            and inst.name not in res_instances):
1578
          res_instances.append(inst.name)
1579

    
1580
    # any leftover items in nv_dict are missing LVs, let's arrange the
1581
    # data better
1582
    for key, inst in nv_dict.iteritems():
1583
      if inst.name not in res_missing:
1584
        res_missing[inst.name] = []
1585
      res_missing[inst.name].append(key)
1586

    
1587
    return result
1588

    
1589

    
1590
class LURepairDiskSizes(NoHooksLU):
1591
  """Verifies the cluster disks sizes.
1592

1593
  """
1594
  _OP_REQP = ["instances"]
1595
  REQ_BGL = False
1596

    
1597
  def ExpandNames(self):
1598
    if not isinstance(self.op.instances, list):
1599
      raise errors.OpPrereqError("Invalid argument type 'instances'")
1600

    
1601
    if self.op.instances:
1602
      self.wanted_names = []
1603
      for name in self.op.instances:
1604
        full_name = self.cfg.ExpandInstanceName(name)
1605
        if full_name is None:
1606
          raise errors.OpPrereqError("Instance '%s' not known" % name)
1607
        self.wanted_names.append(full_name)
1608
      self.needed_locks = {
1609
        locking.LEVEL_NODE: [],
1610
        locking.LEVEL_INSTANCE: self.wanted_names,
1611
        }
1612
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1613
    else:
1614
      self.wanted_names = None
1615
      self.needed_locks = {
1616
        locking.LEVEL_NODE: locking.ALL_SET,
1617
        locking.LEVEL_INSTANCE: locking.ALL_SET,
1618
        }
1619
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1620

    
1621
  def DeclareLocks(self, level):
1622
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
1623
      self._LockInstancesNodes(primary_only=True)
1624

    
1625
  def CheckPrereq(self):
1626
    """Check prerequisites.
1627

1628
    This only checks the optional instance list against the existing names.
1629

1630
    """
1631
    if self.wanted_names is None:
1632
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
1633

    
1634
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
1635
                             in self.wanted_names]
1636

    
1637
  def _EnsureChildSizes(self, disk):
1638
    """Ensure children of the disk have the needed disk size.
1639

1640
    This is valid mainly for DRBD8 and fixes an issue where the
1641
    children have smaller disk size.
1642

1643
    @param disk: an L{ganeti.objects.Disk} object
1644

1645
    """
1646
    if disk.dev_type == constants.LD_DRBD8:
1647
      assert disk.children, "Empty children for DRBD8?"
1648
      fchild = disk.children[0]
1649
      mismatch = fchild.size < disk.size
1650
      if mismatch:
1651
        self.LogInfo("Child disk has size %d, parent %d, fixing",
1652
                     fchild.size, disk.size)
1653
        fchild.size = disk.size
1654

    
1655
      # and we recurse on this child only, not on the metadev
1656
      return self._EnsureChildSizes(fchild) or mismatch
1657
    else:
1658
      return False
1659

    
1660
  def Exec(self, feedback_fn):
1661
    """Verify the size of cluster disks.
1662

1663
    """
1664
    # TODO: check child disks too
1665
    # TODO: check differences in size between primary/secondary nodes
1666
    per_node_disks = {}
1667
    for instance in self.wanted_instances:
1668
      pnode = instance.primary_node
1669
      if pnode not in per_node_disks:
1670
        per_node_disks[pnode] = []
1671
      for idx, disk in enumerate(instance.disks):
1672
        per_node_disks[pnode].append((instance, idx, disk))
1673

    
1674
    changed = []
1675
    for node, dskl in per_node_disks.items():
1676
      newl = [v[2].Copy() for v in dskl]
1677
      for dsk in newl:
1678
        self.cfg.SetDiskID(dsk, node)
1679
      result = self.rpc.call_blockdev_getsizes(node, newl)
1680
      if result.fail_msg:
1681
        self.LogWarning("Failure in blockdev_getsizes call to node"
1682
                        " %s, ignoring", node)
1683
        continue
1684
      if len(result.data) != len(dskl):
1685
        self.LogWarning("Invalid result from node %s, ignoring node results",
1686
                        node)
1687
        continue
1688
      for ((instance, idx, disk), size) in zip(dskl, result.data):
1689
        if size is None:
1690
          self.LogWarning("Disk %d of instance %s did not return size"
1691
                          " information, ignoring", idx, instance.name)
1692
          continue
1693
        if not isinstance(size, (int, long)):
1694
          self.LogWarning("Disk %d of instance %s did not return valid"
1695
                          " size information, ignoring", idx, instance.name)
1696
          continue
1697
        size = size >> 20
1698
        if size != disk.size:
1699
          self.LogInfo("Disk %d of instance %s has mismatched size,"
1700
                       " correcting: recorded %d, actual %d", idx,
1701
                       instance.name, disk.size, size)
1702
          disk.size = size
1703
          self.cfg.Update(instance)
1704
          changed.append((instance.name, idx, size))
1705
        if self._EnsureChildSizes(disk):
1706
          self.cfg.Update(instance)
1707
          changed.append((instance.name, idx, disk.size))
1708
    return changed
1709

    
1710

    
1711
class LURenameCluster(LogicalUnit):
1712
  """Rename the cluster.
1713

1714
  """
1715
  HPATH = "cluster-rename"
1716
  HTYPE = constants.HTYPE_CLUSTER
1717
  _OP_REQP = ["name"]
1718

    
1719
  def BuildHooksEnv(self):
1720
    """Build hooks env.
1721

1722
    """
1723
    env = {
1724
      "OP_TARGET": self.cfg.GetClusterName(),
1725
      "NEW_NAME": self.op.name,
1726
      }
1727
    mn = self.cfg.GetMasterNode()
1728
    return env, [mn], [mn]
1729

    
1730
  def CheckPrereq(self):
1731
    """Verify that the passed name is a valid one.
1732

1733
    """
1734
    hostname = utils.HostInfo(self.op.name)
1735

    
1736
    new_name = hostname.name
1737
    self.ip = new_ip = hostname.ip
1738
    old_name = self.cfg.GetClusterName()
1739
    old_ip = self.cfg.GetMasterIP()
1740
    if new_name == old_name and new_ip == old_ip:
1741
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1742
                                 " cluster has changed")
1743
    if new_ip != old_ip:
1744
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1745
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1746
                                   " reachable on the network. Aborting." %
1747
                                   new_ip)
1748

    
1749
    self.op.name = new_name
1750

    
1751
  def Exec(self, feedback_fn):
1752
    """Rename the cluster.
1753

1754
    """
1755
    clustername = self.op.name
1756
    ip = self.ip
1757

    
1758
    # shutdown the master IP
1759
    master = self.cfg.GetMasterNode()
1760
    result = self.rpc.call_node_stop_master(master, False)
1761
    result.Raise("Could not disable the master role")
1762

    
1763
    try:
1764
      cluster = self.cfg.GetClusterInfo()
1765
      cluster.cluster_name = clustername
1766
      cluster.master_ip = ip
1767
      self.cfg.Update(cluster)
1768

    
1769
      # update the known hosts file
1770
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1771
      node_list = self.cfg.GetNodeList()
1772
      try:
1773
        node_list.remove(master)
1774
      except ValueError:
1775
        pass
1776
      result = self.rpc.call_upload_file(node_list,
1777
                                         constants.SSH_KNOWN_HOSTS_FILE)
1778
      for to_node, to_result in result.iteritems():
1779
        msg = to_result.fail_msg
1780
        if msg:
1781
          msg = ("Copy of file %s to node %s failed: %s" %
1782
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
1783
          self.proc.LogWarning(msg)
1784

    
1785
    finally:
1786
      result = self.rpc.call_node_start_master(master, False, False)
1787
      msg = result.fail_msg
1788
      if msg:
1789
        self.LogWarning("Could not re-enable the master role on"
1790
                        " the master, please restart manually: %s", msg)
1791

    
1792

    
1793
def _RecursiveCheckIfLVMBased(disk):
1794
  """Check if the given disk or its children are lvm-based.
1795

1796
  @type disk: L{objects.Disk}
1797
  @param disk: the disk to check
1798
  @rtype: boolean
1799
  @return: boolean indicating whether a LD_LV dev_type was found or not
1800

1801
  """
1802
  if disk.children:
1803
    for chdisk in disk.children:
1804
      if _RecursiveCheckIfLVMBased(chdisk):
1805
        return True
1806
  return disk.dev_type == constants.LD_LV
1807

    
1808

    
1809
class LUSetClusterParams(LogicalUnit):
1810
  """Change the parameters of the cluster.
1811

1812
  """
1813
  HPATH = "cluster-modify"
1814
  HTYPE = constants.HTYPE_CLUSTER
1815
  _OP_REQP = []
1816
  REQ_BGL = False
1817

    
1818
  def CheckArguments(self):
1819
    """Check parameters
1820

1821
    """
1822
    if not hasattr(self.op, "candidate_pool_size"):
1823
      self.op.candidate_pool_size = None
1824
    if self.op.candidate_pool_size is not None:
1825
      try:
1826
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1827
      except (ValueError, TypeError), err:
1828
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1829
                                   str(err))
1830
      if self.op.candidate_pool_size < 1:
1831
        raise errors.OpPrereqError("At least one master candidate needed")
1832

    
1833
  def ExpandNames(self):
1834
    # FIXME: in the future maybe other cluster params won't require checking on
1835
    # all nodes to be modified.
1836
    self.needed_locks = {
1837
      locking.LEVEL_NODE: locking.ALL_SET,
1838
    }
1839
    self.share_locks[locking.LEVEL_NODE] = 1
1840

    
1841
  def BuildHooksEnv(self):
1842
    """Build hooks env.
1843

1844
    """
1845
    env = {
1846
      "OP_TARGET": self.cfg.GetClusterName(),
1847
      "NEW_VG_NAME": self.op.vg_name,
1848
      }
1849
    mn = self.cfg.GetMasterNode()
1850
    return env, [mn], [mn]
1851

    
1852
  def CheckPrereq(self):
1853
    """Check prerequisites.
1854

1855
    This checks whether the given params don't conflict and
1856
    if the given volume group is valid.
1857

1858
    """
1859
    if self.op.vg_name is not None and not self.op.vg_name:
1860
      instances = self.cfg.GetAllInstancesInfo().values()
1861
      for inst in instances:
1862
        for disk in inst.disks:
1863
          if _RecursiveCheckIfLVMBased(disk):
1864
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1865
                                       " lvm-based instances exist")
1866

    
1867
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1868

    
1869
    # if vg_name not None, checks given volume group on all nodes
1870
    if self.op.vg_name:
1871
      vglist = self.rpc.call_vg_list(node_list)
1872
      for node in node_list:
1873
        msg = vglist[node].fail_msg
1874
        if msg:
1875
          # ignoring down node
1876
          self.LogWarning("Error while gathering data on node %s"
1877
                          " (ignoring node): %s", node, msg)
1878
          continue
1879
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
1880
                                              self.op.vg_name,
1881
                                              constants.MIN_VG_SIZE)
1882
        if vgstatus:
1883
          raise errors.OpPrereqError("Error on node '%s': %s" %
1884
                                     (node, vgstatus))
1885

    
1886
    self.cluster = cluster = self.cfg.GetClusterInfo()
1887
    # validate params changes
1888
    if self.op.beparams:
1889
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
1890
      self.new_beparams = objects.FillDict(
1891
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
1892

    
1893
    if self.op.nicparams:
1894
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
1895
      self.new_nicparams = objects.FillDict(
1896
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
1897
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
1898

    
1899
    # hypervisor list/parameters
1900
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
1901
    if self.op.hvparams:
1902
      if not isinstance(self.op.hvparams, dict):
1903
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1904
      for hv_name, hv_dict in self.op.hvparams.items():
1905
        if hv_name not in self.new_hvparams:
1906
          self.new_hvparams[hv_name] = hv_dict
1907
        else:
1908
          self.new_hvparams[hv_name].update(hv_dict)
1909

    
1910
    if self.op.enabled_hypervisors is not None:
1911
      self.hv_list = self.op.enabled_hypervisors
1912
      if not self.hv_list:
1913
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
1914
                                   " least one member")
1915
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
1916
      if invalid_hvs:
1917
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
1918
                                   " entries: %s" %
1919
                                   utils.CommaJoin(invalid_hvs))
1920
    else:
1921
      self.hv_list = cluster.enabled_hypervisors
1922

    
1923
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1924
      # either the enabled list has changed, or the parameters have, validate
1925
      for hv_name, hv_params in self.new_hvparams.items():
1926
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1927
            (self.op.enabled_hypervisors and
1928
             hv_name in self.op.enabled_hypervisors)):
1929
          # either this is a new hypervisor, or its parameters have changed
1930
          hv_class = hypervisor.GetHypervisor(hv_name)
1931
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1932
          hv_class.CheckParameterSyntax(hv_params)
1933
          _CheckHVParams(self, node_list, hv_name, hv_params)
1934

    
1935
  def Exec(self, feedback_fn):
1936
    """Change the parameters of the cluster.
1937

1938
    """
1939
    if self.op.vg_name is not None:
1940
      new_volume = self.op.vg_name
1941
      if not new_volume:
1942
        new_volume = None
1943
      if new_volume != self.cfg.GetVGName():
1944
        self.cfg.SetVGName(new_volume)
1945
      else:
1946
        feedback_fn("Cluster LVM configuration already in desired"
1947
                    " state, not changing")
1948
    if self.op.hvparams:
1949
      self.cluster.hvparams = self.new_hvparams
1950
    if self.op.enabled_hypervisors is not None:
1951
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1952
    if self.op.beparams:
1953
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
1954
    if self.op.nicparams:
1955
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
1956

    
1957
    if self.op.candidate_pool_size is not None:
1958
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1959
      # we need to update the pool size here, otherwise the save will fail
1960
      _AdjustCandidatePool(self, [])
1961

    
1962
    self.cfg.Update(self.cluster)
1963

    
1964

    
1965
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
1966
  """Distribute additional files which are part of the cluster configuration.
1967

1968
  ConfigWriter takes care of distributing the config and ssconf files, but
1969
  there are more files which should be distributed to all nodes. This function
1970
  makes sure those are copied.
1971

1972
  @param lu: calling logical unit
1973
  @param additional_nodes: list of nodes not in the config to distribute to
1974

1975
  """
1976
  # 1. Gather target nodes
1977
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
1978
  dist_nodes = lu.cfg.GetNodeList()
1979
  if additional_nodes is not None:
1980
    dist_nodes.extend(additional_nodes)
1981
  if myself.name in dist_nodes:
1982
    dist_nodes.remove(myself.name)
1983
  # 2. Gather files to distribute
1984
  dist_files = set([constants.ETC_HOSTS,
1985
                    constants.SSH_KNOWN_HOSTS_FILE,
1986
                    constants.RAPI_CERT_FILE,
1987
                    constants.RAPI_USERS_FILE,
1988
                    constants.HMAC_CLUSTER_KEY,
1989
                   ])
1990

    
1991
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
1992
  for hv_name in enabled_hypervisors:
1993
    hv_class = hypervisor.GetHypervisor(hv_name)
1994
    dist_files.update(hv_class.GetAncillaryFiles())
1995

    
1996
  # 3. Perform the files upload
1997
  for fname in dist_files:
1998
    if os.path.exists(fname):
1999
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2000
      for to_node, to_result in result.items():
2001
        msg = to_result.fail_msg
2002
        if msg:
2003
          msg = ("Copy of file %s to node %s failed: %s" %
2004
                 (fname, to_node, msg))
2005
          lu.proc.LogWarning(msg)
2006

    
2007

    
2008
class LURedistributeConfig(NoHooksLU):
2009
  """Force the redistribution of cluster configuration.
2010

2011
  This is a very simple LU.
2012

2013
  """
2014
  _OP_REQP = []
2015
  REQ_BGL = False
2016

    
2017
  def ExpandNames(self):
2018
    self.needed_locks = {
2019
      locking.LEVEL_NODE: locking.ALL_SET,
2020
    }
2021
    self.share_locks[locking.LEVEL_NODE] = 1
2022

    
2023
  def CheckPrereq(self):
2024
    """Check prerequisites.
2025

2026
    """
2027

    
2028
  def Exec(self, feedback_fn):
2029
    """Redistribute the configuration.
2030

2031
    """
2032
    self.cfg.Update(self.cfg.GetClusterInfo())
2033
    _RedistributeAncillaryFiles(self)
2034

    
2035

    
2036
def _WaitForSync(lu, instance, oneshot=False, unlock=False):
2037
  """Sleep and poll for an instance's disk to sync.
2038

2039
  """
2040
  if not instance.disks:
2041
    return True
2042

    
2043
  if not oneshot:
2044
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2045

    
2046
  node = instance.primary_node
2047

    
2048
  for dev in instance.disks:
2049
    lu.cfg.SetDiskID(dev, node)
2050

    
2051
  retries = 0
2052
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2053
  while True:
2054
    max_time = 0
2055
    done = True
2056
    cumul_degraded = False
2057
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2058
    msg = rstats.fail_msg
2059
    if msg:
2060
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2061
      retries += 1
2062
      if retries >= 10:
2063
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2064
                                 " aborting." % node)
2065
      time.sleep(6)
2066
      continue
2067
    rstats = rstats.payload
2068
    retries = 0
2069
    for i, mstat in enumerate(rstats):
2070
      if mstat is None:
2071
        lu.LogWarning("Can't compute data for node %s/%s",
2072
                           node, instance.disks[i].iv_name)
2073
        continue
2074

    
2075
      cumul_degraded = (cumul_degraded or
2076
                        (mstat.is_degraded and mstat.sync_percent is None))
2077
      if mstat.sync_percent is not None:
2078
        done = False
2079
        if mstat.estimated_time is not None:
2080
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2081
          max_time = mstat.estimated_time
2082
        else:
2083
          rem_time = "no time estimate"
2084
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2085
                        (instance.disks[i].iv_name, mstat.sync_percent,
2086
                         rem_time))
2087

    
2088
    # if we're done but degraded, let's do a few small retries, to
2089
    # make sure we see a stable and not transient situation; therefore
2090
    # we force restart of the loop
2091
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2092
      logging.info("Degraded disks found, %d retries left", degr_retries)
2093
      degr_retries -= 1
2094
      time.sleep(1)
2095
      continue
2096

    
2097
    if done or oneshot:
2098
      break
2099

    
2100
    time.sleep(min(60, max_time))
2101

    
2102
  if done:
2103
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2104
  return not cumul_degraded
2105

    
2106

    
2107
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2108
  """Check that mirrors are not degraded.
2109

2110
  The ldisk parameter, if True, will change the test from the
2111
  is_degraded attribute (which represents overall non-ok status for
2112
  the device(s)) to the ldisk (representing the local storage status).
2113

2114
  """
2115
  lu.cfg.SetDiskID(dev, node)
2116

    
2117
  result = True
2118

    
2119
  if on_primary or dev.AssembleOnSecondary():
2120
    rstats = lu.rpc.call_blockdev_find(node, dev)
2121
    msg = rstats.fail_msg
2122
    if msg:
2123
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2124
      result = False
2125
    elif not rstats.payload:
2126
      lu.LogWarning("Can't find disk on node %s", node)
2127
      result = False
2128
    else:
2129
      if ldisk:
2130
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2131
      else:
2132
        result = result and not rstats.payload.is_degraded
2133

    
2134
  if dev.children:
2135
    for child in dev.children:
2136
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2137

    
2138
  return result
2139

    
2140

    
2141
class LUDiagnoseOS(NoHooksLU):
2142
  """Logical unit for OS diagnose/query.
2143

2144
  """
2145
  _OP_REQP = ["output_fields", "names"]
2146
  REQ_BGL = False
2147
  _FIELDS_STATIC = utils.FieldSet()
2148
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
2149

    
2150
  def ExpandNames(self):
2151
    if self.op.names:
2152
      raise errors.OpPrereqError("Selective OS query not supported")
2153

    
2154
    _CheckOutputFields(static=self._FIELDS_STATIC,
2155
                       dynamic=self._FIELDS_DYNAMIC,
2156
                       selected=self.op.output_fields)
2157

    
2158
    # Lock all nodes, in shared mode
2159
    # Temporary removal of locks, should be reverted later
2160
    # TODO: reintroduce locks when they are lighter-weight
2161
    self.needed_locks = {}
2162
    #self.share_locks[locking.LEVEL_NODE] = 1
2163
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2164

    
2165
  def CheckPrereq(self):
2166
    """Check prerequisites.
2167

2168
    """
2169

    
2170
  @staticmethod
2171
  def _DiagnoseByOS(node_list, rlist):
2172
    """Remaps a per-node return list into an a per-os per-node dictionary
2173

2174
    @param node_list: a list with the names of all nodes
2175
    @param rlist: a map with node names as keys and OS objects as values
2176

2177
    @rtype: dict
2178
    @return: a dictionary with osnames as keys and as value another map, with
2179
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2180

2181
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2182
                                     (/srv/..., False, "invalid api")],
2183
                           "node2": [(/srv/..., True, "")]}
2184
          }
2185

2186
    """
2187
    all_os = {}
2188
    # we build here the list of nodes that didn't fail the RPC (at RPC
2189
    # level), so that nodes with a non-responding node daemon don't
2190
    # make all OSes invalid
2191
    good_nodes = [node_name for node_name in rlist
2192
                  if not rlist[node_name].fail_msg]
2193
    for node_name, nr in rlist.items():
2194
      if nr.fail_msg or not nr.payload:
2195
        continue
2196
      for name, path, status, diagnose in nr.payload:
2197
        if name not in all_os:
2198
          # build a list of nodes for this os containing empty lists
2199
          # for each node in node_list
2200
          all_os[name] = {}
2201
          for nname in good_nodes:
2202
            all_os[name][nname] = []
2203
        all_os[name][node_name].append((path, status, diagnose))
2204
    return all_os
2205

    
2206
  def Exec(self, feedback_fn):
2207
    """Compute the list of OSes.
2208

2209
    """
2210
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2211
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2212
    pol = self._DiagnoseByOS(valid_nodes, node_data)
2213
    output = []
2214
    for os_name, os_data in pol.items():
2215
      row = []
2216
      for field in self.op.output_fields:
2217
        if field == "name":
2218
          val = os_name
2219
        elif field == "valid":
2220
          val = utils.all([osl and osl[0][1] for osl in os_data.values()])
2221
        elif field == "node_status":
2222
          # this is just a copy of the dict
2223
          val = {}
2224
          for node_name, nos_list in os_data.items():
2225
            val[node_name] = nos_list
2226
        else:
2227
          raise errors.ParameterError(field)
2228
        row.append(val)
2229
      output.append(row)
2230

    
2231
    return output
2232

    
2233

    
2234
class LURemoveNode(LogicalUnit):
2235
  """Logical unit for removing a node.
2236

2237
  """
2238
  HPATH = "node-remove"
2239
  HTYPE = constants.HTYPE_NODE
2240
  _OP_REQP = ["node_name"]
2241

    
2242
  def BuildHooksEnv(self):
2243
    """Build hooks env.
2244

2245
    This doesn't run on the target node in the pre phase as a failed
2246
    node would then be impossible to remove.
2247

2248
    """
2249
    env = {
2250
      "OP_TARGET": self.op.node_name,
2251
      "NODE_NAME": self.op.node_name,
2252
      }
2253
    all_nodes = self.cfg.GetNodeList()
2254
    if self.op.node_name in all_nodes:
2255
      all_nodes.remove(self.op.node_name)
2256
    return env, all_nodes, all_nodes
2257

    
2258
  def CheckPrereq(self):
2259
    """Check prerequisites.
2260

2261
    This checks:
2262
     - the node exists in the configuration
2263
     - it does not have primary or secondary instances
2264
     - it's not the master
2265

2266
    Any errors are signaled by raising errors.OpPrereqError.
2267

2268
    """
2269
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
2270
    if node is None:
2271
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
2272

    
2273
    instance_list = self.cfg.GetInstanceList()
2274

    
2275
    masternode = self.cfg.GetMasterNode()
2276
    if node.name == masternode:
2277
      raise errors.OpPrereqError("Node is the master node,"
2278
                                 " you need to failover first.")
2279

    
2280
    for instance_name in instance_list:
2281
      instance = self.cfg.GetInstanceInfo(instance_name)
2282
      if node.name in instance.all_nodes:
2283
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2284
                                   " please remove first." % instance_name)
2285
    self.op.node_name = node.name
2286
    self.node = node
2287

    
2288
  def Exec(self, feedback_fn):
2289
    """Removes the node from the cluster.
2290

2291
    """
2292
    node = self.node
2293
    logging.info("Stopping the node daemon and removing configs from node %s",
2294
                 node.name)
2295

    
2296
    # Promote nodes to master candidate as needed
2297
    _AdjustCandidatePool(self, exceptions=[node.name])
2298
    self.context.RemoveNode(node.name)
2299

    
2300
    # Run post hooks on the node before it's removed
2301
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2302
    try:
2303
      h_results = hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2304
    except:
2305
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2306

    
2307
    result = self.rpc.call_node_leave_cluster(node.name)
2308
    msg = result.fail_msg
2309
    if msg:
2310
      self.LogWarning("Errors encountered on the remote node while leaving"
2311
                      " the cluster: %s", msg)
2312

    
2313

    
2314
class LUQueryNodes(NoHooksLU):
2315
  """Logical unit for querying nodes.
2316

2317
  """
2318
  _OP_REQP = ["output_fields", "names", "use_locking"]
2319
  REQ_BGL = False
2320

    
2321
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2322
                    "master_candidate", "offline", "drained"]
2323

    
2324
  _FIELDS_DYNAMIC = utils.FieldSet(
2325
    "dtotal", "dfree",
2326
    "mtotal", "mnode", "mfree",
2327
    "bootid",
2328
    "ctotal", "cnodes", "csockets",
2329
    )
2330

    
2331
  _FIELDS_STATIC = utils.FieldSet(*[
2332
    "pinst_cnt", "sinst_cnt",
2333
    "pinst_list", "sinst_list",
2334
    "pip", "sip", "tags",
2335
    "master",
2336
    "role"] + _SIMPLE_FIELDS
2337
    )
2338

    
2339
  def ExpandNames(self):
2340
    _CheckOutputFields(static=self._FIELDS_STATIC,
2341
                       dynamic=self._FIELDS_DYNAMIC,
2342
                       selected=self.op.output_fields)
2343

    
2344
    self.needed_locks = {}
2345
    self.share_locks[locking.LEVEL_NODE] = 1
2346

    
2347
    if self.op.names:
2348
      self.wanted = _GetWantedNodes(self, self.op.names)
2349
    else:
2350
      self.wanted = locking.ALL_SET
2351

    
2352
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2353
    self.do_locking = self.do_node_query and self.op.use_locking
2354
    if self.do_locking:
2355
      # if we don't request only static fields, we need to lock the nodes
2356
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2357

    
2358

    
2359
  def CheckPrereq(self):
2360
    """Check prerequisites.
2361

2362
    """
2363
    # The validation of the node list is done in the _GetWantedNodes,
2364
    # if non empty, and if empty, there's no validation to do
2365
    pass
2366

    
2367
  def Exec(self, feedback_fn):
2368
    """Computes the list of nodes and their attributes.
2369

2370
    """
2371
    all_info = self.cfg.GetAllNodesInfo()
2372
    if self.do_locking:
2373
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2374
    elif self.wanted != locking.ALL_SET:
2375
      nodenames = self.wanted
2376
      missing = set(nodenames).difference(all_info.keys())
2377
      if missing:
2378
        raise errors.OpExecError(
2379
          "Some nodes were removed before retrieving their data: %s" % missing)
2380
    else:
2381
      nodenames = all_info.keys()
2382

    
2383
    nodenames = utils.NiceSort(nodenames)
2384
    nodelist = [all_info[name] for name in nodenames]
2385

    
2386
    # begin data gathering
2387

    
2388
    if self.do_node_query:
2389
      live_data = {}
2390
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2391
                                          self.cfg.GetHypervisorType())
2392
      for name in nodenames:
2393
        nodeinfo = node_data[name]
2394
        if not nodeinfo.fail_msg and nodeinfo.payload:
2395
          nodeinfo = nodeinfo.payload
2396
          fn = utils.TryConvert
2397
          live_data[name] = {
2398
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2399
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2400
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2401
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2402
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2403
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2404
            "bootid": nodeinfo.get('bootid', None),
2405
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2406
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2407
            }
2408
        else:
2409
          live_data[name] = {}
2410
    else:
2411
      live_data = dict.fromkeys(nodenames, {})
2412

    
2413
    node_to_primary = dict([(name, set()) for name in nodenames])
2414
    node_to_secondary = dict([(name, set()) for name in nodenames])
2415

    
2416
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2417
                             "sinst_cnt", "sinst_list"))
2418
    if inst_fields & frozenset(self.op.output_fields):
2419
      instancelist = self.cfg.GetInstanceList()
2420

    
2421
      for instance_name in instancelist:
2422
        inst = self.cfg.GetInstanceInfo(instance_name)
2423
        if inst.primary_node in node_to_primary:
2424
          node_to_primary[inst.primary_node].add(inst.name)
2425
        for secnode in inst.secondary_nodes:
2426
          if secnode in node_to_secondary:
2427
            node_to_secondary[secnode].add(inst.name)
2428

    
2429
    master_node = self.cfg.GetMasterNode()
2430

    
2431
    # end data gathering
2432

    
2433
    output = []
2434
    for node in nodelist:
2435
      node_output = []
2436
      for field in self.op.output_fields:
2437
        if field in self._SIMPLE_FIELDS:
2438
          val = getattr(node, field)
2439
        elif field == "pinst_list":
2440
          val = list(node_to_primary[node.name])
2441
        elif field == "sinst_list":
2442
          val = list(node_to_secondary[node.name])
2443
        elif field == "pinst_cnt":
2444
          val = len(node_to_primary[node.name])
2445
        elif field == "sinst_cnt":
2446
          val = len(node_to_secondary[node.name])
2447
        elif field == "pip":
2448
          val = node.primary_ip
2449
        elif field == "sip":
2450
          val = node.secondary_ip
2451
        elif field == "tags":
2452
          val = list(node.GetTags())
2453
        elif field == "master":
2454
          val = node.name == master_node
2455
        elif self._FIELDS_DYNAMIC.Matches(field):
2456
          val = live_data[node.name].get(field, None)
2457
        elif field == "role":
2458
          if node.name == master_node:
2459
            val = "M"
2460
          elif node.master_candidate:
2461
            val = "C"
2462
          elif node.drained:
2463
            val = "D"
2464
          elif node.offline:
2465
            val = "O"
2466
          else:
2467
            val = "R"
2468
        else:
2469
          raise errors.ParameterError(field)
2470
        node_output.append(val)
2471
      output.append(node_output)
2472

    
2473
    return output
2474

    
2475

    
2476
class LUQueryNodeVolumes(NoHooksLU):
2477
  """Logical unit for getting volumes on node(s).
2478

2479
  """
2480
  _OP_REQP = ["nodes", "output_fields"]
2481
  REQ_BGL = False
2482
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2483
  _FIELDS_STATIC = utils.FieldSet("node")
2484

    
2485
  def ExpandNames(self):
2486
    _CheckOutputFields(static=self._FIELDS_STATIC,
2487
                       dynamic=self._FIELDS_DYNAMIC,
2488
                       selected=self.op.output_fields)
2489

    
2490
    self.needed_locks = {}
2491
    self.share_locks[locking.LEVEL_NODE] = 1
2492
    if not self.op.nodes:
2493
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2494
    else:
2495
      self.needed_locks[locking.LEVEL_NODE] = \
2496
        _GetWantedNodes(self, self.op.nodes)
2497

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

2501
    This checks that the fields required are valid output fields.
2502

2503
    """
2504
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2505

    
2506
  def Exec(self, feedback_fn):
2507
    """Computes the list of nodes and their attributes.
2508

2509
    """
2510
    nodenames = self.nodes
2511
    volumes = self.rpc.call_node_volumes(nodenames)
2512

    
2513
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2514
             in self.cfg.GetInstanceList()]
2515

    
2516
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2517

    
2518
    output = []
2519
    for node in nodenames:
2520
      nresult = volumes[node]
2521
      if nresult.offline:
2522
        continue
2523
      msg = nresult.fail_msg
2524
      if msg:
2525
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
2526
        continue
2527

    
2528
      node_vols = nresult.payload[:]
2529
      node_vols.sort(key=lambda vol: vol['dev'])
2530

    
2531
      for vol in node_vols:
2532
        node_output = []
2533
        for field in self.op.output_fields:
2534
          if field == "node":
2535
            val = node
2536
          elif field == "phys":
2537
            val = vol['dev']
2538
          elif field == "vg":
2539
            val = vol['vg']
2540
          elif field == "name":
2541
            val = vol['name']
2542
          elif field == "size":
2543
            val = int(float(vol['size']))
2544
          elif field == "instance":
2545
            for inst in ilist:
2546
              if node not in lv_by_node[inst]:
2547
                continue
2548
              if vol['name'] in lv_by_node[inst][node]:
2549
                val = inst.name
2550
                break
2551
            else:
2552
              val = '-'
2553
          else:
2554
            raise errors.ParameterError(field)
2555
          node_output.append(str(val))
2556

    
2557
        output.append(node_output)
2558

    
2559
    return output
2560

    
2561

    
2562
class LUQueryNodeStorage(NoHooksLU):
2563
  """Logical unit for getting information on storage units on node(s).
2564

2565
  """
2566
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
2567
  REQ_BGL = False
2568
  _FIELDS_STATIC = utils.FieldSet("node")
2569

    
2570
  def ExpandNames(self):
2571
    storage_type = self.op.storage_type
2572

    
2573
    if storage_type not in constants.VALID_STORAGE_FIELDS:
2574
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type)
2575

    
2576
    dynamic_fields = constants.VALID_STORAGE_FIELDS[storage_type]
2577

    
2578
    _CheckOutputFields(static=self._FIELDS_STATIC,
2579
                       dynamic=utils.FieldSet(*dynamic_fields),
2580
                       selected=self.op.output_fields)
2581

    
2582
    self.needed_locks = {}
2583
    self.share_locks[locking.LEVEL_NODE] = 1
2584

    
2585
    if self.op.nodes:
2586
      self.needed_locks[locking.LEVEL_NODE] = \
2587
        _GetWantedNodes(self, self.op.nodes)
2588
    else:
2589
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2590

    
2591
  def CheckPrereq(self):
2592
    """Check prerequisites.
2593

2594
    This checks that the fields required are valid output fields.
2595

2596
    """
2597
    self.op.name = getattr(self.op, "name", None)
2598

    
2599
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2600

    
2601
  def Exec(self, feedback_fn):
2602
    """Computes the list of nodes and their attributes.
2603

2604
    """
2605
    # Always get name to sort by
2606
    if constants.SF_NAME in self.op.output_fields:
2607
      fields = self.op.output_fields[:]
2608
    else:
2609
      fields = [constants.SF_NAME] + self.op.output_fields
2610

    
2611
    # Never ask for node as it's only known to the LU
2612
    while "node" in fields:
2613
      fields.remove("node")
2614

    
2615
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
2616
    name_idx = field_idx[constants.SF_NAME]
2617

    
2618
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2619
    data = self.rpc.call_storage_list(self.nodes,
2620
                                      self.op.storage_type, st_args,
2621
                                      self.op.name, fields)
2622

    
2623
    result = []
2624

    
2625
    for node in utils.NiceSort(self.nodes):
2626
      nresult = data[node]
2627
      if nresult.offline:
2628
        continue
2629

    
2630
      msg = nresult.fail_msg
2631
      if msg:
2632
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
2633
        continue
2634

    
2635
      rows = dict([(row[name_idx], row) for row in nresult.payload])
2636

    
2637
      for name in utils.NiceSort(rows.keys()):
2638
        row = rows[name]
2639

    
2640
        out = []
2641

    
2642
        for field in self.op.output_fields:
2643
          if field == "node":
2644
            val = node
2645
          elif field in field_idx:
2646
            val = row[field_idx[field]]
2647
          else:
2648
            raise errors.ParameterError(field)
2649

    
2650
          out.append(val)
2651

    
2652
        result.append(out)
2653

    
2654
    return result
2655

    
2656

    
2657
class LUModifyNodeStorage(NoHooksLU):
2658
  """Logical unit for modifying a storage volume on a node.
2659

2660
  """
2661
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
2662
  REQ_BGL = False
2663

    
2664
  def CheckArguments(self):
2665
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2666
    if node_name is None:
2667
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2668

    
2669
    self.op.node_name = node_name
2670

    
2671
    storage_type = self.op.storage_type
2672
    if storage_type not in constants.VALID_STORAGE_FIELDS:
2673
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type)
2674

    
2675
  def ExpandNames(self):
2676
    self.needed_locks = {
2677
      locking.LEVEL_NODE: self.op.node_name,
2678
      }
2679

    
2680
  def CheckPrereq(self):
2681
    """Check prerequisites.
2682

2683
    """
2684
    storage_type = self.op.storage_type
2685

    
2686
    try:
2687
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
2688
    except KeyError:
2689
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
2690
                                 " modified" % storage_type)
2691

    
2692
    diff = set(self.op.changes.keys()) - modifiable
2693
    if diff:
2694
      raise errors.OpPrereqError("The following fields can not be modified for"
2695
                                 " storage units of type '%s': %r" %
2696
                                 (storage_type, list(diff)))
2697

    
2698
  def Exec(self, feedback_fn):
2699
    """Computes the list of nodes and their attributes.
2700

2701
    """
2702
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2703
    result = self.rpc.call_storage_modify(self.op.node_name,
2704
                                          self.op.storage_type, st_args,
2705
                                          self.op.name, self.op.changes)
2706
    result.Raise("Failed to modify storage unit '%s' on %s" %
2707
                 (self.op.name, self.op.node_name))
2708

    
2709

    
2710
class LUAddNode(LogicalUnit):
2711
  """Logical unit for adding node to the cluster.
2712

2713
  """
2714
  HPATH = "node-add"
2715
  HTYPE = constants.HTYPE_NODE
2716
  _OP_REQP = ["node_name"]
2717

    
2718
  def BuildHooksEnv(self):
2719
    """Build hooks env.
2720

2721
    This will run on all nodes before, and on all nodes + the new node after.
2722

2723
    """
2724
    env = {
2725
      "OP_TARGET": self.op.node_name,
2726
      "NODE_NAME": self.op.node_name,
2727
      "NODE_PIP": self.op.primary_ip,
2728
      "NODE_SIP": self.op.secondary_ip,
2729
      }
2730
    nodes_0 = self.cfg.GetNodeList()
2731
    nodes_1 = nodes_0 + [self.op.node_name, ]
2732
    return env, nodes_0, nodes_1
2733

    
2734
  def CheckPrereq(self):
2735
    """Check prerequisites.
2736

2737
    This checks:
2738
     - the new node is not already in the config
2739
     - it is resolvable
2740
     - its parameters (single/dual homed) matches the cluster
2741

2742
    Any errors are signaled by raising errors.OpPrereqError.
2743

2744
    """
2745
    node_name = self.op.node_name
2746
    cfg = self.cfg
2747

    
2748
    dns_data = utils.HostInfo(node_name)
2749

    
2750
    node = dns_data.name
2751
    primary_ip = self.op.primary_ip = dns_data.ip
2752
    secondary_ip = getattr(self.op, "secondary_ip", None)
2753
    if secondary_ip is None:
2754
      secondary_ip = primary_ip
2755
    if not utils.IsValidIP(secondary_ip):
2756
      raise errors.OpPrereqError("Invalid secondary IP given")
2757
    self.op.secondary_ip = secondary_ip
2758

    
2759
    node_list = cfg.GetNodeList()
2760
    if not self.op.readd and node in node_list:
2761
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2762
                                 node)
2763
    elif self.op.readd and node not in node_list:
2764
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2765

    
2766
    for existing_node_name in node_list:
2767
      existing_node = cfg.GetNodeInfo(existing_node_name)
2768

    
2769
      if self.op.readd and node == existing_node_name:
2770
        if (existing_node.primary_ip != primary_ip or
2771
            existing_node.secondary_ip != secondary_ip):
2772
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2773
                                     " address configuration as before")
2774
        continue
2775

    
2776
      if (existing_node.primary_ip == primary_ip or
2777
          existing_node.secondary_ip == primary_ip or
2778
          existing_node.primary_ip == secondary_ip or
2779
          existing_node.secondary_ip == secondary_ip):
2780
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2781
                                   " existing node %s" % existing_node.name)
2782

    
2783
    # check that the type of the node (single versus dual homed) is the
2784
    # same as for the master
2785
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2786
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2787
    newbie_singlehomed = secondary_ip == primary_ip
2788
    if master_singlehomed != newbie_singlehomed:
2789
      if master_singlehomed:
2790
        raise errors.OpPrereqError("The master has no private ip but the"
2791
                                   " new node has one")
2792
      else:
2793
        raise errors.OpPrereqError("The master has a private ip but the"
2794
                                   " new node doesn't have one")
2795

    
2796
    # checks reachability
2797
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2798
      raise errors.OpPrereqError("Node not reachable by ping")
2799

    
2800
    if not newbie_singlehomed:
2801
      # check reachability from my secondary ip to newbie's secondary ip
2802
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2803
                           source=myself.secondary_ip):
2804
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2805
                                   " based ping to noded port")
2806

    
2807
    if self.op.readd:
2808
      exceptions = [node]
2809
    else:
2810
      exceptions = []
2811

    
2812
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
2813

    
2814
    if self.op.readd:
2815
      self.new_node = self.cfg.GetNodeInfo(node)
2816
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
2817
    else:
2818
      self.new_node = objects.Node(name=node,
2819
                                   primary_ip=primary_ip,
2820
                                   secondary_ip=secondary_ip,
2821
                                   master_candidate=self.master_candidate,
2822
                                   offline=False, drained=False)
2823

    
2824
  def Exec(self, feedback_fn):
2825
    """Adds the new node to the cluster.
2826

2827
    """
2828
    new_node = self.new_node
2829
    node = new_node.name
2830

    
2831
    # for re-adds, reset the offline/drained/master-candidate flags;
2832
    # we need to reset here, otherwise offline would prevent RPC calls
2833
    # later in the procedure; this also means that if the re-add
2834
    # fails, we are left with a non-offlined, broken node
2835
    if self.op.readd:
2836
      new_node.drained = new_node.offline = False
2837
      self.LogInfo("Readding a node, the offline/drained flags were reset")
2838
      # if we demote the node, we do cleanup later in the procedure
2839
      new_node.master_candidate = self.master_candidate
2840

    
2841
    # notify the user about any possible mc promotion
2842
    if new_node.master_candidate:
2843
      self.LogInfo("Node will be a master candidate")
2844

    
2845
    # check connectivity
2846
    result = self.rpc.call_version([node])[node]
2847
    result.Raise("Can't get version information from node %s" % node)
2848
    if constants.PROTOCOL_VERSION == result.payload:
2849
      logging.info("Communication to node %s fine, sw version %s match",
2850
                   node, result.payload)
2851
    else:
2852
      raise errors.OpExecError("Version mismatch master version %s,"
2853
                               " node version %s" %
2854
                               (constants.PROTOCOL_VERSION, result.payload))
2855

    
2856
    # setup ssh on node
2857
    logging.info("Copy ssh key to node %s", node)
2858
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2859
    keyarray = []
2860
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2861
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2862
                priv_key, pub_key]
2863

    
2864
    for i in keyfiles:
2865
      keyarray.append(utils.ReadFile(i))
2866

    
2867
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2868
                                    keyarray[2],
2869
                                    keyarray[3], keyarray[4], keyarray[5])
2870
    result.Raise("Cannot transfer ssh keys to the new node")
2871

    
2872
    # Add node to our /etc/hosts, and add key to known_hosts
2873
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2874
      utils.AddHostToEtcHosts(new_node.name)
2875

    
2876
    if new_node.secondary_ip != new_node.primary_ip:
2877
      result = self.rpc.call_node_has_ip_address(new_node.name,
2878
                                                 new_node.secondary_ip)
2879
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
2880
                   prereq=True)
2881
      if not result.payload:
2882
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2883
                                 " you gave (%s). Please fix and re-run this"
2884
                                 " command." % new_node.secondary_ip)
2885

    
2886
    node_verify_list = [self.cfg.GetMasterNode()]
2887
    node_verify_param = {
2888
      constants.NV_NODELIST: [node],
2889
      # TODO: do a node-net-test as well?
2890
    }
2891

    
2892
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2893
                                       self.cfg.GetClusterName())
2894
    for verifier in node_verify_list:
2895
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
2896
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
2897
      if nl_payload:
2898
        for failed in nl_payload:
2899
          feedback_fn("ssh/hostname verification failed"
2900
                      " (checking from %s): %s" %
2901
                      (verifier, nl_payload[failed]))
2902
        raise errors.OpExecError("ssh/hostname verification failed.")
2903

    
2904
    if self.op.readd:
2905
      _RedistributeAncillaryFiles(self)
2906
      self.context.ReaddNode(new_node)
2907
      # make sure we redistribute the config
2908
      self.cfg.Update(new_node)
2909
      # and make sure the new node will not have old files around
2910
      if not new_node.master_candidate:
2911
        result = self.rpc.call_node_demote_from_mc(new_node.name)
2912
        msg = result.fail_msg
2913
        if msg:
2914
          self.LogWarning("Node failed to demote itself from master"
2915
                          " candidate status: %s" % msg)
2916
    else:
2917
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
2918
      self.context.AddNode(new_node)
2919

    
2920

    
2921
class LUSetNodeParams(LogicalUnit):
2922
  """Modifies the parameters of a node.
2923

2924
  """
2925
  HPATH = "node-modify"
2926
  HTYPE = constants.HTYPE_NODE
2927
  _OP_REQP = ["node_name"]
2928
  REQ_BGL = False
2929

    
2930
  def CheckArguments(self):
2931
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2932
    if node_name is None:
2933
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2934
    self.op.node_name = node_name
2935
    _CheckBooleanOpField(self.op, 'master_candidate')
2936
    _CheckBooleanOpField(self.op, 'offline')
2937
    _CheckBooleanOpField(self.op, 'drained')
2938
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
2939
    if all_mods.count(None) == 3:
2940
      raise errors.OpPrereqError("Please pass at least one modification")
2941
    if all_mods.count(True) > 1:
2942
      raise errors.OpPrereqError("Can't set the node into more than one"
2943
                                 " state at the same time")
2944

    
2945
  def ExpandNames(self):
2946
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2947

    
2948
  def BuildHooksEnv(self):
2949
    """Build hooks env.
2950

2951
    This runs on the master node.
2952

2953
    """
2954
    env = {
2955
      "OP_TARGET": self.op.node_name,
2956
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2957
      "OFFLINE": str(self.op.offline),
2958
      "DRAINED": str(self.op.drained),
2959
      }
2960
    nl = [self.cfg.GetMasterNode(),
2961
          self.op.node_name]
2962
    return env, nl, nl
2963

    
2964
  def CheckPrereq(self):
2965
    """Check prerequisites.
2966

2967
    This only checks the instance list against the existing names.
2968

2969
    """
2970
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2971

    
2972
    if (self.op.master_candidate is not None or
2973
        self.op.drained is not None or
2974
        self.op.offline is not None):
2975
      # we can't change the master's node flags
2976
      if self.op.node_name == self.cfg.GetMasterNode():
2977
        raise errors.OpPrereqError("The master role can be changed"
2978
                                   " only via masterfailover")
2979

    
2980
    # Boolean value that tells us whether we're offlining or draining the node
2981
    offline_or_drain = self.op.offline == True or self.op.drained == True
2982

    
2983
    if (node.master_candidate and
2984
        (self.op.master_candidate == False or offline_or_drain)):
2985
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2986
      mc_now, mc_should, mc_max = self.cfg.GetMasterCandidateStats()
2987
      if mc_now <= cp_size:
2988
        msg = ("Not enough master candidates (desired"
2989
               " %d, new value will be %d)" % (cp_size, mc_now-1))
2990
        # Only allow forcing the operation if it's an offline/drain operation,
2991
        # and we could not possibly promote more nodes.
2992
        # FIXME: this can still lead to issues if in any way another node which
2993
        # could be promoted appears in the meantime.
2994
        if self.op.force and offline_or_drain and mc_should == mc_max:
2995
          self.LogWarning(msg)
2996
        else:
2997
          raise errors.OpPrereqError(msg)
2998

    
2999
    if (self.op.master_candidate == True and
3000
        ((node.offline and not self.op.offline == False) or
3001
         (node.drained and not self.op.drained == False))):
3002
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3003
                                 " to master_candidate" % node.name)
3004

    
3005
    return
3006

    
3007
  def Exec(self, feedback_fn):
3008
    """Modifies a node.
3009

3010
    """
3011
    node = self.node
3012

    
3013
    result = []
3014
    changed_mc = False
3015

    
3016
    if self.op.offline is not None:
3017
      node.offline = self.op.offline
3018
      result.append(("offline", str(self.op.offline)))
3019
      if self.op.offline == True:
3020
        if node.master_candidate:
3021
          node.master_candidate = False
3022
          changed_mc = True
3023
          result.append(("master_candidate", "auto-demotion due to offline"))
3024
        if node.drained:
3025
          node.drained = False
3026
          result.append(("drained", "clear drained status due to offline"))
3027

    
3028
    if self.op.master_candidate is not None:
3029
      node.master_candidate = self.op.master_candidate
3030
      changed_mc = True
3031
      result.append(("master_candidate", str(self.op.master_candidate)))
3032
      if self.op.master_candidate == False:
3033
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3034
        msg = rrc.fail_msg
3035
        if msg:
3036
          self.LogWarning("Node failed to demote itself: %s" % msg)
3037

    
3038
    if self.op.drained is not None:
3039
      node.drained = self.op.drained
3040
      result.append(("drained", str(self.op.drained)))
3041
      if self.op.drained == True:
3042
        if node.master_candidate:
3043
          node.master_candidate = False
3044
          changed_mc = True
3045
          result.append(("master_candidate", "auto-demotion due to drain"))
3046
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3047
          msg = rrc.fail_msg
3048
          if msg:
3049
            self.LogWarning("Node failed to demote itself: %s" % msg)
3050
        if node.offline:
3051
          node.offline = False
3052
          result.append(("offline", "clear offline status due to drain"))
3053

    
3054
    # this will trigger configuration file update, if needed
3055
    self.cfg.Update(node)
3056
    # this will trigger job queue propagation or cleanup
3057
    if changed_mc:
3058
      self.context.ReaddNode(node)
3059

    
3060
    return result
3061

    
3062

    
3063
class LUPowercycleNode(NoHooksLU):
3064
  """Powercycles a node.
3065

3066
  """
3067
  _OP_REQP = ["node_name", "force"]
3068
  REQ_BGL = False
3069

    
3070
  def CheckArguments(self):
3071
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3072
    if node_name is None:
3073
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
3074
    self.op.node_name = node_name
3075
    if node_name == self.cfg.GetMasterNode() and not self.op.force:
3076
      raise errors.OpPrereqError("The node is the master and the force"
3077
                                 " parameter was not set")
3078

    
3079
  def ExpandNames(self):
3080
    """Locking for PowercycleNode.
3081

3082
    This is a last-resort option and shouldn't block on other
3083
    jobs. Therefore, we grab no locks.
3084

3085
    """
3086
    self.needed_locks = {}
3087

    
3088
  def CheckPrereq(self):
3089
    """Check prerequisites.
3090

3091
    This LU has no prereqs.
3092

3093
    """
3094
    pass
3095

    
3096
  def Exec(self, feedback_fn):
3097
    """Reboots a node.
3098

3099
    """
3100
    result = self.rpc.call_node_powercycle(self.op.node_name,
3101
                                           self.cfg.GetHypervisorType())
3102
    result.Raise("Failed to schedule the reboot")
3103
    return result.payload
3104

    
3105

    
3106
class LUQueryClusterInfo(NoHooksLU):
3107
  """Query cluster configuration.
3108

3109
  """
3110
  _OP_REQP = []
3111
  REQ_BGL = False
3112

    
3113
  def ExpandNames(self):
3114
    self.needed_locks = {}
3115

    
3116
  def CheckPrereq(self):
3117
    """No prerequsites needed for this LU.
3118

3119
    """
3120
    pass
3121

    
3122
  def Exec(self, feedback_fn):
3123
    """Return cluster config.
3124

3125
    """
3126
    cluster = self.cfg.GetClusterInfo()
3127
    result = {
3128
      "software_version": constants.RELEASE_VERSION,
3129
      "protocol_version": constants.PROTOCOL_VERSION,
3130
      "config_version": constants.CONFIG_VERSION,
3131
      "os_api_version": max(constants.OS_API_VERSIONS),
3132
      "export_version": constants.EXPORT_VERSION,
3133
      "architecture": (platform.architecture()[0], platform.machine()),
3134
      "name": cluster.cluster_name,
3135
      "master": cluster.master_node,
3136
      "default_hypervisor": cluster.enabled_hypervisors[0],
3137
      "enabled_hypervisors": cluster.enabled_hypervisors,
3138
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3139
                        for hypervisor_name in cluster.enabled_hypervisors]),
3140
      "beparams": cluster.beparams,
3141
      "nicparams": cluster.nicparams,
3142
      "candidate_pool_size": cluster.candidate_pool_size,
3143
      "master_netdev": cluster.master_netdev,
3144
      "volume_group_name": cluster.volume_group_name,
3145
      "file_storage_dir": cluster.file_storage_dir,
3146
      "ctime": cluster.ctime,
3147
      "mtime": cluster.mtime,
3148
      "uuid": cluster.uuid,
3149
      "tags": list(cluster.GetTags()),
3150
      }
3151

    
3152
    return result
3153

    
3154

    
3155
class LUQueryConfigValues(NoHooksLU):
3156
  """Return configuration values.
3157

3158
  """
3159
  _OP_REQP = []
3160
  REQ_BGL = False
3161
  _FIELDS_DYNAMIC = utils.FieldSet()
3162
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3163
                                  "watcher_pause")
3164

    
3165
  def ExpandNames(self):
3166
    self.needed_locks = {}
3167

    
3168
    _CheckOutputFields(static=self._FIELDS_STATIC,
3169
                       dynamic=self._FIELDS_DYNAMIC,
3170
                       selected=self.op.output_fields)
3171

    
3172
  def CheckPrereq(self):
3173
    """No prerequisites.
3174

3175
    """
3176
    pass
3177

    
3178
  def Exec(self, feedback_fn):
3179
    """Dump a representation of the cluster config to the standard output.
3180

3181
    """
3182
    values = []
3183
    for field in self.op.output_fields:
3184
      if field == "cluster_name":
3185
        entry = self.cfg.GetClusterName()
3186
      elif field == "master_node":
3187
        entry = self.cfg.GetMasterNode()
3188
      elif field == "drain_flag":
3189
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3190
      elif field == "watcher_pause":
3191
        return utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3192
      else:
3193
        raise errors.ParameterError(field)
3194
      values.append(entry)
3195
    return values
3196

    
3197

    
3198
class LUActivateInstanceDisks(NoHooksLU):
3199
  """Bring up an instance's disks.
3200

3201
  """
3202
  _OP_REQP = ["instance_name"]
3203
  REQ_BGL = False
3204

    
3205
  def ExpandNames(self):
3206
    self._ExpandAndLockInstance()
3207
    self.needed_locks[locking.LEVEL_NODE] = []
3208
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3209

    
3210
  def DeclareLocks(self, level):
3211
    if level == locking.LEVEL_NODE:
3212
      self._LockInstancesNodes()
3213

    
3214
  def CheckPrereq(self):
3215
    """Check prerequisites.
3216

3217
    This checks that the instance is in the cluster.
3218

3219
    """
3220
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3221
    assert self.instance is not None, \
3222
      "Cannot retrieve locked instance %s" % self.op.instance_name
3223
    _CheckNodeOnline(self, self.instance.primary_node)
3224
    if not hasattr(self.op, "ignore_size"):
3225
      self.op.ignore_size = False
3226

    
3227
  def Exec(self, feedback_fn):
3228
    """Activate the disks.
3229

3230
    """
3231
    disks_ok, disks_info = \
3232
              _AssembleInstanceDisks(self, self.instance,
3233
                                     ignore_size=self.op.ignore_size)
3234
    if not disks_ok:
3235
      raise errors.OpExecError("Cannot activate block devices")
3236

    
3237
    return disks_info
3238

    
3239

    
3240
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3241
                           ignore_size=False):
3242
  """Prepare the block devices for an instance.
3243

3244
  This sets up the block devices on all nodes.
3245

3246
  @type lu: L{LogicalUnit}
3247
  @param lu: the logical unit on whose behalf we execute
3248
  @type instance: L{objects.Instance}
3249
  @param instance: the instance for whose disks we assemble
3250
  @type ignore_secondaries: boolean
3251
  @param ignore_secondaries: if true, errors on secondary nodes
3252
      won't result in an error return from the function
3253
  @type ignore_size: boolean
3254
  @param ignore_size: if true, the current known size of the disk
3255
      will not be used during the disk activation, useful for cases
3256
      when the size is wrong
3257
  @return: False if the operation failed, otherwise a list of
3258
      (host, instance_visible_name, node_visible_name)
3259
      with the mapping from node devices to instance devices
3260

3261
  """
3262
  device_info = []
3263
  disks_ok = True
3264
  iname = instance.name
3265
  # With the two passes mechanism we try to reduce the window of
3266
  # opportunity for the race condition of switching DRBD to primary
3267
  # before handshaking occured, but we do not eliminate it
3268

    
3269
  # The proper fix would be to wait (with some limits) until the
3270
  # connection has been made and drbd transitions from WFConnection
3271
  # into any other network-connected state (Connected, SyncTarget,
3272
  # SyncSource, etc.)
3273

    
3274
  # 1st pass, assemble on all nodes in secondary mode
3275
  for inst_disk in instance.disks:
3276
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3277
      if ignore_size:
3278
        node_disk = node_disk.Copy()
3279
        node_disk.UnsetSize()
3280
      lu.cfg.SetDiskID(node_disk, node)
3281
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3282
      msg = result.fail_msg
3283
      if msg:
3284
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3285
                           " (is_primary=False, pass=1): %s",
3286
                           inst_disk.iv_name, node, msg)
3287
        if not ignore_secondaries:
3288
          disks_ok = False
3289

    
3290
  # FIXME: race condition on drbd migration to primary
3291

    
3292
  # 2nd pass, do only the primary node
3293
  for inst_disk in instance.disks:
3294
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3295
      if node != instance.primary_node:
3296
        continue
3297
      if ignore_size:
3298
        node_disk = node_disk.Copy()
3299
        node_disk.UnsetSize()
3300
      lu.cfg.SetDiskID(node_disk, node)
3301
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3302
      msg = result.fail_msg
3303
      if msg:
3304
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3305
                           " (is_primary=True, pass=2): %s",
3306
                           inst_disk.iv_name, node, msg)
3307
        disks_ok = False
3308
    device_info.append((instance.primary_node, inst_disk.iv_name,
3309
                        result.payload))
3310

    
3311
  # leave the disks configured for the primary node
3312
  # this is a workaround that would be fixed better by
3313
  # improving the logical/physical id handling
3314
  for disk in instance.disks:
3315
    lu.cfg.SetDiskID(disk, instance.primary_node)
3316

    
3317
  return disks_ok, device_info
3318

    
3319

    
3320
def _StartInstanceDisks(lu, instance, force):
3321
  """Start the disks of an instance.
3322

3323
  """
3324
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3325
                                           ignore_secondaries=force)
3326
  if not disks_ok:
3327
    _ShutdownInstanceDisks(lu, instance)
3328
    if force is not None and not force:
3329
      lu.proc.LogWarning("", hint="If the message above refers to a"
3330
                         " secondary node,"
3331
                         " you can retry the operation using '--force'.")
3332
    raise errors.OpExecError("Disk consistency error")
3333

    
3334

    
3335
class LUDeactivateInstanceDisks(NoHooksLU):
3336
  """Shutdown an instance's disks.
3337

3338
  """
3339
  _OP_REQP = ["instance_name"]
3340
  REQ_BGL = False
3341

    
3342
  def ExpandNames(self):
3343
    self._ExpandAndLockInstance()
3344
    self.needed_locks[locking.LEVEL_NODE] = []
3345
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3346

    
3347
  def DeclareLocks(self, level):
3348
    if level == locking.LEVEL_NODE:
3349
      self._LockInstancesNodes()
3350

    
3351
  def CheckPrereq(self):
3352
    """Check prerequisites.
3353

3354
    This checks that the instance is in the cluster.
3355

3356
    """
3357
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3358
    assert self.instance is not None, \
3359
      "Cannot retrieve locked instance %s" % self.op.instance_name
3360

    
3361
  def Exec(self, feedback_fn):
3362
    """Deactivate the disks
3363

3364
    """
3365
    instance = self.instance
3366
    _SafeShutdownInstanceDisks(self, instance)
3367

    
3368

    
3369
def _SafeShutdownInstanceDisks(lu, instance):
3370
  """Shutdown block devices of an instance.
3371

3372
  This function checks if an instance is running, before calling
3373
  _ShutdownInstanceDisks.
3374

3375
  """
3376
  pnode = instance.primary_node
3377
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
3378
  ins_l.Raise("Can't contact node %s" % pnode)
3379

    
3380
  if instance.name in ins_l.payload:
3381
    raise errors.OpExecError("Instance is running, can't shutdown"
3382
                             " block devices.")
3383

    
3384
  _ShutdownInstanceDisks(lu, instance)
3385

    
3386

    
3387
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3388
  """Shutdown block devices of an instance.
3389

3390
  This does the shutdown on all nodes of the instance.
3391

3392
  If the ignore_primary is false, errors on the primary node are
3393
  ignored.
3394

3395
  """
3396
  all_result = True
3397
  for disk in instance.disks:
3398
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3399
      lu.cfg.SetDiskID(top_disk, node)
3400
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3401
      msg = result.fail_msg
3402
      if msg:
3403
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3404
                      disk.iv_name, node, msg)
3405
        if not ignore_primary or node != instance.primary_node:
3406
          all_result = False
3407
  return all_result
3408

    
3409

    
3410
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3411
  """Checks if a node has enough free memory.
3412

3413
  This function check if a given node has the needed amount of free
3414
  memory. In case the node has less memory or we cannot get the
3415
  information from the node, this function raise an OpPrereqError
3416
  exception.
3417

3418
  @type lu: C{LogicalUnit}
3419
  @param lu: a logical unit from which we get configuration data
3420
  @type node: C{str}
3421
  @param node: the node to check
3422
  @type reason: C{str}
3423
  @param reason: string to use in the error message
3424
  @type requested: C{int}
3425
  @param requested: the amount of memory in MiB to check for
3426
  @type hypervisor_name: C{str}
3427
  @param hypervisor_name: the hypervisor to ask for memory stats
3428
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3429
      we cannot check the node
3430

3431
  """
3432
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3433
  nodeinfo[node].Raise("Can't get data from node %s" % node, prereq=True)
3434
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3435
  if not isinstance(free_mem, int):
3436
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3437
                               " was '%s'" % (node, free_mem))
3438
  if requested > free_mem:
3439
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3440
                               " needed %s MiB, available %s MiB" %
3441
                               (node, reason, requested, free_mem))
3442

    
3443

    
3444
class LUStartupInstance(LogicalUnit):
3445
  """Starts an instance.
3446

3447
  """
3448
  HPATH = "instance-start"
3449
  HTYPE = constants.HTYPE_INSTANCE
3450
  _OP_REQP = ["instance_name", "force"]
3451
  REQ_BGL = False
3452

    
3453
  def ExpandNames(self):
3454
    self._ExpandAndLockInstance()
3455

    
3456
  def BuildHooksEnv(self):
3457
    """Build hooks env.
3458

3459
    This runs on master, primary and secondary nodes of the instance.
3460

3461
    """
3462
    env = {
3463
      "FORCE": self.op.force,
3464
      }
3465
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3466
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3467
    return env, nl, nl
3468

    
3469
  def CheckPrereq(self):
3470
    """Check prerequisites.
3471

3472
    This checks that the instance is in the cluster.
3473

3474
    """
3475
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3476
    assert self.instance is not None, \
3477
      "Cannot retrieve locked instance %s" % self.op.instance_name
3478

    
3479
    # extra beparams
3480
    self.beparams = getattr(self.op, "beparams", {})
3481
    if self.beparams:
3482
      if not isinstance(self.beparams, dict):
3483
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3484
                                   " dict" % (type(self.beparams), ))
3485
      # fill the beparams dict
3486
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3487
      self.op.beparams = self.beparams
3488

    
3489
    # extra hvparams
3490
    self.hvparams = getattr(self.op, "hvparams", {})
3491
    if self.hvparams:
3492
      if not isinstance(self.hvparams, dict):
3493
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3494
                                   " dict" % (type(self.hvparams), ))
3495

    
3496
      # check hypervisor parameter syntax (locally)
3497
      cluster = self.cfg.GetClusterInfo()
3498
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3499
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
3500
                                    instance.hvparams)
3501
      filled_hvp.update(self.hvparams)
3502
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3503
      hv_type.CheckParameterSyntax(filled_hvp)
3504
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3505
      self.op.hvparams = self.hvparams
3506

    
3507
    _CheckNodeOnline(self, instance.primary_node)
3508

    
3509
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3510
    # check bridges existence
3511
    _CheckInstanceBridgesExist(self, instance)
3512

    
3513
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3514
                                              instance.name,
3515
                                              instance.hypervisor)
3516
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3517
                      prereq=True)
3518
    if not remote_info.payload: # not running already
3519
      _CheckNodeFreeMemory(self, instance.primary_node,
3520
                           "starting instance %s" % instance.name,
3521
                           bep[constants.BE_MEMORY], instance.hypervisor)
3522

    
3523
  def Exec(self, feedback_fn):
3524
    """Start the instance.
3525

3526
    """
3527
    instance = self.instance
3528
    force = self.op.force
3529

    
3530
    self.cfg.MarkInstanceUp(instance.name)
3531

    
3532
    node_current = instance.primary_node
3533

    
3534
    _StartInstanceDisks(self, instance, force)
3535

    
3536
    result = self.rpc.call_instance_start(node_current, instance,
3537
                                          self.hvparams, self.beparams)
3538
    msg = result.fail_msg
3539
    if msg:
3540
      _ShutdownInstanceDisks(self, instance)
3541
      raise errors.OpExecError("Could not start instance: %s" % msg)
3542

    
3543

    
3544
class LURebootInstance(LogicalUnit):
3545
  """Reboot an instance.
3546

3547
  """
3548
  HPATH = "instance-reboot"
3549
  HTYPE = constants.HTYPE_INSTANCE
3550
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3551
  REQ_BGL = False
3552

    
3553
  def ExpandNames(self):
3554
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3555
                                   constants.INSTANCE_REBOOT_HARD,
3556
                                   constants.INSTANCE_REBOOT_FULL]:
3557
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3558
                                  (constants.INSTANCE_REBOOT_SOFT,
3559
                                   constants.INSTANCE_REBOOT_HARD,
3560
                                   constants.INSTANCE_REBOOT_FULL))
3561
    self._ExpandAndLockInstance()
3562

    
3563
  def BuildHooksEnv(self):
3564
    """Build hooks env.
3565

3566
    This runs on master, primary and secondary nodes of the instance.
3567

3568
    """
3569
    env = {
3570
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3571
      "REBOOT_TYPE": self.op.reboot_type,
3572
      }
3573
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3574
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3575
    return env, nl, nl
3576

    
3577
  def CheckPrereq(self):
3578
    """Check prerequisites.
3579

3580
    This checks that the instance is in the cluster.
3581

3582
    """
3583
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3584
    assert self.instance is not None, \
3585
      "Cannot retrieve locked instance %s" % self.op.instance_name
3586

    
3587
    _CheckNodeOnline(self, instance.primary_node)
3588

    
3589
    # check bridges existence
3590
    _CheckInstanceBridgesExist(self, instance)
3591

    
3592
  def Exec(self, feedback_fn):
3593
    """Reboot the instance.
3594

3595
    """
3596
    instance = self.instance
3597
    ignore_secondaries = self.op.ignore_secondaries
3598
    reboot_type = self.op.reboot_type
3599

    
3600
    node_current = instance.primary_node
3601

    
3602
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3603
                       constants.INSTANCE_REBOOT_HARD]:
3604
      for disk in instance.disks:
3605
        self.cfg.SetDiskID(disk, node_current)
3606
      result = self.rpc.call_instance_reboot(node_current, instance,
3607
                                             reboot_type)
3608
      result.Raise("Could not reboot instance")
3609
    else:
3610
      result = self.rpc.call_instance_shutdown(node_current, instance)
3611
      result.Raise("Could not shutdown instance for full reboot")
3612
      _ShutdownInstanceDisks(self, instance)
3613
      _StartInstanceDisks(self, instance, ignore_secondaries)
3614
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3615
      msg = result.fail_msg
3616
      if msg:
3617
        _ShutdownInstanceDisks(self, instance)
3618
        raise errors.OpExecError("Could not start instance for"
3619
                                 " full reboot: %s" % msg)
3620

    
3621
    self.cfg.MarkInstanceUp(instance.name)
3622

    
3623

    
3624
class LUShutdownInstance(LogicalUnit):
3625
  """Shutdown an instance.
3626

3627
  """
3628
  HPATH = "instance-stop"
3629
  HTYPE = constants.HTYPE_INSTANCE
3630
  _OP_REQP = ["instance_name"]
3631
  REQ_BGL = False
3632

    
3633
  def ExpandNames(self):
3634
    self._ExpandAndLockInstance()
3635

    
3636
  def BuildHooksEnv(self):
3637
    """Build hooks env.
3638

3639
    This runs on master, primary and secondary nodes of the instance.
3640

3641
    """
3642
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3643
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3644
    return env, nl, nl
3645

    
3646
  def CheckPrereq(self):
3647
    """Check prerequisites.
3648

3649
    This checks that the instance is in the cluster.
3650

3651
    """
3652
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3653
    assert self.instance is not None, \
3654
      "Cannot retrieve locked instance %s" % self.op.instance_name
3655
    _CheckNodeOnline(self, self.instance.primary_node)
3656

    
3657
  def Exec(self, feedback_fn):
3658
    """Shutdown the instance.
3659

3660
    """
3661
    instance = self.instance
3662
    node_current = instance.primary_node
3663
    self.cfg.MarkInstanceDown(instance.name)
3664
    result = self.rpc.call_instance_shutdown(node_current, instance)
3665
    msg = result.fail_msg
3666
    if msg:
3667
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
3668

    
3669
    _ShutdownInstanceDisks(self, instance)
3670

    
3671

    
3672
class LUReinstallInstance(LogicalUnit):
3673
  """Reinstall an instance.
3674

3675
  """
3676
  HPATH = "instance-reinstall"
3677
  HTYPE = constants.HTYPE_INSTANCE
3678
  _OP_REQP = ["instance_name"]
3679
  REQ_BGL = False
3680

    
3681
  def ExpandNames(self):
3682
    self._ExpandAndLockInstance()
3683

    
3684
  def BuildHooksEnv(self):
3685
    """Build hooks env.
3686

3687
    This runs on master, primary and secondary nodes of the instance.
3688

3689
    """
3690
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3691
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3692
    return env, nl, nl
3693

    
3694
  def CheckPrereq(self):
3695
    """Check prerequisites.
3696

3697
    This checks that the instance is in the cluster and is not running.
3698

3699
    """
3700
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3701
    assert instance is not None, \
3702
      "Cannot retrieve locked instance %s" % self.op.instance_name
3703
    _CheckNodeOnline(self, instance.primary_node)
3704

    
3705
    if instance.disk_template == constants.DT_DISKLESS:
3706
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3707
                                 self.op.instance_name)
3708
    if instance.admin_up:
3709
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3710
                                 self.op.instance_name)
3711
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3712
                                              instance.name,
3713
                                              instance.hypervisor)
3714
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3715
                      prereq=True)
3716
    if remote_info.payload:
3717
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3718
                                 (self.op.instance_name,
3719
                                  instance.primary_node))
3720

    
3721
    self.op.os_type = getattr(self.op, "os_type", None)
3722
    if self.op.os_type is not None:
3723
      # OS verification
3724
      pnode = self.cfg.GetNodeInfo(
3725
        self.cfg.ExpandNodeName(instance.primary_node))
3726
      if pnode is None:
3727
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
3728
                                   self.op.pnode)
3729
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
3730
      result.Raise("OS '%s' not in supported OS list for primary node %s" %
3731
                   (self.op.os_type, pnode.name), prereq=True)
3732

    
3733
    self.instance = instance
3734

    
3735
  def Exec(self, feedback_fn):
3736
    """Reinstall the instance.
3737

3738
    """
3739
    inst = self.instance
3740

    
3741
    if self.op.os_type is not None:
3742
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
3743
      inst.os = self.op.os_type
3744
      self.cfg.Update(inst)
3745

    
3746
    _StartInstanceDisks(self, inst, None)
3747
    try:
3748
      feedback_fn("Running the instance OS create scripts...")
3749
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True)
3750
      result.Raise("Could not install OS for instance %s on node %s" %
3751
                   (inst.name, inst.primary_node))
3752
    finally:
3753
      _ShutdownInstanceDisks(self, inst)
3754

    
3755

    
3756
class LURecreateInstanceDisks(LogicalUnit):
3757
  """Recreate an instance's missing disks.
3758

3759
  """
3760
  HPATH = "instance-recreate-disks"
3761
  HTYPE = constants.HTYPE_INSTANCE
3762
  _OP_REQP = ["instance_name", "disks"]
3763
  REQ_BGL = False
3764

    
3765
  def CheckArguments(self):
3766
    """Check the arguments.
3767

3768
    """
3769
    if not isinstance(self.op.disks, list):
3770
      raise errors.OpPrereqError("Invalid disks parameter")
3771
    for item in self.op.disks:
3772
      if (not isinstance(item, int) or
3773
          item < 0):
3774
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
3775
                                   str(item))
3776

    
3777
  def ExpandNames(self):
3778
    self._ExpandAndLockInstance()
3779

    
3780
  def BuildHooksEnv(self):
3781
    """Build hooks env.
3782

3783
    This runs on master, primary and secondary nodes of the instance.
3784

3785
    """
3786
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3787
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3788
    return env, nl, nl
3789

    
3790
  def CheckPrereq(self):
3791
    """Check prerequisites.
3792

3793
    This checks that the instance is in the cluster and is not running.
3794

3795
    """
3796
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3797
    assert instance is not None, \
3798
      "Cannot retrieve locked instance %s" % self.op.instance_name
3799
    _CheckNodeOnline(self, instance.primary_node)
3800

    
3801
    if instance.disk_template == constants.DT_DISKLESS:
3802
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3803
                                 self.op.instance_name)
3804
    if instance.admin_up:
3805
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3806
                                 self.op.instance_name)
3807
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3808
                                              instance.name,
3809
                                              instance.hypervisor)
3810
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3811
                      prereq=True)
3812
    if remote_info.payload:
3813
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3814
                                 (self.op.instance_name,
3815
                                  instance.primary_node))
3816

    
3817
    if not self.op.disks:
3818
      self.op.disks = range(len(instance.disks))
3819
    else:
3820
      for idx in self.op.disks:
3821
        if idx >= len(instance.disks):
3822
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx)
3823

    
3824
    self.instance = instance
3825

    
3826
  def Exec(self, feedback_fn):
3827
    """Recreate the disks.
3828

3829
    """
3830
    to_skip = []
3831
    for idx, disk in enumerate(self.instance.disks):
3832
      if idx not in self.op.disks: # disk idx has not been passed in
3833
        to_skip.append(idx)
3834
        continue
3835

    
3836
    _CreateDisks(self, self.instance, to_skip=to_skip)
3837

    
3838

    
3839
class LURenameInstance(LogicalUnit):
3840
  """Rename an instance.
3841

3842
  """
3843
  HPATH = "instance-rename"
3844
  HTYPE = constants.HTYPE_INSTANCE
3845
  _OP_REQP = ["instance_name", "new_name"]
3846

    
3847
  def BuildHooksEnv(self):
3848
    """Build hooks env.
3849

3850
    This runs on master, primary and secondary nodes of the instance.
3851

3852
    """
3853
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3854
    env["INSTANCE_NEW_NAME"] = self.op.new_name
3855
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3856
    return env, nl, nl
3857

    
3858
  def CheckPrereq(self):
3859
    """Check prerequisites.
3860

3861
    This checks that the instance is in the cluster and is not running.
3862

3863
    """
3864
    instance = self.cfg.GetInstanceInfo(
3865
      self.cfg.ExpandInstanceName(self.op.instance_name))
3866
    if instance is None:
3867
      raise errors.OpPrereqError("Instance '%s' not known" %
3868
                                 self.op.instance_name)
3869
    _CheckNodeOnline(self, instance.primary_node)
3870

    
3871
    if instance.admin_up:
3872
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3873
                                 self.op.instance_name)
3874
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3875
                                              instance.name,
3876
                                              instance.hypervisor)
3877
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3878
                      prereq=True)
3879
    if remote_info.payload:
3880
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3881
                                 (self.op.instance_name,
3882
                                  instance.primary_node))
3883
    self.instance = instance
3884

    
3885
    # new name verification
3886
    name_info = utils.HostInfo(self.op.new_name)
3887

    
3888
    self.op.new_name = new_name = name_info.name
3889
    instance_list = self.cfg.GetInstanceList()
3890
    if new_name in instance_list:
3891
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3892
                                 new_name)
3893

    
3894
    if not getattr(self.op, "ignore_ip", False):
3895
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
3896
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3897
                                   (name_info.ip, new_name))
3898

    
3899

    
3900
  def Exec(self, feedback_fn):
3901
    """Reinstall the instance.
3902

3903
    """
3904
    inst = self.instance
3905
    old_name = inst.name
3906

    
3907
    if inst.disk_template == constants.DT_FILE:
3908
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3909

    
3910
    self.cfg.RenameInstance(inst.name, self.op.new_name)
3911
    # Change the instance lock. This is definitely safe while we hold the BGL
3912
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
3913
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
3914

    
3915
    # re-read the instance from the configuration after rename
3916
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
3917

    
3918
    if inst.disk_template == constants.DT_FILE:
3919
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3920
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
3921
                                                     old_file_storage_dir,
3922
                                                     new_file_storage_dir)
3923
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
3924
                   " (but the instance has been renamed in Ganeti)" %
3925
                   (inst.primary_node, old_file_storage_dir,
3926
                    new_file_storage_dir))
3927

    
3928
    _StartInstanceDisks(self, inst, None)
3929
    try:
3930
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
3931
                                                 old_name)
3932
      msg = result.fail_msg
3933
      if msg:
3934
        msg = ("Could not run OS rename script for instance %s on node %s"
3935
               " (but the instance has been renamed in Ganeti): %s" %
3936
               (inst.name, inst.primary_node, msg))
3937
        self.proc.LogWarning(msg)
3938
    finally:
3939
      _ShutdownInstanceDisks(self, inst)
3940

    
3941

    
3942
class LURemoveInstance(LogicalUnit):
3943
  """Remove an instance.
3944

3945
  """
3946
  HPATH = "instance-remove"
3947
  HTYPE = constants.HTYPE_INSTANCE
3948
  _OP_REQP = ["instance_name", "ignore_failures"]
3949
  REQ_BGL = False
3950

    
3951
  def ExpandNames(self):
3952
    self._ExpandAndLockInstance()
3953
    self.needed_locks[locking.LEVEL_NODE] = []
3954
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3955

    
3956
  def DeclareLocks(self, level):
3957
    if level == locking.LEVEL_NODE:
3958
      self._LockInstancesNodes()
3959

    
3960
  def BuildHooksEnv(self):
3961
    """Build hooks env.
3962

3963
    This runs on master, primary and secondary nodes of the instance.
3964

3965
    """
3966
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3967
    nl = [self.cfg.GetMasterNode()]
3968
    return env, nl, nl
3969

    
3970
  def CheckPrereq(self):
3971
    """Check prerequisites.
3972

3973
    This checks that the instance is in the cluster.
3974

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

    
3980
  def Exec(self, feedback_fn):
3981
    """Remove the instance.
3982

3983
    """
3984
    instance = self.instance
3985
    logging.info("Shutting down instance %s on node %s",
3986
                 instance.name, instance.primary_node)
3987

    
3988
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3989
    msg = result.fail_msg
3990
    if msg:
3991
      if self.op.ignore_failures:
3992
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
3993
      else:
3994
        raise errors.OpExecError("Could not shutdown instance %s on"
3995
                                 " node %s: %s" %
3996
                                 (instance.name, instance.primary_node, msg))
3997

    
3998
    logging.info("Removing block devices for instance %s", instance.name)
3999

    
4000
    if not _RemoveDisks(self, instance):
4001
      if self.op.ignore_failures:
4002
        feedback_fn("Warning: can't remove instance's disks")
4003
      else:
4004
        raise errors.OpExecError("Can't remove instance's disks")
4005

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

    
4008
    self.cfg.RemoveInstance(instance.name)
4009
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4010

    
4011

    
4012
class LUQueryInstances(NoHooksLU):
4013
  """Logical unit for querying instances.
4014

4015
  """
4016
  _OP_REQP = ["output_fields", "names", "use_locking"]
4017
  REQ_BGL = False
4018
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4019
                    "serial_no", "ctime", "mtime", "uuid"]
4020
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4021
                                    "admin_state",
4022
                                    "disk_template", "ip", "mac", "bridge",
4023
                                    "nic_mode", "nic_link",
4024
                                    "sda_size", "sdb_size", "vcpus", "tags",
4025
                                    "network_port", "beparams",
4026
                                    r"(disk)\.(size)/([0-9]+)",
4027
                                    r"(disk)\.(sizes)", "disk_usage",
4028
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4029
                                    r"(nic)\.(bridge)/([0-9]+)",
4030
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4031
                                    r"(disk|nic)\.(count)",
4032
                                    "hvparams",
4033
                                    ] + _SIMPLE_FIELDS +
4034
                                  ["hv/%s" % name
4035
                                   for name in constants.HVS_PARAMETERS] +
4036
                                  ["be/%s" % name
4037
                                   for name in constants.BES_PARAMETERS])
4038
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4039

    
4040

    
4041
  def ExpandNames(self):
4042
    _CheckOutputFields(static=self._FIELDS_STATIC,
4043
                       dynamic=self._FIELDS_DYNAMIC,
4044
                       selected=self.op.output_fields)
4045

    
4046
    self.needed_locks = {}
4047
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4048
    self.share_locks[locking.LEVEL_NODE] = 1
4049

    
4050
    if self.op.names:
4051
      self.wanted = _GetWantedInstances(self, self.op.names)
4052
    else:
4053
      self.wanted = locking.ALL_SET
4054

    
4055
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4056
    self.do_locking = self.do_node_query and self.op.use_locking
4057
    if self.do_locking:
4058
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4059
      self.needed_locks[locking.LEVEL_NODE] = []
4060
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4061

    
4062
  def DeclareLocks(self, level):
4063
    if level == locking.LEVEL_NODE and self.do_locking:
4064
      self._LockInstancesNodes()
4065

    
4066
  def CheckPrereq(self):
4067
    """Check prerequisites.
4068

4069
    """
4070
    pass
4071

    
4072
  def Exec(self, feedback_fn):
4073
    """Computes the list of nodes and their attributes.
4074

4075
    """
4076
    all_info = self.cfg.GetAllInstancesInfo()
4077
    if self.wanted == locking.ALL_SET:
4078
      # caller didn't specify instance names, so ordering is not important
4079
      if self.do_locking:
4080
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4081
      else:
4082
        instance_names = all_info.keys()
4083
      instance_names = utils.NiceSort(instance_names)
4084
    else:
4085
      # caller did specify names, so we must keep the ordering
4086
      if self.do_locking:
4087
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4088
      else:
4089
        tgt_set = all_info.keys()
4090
      missing = set(self.wanted).difference(tgt_set)
4091
      if missing:
4092
        raise errors.OpExecError("Some instances were removed before"
4093
                                 " retrieving their data: %s" % missing)
4094
      instance_names = self.wanted
4095

    
4096
    instance_list = [all_info[iname] for iname in instance_names]
4097

    
4098
    # begin data gathering
4099

    
4100
    nodes = frozenset([inst.primary_node for inst in instance_list])
4101
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4102

    
4103
    bad_nodes = []
4104
    off_nodes = []
4105
    if self.do_node_query:
4106
      live_data = {}
4107
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4108
      for name in nodes:
4109
        result = node_data[name]
4110
        if result.offline:
4111
          # offline nodes will be in both lists
4112
          off_nodes.append(name)
4113
        if result.fail_msg:
4114
          bad_nodes.append(name)
4115
        else:
4116
          if result.payload:
4117
            live_data.update(result.payload)
4118
          # else no instance is alive
4119
    else:
4120
      live_data = dict([(name, {}) for name in instance_names])
4121

    
4122
    # end data gathering
4123

    
4124
    HVPREFIX = "hv/"
4125
    BEPREFIX = "be/"
4126
    output = []
4127
    cluster = self.cfg.GetClusterInfo()
4128
    for instance in instance_list:
4129
      iout = []
4130
      i_hv = cluster.FillHV(instance)
4131
      i_be = cluster.FillBE(instance)
4132
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
4133
                                 nic.nicparams) for nic in instance.nics]
4134
      for field in self.op.output_fields:
4135
        st_match = self._FIELDS_STATIC.Matches(field)
4136
        if field in self._SIMPLE_FIELDS:
4137
          val = getattr(instance, field)
4138
        elif field == "pnode":
4139
          val = instance.primary_node
4140
        elif field == "snodes":
4141
          val = list(instance.secondary_nodes)
4142
        elif field == "admin_state":
4143
          val = instance.admin_up
4144
        elif field == "oper_state":
4145
          if instance.primary_node in bad_nodes:
4146
            val = None
4147
          else:
4148
            val = bool(live_data.get(instance.name))
4149
        elif field == "status":
4150
          if instance.primary_node in off_nodes:
4151
            val = "ERROR_nodeoffline"
4152
          elif instance.primary_node in bad_nodes:
4153
            val = "ERROR_nodedown"
4154
          else:
4155
            running = bool(live_data.get(instance.name))
4156
            if running:
4157
              if instance.admin_up:
4158
                val = "running"
4159
              else:
4160
                val = "ERROR_up"
4161
            else:
4162
              if instance.admin_up:
4163
                val = "ERROR_down"
4164
              else:
4165
                val = "ADMIN_down"
4166
        elif field == "oper_ram":
4167
          if instance.primary_node in bad_nodes:
4168
            val = None
4169
          elif instance.name in live_data:
4170
            val = live_data[instance.name].get("memory", "?")
4171
          else:
4172
            val = "-"
4173
        elif field == "vcpus":
4174
          val = i_be[constants.BE_VCPUS]
4175
        elif field == "disk_template":
4176
          val = instance.disk_template
4177
        elif field == "ip":
4178
          if instance.nics:
4179
            val = instance.nics[0].ip
4180
          else:
4181
            val = None
4182
        elif field == "nic_mode":
4183
          if instance.nics:
4184
            val = i_nicp[0][constants.NIC_MODE]
4185
          else:
4186
            val = None
4187
        elif field == "nic_link":
4188
          if instance.nics:
4189
            val = i_nicp[0][constants.NIC_LINK]
4190
          else:
4191
            val = None
4192
        elif field == "bridge":
4193
          if (instance.nics and
4194
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4195
            val = i_nicp[0][constants.NIC_LINK]
4196
          else:
4197
            val = None
4198
        elif field == "mac":
4199
          if instance.nics:
4200
            val = instance.nics[0].mac
4201
          else:
4202
            val = None
4203
        elif field == "sda_size" or field == "sdb_size":
4204
          idx = ord(field[2]) - ord('a')
4205
          try:
4206
            val = instance.FindDisk(idx).size
4207
          except errors.OpPrereqError:
4208
            val = None
4209
        elif field == "disk_usage": # total disk usage per node
4210
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4211
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4212
        elif field == "tags":
4213
          val = list(instance.GetTags())
4214
        elif field == "hvparams":
4215
          val = i_hv
4216
        elif (field.startswith(HVPREFIX) and
4217
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
4218
          val = i_hv.get(field[len(HVPREFIX):], None)
4219
        elif field == "beparams":
4220
          val = i_be
4221
        elif (field.startswith(BEPREFIX) and
4222
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4223
          val = i_be.get(field[len(BEPREFIX):], None)
4224
        elif st_match and st_match.groups():
4225
          # matches a variable list
4226
          st_groups = st_match.groups()
4227
          if st_groups and st_groups[0] == "disk":
4228
            if st_groups[1] == "count":
4229
              val = len(instance.disks)
4230
            elif st_groups[1] == "sizes":
4231
              val = [disk.size for disk in instance.disks]
4232
            elif st_groups[1] == "size":
4233
              try:
4234
                val = instance.FindDisk(st_groups[2]).size
4235
              except errors.OpPrereqError:
4236
                val = None
4237
            else:
4238
              assert False, "Unhandled disk parameter"
4239
          elif st_groups[0] == "nic":
4240
            if st_groups[1] == "count":
4241
              val = len(instance.nics)
4242
            elif st_groups[1] == "macs":
4243
              val = [nic.mac for nic in instance.nics]
4244
            elif st_groups[1] == "ips":
4245
              val = [nic.ip for nic in instance.nics]
4246
            elif st_groups[1] == "modes":
4247
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4248
            elif st_groups[1] == "links":
4249
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4250
            elif st_groups[1] == "bridges":
4251
              val = []
4252
              for nicp in i_nicp:
4253
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4254
                  val.append(nicp[constants.NIC_LINK])
4255
                else:
4256
                  val.append(None)
4257
            else:
4258
              # index-based item
4259
              nic_idx = int(st_groups[2])
4260
              if nic_idx >= len(instance.nics):
4261
                val = None
4262
              else:
4263
                if st_groups[1] == "mac":
4264
                  val = instance.nics[nic_idx].mac
4265
                elif st_groups[1] == "ip":
4266
                  val = instance.nics[nic_idx].ip
4267
                elif st_groups[1] == "mode":
4268
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4269
                elif st_groups[1] == "link":
4270
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4271
                elif st_groups[1] == "bridge":
4272
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4273
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4274
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4275
                  else:
4276
                    val = None
4277
                else:
4278
                  assert False, "Unhandled NIC parameter"
4279
          else:
4280
            assert False, ("Declared but unhandled variable parameter '%s'" %
4281
                           field)
4282
        else:
4283
          assert False, "Declared but unhandled parameter '%s'" % field
4284
        iout.append(val)
4285
      output.append(iout)
4286

    
4287
    return output
4288

    
4289

    
4290
class LUFailoverInstance(LogicalUnit):
4291
  """Failover an instance.
4292

4293
  """
4294
  HPATH = "instance-failover"
4295
  HTYPE = constants.HTYPE_INSTANCE
4296
  _OP_REQP = ["instance_name", "ignore_consistency"]
4297
  REQ_BGL = False
4298

    
4299
  def ExpandNames(self):
4300
    self._ExpandAndLockInstance()
4301
    self.needed_locks[locking.LEVEL_NODE] = []
4302
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4303

    
4304
  def DeclareLocks(self, level):
4305
    if level == locking.LEVEL_NODE:
4306
      self._LockInstancesNodes()
4307

    
4308
  def BuildHooksEnv(self):
4309
    """Build hooks env.
4310

4311
    This runs on master, primary and secondary nodes of the instance.
4312

4313
    """
4314
    env = {
4315
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4316
      }
4317
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4318
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
4319
    return env, nl, nl
4320

    
4321
  def CheckPrereq(self):
4322
    """Check prerequisites.
4323

4324
    This checks that the instance is in the cluster.
4325

4326
    """
4327
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4328
    assert self.instance is not None, \
4329
      "Cannot retrieve locked instance %s" % self.op.instance_name
4330

    
4331
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4332
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4333
      raise errors.OpPrereqError("Instance's disk layout is not"
4334
                                 " network mirrored, cannot failover.")
4335

    
4336
    secondary_nodes = instance.secondary_nodes
4337
    if not secondary_nodes:
4338
      raise errors.ProgrammerError("no secondary node but using "
4339
                                   "a mirrored disk template")
4340

    
4341
    target_node = secondary_nodes[0]
4342
    _CheckNodeOnline(self, target_node)
4343
    _CheckNodeNotDrained(self, target_node)
4344
    if instance.admin_up:
4345
      # check memory requirements on the secondary node
4346
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4347
                           instance.name, bep[constants.BE_MEMORY],
4348
                           instance.hypervisor)
4349
    else:
4350
      self.LogInfo("Not checking memory on the secondary node as"
4351
                   " instance will not be started")
4352

    
4353
    # check bridge existance
4354
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4355

    
4356
  def Exec(self, feedback_fn):
4357
    """Failover an instance.
4358

4359
    The failover is done by shutting it down on its present node and
4360
    starting it on the secondary.
4361

4362
    """
4363
    instance = self.instance
4364

    
4365
    source_node = instance.primary_node
4366
    target_node = instance.secondary_nodes[0]
4367

    
4368
    feedback_fn("* checking disk consistency between source and target")
4369
    for dev in instance.disks:
4370
      # for drbd, these are drbd over lvm
4371
      if not _CheckDiskConsistency(self, dev, target_node, False):
4372
        if instance.admin_up and not self.op.ignore_consistency:
4373
          raise errors.OpExecError("Disk %s is degraded on target node,"
4374
                                   " aborting failover." % dev.iv_name)
4375

    
4376
    feedback_fn("* shutting down instance on source node")
4377
    logging.info("Shutting down instance %s on node %s",
4378
                 instance.name, source_node)
4379

    
4380
    result = self.rpc.call_instance_shutdown(source_node, instance)
4381
    msg = result.fail_msg
4382
    if msg:
4383
      if self.op.ignore_consistency:
4384
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4385
                             " Proceeding anyway. Please make sure node"
4386
                             " %s is down. Error details: %s",
4387
                             instance.name, source_node, source_node, msg)
4388
      else:
4389
        raise errors.OpExecError("Could not shutdown instance %s on"
4390
                                 " node %s: %s" %
4391
                                 (instance.name, source_node, msg))
4392

    
4393
    feedback_fn("* deactivating the instance's disks on source node")
4394
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
4395
      raise errors.OpExecError("Can't shut down the instance's disks.")
4396

    
4397
    instance.primary_node = target_node
4398
    # distribute new instance config to the other nodes
4399
    self.cfg.Update(instance)
4400

    
4401
    # Only start the instance if it's marked as up
4402
    if instance.admin_up:
4403
      feedback_fn("* activating the instance's disks on target node")
4404
      logging.info("Starting instance %s on node %s",
4405
                   instance.name, target_node)
4406

    
4407
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4408
                                               ignore_secondaries=True)
4409
      if not disks_ok:
4410
        _ShutdownInstanceDisks(self, instance)
4411
        raise errors.OpExecError("Can't activate the instance's disks")
4412

    
4413
      feedback_fn("* starting the instance on the target node")
4414
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4415
      msg = result.fail_msg
4416
      if msg:
4417
        _ShutdownInstanceDisks(self, instance)
4418
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4419
                                 (instance.name, target_node, msg))
4420

    
4421

    
4422
class LUMigrateInstance(LogicalUnit):
4423
  """Migrate an instance.
4424

4425
  This is migration without shutting down, compared to the failover,
4426
  which is done with shutdown.
4427

4428
  """
4429
  HPATH = "instance-migrate"
4430
  HTYPE = constants.HTYPE_INSTANCE
4431
  _OP_REQP = ["instance_name", "live", "cleanup"]
4432

    
4433
  REQ_BGL = False
4434

    
4435
  def ExpandNames(self):
4436
    self._ExpandAndLockInstance()
4437

    
4438
    self.needed_locks[locking.LEVEL_NODE] = []
4439
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4440

    
4441
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
4442
                                       self.op.live, self.op.cleanup)
4443
    self.tasklets = [self._migrater]
4444

    
4445
  def DeclareLocks(self, level):
4446
    if level == locking.LEVEL_NODE:
4447
      self._LockInstancesNodes()
4448

    
4449
  def BuildHooksEnv(self):
4450
    """Build hooks env.
4451

4452
    This runs on master, primary and secondary nodes of the instance.
4453

4454
    """
4455
    instance = self._migrater.instance
4456
    env = _BuildInstanceHookEnvByObject(self, instance)
4457
    env["MIGRATE_LIVE"] = self.op.live
4458
    env["MIGRATE_CLEANUP"] = self.op.cleanup
4459
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4460
    return env, nl, nl
4461

    
4462

    
4463
class LUMoveInstance(LogicalUnit):
4464
  """Move an instance by data-copying.
4465

4466
  """
4467
  HPATH = "instance-move"
4468
  HTYPE = constants.HTYPE_INSTANCE
4469
  _OP_REQP = ["instance_name", "target_node"]
4470
  REQ_BGL = False
4471

    
4472
  def ExpandNames(self):
4473
    self._ExpandAndLockInstance()
4474
    target_node = self.cfg.ExpandNodeName(self.op.target_node)
4475
    if target_node is None:
4476
      raise errors.OpPrereqError("Node '%s' not known" %
4477
                                  self.op.target_node)
4478
    self.op.target_node = target_node
4479
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
4480
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4481

    
4482
  def DeclareLocks(self, level):
4483
    if level == locking.LEVEL_NODE:
4484
      self._LockInstancesNodes(primary_only=True)
4485

    
4486
  def BuildHooksEnv(self):
4487
    """Build hooks env.
4488

4489
    This runs on master, primary and secondary nodes of the instance.
4490

4491
    """
4492
    env = {
4493
      "TARGET_NODE": self.op.target_node,
4494
      }
4495
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4496
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
4497
                                       self.op.target_node]
4498
    return env, nl, nl
4499

    
4500
  def CheckPrereq(self):
4501
    """Check prerequisites.
4502

4503
    This checks that the instance is in the cluster.
4504

4505
    """
4506
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4507
    assert self.instance is not None, \
4508
      "Cannot retrieve locked instance %s" % self.op.instance_name
4509

    
4510
    node = self.cfg.GetNodeInfo(self.op.target_node)
4511
    assert node is not None, \
4512
      "Cannot retrieve locked node %s" % self.op.target_node
4513

    
4514
    self.target_node = target_node = node.name
4515

    
4516
    if target_node == instance.primary_node:
4517
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
4518
                                 (instance.name, target_node))
4519

    
4520
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4521

    
4522
    for idx, dsk in enumerate(instance.disks):
4523
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
4524
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
4525
                                   " cannot copy")
4526

    
4527
    _CheckNodeOnline(self, target_node)
4528
    _CheckNodeNotDrained(self, target_node)
4529

    
4530
    if instance.admin_up:
4531
      # check memory requirements on the secondary node
4532
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4533
                           instance.name, bep[constants.BE_MEMORY],
4534
                           instance.hypervisor)
4535
    else:
4536
      self.LogInfo("Not checking memory on the secondary node as"
4537
                   " instance will not be started")
4538

    
4539
    # check bridge existance
4540
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4541

    
4542
  def Exec(self, feedback_fn):
4543
    """Move an instance.
4544

4545
    The move is done by shutting it down on its present node, copying
4546
    the data over (slow) and starting it on the new node.
4547

4548
    """
4549
    instance = self.instance
4550

    
4551
    source_node = instance.primary_node
4552
    target_node = self.target_node
4553

    
4554
    self.LogInfo("Shutting down instance %s on source node %s",
4555
                 instance.name, source_node)
4556

    
4557
    result = self.rpc.call_instance_shutdown(source_node, instance)
4558
    msg = result.fail_msg
4559
    if msg:
4560
      if self.op.ignore_consistency:
4561
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4562
                             " Proceeding anyway. Please make sure node"
4563
                             " %s is down. Error details: %s",
4564
                             instance.name, source_node, source_node, msg)
4565
      else:
4566
        raise errors.OpExecError("Could not shutdown instance %s on"
4567
                                 " node %s: %s" %
4568
                                 (instance.name, source_node, msg))
4569

    
4570
    # create the target disks
4571
    try:
4572
      _CreateDisks(self, instance, target_node=target_node)
4573
    except errors.OpExecError:
4574
      self.LogWarning("Device creation failed, reverting...")
4575
      try:
4576
        _RemoveDisks(self, instance, target_node=target_node)
4577
      finally:
4578
        self.cfg.ReleaseDRBDMinors(instance.name)
4579
        raise
4580

    
4581
    cluster_name = self.cfg.GetClusterInfo().cluster_name
4582

    
4583
    errs = []
4584
    # activate, get path, copy the data over
4585
    for idx, disk in enumerate(instance.disks):
4586
      self.LogInfo("Copying data for disk %d", idx)
4587
      result = self.rpc.call_blockdev_assemble(target_node, disk,
4588
                                               instance.name, True)
4589
      if result.fail_msg:
4590
        self.LogWarning("Can't assemble newly created disk %d: %s",
4591
                        idx, result.fail_msg)
4592
        errs.append(result.fail_msg)
4593
        break
4594
      dev_path = result.payload
4595
      result = self.rpc.call_blockdev_export(source_node, disk,
4596
                                             target_node, dev_path,
4597
                                             cluster_name)
4598
      if result.fail_msg:
4599
        self.LogWarning("Can't copy data over for disk %d: %s",
4600
                        idx, result.fail_msg)
4601
        errs.append(result.fail_msg)
4602
        break
4603

    
4604
    if errs:
4605
      self.LogWarning("Some disks failed to copy, aborting")
4606
      try:
4607
        _RemoveDisks(self, instance, target_node=target_node)
4608
      finally:
4609
        self.cfg.ReleaseDRBDMinors(instance.name)
4610
        raise errors.OpExecError("Errors during disk copy: %s" %
4611
                                 (",".join(errs),))
4612

    
4613
    instance.primary_node = target_node
4614
    self.cfg.Update(instance)
4615

    
4616
    self.LogInfo("Removing the disks on the original node")
4617
    _RemoveDisks(self, instance, target_node=source_node)
4618

    
4619
    # Only start the instance if it's marked as up
4620
    if instance.admin_up:
4621
      self.LogInfo("Starting instance %s on node %s",
4622
                   instance.name, target_node)
4623

    
4624
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4625
                                           ignore_secondaries=True)
4626
      if not disks_ok:
4627
        _ShutdownInstanceDisks(self, instance)
4628
        raise errors.OpExecError("Can't activate the instance's disks")
4629

    
4630
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4631
      msg = result.fail_msg
4632
      if msg:
4633
        _ShutdownInstanceDisks(self, instance)
4634
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4635
                                 (instance.name, target_node, msg))
4636

    
4637

    
4638
class LUMigrateNode(LogicalUnit):
4639
  """Migrate all instances from a node.
4640

4641
  """
4642
  HPATH = "node-migrate"
4643
  HTYPE = constants.HTYPE_NODE
4644
  _OP_REQP = ["node_name", "live"]
4645
  REQ_BGL = False
4646

    
4647
  def ExpandNames(self):
4648
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
4649
    if self.op.node_name is None:
4650
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name)
4651

    
4652
    self.needed_locks = {
4653
      locking.LEVEL_NODE: [self.op.node_name],
4654
      }
4655

    
4656
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4657

    
4658
    # Create tasklets for migrating instances for all instances on this node
4659
    names = []
4660
    tasklets = []
4661

    
4662
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
4663
      logging.debug("Migrating instance %s", inst.name)
4664
      names.append(inst.name)
4665

    
4666
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
4667

    
4668
    self.tasklets = tasklets
4669

    
4670
    # Declare instance locks
4671
    self.needed_locks[locking.LEVEL_INSTANCE] = names
4672

    
4673
  def DeclareLocks(self, level):
4674
    if level == locking.LEVEL_NODE:
4675
      self._LockInstancesNodes()
4676

    
4677
  def BuildHooksEnv(self):
4678
    """Build hooks env.
4679

4680
    This runs on the master, the primary and all the secondaries.
4681

4682
    """
4683
    env = {
4684
      "NODE_NAME": self.op.node_name,
4685
      }
4686

    
4687
    nl = [self.cfg.GetMasterNode()]
4688

    
4689
    return (env, nl, nl)
4690

    
4691

    
4692
class TLMigrateInstance(Tasklet):
4693
  def __init__(self, lu, instance_name, live, cleanup):
4694
    """Initializes this class.
4695

4696
    """
4697
    Tasklet.__init__(self, lu)
4698

    
4699
    # Parameters
4700
    self.instance_name = instance_name
4701
    self.live = live
4702
    self.cleanup = cleanup
4703

    
4704
  def CheckPrereq(self):
4705
    """Check prerequisites.
4706

4707
    This checks that the instance is in the cluster.
4708

4709
    """
4710
    instance = self.cfg.GetInstanceInfo(
4711
      self.cfg.ExpandInstanceName(self.instance_name))
4712
    if instance is None:
4713
      raise errors.OpPrereqError("Instance '%s' not known" %
4714
                                 self.instance_name)
4715

    
4716
    if instance.disk_template != constants.DT_DRBD8:
4717
      raise errors.OpPrereqError("Instance's disk layout is not"
4718
                                 " drbd8, cannot migrate.")
4719

    
4720
    secondary_nodes = instance.secondary_nodes
4721
    if not secondary_nodes:
4722
      raise errors.ConfigurationError("No secondary node but using"
4723
                                      " drbd8 disk template")
4724

    
4725
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
4726

    
4727
    target_node = secondary_nodes[0]
4728
    # check memory requirements on the secondary node
4729
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
4730
                         instance.name, i_be[constants.BE_MEMORY],
4731
                         instance.hypervisor)
4732

    
4733
    # check bridge existance
4734
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4735

    
4736
    if not self.cleanup:
4737
      _CheckNodeNotDrained(self, target_node)
4738
      result = self.rpc.call_instance_migratable(instance.primary_node,
4739
                                                 instance)
4740
      result.Raise("Can't migrate, please use failover", prereq=True)
4741

    
4742
    self.instance = instance
4743

    
4744
  def _WaitUntilSync(self):
4745
    """Poll with custom rpc for disk sync.
4746

4747
    This uses our own step-based rpc call.
4748

4749
    """
4750
    self.feedback_fn("* wait until resync is done")
4751
    all_done = False
4752
    while not all_done:
4753
      all_done = True
4754
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
4755
                                            self.nodes_ip,
4756
                                            self.instance.disks)
4757
      min_percent = 100
4758
      for node, nres in result.items():
4759
        nres.Raise("Cannot resync disks on node %s" % node)
4760
        node_done, node_percent = nres.payload
4761
        all_done = all_done and node_done
4762
        if node_percent is not None:
4763
          min_percent = min(min_percent, node_percent)
4764
      if not all_done:
4765
        if min_percent < 100:
4766
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
4767
        time.sleep(2)
4768

    
4769
  def _EnsureSecondary(self, node):
4770
    """Demote a node to secondary.
4771

4772
    """
4773
    self.feedback_fn("* switching node %s to secondary mode" % node)
4774

    
4775
    for dev in self.instance.disks:
4776
      self.cfg.SetDiskID(dev, node)
4777

    
4778
    result = self.rpc.call_blockdev_close(node, self.instance.name,
4779
                                          self.instance.disks)
4780
    result.Raise("Cannot change disk to secondary on node %s" % node)
4781

    
4782
  def _GoStandalone(self):
4783
    """Disconnect from the network.
4784

4785
    """
4786
    self.feedback_fn("* changing into standalone mode")
4787
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
4788
                                               self.instance.disks)
4789
    for node, nres in result.items():
4790
      nres.Raise("Cannot disconnect disks node %s" % node)
4791

    
4792
  def _GoReconnect(self, multimaster):
4793
    """Reconnect to the network.
4794

4795
    """
4796
    if multimaster:
4797
      msg = "dual-master"
4798
    else:
4799
      msg = "single-master"
4800
    self.feedback_fn("* changing disks into %s mode" % msg)
4801
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
4802
                                           self.instance.disks,
4803
                                           self.instance.name, multimaster)
4804
    for node, nres in result.items():
4805
      nres.Raise("Cannot change disks config on node %s" % node)
4806

    
4807
  def _ExecCleanup(self):
4808
    """Try to cleanup after a failed migration.
4809

4810
    The cleanup is done by:
4811
      - check that the instance is running only on one node
4812
        (and update the config if needed)
4813
      - change disks on its secondary node to secondary
4814
      - wait until disks are fully synchronized
4815
      - disconnect from the network
4816
      - change disks into single-master mode
4817
      - wait again until disks are fully synchronized
4818

4819
    """
4820
    instance = self.instance
4821
    target_node = self.target_node
4822
    source_node = self.source_node
4823

    
4824
    # check running on only one node
4825
    self.feedback_fn("* checking where the instance actually runs"
4826
                     " (if this hangs, the hypervisor might be in"
4827
                     " a bad state)")
4828
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
4829
    for node, result in ins_l.items():
4830
      result.Raise("Can't contact node %s" % node)
4831

    
4832
    runningon_source = instance.name in ins_l[source_node].payload
4833
    runningon_target = instance.name in ins_l[target_node].payload
4834

    
4835
    if runningon_source and runningon_target:
4836
      raise errors.OpExecError("Instance seems to be running on two nodes,"
4837
                               " or the hypervisor is confused. You will have"
4838
                               " to ensure manually that it runs only on one"
4839
                               " and restart this operation.")
4840

    
4841
    if not (runningon_source or runningon_target):
4842
      raise errors.OpExecError("Instance does not seem to be running at all."
4843
                               " In this case, it's safer to repair by"
4844
                               " running 'gnt-instance stop' to ensure disk"
4845
                               " shutdown, and then restarting it.")
4846

    
4847
    if runningon_target:
4848
      # the migration has actually succeeded, we need to update the config
4849
      self.feedback_fn("* instance running on secondary node (%s),"
4850
                       " updating config" % target_node)
4851
      instance.primary_node = target_node
4852
      self.cfg.Update(instance)
4853
      demoted_node = source_node
4854
    else:
4855
      self.feedback_fn("* instance confirmed to be running on its"
4856
                       " primary node (%s)" % source_node)
4857
      demoted_node = target_node
4858

    
4859
    self._EnsureSecondary(demoted_node)
4860
    try:
4861
      self._WaitUntilSync()
4862
    except errors.OpExecError:
4863
      # we ignore here errors, since if the device is standalone, it
4864
      # won't be able to sync
4865
      pass
4866
    self._GoStandalone()
4867
    self._GoReconnect(False)
4868
    self._WaitUntilSync()
4869

    
4870
    self.feedback_fn("* done")
4871

    
4872
  def _RevertDiskStatus(self):
4873
    """Try to revert the disk status after a failed migration.
4874

4875
    """
4876
    target_node = self.target_node
4877
    try:
4878
      self._EnsureSecondary(target_node)
4879
      self._GoStandalone()
4880
      self._GoReconnect(False)
4881
      self._WaitUntilSync()
4882
    except errors.OpExecError, err:
4883
      self.lu.LogWarning("Migration failed and I can't reconnect the"
4884
                         " drives: error '%s'\n"
4885
                         "Please look and recover the instance status" %
4886
                         str(err))
4887

    
4888
  def _AbortMigration(self):
4889
    """Call the hypervisor code to abort a started migration.
4890

4891
    """
4892
    instance = self.instance
4893
    target_node = self.target_node
4894
    migration_info = self.migration_info
4895

    
4896
    abort_result = self.rpc.call_finalize_migration(target_node,
4897
                                                    instance,
4898
                                                    migration_info,
4899
                                                    False)
4900
    abort_msg = abort_result.fail_msg
4901
    if abort_msg:
4902
      logging.error("Aborting migration failed on target node %s: %s" %
4903
                    (target_node, abort_msg))
4904
      # Don't raise an exception here, as we stil have to try to revert the
4905
      # disk status, even if this step failed.
4906

    
4907
  def _ExecMigration(self):
4908
    """Migrate an instance.
4909

4910
    The migrate is done by:
4911
      - change the disks into dual-master mode
4912
      - wait until disks are fully synchronized again
4913
      - migrate the instance
4914
      - change disks on the new secondary node (the old primary) to secondary
4915
      - wait until disks are fully synchronized
4916
      - change disks into single-master mode
4917

4918
    """
4919
    instance = self.instance
4920
    target_node = self.target_node
4921
    source_node = self.source_node
4922

    
4923
    self.feedback_fn("* checking disk consistency between source and target")
4924
    for dev in instance.disks:
4925
      if not _CheckDiskConsistency(self, dev, target_node, False):
4926
        raise errors.OpExecError("Disk %s is degraded or not fully"
4927
                                 " synchronized on target node,"
4928
                                 " aborting migrate." % dev.iv_name)
4929

    
4930
    # First get the migration information from the remote node
4931
    result = self.rpc.call_migration_info(source_node, instance)
4932
    msg = result.fail_msg
4933
    if msg:
4934
      log_err = ("Failed fetching source migration information from %s: %s" %
4935
                 (source_node, msg))
4936
      logging.error(log_err)
4937
      raise errors.OpExecError(log_err)
4938

    
4939
    self.migration_info = migration_info = result.payload
4940

    
4941
    # Then switch the disks to master/master mode
4942
    self._EnsureSecondary(target_node)
4943
    self._GoStandalone()
4944
    self._GoReconnect(True)
4945
    self._WaitUntilSync()
4946

    
4947
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
4948
    result = self.rpc.call_accept_instance(target_node,
4949
                                           instance,
4950
                                           migration_info,
4951
                                           self.nodes_ip[target_node])
4952

    
4953
    msg = result.fail_msg
4954
    if msg:
4955
      logging.error("Instance pre-migration failed, trying to revert"
4956
                    " disk status: %s", msg)
4957
      self._AbortMigration()
4958
      self._RevertDiskStatus()
4959
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
4960
                               (instance.name, msg))
4961

    
4962
    self.feedback_fn("* migrating instance to %s" % target_node)
4963
    time.sleep(10)
4964
    result = self.rpc.call_instance_migrate(source_node, instance,
4965
                                            self.nodes_ip[target_node],
4966
                                            self.live)
4967
    msg = result.fail_msg
4968
    if msg:
4969
      logging.error("Instance migration failed, trying to revert"
4970
                    " disk status: %s", msg)
4971
      self._AbortMigration()
4972
      self._RevertDiskStatus()
4973
      raise errors.OpExecError("Could not migrate instance %s: %s" %
4974
                               (instance.name, msg))
4975
    time.sleep(10)
4976

    
4977
    instance.primary_node = target_node
4978
    # distribute new instance config to the other nodes
4979
    self.cfg.Update(instance)
4980

    
4981
    result = self.rpc.call_finalize_migration(target_node,
4982
                                              instance,
4983
                                              migration_info,
4984
                                              True)
4985
    msg = result.fail_msg
4986
    if msg:
4987
      logging.error("Instance migration succeeded, but finalization failed:"
4988
                    " %s" % msg)
4989
      raise errors.OpExecError("Could not finalize instance migration: %s" %
4990
                               msg)
4991

    
4992
    self._EnsureSecondary(source_node)
4993
    self._WaitUntilSync()
4994
    self._GoStandalone()
4995
    self._GoReconnect(False)
4996
    self._WaitUntilSync()
4997

    
4998
    self.feedback_fn("* done")
4999

    
5000
  def Exec(self, feedback_fn):
5001
    """Perform the migration.
5002

5003
    """
5004
    feedback_fn("Migrating instance %s" % self.instance.name)
5005

    
5006
    self.feedback_fn = feedback_fn
5007

    
5008
    self.source_node = self.instance.primary_node
5009
    self.target_node = self.instance.secondary_nodes[0]
5010
    self.all_nodes = [self.source_node, self.target_node]
5011
    self.nodes_ip = {
5012
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5013
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5014
      }
5015

    
5016
    if self.cleanup:
5017
      return self._ExecCleanup()
5018
    else:
5019
      return self._ExecMigration()
5020

    
5021

    
5022
def _CreateBlockDev(lu, node, instance, device, force_create,
5023
                    info, force_open):
5024
  """Create a tree of block devices on a given node.
5025

5026
  If this device type has to be created on secondaries, create it and
5027
  all its children.
5028

5029
  If not, just recurse to children keeping the same 'force' value.
5030

5031
  @param lu: the lu on whose behalf we execute
5032
  @param node: the node on which to create the device
5033
  @type instance: L{objects.Instance}
5034
  @param instance: the instance which owns the device
5035
  @type device: L{objects.Disk}
5036
  @param device: the device to create
5037
  @type force_create: boolean
5038
  @param force_create: whether to force creation of this device; this
5039
      will be change to True whenever we find a device which has
5040
      CreateOnSecondary() attribute
5041
  @param info: the extra 'metadata' we should attach to the device
5042
      (this will be represented as a LVM tag)
5043
  @type force_open: boolean
5044
  @param force_open: this parameter will be passes to the
5045
      L{backend.BlockdevCreate} function where it specifies
5046
      whether we run on primary or not, and it affects both
5047
      the child assembly and the device own Open() execution
5048

5049
  """
5050
  if device.CreateOnSecondary():
5051
    force_create = True
5052

    
5053
  if device.children:
5054
    for child in device.children:
5055
      _CreateBlockDev(lu, node, instance, child, force_create,
5056
                      info, force_open)
5057

    
5058
  if not force_create:
5059
    return
5060

    
5061
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5062

    
5063

    
5064
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5065
  """Create a single block device on a given node.
5066

5067
  This will not recurse over children of the device, so they must be
5068
  created in advance.
5069

5070
  @param lu: the lu on whose behalf we execute
5071
  @param node: the node on which to create the device
5072
  @type instance: L{objects.Instance}
5073
  @param instance: the instance which owns the device
5074
  @type device: L{objects.Disk}
5075
  @param device: the device to create
5076
  @param info: the extra 'metadata' we should attach to the device
5077
      (this will be represented as a LVM tag)
5078
  @type force_open: boolean
5079
  @param force_open: this parameter will be passes to the
5080
      L{backend.BlockdevCreate} function where it specifies
5081
      whether we run on primary or not, and it affects both
5082
      the child assembly and the device own Open() execution
5083

5084
  """
5085
  lu.cfg.SetDiskID(device, node)
5086
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5087
                                       instance.name, force_open, info)
5088
  result.Raise("Can't create block device %s on"
5089
               " node %s for instance %s" % (device, node, instance.name))
5090
  if device.physical_id is None:
5091
    device.physical_id = result.payload
5092

    
5093

    
5094
def _GenerateUniqueNames(lu, exts):
5095
  """Generate a suitable LV name.
5096

5097
  This will generate a logical volume name for the given instance.
5098

5099
  """
5100
  results = []
5101
  for val in exts:
5102
    new_id = lu.cfg.GenerateUniqueID()
5103
    results.append("%s%s" % (new_id, val))
5104
  return results
5105

    
5106

    
5107
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5108
                         p_minor, s_minor):
5109
  """Generate a drbd8 device complete with its children.
5110

5111
  """
5112
  port = lu.cfg.AllocatePort()
5113
  vgname = lu.cfg.GetVGName()
5114
  shared_secret = lu.cfg.GenerateDRBDSecret()
5115
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5116
                          logical_id=(vgname, names[0]))
5117
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5118
                          logical_id=(vgname, names[1]))
5119
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5120
                          logical_id=(primary, secondary, port,
5121
                                      p_minor, s_minor,
5122
                                      shared_secret),
5123
                          children=[dev_data, dev_meta],
5124
                          iv_name=iv_name)
5125
  return drbd_dev
5126

    
5127

    
5128
def _GenerateDiskTemplate(lu, template_name,
5129
                          instance_name, primary_node,
5130
                          secondary_nodes, disk_info,
5131
                          file_storage_dir, file_driver,
5132
                          base_index):
5133
  """Generate the entire disk layout for a given template type.
5134

5135
  """
5136
  #TODO: compute space requirements
5137

    
5138
  vgname = lu.cfg.GetVGName()
5139
  disk_count = len(disk_info)
5140
  disks = []
5141
  if template_name == constants.DT_DISKLESS:
5142
    pass
5143
  elif template_name == constants.DT_PLAIN:
5144
    if len(secondary_nodes) != 0:
5145
      raise errors.ProgrammerError("Wrong template configuration")
5146

    
5147
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5148
                                      for i in range(disk_count)])
5149
    for idx, disk in enumerate(disk_info):
5150
      disk_index = idx + base_index
5151
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5152
                              logical_id=(vgname, names[idx]),
5153
                              iv_name="disk/%d" % disk_index,
5154
                              mode=disk["mode"])
5155
      disks.append(disk_dev)
5156
  elif template_name == constants.DT_DRBD8:
5157
    if len(secondary_nodes) != 1:
5158
      raise errors.ProgrammerError("Wrong template configuration")
5159
    remote_node = secondary_nodes[0]
5160
    minors = lu.cfg.AllocateDRBDMinor(
5161
      [primary_node, remote_node] * len(disk_info), instance_name)
5162

    
5163
    names = []
5164
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5165
                                               for i in range(disk_count)]):
5166
      names.append(lv_prefix + "_data")
5167
      names.append(lv_prefix + "_meta")
5168
    for idx, disk in enumerate(disk_info):
5169
      disk_index = idx + base_index
5170
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5171
                                      disk["size"], names[idx*2:idx*2+2],
5172
                                      "disk/%d" % disk_index,
5173
                                      minors[idx*2], minors[idx*2+1])
5174
      disk_dev.mode = disk["mode"]
5175
      disks.append(disk_dev)
5176
  elif template_name == constants.DT_FILE:
5177
    if len(secondary_nodes) != 0:
5178
      raise errors.ProgrammerError("Wrong template configuration")
5179

    
5180
    for idx, disk in enumerate(disk_info):
5181
      disk_index = idx + base_index
5182
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5183
                              iv_name="disk/%d" % disk_index,
5184
                              logical_id=(file_driver,
5185
                                          "%s/disk%d" % (file_storage_dir,
5186
                                                         disk_index)),
5187
                              mode=disk["mode"])
5188
      disks.append(disk_dev)
5189
  else:
5190
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5191
  return disks
5192

    
5193

    
5194
def _GetInstanceInfoText(instance):
5195
  """Compute that text that should be added to the disk's metadata.
5196

5197
  """
5198
  return "originstname+%s" % instance.name
5199

    
5200

    
5201
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5202
  """Create all disks for an instance.
5203

5204
  This abstracts away some work from AddInstance.
5205

5206
  @type lu: L{LogicalUnit}
5207
  @param lu: the logical unit on whose behalf we execute
5208
  @type instance: L{objects.Instance}
5209
  @param instance: the instance whose disks we should create
5210
  @type to_skip: list
5211
  @param to_skip: list of indices to skip
5212
  @type target_node: string
5213
  @param target_node: if passed, overrides the target node for creation
5214
  @rtype: boolean
5215
  @return: the success of the creation
5216

5217
  """
5218
  info = _GetInstanceInfoText(instance)
5219
  if target_node is None:
5220
    pnode = instance.primary_node
5221
    all_nodes = instance.all_nodes
5222
  else:
5223
    pnode = target_node
5224
    all_nodes = [pnode]
5225

    
5226
  if instance.disk_template == constants.DT_FILE:
5227
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5228
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5229

    
5230
    result.Raise("Failed to create directory '%s' on"
5231
                 " node %s" % (file_storage_dir, pnode))
5232

    
5233
  # Note: this needs to be kept in sync with adding of disks in
5234
  # LUSetInstanceParams
5235
  for idx, device in enumerate(instance.disks):
5236
    if to_skip and idx in to_skip:
5237
      continue
5238
    logging.info("Creating volume %s for instance %s",
5239
                 device.iv_name, instance.name)
5240
    #HARDCODE
5241
    for node in all_nodes:
5242
      f_create = node == pnode
5243
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5244

    
5245

    
5246
def _RemoveDisks(lu, instance, target_node=None):
5247
  """Remove all disks for an instance.
5248

5249
  This abstracts away some work from `AddInstance()` and
5250
  `RemoveInstance()`. Note that in case some of the devices couldn't
5251
  be removed, the removal will continue with the other ones (compare
5252
  with `_CreateDisks()`).
5253

5254
  @type lu: L{LogicalUnit}
5255
  @param lu: the logical unit on whose behalf we execute
5256
  @type instance: L{objects.Instance}
5257
  @param instance: the instance whose disks we should remove
5258
  @type target_node: string
5259
  @param target_node: used to override the node on which to remove the disks
5260
  @rtype: boolean
5261
  @return: the success of the removal
5262

5263
  """
5264
  logging.info("Removing block devices for instance %s", instance.name)
5265

    
5266
  all_result = True
5267
  for device in instance.disks:
5268
    if target_node:
5269
      edata = [(target_node, device)]
5270
    else:
5271
      edata = device.ComputeNodeTree(instance.primary_node)
5272
    for node, disk in edata:
5273
      lu.cfg.SetDiskID(disk, node)
5274
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5275
      if msg:
5276
        lu.LogWarning("Could not remove block device %s on node %s,"
5277
                      " continuing anyway: %s", device.iv_name, node, msg)
5278
        all_result = False
5279

    
5280
  if instance.disk_template == constants.DT_FILE:
5281
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5282
    if target_node:
5283
      tgt = target_node
5284
    else:
5285
      tgt = instance.primary_node
5286
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5287
    if result.fail_msg:
5288
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5289
                    file_storage_dir, instance.primary_node, result.fail_msg)
5290
      all_result = False
5291

    
5292
  return all_result
5293

    
5294

    
5295
def _ComputeDiskSize(disk_template, disks):
5296
  """Compute disk size requirements in the volume group
5297

5298
  """
5299
  # Required free disk space as a function of disk and swap space
5300
  req_size_dict = {
5301
    constants.DT_DISKLESS: None,
5302
    constants.DT_PLAIN: sum(d["size"] for d in disks),
5303
    # 128 MB are added for drbd metadata for each disk
5304
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
5305
    constants.DT_FILE: None,
5306
  }
5307

    
5308
  if disk_template not in req_size_dict:
5309
    raise errors.ProgrammerError("Disk template '%s' size requirement"
5310
                                 " is unknown" %  disk_template)
5311

    
5312
  return req_size_dict[disk_template]
5313

    
5314

    
5315
def _CheckHVParams(lu, nodenames, hvname, hvparams):
5316
  """Hypervisor parameter validation.
5317

5318
  This function abstract the hypervisor parameter validation to be
5319
  used in both instance create and instance modify.
5320

5321
  @type lu: L{LogicalUnit}
5322
  @param lu: the logical unit for which we check
5323
  @type nodenames: list
5324
  @param nodenames: the list of nodes on which we should check
5325
  @type hvname: string
5326
  @param hvname: the name of the hypervisor we should use
5327
  @type hvparams: dict
5328
  @param hvparams: the parameters which we need to check
5329
  @raise errors.OpPrereqError: if the parameters are not valid
5330

5331
  """
5332
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
5333
                                                  hvname,
5334
                                                  hvparams)
5335
  for node in nodenames:
5336
    info = hvinfo[node]
5337
    if info.offline:
5338
      continue
5339
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
5340

    
5341

    
5342
class LUCreateInstance(LogicalUnit):
5343
  """Create an instance.
5344

5345
  """
5346
  HPATH = "instance-add"
5347
  HTYPE = constants.HTYPE_INSTANCE
5348
  _OP_REQP = ["instance_name", "disks", "disk_template",
5349
              "mode", "start",
5350
              "wait_for_sync", "ip_check", "nics",
5351
              "hvparams", "beparams"]
5352
  REQ_BGL = False
5353

    
5354
  def _ExpandNode(self, node):
5355
    """Expands and checks one node name.
5356

5357
    """
5358
    node_full = self.cfg.ExpandNodeName(node)
5359
    if node_full is None:
5360
      raise errors.OpPrereqError("Unknown node %s" % node)
5361
    return node_full
5362

    
5363
  def ExpandNames(self):
5364
    """ExpandNames for CreateInstance.
5365

5366
    Figure out the right locks for instance creation.
5367

5368
    """
5369
    self.needed_locks = {}
5370

    
5371
    # set optional parameters to none if they don't exist
5372
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
5373
      if not hasattr(self.op, attr):
5374
        setattr(self.op, attr, None)
5375

    
5376
    # cheap checks, mostly valid constants given
5377

    
5378
    # verify creation mode
5379
    if self.op.mode not in (constants.INSTANCE_CREATE,
5380
                            constants.INSTANCE_IMPORT):
5381
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
5382
                                 self.op.mode)
5383

    
5384
    # disk template and mirror node verification
5385
    if self.op.disk_template not in constants.DISK_TEMPLATES:
5386
      raise errors.OpPrereqError("Invalid disk template name")
5387

    
5388
    if self.op.hypervisor is None:
5389
      self.op.hypervisor = self.cfg.GetHypervisorType()
5390

    
5391
    cluster = self.cfg.GetClusterInfo()
5392
    enabled_hvs = cluster.enabled_hypervisors
5393
    if self.op.hypervisor not in enabled_hvs:
5394
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
5395
                                 " cluster (%s)" % (self.op.hypervisor,
5396
                                  ",".join(enabled_hvs)))
5397

    
5398
    # check hypervisor parameter syntax (locally)
5399
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5400
    filled_hvp = objects.FillDict(cluster.hvparams[self.op.hypervisor],
5401
                                  self.op.hvparams)
5402
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
5403
    hv_type.CheckParameterSyntax(filled_hvp)
5404
    self.hv_full = filled_hvp
5405

    
5406
    # fill and remember the beparams dict
5407
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5408
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
5409
                                    self.op.beparams)
5410

    
5411
    #### instance parameters check
5412

    
5413
    # instance name verification
5414
    hostname1 = utils.HostInfo(self.op.instance_name)
5415
    self.op.instance_name = instance_name = hostname1.name
5416

    
5417
    # this is just a preventive check, but someone might still add this
5418
    # instance in the meantime, and creation will fail at lock-add time
5419
    if instance_name in self.cfg.GetInstanceList():
5420
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5421
                                 instance_name)
5422

    
5423
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
5424

    
5425
    # NIC buildup
5426
    self.nics = []
5427
    for idx, nic in enumerate(self.op.nics):
5428
      nic_mode_req = nic.get("mode", None)
5429
      nic_mode = nic_mode_req
5430
      if nic_mode is None:
5431
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
5432

    
5433
      # in routed mode, for the first nic, the default ip is 'auto'
5434
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
5435
        default_ip_mode = constants.VALUE_AUTO
5436
      else:
5437
        default_ip_mode = constants.VALUE_NONE
5438

    
5439
      # ip validity checks
5440
      ip = nic.get("ip", default_ip_mode)
5441
      if ip is None or ip.lower() == constants.VALUE_NONE:
5442
        nic_ip = None
5443
      elif ip.lower() == constants.VALUE_AUTO:
5444
        nic_ip = hostname1.ip
5445
      else:
5446
        if not utils.IsValidIP(ip):
5447
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
5448
                                     " like a valid IP" % ip)
5449
        nic_ip = ip
5450

    
5451
      # TODO: check the ip for uniqueness !!
5452
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
5453
        raise errors.OpPrereqError("Routed nic mode requires an ip address")
5454

    
5455
      # MAC address verification
5456
      mac = nic.get("mac", constants.VALUE_AUTO)
5457
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5458
        if not utils.IsValidMac(mac.lower()):
5459
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
5460
                                     mac)
5461
        else:
5462
          # or validate/reserve the current one
5463
          if self.cfg.IsMacInUse(mac):
5464
            raise errors.OpPrereqError("MAC address %s already in use"
5465
                                       " in cluster" % mac)
5466

    
5467
      # bridge verification
5468
      bridge = nic.get("bridge", None)
5469
      link = nic.get("link", None)
5470
      if bridge and link:
5471
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
5472
                                   " at the same time")
5473
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
5474
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic")
5475
      elif bridge:
5476
        link = bridge
5477

    
5478
      nicparams = {}
5479
      if nic_mode_req:
5480
        nicparams[constants.NIC_MODE] = nic_mode_req
5481
      if link:
5482
        nicparams[constants.NIC_LINK] = link
5483

    
5484
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
5485
                                      nicparams)
5486
      objects.NIC.CheckParameterSyntax(check_params)
5487
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
5488

    
5489
    # disk checks/pre-build
5490
    self.disks = []
5491
    for disk in self.op.disks:
5492
      mode = disk.get("mode", constants.DISK_RDWR)
5493
      if mode not in constants.DISK_ACCESS_SET:
5494
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
5495
                                   mode)
5496
      size = disk.get("size", None)
5497
      if size is None:
5498
        raise errors.OpPrereqError("Missing disk size")
5499
      try:
5500
        size = int(size)
5501
      except ValueError:
5502
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
5503
      self.disks.append({"size": size, "mode": mode})
5504

    
5505
    # used in CheckPrereq for ip ping check
5506
    self.check_ip = hostname1.ip
5507

    
5508
    # file storage checks
5509
    if (self.op.file_driver and
5510
        not self.op.file_driver in constants.FILE_DRIVER):
5511
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
5512
                                 self.op.file_driver)
5513

    
5514
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
5515
      raise errors.OpPrereqError("File storage directory path not absolute")
5516

    
5517
    ### Node/iallocator related checks
5518
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
5519
      raise errors.OpPrereqError("One and only one of iallocator and primary"
5520
                                 " node must be given")
5521

    
5522
    if self.op.iallocator:
5523
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5524
    else:
5525
      self.op.pnode = self._ExpandNode(self.op.pnode)
5526
      nodelist = [self.op.pnode]
5527
      if self.op.snode is not None:
5528
        self.op.snode = self._ExpandNode(self.op.snode)
5529
        nodelist.append(self.op.snode)
5530
      self.needed_locks[locking.LEVEL_NODE] = nodelist
5531

    
5532
    # in case of import lock the source node too
5533
    if self.op.mode == constants.INSTANCE_IMPORT:
5534
      src_node = getattr(self.op, "src_node", None)
5535
      src_path = getattr(self.op, "src_path", None)
5536

    
5537
      if src_path is None:
5538
        self.op.src_path = src_path = self.op.instance_name
5539

    
5540
      if src_node is None:
5541
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5542
        self.op.src_node = None
5543
        if os.path.isabs(src_path):
5544
          raise errors.OpPrereqError("Importing an instance from an absolute"
5545
                                     " path requires a source node option.")
5546
      else:
5547
        self.op.src_node = src_node = self._ExpandNode(src_node)
5548
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
5549
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
5550
        if not os.path.isabs(src_path):
5551
          self.op.src_path = src_path = \
5552
            os.path.join(constants.EXPORT_DIR, src_path)
5553

    
5554
    else: # INSTANCE_CREATE
5555
      if getattr(self.op, "os_type", None) is None:
5556
        raise errors.OpPrereqError("No guest OS specified")
5557

    
5558
  def _RunAllocator(self):
5559
    """Run the allocator based on input opcode.
5560

5561
    """
5562
    nics = [n.ToDict() for n in self.nics]
5563
    ial = IAllocator(self.cfg, self.rpc,
5564
                     mode=constants.IALLOCATOR_MODE_ALLOC,
5565
                     name=self.op.instance_name,
5566
                     disk_template=self.op.disk_template,
5567
                     tags=[],
5568
                     os=self.op.os_type,
5569
                     vcpus=self.be_full[constants.BE_VCPUS],
5570
                     mem_size=self.be_full[constants.BE_MEMORY],
5571
                     disks=self.disks,
5572
                     nics=nics,
5573
                     hypervisor=self.op.hypervisor,
5574
                     )
5575

    
5576
    ial.Run(self.op.iallocator)
5577

    
5578
    if not ial.success:
5579
      raise errors.OpPrereqError("Can't compute nodes using"
5580
                                 " iallocator '%s': %s" % (self.op.iallocator,
5581
                                                           ial.info))
5582
    if len(ial.nodes) != ial.required_nodes:
5583
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5584
                                 " of nodes (%s), required %s" %
5585
                                 (self.op.iallocator, len(ial.nodes),
5586
                                  ial.required_nodes))
5587
    self.op.pnode = ial.nodes[0]
5588
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5589
                 self.op.instance_name, self.op.iallocator,
5590
                 ", ".join(ial.nodes))
5591
    if ial.required_nodes == 2:
5592
      self.op.snode = ial.nodes[1]
5593

    
5594
  def BuildHooksEnv(self):
5595
    """Build hooks env.
5596

5597
    This runs on master, primary and secondary nodes of the instance.
5598

5599
    """
5600
    env = {
5601
      "ADD_MODE": self.op.mode,
5602
      }
5603
    if self.op.mode == constants.INSTANCE_IMPORT:
5604
      env["SRC_NODE"] = self.op.src_node
5605
      env["SRC_PATH"] = self.op.src_path
5606
      env["SRC_IMAGES"] = self.src_images
5607

    
5608
    env.update(_BuildInstanceHookEnv(
5609
      name=self.op.instance_name,
5610
      primary_node=self.op.pnode,
5611
      secondary_nodes=self.secondaries,
5612
      status=self.op.start,
5613
      os_type=self.op.os_type,
5614
      memory=self.be_full[constants.BE_MEMORY],
5615
      vcpus=self.be_full[constants.BE_VCPUS],
5616
      nics=_NICListToTuple(self, self.nics),
5617
      disk_template=self.op.disk_template,
5618
      disks=[(d["size"], d["mode"]) for d in self.disks],
5619
      bep=self.be_full,
5620
      hvp=self.hv_full,
5621
      hypervisor_name=self.op.hypervisor,
5622
    ))
5623

    
5624
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
5625
          self.secondaries)
5626
    return env, nl, nl
5627

    
5628

    
5629
  def CheckPrereq(self):
5630
    """Check prerequisites.
5631

5632
    """
5633
    if (not self.cfg.GetVGName() and
5634
        self.op.disk_template not in constants.DTS_NOT_LVM):
5635
      raise errors.OpPrereqError("Cluster does not support lvm-based"
5636
                                 " instances")
5637

    
5638
    if self.op.mode == constants.INSTANCE_IMPORT:
5639
      src_node = self.op.src_node
5640
      src_path = self.op.src_path
5641

    
5642
      if src_node is None:
5643
        locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
5644
        exp_list = self.rpc.call_export_list(locked_nodes)
5645
        found = False
5646
        for node in exp_list:
5647
          if exp_list[node].fail_msg:
5648
            continue
5649
          if src_path in exp_list[node].payload:
5650
            found = True
5651
            self.op.src_node = src_node = node
5652
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
5653
                                                       src_path)
5654
            break
5655
        if not found:
5656
          raise errors.OpPrereqError("No export found for relative path %s" %
5657
                                      src_path)
5658

    
5659
      _CheckNodeOnline(self, src_node)
5660
      result = self.rpc.call_export_info(src_node, src_path)
5661
      result.Raise("No export or invalid export found in dir %s" % src_path)
5662

    
5663
      export_info = objects.SerializableConfigParser.Loads(str(result.payload))
5664
      if not export_info.has_section(constants.INISECT_EXP):
5665
        raise errors.ProgrammerError("Corrupted export config")
5666

    
5667
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
5668
      if (int(ei_version) != constants.EXPORT_VERSION):
5669
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
5670
                                   (ei_version, constants.EXPORT_VERSION))
5671

    
5672
      # Check that the new instance doesn't have less disks than the export
5673
      instance_disks = len(self.disks)
5674
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
5675
      if instance_disks < export_disks:
5676
        raise errors.OpPrereqError("Not enough disks to import."
5677
                                   " (instance: %d, export: %d)" %
5678
                                   (instance_disks, export_disks))
5679

    
5680
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
5681
      disk_images = []
5682
      for idx in range(export_disks):
5683
        option = 'disk%d_dump' % idx
5684
        if export_info.has_option(constants.INISECT_INS, option):
5685
          # FIXME: are the old os-es, disk sizes, etc. useful?
5686
          export_name = export_info.get(constants.INISECT_INS, option)
5687
          image = os.path.join(src_path, export_name)
5688
          disk_images.append(image)
5689
        else:
5690
          disk_images.append(False)
5691

    
5692
      self.src_images = disk_images
5693

    
5694
      old_name = export_info.get(constants.INISECT_INS, 'name')
5695
      # FIXME: int() here could throw a ValueError on broken exports
5696
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
5697
      if self.op.instance_name == old_name:
5698
        for idx, nic in enumerate(self.nics):
5699
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
5700
            nic_mac_ini = 'nic%d_mac' % idx
5701
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
5702

    
5703
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
5704
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
5705
    if self.op.start and not self.op.ip_check:
5706
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
5707
                                 " adding an instance in start mode")
5708

    
5709
    if self.op.ip_check:
5710
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
5711
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5712
                                   (self.check_ip, self.op.instance_name))
5713

    
5714
    #### mac address generation
5715
    # By generating here the mac address both the allocator and the hooks get
5716
    # the real final mac address rather than the 'auto' or 'generate' value.
5717
    # There is a race condition between the generation and the instance object
5718
    # creation, which means that we know the mac is valid now, but we're not
5719
    # sure it will be when we actually add the instance. If things go bad
5720
    # adding the instance will abort because of a duplicate mac, and the
5721
    # creation job will fail.
5722
    for nic in self.nics:
5723
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5724
        nic.mac = self.cfg.GenerateMAC()
5725

    
5726
    #### allocator run
5727

    
5728
    if self.op.iallocator is not None:
5729
      self._RunAllocator()
5730

    
5731
    #### node related checks
5732

    
5733
    # check primary node
5734
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
5735
    assert self.pnode is not None, \
5736
      "Cannot retrieve locked node %s" % self.op.pnode
5737
    if pnode.offline:
5738
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
5739
                                 pnode.name)
5740
    if pnode.drained:
5741
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
5742
                                 pnode.name)
5743

    
5744
    self.secondaries = []
5745

    
5746
    # mirror node verification
5747
    if self.op.disk_template in constants.DTS_NET_MIRROR:
5748
      if self.op.snode is None:
5749
        raise errors.OpPrereqError("The networked disk templates need"
5750
                                   " a mirror node")
5751
      if self.op.snode == pnode.name:
5752
        raise errors.OpPrereqError("The secondary node cannot be"
5753
                                   " the primary node.")
5754
      _CheckNodeOnline(self, self.op.snode)
5755
      _CheckNodeNotDrained(self, self.op.snode)
5756
      self.secondaries.append(self.op.snode)
5757

    
5758
    nodenames = [pnode.name] + self.secondaries
5759

    
5760
    req_size = _ComputeDiskSize(self.op.disk_template,
5761
                                self.disks)
5762

    
5763
    # Check lv size requirements
5764
    if req_size is not None:
5765
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5766
                                         self.op.hypervisor)
5767
      for node in nodenames:
5768
        info = nodeinfo[node]
5769
        info.Raise("Cannot get current information from node %s" % node)
5770
        info = info.payload
5771
        vg_free = info.get('vg_free', None)
5772
        if not isinstance(vg_free, int):
5773
          raise errors.OpPrereqError("Can't compute free disk space on"
5774
                                     " node %s" % node)
5775
        if req_size > vg_free:
5776
          raise errors.OpPrereqError("Not enough disk space on target node %s."
5777
                                     " %d MB available, %d MB required" %
5778
                                     (node, vg_free, req_size))
5779

    
5780
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
5781

    
5782
    # os verification
5783
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
5784
    result.Raise("OS '%s' not in supported os list for primary node %s" %
5785
                 (self.op.os_type, pnode.name), prereq=True)
5786

    
5787
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
5788

    
5789
    # memory check on primary node
5790
    if self.op.start:
5791
      _CheckNodeFreeMemory(self, self.pnode.name,
5792
                           "creating instance %s" % self.op.instance_name,
5793
                           self.be_full[constants.BE_MEMORY],
5794
                           self.op.hypervisor)
5795

    
5796
    self.dry_run_result = list(nodenames)
5797

    
5798
  def Exec(self, feedback_fn):
5799
    """Create and add the instance to the cluster.
5800

5801
    """
5802
    instance = self.op.instance_name
5803
    pnode_name = self.pnode.name
5804

    
5805
    ht_kind = self.op.hypervisor
5806
    if ht_kind in constants.HTS_REQ_PORT:
5807
      network_port = self.cfg.AllocatePort()
5808
    else:
5809
      network_port = None
5810

    
5811
    ##if self.op.vnc_bind_address is None:
5812
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
5813

    
5814
    # this is needed because os.path.join does not accept None arguments
5815
    if self.op.file_storage_dir is None:
5816
      string_file_storage_dir = ""
5817
    else:
5818
      string_file_storage_dir = self.op.file_storage_dir
5819

    
5820
    # build the full file storage dir path
5821
    file_storage_dir = os.path.normpath(os.path.join(
5822
                                        self.cfg.GetFileStorageDir(),
5823
                                        string_file_storage_dir, instance))
5824

    
5825

    
5826
    disks = _GenerateDiskTemplate(self,
5827
                                  self.op.disk_template,
5828
                                  instance, pnode_name,
5829
                                  self.secondaries,
5830
                                  self.disks,
5831
                                  file_storage_dir,
5832
                                  self.op.file_driver,
5833
                                  0)
5834

    
5835
    iobj = objects.Instance(name=instance, os=self.op.os_type,
5836
                            primary_node=pnode_name,
5837
                            nics=self.nics, disks=disks,
5838
                            disk_template=self.op.disk_template,
5839
                            admin_up=False,
5840
                            network_port=network_port,
5841
                            beparams=self.op.beparams,
5842
                            hvparams=self.op.hvparams,
5843
                            hypervisor=self.op.hypervisor,
5844
                            )
5845

    
5846
    feedback_fn("* creating instance disks...")
5847
    try:
5848
      _CreateDisks(self, iobj)
5849
    except errors.OpExecError:
5850
      self.LogWarning("Device creation failed, reverting...")
5851
      try:
5852
        _RemoveDisks(self, iobj)
5853
      finally:
5854
        self.cfg.ReleaseDRBDMinors(instance)
5855
        raise
5856

    
5857
    feedback_fn("adding instance %s to cluster config" % instance)
5858

    
5859
    self.cfg.AddInstance(iobj)
5860
    # Declare that we don't want to remove the instance lock anymore, as we've
5861
    # added the instance to the config
5862
    del self.remove_locks[locking.LEVEL_INSTANCE]
5863
    # Unlock all the nodes
5864
    if self.op.mode == constants.INSTANCE_IMPORT:
5865
      nodes_keep = [self.op.src_node]
5866
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
5867
                       if node != self.op.src_node]
5868
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
5869
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
5870
    else:
5871
      self.context.glm.release(locking.LEVEL_NODE)
5872
      del self.acquired_locks[locking.LEVEL_NODE]
5873

    
5874
    if self.op.wait_for_sync:
5875
      disk_abort = not _WaitForSync(self, iobj)
5876
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
5877
      # make sure the disks are not degraded (still sync-ing is ok)
5878
      time.sleep(15)
5879
      feedback_fn("* checking mirrors status")
5880
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
5881
    else:
5882
      disk_abort = False
5883

    
5884
    if disk_abort:
5885
      _RemoveDisks(self, iobj)
5886
      self.cfg.RemoveInstance(iobj.name)
5887
      # Make sure the instance lock gets removed
5888
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
5889
      raise errors.OpExecError("There are some degraded disks for"
5890
                               " this instance")
5891

    
5892
    feedback_fn("creating os for instance %s on node %s" %
5893
                (instance, pnode_name))
5894

    
5895
    if iobj.disk_template != constants.DT_DISKLESS:
5896
      if self.op.mode == constants.INSTANCE_CREATE:
5897
        feedback_fn("* running the instance OS create scripts...")
5898
        result = self.rpc.call_instance_os_add(pnode_name, iobj, False)
5899
        result.Raise("Could not add os for instance %s"
5900
                     " on node %s" % (instance, pnode_name))
5901

    
5902
      elif self.op.mode == constants.INSTANCE_IMPORT:
5903
        feedback_fn("* running the instance OS import scripts...")
5904
        src_node = self.op.src_node
5905
        src_images = self.src_images
5906
        cluster_name = self.cfg.GetClusterName()
5907
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
5908
                                                         src_node, src_images,
5909
                                                         cluster_name)
5910
        msg = import_result.fail_msg
5911
        if msg:
5912
          self.LogWarning("Error while importing the disk images for instance"
5913
                          " %s on node %s: %s" % (instance, pnode_name, msg))
5914
      else:
5915
        # also checked in the prereq part
5916
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
5917
                                     % self.op.mode)
5918

    
5919
    if self.op.start:
5920
      iobj.admin_up = True
5921
      self.cfg.Update(iobj)
5922
      logging.info("Starting instance %s on node %s", instance, pnode_name)
5923
      feedback_fn("* starting instance...")
5924
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
5925
      result.Raise("Could not start instance")
5926

    
5927
    return list(iobj.all_nodes)
5928

    
5929

    
5930
class LUConnectConsole(NoHooksLU):
5931
  """Connect to an instance's console.
5932

5933
  This is somewhat special in that it returns the command line that
5934
  you need to run on the master node in order to connect to the
5935
  console.
5936

5937
  """
5938
  _OP_REQP = ["instance_name"]
5939
  REQ_BGL = False
5940

    
5941
  def ExpandNames(self):
5942
    self._ExpandAndLockInstance()
5943

    
5944
  def CheckPrereq(self):
5945
    """Check prerequisites.
5946

5947
    This checks that the instance is in the cluster.
5948

5949
    """
5950
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5951
    assert self.instance is not None, \
5952
      "Cannot retrieve locked instance %s" % self.op.instance_name
5953
    _CheckNodeOnline(self, self.instance.primary_node)
5954

    
5955
  def Exec(self, feedback_fn):
5956
    """Connect to the console of an instance
5957

5958
    """
5959
    instance = self.instance
5960
    node = instance.primary_node
5961

    
5962
    node_insts = self.rpc.call_instance_list([node],
5963
                                             [instance.hypervisor])[node]
5964
    node_insts.Raise("Can't get node information from %s" % node)
5965

    
5966
    if instance.name not in node_insts.payload:
5967
      raise errors.OpExecError("Instance %s is not running." % instance.name)
5968

    
5969
    logging.debug("Connecting to console of %s on %s", instance.name, node)
5970

    
5971
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
5972
    cluster = self.cfg.GetClusterInfo()
5973
    # beparams and hvparams are passed separately, to avoid editing the
5974
    # instance and then saving the defaults in the instance itself.
5975
    hvparams = cluster.FillHV(instance)
5976
    beparams = cluster.FillBE(instance)
5977
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
5978

    
5979
    # build ssh cmdline
5980
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
5981

    
5982

    
5983
class LUReplaceDisks(LogicalUnit):
5984
  """Replace the disks of an instance.
5985

5986
  """
5987
  HPATH = "mirrors-replace"
5988
  HTYPE = constants.HTYPE_INSTANCE
5989
  _OP_REQP = ["instance_name", "mode", "disks"]
5990
  REQ_BGL = False
5991

    
5992
  def CheckArguments(self):
5993
    if not hasattr(self.op, "remote_node"):
5994
      self.op.remote_node = None
5995
    if not hasattr(self.op, "iallocator"):
5996
      self.op.iallocator = None
5997

    
5998
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
5999
                                  self.op.iallocator)
6000

    
6001
  def ExpandNames(self):
6002
    self._ExpandAndLockInstance()
6003

    
6004
    if self.op.iallocator is not None:
6005
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6006

    
6007
    elif self.op.remote_node is not None:
6008
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6009
      if remote_node is None:
6010
        raise errors.OpPrereqError("Node '%s' not known" %
6011
                                   self.op.remote_node)
6012

    
6013
      self.op.remote_node = remote_node
6014

    
6015
      # Warning: do not remove the locking of the new secondary here
6016
      # unless DRBD8.AddChildren is changed to work in parallel;
6017
      # currently it doesn't since parallel invocations of
6018
      # FindUnusedMinor will conflict
6019
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6020
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6021

    
6022
    else:
6023
      self.needed_locks[locking.LEVEL_NODE] = []
6024
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6025

    
6026
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
6027
                                   self.op.iallocator, self.op.remote_node,
6028
                                   self.op.disks)
6029

    
6030
    self.tasklets = [self.replacer]
6031

    
6032
  def DeclareLocks(self, level):
6033
    # If we're not already locking all nodes in the set we have to declare the
6034
    # instance's primary/secondary nodes.
6035
    if (level == locking.LEVEL_NODE and
6036
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6037
      self._LockInstancesNodes()
6038

    
6039
  def BuildHooksEnv(self):
6040
    """Build hooks env.
6041

6042
    This runs on the master, the primary and all the secondaries.
6043

6044
    """
6045
    instance = self.replacer.instance
6046
    env = {
6047
      "MODE": self.op.mode,
6048
      "NEW_SECONDARY": self.op.remote_node,
6049
      "OLD_SECONDARY": instance.secondary_nodes[0],
6050
      }
6051
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6052
    nl = [
6053
      self.cfg.GetMasterNode(),
6054
      instance.primary_node,
6055
      ]
6056
    if self.op.remote_node is not None:
6057
      nl.append(self.op.remote_node)
6058
    return env, nl, nl
6059

    
6060

    
6061
class LUEvacuateNode(LogicalUnit):
6062
  """Relocate the secondary instances from a node.
6063

6064
  """
6065
  HPATH = "node-evacuate"
6066
  HTYPE = constants.HTYPE_NODE
6067
  _OP_REQP = ["node_name"]
6068
  REQ_BGL = False
6069

    
6070
  def CheckArguments(self):
6071
    if not hasattr(self.op, "remote_node"):
6072
      self.op.remote_node = None
6073
    if not hasattr(self.op, "iallocator"):
6074
      self.op.iallocator = None
6075

    
6076
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
6077
                                  self.op.remote_node,
6078
                                  self.op.iallocator)
6079

    
6080
  def ExpandNames(self):
6081
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
6082
    if self.op.node_name is None:
6083
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name)
6084

    
6085
    self.needed_locks = {}
6086

    
6087
    # Declare node locks
6088
    if self.op.iallocator is not None:
6089
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6090

    
6091
    elif self.op.remote_node is not None:
6092
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6093
      if remote_node is None:
6094
        raise errors.OpPrereqError("Node '%s' not known" %
6095
                                   self.op.remote_node)
6096

    
6097
      self.op.remote_node = remote_node
6098

    
6099
      # Warning: do not remove the locking of the new secondary here
6100
      # unless DRBD8.AddChildren is changed to work in parallel;
6101
      # currently it doesn't since parallel invocations of
6102
      # FindUnusedMinor will conflict
6103
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6104
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6105

    
6106
    else:
6107
      raise errors.OpPrereqError("Invalid parameters")
6108

    
6109
    # Create tasklets for replacing disks for all secondary instances on this
6110
    # node
6111
    names = []
6112
    tasklets = []
6113

    
6114
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
6115
      logging.debug("Replacing disks for instance %s", inst.name)
6116
      names.append(inst.name)
6117

    
6118
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
6119
                                self.op.iallocator, self.op.remote_node, [])
6120
      tasklets.append(replacer)
6121

    
6122
    self.tasklets = tasklets
6123
    self.instance_names = names
6124

    
6125
    # Declare instance locks
6126
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
6127

    
6128
  def DeclareLocks(self, level):
6129
    # If we're not already locking all nodes in the set we have to declare the
6130
    # instance's primary/secondary nodes.
6131
    if (level == locking.LEVEL_NODE and
6132
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6133
      self._LockInstancesNodes()
6134

    
6135
  def BuildHooksEnv(self):
6136
    """Build hooks env.
6137

6138
    This runs on the master, the primary and all the secondaries.
6139

6140
    """
6141
    env = {
6142
      "NODE_NAME": self.op.node_name,
6143
      }
6144

    
6145
    nl = [self.cfg.GetMasterNode()]
6146

    
6147
    if self.op.remote_node is not None:
6148
      env["NEW_SECONDARY"] = self.op.remote_node
6149
      nl.append(self.op.remote_node)
6150

    
6151
    return (env, nl, nl)
6152

    
6153

    
6154
class TLReplaceDisks(Tasklet):
6155
  """Replaces disks for an instance.
6156

6157
  Note: Locking is not within the scope of this class.
6158

6159
  """
6160
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
6161
               disks):
6162
    """Initializes this class.
6163

6164
    """
6165
    Tasklet.__init__(self, lu)
6166

    
6167
    # Parameters
6168
    self.instance_name = instance_name
6169
    self.mode = mode
6170
    self.iallocator_name = iallocator_name
6171
    self.remote_node = remote_node
6172
    self.disks = disks
6173

    
6174
    # Runtime data
6175
    self.instance = None
6176
    self.new_node = None
6177
    self.target_node = None
6178
    self.other_node = None
6179
    self.remote_node_info = None
6180
    self.node_secondary_ip = None
6181

    
6182
  @staticmethod
6183
  def CheckArguments(mode, remote_node, iallocator):
6184
    """Helper function for users of this class.
6185

6186
    """
6187
    # check for valid parameter combination
6188
    if mode == constants.REPLACE_DISK_CHG:
6189
      if remote_node is None and iallocator is None:
6190
        raise errors.OpPrereqError("When changing the secondary either an"
6191
                                   " iallocator script must be used or the"
6192
                                   " new node given")
6193

    
6194
      if remote_node is not None and iallocator is not None:
6195
        raise errors.OpPrereqError("Give either the iallocator or the new"
6196
                                   " secondary, not both")
6197

    
6198
    elif remote_node is not None or iallocator is not None:
6199
      # Not replacing the secondary
6200
      raise errors.OpPrereqError("The iallocator and new node options can"
6201
                                 " only be used when changing the"
6202
                                 " secondary node")
6203

    
6204
  @staticmethod
6205
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
6206
    """Compute a new secondary node using an IAllocator.
6207

6208
    """
6209
    ial = IAllocator(lu.cfg, lu.rpc,
6210
                     mode=constants.IALLOCATOR_MODE_RELOC,
6211
                     name=instance_name,
6212
                     relocate_from=relocate_from)
6213

    
6214
    ial.Run(iallocator_name)
6215

    
6216
    if not ial.success:
6217
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
6218
                                 " %s" % (iallocator_name, ial.info))
6219

    
6220
    if len(ial.nodes) != ial.required_nodes:
6221
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6222
                                 " of nodes (%s), required %s" %
6223
                                 (len(ial.nodes), ial.required_nodes))
6224

    
6225
    remote_node_name = ial.nodes[0]
6226

    
6227
    lu.LogInfo("Selected new secondary for instance '%s': %s",
6228
               instance_name, remote_node_name)
6229

    
6230
    return remote_node_name
6231

    
6232
  def _FindFaultyDisks(self, node_name):
6233
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
6234
                                    node_name, True)
6235

    
6236
  def CheckPrereq(self):
6237
    """Check prerequisites.
6238

6239
    This checks that the instance is in the cluster.
6240

6241
    """
6242
    self.instance = self.cfg.GetInstanceInfo(self.instance_name)
6243
    assert self.instance is not None, \
6244
      "Cannot retrieve locked instance %s" % self.instance_name
6245

    
6246
    if self.instance.disk_template != constants.DT_DRBD8:
6247
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
6248
                                 " instances")
6249

    
6250
    if len(self.instance.secondary_nodes) != 1:
6251
      raise errors.OpPrereqError("The instance has a strange layout,"
6252
                                 " expected one secondary but found %d" %
6253
                                 len(self.instance.secondary_nodes))
6254

    
6255
    secondary_node = self.instance.secondary_nodes[0]
6256

    
6257
    if self.iallocator_name is None:
6258
      remote_node = self.remote_node
6259
    else:
6260
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
6261
                                       self.instance.name, secondary_node)
6262

    
6263
    if remote_node is not None:
6264
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
6265
      assert self.remote_node_info is not None, \
6266
        "Cannot retrieve locked node %s" % remote_node
6267
    else:
6268
      self.remote_node_info = None
6269

    
6270
    if remote_node == self.instance.primary_node:
6271
      raise errors.OpPrereqError("The specified node is the primary node of"
6272
                                 " the instance.")
6273

    
6274
    if remote_node == secondary_node:
6275
      raise errors.OpPrereqError("The specified node is already the"
6276
                                 " secondary node of the instance.")
6277

    
6278
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
6279
                                    constants.REPLACE_DISK_CHG):
6280
      raise errors.OpPrereqError("Cannot specify disks to be replaced")
6281

    
6282
    if self.mode == constants.REPLACE_DISK_AUTO:
6283
      faulty_primary = self._FindFaultyDisks(self.instance.primary_node)
6284
      faulty_secondary = self._FindFaultyDisks(secondary_node)
6285

    
6286
      if faulty_primary and faulty_secondary:
6287
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
6288
                                   " one node and can not be repaired"
6289
                                   " automatically" % self.instance_name)
6290

    
6291
      if faulty_primary:
6292
        self.disks = faulty_primary
6293
        self.target_node = self.instance.primary_node
6294
        self.other_node = secondary_node
6295
        check_nodes = [self.target_node, self.other_node]
6296
      elif faulty_secondary:
6297
        self.disks = faulty_secondary
6298
        self.target_node = secondary_node
6299
        self.other_node = self.instance.primary_node
6300
        check_nodes = [self.target_node, self.other_node]
6301
      else:
6302
        self.disks = []
6303
        check_nodes = []
6304

    
6305
    else:
6306
      # Non-automatic modes
6307
      if self.mode == constants.REPLACE_DISK_PRI:
6308
        self.target_node = self.instance.primary_node
6309
        self.other_node = secondary_node
6310
        check_nodes = [self.target_node, self.other_node]
6311

    
6312
      elif self.mode == constants.REPLACE_DISK_SEC:
6313
        self.target_node = secondary_node
6314
        self.other_node = self.instance.primary_node
6315
        check_nodes = [self.target_node, self.other_node]
6316

    
6317
      elif self.mode == constants.REPLACE_DISK_CHG:
6318
        self.new_node = remote_node
6319
        self.other_node = self.instance.primary_node
6320
        self.target_node = secondary_node
6321
        check_nodes = [self.new_node, self.other_node]
6322

    
6323
        _CheckNodeNotDrained(self.lu, remote_node)
6324

    
6325
      else:
6326
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
6327
                                     self.mode)
6328

    
6329
      # If not specified all disks should be replaced
6330
      if not self.disks:
6331
        self.disks = range(len(self.instance.disks))
6332

    
6333
    for node in check_nodes:
6334
      _CheckNodeOnline(self.lu, node)
6335

    
6336
    # Check whether disks are valid
6337
    for disk_idx in self.disks:
6338
      self.instance.FindDisk(disk_idx)
6339

    
6340
    # Get secondary node IP addresses
6341
    node_2nd_ip = {}
6342

    
6343
    for node_name in [self.target_node, self.other_node, self.new_node]:
6344
      if node_name is not None:
6345
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
6346

    
6347
    self.node_secondary_ip = node_2nd_ip
6348

    
6349
  def Exec(self, feedback_fn):
6350
    """Execute disk replacement.
6351

6352
    This dispatches the disk replacement to the appropriate handler.
6353

6354
    """
6355
    if not self.disks:
6356
      feedback_fn("No disks need replacement")
6357
      return
6358

    
6359
    feedback_fn("Replacing disk(s) %s for %s" %
6360
                (", ".join([str(i) for i in self.disks]), self.instance.name))
6361

    
6362
    activate_disks = (not self.instance.admin_up)
6363

    
6364
    # Activate the instance disks if we're replacing them on a down instance
6365
    if activate_disks:
6366
      _StartInstanceDisks(self.lu, self.instance, True)
6367

    
6368
    try:
6369
      # Should we replace the secondary node?
6370
      if self.new_node is not None:
6371
        return self._ExecDrbd8Secondary()
6372
      else:
6373
        return self._ExecDrbd8DiskOnly()
6374

    
6375
    finally:
6376
      # Deactivate the instance disks if we're replacing them on a down instance
6377
      if activate_disks:
6378
        _SafeShutdownInstanceDisks(self.lu, self.instance)
6379

    
6380
  def _CheckVolumeGroup(self, nodes):
6381
    self.lu.LogInfo("Checking volume groups")
6382

    
6383
    vgname = self.cfg.GetVGName()
6384

    
6385
    # Make sure volume group exists on all involved nodes
6386
    results = self.rpc.call_vg_list(nodes)
6387
    if not results:
6388
      raise errors.OpExecError("Can't list volume groups on the nodes")
6389

    
6390
    for node in nodes:
6391
      res = results[node]
6392
      res.Raise("Error checking node %s" % node)
6393
      if vgname not in res.payload:
6394
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
6395
                                 (vgname, node))
6396

    
6397
  def _CheckDisksExistence(self, nodes):
6398
    # Check disk existence
6399
    for idx, dev in enumerate(self.instance.disks):
6400
      if idx not in self.disks:
6401
        continue
6402

    
6403
      for node in nodes:
6404
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
6405
        self.cfg.SetDiskID(dev, node)
6406

    
6407
        result = self.rpc.call_blockdev_find(node, dev)
6408

    
6409
        msg = result.fail_msg
6410
        if msg or not result.payload:
6411
          if not msg:
6412
            msg = "disk not found"
6413
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
6414
                                   (idx, node, msg))
6415

    
6416
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
6417
    for idx, dev in enumerate(self.instance.disks):
6418
      if idx not in self.disks:
6419
        continue
6420

    
6421
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
6422
                      (idx, node_name))
6423

    
6424
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
6425
                                   ldisk=ldisk):
6426
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
6427
                                 " replace disks for instance %s" %
6428
                                 (node_name, self.instance.name))
6429

    
6430
  def _CreateNewStorage(self, node_name):
6431
    vgname = self.cfg.GetVGName()
6432
    iv_names = {}
6433

    
6434
    for idx, dev in enumerate(self.instance.disks):
6435
      if idx not in self.disks:
6436
        continue
6437

    
6438
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
6439

    
6440
      self.cfg.SetDiskID(dev, node_name)
6441

    
6442
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
6443
      names = _GenerateUniqueNames(self.lu, lv_names)
6444

    
6445
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
6446
                             logical_id=(vgname, names[0]))
6447
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6448
                             logical_id=(vgname, names[1]))
6449

    
6450
      new_lvs = [lv_data, lv_meta]
6451
      old_lvs = dev.children
6452
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
6453

    
6454
      # we pass force_create=True to force the LVM creation
6455
      for new_lv in new_lvs:
6456
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
6457
                        _GetInstanceInfoText(self.instance), False)
6458

    
6459
    return iv_names
6460

    
6461
  def _CheckDevices(self, node_name, iv_names):
6462
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
6463
      self.cfg.SetDiskID(dev, node_name)
6464

    
6465
      result = self.rpc.call_blockdev_find(node_name, dev)
6466

    
6467
      msg = result.fail_msg
6468
      if msg or not result.payload:
6469
        if not msg:
6470
          msg = "disk not found"
6471
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
6472
                                 (name, msg))
6473

    
6474
      if result.payload.is_degraded:
6475
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
6476

    
6477
  def _RemoveOldStorage(self, node_name, iv_names):
6478
    for name, (dev, old_lvs, _) in iv_names.iteritems():
6479
      self.lu.LogInfo("Remove logical volumes for %s" % name)
6480

    
6481
      for lv in old_lvs:
6482
        self.cfg.SetDiskID(lv, node_name)
6483

    
6484
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
6485
        if msg:
6486
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
6487
                             hint="remove unused LVs manually")
6488

    
6489
  def _ExecDrbd8DiskOnly(self):
6490
    """Replace a disk on the primary or secondary for DRBD 8.
6491

6492
    The algorithm for replace is quite complicated:
6493

6494
      1. for each disk to be replaced:
6495

6496
        1. create new LVs on the target node with unique names
6497
        1. detach old LVs from the drbd device
6498
        1. rename old LVs to name_replaced.<time_t>
6499
        1. rename new LVs to old LVs
6500
        1. attach the new LVs (with the old names now) to the drbd device
6501

6502
      1. wait for sync across all devices
6503

6504
      1. for each modified disk:
6505

6506
        1. remove old LVs (which have the name name_replaces.<time_t>)
6507

6508
    Failures are not very well handled.
6509

6510
    """
6511
    steps_total = 6
6512

    
6513
    # Step: check device activation
6514
    self.lu.LogStep(1, steps_total, "Check device existence")
6515
    self._CheckDisksExistence([self.other_node, self.target_node])
6516
    self._CheckVolumeGroup([self.target_node, self.other_node])
6517

    
6518
    # Step: check other node consistency
6519
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6520
    self._CheckDisksConsistency(self.other_node,
6521
                                self.other_node == self.instance.primary_node,
6522
                                False)
6523

    
6524
    # Step: create new storage
6525
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6526
    iv_names = self._CreateNewStorage(self.target_node)
6527

    
6528
    # Step: for each lv, detach+rename*2+attach
6529
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6530
    for dev, old_lvs, new_lvs in iv_names.itervalues():
6531
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
6532

    
6533
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
6534
                                                     old_lvs)
6535
      result.Raise("Can't detach drbd from local storage on node"
6536
                   " %s for device %s" % (self.target_node, dev.iv_name))
6537
      #dev.children = []
6538
      #cfg.Update(instance)
6539

    
6540
      # ok, we created the new LVs, so now we know we have the needed
6541
      # storage; as such, we proceed on the target node to rename
6542
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
6543
      # using the assumption that logical_id == physical_id (which in
6544
      # turn is the unique_id on that node)
6545

    
6546
      # FIXME(iustin): use a better name for the replaced LVs
6547
      temp_suffix = int(time.time())
6548
      ren_fn = lambda d, suff: (d.physical_id[0],
6549
                                d.physical_id[1] + "_replaced-%s" % suff)
6550

    
6551
      # Build the rename list based on what LVs exist on the node
6552
      rename_old_to_new = []
6553
      for to_ren in old_lvs:
6554
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
6555
        if not result.fail_msg and result.payload:
6556
          # device exists
6557
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
6558

    
6559
      self.lu.LogInfo("Renaming the old LVs on the target node")
6560
      result = self.rpc.call_blockdev_rename(self.target_node,
6561
                                             rename_old_to_new)
6562
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
6563

    
6564
      # Now we rename the new LVs to the old LVs
6565
      self.lu.LogInfo("Renaming the new LVs on the target node")
6566
      rename_new_to_old = [(new, old.physical_id)
6567
                           for old, new in zip(old_lvs, new_lvs)]
6568
      result = self.rpc.call_blockdev_rename(self.target_node,
6569
                                             rename_new_to_old)
6570
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
6571

    
6572
      for old, new in zip(old_lvs, new_lvs):
6573
        new.logical_id = old.logical_id
6574
        self.cfg.SetDiskID(new, self.target_node)
6575

    
6576
      for disk in old_lvs:
6577
        disk.logical_id = ren_fn(disk, temp_suffix)
6578
        self.cfg.SetDiskID(disk, self.target_node)
6579

    
6580
      # Now that the new lvs have the old name, we can add them to the device
6581
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
6582
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
6583
                                                  new_lvs)
6584
      msg = result.fail_msg
6585
      if msg:
6586
        for new_lv in new_lvs:
6587
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
6588
                                               new_lv).fail_msg
6589
          if msg2:
6590
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
6591
                               hint=("cleanup manually the unused logical"
6592
                                     "volumes"))
6593
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
6594

    
6595
      dev.children = new_lvs
6596

    
6597
      self.cfg.Update(self.instance)
6598

    
6599
    # Wait for sync
6600
    # This can fail as the old devices are degraded and _WaitForSync
6601
    # does a combined result over all disks, so we don't check its return value
6602
    self.lu.LogStep(5, steps_total, "Sync devices")
6603
    _WaitForSync(self.lu, self.instance, unlock=True)
6604

    
6605
    # Check all devices manually
6606
    self._CheckDevices(self.instance.primary_node, iv_names)
6607

    
6608
    # Step: remove old storage
6609
    self.lu.LogStep(6, steps_total, "Removing old storage")
6610
    self._RemoveOldStorage(self.target_node, iv_names)
6611

    
6612
  def _ExecDrbd8Secondary(self):
6613
    """Replace the secondary node for DRBD 8.
6614

6615
    The algorithm for replace is quite complicated:
6616
      - for all disks of the instance:
6617
        - create new LVs on the new node with same names
6618
        - shutdown the drbd device on the old secondary
6619
        - disconnect the drbd network on the primary
6620
        - create the drbd device on the new secondary
6621
        - network attach the drbd on the primary, using an artifice:
6622
          the drbd code for Attach() will connect to the network if it
6623
          finds a device which is connected to the good local disks but
6624
          not network enabled
6625
      - wait for sync across all devices
6626
      - remove all disks from the old secondary
6627

6628
    Failures are not very well handled.
6629

6630
    """
6631
    steps_total = 6
6632

    
6633
    # Step: check device activation
6634
    self.lu.LogStep(1, steps_total, "Check device existence")
6635
    self._CheckDisksExistence([self.instance.primary_node])
6636
    self._CheckVolumeGroup([self.instance.primary_node])
6637

    
6638
    # Step: check other node consistency
6639
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6640
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
6641

    
6642
    # Step: create new storage
6643
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6644
    for idx, dev in enumerate(self.instance.disks):
6645
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
6646
                      (self.new_node, idx))
6647
      # we pass force_create=True to force LVM creation
6648
      for new_lv in dev.children:
6649
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
6650
                        _GetInstanceInfoText(self.instance), False)
6651

    
6652
    # Step 4: dbrd minors and drbd setups changes
6653
    # after this, we must manually remove the drbd minors on both the
6654
    # error and the success paths
6655
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6656
    minors = self.cfg.AllocateDRBDMinor([self.new_node
6657
                                         for dev in self.instance.disks],
6658
                                        self.instance.name)
6659
    logging.debug("Allocated minors %r" % (minors,))
6660

    
6661
    iv_names = {}
6662
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
6663
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
6664
                      (self.new_node, idx))
6665
      # create new devices on new_node; note that we create two IDs:
6666
      # one without port, so the drbd will be activated without
6667
      # networking information on the new node at this stage, and one
6668
      # with network, for the latter activation in step 4
6669
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
6670
      if self.instance.primary_node == o_node1:
6671
        p_minor = o_minor1
6672
      else:
6673
        p_minor = o_minor2
6674

    
6675
      new_alone_id = (self.instance.primary_node, self.new_node, None,
6676
                      p_minor, new_minor, o_secret)
6677
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
6678
                    p_minor, new_minor, o_secret)
6679

    
6680
      iv_names[idx] = (dev, dev.children, new_net_id)
6681
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
6682
                    new_net_id)
6683
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
6684
                              logical_id=new_alone_id,
6685
                              children=dev.children,
6686
                              size=dev.size)
6687
      try:
6688
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
6689
                              _GetInstanceInfoText(self.instance), False)
6690
      except errors.GenericError:
6691
        self.cfg.ReleaseDRBDMinors(self.instance.name)
6692
        raise
6693

    
6694
    # We have new devices, shutdown the drbd on the old secondary
6695
    for idx, dev in enumerate(self.instance.disks):
6696
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
6697
      self.cfg.SetDiskID(dev, self.target_node)
6698
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
6699
      if msg:
6700
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
6701
                           "node: %s" % (idx, msg),
6702
                           hint=("Please cleanup this device manually as"
6703
                                 " soon as possible"))
6704

    
6705
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
6706
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
6707
                                               self.node_secondary_ip,
6708
                                               self.instance.disks)\
6709
                                              [self.instance.primary_node]
6710

    
6711
    msg = result.fail_msg
6712
    if msg:
6713
      # detaches didn't succeed (unlikely)
6714
      self.cfg.ReleaseDRBDMinors(self.instance.name)
6715
      raise errors.OpExecError("Can't detach the disks from the network on"
6716
                               " old node: %s" % (msg,))
6717

    
6718
    # if we managed to detach at least one, we update all the disks of
6719
    # the instance to point to the new secondary
6720
    self.lu.LogInfo("Updating instance configuration")
6721
    for dev, _, new_logical_id in iv_names.itervalues():
6722
      dev.logical_id = new_logical_id
6723
      self.cfg.SetDiskID(dev, self.instance.primary_node)
6724

    
6725
    self.cfg.Update(self.instance)
6726

    
6727
    # and now perform the drbd attach
6728
    self.lu.LogInfo("Attaching primary drbds to new secondary"
6729
                    " (standalone => connected)")
6730
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
6731
                                            self.new_node],
6732
                                           self.node_secondary_ip,
6733
                                           self.instance.disks,
6734
                                           self.instance.name,
6735
                                           False)
6736
    for to_node, to_result in result.items():
6737
      msg = to_result.fail_msg
6738
      if msg:
6739
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
6740
                           to_node, msg,
6741
                           hint=("please do a gnt-instance info to see the"
6742
                                 " status of disks"))
6743

    
6744
    # Wait for sync
6745
    # This can fail as the old devices are degraded and _WaitForSync
6746
    # does a combined result over all disks, so we don't check its return value
6747
    self.lu.LogStep(5, steps_total, "Sync devices")
6748
    _WaitForSync(self.lu, self.instance, unlock=True)
6749

    
6750
    # Check all devices manually
6751
    self._CheckDevices(self.instance.primary_node, iv_names)
6752

    
6753
    # Step: remove old storage
6754
    self.lu.LogStep(6, steps_total, "Removing old storage")
6755
    self._RemoveOldStorage(self.target_node, iv_names)
6756

    
6757

    
6758
class LURepairNodeStorage(NoHooksLU):
6759
  """Repairs the volume group on a node.
6760

6761
  """
6762
  _OP_REQP = ["node_name"]
6763
  REQ_BGL = False
6764

    
6765
  def CheckArguments(self):
6766
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
6767
    if node_name is None:
6768
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
6769

    
6770
    self.op.node_name = node_name
6771

    
6772
  def ExpandNames(self):
6773
    self.needed_locks = {
6774
      locking.LEVEL_NODE: [self.op.node_name],
6775
      }
6776

    
6777
  def _CheckFaultyDisks(self, instance, node_name):
6778
    if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
6779
                                node_name, True):
6780
      raise errors.OpPrereqError("Instance '%s' has faulty disks on"
6781
                                 " node '%s'" % (instance.name, node_name))
6782

    
6783
  def CheckPrereq(self):
6784
    """Check prerequisites.
6785

6786
    """
6787
    storage_type = self.op.storage_type
6788

    
6789
    if (constants.SO_FIX_CONSISTENCY not in
6790
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
6791
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
6792
                                 " repaired" % storage_type)
6793

    
6794
    # Check whether any instance on this node has faulty disks
6795
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
6796
      check_nodes = set(inst.all_nodes)
6797
      check_nodes.discard(self.op.node_name)
6798
      for inst_node_name in check_nodes:
6799
        self._CheckFaultyDisks(inst, inst_node_name)
6800

    
6801
  def Exec(self, feedback_fn):
6802
    feedback_fn("Repairing storage unit '%s' on %s ..." %
6803
                (self.op.name, self.op.node_name))
6804

    
6805
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
6806
    result = self.rpc.call_storage_execute(self.op.node_name,
6807
                                           self.op.storage_type, st_args,
6808
                                           self.op.name,
6809
                                           constants.SO_FIX_CONSISTENCY)
6810
    result.Raise("Failed to repair storage unit '%s' on %s" %
6811
                 (self.op.name, self.op.node_name))
6812

    
6813

    
6814
class LUGrowDisk(LogicalUnit):
6815
  """Grow a disk of an instance.
6816

6817
  """
6818
  HPATH = "disk-grow"
6819
  HTYPE = constants.HTYPE_INSTANCE
6820
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
6821
  REQ_BGL = False
6822

    
6823
  def ExpandNames(self):
6824
    self._ExpandAndLockInstance()
6825
    self.needed_locks[locking.LEVEL_NODE] = []
6826
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6827

    
6828
  def DeclareLocks(self, level):
6829
    if level == locking.LEVEL_NODE:
6830
      self._LockInstancesNodes()
6831

    
6832
  def BuildHooksEnv(self):
6833
    """Build hooks env.
6834

6835
    This runs on the master, the primary and all the secondaries.
6836

6837
    """
6838
    env = {
6839
      "DISK": self.op.disk,
6840
      "AMOUNT": self.op.amount,
6841
      }
6842
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6843
    nl = [
6844
      self.cfg.GetMasterNode(),
6845
      self.instance.primary_node,
6846
      ]
6847
    return env, nl, nl
6848

    
6849
  def CheckPrereq(self):
6850
    """Check prerequisites.
6851

6852
    This checks that the instance is in the cluster.
6853

6854
    """
6855
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6856
    assert instance is not None, \
6857
      "Cannot retrieve locked instance %s" % self.op.instance_name
6858
    nodenames = list(instance.all_nodes)
6859
    for node in nodenames:
6860
      _CheckNodeOnline(self, node)
6861

    
6862

    
6863
    self.instance = instance
6864

    
6865
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
6866
      raise errors.OpPrereqError("Instance's disk layout does not support"
6867
                                 " growing.")
6868

    
6869
    self.disk = instance.FindDisk(self.op.disk)
6870

    
6871
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
6872
                                       instance.hypervisor)
6873
    for node in nodenames:
6874
      info = nodeinfo[node]
6875
      info.Raise("Cannot get current information from node %s" % node)
6876
      vg_free = info.payload.get('vg_free', None)
6877
      if not isinstance(vg_free, int):
6878
        raise errors.OpPrereqError("Can't compute free disk space on"
6879
                                   " node %s" % node)
6880
      if self.op.amount > vg_free:
6881
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
6882
                                   " %d MiB available, %d MiB required" %
6883
                                   (node, vg_free, self.op.amount))
6884

    
6885
  def Exec(self, feedback_fn):
6886
    """Execute disk grow.
6887

6888
    """
6889
    instance = self.instance
6890
    disk = self.disk
6891
    for node in instance.all_nodes:
6892
      self.cfg.SetDiskID(disk, node)
6893
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
6894
      result.Raise("Grow request failed to node %s" % node)
6895
    disk.RecordGrow(self.op.amount)
6896
    self.cfg.Update(instance)
6897
    if self.op.wait_for_sync:
6898
      disk_abort = not _WaitForSync(self, instance)
6899
      if disk_abort:
6900
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
6901
                             " status.\nPlease check the instance.")
6902

    
6903

    
6904
class LUQueryInstanceData(NoHooksLU):
6905
  """Query runtime instance data.
6906

6907
  """
6908
  _OP_REQP = ["instances", "static"]
6909
  REQ_BGL = False
6910

    
6911
  def ExpandNames(self):
6912
    self.needed_locks = {}
6913
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
6914

    
6915
    if not isinstance(self.op.instances, list):
6916
      raise errors.OpPrereqError("Invalid argument type 'instances'")
6917

    
6918
    if self.op.instances:
6919
      self.wanted_names = []
6920
      for name in self.op.instances:
6921
        full_name = self.cfg.ExpandInstanceName(name)
6922
        if full_name is None:
6923
          raise errors.OpPrereqError("Instance '%s' not known" % name)
6924
        self.wanted_names.append(full_name)
6925
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
6926
    else:
6927
      self.wanted_names = None
6928
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
6929

    
6930
    self.needed_locks[locking.LEVEL_NODE] = []
6931
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6932

    
6933
  def DeclareLocks(self, level):
6934
    if level == locking.LEVEL_NODE:
6935
      self._LockInstancesNodes()
6936

    
6937
  def CheckPrereq(self):
6938
    """Check prerequisites.
6939

6940
    This only checks the optional instance list against the existing names.
6941

6942
    """
6943
    if self.wanted_names is None:
6944
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
6945

    
6946
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
6947
                             in self.wanted_names]
6948
    return
6949

    
6950
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
6951
    """Returns the status of a block device
6952

6953
    """
6954
    if self.op.static or not node:
6955
      return None
6956

    
6957
    self.cfg.SetDiskID(dev, node)
6958

    
6959
    result = self.rpc.call_blockdev_find(node, dev)
6960
    if result.offline:
6961
      return None
6962

    
6963
    result.Raise("Can't compute disk status for %s" % instance_name)
6964

    
6965
    status = result.payload
6966
    if status is None:
6967
      return None
6968

    
6969
    return (status.dev_path, status.major, status.minor,
6970
            status.sync_percent, status.estimated_time,
6971
            status.is_degraded, status.ldisk_status)
6972

    
6973
  def _ComputeDiskStatus(self, instance, snode, dev):
6974
    """Compute block device status.
6975

6976
    """
6977
    if dev.dev_type in constants.LDS_DRBD:
6978
      # we change the snode then (otherwise we use the one passed in)
6979
      if dev.logical_id[0] == instance.primary_node:
6980
        snode = dev.logical_id[1]
6981
      else:
6982
        snode = dev.logical_id[0]
6983

    
6984
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
6985
                                              instance.name, dev)
6986
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
6987

    
6988
    if dev.children:
6989
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
6990
                      for child in dev.children]
6991
    else:
6992
      dev_children = []
6993

    
6994
    data = {
6995
      "iv_name": dev.iv_name,
6996
      "dev_type": dev.dev_type,
6997
      "logical_id": dev.logical_id,
6998
      "physical_id": dev.physical_id,
6999
      "pstatus": dev_pstatus,
7000
      "sstatus": dev_sstatus,
7001
      "children": dev_children,
7002
      "mode": dev.mode,
7003
      "size": dev.size,
7004
      }
7005

    
7006
    return data
7007

    
7008
  def Exec(self, feedback_fn):
7009
    """Gather and return data"""
7010
    result = {}
7011

    
7012
    cluster = self.cfg.GetClusterInfo()
7013

    
7014
    for instance in self.wanted_instances:
7015
      if not self.op.static:
7016
        remote_info = self.rpc.call_instance_info(instance.primary_node,
7017
                                                  instance.name,
7018
                                                  instance.hypervisor)
7019
        remote_info.Raise("Error checking node %s" % instance.primary_node)
7020
        remote_info = remote_info.payload
7021
        if remote_info and "state" in remote_info:
7022
          remote_state = "up"
7023
        else:
7024
          remote_state = "down"
7025
      else:
7026
        remote_state = None
7027
      if instance.admin_up:
7028
        config_state = "up"
7029
      else:
7030
        config_state = "down"
7031

    
7032
      disks = [self._ComputeDiskStatus(instance, None, device)
7033
               for device in instance.disks]
7034

    
7035
      idict = {
7036
        "name": instance.name,
7037
        "config_state": config_state,
7038
        "run_state": remote_state,
7039
        "pnode": instance.primary_node,
7040
        "snodes": instance.secondary_nodes,
7041
        "os": instance.os,
7042
        # this happens to be the same format used for hooks
7043
        "nics": _NICListToTuple(self, instance.nics),
7044
        "disks": disks,
7045
        "hypervisor": instance.hypervisor,
7046
        "network_port": instance.network_port,
7047
        "hv_instance": instance.hvparams,
7048
        "hv_actual": cluster.FillHV(instance),
7049
        "be_instance": instance.beparams,
7050
        "be_actual": cluster.FillBE(instance),
7051
        "serial_no": instance.serial_no,
7052
        "mtime": instance.mtime,
7053
        "ctime": instance.ctime,
7054
        "uuid": instance.uuid,
7055
        }
7056

    
7057
      result[instance.name] = idict
7058

    
7059
    return result
7060

    
7061

    
7062
class LUSetInstanceParams(LogicalUnit):
7063
  """Modifies an instances's parameters.
7064

7065
  """
7066
  HPATH = "instance-modify"
7067
  HTYPE = constants.HTYPE_INSTANCE
7068
  _OP_REQP = ["instance_name"]
7069
  REQ_BGL = False
7070

    
7071
  def CheckArguments(self):
7072
    if not hasattr(self.op, 'nics'):
7073
      self.op.nics = []
7074
    if not hasattr(self.op, 'disks'):
7075
      self.op.disks = []
7076
    if not hasattr(self.op, 'beparams'):
7077
      self.op.beparams = {}
7078
    if not hasattr(self.op, 'hvparams'):
7079
      self.op.hvparams = {}
7080
    self.op.force = getattr(self.op, "force", False)
7081
    if not (self.op.nics or self.op.disks or
7082
            self.op.hvparams or self.op.beparams):
7083
      raise errors.OpPrereqError("No changes submitted")
7084

    
7085
    # Disk validation
7086
    disk_addremove = 0
7087
    for disk_op, disk_dict in self.op.disks:
7088
      if disk_op == constants.DDM_REMOVE:
7089
        disk_addremove += 1
7090
        continue
7091
      elif disk_op == constants.DDM_ADD:
7092
        disk_addremove += 1
7093
      else:
7094
        if not isinstance(disk_op, int):
7095
          raise errors.OpPrereqError("Invalid disk index")
7096
        if not isinstance(disk_dict, dict):
7097
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
7098
          raise errors.OpPrereqError(msg)
7099

    
7100
      if disk_op == constants.DDM_ADD:
7101
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
7102
        if mode not in constants.DISK_ACCESS_SET:
7103
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
7104
        size = disk_dict.get('size', None)
7105
        if size is None:
7106
          raise errors.OpPrereqError("Required disk parameter size missing")
7107
        try:
7108
          size = int(size)
7109
        except ValueError, err:
7110
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
7111
                                     str(err))
7112
        disk_dict['size'] = size
7113
      else:
7114
        # modification of disk
7115
        if 'size' in disk_dict:
7116
          raise errors.OpPrereqError("Disk size change not possible, use"
7117
                                     " grow-disk")
7118

    
7119
    if disk_addremove > 1:
7120
      raise errors.OpPrereqError("Only one disk add or remove operation"
7121
                                 " supported at a time")
7122

    
7123
    # NIC validation
7124
    nic_addremove = 0
7125
    for nic_op, nic_dict in self.op.nics:
7126
      if nic_op == constants.DDM_REMOVE:
7127
        nic_addremove += 1
7128
        continue
7129
      elif nic_op == constants.DDM_ADD:
7130
        nic_addremove += 1
7131
      else:
7132
        if not isinstance(nic_op, int):
7133
          raise errors.OpPrereqError("Invalid nic index")
7134
        if not isinstance(nic_dict, dict):
7135
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
7136
          raise errors.OpPrereqError(msg)
7137

    
7138
      # nic_dict should be a dict
7139
      nic_ip = nic_dict.get('ip', None)
7140
      if nic_ip is not None:
7141
        if nic_ip.lower() == constants.VALUE_NONE:
7142
          nic_dict['ip'] = None
7143
        else:
7144
          if not utils.IsValidIP(nic_ip):
7145
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
7146

    
7147
      nic_bridge = nic_dict.get('bridge', None)
7148
      nic_link = nic_dict.get('link', None)
7149
      if nic_bridge and nic_link:
7150
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7151
                                   " at the same time")
7152
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
7153
        nic_dict['bridge'] = None
7154
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
7155
        nic_dict['link'] = None
7156

    
7157
      if nic_op == constants.DDM_ADD:
7158
        nic_mac = nic_dict.get('mac', None)
7159
        if nic_mac is None:
7160
          nic_dict['mac'] = constants.VALUE_AUTO
7161

    
7162
      if 'mac' in nic_dict:
7163
        nic_mac = nic_dict['mac']
7164
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7165
          if not utils.IsValidMac(nic_mac):
7166
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
7167
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
7168
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
7169
                                     " modifying an existing nic")
7170

    
7171
    if nic_addremove > 1:
7172
      raise errors.OpPrereqError("Only one NIC add or remove operation"
7173
                                 " supported at a time")
7174

    
7175
  def ExpandNames(self):
7176
    self._ExpandAndLockInstance()
7177
    self.needed_locks[locking.LEVEL_NODE] = []
7178
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7179

    
7180
  def DeclareLocks(self, level):
7181
    if level == locking.LEVEL_NODE:
7182
      self._LockInstancesNodes()
7183

    
7184
  def BuildHooksEnv(self):
7185
    """Build hooks env.
7186

7187
    This runs on the master, primary and secondaries.
7188

7189
    """
7190
    args = dict()
7191
    if constants.BE_MEMORY in self.be_new:
7192
      args['memory'] = self.be_new[constants.BE_MEMORY]
7193
    if constants.BE_VCPUS in self.be_new:
7194
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
7195
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
7196
    # information at all.
7197
    if self.op.nics:
7198
      args['nics'] = []
7199
      nic_override = dict(self.op.nics)
7200
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
7201
      for idx, nic in enumerate(self.instance.nics):
7202
        if idx in nic_override:
7203
          this_nic_override = nic_override[idx]
7204
        else:
7205
          this_nic_override = {}
7206
        if 'ip' in this_nic_override:
7207
          ip = this_nic_override['ip']
7208
        else:
7209
          ip = nic.ip
7210
        if 'mac' in this_nic_override:
7211
          mac = this_nic_override['mac']
7212
        else:
7213
          mac = nic.mac
7214
        if idx in self.nic_pnew:
7215
          nicparams = self.nic_pnew[idx]
7216
        else:
7217
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
7218
        mode = nicparams[constants.NIC_MODE]
7219
        link = nicparams[constants.NIC_LINK]
7220
        args['nics'].append((ip, mac, mode, link))
7221
      if constants.DDM_ADD in nic_override:
7222
        ip = nic_override[constants.DDM_ADD].get('ip', None)
7223
        mac = nic_override[constants.DDM_ADD]['mac']
7224
        nicparams = self.nic_pnew[constants.DDM_ADD]
7225
        mode = nicparams[constants.NIC_MODE]
7226
        link = nicparams[constants.NIC_LINK]
7227
        args['nics'].append((ip, mac, mode, link))
7228
      elif constants.DDM_REMOVE in nic_override:
7229
        del args['nics'][-1]
7230

    
7231
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
7232
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7233
    return env, nl, nl
7234

    
7235
  def _GetUpdatedParams(self, old_params, update_dict,
7236
                        default_values, parameter_types):
7237
    """Return the new params dict for the given params.
7238

7239
    @type old_params: dict
7240
    @param old_params: old parameters
7241
    @type update_dict: dict
7242
    @param update_dict: dict containing new parameter values,
7243
                        or constants.VALUE_DEFAULT to reset the
7244
                        parameter to its default value
7245
    @type default_values: dict
7246
    @param default_values: default values for the filled parameters
7247
    @type parameter_types: dict
7248
    @param parameter_types: dict mapping target dict keys to types
7249
                            in constants.ENFORCEABLE_TYPES
7250
    @rtype: (dict, dict)
7251
    @return: (new_parameters, filled_parameters)
7252

7253
    """
7254
    params_copy = copy.deepcopy(old_params)
7255
    for key, val in update_dict.iteritems():
7256
      if val == constants.VALUE_DEFAULT:
7257
        try:
7258
          del params_copy[key]
7259
        except KeyError:
7260
          pass
7261
      else:
7262
        params_copy[key] = val
7263
    utils.ForceDictType(params_copy, parameter_types)
7264
    params_filled = objects.FillDict(default_values, params_copy)
7265
    return (params_copy, params_filled)
7266

    
7267
  def CheckPrereq(self):
7268
    """Check prerequisites.
7269

7270
    This only checks the instance list against the existing names.
7271

7272
    """
7273
    self.force = self.op.force
7274

    
7275
    # checking the new params on the primary/secondary nodes
7276

    
7277
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7278
    cluster = self.cluster = self.cfg.GetClusterInfo()
7279
    assert self.instance is not None, \
7280
      "Cannot retrieve locked instance %s" % self.op.instance_name
7281
    pnode = instance.primary_node
7282
    nodelist = list(instance.all_nodes)
7283

    
7284
    # hvparams processing
7285
    if self.op.hvparams:
7286
      i_hvdict, hv_new = self._GetUpdatedParams(
7287
                             instance.hvparams, self.op.hvparams,
7288
                             cluster.hvparams[instance.hypervisor],
7289
                             constants.HVS_PARAMETER_TYPES)
7290
      # local check
7291
      hypervisor.GetHypervisor(
7292
        instance.hypervisor).CheckParameterSyntax(hv_new)
7293
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
7294
      self.hv_new = hv_new # the new actual values
7295
      self.hv_inst = i_hvdict # the new dict (without defaults)
7296
    else:
7297
      self.hv_new = self.hv_inst = {}
7298

    
7299
    # beparams processing
7300
    if self.op.beparams:
7301
      i_bedict, be_new = self._GetUpdatedParams(
7302
                             instance.beparams, self.op.beparams,
7303
                             cluster.beparams[constants.PP_DEFAULT],
7304
                             constants.BES_PARAMETER_TYPES)
7305
      self.be_new = be_new # the new actual values
7306
      self.be_inst = i_bedict # the new dict (without defaults)
7307
    else:
7308
      self.be_new = self.be_inst = {}
7309

    
7310
    self.warn = []
7311

    
7312
    if constants.BE_MEMORY in self.op.beparams and not self.force:
7313
      mem_check_list = [pnode]
7314
      if be_new[constants.BE_AUTO_BALANCE]:
7315
        # either we changed auto_balance to yes or it was from before
7316
        mem_check_list.extend(instance.secondary_nodes)
7317
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
7318
                                                  instance.hypervisor)
7319
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
7320
                                         instance.hypervisor)
7321
      pninfo = nodeinfo[pnode]
7322
      msg = pninfo.fail_msg
7323
      if msg:
7324
        # Assume the primary node is unreachable and go ahead
7325
        self.warn.append("Can't get info from primary node %s: %s" %
7326
                         (pnode,  msg))
7327
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
7328
        self.warn.append("Node data from primary node %s doesn't contain"
7329
                         " free memory information" % pnode)
7330
      elif instance_info.fail_msg:
7331
        self.warn.append("Can't get instance runtime information: %s" %
7332
                        instance_info.fail_msg)
7333
      else:
7334
        if instance_info.payload:
7335
          current_mem = int(instance_info.payload['memory'])
7336
        else:
7337
          # Assume instance not running
7338
          # (there is a slight race condition here, but it's not very probable,
7339
          # and we have no other way to check)
7340
          current_mem = 0
7341
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
7342
                    pninfo.payload['memory_free'])
7343
        if miss_mem > 0:
7344
          raise errors.OpPrereqError("This change will prevent the instance"
7345
                                     " from starting, due to %d MB of memory"
7346
                                     " missing on its primary node" % miss_mem)
7347

    
7348
      if be_new[constants.BE_AUTO_BALANCE]:
7349
        for node, nres in nodeinfo.items():
7350
          if node not in instance.secondary_nodes:
7351
            continue
7352
          msg = nres.fail_msg
7353
          if msg:
7354
            self.warn.append("Can't get info from secondary node %s: %s" %
7355
                             (node, msg))
7356
          elif not isinstance(nres.payload.get('memory_free', None), int):
7357
            self.warn.append("Secondary node %s didn't return free"
7358
                             " memory information" % node)
7359
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
7360
            self.warn.append("Not enough memory to failover instance to"
7361
                             " secondary node %s" % node)
7362

    
7363
    # NIC processing
7364
    self.nic_pnew = {}
7365
    self.nic_pinst = {}
7366
    for nic_op, nic_dict in self.op.nics:
7367
      if nic_op == constants.DDM_REMOVE:
7368
        if not instance.nics:
7369
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
7370
        continue
7371
      if nic_op != constants.DDM_ADD:
7372
        # an existing nic
7373
        if nic_op < 0 or nic_op >= len(instance.nics):
7374
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
7375
                                     " are 0 to %d" %
7376
                                     (nic_op, len(instance.nics)))
7377
        old_nic_params = instance.nics[nic_op].nicparams
7378
        old_nic_ip = instance.nics[nic_op].ip
7379
      else:
7380
        old_nic_params = {}
7381
        old_nic_ip = None
7382

    
7383
      update_params_dict = dict([(key, nic_dict[key])
7384
                                 for key in constants.NICS_PARAMETERS
7385
                                 if key in nic_dict])
7386

    
7387
      if 'bridge' in nic_dict:
7388
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
7389

    
7390
      new_nic_params, new_filled_nic_params = \
7391
          self._GetUpdatedParams(old_nic_params, update_params_dict,
7392
                                 cluster.nicparams[constants.PP_DEFAULT],
7393
                                 constants.NICS_PARAMETER_TYPES)
7394
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
7395
      self.nic_pinst[nic_op] = new_nic_params
7396
      self.nic_pnew[nic_op] = new_filled_nic_params
7397
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
7398

    
7399
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
7400
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
7401
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
7402
        if msg:
7403
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
7404
          if self.force:
7405
            self.warn.append(msg)
7406
          else:
7407
            raise errors.OpPrereqError(msg)
7408
      if new_nic_mode == constants.NIC_MODE_ROUTED:
7409
        if 'ip' in nic_dict:
7410
          nic_ip = nic_dict['ip']
7411
        else:
7412
          nic_ip = old_nic_ip
7413
        if nic_ip is None:
7414
          raise errors.OpPrereqError('Cannot set the nic ip to None'
7415
                                     ' on a routed nic')
7416
      if 'mac' in nic_dict:
7417
        nic_mac = nic_dict['mac']
7418
        if nic_mac is None:
7419
          raise errors.OpPrereqError('Cannot set the nic mac to None')
7420
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7421
          # otherwise generate the mac
7422
          nic_dict['mac'] = self.cfg.GenerateMAC()
7423
        else:
7424
          # or validate/reserve the current one
7425
          if self.cfg.IsMacInUse(nic_mac):
7426
            raise errors.OpPrereqError("MAC address %s already in use"
7427
                                       " in cluster" % nic_mac)
7428

    
7429
    # DISK processing
7430
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
7431
      raise errors.OpPrereqError("Disk operations not supported for"
7432
                                 " diskless instances")
7433
    for disk_op, disk_dict in self.op.disks:
7434
      if disk_op == constants.DDM_REMOVE:
7435
        if len(instance.disks) == 1:
7436
          raise errors.OpPrereqError("Cannot remove the last disk of"
7437
                                     " an instance")
7438
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
7439
        ins_l = ins_l[pnode]
7440
        msg = ins_l.fail_msg
7441
        if msg:
7442
          raise errors.OpPrereqError("Can't contact node %s: %s" %
7443
                                     (pnode, msg))
7444
        if instance.name in ins_l.payload:
7445
          raise errors.OpPrereqError("Instance is running, can't remove"
7446
                                     " disks.")
7447

    
7448
      if (disk_op == constants.DDM_ADD and
7449
          len(instance.nics) >= constants.MAX_DISKS):
7450
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
7451
                                   " add more" % constants.MAX_DISKS)
7452
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
7453
        # an existing disk
7454
        if disk_op < 0 or disk_op >= len(instance.disks):
7455
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
7456
                                     " are 0 to %d" %
7457
                                     (disk_op, len(instance.disks)))
7458

    
7459
    return
7460

    
7461
  def Exec(self, feedback_fn):
7462
    """Modifies an instance.
7463

7464
    All parameters take effect only at the next restart of the instance.
7465

7466
    """
7467
    # Process here the warnings from CheckPrereq, as we don't have a
7468
    # feedback_fn there.
7469
    for warn in self.warn:
7470
      feedback_fn("WARNING: %s" % warn)
7471

    
7472
    result = []
7473
    instance = self.instance
7474
    cluster = self.cluster
7475
    # disk changes
7476
    for disk_op, disk_dict in self.op.disks:
7477
      if disk_op == constants.DDM_REMOVE:
7478
        # remove the last disk
7479
        device = instance.disks.pop()
7480
        device_idx = len(instance.disks)
7481
        for node, disk in device.ComputeNodeTree(instance.primary_node):
7482
          self.cfg.SetDiskID(disk, node)
7483
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
7484
          if msg:
7485
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
7486
                            " continuing anyway", device_idx, node, msg)
7487
        result.append(("disk/%d" % device_idx, "remove"))
7488
      elif disk_op == constants.DDM_ADD:
7489
        # add a new disk
7490
        if instance.disk_template == constants.DT_FILE:
7491
          file_driver, file_path = instance.disks[0].logical_id
7492
          file_path = os.path.dirname(file_path)
7493
        else:
7494
          file_driver = file_path = None
7495
        disk_idx_base = len(instance.disks)
7496
        new_disk = _GenerateDiskTemplate(self,
7497
                                         instance.disk_template,
7498
                                         instance.name, instance.primary_node,
7499
                                         instance.secondary_nodes,
7500
                                         [disk_dict],
7501
                                         file_path,
7502
                                         file_driver,
7503
                                         disk_idx_base)[0]
7504
        instance.disks.append(new_disk)
7505
        info = _GetInstanceInfoText(instance)
7506

    
7507
        logging.info("Creating volume %s for instance %s",
7508
                     new_disk.iv_name, instance.name)
7509
        # Note: this needs to be kept in sync with _CreateDisks
7510
        #HARDCODE
7511
        for node in instance.all_nodes:
7512
          f_create = node == instance.primary_node
7513
          try:
7514
            _CreateBlockDev(self, node, instance, new_disk,
7515
                            f_create, info, f_create)
7516
          except errors.OpExecError, err:
7517
            self.LogWarning("Failed to create volume %s (%s) on"
7518
                            " node %s: %s",
7519
                            new_disk.iv_name, new_disk, node, err)
7520
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
7521
                       (new_disk.size, new_disk.mode)))
7522
      else:
7523
        # change a given disk
7524
        instance.disks[disk_op].mode = disk_dict['mode']
7525
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
7526
    # NIC changes
7527
    for nic_op, nic_dict in self.op.nics:
7528
      if nic_op == constants.DDM_REMOVE:
7529
        # remove the last nic
7530
        del instance.nics[-1]
7531
        result.append(("nic.%d" % len(instance.nics), "remove"))
7532
      elif nic_op == constants.DDM_ADD:
7533
        # mac and bridge should be set, by now
7534
        mac = nic_dict['mac']
7535
        ip = nic_dict.get('ip', None)
7536
        nicparams = self.nic_pinst[constants.DDM_ADD]
7537
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
7538
        instance.nics.append(new_nic)
7539
        result.append(("nic.%d" % (len(instance.nics) - 1),
7540
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
7541
                       (new_nic.mac, new_nic.ip,
7542
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
7543
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
7544
                       )))
7545
      else:
7546
        for key in 'mac', 'ip':
7547
          if key in nic_dict:
7548
            setattr(instance.nics[nic_op], key, nic_dict[key])
7549
        if nic_op in self.nic_pnew:
7550
          instance.nics[nic_op].nicparams = self.nic_pnew[nic_op]
7551
        for key, val in nic_dict.iteritems():
7552
          result.append(("nic.%s/%d" % (key, nic_op), val))
7553

    
7554
    # hvparams changes
7555
    if self.op.hvparams:
7556
      instance.hvparams = self.hv_inst
7557
      for key, val in self.op.hvparams.iteritems():
7558
        result.append(("hv/%s" % key, val))
7559

    
7560
    # beparams changes
7561
    if self.op.beparams:
7562
      instance.beparams = self.be_inst
7563
      for key, val in self.op.beparams.iteritems():
7564
        result.append(("be/%s" % key, val))
7565

    
7566
    self.cfg.Update(instance)
7567

    
7568
    return result
7569

    
7570

    
7571
class LUQueryExports(NoHooksLU):
7572
  """Query the exports list
7573

7574
  """
7575
  _OP_REQP = ['nodes']
7576
  REQ_BGL = False
7577

    
7578
  def ExpandNames(self):
7579
    self.needed_locks = {}
7580
    self.share_locks[locking.LEVEL_NODE] = 1
7581
    if not self.op.nodes:
7582
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7583
    else:
7584
      self.needed_locks[locking.LEVEL_NODE] = \
7585
        _GetWantedNodes(self, self.op.nodes)
7586

    
7587
  def CheckPrereq(self):
7588
    """Check prerequisites.
7589

7590
    """
7591
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
7592

    
7593
  def Exec(self, feedback_fn):
7594
    """Compute the list of all the exported system images.
7595

7596
    @rtype: dict
7597
    @return: a dictionary with the structure node->(export-list)
7598
        where export-list is a list of the instances exported on
7599
        that node.
7600

7601
    """
7602
    rpcresult = self.rpc.call_export_list(self.nodes)
7603
    result = {}
7604
    for node in rpcresult:
7605
      if rpcresult[node].fail_msg:
7606
        result[node] = False
7607
      else:
7608
        result[node] = rpcresult[node].payload
7609

    
7610
    return result
7611

    
7612

    
7613
class LUExportInstance(LogicalUnit):
7614
  """Export an instance to an image in the cluster.
7615

7616
  """
7617
  HPATH = "instance-export"
7618
  HTYPE = constants.HTYPE_INSTANCE
7619
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
7620
  REQ_BGL = False
7621

    
7622
  def ExpandNames(self):
7623
    self._ExpandAndLockInstance()
7624
    # FIXME: lock only instance primary and destination node
7625
    #
7626
    # Sad but true, for now we have do lock all nodes, as we don't know where
7627
    # the previous export might be, and and in this LU we search for it and
7628
    # remove it from its current node. In the future we could fix this by:
7629
    #  - making a tasklet to search (share-lock all), then create the new one,
7630
    #    then one to remove, after
7631
    #  - removing the removal operation altogether
7632
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7633

    
7634
  def DeclareLocks(self, level):
7635
    """Last minute lock declaration."""
7636
    # All nodes are locked anyway, so nothing to do here.
7637

    
7638
  def BuildHooksEnv(self):
7639
    """Build hooks env.
7640

7641
    This will run on the master, primary node and target node.
7642

7643
    """
7644
    env = {
7645
      "EXPORT_NODE": self.op.target_node,
7646
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
7647
      }
7648
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7649
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
7650
          self.op.target_node]
7651
    return env, nl, nl
7652

    
7653
  def CheckPrereq(self):
7654
    """Check prerequisites.
7655

7656
    This checks that the instance and node names are valid.
7657

7658
    """
7659
    instance_name = self.op.instance_name
7660
    self.instance = self.cfg.GetInstanceInfo(instance_name)
7661
    assert self.instance is not None, \
7662
          "Cannot retrieve locked instance %s" % self.op.instance_name
7663
    _CheckNodeOnline(self, self.instance.primary_node)
7664

    
7665
    self.dst_node = self.cfg.GetNodeInfo(
7666
      self.cfg.ExpandNodeName(self.op.target_node))
7667

    
7668
    if self.dst_node is None:
7669
      # This is wrong node name, not a non-locked node
7670
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
7671
    _CheckNodeOnline(self, self.dst_node.name)
7672
    _CheckNodeNotDrained(self, self.dst_node.name)
7673

    
7674
    # instance disk type verification
7675
    for disk in self.instance.disks:
7676
      if disk.dev_type == constants.LD_FILE:
7677
        raise errors.OpPrereqError("Export not supported for instances with"
7678
                                   " file-based disks")
7679

    
7680
  def Exec(self, feedback_fn):
7681
    """Export an instance to an image in the cluster.
7682

7683
    """
7684
    instance = self.instance
7685
    dst_node = self.dst_node
7686
    src_node = instance.primary_node
7687

    
7688
    if self.op.shutdown:
7689
      # shutdown the instance, but not the disks
7690
      feedback_fn("Shutting down instance %s" % instance.name)
7691
      result = self.rpc.call_instance_shutdown(src_node, instance)
7692
      result.Raise("Could not shutdown instance %s on"
7693
                   " node %s" % (instance.name, src_node))
7694

    
7695
    vgname = self.cfg.GetVGName()
7696

    
7697
    snap_disks = []
7698

    
7699
    # set the disks ID correctly since call_instance_start needs the
7700
    # correct drbd minor to create the symlinks
7701
    for disk in instance.disks:
7702
      self.cfg.SetDiskID(disk, src_node)
7703

    
7704
    # per-disk results
7705
    dresults = []
7706
    try:
7707
      for idx, disk in enumerate(instance.disks):
7708
        feedback_fn("Creating a snapshot of disk/%s on node %s" %
7709
                    (idx, src_node))
7710

    
7711
        # result.payload will be a snapshot of an lvm leaf of the one we passed
7712
        result = self.rpc.call_blockdev_snapshot(src_node, disk)
7713
        msg = result.fail_msg
7714
        if msg:
7715
          self.LogWarning("Could not snapshot disk/%s on node %s: %s",
7716
                          idx, src_node, msg)
7717
          snap_disks.append(False)
7718
        else:
7719
          disk_id = (vgname, result.payload)
7720
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
7721
                                 logical_id=disk_id, physical_id=disk_id,
7722
                                 iv_name=disk.iv_name)
7723
          snap_disks.append(new_dev)
7724

    
7725
    finally:
7726
      if self.op.shutdown and instance.admin_up:
7727
        feedback_fn("Starting instance %s" % instance.name)
7728
        result = self.rpc.call_instance_start(src_node, instance, None, None)
7729
        msg = result.fail_msg
7730
        if msg:
7731
          _ShutdownInstanceDisks(self, instance)
7732
          raise errors.OpExecError("Could not start instance: %s" % msg)
7733

    
7734
    # TODO: check for size
7735

    
7736
    cluster_name = self.cfg.GetClusterName()
7737
    for idx, dev in enumerate(snap_disks):
7738
      feedback_fn("Exporting snapshot %s from %s to %s" %
7739
                  (idx, src_node, dst_node.name))
7740
      if dev:
7741
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
7742
                                               instance, cluster_name, idx)
7743
        msg = result.fail_msg
7744
        if msg:
7745
          self.LogWarning("Could not export disk/%s from node %s to"
7746
                          " node %s: %s", idx, src_node, dst_node.name, msg)
7747
          dresults.append(False)
7748
        else:
7749
          dresults.append(True)
7750
        msg = self.rpc.call_blockdev_remove(src_node, dev).fail_msg
7751
        if msg:
7752
          self.LogWarning("Could not remove snapshot for disk/%d from node"
7753
                          " %s: %s", idx, src_node, msg)
7754
      else:
7755
        dresults.append(False)
7756

    
7757
    feedback_fn("Finalizing export on %s" % dst_node.name)
7758
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
7759
    fin_resu = True
7760
    msg = result.fail_msg
7761
    if msg:
7762
      self.LogWarning("Could not finalize export for instance %s"
7763
                      " on node %s: %s", instance.name, dst_node.name, msg)
7764
      fin_resu = False
7765

    
7766
    nodelist = self.cfg.GetNodeList()
7767
    nodelist.remove(dst_node.name)
7768

    
7769
    # on one-node clusters nodelist will be empty after the removal
7770
    # if we proceed the backup would be removed because OpQueryExports
7771
    # substitutes an empty list with the full cluster node list.
7772
    iname = instance.name
7773
    if nodelist:
7774
      feedback_fn("Removing old exports for instance %s" % iname)
7775
      exportlist = self.rpc.call_export_list(nodelist)
7776
      for node in exportlist:
7777
        if exportlist[node].fail_msg:
7778
          continue
7779
        if iname in exportlist[node].payload:
7780
          msg = self.rpc.call_export_remove(node, iname).fail_msg
7781
          if msg:
7782
            self.LogWarning("Could not remove older export for instance %s"
7783
                            " on node %s: %s", iname, node, msg)
7784
    return fin_resu, dresults
7785

    
7786

    
7787
class LURemoveExport(NoHooksLU):
7788
  """Remove exports related to the named instance.
7789

7790
  """
7791
  _OP_REQP = ["instance_name"]
7792
  REQ_BGL = False
7793

    
7794
  def ExpandNames(self):
7795
    self.needed_locks = {}
7796
    # We need all nodes to be locked in order for RemoveExport to work, but we
7797
    # don't need to lock the instance itself, as nothing will happen to it (and
7798
    # we can remove exports also for a removed instance)
7799
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7800

    
7801
  def CheckPrereq(self):
7802
    """Check prerequisites.
7803
    """
7804
    pass
7805

    
7806
  def Exec(self, feedback_fn):
7807
    """Remove any export.
7808

7809
    """
7810
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
7811
    # If the instance was not found we'll try with the name that was passed in.
7812
    # This will only work if it was an FQDN, though.
7813
    fqdn_warn = False
7814
    if not instance_name:
7815
      fqdn_warn = True
7816
      instance_name = self.op.instance_name
7817

    
7818
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7819
    exportlist = self.rpc.call_export_list(locked_nodes)
7820
    found = False
7821
    for node in exportlist:
7822
      msg = exportlist[node].fail_msg
7823
      if msg:
7824
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
7825
        continue
7826
      if instance_name in exportlist[node].payload:
7827
        found = True
7828
        result = self.rpc.call_export_remove(node, instance_name)
7829
        msg = result.fail_msg
7830
        if msg:
7831
          logging.error("Could not remove export for instance %s"
7832
                        " on node %s: %s", instance_name, node, msg)
7833

    
7834
    if fqdn_warn and not found:
7835
      feedback_fn("Export not found. If trying to remove an export belonging"
7836
                  " to a deleted instance please use its Fully Qualified"
7837
                  " Domain Name.")
7838

    
7839

    
7840
class TagsLU(NoHooksLU):
7841
  """Generic tags LU.
7842

7843
  This is an abstract class which is the parent of all the other tags LUs.
7844

7845
  """
7846

    
7847
  def ExpandNames(self):
7848
    self.needed_locks = {}
7849
    if self.op.kind == constants.TAG_NODE:
7850
      name = self.cfg.ExpandNodeName(self.op.name)
7851
      if name is None:
7852
        raise errors.OpPrereqError("Invalid node name (%s)" %
7853
                                   (self.op.name,))
7854
      self.op.name = name
7855
      self.needed_locks[locking.LEVEL_NODE] = name
7856
    elif self.op.kind == constants.TAG_INSTANCE:
7857
      name = self.cfg.ExpandInstanceName(self.op.name)
7858
      if name is None:
7859
        raise errors.OpPrereqError("Invalid instance name (%s)" %
7860
                                   (self.op.name,))
7861
      self.op.name = name
7862
      self.needed_locks[locking.LEVEL_INSTANCE] = name
7863

    
7864
  def CheckPrereq(self):
7865
    """Check prerequisites.
7866

7867
    """
7868
    if self.op.kind == constants.TAG_CLUSTER:
7869
      self.target = self.cfg.GetClusterInfo()
7870
    elif self.op.kind == constants.TAG_NODE:
7871
      self.target = self.cfg.GetNodeInfo(self.op.name)
7872
    elif self.op.kind == constants.TAG_INSTANCE:
7873
      self.target = self.cfg.GetInstanceInfo(self.op.name)
7874
    else:
7875
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
7876
                                 str(self.op.kind))
7877

    
7878

    
7879
class LUGetTags(TagsLU):
7880
  """Returns the tags of a given object.
7881

7882
  """
7883
  _OP_REQP = ["kind", "name"]
7884
  REQ_BGL = False
7885

    
7886
  def Exec(self, feedback_fn):
7887
    """Returns the tag list.
7888

7889
    """
7890
    return list(self.target.GetTags())
7891

    
7892

    
7893
class LUSearchTags(NoHooksLU):
7894
  """Searches the tags for a given pattern.
7895

7896
  """
7897
  _OP_REQP = ["pattern"]
7898
  REQ_BGL = False
7899

    
7900
  def ExpandNames(self):
7901
    self.needed_locks = {}
7902

    
7903
  def CheckPrereq(self):
7904
    """Check prerequisites.
7905

7906
    This checks the pattern passed for validity by compiling it.
7907

7908
    """
7909
    try:
7910
      self.re = re.compile(self.op.pattern)
7911
    except re.error, err:
7912
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
7913
                                 (self.op.pattern, err))
7914

    
7915
  def Exec(self, feedback_fn):
7916
    """Returns the tag list.
7917

7918
    """
7919
    cfg = self.cfg
7920
    tgts = [("/cluster", cfg.GetClusterInfo())]
7921
    ilist = cfg.GetAllInstancesInfo().values()
7922
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
7923
    nlist = cfg.GetAllNodesInfo().values()
7924
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
7925
    results = []
7926
    for path, target in tgts:
7927
      for tag in target.GetTags():
7928
        if self.re.search(tag):
7929
          results.append((path, tag))
7930
    return results
7931

    
7932

    
7933
class LUAddTags(TagsLU):
7934
  """Sets a tag on a given object.
7935

7936
  """
7937
  _OP_REQP = ["kind", "name", "tags"]
7938
  REQ_BGL = False
7939

    
7940
  def CheckPrereq(self):
7941
    """Check prerequisites.
7942

7943
    This checks the type and length of the tag name and value.
7944

7945
    """
7946
    TagsLU.CheckPrereq(self)
7947
    for tag in self.op.tags:
7948
      objects.TaggableObject.ValidateTag(tag)
7949

    
7950
  def Exec(self, feedback_fn):
7951
    """Sets the tag.
7952

7953
    """
7954
    try:
7955
      for tag in self.op.tags:
7956
        self.target.AddTag(tag)
7957
    except errors.TagError, err:
7958
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
7959
    try:
7960
      self.cfg.Update(self.target)
7961
    except errors.ConfigurationError:
7962
      raise errors.OpRetryError("There has been a modification to the"
7963
                                " config file and the operation has been"
7964
                                " aborted. Please retry.")
7965

    
7966

    
7967
class LUDelTags(TagsLU):
7968
  """Delete a list of tags from a given object.
7969

7970
  """
7971
  _OP_REQP = ["kind", "name", "tags"]
7972
  REQ_BGL = False
7973

    
7974
  def CheckPrereq(self):
7975
    """Check prerequisites.
7976

7977
    This checks that we have the given tag.
7978

7979
    """
7980
    TagsLU.CheckPrereq(self)
7981
    for tag in self.op.tags:
7982
      objects.TaggableObject.ValidateTag(tag)
7983
    del_tags = frozenset(self.op.tags)
7984
    cur_tags = self.target.GetTags()
7985
    if not del_tags <= cur_tags:
7986
      diff_tags = del_tags - cur_tags
7987
      diff_names = ["'%s'" % tag for tag in diff_tags]
7988
      diff_names.sort()
7989
      raise errors.OpPrereqError("Tag(s) %s not found" %
7990
                                 (",".join(diff_names)))
7991

    
7992
  def Exec(self, feedback_fn):
7993
    """Remove the tag from the object.
7994

7995
    """
7996
    for tag in self.op.tags:
7997
      self.target.RemoveTag(tag)
7998
    try:
7999
      self.cfg.Update(self.target)
8000
    except errors.ConfigurationError:
8001
      raise errors.OpRetryError("There has been a modification to the"
8002
                                " config file and the operation has been"
8003
                                " aborted. Please retry.")
8004

    
8005

    
8006
class LUTestDelay(NoHooksLU):
8007
  """Sleep for a specified amount of time.
8008

8009
  This LU sleeps on the master and/or nodes for a specified amount of
8010
  time.
8011

8012
  """
8013
  _OP_REQP = ["duration", "on_master", "on_nodes"]
8014
  REQ_BGL = False
8015

    
8016
  def ExpandNames(self):
8017
    """Expand names and set required locks.
8018

8019
    This expands the node list, if any.
8020

8021
    """
8022
    self.needed_locks = {}
8023
    if self.op.on_nodes:
8024
      # _GetWantedNodes can be used here, but is not always appropriate to use
8025
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
8026
      # more information.
8027
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
8028
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
8029

    
8030
  def CheckPrereq(self):
8031
    """Check prerequisites.
8032

8033
    """
8034

    
8035
  def Exec(self, feedback_fn):
8036
    """Do the actual sleep.
8037

8038
    """
8039
    if self.op.on_master:
8040
      if not utils.TestDelay(self.op.duration):
8041
        raise errors.OpExecError("Error during master delay test")
8042
    if self.op.on_nodes:
8043
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
8044
      for node, node_result in result.items():
8045
        node_result.Raise("Failure during rpc call to node %s" % node)
8046

    
8047

    
8048
class IAllocator(object):
8049
  """IAllocator framework.
8050

8051
  An IAllocator instance has three sets of attributes:
8052
    - cfg that is needed to query the cluster
8053
    - input data (all members of the _KEYS class attribute are required)
8054
    - four buffer attributes (in|out_data|text), that represent the
8055
      input (to the external script) in text and data structure format,
8056
      and the output from it, again in two formats
8057
    - the result variables from the script (success, info, nodes) for
8058
      easy usage
8059

8060
  """
8061
  _ALLO_KEYS = [
8062
    "mem_size", "disks", "disk_template",
8063
    "os", "tags", "nics", "vcpus", "hypervisor",
8064
    ]
8065
  _RELO_KEYS = [
8066
    "relocate_from",
8067
    ]
8068

    
8069
  def __init__(self, cfg, rpc, mode, name, **kwargs):
8070
    self.cfg = cfg
8071
    self.rpc = rpc
8072
    # init buffer variables
8073
    self.in_text = self.out_text = self.in_data = self.out_data = None
8074
    # init all input fields so that pylint is happy
8075
    self.mode = mode
8076
    self.name = name
8077
    self.mem_size = self.disks = self.disk_template = None
8078
    self.os = self.tags = self.nics = self.vcpus = None
8079
    self.hypervisor = None
8080
    self.relocate_from = None
8081
    # computed fields
8082
    self.required_nodes = None
8083
    # init result fields
8084
    self.success = self.info = self.nodes = None
8085
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8086
      keyset = self._ALLO_KEYS
8087
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8088
      keyset = self._RELO_KEYS
8089
    else:
8090
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
8091
                                   " IAllocator" % self.mode)
8092
    for key in kwargs:
8093
      if key not in keyset:
8094
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
8095
                                     " IAllocator" % key)
8096
      setattr(self, key, kwargs[key])
8097
    for key in keyset:
8098
      if key not in kwargs:
8099
        raise errors.ProgrammerError("Missing input parameter '%s' to"
8100
                                     " IAllocator" % key)
8101
    self._BuildInputData()
8102

    
8103
  def _ComputeClusterData(self):
8104
    """Compute the generic allocator input data.
8105

8106
    This is the data that is independent of the actual operation.
8107

8108
    """
8109
    cfg = self.cfg
8110
    cluster_info = cfg.GetClusterInfo()
8111
    # cluster data
8112
    data = {
8113
      "version": constants.IALLOCATOR_VERSION,
8114
      "cluster_name": cfg.GetClusterName(),
8115
      "cluster_tags": list(cluster_info.GetTags()),
8116
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
8117
      # we don't have job IDs
8118
      }
8119
    iinfo = cfg.GetAllInstancesInfo().values()
8120
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
8121

    
8122
    # node data
8123
    node_results = {}
8124
    node_list = cfg.GetNodeList()
8125

    
8126
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8127
      hypervisor_name = self.hypervisor
8128
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8129
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
8130

    
8131
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
8132
                                        hypervisor_name)
8133
    node_iinfo = \
8134
      self.rpc.call_all_instances_info(node_list,
8135
                                       cluster_info.enabled_hypervisors)
8136
    for nname, nresult in node_data.items():
8137
      # first fill in static (config-based) values
8138
      ninfo = cfg.GetNodeInfo(nname)
8139
      pnr = {
8140
        "tags": list(ninfo.GetTags()),
8141
        "primary_ip": ninfo.primary_ip,
8142
        "secondary_ip": ninfo.secondary_ip,
8143
        "offline": ninfo.offline,
8144
        "drained": ninfo.drained,
8145
        "master_candidate": ninfo.master_candidate,
8146
        }
8147

    
8148
      if not (ninfo.offline or ninfo.drained):
8149
        nresult.Raise("Can't get data for node %s" % nname)
8150
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
8151
                                nname)
8152
        remote_info = nresult.payload
8153

    
8154
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
8155
                     'vg_size', 'vg_free', 'cpu_total']:
8156
          if attr not in remote_info:
8157
            raise errors.OpExecError("Node '%s' didn't return attribute"
8158
                                     " '%s'" % (nname, attr))
8159
          if not isinstance(remote_info[attr], int):
8160
            raise errors.OpExecError("Node '%s' returned invalid value"
8161
                                     " for '%s': %s" %
8162
                                     (nname, attr, remote_info[attr]))
8163
        # compute memory used by primary instances
8164
        i_p_mem = i_p_up_mem = 0
8165
        for iinfo, beinfo in i_list:
8166
          if iinfo.primary_node == nname:
8167
            i_p_mem += beinfo[constants.BE_MEMORY]
8168
            if iinfo.name not in node_iinfo[nname].payload:
8169
              i_used_mem = 0
8170
            else:
8171
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
8172
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
8173
            remote_info['memory_free'] -= max(0, i_mem_diff)
8174

    
8175
            if iinfo.admin_up:
8176
              i_p_up_mem += beinfo[constants.BE_MEMORY]
8177

    
8178
        # compute memory used by instances
8179
        pnr_dyn = {
8180
          "total_memory": remote_info['memory_total'],
8181
          "reserved_memory": remote_info['memory_dom0'],
8182
          "free_memory": remote_info['memory_free'],
8183
          "total_disk": remote_info['vg_size'],
8184
          "free_disk": remote_info['vg_free'],
8185
          "total_cpus": remote_info['cpu_total'],
8186
          "i_pri_memory": i_p_mem,
8187
          "i_pri_up_memory": i_p_up_mem,
8188
          }
8189
        pnr.update(pnr_dyn)
8190

    
8191
      node_results[nname] = pnr
8192
    data["nodes"] = node_results
8193

    
8194
    # instance data
8195
    instance_data = {}
8196
    for iinfo, beinfo in i_list:
8197
      nic_data = []
8198
      for nic in iinfo.nics:
8199
        filled_params = objects.FillDict(
8200
            cluster_info.nicparams[constants.PP_DEFAULT],
8201
            nic.nicparams)
8202
        nic_dict = {"mac": nic.mac,
8203
                    "ip": nic.ip,
8204
                    "mode": filled_params[constants.NIC_MODE],
8205
                    "link": filled_params[constants.NIC_LINK],
8206
                   }
8207
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
8208
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
8209
        nic_data.append(nic_dict)
8210
      pir = {
8211
        "tags": list(iinfo.GetTags()),
8212
        "admin_up": iinfo.admin_up,
8213
        "vcpus": beinfo[constants.BE_VCPUS],
8214
        "memory": beinfo[constants.BE_MEMORY],
8215
        "os": iinfo.os,
8216
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
8217
        "nics": nic_data,
8218
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
8219
        "disk_template": iinfo.disk_template,
8220
        "hypervisor": iinfo.hypervisor,
8221
        }
8222
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
8223
                                                 pir["disks"])
8224
      instance_data[iinfo.name] = pir
8225

    
8226
    data["instances"] = instance_data
8227

    
8228
    self.in_data = data
8229

    
8230
  def _AddNewInstance(self):
8231
    """Add new instance data to allocator structure.
8232

8233
    This in combination with _AllocatorGetClusterData will create the
8234
    correct structure needed as input for the allocator.
8235

8236
    The checks for the completeness of the opcode must have already been
8237
    done.
8238

8239
    """
8240
    data = self.in_data
8241

    
8242
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
8243

    
8244
    if self.disk_template in constants.DTS_NET_MIRROR:
8245
      self.required_nodes = 2
8246
    else:
8247
      self.required_nodes = 1
8248
    request = {
8249
      "type": "allocate",
8250
      "name": self.name,
8251
      "disk_template": self.disk_template,
8252
      "tags": self.tags,
8253
      "os": self.os,
8254
      "vcpus": self.vcpus,
8255
      "memory": self.mem_size,
8256
      "disks": self.disks,
8257
      "disk_space_total": disk_space,
8258
      "nics": self.nics,
8259
      "required_nodes": self.required_nodes,
8260
      }
8261
    data["request"] = request
8262

    
8263
  def _AddRelocateInstance(self):
8264
    """Add relocate instance data to allocator structure.
8265

8266
    This in combination with _IAllocatorGetClusterData will create the
8267
    correct structure needed as input for the allocator.
8268

8269
    The checks for the completeness of the opcode must have already been
8270
    done.
8271

8272
    """
8273
    instance = self.cfg.GetInstanceInfo(self.name)
8274
    if instance is None:
8275
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
8276
                                   " IAllocator" % self.name)
8277

    
8278
    if instance.disk_template not in constants.DTS_NET_MIRROR:
8279
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
8280

    
8281
    if len(instance.secondary_nodes) != 1:
8282
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
8283

    
8284
    self.required_nodes = 1
8285
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
8286
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
8287

    
8288
    request = {
8289
      "type": "relocate",
8290
      "name": self.name,
8291
      "disk_space_total": disk_space,
8292
      "required_nodes": self.required_nodes,
8293
      "relocate_from": self.relocate_from,
8294
      }
8295
    self.in_data["request"] = request
8296

    
8297
  def _BuildInputData(self):
8298
    """Build input data structures.
8299

8300
    """
8301
    self._ComputeClusterData()
8302

    
8303
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8304
      self._AddNewInstance()
8305
    else:
8306
      self._AddRelocateInstance()
8307

    
8308
    self.in_text = serializer.Dump(self.in_data)
8309

    
8310
  def Run(self, name, validate=True, call_fn=None):
8311
    """Run an instance allocator and return the results.
8312

8313
    """
8314
    if call_fn is None:
8315
      call_fn = self.rpc.call_iallocator_runner
8316

    
8317
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
8318
    result.Raise("Failure while running the iallocator script")
8319

    
8320
    self.out_text = result.payload
8321
    if validate:
8322
      self._ValidateResult()
8323

    
8324
  def _ValidateResult(self):
8325
    """Process the allocator results.
8326

8327
    This will process and if successful save the result in
8328
    self.out_data and the other parameters.
8329

8330
    """
8331
    try:
8332
      rdict = serializer.Load(self.out_text)
8333
    except Exception, err:
8334
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
8335

    
8336
    if not isinstance(rdict, dict):
8337
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
8338

    
8339
    for key in "success", "info", "nodes":
8340
      if key not in rdict:
8341
        raise errors.OpExecError("Can't parse iallocator results:"
8342
                                 " missing key '%s'" % key)
8343
      setattr(self, key, rdict[key])
8344

    
8345
    if not isinstance(rdict["nodes"], list):
8346
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
8347
                               " is not a list")
8348
    self.out_data = rdict
8349

    
8350

    
8351
class LUTestAllocator(NoHooksLU):
8352
  """Run allocator tests.
8353

8354
  This LU runs the allocator tests
8355

8356
  """
8357
  _OP_REQP = ["direction", "mode", "name"]
8358

    
8359
  def CheckPrereq(self):
8360
    """Check prerequisites.
8361

8362
    This checks the opcode parameters depending on the director and mode test.
8363

8364
    """
8365
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8366
      for attr in ["name", "mem_size", "disks", "disk_template",
8367
                   "os", "tags", "nics", "vcpus"]:
8368
        if not hasattr(self.op, attr):
8369
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
8370
                                     attr)
8371
      iname = self.cfg.ExpandInstanceName(self.op.name)
8372
      if iname is not None:
8373
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
8374
                                   iname)
8375
      if not isinstance(self.op.nics, list):
8376
        raise errors.OpPrereqError("Invalid parameter 'nics'")
8377
      for row in self.op.nics:
8378
        if (not isinstance(row, dict) or
8379
            "mac" not in row or
8380
            "ip" not in row or
8381
            "bridge" not in row):
8382
          raise errors.OpPrereqError("Invalid contents of the"
8383
                                     " 'nics' parameter")
8384
      if not isinstance(self.op.disks, list):
8385
        raise errors.OpPrereqError("Invalid parameter 'disks'")
8386
      for row in self.op.disks:
8387
        if (not isinstance(row, dict) or
8388
            "size" not in row or
8389
            not isinstance(row["size"], int) or
8390
            "mode" not in row or
8391
            row["mode"] not in ['r', 'w']):
8392
          raise errors.OpPrereqError("Invalid contents of the"
8393
                                     " 'disks' parameter")
8394
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
8395
        self.op.hypervisor = self.cfg.GetHypervisorType()
8396
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
8397
      if not hasattr(self.op, "name"):
8398
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
8399
      fname = self.cfg.ExpandInstanceName(self.op.name)
8400
      if fname is None:
8401
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
8402
                                   self.op.name)
8403
      self.op.name = fname
8404
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
8405
    else:
8406
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
8407
                                 self.op.mode)
8408

    
8409
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
8410
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
8411
        raise errors.OpPrereqError("Missing allocator name")
8412
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
8413
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
8414
                                 self.op.direction)
8415

    
8416
  def Exec(self, feedback_fn):
8417
    """Run the allocator test.
8418

8419
    """
8420
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8421
      ial = IAllocator(self.cfg, self.rpc,
8422
                       mode=self.op.mode,
8423
                       name=self.op.name,
8424
                       mem_size=self.op.mem_size,
8425
                       disks=self.op.disks,
8426
                       disk_template=self.op.disk_template,
8427
                       os=self.op.os,
8428
                       tags=self.op.tags,
8429
                       nics=self.op.nics,
8430
                       vcpus=self.op.vcpus,
8431
                       hypervisor=self.op.hypervisor,
8432
                       )
8433
    else:
8434
      ial = IAllocator(self.cfg, self.rpc,
8435
                       mode=self.op.mode,
8436
                       name=self.op.name,
8437
                       relocate_from=list(self.relocate_from),
8438
                       )
8439

    
8440
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
8441
      result = ial.in_text
8442
    else:
8443
      ial.Run(self.op.allocator, validate=False)
8444
      result = ial.out_text
8445
    return result