Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ b5f5fae9

History | View | Annotate | Download (267.5 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):
674
  """Adjust the candidate pool after node operations.
675

676
  """
677
  mod_list = lu.cfg.MaintainCandidatePool()
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()
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 _CheckNicsBridgesExist(lu, target_nics, target_node,
690
                               profile=constants.PP_DEFAULT):
691
  """Check that the brigdes needed by a list of nics exist.
692

693
  """
694
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
695
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
696
                for nic in target_nics]
697
  brlist = [params[constants.NIC_LINK] for params in paramslist
698
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
699
  if brlist:
700
    result = lu.rpc.call_bridges_exist(target_node, brlist)
701
    result.Raise("Error checking bridges on destination node '%s'" %
702
                 target_node, prereq=True)
703

    
704

    
705
def _CheckInstanceBridgesExist(lu, instance, node=None):
706
  """Check that the brigdes needed by an instance exist.
707

708
  """
709
  if node is None:
710
    node = instance.primary_node
711
  _CheckNicsBridgesExist(lu, instance.nics, node)
712

    
713

    
714
def _GetNodePrimaryInstances(cfg, node_name):
715
  """Returns primary instances on a node.
716

717
  """
718
  instances = []
719

    
720
  for (_, inst) in cfg.GetAllInstancesInfo().iteritems():
721
    if node_name == inst.primary_node:
722
      instances.append(inst)
723

    
724
  return instances
725

    
726

    
727
def _GetNodeSecondaryInstances(cfg, node_name):
728
  """Returns secondary instances on a node.
729

730
  """
731
  instances = []
732

    
733
  for (_, inst) in cfg.GetAllInstancesInfo().iteritems():
734
    if node_name in inst.secondary_nodes:
735
      instances.append(inst)
736

    
737
  return instances
738

    
739

    
740
def _GetStorageTypeArgs(cfg, storage_type):
741
  """Returns the arguments for a storage type.
742

743
  """
744
  # Special case for file storage
745
  if storage_type == constants.ST_FILE:
746
    # storage.FileStorage wants a list of storage directories
747
    return [[cfg.GetFileStorageDir()]]
748

    
749
  return []
750

    
751

    
752
class LUPostInitCluster(LogicalUnit):
753
  """Logical unit for running hooks after cluster initialization.
754

755
  """
756
  HPATH = "cluster-init"
757
  HTYPE = constants.HTYPE_CLUSTER
758
  _OP_REQP = []
759

    
760
  def BuildHooksEnv(self):
761
    """Build hooks env.
762

763
    """
764
    env = {"OP_TARGET": self.cfg.GetClusterName()}
765
    mn = self.cfg.GetMasterNode()
766
    return env, [], [mn]
767

    
768
  def CheckPrereq(self):
769
    """No prerequisites to check.
770

771
    """
772
    return True
773

    
774
  def Exec(self, feedback_fn):
775
    """Nothing to do.
776

777
    """
778
    return True
779

    
780

    
781
class LUDestroyCluster(NoHooksLU):
782
  """Logical unit for destroying the cluster.
783

784
  """
785
  _OP_REQP = []
786

    
787
  def CheckPrereq(self):
788
    """Check prerequisites.
789

790
    This checks whether the cluster is empty.
791

792
    Any errors are signaled by raising errors.OpPrereqError.
793

794
    """
795
    master = self.cfg.GetMasterNode()
796

    
797
    nodelist = self.cfg.GetNodeList()
798
    if len(nodelist) != 1 or nodelist[0] != master:
799
      raise errors.OpPrereqError("There are still %d node(s) in"
800
                                 " this cluster." % (len(nodelist) - 1))
801
    instancelist = self.cfg.GetInstanceList()
802
    if instancelist:
803
      raise errors.OpPrereqError("There are still %d instance(s) in"
804
                                 " this cluster." % len(instancelist))
805

    
806
  def Exec(self, feedback_fn):
807
    """Destroys the cluster.
808

809
    """
810
    master = self.cfg.GetMasterNode()
811
    result = self.rpc.call_node_stop_master(master, False)
812
    result.Raise("Could not disable the master role")
813
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
814
    utils.CreateBackup(priv_key)
815
    utils.CreateBackup(pub_key)
816
    return master
817

    
818

    
819
class LUVerifyCluster(LogicalUnit):
820
  """Verifies the cluster status.
821

822
  """
823
  HPATH = "cluster-verify"
824
  HTYPE = constants.HTYPE_CLUSTER
825
  _OP_REQP = ["skip_checks"]
826
  REQ_BGL = False
827

    
828
  def ExpandNames(self):
829
    self.needed_locks = {
830
      locking.LEVEL_NODE: locking.ALL_SET,
831
      locking.LEVEL_INSTANCE: locking.ALL_SET,
832
    }
833
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
834

    
835
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
836
                  node_result, feedback_fn, master_files,
837
                  drbd_map, vg_name):
838
    """Run multiple tests against a node.
839

840
    Test list:
841

842
      - compares ganeti version
843
      - checks vg existence and size > 20G
844
      - checks config file checksum
845
      - checks ssh to other nodes
846

847
    @type nodeinfo: L{objects.Node}
848
    @param nodeinfo: the node to check
849
    @param file_list: required list of files
850
    @param local_cksum: dictionary of local files and their checksums
851
    @param node_result: the results from the node
852
    @param feedback_fn: function used to accumulate results
853
    @param master_files: list of files that only masters should have
854
    @param drbd_map: the useddrbd minors for this node, in
855
        form of minor: (instance, must_exist) which correspond to instances
856
        and their running status
857
    @param vg_name: Ganeti Volume Group (result of self.cfg.GetVGName())
858

859
    """
860
    node = nodeinfo.name
861

    
862
    # main result, node_result should be a non-empty dict
863
    if not node_result or not isinstance(node_result, dict):
864
      feedback_fn("  - ERROR: unable to verify node %s." % (node,))
865
      return True
866

    
867
    # compares ganeti version
868
    local_version = constants.PROTOCOL_VERSION
869
    remote_version = node_result.get('version', None)
870
    if not (remote_version and isinstance(remote_version, (list, tuple)) and
871
            len(remote_version) == 2):
872
      feedback_fn("  - ERROR: connection to %s failed" % (node))
873
      return True
874

    
875
    if local_version != remote_version[0]:
876
      feedback_fn("  - ERROR: incompatible protocol versions: master %s,"
877
                  " node %s %s" % (local_version, node, remote_version[0]))
878
      return True
879

    
880
    # node seems compatible, we can actually try to look into its results
881

    
882
    bad = False
883

    
884
    # full package version
885
    if constants.RELEASE_VERSION != remote_version[1]:
886
      feedback_fn("  - WARNING: software version mismatch: master %s,"
887
                  " node %s %s" %
888
                  (constants.RELEASE_VERSION, node, remote_version[1]))
889

    
890
    # checks vg existence and size > 20G
891
    if vg_name is not None:
892
      vglist = node_result.get(constants.NV_VGLIST, None)
893
      if not vglist:
894
        feedback_fn("  - ERROR: unable to check volume groups on node %s." %
895
                        (node,))
896
        bad = True
897
      else:
898
        vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
899
                                              constants.MIN_VG_SIZE)
900
        if vgstatus:
901
          feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
902
          bad = True
903

    
904
    # checks config file checksum
905

    
906
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
907
    if not isinstance(remote_cksum, dict):
908
      bad = True
909
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
910
    else:
911
      for file_name in file_list:
912
        node_is_mc = nodeinfo.master_candidate
913
        must_have_file = file_name not in master_files
914
        if file_name not in remote_cksum:
915
          if node_is_mc or must_have_file:
916
            bad = True
917
            feedback_fn("  - ERROR: file '%s' missing" % file_name)
918
        elif remote_cksum[file_name] != local_cksum[file_name]:
919
          if node_is_mc or must_have_file:
920
            bad = True
921
            feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
922
          else:
923
            # not candidate and this is not a must-have file
924
            bad = True
925
            feedback_fn("  - ERROR: file '%s' should not exist on non master"
926
                        " candidates (and the file is outdated)" % file_name)
927
        else:
928
          # all good, except non-master/non-must have combination
929
          if not node_is_mc and not must_have_file:
930
            feedback_fn("  - ERROR: file '%s' should not exist on non master"
931
                        " candidates" % file_name)
932

    
933
    # checks ssh to any
934

    
935
    if constants.NV_NODELIST not in node_result:
936
      bad = True
937
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
938
    else:
939
      if node_result[constants.NV_NODELIST]:
940
        bad = True
941
        for node in node_result[constants.NV_NODELIST]:
942
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
943
                          (node, node_result[constants.NV_NODELIST][node]))
944

    
945
    if constants.NV_NODENETTEST not in node_result:
946
      bad = True
947
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
948
    else:
949
      if node_result[constants.NV_NODENETTEST]:
950
        bad = True
951
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
952
        for node in nlist:
953
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
954
                          (node, node_result[constants.NV_NODENETTEST][node]))
955

    
956
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
957
    if isinstance(hyp_result, dict):
958
      for hv_name, hv_result in hyp_result.iteritems():
959
        if hv_result is not None:
960
          feedback_fn("  - ERROR: hypervisor %s verify failure: '%s'" %
961
                      (hv_name, hv_result))
962

    
963
    # check used drbd list
964
    if vg_name is not None:
965
      used_minors = node_result.get(constants.NV_DRBDLIST, [])
966
      if not isinstance(used_minors, (tuple, list)):
967
        feedback_fn("  - ERROR: cannot parse drbd status file: %s" %
968
                    str(used_minors))
969
      else:
970
        for minor, (iname, must_exist) in drbd_map.items():
971
          if minor not in used_minors and must_exist:
972
            feedback_fn("  - ERROR: drbd minor %d of instance %s is"
973
                        " not active" % (minor, iname))
974
            bad = True
975
        for minor in used_minors:
976
          if minor not in drbd_map:
977
            feedback_fn("  - ERROR: unallocated drbd minor %d is in use" %
978
                        minor)
979
            bad = True
980

    
981
    return bad
982

    
983
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
984
                      node_instance, feedback_fn, n_offline):
985
    """Verify an instance.
986

987
    This function checks to see if the required block devices are
988
    available on the instance's node.
989

990
    """
991
    bad = False
992

    
993
    node_current = instanceconfig.primary_node
994

    
995
    node_vol_should = {}
996
    instanceconfig.MapLVsByNode(node_vol_should)
997

    
998
    for node in node_vol_should:
999
      if node in n_offline:
1000
        # ignore missing volumes on offline nodes
1001
        continue
1002
      for volume in node_vol_should[node]:
1003
        if node not in node_vol_is or volume not in node_vol_is[node]:
1004
          feedback_fn("  - ERROR: volume %s missing on node %s" %
1005
                          (volume, node))
1006
          bad = True
1007

    
1008
    if instanceconfig.admin_up:
1009
      if ((node_current not in node_instance or
1010
          not instance in node_instance[node_current]) and
1011
          node_current not in n_offline):
1012
        feedback_fn("  - ERROR: instance %s not running on node %s" %
1013
                        (instance, node_current))
1014
        bad = True
1015

    
1016
    for node in node_instance:
1017
      if (not node == node_current):
1018
        if instance in node_instance[node]:
1019
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
1020
                          (instance, node))
1021
          bad = True
1022

    
1023
    return bad
1024

    
1025
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
1026
    """Verify if there are any unknown volumes in the cluster.
1027

1028
    The .os, .swap and backup volumes are ignored. All other volumes are
1029
    reported as unknown.
1030

1031
    """
1032
    bad = False
1033

    
1034
    for node in node_vol_is:
1035
      for volume in node_vol_is[node]:
1036
        if node not in node_vol_should or volume not in node_vol_should[node]:
1037
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
1038
                      (volume, node))
1039
          bad = True
1040
    return bad
1041

    
1042
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
1043
    """Verify the list of running instances.
1044

1045
    This checks what instances are running but unknown to the cluster.
1046

1047
    """
1048
    bad = False
1049
    for node in node_instance:
1050
      for runninginstance in node_instance[node]:
1051
        if runninginstance not in instancelist:
1052
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
1053
                          (runninginstance, node))
1054
          bad = True
1055
    return bad
1056

    
1057
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
1058
    """Verify N+1 Memory Resilience.
1059

1060
    Check that if one single node dies we can still start all the instances it
1061
    was primary for.
1062

1063
    """
1064
    bad = False
1065

    
1066
    for node, nodeinfo in node_info.iteritems():
1067
      # This code checks that every node which is now listed as secondary has
1068
      # enough memory to host all instances it is supposed to should a single
1069
      # other node in the cluster fail.
1070
      # FIXME: not ready for failover to an arbitrary node
1071
      # FIXME: does not support file-backed instances
1072
      # WARNING: we currently take into account down instances as well as up
1073
      # ones, considering that even if they're down someone might want to start
1074
      # them even in the event of a node failure.
1075
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
1076
        needed_mem = 0
1077
        for instance in instances:
1078
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1079
          if bep[constants.BE_AUTO_BALANCE]:
1080
            needed_mem += bep[constants.BE_MEMORY]
1081
        if nodeinfo['mfree'] < needed_mem:
1082
          feedback_fn("  - ERROR: not enough memory on node %s to accommodate"
1083
                      " failovers should node %s fail" % (node, prinode))
1084
          bad = True
1085
    return bad
1086

    
1087
  def CheckPrereq(self):
1088
    """Check prerequisites.
1089

1090
    Transform the list of checks we're going to skip into a set and check that
1091
    all its members are valid.
1092

1093
    """
1094
    self.skip_set = frozenset(self.op.skip_checks)
1095
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1096
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
1097

    
1098
  def BuildHooksEnv(self):
1099
    """Build hooks env.
1100

1101
    Cluster-Verify hooks just ran in the post phase and their failure makes
1102
    the output be logged in the verify output and the verification to fail.
1103

1104
    """
1105
    all_nodes = self.cfg.GetNodeList()
1106
    env = {
1107
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1108
      }
1109
    for node in self.cfg.GetAllNodesInfo().values():
1110
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1111

    
1112
    return env, [], all_nodes
1113

    
1114
  def Exec(self, feedback_fn):
1115
    """Verify integrity of cluster, performing various test on nodes.
1116

1117
    """
1118
    bad = False
1119
    feedback_fn("* Verifying global settings")
1120
    for msg in self.cfg.VerifyConfig():
1121
      feedback_fn("  - ERROR: %s" % msg)
1122

    
1123
    vg_name = self.cfg.GetVGName()
1124
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1125
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1126
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1127
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1128
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1129
                        for iname in instancelist)
1130
    i_non_redundant = [] # Non redundant instances
1131
    i_non_a_balanced = [] # Non auto-balanced instances
1132
    n_offline = [] # List of offline nodes
1133
    n_drained = [] # List of nodes being drained
1134
    node_volume = {}
1135
    node_instance = {}
1136
    node_info = {}
1137
    instance_cfg = {}
1138

    
1139
    # FIXME: verify OS list
1140
    # do local checksums
1141
    master_files = [constants.CLUSTER_CONF_FILE]
1142

    
1143
    file_names = ssconf.SimpleStore().GetFileList()
1144
    file_names.append(constants.SSL_CERT_FILE)
1145
    file_names.append(constants.RAPI_CERT_FILE)
1146
    file_names.extend(master_files)
1147

    
1148
    local_checksums = utils.FingerprintFiles(file_names)
1149

    
1150
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1151
    node_verify_param = {
1152
      constants.NV_FILELIST: file_names,
1153
      constants.NV_NODELIST: [node.name for node in nodeinfo
1154
                              if not node.offline],
1155
      constants.NV_HYPERVISOR: hypervisors,
1156
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1157
                                  node.secondary_ip) for node in nodeinfo
1158
                                 if not node.offline],
1159
      constants.NV_INSTANCELIST: hypervisors,
1160
      constants.NV_VERSION: None,
1161
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1162
      }
1163
    if vg_name is not None:
1164
      node_verify_param[constants.NV_VGLIST] = None
1165
      node_verify_param[constants.NV_LVLIST] = vg_name
1166
      node_verify_param[constants.NV_DRBDLIST] = None
1167
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1168
                                           self.cfg.GetClusterName())
1169

    
1170
    cluster = self.cfg.GetClusterInfo()
1171
    master_node = self.cfg.GetMasterNode()
1172
    all_drbd_map = self.cfg.ComputeDRBDMap()
1173

    
1174
    for node_i in nodeinfo:
1175
      node = node_i.name
1176

    
1177
      if node_i.offline:
1178
        feedback_fn("* Skipping offline node %s" % (node,))
1179
        n_offline.append(node)
1180
        continue
1181

    
1182
      if node == master_node:
1183
        ntype = "master"
1184
      elif node_i.master_candidate:
1185
        ntype = "master candidate"
1186
      elif node_i.drained:
1187
        ntype = "drained"
1188
        n_drained.append(node)
1189
      else:
1190
        ntype = "regular"
1191
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1192

    
1193
      msg = all_nvinfo[node].fail_msg
1194
      if msg:
1195
        feedback_fn("  - ERROR: while contacting node %s: %s" % (node, msg))
1196
        bad = True
1197
        continue
1198

    
1199
      nresult = all_nvinfo[node].payload
1200
      node_drbd = {}
1201
      for minor, instance in all_drbd_map[node].items():
1202
        if instance not in instanceinfo:
1203
          feedback_fn("  - ERROR: ghost instance '%s' in temporary DRBD map" %
1204
                      instance)
1205
          # ghost instance should not be running, but otherwise we
1206
          # don't give double warnings (both ghost instance and
1207
          # unallocated minor in use)
1208
          node_drbd[minor] = (instance, False)
1209
        else:
1210
          instance = instanceinfo[instance]
1211
          node_drbd[minor] = (instance.name, instance.admin_up)
1212
      result = self._VerifyNode(node_i, file_names, local_checksums,
1213
                                nresult, feedback_fn, master_files,
1214
                                node_drbd, vg_name)
1215
      bad = bad or result
1216

    
1217
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1218
      if vg_name is None:
1219
        node_volume[node] = {}
1220
      elif isinstance(lvdata, basestring):
1221
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
1222
                    (node, utils.SafeEncode(lvdata)))
1223
        bad = True
1224
        node_volume[node] = {}
1225
      elif not isinstance(lvdata, dict):
1226
        feedback_fn("  - ERROR: connection to %s failed (lvlist)" % (node,))
1227
        bad = True
1228
        continue
1229
      else:
1230
        node_volume[node] = lvdata
1231

    
1232
      # node_instance
1233
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1234
      if not isinstance(idata, list):
1235
        feedback_fn("  - ERROR: connection to %s failed (instancelist)" %
1236
                    (node,))
1237
        bad = True
1238
        continue
1239

    
1240
      node_instance[node] = idata
1241

    
1242
      # node_info
1243
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1244
      if not isinstance(nodeinfo, dict):
1245
        feedback_fn("  - ERROR: connection to %s failed (hvinfo)" % (node,))
1246
        bad = True
1247
        continue
1248

    
1249
      try:
1250
        node_info[node] = {
1251
          "mfree": int(nodeinfo['memory_free']),
1252
          "pinst": [],
1253
          "sinst": [],
1254
          # dictionary holding all instances this node is secondary for,
1255
          # grouped by their primary node. Each key is a cluster node, and each
1256
          # value is a list of instances which have the key as primary and the
1257
          # current node as secondary.  this is handy to calculate N+1 memory
1258
          # availability if you can only failover from a primary to its
1259
          # secondary.
1260
          "sinst-by-pnode": {},
1261
        }
1262
        # FIXME: devise a free space model for file based instances as well
1263
        if vg_name is not None:
1264
          if (constants.NV_VGLIST not in nresult or
1265
              vg_name not in nresult[constants.NV_VGLIST]):
1266
            feedback_fn("  - ERROR: node %s didn't return data for the"
1267
                        " volume group '%s' - it is either missing or broken" %
1268
                        (node, vg_name))
1269
            bad = True
1270
            continue
1271
          node_info[node]["dfree"] = int(nresult[constants.NV_VGLIST][vg_name])
1272
      except (ValueError, KeyError):
1273
        feedback_fn("  - ERROR: invalid nodeinfo value returned"
1274
                    " from node %s" % (node,))
1275
        bad = True
1276
        continue
1277

    
1278
    node_vol_should = {}
1279

    
1280
    for instance in instancelist:
1281
      feedback_fn("* Verifying instance %s" % instance)
1282
      inst_config = instanceinfo[instance]
1283
      result =  self._VerifyInstance(instance, inst_config, node_volume,
1284
                                     node_instance, feedback_fn, n_offline)
1285
      bad = bad or result
1286
      inst_nodes_offline = []
1287

    
1288
      inst_config.MapLVsByNode(node_vol_should)
1289

    
1290
      instance_cfg[instance] = inst_config
1291

    
1292
      pnode = inst_config.primary_node
1293
      if pnode in node_info:
1294
        node_info[pnode]['pinst'].append(instance)
1295
      elif pnode not in n_offline:
1296
        feedback_fn("  - ERROR: instance %s, connection to primary node"
1297
                    " %s failed" % (instance, pnode))
1298
        bad = True
1299

    
1300
      if pnode in n_offline:
1301
        inst_nodes_offline.append(pnode)
1302

    
1303
      # If the instance is non-redundant we cannot survive losing its primary
1304
      # node, so we are not N+1 compliant. On the other hand we have no disk
1305
      # templates with more than one secondary so that situation is not well
1306
      # supported either.
1307
      # FIXME: does not support file-backed instances
1308
      if len(inst_config.secondary_nodes) == 0:
1309
        i_non_redundant.append(instance)
1310
      elif len(inst_config.secondary_nodes) > 1:
1311
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
1312
                    % instance)
1313

    
1314
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1315
        i_non_a_balanced.append(instance)
1316

    
1317
      for snode in inst_config.secondary_nodes:
1318
        if snode in node_info:
1319
          node_info[snode]['sinst'].append(instance)
1320
          if pnode not in node_info[snode]['sinst-by-pnode']:
1321
            node_info[snode]['sinst-by-pnode'][pnode] = []
1322
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1323
        elif snode not in n_offline:
1324
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
1325
                      " %s failed" % (instance, snode))
1326
          bad = True
1327
        if snode in n_offline:
1328
          inst_nodes_offline.append(snode)
1329

    
1330
      if inst_nodes_offline:
1331
        # warn that the instance lives on offline nodes, and set bad=True
1332
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1333
                    ", ".join(inst_nodes_offline))
1334
        bad = True
1335

    
1336
    feedback_fn("* Verifying orphan volumes")
1337
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1338
                                       feedback_fn)
1339
    bad = bad or result
1340

    
1341
    feedback_fn("* Verifying remaining instances")
1342
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1343
                                         feedback_fn)
1344
    bad = bad or result
1345

    
1346
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1347
      feedback_fn("* Verifying N+1 Memory redundancy")
1348
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1349
      bad = bad or result
1350

    
1351
    feedback_fn("* Other Notes")
1352
    if i_non_redundant:
1353
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1354
                  % len(i_non_redundant))
1355

    
1356
    if i_non_a_balanced:
1357
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1358
                  % len(i_non_a_balanced))
1359

    
1360
    if n_offline:
1361
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1362

    
1363
    if n_drained:
1364
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1365

    
1366
    return not bad
1367

    
1368
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1369
    """Analyze the post-hooks' result
1370

1371
    This method analyses the hook result, handles it, and sends some
1372
    nicely-formatted feedback back to the user.
1373

1374
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1375
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1376
    @param hooks_results: the results of the multi-node hooks rpc call
1377
    @param feedback_fn: function used send feedback back to the caller
1378
    @param lu_result: previous Exec result
1379
    @return: the new Exec result, based on the previous result
1380
        and hook results
1381

1382
    """
1383
    # We only really run POST phase hooks, and are only interested in
1384
    # their results
1385
    if phase == constants.HOOKS_PHASE_POST:
1386
      # Used to change hooks' output to proper indentation
1387
      indent_re = re.compile('^', re.M)
1388
      feedback_fn("* Hooks Results")
1389
      if not hooks_results:
1390
        feedback_fn("  - ERROR: general communication failure")
1391
        lu_result = 1
1392
      else:
1393
        for node_name in hooks_results:
1394
          show_node_header = True
1395
          res = hooks_results[node_name]
1396
          msg = res.fail_msg
1397
          if msg:
1398
            if res.offline:
1399
              # no need to warn or set fail return value
1400
              continue
1401
            feedback_fn("    Communication failure in hooks execution: %s" %
1402
                        msg)
1403
            lu_result = 1
1404
            continue
1405
          for script, hkr, output in res.payload:
1406
            if hkr == constants.HKR_FAIL:
1407
              # The node header is only shown once, if there are
1408
              # failing hooks on that node
1409
              if show_node_header:
1410
                feedback_fn("  Node %s:" % node_name)
1411
                show_node_header = False
1412
              feedback_fn("    ERROR: Script %s failed, output:" % script)
1413
              output = indent_re.sub('      ', output)
1414
              feedback_fn("%s" % output)
1415
              lu_result = 1
1416

    
1417
      return lu_result
1418

    
1419

    
1420
class LUVerifyDisks(NoHooksLU):
1421
  """Verifies the cluster disks status.
1422

1423
  """
1424
  _OP_REQP = []
1425
  REQ_BGL = False
1426

    
1427
  def ExpandNames(self):
1428
    self.needed_locks = {
1429
      locking.LEVEL_NODE: locking.ALL_SET,
1430
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1431
    }
1432
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1433

    
1434
  def CheckPrereq(self):
1435
    """Check prerequisites.
1436

1437
    This has no prerequisites.
1438

1439
    """
1440
    pass
1441

    
1442
  def Exec(self, feedback_fn):
1443
    """Verify integrity of cluster disks.
1444

1445
    @rtype: tuple of three items
1446
    @return: a tuple of (dict of node-to-node_error, list of instances
1447
        which need activate-disks, dict of instance: (node, volume) for
1448
        missing volumes
1449

1450
    """
1451
    result = res_nodes, res_instances, res_missing = {}, [], {}
1452

    
1453
    vg_name = self.cfg.GetVGName()
1454
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1455
    instances = [self.cfg.GetInstanceInfo(name)
1456
                 for name in self.cfg.GetInstanceList()]
1457

    
1458
    nv_dict = {}
1459
    for inst in instances:
1460
      inst_lvs = {}
1461
      if (not inst.admin_up or
1462
          inst.disk_template not in constants.DTS_NET_MIRROR):
1463
        continue
1464
      inst.MapLVsByNode(inst_lvs)
1465
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1466
      for node, vol_list in inst_lvs.iteritems():
1467
        for vol in vol_list:
1468
          nv_dict[(node, vol)] = inst
1469

    
1470
    if not nv_dict:
1471
      return result
1472

    
1473
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1474

    
1475
    for node in nodes:
1476
      # node_volume
1477
      node_res = node_lvs[node]
1478
      if node_res.offline:
1479
        continue
1480
      msg = node_res.fail_msg
1481
      if msg:
1482
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1483
        res_nodes[node] = msg
1484
        continue
1485

    
1486
      lvs = node_res.payload
1487
      for lv_name, (_, lv_inactive, lv_online) in lvs.items():
1488
        inst = nv_dict.pop((node, lv_name), None)
1489
        if (not lv_online and inst is not None
1490
            and inst.name not in res_instances):
1491
          res_instances.append(inst.name)
1492

    
1493
    # any leftover items in nv_dict are missing LVs, let's arrange the
1494
    # data better
1495
    for key, inst in nv_dict.iteritems():
1496
      if inst.name not in res_missing:
1497
        res_missing[inst.name] = []
1498
      res_missing[inst.name].append(key)
1499

    
1500
    return result
1501

    
1502

    
1503
class LURenameCluster(LogicalUnit):
1504
  """Rename the cluster.
1505

1506
  """
1507
  HPATH = "cluster-rename"
1508
  HTYPE = constants.HTYPE_CLUSTER
1509
  _OP_REQP = ["name"]
1510

    
1511
  def BuildHooksEnv(self):
1512
    """Build hooks env.
1513

1514
    """
1515
    env = {
1516
      "OP_TARGET": self.cfg.GetClusterName(),
1517
      "NEW_NAME": self.op.name,
1518
      }
1519
    mn = self.cfg.GetMasterNode()
1520
    return env, [mn], [mn]
1521

    
1522
  def CheckPrereq(self):
1523
    """Verify that the passed name is a valid one.
1524

1525
    """
1526
    hostname = utils.HostInfo(self.op.name)
1527

    
1528
    new_name = hostname.name
1529
    self.ip = new_ip = hostname.ip
1530
    old_name = self.cfg.GetClusterName()
1531
    old_ip = self.cfg.GetMasterIP()
1532
    if new_name == old_name and new_ip == old_ip:
1533
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1534
                                 " cluster has changed")
1535
    if new_ip != old_ip:
1536
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1537
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1538
                                   " reachable on the network. Aborting." %
1539
                                   new_ip)
1540

    
1541
    self.op.name = new_name
1542

    
1543
  def Exec(self, feedback_fn):
1544
    """Rename the cluster.
1545

1546
    """
1547
    clustername = self.op.name
1548
    ip = self.ip
1549

    
1550
    # shutdown the master IP
1551
    master = self.cfg.GetMasterNode()
1552
    result = self.rpc.call_node_stop_master(master, False)
1553
    result.Raise("Could not disable the master role")
1554

    
1555
    try:
1556
      cluster = self.cfg.GetClusterInfo()
1557
      cluster.cluster_name = clustername
1558
      cluster.master_ip = ip
1559
      self.cfg.Update(cluster)
1560

    
1561
      # update the known hosts file
1562
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1563
      node_list = self.cfg.GetNodeList()
1564
      try:
1565
        node_list.remove(master)
1566
      except ValueError:
1567
        pass
1568
      result = self.rpc.call_upload_file(node_list,
1569
                                         constants.SSH_KNOWN_HOSTS_FILE)
1570
      for to_node, to_result in result.iteritems():
1571
        msg = to_result.fail_msg
1572
        if msg:
1573
          msg = ("Copy of file %s to node %s failed: %s" %
1574
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
1575
          self.proc.LogWarning(msg)
1576

    
1577
    finally:
1578
      result = self.rpc.call_node_start_master(master, False, False)
1579
      msg = result.fail_msg
1580
      if msg:
1581
        self.LogWarning("Could not re-enable the master role on"
1582
                        " the master, please restart manually: %s", msg)
1583

    
1584

    
1585
def _RecursiveCheckIfLVMBased(disk):
1586
  """Check if the given disk or its children are lvm-based.
1587

1588
  @type disk: L{objects.Disk}
1589
  @param disk: the disk to check
1590
  @rtype: boolean
1591
  @return: boolean indicating whether a LD_LV dev_type was found or not
1592

1593
  """
1594
  if disk.children:
1595
    for chdisk in disk.children:
1596
      if _RecursiveCheckIfLVMBased(chdisk):
1597
        return True
1598
  return disk.dev_type == constants.LD_LV
1599

    
1600

    
1601
class LUSetClusterParams(LogicalUnit):
1602
  """Change the parameters of the cluster.
1603

1604
  """
1605
  HPATH = "cluster-modify"
1606
  HTYPE = constants.HTYPE_CLUSTER
1607
  _OP_REQP = []
1608
  REQ_BGL = False
1609

    
1610
  def CheckArguments(self):
1611
    """Check parameters
1612

1613
    """
1614
    if not hasattr(self.op, "candidate_pool_size"):
1615
      self.op.candidate_pool_size = None
1616
    if self.op.candidate_pool_size is not None:
1617
      try:
1618
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1619
      except (ValueError, TypeError), err:
1620
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1621
                                   str(err))
1622
      if self.op.candidate_pool_size < 1:
1623
        raise errors.OpPrereqError("At least one master candidate needed")
1624

    
1625
  def ExpandNames(self):
1626
    # FIXME: in the future maybe other cluster params won't require checking on
1627
    # all nodes to be modified.
1628
    self.needed_locks = {
1629
      locking.LEVEL_NODE: locking.ALL_SET,
1630
    }
1631
    self.share_locks[locking.LEVEL_NODE] = 1
1632

    
1633
  def BuildHooksEnv(self):
1634
    """Build hooks env.
1635

1636
    """
1637
    env = {
1638
      "OP_TARGET": self.cfg.GetClusterName(),
1639
      "NEW_VG_NAME": self.op.vg_name,
1640
      }
1641
    mn = self.cfg.GetMasterNode()
1642
    return env, [mn], [mn]
1643

    
1644
  def CheckPrereq(self):
1645
    """Check prerequisites.
1646

1647
    This checks whether the given params don't conflict and
1648
    if the given volume group is valid.
1649

1650
    """
1651
    if self.op.vg_name is not None and not self.op.vg_name:
1652
      instances = self.cfg.GetAllInstancesInfo().values()
1653
      for inst in instances:
1654
        for disk in inst.disks:
1655
          if _RecursiveCheckIfLVMBased(disk):
1656
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1657
                                       " lvm-based instances exist")
1658

    
1659
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1660

    
1661
    # if vg_name not None, checks given volume group on all nodes
1662
    if self.op.vg_name:
1663
      vglist = self.rpc.call_vg_list(node_list)
1664
      for node in node_list:
1665
        msg = vglist[node].fail_msg
1666
        if msg:
1667
          # ignoring down node
1668
          self.LogWarning("Error while gathering data on node %s"
1669
                          " (ignoring node): %s", node, msg)
1670
          continue
1671
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
1672
                                              self.op.vg_name,
1673
                                              constants.MIN_VG_SIZE)
1674
        if vgstatus:
1675
          raise errors.OpPrereqError("Error on node '%s': %s" %
1676
                                     (node, vgstatus))
1677

    
1678
    self.cluster = cluster = self.cfg.GetClusterInfo()
1679
    # validate params changes
1680
    if self.op.beparams:
1681
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
1682
      self.new_beparams = objects.FillDict(
1683
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
1684

    
1685
    if self.op.nicparams:
1686
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
1687
      self.new_nicparams = objects.FillDict(
1688
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
1689
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
1690

    
1691
    # hypervisor list/parameters
1692
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
1693
    if self.op.hvparams:
1694
      if not isinstance(self.op.hvparams, dict):
1695
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1696
      for hv_name, hv_dict in self.op.hvparams.items():
1697
        if hv_name not in self.new_hvparams:
1698
          self.new_hvparams[hv_name] = hv_dict
1699
        else:
1700
          self.new_hvparams[hv_name].update(hv_dict)
1701

    
1702
    if self.op.enabled_hypervisors is not None:
1703
      self.hv_list = self.op.enabled_hypervisors
1704
      if not self.hv_list:
1705
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
1706
                                   " least one member")
1707
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
1708
      if invalid_hvs:
1709
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
1710
                                   " entries: %s" % invalid_hvs)
1711
    else:
1712
      self.hv_list = cluster.enabled_hypervisors
1713

    
1714
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1715
      # either the enabled list has changed, or the parameters have, validate
1716
      for hv_name, hv_params in self.new_hvparams.items():
1717
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1718
            (self.op.enabled_hypervisors and
1719
             hv_name in self.op.enabled_hypervisors)):
1720
          # either this is a new hypervisor, or its parameters have changed
1721
          hv_class = hypervisor.GetHypervisor(hv_name)
1722
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1723
          hv_class.CheckParameterSyntax(hv_params)
1724
          _CheckHVParams(self, node_list, hv_name, hv_params)
1725

    
1726
  def Exec(self, feedback_fn):
1727
    """Change the parameters of the cluster.
1728

1729
    """
1730
    if self.op.vg_name is not None:
1731
      new_volume = self.op.vg_name
1732
      if not new_volume:
1733
        new_volume = None
1734
      if new_volume != self.cfg.GetVGName():
1735
        self.cfg.SetVGName(new_volume)
1736
      else:
1737
        feedback_fn("Cluster LVM configuration already in desired"
1738
                    " state, not changing")
1739
    if self.op.hvparams:
1740
      self.cluster.hvparams = self.new_hvparams
1741
    if self.op.enabled_hypervisors is not None:
1742
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1743
    if self.op.beparams:
1744
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
1745
    if self.op.nicparams:
1746
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
1747

    
1748
    if self.op.candidate_pool_size is not None:
1749
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1750
      # we need to update the pool size here, otherwise the save will fail
1751
      _AdjustCandidatePool(self)
1752

    
1753
    self.cfg.Update(self.cluster)
1754

    
1755

    
1756
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
1757
  """Distribute additional files which are part of the cluster configuration.
1758

1759
  ConfigWriter takes care of distributing the config and ssconf files, but
1760
  there are more files which should be distributed to all nodes. This function
1761
  makes sure those are copied.
1762

1763
  @param lu: calling logical unit
1764
  @param additional_nodes: list of nodes not in the config to distribute to
1765

1766
  """
1767
  # 1. Gather target nodes
1768
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
1769
  dist_nodes = lu.cfg.GetNodeList()
1770
  if additional_nodes is not None:
1771
    dist_nodes.extend(additional_nodes)
1772
  if myself.name in dist_nodes:
1773
    dist_nodes.remove(myself.name)
1774
  # 2. Gather files to distribute
1775
  dist_files = set([constants.ETC_HOSTS,
1776
                    constants.SSH_KNOWN_HOSTS_FILE,
1777
                    constants.RAPI_CERT_FILE,
1778
                    constants.RAPI_USERS_FILE,
1779
                    constants.HMAC_CLUSTER_KEY,
1780
                   ])
1781

    
1782
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
1783
  for hv_name in enabled_hypervisors:
1784
    hv_class = hypervisor.GetHypervisor(hv_name)
1785
    dist_files.update(hv_class.GetAncillaryFiles())
1786

    
1787
  # 3. Perform the files upload
1788
  for fname in dist_files:
1789
    if os.path.exists(fname):
1790
      result = lu.rpc.call_upload_file(dist_nodes, fname)
1791
      for to_node, to_result in result.items():
1792
        msg = to_result.fail_msg
1793
        if msg:
1794
          msg = ("Copy of file %s to node %s failed: %s" %
1795
                 (fname, to_node, msg))
1796
          lu.proc.LogWarning(msg)
1797

    
1798

    
1799
class LURedistributeConfig(NoHooksLU):
1800
  """Force the redistribution of cluster configuration.
1801

1802
  This is a very simple LU.
1803

1804
  """
1805
  _OP_REQP = []
1806
  REQ_BGL = False
1807

    
1808
  def ExpandNames(self):
1809
    self.needed_locks = {
1810
      locking.LEVEL_NODE: locking.ALL_SET,
1811
    }
1812
    self.share_locks[locking.LEVEL_NODE] = 1
1813

    
1814
  def CheckPrereq(self):
1815
    """Check prerequisites.
1816

1817
    """
1818

    
1819
  def Exec(self, feedback_fn):
1820
    """Redistribute the configuration.
1821

1822
    """
1823
    self.cfg.Update(self.cfg.GetClusterInfo())
1824
    _RedistributeAncillaryFiles(self)
1825

    
1826

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

1830
  """
1831
  if not instance.disks:
1832
    return True
1833

    
1834
  if not oneshot:
1835
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1836

    
1837
  node = instance.primary_node
1838

    
1839
  for dev in instance.disks:
1840
    lu.cfg.SetDiskID(dev, node)
1841

    
1842
  retries = 0
1843
  degr_retries = 10 # in seconds, as we sleep 1 second each time
1844
  while True:
1845
    max_time = 0
1846
    done = True
1847
    cumul_degraded = False
1848
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1849
    msg = rstats.fail_msg
1850
    if msg:
1851
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
1852
      retries += 1
1853
      if retries >= 10:
1854
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1855
                                 " aborting." % node)
1856
      time.sleep(6)
1857
      continue
1858
    rstats = rstats.payload
1859
    retries = 0
1860
    for i, mstat in enumerate(rstats):
1861
      if mstat is None:
1862
        lu.LogWarning("Can't compute data for node %s/%s",
1863
                           node, instance.disks[i].iv_name)
1864
        continue
1865

    
1866
      cumul_degraded = (cumul_degraded or
1867
                        (mstat.is_degraded and mstat.sync_percent is None))
1868
      if mstat.sync_percent is not None:
1869
        done = False
1870
        if mstat.estimated_time is not None:
1871
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
1872
          max_time = mstat.estimated_time
1873
        else:
1874
          rem_time = "no time estimate"
1875
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1876
                        (instance.disks[i].iv_name, mstat.sync_percent, rem_time))
1877

    
1878
    # if we're done but degraded, let's do a few small retries, to
1879
    # make sure we see a stable and not transient situation; therefore
1880
    # we force restart of the loop
1881
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
1882
      logging.info("Degraded disks found, %d retries left", degr_retries)
1883
      degr_retries -= 1
1884
      time.sleep(1)
1885
      continue
1886

    
1887
    if done or oneshot:
1888
      break
1889

    
1890
    time.sleep(min(60, max_time))
1891

    
1892
  if done:
1893
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1894
  return not cumul_degraded
1895

    
1896

    
1897
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1898
  """Check that mirrors are not degraded.
1899

1900
  The ldisk parameter, if True, will change the test from the
1901
  is_degraded attribute (which represents overall non-ok status for
1902
  the device(s)) to the ldisk (representing the local storage status).
1903

1904
  """
1905
  lu.cfg.SetDiskID(dev, node)
1906

    
1907
  result = True
1908

    
1909
  if on_primary or dev.AssembleOnSecondary():
1910
    rstats = lu.rpc.call_blockdev_find(node, dev)
1911
    msg = rstats.fail_msg
1912
    if msg:
1913
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
1914
      result = False
1915
    elif not rstats.payload:
1916
      lu.LogWarning("Can't find disk on node %s", node)
1917
      result = False
1918
    else:
1919
      if ldisk:
1920
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
1921
      else:
1922
        result = result and not rstats.payload.is_degraded
1923

    
1924
  if dev.children:
1925
    for child in dev.children:
1926
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1927

    
1928
  return result
1929

    
1930

    
1931
class LUDiagnoseOS(NoHooksLU):
1932
  """Logical unit for OS diagnose/query.
1933

1934
  """
1935
  _OP_REQP = ["output_fields", "names"]
1936
  REQ_BGL = False
1937
  _FIELDS_STATIC = utils.FieldSet()
1938
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1939

    
1940
  def ExpandNames(self):
1941
    if self.op.names:
1942
      raise errors.OpPrereqError("Selective OS query not supported")
1943

    
1944
    _CheckOutputFields(static=self._FIELDS_STATIC,
1945
                       dynamic=self._FIELDS_DYNAMIC,
1946
                       selected=self.op.output_fields)
1947

    
1948
    # Lock all nodes, in shared mode
1949
    # Temporary removal of locks, should be reverted later
1950
    # TODO: reintroduce locks when they are lighter-weight
1951
    self.needed_locks = {}
1952
    #self.share_locks[locking.LEVEL_NODE] = 1
1953
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1954

    
1955
  def CheckPrereq(self):
1956
    """Check prerequisites.
1957

1958
    """
1959

    
1960
  @staticmethod
1961
  def _DiagnoseByOS(node_list, rlist):
1962
    """Remaps a per-node return list into an a per-os per-node dictionary
1963

1964
    @param node_list: a list with the names of all nodes
1965
    @param rlist: a map with node names as keys and OS objects as values
1966

1967
    @rtype: dict
1968
    @return: a dictionary with osnames as keys and as value another map, with
1969
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
1970

1971
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
1972
                                     (/srv/..., False, "invalid api")],
1973
                           "node2": [(/srv/..., True, "")]}
1974
          }
1975

1976
    """
1977
    all_os = {}
1978
    # we build here the list of nodes that didn't fail the RPC (at RPC
1979
    # level), so that nodes with a non-responding node daemon don't
1980
    # make all OSes invalid
1981
    good_nodes = [node_name for node_name in rlist
1982
                  if not rlist[node_name].fail_msg]
1983
    for node_name, nr in rlist.items():
1984
      if nr.fail_msg or not nr.payload:
1985
        continue
1986
      for name, path, status, diagnose in nr.payload:
1987
        if name not in all_os:
1988
          # build a list of nodes for this os containing empty lists
1989
          # for each node in node_list
1990
          all_os[name] = {}
1991
          for nname in good_nodes:
1992
            all_os[name][nname] = []
1993
        all_os[name][node_name].append((path, status, diagnose))
1994
    return all_os
1995

    
1996
  def Exec(self, feedback_fn):
1997
    """Compute the list of OSes.
1998

1999
    """
2000
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2001
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2002
    pol = self._DiagnoseByOS(valid_nodes, node_data)
2003
    output = []
2004
    for os_name, os_data in pol.items():
2005
      row = []
2006
      for field in self.op.output_fields:
2007
        if field == "name":
2008
          val = os_name
2009
        elif field == "valid":
2010
          val = utils.all([osl and osl[0][1] for osl in os_data.values()])
2011
        elif field == "node_status":
2012
          # this is just a copy of the dict
2013
          val = {}
2014
          for node_name, nos_list in os_data.items():
2015
            val[node_name] = nos_list
2016
        else:
2017
          raise errors.ParameterError(field)
2018
        row.append(val)
2019
      output.append(row)
2020

    
2021
    return output
2022

    
2023

    
2024
class LURemoveNode(LogicalUnit):
2025
  """Logical unit for removing a node.
2026

2027
  """
2028
  HPATH = "node-remove"
2029
  HTYPE = constants.HTYPE_NODE
2030
  _OP_REQP = ["node_name"]
2031

    
2032
  def BuildHooksEnv(self):
2033
    """Build hooks env.
2034

2035
    This doesn't run on the target node in the pre phase as a failed
2036
    node would then be impossible to remove.
2037

2038
    """
2039
    env = {
2040
      "OP_TARGET": self.op.node_name,
2041
      "NODE_NAME": self.op.node_name,
2042
      }
2043
    all_nodes = self.cfg.GetNodeList()
2044
    all_nodes.remove(self.op.node_name)
2045
    return env, all_nodes, all_nodes
2046

    
2047
  def CheckPrereq(self):
2048
    """Check prerequisites.
2049

2050
    This checks:
2051
     - the node exists in the configuration
2052
     - it does not have primary or secondary instances
2053
     - it's not the master
2054

2055
    Any errors are signaled by raising errors.OpPrereqError.
2056

2057
    """
2058
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
2059
    if node is None:
2060
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
2061

    
2062
    instance_list = self.cfg.GetInstanceList()
2063

    
2064
    masternode = self.cfg.GetMasterNode()
2065
    if node.name == masternode:
2066
      raise errors.OpPrereqError("Node is the master node,"
2067
                                 " you need to failover first.")
2068

    
2069
    for instance_name in instance_list:
2070
      instance = self.cfg.GetInstanceInfo(instance_name)
2071
      if node.name in instance.all_nodes:
2072
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2073
                                   " please remove first." % instance_name)
2074
    self.op.node_name = node.name
2075
    self.node = node
2076

    
2077
  def Exec(self, feedback_fn):
2078
    """Removes the node from the cluster.
2079

2080
    """
2081
    node = self.node
2082
    logging.info("Stopping the node daemon and removing configs from node %s",
2083
                 node.name)
2084

    
2085
    self.context.RemoveNode(node.name)
2086

    
2087
    result = self.rpc.call_node_leave_cluster(node.name)
2088
    msg = result.fail_msg
2089
    if msg:
2090
      self.LogWarning("Errors encountered on the remote node while leaving"
2091
                      " the cluster: %s", msg)
2092

    
2093
    # Promote nodes to master candidate as needed
2094
    _AdjustCandidatePool(self)
2095

    
2096

    
2097
class LUQueryNodes(NoHooksLU):
2098
  """Logical unit for querying nodes.
2099

2100
  """
2101
  _OP_REQP = ["output_fields", "names", "use_locking"]
2102
  REQ_BGL = False
2103
  _FIELDS_DYNAMIC = utils.FieldSet(
2104
    "dtotal", "dfree",
2105
    "mtotal", "mnode", "mfree",
2106
    "bootid",
2107
    "ctotal", "cnodes", "csockets",
2108
    )
2109

    
2110
  _FIELDS_STATIC = utils.FieldSet(
2111
    "name", "pinst_cnt", "sinst_cnt",
2112
    "pinst_list", "sinst_list",
2113
    "pip", "sip", "tags",
2114
    "serial_no",
2115
    "master_candidate",
2116
    "master",
2117
    "offline",
2118
    "drained",
2119
    "role",
2120
    )
2121

    
2122
  def ExpandNames(self):
2123
    _CheckOutputFields(static=self._FIELDS_STATIC,
2124
                       dynamic=self._FIELDS_DYNAMIC,
2125
                       selected=self.op.output_fields)
2126

    
2127
    self.needed_locks = {}
2128
    self.share_locks[locking.LEVEL_NODE] = 1
2129

    
2130
    if self.op.names:
2131
      self.wanted = _GetWantedNodes(self, self.op.names)
2132
    else:
2133
      self.wanted = locking.ALL_SET
2134

    
2135
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2136
    self.do_locking = self.do_node_query and self.op.use_locking
2137
    if self.do_locking:
2138
      # if we don't request only static fields, we need to lock the nodes
2139
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2140

    
2141

    
2142
  def CheckPrereq(self):
2143
    """Check prerequisites.
2144

2145
    """
2146
    # The validation of the node list is done in the _GetWantedNodes,
2147
    # if non empty, and if empty, there's no validation to do
2148
    pass
2149

    
2150
  def Exec(self, feedback_fn):
2151
    """Computes the list of nodes and their attributes.
2152

2153
    """
2154
    all_info = self.cfg.GetAllNodesInfo()
2155
    if self.do_locking:
2156
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2157
    elif self.wanted != locking.ALL_SET:
2158
      nodenames = self.wanted
2159
      missing = set(nodenames).difference(all_info.keys())
2160
      if missing:
2161
        raise errors.OpExecError(
2162
          "Some nodes were removed before retrieving their data: %s" % missing)
2163
    else:
2164
      nodenames = all_info.keys()
2165

    
2166
    nodenames = utils.NiceSort(nodenames)
2167
    nodelist = [all_info[name] for name in nodenames]
2168

    
2169
    # begin data gathering
2170

    
2171
    if self.do_node_query:
2172
      live_data = {}
2173
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2174
                                          self.cfg.GetHypervisorType())
2175
      for name in nodenames:
2176
        nodeinfo = node_data[name]
2177
        if not nodeinfo.fail_msg and nodeinfo.payload:
2178
          nodeinfo = nodeinfo.payload
2179
          fn = utils.TryConvert
2180
          live_data[name] = {
2181
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2182
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2183
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2184
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2185
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2186
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2187
            "bootid": nodeinfo.get('bootid', None),
2188
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2189
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2190
            }
2191
        else:
2192
          live_data[name] = {}
2193
    else:
2194
      live_data = dict.fromkeys(nodenames, {})
2195

    
2196
    node_to_primary = dict([(name, set()) for name in nodenames])
2197
    node_to_secondary = dict([(name, set()) for name in nodenames])
2198

    
2199
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2200
                             "sinst_cnt", "sinst_list"))
2201
    if inst_fields & frozenset(self.op.output_fields):
2202
      instancelist = self.cfg.GetInstanceList()
2203

    
2204
      for instance_name in instancelist:
2205
        inst = self.cfg.GetInstanceInfo(instance_name)
2206
        if inst.primary_node in node_to_primary:
2207
          node_to_primary[inst.primary_node].add(inst.name)
2208
        for secnode in inst.secondary_nodes:
2209
          if secnode in node_to_secondary:
2210
            node_to_secondary[secnode].add(inst.name)
2211

    
2212
    master_node = self.cfg.GetMasterNode()
2213

    
2214
    # end data gathering
2215

    
2216
    output = []
2217
    for node in nodelist:
2218
      node_output = []
2219
      for field in self.op.output_fields:
2220
        if field == "name":
2221
          val = node.name
2222
        elif field == "pinst_list":
2223
          val = list(node_to_primary[node.name])
2224
        elif field == "sinst_list":
2225
          val = list(node_to_secondary[node.name])
2226
        elif field == "pinst_cnt":
2227
          val = len(node_to_primary[node.name])
2228
        elif field == "sinst_cnt":
2229
          val = len(node_to_secondary[node.name])
2230
        elif field == "pip":
2231
          val = node.primary_ip
2232
        elif field == "sip":
2233
          val = node.secondary_ip
2234
        elif field == "tags":
2235
          val = list(node.GetTags())
2236
        elif field == "serial_no":
2237
          val = node.serial_no
2238
        elif field == "master_candidate":
2239
          val = node.master_candidate
2240
        elif field == "master":
2241
          val = node.name == master_node
2242
        elif field == "offline":
2243
          val = node.offline
2244
        elif field == "drained":
2245
          val = node.drained
2246
        elif self._FIELDS_DYNAMIC.Matches(field):
2247
          val = live_data[node.name].get(field, None)
2248
        elif field == "role":
2249
          if node.name == master_node:
2250
            val = "M"
2251
          elif node.master_candidate:
2252
            val = "C"
2253
          elif node.drained:
2254
            val = "D"
2255
          elif node.offline:
2256
            val = "O"
2257
          else:
2258
            val = "R"
2259
        else:
2260
          raise errors.ParameterError(field)
2261
        node_output.append(val)
2262
      output.append(node_output)
2263

    
2264
    return output
2265

    
2266

    
2267
class LUQueryNodeVolumes(NoHooksLU):
2268
  """Logical unit for getting volumes on node(s).
2269

2270
  """
2271
  _OP_REQP = ["nodes", "output_fields"]
2272
  REQ_BGL = False
2273
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2274
  _FIELDS_STATIC = utils.FieldSet("node")
2275

    
2276
  def ExpandNames(self):
2277
    _CheckOutputFields(static=self._FIELDS_STATIC,
2278
                       dynamic=self._FIELDS_DYNAMIC,
2279
                       selected=self.op.output_fields)
2280

    
2281
    self.needed_locks = {}
2282
    self.share_locks[locking.LEVEL_NODE] = 1
2283
    if not self.op.nodes:
2284
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2285
    else:
2286
      self.needed_locks[locking.LEVEL_NODE] = \
2287
        _GetWantedNodes(self, self.op.nodes)
2288

    
2289
  def CheckPrereq(self):
2290
    """Check prerequisites.
2291

2292
    This checks that the fields required are valid output fields.
2293

2294
    """
2295
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2296

    
2297
  def Exec(self, feedback_fn):
2298
    """Computes the list of nodes and their attributes.
2299

2300
    """
2301
    nodenames = self.nodes
2302
    volumes = self.rpc.call_node_volumes(nodenames)
2303

    
2304
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2305
             in self.cfg.GetInstanceList()]
2306

    
2307
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2308

    
2309
    output = []
2310
    for node in nodenames:
2311
      nresult = volumes[node]
2312
      if nresult.offline:
2313
        continue
2314
      msg = nresult.fail_msg
2315
      if msg:
2316
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
2317
        continue
2318

    
2319
      node_vols = nresult.payload[:]
2320
      node_vols.sort(key=lambda vol: vol['dev'])
2321

    
2322
      for vol in node_vols:
2323
        node_output = []
2324
        for field in self.op.output_fields:
2325
          if field == "node":
2326
            val = node
2327
          elif field == "phys":
2328
            val = vol['dev']
2329
          elif field == "vg":
2330
            val = vol['vg']
2331
          elif field == "name":
2332
            val = vol['name']
2333
          elif field == "size":
2334
            val = int(float(vol['size']))
2335
          elif field == "instance":
2336
            for inst in ilist:
2337
              if node not in lv_by_node[inst]:
2338
                continue
2339
              if vol['name'] in lv_by_node[inst][node]:
2340
                val = inst.name
2341
                break
2342
            else:
2343
              val = '-'
2344
          else:
2345
            raise errors.ParameterError(field)
2346
          node_output.append(str(val))
2347

    
2348
        output.append(node_output)
2349

    
2350
    return output
2351

    
2352

    
2353
class LUQueryNodeStorage(NoHooksLU):
2354
  """Logical unit for getting information on storage units on node(s).
2355

2356
  """
2357
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
2358
  REQ_BGL = False
2359
  _FIELDS_STATIC = utils.FieldSet("node")
2360

    
2361
  def ExpandNames(self):
2362
    storage_type = self.op.storage_type
2363

    
2364
    if storage_type not in constants.VALID_STORAGE_FIELDS:
2365
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type)
2366

    
2367
    dynamic_fields = constants.VALID_STORAGE_FIELDS[storage_type]
2368

    
2369
    _CheckOutputFields(static=self._FIELDS_STATIC,
2370
                       dynamic=utils.FieldSet(*dynamic_fields),
2371
                       selected=self.op.output_fields)
2372

    
2373
    self.needed_locks = {}
2374
    self.share_locks[locking.LEVEL_NODE] = 1
2375

    
2376
    if self.op.nodes:
2377
      self.needed_locks[locking.LEVEL_NODE] = \
2378
        _GetWantedNodes(self, self.op.nodes)
2379
    else:
2380
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2381

    
2382
  def CheckPrereq(self):
2383
    """Check prerequisites.
2384

2385
    This checks that the fields required are valid output fields.
2386

2387
    """
2388
    self.op.name = getattr(self.op, "name", None)
2389

    
2390
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2391

    
2392
  def Exec(self, feedback_fn):
2393
    """Computes the list of nodes and their attributes.
2394

2395
    """
2396
    # Always get name to sort by
2397
    if constants.SF_NAME in self.op.output_fields:
2398
      fields = self.op.output_fields[:]
2399
    else:
2400
      fields = [constants.SF_NAME] + self.op.output_fields
2401

    
2402
    # Never ask for node as it's only known to the LU
2403
    while "node" in fields:
2404
      fields.remove("node")
2405

    
2406
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
2407
    name_idx = field_idx[constants.SF_NAME]
2408

    
2409
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2410
    data = self.rpc.call_storage_list(self.nodes,
2411
                                      self.op.storage_type, st_args,
2412
                                      self.op.name, fields)
2413

    
2414
    result = []
2415

    
2416
    for node in utils.NiceSort(self.nodes):
2417
      nresult = data[node]
2418
      if nresult.offline:
2419
        continue
2420

    
2421
      msg = nresult.fail_msg
2422
      if msg:
2423
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
2424
        continue
2425

    
2426
      rows = dict([(row[name_idx], row) for row in nresult.payload])
2427

    
2428
      for name in utils.NiceSort(rows.keys()):
2429
        row = rows[name]
2430

    
2431
        out = []
2432

    
2433
        for field in self.op.output_fields:
2434
          if field == "node":
2435
            val = node
2436
          elif field in field_idx:
2437
            val = row[field_idx[field]]
2438
          else:
2439
            raise errors.ParameterError(field)
2440

    
2441
          out.append(val)
2442

    
2443
        result.append(out)
2444

    
2445
    return result
2446

    
2447

    
2448
class LUModifyNodeStorage(NoHooksLU):
2449
  """Logical unit for modifying a storage volume on a node.
2450

2451
  """
2452
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
2453
  REQ_BGL = False
2454

    
2455
  def CheckArguments(self):
2456
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2457
    if node_name is None:
2458
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2459

    
2460
    self.op.node_name = node_name
2461

    
2462
    storage_type = self.op.storage_type
2463
    if storage_type not in constants.VALID_STORAGE_FIELDS:
2464
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type)
2465

    
2466
  def ExpandNames(self):
2467
    self.needed_locks = {
2468
      locking.LEVEL_NODE: self.op.node_name,
2469
      }
2470

    
2471
  def CheckPrereq(self):
2472
    """Check prerequisites.
2473

2474
    """
2475
    storage_type = self.op.storage_type
2476

    
2477
    try:
2478
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
2479
    except KeyError:
2480
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
2481
                                 " modified" % storage_type)
2482

    
2483
    diff = set(self.op.changes.keys()) - modifiable
2484
    if diff:
2485
      raise errors.OpPrereqError("The following fields can not be modified for"
2486
                                 " storage units of type '%s': %r" %
2487
                                 (storage_type, list(diff)))
2488

    
2489
  def Exec(self, feedback_fn):
2490
    """Computes the list of nodes and their attributes.
2491

2492
    """
2493
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2494
    result = self.rpc.call_storage_modify(self.op.node_name,
2495
                                          self.op.storage_type, st_args,
2496
                                          self.op.name, self.op.changes)
2497
    result.Raise("Failed to modify storage unit '%s' on %s" %
2498
                 (self.op.name, self.op.node_name))
2499

    
2500

    
2501
class LUAddNode(LogicalUnit):
2502
  """Logical unit for adding node to the cluster.
2503

2504
  """
2505
  HPATH = "node-add"
2506
  HTYPE = constants.HTYPE_NODE
2507
  _OP_REQP = ["node_name"]
2508

    
2509
  def BuildHooksEnv(self):
2510
    """Build hooks env.
2511

2512
    This will run on all nodes before, and on all nodes + the new node after.
2513

2514
    """
2515
    env = {
2516
      "OP_TARGET": self.op.node_name,
2517
      "NODE_NAME": self.op.node_name,
2518
      "NODE_PIP": self.op.primary_ip,
2519
      "NODE_SIP": self.op.secondary_ip,
2520
      }
2521
    nodes_0 = self.cfg.GetNodeList()
2522
    nodes_1 = nodes_0 + [self.op.node_name, ]
2523
    return env, nodes_0, nodes_1
2524

    
2525
  def CheckPrereq(self):
2526
    """Check prerequisites.
2527

2528
    This checks:
2529
     - the new node is not already in the config
2530
     - it is resolvable
2531
     - its parameters (single/dual homed) matches the cluster
2532

2533
    Any errors are signaled by raising errors.OpPrereqError.
2534

2535
    """
2536
    node_name = self.op.node_name
2537
    cfg = self.cfg
2538

    
2539
    dns_data = utils.HostInfo(node_name)
2540

    
2541
    node = dns_data.name
2542
    primary_ip = self.op.primary_ip = dns_data.ip
2543
    secondary_ip = getattr(self.op, "secondary_ip", None)
2544
    if secondary_ip is None:
2545
      secondary_ip = primary_ip
2546
    if not utils.IsValidIP(secondary_ip):
2547
      raise errors.OpPrereqError("Invalid secondary IP given")
2548
    self.op.secondary_ip = secondary_ip
2549

    
2550
    node_list = cfg.GetNodeList()
2551
    if not self.op.readd and node in node_list:
2552
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2553
                                 node)
2554
    elif self.op.readd and node not in node_list:
2555
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
2556

    
2557
    for existing_node_name in node_list:
2558
      existing_node = cfg.GetNodeInfo(existing_node_name)
2559

    
2560
      if self.op.readd and node == existing_node_name:
2561
        if (existing_node.primary_ip != primary_ip or
2562
            existing_node.secondary_ip != secondary_ip):
2563
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2564
                                     " address configuration as before")
2565
        continue
2566

    
2567
      if (existing_node.primary_ip == primary_ip or
2568
          existing_node.secondary_ip == primary_ip or
2569
          existing_node.primary_ip == secondary_ip or
2570
          existing_node.secondary_ip == secondary_ip):
2571
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2572
                                   " existing node %s" % existing_node.name)
2573

    
2574
    # check that the type of the node (single versus dual homed) is the
2575
    # same as for the master
2576
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2577
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2578
    newbie_singlehomed = secondary_ip == primary_ip
2579
    if master_singlehomed != newbie_singlehomed:
2580
      if master_singlehomed:
2581
        raise errors.OpPrereqError("The master has no private ip but the"
2582
                                   " new node has one")
2583
      else:
2584
        raise errors.OpPrereqError("The master has a private ip but the"
2585
                                   " new node doesn't have one")
2586

    
2587
    # checks reachability
2588
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2589
      raise errors.OpPrereqError("Node not reachable by ping")
2590

    
2591
    if not newbie_singlehomed:
2592
      # check reachability from my secondary ip to newbie's secondary ip
2593
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2594
                           source=myself.secondary_ip):
2595
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2596
                                   " based ping to noded port")
2597

    
2598
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2599
    if self.op.readd:
2600
      exceptions = [node]
2601
    else:
2602
      exceptions = []
2603
    mc_now, mc_max = self.cfg.GetMasterCandidateStats(exceptions)
2604
    # the new node will increase mc_max with one, so:
2605
    mc_max = min(mc_max + 1, cp_size)
2606
    self.master_candidate = mc_now < mc_max
2607

    
2608
    if self.op.readd:
2609
      self.new_node = self.cfg.GetNodeInfo(node)
2610
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
2611
    else:
2612
      self.new_node = objects.Node(name=node,
2613
                                   primary_ip=primary_ip,
2614
                                   secondary_ip=secondary_ip,
2615
                                   master_candidate=self.master_candidate,
2616
                                   offline=False, drained=False)
2617

    
2618
  def Exec(self, feedback_fn):
2619
    """Adds the new node to the cluster.
2620

2621
    """
2622
    new_node = self.new_node
2623
    node = new_node.name
2624

    
2625
    # for re-adds, reset the offline/drained/master-candidate flags;
2626
    # we need to reset here, otherwise offline would prevent RPC calls
2627
    # later in the procedure; this also means that if the re-add
2628
    # fails, we are left with a non-offlined, broken node
2629
    if self.op.readd:
2630
      new_node.drained = new_node.offline = False
2631
      self.LogInfo("Readding a node, the offline/drained flags were reset")
2632
      # if we demote the node, we do cleanup later in the procedure
2633
      new_node.master_candidate = self.master_candidate
2634

    
2635
    # notify the user about any possible mc promotion
2636
    if new_node.master_candidate:
2637
      self.LogInfo("Node will be a master candidate")
2638

    
2639
    # check connectivity
2640
    result = self.rpc.call_version([node])[node]
2641
    result.Raise("Can't get version information from node %s" % node)
2642
    if constants.PROTOCOL_VERSION == result.payload:
2643
      logging.info("Communication to node %s fine, sw version %s match",
2644
                   node, result.payload)
2645
    else:
2646
      raise errors.OpExecError("Version mismatch master version %s,"
2647
                               " node version %s" %
2648
                               (constants.PROTOCOL_VERSION, result.payload))
2649

    
2650
    # setup ssh on node
2651
    logging.info("Copy ssh key to node %s", node)
2652
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2653
    keyarray = []
2654
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2655
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2656
                priv_key, pub_key]
2657

    
2658
    for i in keyfiles:
2659
      f = open(i, 'r')
2660
      try:
2661
        keyarray.append(f.read())
2662
      finally:
2663
        f.close()
2664

    
2665
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2666
                                    keyarray[2],
2667
                                    keyarray[3], keyarray[4], keyarray[5])
2668
    result.Raise("Cannot transfer ssh keys to the new node")
2669

    
2670
    # Add node to our /etc/hosts, and add key to known_hosts
2671
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2672
      utils.AddHostToEtcHosts(new_node.name)
2673

    
2674
    if new_node.secondary_ip != new_node.primary_ip:
2675
      result = self.rpc.call_node_has_ip_address(new_node.name,
2676
                                                 new_node.secondary_ip)
2677
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
2678
                   prereq=True)
2679
      if not result.payload:
2680
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2681
                                 " you gave (%s). Please fix and re-run this"
2682
                                 " command." % new_node.secondary_ip)
2683

    
2684
    node_verify_list = [self.cfg.GetMasterNode()]
2685
    node_verify_param = {
2686
      'nodelist': [node],
2687
      # TODO: do a node-net-test as well?
2688
    }
2689

    
2690
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2691
                                       self.cfg.GetClusterName())
2692
    for verifier in node_verify_list:
2693
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
2694
      nl_payload = result[verifier].payload['nodelist']
2695
      if nl_payload:
2696
        for failed in nl_payload:
2697
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2698
                      (verifier, nl_payload[failed]))
2699
        raise errors.OpExecError("ssh/hostname verification failed.")
2700

    
2701
    if self.op.readd:
2702
      _RedistributeAncillaryFiles(self)
2703
      self.context.ReaddNode(new_node)
2704
      # make sure we redistribute the config
2705
      self.cfg.Update(new_node)
2706
      # and make sure the new node will not have old files around
2707
      if not new_node.master_candidate:
2708
        result = self.rpc.call_node_demote_from_mc(new_node.name)
2709
        msg = result.RemoteFailMsg()
2710
        if msg:
2711
          self.LogWarning("Node failed to demote itself from master"
2712
                          " candidate status: %s" % msg)
2713
    else:
2714
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
2715
      self.context.AddNode(new_node)
2716

    
2717

    
2718
class LUSetNodeParams(LogicalUnit):
2719
  """Modifies the parameters of a node.
2720

2721
  """
2722
  HPATH = "node-modify"
2723
  HTYPE = constants.HTYPE_NODE
2724
  _OP_REQP = ["node_name"]
2725
  REQ_BGL = False
2726

    
2727
  def CheckArguments(self):
2728
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2729
    if node_name is None:
2730
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2731
    self.op.node_name = node_name
2732
    _CheckBooleanOpField(self.op, 'master_candidate')
2733
    _CheckBooleanOpField(self.op, 'offline')
2734
    _CheckBooleanOpField(self.op, 'drained')
2735
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
2736
    if all_mods.count(None) == 3:
2737
      raise errors.OpPrereqError("Please pass at least one modification")
2738
    if all_mods.count(True) > 1:
2739
      raise errors.OpPrereqError("Can't set the node into more than one"
2740
                                 " state at the same time")
2741

    
2742
  def ExpandNames(self):
2743
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2744

    
2745
  def BuildHooksEnv(self):
2746
    """Build hooks env.
2747

2748
    This runs on the master node.
2749

2750
    """
2751
    env = {
2752
      "OP_TARGET": self.op.node_name,
2753
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2754
      "OFFLINE": str(self.op.offline),
2755
      "DRAINED": str(self.op.drained),
2756
      }
2757
    nl = [self.cfg.GetMasterNode(),
2758
          self.op.node_name]
2759
    return env, nl, nl
2760

    
2761
  def CheckPrereq(self):
2762
    """Check prerequisites.
2763

2764
    This only checks the instance list against the existing names.
2765

2766
    """
2767
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2768

    
2769
    if ((self.op.master_candidate == False or self.op.offline == True or
2770
         self.op.drained == True) and node.master_candidate):
2771
      # we will demote the node from master_candidate
2772
      if self.op.node_name == self.cfg.GetMasterNode():
2773
        raise errors.OpPrereqError("The master node has to be a"
2774
                                   " master candidate, online and not drained")
2775
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2776
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2777
      if num_candidates <= cp_size:
2778
        msg = ("Not enough master candidates (desired"
2779
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2780
        if self.op.force:
2781
          self.LogWarning(msg)
2782
        else:
2783
          raise errors.OpPrereqError(msg)
2784

    
2785
    if (self.op.master_candidate == True and
2786
        ((node.offline and not self.op.offline == False) or
2787
         (node.drained and not self.op.drained == False))):
2788
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
2789
                                 " to master_candidate" % node.name)
2790

    
2791
    return
2792

    
2793
  def Exec(self, feedback_fn):
2794
    """Modifies a node.
2795

2796
    """
2797
    node = self.node
2798

    
2799
    result = []
2800
    changed_mc = False
2801

    
2802
    if self.op.offline is not None:
2803
      node.offline = self.op.offline
2804
      result.append(("offline", str(self.op.offline)))
2805
      if self.op.offline == True:
2806
        if node.master_candidate:
2807
          node.master_candidate = False
2808
          changed_mc = True
2809
          result.append(("master_candidate", "auto-demotion due to offline"))
2810
        if node.drained:
2811
          node.drained = False
2812
          result.append(("drained", "clear drained status due to offline"))
2813

    
2814
    if self.op.master_candidate is not None:
2815
      node.master_candidate = self.op.master_candidate
2816
      changed_mc = True
2817
      result.append(("master_candidate", str(self.op.master_candidate)))
2818
      if self.op.master_candidate == False:
2819
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2820
        msg = rrc.fail_msg
2821
        if msg:
2822
          self.LogWarning("Node failed to demote itself: %s" % msg)
2823

    
2824
    if self.op.drained is not None:
2825
      node.drained = self.op.drained
2826
      result.append(("drained", str(self.op.drained)))
2827
      if self.op.drained == True:
2828
        if node.master_candidate:
2829
          node.master_candidate = False
2830
          changed_mc = True
2831
          result.append(("master_candidate", "auto-demotion due to drain"))
2832
          rrc = self.rpc.call_node_demote_from_mc(node.name)
2833
          msg = rrc.RemoteFailMsg()
2834
          if msg:
2835
            self.LogWarning("Node failed to demote itself: %s" % msg)
2836
        if node.offline:
2837
          node.offline = False
2838
          result.append(("offline", "clear offline status due to drain"))
2839

    
2840
    # this will trigger configuration file update, if needed
2841
    self.cfg.Update(node)
2842
    # this will trigger job queue propagation or cleanup
2843
    if changed_mc:
2844
      self.context.ReaddNode(node)
2845

    
2846
    return result
2847

    
2848

    
2849
class LUPowercycleNode(NoHooksLU):
2850
  """Powercycles a node.
2851

2852
  """
2853
  _OP_REQP = ["node_name", "force"]
2854
  REQ_BGL = False
2855

    
2856
  def CheckArguments(self):
2857
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2858
    if node_name is None:
2859
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2860
    self.op.node_name = node_name
2861
    if node_name == self.cfg.GetMasterNode() and not self.op.force:
2862
      raise errors.OpPrereqError("The node is the master and the force"
2863
                                 " parameter was not set")
2864

    
2865
  def ExpandNames(self):
2866
    """Locking for PowercycleNode.
2867

2868
    This is a last-resort option and shouldn't block on other
2869
    jobs. Therefore, we grab no locks.
2870

2871
    """
2872
    self.needed_locks = {}
2873

    
2874
  def CheckPrereq(self):
2875
    """Check prerequisites.
2876

2877
    This LU has no prereqs.
2878

2879
    """
2880
    pass
2881

    
2882
  def Exec(self, feedback_fn):
2883
    """Reboots a node.
2884

2885
    """
2886
    result = self.rpc.call_node_powercycle(self.op.node_name,
2887
                                           self.cfg.GetHypervisorType())
2888
    result.Raise("Failed to schedule the reboot")
2889
    return result.payload
2890

    
2891

    
2892
class LUQueryClusterInfo(NoHooksLU):
2893
  """Query cluster configuration.
2894

2895
  """
2896
  _OP_REQP = []
2897
  REQ_BGL = False
2898

    
2899
  def ExpandNames(self):
2900
    self.needed_locks = {}
2901

    
2902
  def CheckPrereq(self):
2903
    """No prerequsites needed for this LU.
2904

2905
    """
2906
    pass
2907

    
2908
  def Exec(self, feedback_fn):
2909
    """Return cluster config.
2910

2911
    """
2912
    cluster = self.cfg.GetClusterInfo()
2913
    result = {
2914
      "software_version": constants.RELEASE_VERSION,
2915
      "protocol_version": constants.PROTOCOL_VERSION,
2916
      "config_version": constants.CONFIG_VERSION,
2917
      "os_api_version": max(constants.OS_API_VERSIONS),
2918
      "export_version": constants.EXPORT_VERSION,
2919
      "architecture": (platform.architecture()[0], platform.machine()),
2920
      "name": cluster.cluster_name,
2921
      "master": cluster.master_node,
2922
      "default_hypervisor": cluster.enabled_hypervisors[0],
2923
      "enabled_hypervisors": cluster.enabled_hypervisors,
2924
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
2925
                        for hypervisor_name in cluster.enabled_hypervisors]),
2926
      "beparams": cluster.beparams,
2927
      "nicparams": cluster.nicparams,
2928
      "candidate_pool_size": cluster.candidate_pool_size,
2929
      "master_netdev": cluster.master_netdev,
2930
      "volume_group_name": cluster.volume_group_name,
2931
      "file_storage_dir": cluster.file_storage_dir,
2932
      }
2933

    
2934
    return result
2935

    
2936

    
2937
class LUQueryConfigValues(NoHooksLU):
2938
  """Return configuration values.
2939

2940
  """
2941
  _OP_REQP = []
2942
  REQ_BGL = False
2943
  _FIELDS_DYNAMIC = utils.FieldSet()
2944
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2945

    
2946
  def ExpandNames(self):
2947
    self.needed_locks = {}
2948

    
2949
    _CheckOutputFields(static=self._FIELDS_STATIC,
2950
                       dynamic=self._FIELDS_DYNAMIC,
2951
                       selected=self.op.output_fields)
2952

    
2953
  def CheckPrereq(self):
2954
    """No prerequisites.
2955

2956
    """
2957
    pass
2958

    
2959
  def Exec(self, feedback_fn):
2960
    """Dump a representation of the cluster config to the standard output.
2961

2962
    """
2963
    values = []
2964
    for field in self.op.output_fields:
2965
      if field == "cluster_name":
2966
        entry = self.cfg.GetClusterName()
2967
      elif field == "master_node":
2968
        entry = self.cfg.GetMasterNode()
2969
      elif field == "drain_flag":
2970
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2971
      else:
2972
        raise errors.ParameterError(field)
2973
      values.append(entry)
2974
    return values
2975

    
2976

    
2977
class LUActivateInstanceDisks(NoHooksLU):
2978
  """Bring up an instance's disks.
2979

2980
  """
2981
  _OP_REQP = ["instance_name"]
2982
  REQ_BGL = False
2983

    
2984
  def ExpandNames(self):
2985
    self._ExpandAndLockInstance()
2986
    self.needed_locks[locking.LEVEL_NODE] = []
2987
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2988

    
2989
  def DeclareLocks(self, level):
2990
    if level == locking.LEVEL_NODE:
2991
      self._LockInstancesNodes()
2992

    
2993
  def CheckPrereq(self):
2994
    """Check prerequisites.
2995

2996
    This checks that the instance is in the cluster.
2997

2998
    """
2999
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3000
    assert self.instance is not None, \
3001
      "Cannot retrieve locked instance %s" % self.op.instance_name
3002
    _CheckNodeOnline(self, self.instance.primary_node)
3003

    
3004
  def Exec(self, feedback_fn):
3005
    """Activate the disks.
3006

3007
    """
3008
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
3009
    if not disks_ok:
3010
      raise errors.OpExecError("Cannot activate block devices")
3011

    
3012
    return disks_info
3013

    
3014

    
3015
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
3016
  """Prepare the block devices for an instance.
3017

3018
  This sets up the block devices on all nodes.
3019

3020
  @type lu: L{LogicalUnit}
3021
  @param lu: the logical unit on whose behalf we execute
3022
  @type instance: L{objects.Instance}
3023
  @param instance: the instance for whose disks we assemble
3024
  @type ignore_secondaries: boolean
3025
  @param ignore_secondaries: if true, errors on secondary nodes
3026
      won't result in an error return from the function
3027
  @return: False if the operation failed, otherwise a list of
3028
      (host, instance_visible_name, node_visible_name)
3029
      with the mapping from node devices to instance devices
3030

3031
  """
3032
  device_info = []
3033
  disks_ok = True
3034
  iname = instance.name
3035
  # With the two passes mechanism we try to reduce the window of
3036
  # opportunity for the race condition of switching DRBD to primary
3037
  # before handshaking occured, but we do not eliminate it
3038

    
3039
  # The proper fix would be to wait (with some limits) until the
3040
  # connection has been made and drbd transitions from WFConnection
3041
  # into any other network-connected state (Connected, SyncTarget,
3042
  # SyncSource, etc.)
3043

    
3044
  # 1st pass, assemble on all nodes in secondary mode
3045
  for inst_disk in instance.disks:
3046
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3047
      lu.cfg.SetDiskID(node_disk, node)
3048
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3049
      msg = result.fail_msg
3050
      if msg:
3051
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3052
                           " (is_primary=False, pass=1): %s",
3053
                           inst_disk.iv_name, node, msg)
3054
        if not ignore_secondaries:
3055
          disks_ok = False
3056

    
3057
  # FIXME: race condition on drbd migration to primary
3058

    
3059
  # 2nd pass, do only the primary node
3060
  for inst_disk in instance.disks:
3061
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3062
      if node != instance.primary_node:
3063
        continue
3064
      lu.cfg.SetDiskID(node_disk, node)
3065
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3066
      msg = result.fail_msg
3067
      if msg:
3068
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3069
                           " (is_primary=True, pass=2): %s",
3070
                           inst_disk.iv_name, node, msg)
3071
        disks_ok = False
3072
    device_info.append((instance.primary_node, inst_disk.iv_name,
3073
                        result.payload))
3074

    
3075
  # leave the disks configured for the primary node
3076
  # this is a workaround that would be fixed better by
3077
  # improving the logical/physical id handling
3078
  for disk in instance.disks:
3079
    lu.cfg.SetDiskID(disk, instance.primary_node)
3080

    
3081
  return disks_ok, device_info
3082

    
3083

    
3084
def _StartInstanceDisks(lu, instance, force):
3085
  """Start the disks of an instance.
3086

3087
  """
3088
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3089
                                           ignore_secondaries=force)
3090
  if not disks_ok:
3091
    _ShutdownInstanceDisks(lu, instance)
3092
    if force is not None and not force:
3093
      lu.proc.LogWarning("", hint="If the message above refers to a"
3094
                         " secondary node,"
3095
                         " you can retry the operation using '--force'.")
3096
    raise errors.OpExecError("Disk consistency error")
3097

    
3098

    
3099
class LUDeactivateInstanceDisks(NoHooksLU):
3100
  """Shutdown an instance's disks.
3101

3102
  """
3103
  _OP_REQP = ["instance_name"]
3104
  REQ_BGL = False
3105

    
3106
  def ExpandNames(self):
3107
    self._ExpandAndLockInstance()
3108
    self.needed_locks[locking.LEVEL_NODE] = []
3109
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3110

    
3111
  def DeclareLocks(self, level):
3112
    if level == locking.LEVEL_NODE:
3113
      self._LockInstancesNodes()
3114

    
3115
  def CheckPrereq(self):
3116
    """Check prerequisites.
3117

3118
    This checks that the instance is in the cluster.
3119

3120
    """
3121
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3122
    assert self.instance is not None, \
3123
      "Cannot retrieve locked instance %s" % self.op.instance_name
3124

    
3125
  def Exec(self, feedback_fn):
3126
    """Deactivate the disks
3127

3128
    """
3129
    instance = self.instance
3130
    _SafeShutdownInstanceDisks(self, instance)
3131

    
3132

    
3133
def _SafeShutdownInstanceDisks(lu, instance):
3134
  """Shutdown block devices of an instance.
3135

3136
  This function checks if an instance is running, before calling
3137
  _ShutdownInstanceDisks.
3138

3139
  """
3140
  pnode = instance.primary_node
3141
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
3142
  ins_l.Raise("Can't contact node %s" % pnode)
3143

    
3144
  if instance.name in ins_l.payload:
3145
    raise errors.OpExecError("Instance is running, can't shutdown"
3146
                             " block devices.")
3147

    
3148
  _ShutdownInstanceDisks(lu, instance)
3149

    
3150

    
3151
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3152
  """Shutdown block devices of an instance.
3153

3154
  This does the shutdown on all nodes of the instance.
3155

3156
  If the ignore_primary is false, errors on the primary node are
3157
  ignored.
3158

3159
  """
3160
  all_result = True
3161
  for disk in instance.disks:
3162
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3163
      lu.cfg.SetDiskID(top_disk, node)
3164
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3165
      msg = result.fail_msg
3166
      if msg:
3167
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3168
                      disk.iv_name, node, msg)
3169
        if not ignore_primary or node != instance.primary_node:
3170
          all_result = False
3171
  return all_result
3172

    
3173

    
3174
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3175
  """Checks if a node has enough free memory.
3176

3177
  This function check if a given node has the needed amount of free
3178
  memory. In case the node has less memory or we cannot get the
3179
  information from the node, this function raise an OpPrereqError
3180
  exception.
3181

3182
  @type lu: C{LogicalUnit}
3183
  @param lu: a logical unit from which we get configuration data
3184
  @type node: C{str}
3185
  @param node: the node to check
3186
  @type reason: C{str}
3187
  @param reason: string to use in the error message
3188
  @type requested: C{int}
3189
  @param requested: the amount of memory in MiB to check for
3190
  @type hypervisor_name: C{str}
3191
  @param hypervisor_name: the hypervisor to ask for memory stats
3192
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3193
      we cannot check the node
3194

3195
  """
3196
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3197
  nodeinfo[node].Raise("Can't get data from node %s" % node, prereq=True)
3198
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3199
  if not isinstance(free_mem, int):
3200
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3201
                               " was '%s'" % (node, free_mem))
3202
  if requested > free_mem:
3203
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3204
                               " needed %s MiB, available %s MiB" %
3205
                               (node, reason, requested, free_mem))
3206

    
3207

    
3208
class LUStartupInstance(LogicalUnit):
3209
  """Starts an instance.
3210

3211
  """
3212
  HPATH = "instance-start"
3213
  HTYPE = constants.HTYPE_INSTANCE
3214
  _OP_REQP = ["instance_name", "force"]
3215
  REQ_BGL = False
3216

    
3217
  def ExpandNames(self):
3218
    self._ExpandAndLockInstance()
3219

    
3220
  def BuildHooksEnv(self):
3221
    """Build hooks env.
3222

3223
    This runs on master, primary and secondary nodes of the instance.
3224

3225
    """
3226
    env = {
3227
      "FORCE": self.op.force,
3228
      }
3229
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3230
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3231
    return env, nl, nl
3232

    
3233
  def CheckPrereq(self):
3234
    """Check prerequisites.
3235

3236
    This checks that the instance is in the cluster.
3237

3238
    """
3239
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3240
    assert self.instance is not None, \
3241
      "Cannot retrieve locked instance %s" % self.op.instance_name
3242

    
3243
    # extra beparams
3244
    self.beparams = getattr(self.op, "beparams", {})
3245
    if self.beparams:
3246
      if not isinstance(self.beparams, dict):
3247
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3248
                                   " dict" % (type(self.beparams), ))
3249
      # fill the beparams dict
3250
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3251
      self.op.beparams = self.beparams
3252

    
3253
    # extra hvparams
3254
    self.hvparams = getattr(self.op, "hvparams", {})
3255
    if self.hvparams:
3256
      if not isinstance(self.hvparams, dict):
3257
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3258
                                   " dict" % (type(self.hvparams), ))
3259

    
3260
      # check hypervisor parameter syntax (locally)
3261
      cluster = self.cfg.GetClusterInfo()
3262
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3263
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
3264
                                    instance.hvparams)
3265
      filled_hvp.update(self.hvparams)
3266
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3267
      hv_type.CheckParameterSyntax(filled_hvp)
3268
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3269
      self.op.hvparams = self.hvparams
3270

    
3271
    _CheckNodeOnline(self, instance.primary_node)
3272

    
3273
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3274
    # check bridges existence
3275
    _CheckInstanceBridgesExist(self, instance)
3276

    
3277
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3278
                                              instance.name,
3279
                                              instance.hypervisor)
3280
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3281
                      prereq=True)
3282
    if not remote_info.payload: # not running already
3283
      _CheckNodeFreeMemory(self, instance.primary_node,
3284
                           "starting instance %s" % instance.name,
3285
                           bep[constants.BE_MEMORY], instance.hypervisor)
3286

    
3287
  def Exec(self, feedback_fn):
3288
    """Start the instance.
3289

3290
    """
3291
    instance = self.instance
3292
    force = self.op.force
3293

    
3294
    self.cfg.MarkInstanceUp(instance.name)
3295

    
3296
    node_current = instance.primary_node
3297

    
3298
    _StartInstanceDisks(self, instance, force)
3299

    
3300
    result = self.rpc.call_instance_start(node_current, instance,
3301
                                          self.hvparams, self.beparams)
3302
    msg = result.fail_msg
3303
    if msg:
3304
      _ShutdownInstanceDisks(self, instance)
3305
      raise errors.OpExecError("Could not start instance: %s" % msg)
3306

    
3307

    
3308
class LURebootInstance(LogicalUnit):
3309
  """Reboot an instance.
3310

3311
  """
3312
  HPATH = "instance-reboot"
3313
  HTYPE = constants.HTYPE_INSTANCE
3314
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3315
  REQ_BGL = False
3316

    
3317
  def ExpandNames(self):
3318
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3319
                                   constants.INSTANCE_REBOOT_HARD,
3320
                                   constants.INSTANCE_REBOOT_FULL]:
3321
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3322
                                  (constants.INSTANCE_REBOOT_SOFT,
3323
                                   constants.INSTANCE_REBOOT_HARD,
3324
                                   constants.INSTANCE_REBOOT_FULL))
3325
    self._ExpandAndLockInstance()
3326

    
3327
  def BuildHooksEnv(self):
3328
    """Build hooks env.
3329

3330
    This runs on master, primary and secondary nodes of the instance.
3331

3332
    """
3333
    env = {
3334
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3335
      "REBOOT_TYPE": self.op.reboot_type,
3336
      }
3337
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3338
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3339
    return env, nl, nl
3340

    
3341
  def CheckPrereq(self):
3342
    """Check prerequisites.
3343

3344
    This checks that the instance is in the cluster.
3345

3346
    """
3347
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3348
    assert self.instance is not None, \
3349
      "Cannot retrieve locked instance %s" % self.op.instance_name
3350

    
3351
    _CheckNodeOnline(self, instance.primary_node)
3352

    
3353
    # check bridges existence
3354
    _CheckInstanceBridgesExist(self, instance)
3355

    
3356
  def Exec(self, feedback_fn):
3357
    """Reboot the instance.
3358

3359
    """
3360
    instance = self.instance
3361
    ignore_secondaries = self.op.ignore_secondaries
3362
    reboot_type = self.op.reboot_type
3363

    
3364
    node_current = instance.primary_node
3365

    
3366
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3367
                       constants.INSTANCE_REBOOT_HARD]:
3368
      for disk in instance.disks:
3369
        self.cfg.SetDiskID(disk, node_current)
3370
      result = self.rpc.call_instance_reboot(node_current, instance,
3371
                                             reboot_type)
3372
      result.Raise("Could not reboot instance")
3373
    else:
3374
      result = self.rpc.call_instance_shutdown(node_current, instance)
3375
      result.Raise("Could not shutdown instance for full reboot")
3376
      _ShutdownInstanceDisks(self, instance)
3377
      _StartInstanceDisks(self, instance, ignore_secondaries)
3378
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3379
      msg = result.fail_msg
3380
      if msg:
3381
        _ShutdownInstanceDisks(self, instance)
3382
        raise errors.OpExecError("Could not start instance for"
3383
                                 " full reboot: %s" % msg)
3384

    
3385
    self.cfg.MarkInstanceUp(instance.name)
3386

    
3387

    
3388
class LUShutdownInstance(LogicalUnit):
3389
  """Shutdown an instance.
3390

3391
  """
3392
  HPATH = "instance-stop"
3393
  HTYPE = constants.HTYPE_INSTANCE
3394
  _OP_REQP = ["instance_name"]
3395
  REQ_BGL = False
3396

    
3397
  def ExpandNames(self):
3398
    self._ExpandAndLockInstance()
3399

    
3400
  def BuildHooksEnv(self):
3401
    """Build hooks env.
3402

3403
    This runs on master, primary and secondary nodes of the instance.
3404

3405
    """
3406
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3407
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3408
    return env, nl, nl
3409

    
3410
  def CheckPrereq(self):
3411
    """Check prerequisites.
3412

3413
    This checks that the instance is in the cluster.
3414

3415
    """
3416
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3417
    assert self.instance is not None, \
3418
      "Cannot retrieve locked instance %s" % self.op.instance_name
3419
    _CheckNodeOnline(self, self.instance.primary_node)
3420

    
3421
  def Exec(self, feedback_fn):
3422
    """Shutdown the instance.
3423

3424
    """
3425
    instance = self.instance
3426
    node_current = instance.primary_node
3427
    self.cfg.MarkInstanceDown(instance.name)
3428
    result = self.rpc.call_instance_shutdown(node_current, instance)
3429
    msg = result.fail_msg
3430
    if msg:
3431
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
3432

    
3433
    _ShutdownInstanceDisks(self, instance)
3434

    
3435

    
3436
class LUReinstallInstance(LogicalUnit):
3437
  """Reinstall an instance.
3438

3439
  """
3440
  HPATH = "instance-reinstall"
3441
  HTYPE = constants.HTYPE_INSTANCE
3442
  _OP_REQP = ["instance_name"]
3443
  REQ_BGL = False
3444

    
3445
  def ExpandNames(self):
3446
    self._ExpandAndLockInstance()
3447

    
3448
  def BuildHooksEnv(self):
3449
    """Build hooks env.
3450

3451
    This runs on master, primary and secondary nodes of the instance.
3452

3453
    """
3454
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3455
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3456
    return env, nl, nl
3457

    
3458
  def CheckPrereq(self):
3459
    """Check prerequisites.
3460

3461
    This checks that the instance is in the cluster and is not running.
3462

3463
    """
3464
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3465
    assert instance is not None, \
3466
      "Cannot retrieve locked instance %s" % self.op.instance_name
3467
    _CheckNodeOnline(self, instance.primary_node)
3468

    
3469
    if instance.disk_template == constants.DT_DISKLESS:
3470
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3471
                                 self.op.instance_name)
3472
    if instance.admin_up:
3473
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3474
                                 self.op.instance_name)
3475
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3476
                                              instance.name,
3477
                                              instance.hypervisor)
3478
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3479
                      prereq=True)
3480
    if remote_info.payload:
3481
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3482
                                 (self.op.instance_name,
3483
                                  instance.primary_node))
3484

    
3485
    self.op.os_type = getattr(self.op, "os_type", None)
3486
    if self.op.os_type is not None:
3487
      # OS verification
3488
      pnode = self.cfg.GetNodeInfo(
3489
        self.cfg.ExpandNodeName(instance.primary_node))
3490
      if pnode is None:
3491
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
3492
                                   self.op.pnode)
3493
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
3494
      result.Raise("OS '%s' not in supported OS list for primary node %s" %
3495
                   (self.op.os_type, pnode.name), prereq=True)
3496

    
3497
    self.instance = instance
3498

    
3499
  def Exec(self, feedback_fn):
3500
    """Reinstall the instance.
3501

3502
    """
3503
    inst = self.instance
3504

    
3505
    if self.op.os_type is not None:
3506
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
3507
      inst.os = self.op.os_type
3508
      self.cfg.Update(inst)
3509

    
3510
    _StartInstanceDisks(self, inst, None)
3511
    try:
3512
      feedback_fn("Running the instance OS create scripts...")
3513
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True)
3514
      result.Raise("Could not install OS for instance %s on node %s" %
3515
                   (inst.name, inst.primary_node))
3516
    finally:
3517
      _ShutdownInstanceDisks(self, inst)
3518

    
3519

    
3520
class LURenameInstance(LogicalUnit):
3521
  """Rename an instance.
3522

3523
  """
3524
  HPATH = "instance-rename"
3525
  HTYPE = constants.HTYPE_INSTANCE
3526
  _OP_REQP = ["instance_name", "new_name"]
3527

    
3528
  def BuildHooksEnv(self):
3529
    """Build hooks env.
3530

3531
    This runs on master, primary and secondary nodes of the instance.
3532

3533
    """
3534
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3535
    env["INSTANCE_NEW_NAME"] = self.op.new_name
3536
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3537
    return env, nl, nl
3538

    
3539
  def CheckPrereq(self):
3540
    """Check prerequisites.
3541

3542
    This checks that the instance is in the cluster and is not running.
3543

3544
    """
3545
    instance = self.cfg.GetInstanceInfo(
3546
      self.cfg.ExpandInstanceName(self.op.instance_name))
3547
    if instance is None:
3548
      raise errors.OpPrereqError("Instance '%s' not known" %
3549
                                 self.op.instance_name)
3550
    _CheckNodeOnline(self, instance.primary_node)
3551

    
3552
    if instance.admin_up:
3553
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3554
                                 self.op.instance_name)
3555
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3556
                                              instance.name,
3557
                                              instance.hypervisor)
3558
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3559
                      prereq=True)
3560
    if remote_info.payload:
3561
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3562
                                 (self.op.instance_name,
3563
                                  instance.primary_node))
3564
    self.instance = instance
3565

    
3566
    # new name verification
3567
    name_info = utils.HostInfo(self.op.new_name)
3568

    
3569
    self.op.new_name = new_name = name_info.name
3570
    instance_list = self.cfg.GetInstanceList()
3571
    if new_name in instance_list:
3572
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3573
                                 new_name)
3574

    
3575
    if not getattr(self.op, "ignore_ip", False):
3576
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
3577
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3578
                                   (name_info.ip, new_name))
3579

    
3580

    
3581
  def Exec(self, feedback_fn):
3582
    """Reinstall the instance.
3583

3584
    """
3585
    inst = self.instance
3586
    old_name = inst.name
3587

    
3588
    if inst.disk_template == constants.DT_FILE:
3589
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3590

    
3591
    self.cfg.RenameInstance(inst.name, self.op.new_name)
3592
    # Change the instance lock. This is definitely safe while we hold the BGL
3593
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
3594
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
3595

    
3596
    # re-read the instance from the configuration after rename
3597
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
3598

    
3599
    if inst.disk_template == constants.DT_FILE:
3600
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
3601
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
3602
                                                     old_file_storage_dir,
3603
                                                     new_file_storage_dir)
3604
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
3605
                   " (but the instance has been renamed in Ganeti)" %
3606
                   (inst.primary_node, old_file_storage_dir,
3607
                    new_file_storage_dir))
3608

    
3609
    _StartInstanceDisks(self, inst, None)
3610
    try:
3611
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
3612
                                                 old_name)
3613
      msg = result.fail_msg
3614
      if msg:
3615
        msg = ("Could not run OS rename script for instance %s on node %s"
3616
               " (but the instance has been renamed in Ganeti): %s" %
3617
               (inst.name, inst.primary_node, msg))
3618
        self.proc.LogWarning(msg)
3619
    finally:
3620
      _ShutdownInstanceDisks(self, inst)
3621

    
3622

    
3623
class LURemoveInstance(LogicalUnit):
3624
  """Remove an instance.
3625

3626
  """
3627
  HPATH = "instance-remove"
3628
  HTYPE = constants.HTYPE_INSTANCE
3629
  _OP_REQP = ["instance_name", "ignore_failures"]
3630
  REQ_BGL = False
3631

    
3632
  def ExpandNames(self):
3633
    self._ExpandAndLockInstance()
3634
    self.needed_locks[locking.LEVEL_NODE] = []
3635
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3636

    
3637
  def DeclareLocks(self, level):
3638
    if level == locking.LEVEL_NODE:
3639
      self._LockInstancesNodes()
3640

    
3641
  def BuildHooksEnv(self):
3642
    """Build hooks env.
3643

3644
    This runs on master, primary and secondary nodes of the instance.
3645

3646
    """
3647
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3648
    nl = [self.cfg.GetMasterNode()]
3649
    return env, nl, nl
3650

    
3651
  def CheckPrereq(self):
3652
    """Check prerequisites.
3653

3654
    This checks that the instance is in the cluster.
3655

3656
    """
3657
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3658
    assert self.instance is not None, \
3659
      "Cannot retrieve locked instance %s" % self.op.instance_name
3660

    
3661
  def Exec(self, feedback_fn):
3662
    """Remove the instance.
3663

3664
    """
3665
    instance = self.instance
3666
    logging.info("Shutting down instance %s on node %s",
3667
                 instance.name, instance.primary_node)
3668

    
3669
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3670
    msg = result.fail_msg
3671
    if msg:
3672
      if self.op.ignore_failures:
3673
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
3674
      else:
3675
        raise errors.OpExecError("Could not shutdown instance %s on"
3676
                                 " node %s: %s" %
3677
                                 (instance.name, instance.primary_node, msg))
3678

    
3679
    logging.info("Removing block devices for instance %s", instance.name)
3680

    
3681
    if not _RemoveDisks(self, instance):
3682
      if self.op.ignore_failures:
3683
        feedback_fn("Warning: can't remove instance's disks")
3684
      else:
3685
        raise errors.OpExecError("Can't remove instance's disks")
3686

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

    
3689
    self.cfg.RemoveInstance(instance.name)
3690
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3691

    
3692

    
3693
class LUQueryInstances(NoHooksLU):
3694
  """Logical unit for querying instances.
3695

3696
  """
3697
  _OP_REQP = ["output_fields", "names", "use_locking"]
3698
  REQ_BGL = False
3699
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3700
                                    "admin_state",
3701
                                    "disk_template", "ip", "mac", "bridge",
3702
                                    "nic_mode", "nic_link",
3703
                                    "sda_size", "sdb_size", "vcpus", "tags",
3704
                                    "network_port", "beparams",
3705
                                    r"(disk)\.(size)/([0-9]+)",
3706
                                    r"(disk)\.(sizes)", "disk_usage",
3707
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
3708
                                    r"(nic)\.(bridge)/([0-9]+)",
3709
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
3710
                                    r"(disk|nic)\.(count)",
3711
                                    "serial_no", "hypervisor", "hvparams",] +
3712
                                  ["hv/%s" % name
3713
                                   for name in constants.HVS_PARAMETERS] +
3714
                                  ["be/%s" % name
3715
                                   for name in constants.BES_PARAMETERS])
3716
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3717

    
3718

    
3719
  def ExpandNames(self):
3720
    _CheckOutputFields(static=self._FIELDS_STATIC,
3721
                       dynamic=self._FIELDS_DYNAMIC,
3722
                       selected=self.op.output_fields)
3723

    
3724
    self.needed_locks = {}
3725
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3726
    self.share_locks[locking.LEVEL_NODE] = 1
3727

    
3728
    if self.op.names:
3729
      self.wanted = _GetWantedInstances(self, self.op.names)
3730
    else:
3731
      self.wanted = locking.ALL_SET
3732

    
3733
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3734
    self.do_locking = self.do_node_query and self.op.use_locking
3735
    if self.do_locking:
3736
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3737
      self.needed_locks[locking.LEVEL_NODE] = []
3738
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3739

    
3740
  def DeclareLocks(self, level):
3741
    if level == locking.LEVEL_NODE and self.do_locking:
3742
      self._LockInstancesNodes()
3743

    
3744
  def CheckPrereq(self):
3745
    """Check prerequisites.
3746

3747
    """
3748
    pass
3749

    
3750
  def Exec(self, feedback_fn):
3751
    """Computes the list of nodes and their attributes.
3752

3753
    """
3754
    all_info = self.cfg.GetAllInstancesInfo()
3755
    if self.wanted == locking.ALL_SET:
3756
      # caller didn't specify instance names, so ordering is not important
3757
      if self.do_locking:
3758
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3759
      else:
3760
        instance_names = all_info.keys()
3761
      instance_names = utils.NiceSort(instance_names)
3762
    else:
3763
      # caller did specify names, so we must keep the ordering
3764
      if self.do_locking:
3765
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
3766
      else:
3767
        tgt_set = all_info.keys()
3768
      missing = set(self.wanted).difference(tgt_set)
3769
      if missing:
3770
        raise errors.OpExecError("Some instances were removed before"
3771
                                 " retrieving their data: %s" % missing)
3772
      instance_names = self.wanted
3773

    
3774
    instance_list = [all_info[iname] for iname in instance_names]
3775

    
3776
    # begin data gathering
3777

    
3778
    nodes = frozenset([inst.primary_node for inst in instance_list])
3779
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3780

    
3781
    bad_nodes = []
3782
    off_nodes = []
3783
    if self.do_node_query:
3784
      live_data = {}
3785
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3786
      for name in nodes:
3787
        result = node_data[name]
3788
        if result.offline:
3789
          # offline nodes will be in both lists
3790
          off_nodes.append(name)
3791
        if result.failed or result.fail_msg:
3792
          bad_nodes.append(name)
3793
        else:
3794
          if result.payload:
3795
            live_data.update(result.payload)
3796
          # else no instance is alive
3797
    else:
3798
      live_data = dict([(name, {}) for name in instance_names])
3799

    
3800
    # end data gathering
3801

    
3802
    HVPREFIX = "hv/"
3803
    BEPREFIX = "be/"
3804
    output = []
3805
    cluster = self.cfg.GetClusterInfo()
3806
    for instance in instance_list:
3807
      iout = []
3808
      i_hv = cluster.FillHV(instance)
3809
      i_be = cluster.FillBE(instance)
3810
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
3811
                                 nic.nicparams) for nic in instance.nics]
3812
      for field in self.op.output_fields:
3813
        st_match = self._FIELDS_STATIC.Matches(field)
3814
        if field == "name":
3815
          val = instance.name
3816
        elif field == "os":
3817
          val = instance.os
3818
        elif field == "pnode":
3819
          val = instance.primary_node
3820
        elif field == "snodes":
3821
          val = list(instance.secondary_nodes)
3822
        elif field == "admin_state":
3823
          val = instance.admin_up
3824
        elif field == "oper_state":
3825
          if instance.primary_node in bad_nodes:
3826
            val = None
3827
          else:
3828
            val = bool(live_data.get(instance.name))
3829
        elif field == "status":
3830
          if instance.primary_node in off_nodes:
3831
            val = "ERROR_nodeoffline"
3832
          elif instance.primary_node in bad_nodes:
3833
            val = "ERROR_nodedown"
3834
          else:
3835
            running = bool(live_data.get(instance.name))
3836
            if running:
3837
              if instance.admin_up:
3838
                val = "running"
3839
              else:
3840
                val = "ERROR_up"
3841
            else:
3842
              if instance.admin_up:
3843
                val = "ERROR_down"
3844
              else:
3845
                val = "ADMIN_down"
3846
        elif field == "oper_ram":
3847
          if instance.primary_node in bad_nodes:
3848
            val = None
3849
          elif instance.name in live_data:
3850
            val = live_data[instance.name].get("memory", "?")
3851
          else:
3852
            val = "-"
3853
        elif field == "vcpus":
3854
          val = i_be[constants.BE_VCPUS]
3855
        elif field == "disk_template":
3856
          val = instance.disk_template
3857
        elif field == "ip":
3858
          if instance.nics:
3859
            val = instance.nics[0].ip
3860
          else:
3861
            val = None
3862
        elif field == "nic_mode":
3863
          if instance.nics:
3864
            val = i_nicp[0][constants.NIC_MODE]
3865
          else:
3866
            val = None
3867
        elif field == "nic_link":
3868
          if instance.nics:
3869
            val = i_nicp[0][constants.NIC_LINK]
3870
          else:
3871
            val = None
3872
        elif field == "bridge":
3873
          if (instance.nics and
3874
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
3875
            val = i_nicp[0][constants.NIC_LINK]
3876
          else:
3877
            val = None
3878
        elif field == "mac":
3879
          if instance.nics:
3880
            val = instance.nics[0].mac
3881
          else:
3882
            val = None
3883
        elif field == "sda_size" or field == "sdb_size":
3884
          idx = ord(field[2]) - ord('a')
3885
          try:
3886
            val = instance.FindDisk(idx).size
3887
          except errors.OpPrereqError:
3888
            val = None
3889
        elif field == "disk_usage": # total disk usage per node
3890
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
3891
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
3892
        elif field == "tags":
3893
          val = list(instance.GetTags())
3894
        elif field == "serial_no":
3895
          val = instance.serial_no
3896
        elif field == "network_port":
3897
          val = instance.network_port
3898
        elif field == "hypervisor":
3899
          val = instance.hypervisor
3900
        elif field == "hvparams":
3901
          val = i_hv
3902
        elif (field.startswith(HVPREFIX) and
3903
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
3904
          val = i_hv.get(field[len(HVPREFIX):], None)
3905
        elif field == "beparams":
3906
          val = i_be
3907
        elif (field.startswith(BEPREFIX) and
3908
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
3909
          val = i_be.get(field[len(BEPREFIX):], None)
3910
        elif st_match and st_match.groups():
3911
          # matches a variable list
3912
          st_groups = st_match.groups()
3913
          if st_groups and st_groups[0] == "disk":
3914
            if st_groups[1] == "count":
3915
              val = len(instance.disks)
3916
            elif st_groups[1] == "sizes":
3917
              val = [disk.size for disk in instance.disks]
3918
            elif st_groups[1] == "size":
3919
              try:
3920
                val = instance.FindDisk(st_groups[2]).size
3921
              except errors.OpPrereqError:
3922
                val = None
3923
            else:
3924
              assert False, "Unhandled disk parameter"
3925
          elif st_groups[0] == "nic":
3926
            if st_groups[1] == "count":
3927
              val = len(instance.nics)
3928
            elif st_groups[1] == "macs":
3929
              val = [nic.mac for nic in instance.nics]
3930
            elif st_groups[1] == "ips":
3931
              val = [nic.ip for nic in instance.nics]
3932
            elif st_groups[1] == "modes":
3933
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
3934
            elif st_groups[1] == "links":
3935
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
3936
            elif st_groups[1] == "bridges":
3937
              val = []
3938
              for nicp in i_nicp:
3939
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
3940
                  val.append(nicp[constants.NIC_LINK])
3941
                else:
3942
                  val.append(None)
3943
            else:
3944
              # index-based item
3945
              nic_idx = int(st_groups[2])
3946
              if nic_idx >= len(instance.nics):
3947
                val = None
3948
              else:
3949
                if st_groups[1] == "mac":
3950
                  val = instance.nics[nic_idx].mac
3951
                elif st_groups[1] == "ip":
3952
                  val = instance.nics[nic_idx].ip
3953
                elif st_groups[1] == "mode":
3954
                  val = i_nicp[nic_idx][constants.NIC_MODE]
3955
                elif st_groups[1] == "link":
3956
                  val = i_nicp[nic_idx][constants.NIC_LINK]
3957
                elif st_groups[1] == "bridge":
3958
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
3959
                  if nic_mode == constants.NIC_MODE_BRIDGED:
3960
                    val = i_nicp[nic_idx][constants.NIC_LINK]
3961
                  else:
3962
                    val = None
3963
                else:
3964
                  assert False, "Unhandled NIC parameter"
3965
          else:
3966
            assert False, ("Declared but unhandled variable parameter '%s'" %
3967
                           field)
3968
        else:
3969
          assert False, "Declared but unhandled parameter '%s'" % field
3970
        iout.append(val)
3971
      output.append(iout)
3972

    
3973
    return output
3974

    
3975

    
3976
class LUFailoverInstance(LogicalUnit):
3977
  """Failover an instance.
3978

3979
  """
3980
  HPATH = "instance-failover"
3981
  HTYPE = constants.HTYPE_INSTANCE
3982
  _OP_REQP = ["instance_name", "ignore_consistency"]
3983
  REQ_BGL = False
3984

    
3985
  def ExpandNames(self):
3986
    self._ExpandAndLockInstance()
3987
    self.needed_locks[locking.LEVEL_NODE] = []
3988
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3989

    
3990
  def DeclareLocks(self, level):
3991
    if level == locking.LEVEL_NODE:
3992
      self._LockInstancesNodes()
3993

    
3994
  def BuildHooksEnv(self):
3995
    """Build hooks env.
3996

3997
    This runs on master, primary and secondary nodes of the instance.
3998

3999
    """
4000
    env = {
4001
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4002
      }
4003
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4004
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)