Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 5c983ee5

History | View | Annotate | Download (303.2 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Module implementing the master-side code."""
23

    
24
# pylint: disable-msg=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, errors.ECODE_INVAL)
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, errors.ECODE_NOENT)
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
                               errors.ECODE_INVAL)
422

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

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

    
435
  return utils.NiceSort(wanted)
436

    
437

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

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

450
  """
451
  if not isinstance(instances, list):
452
    raise errors.OpPrereqError("Invalid argument type 'instances'",
453
                               errors.ECODE_INVAL)
454

    
455
  if instances:
456
    wanted = []
457

    
458
    for name in instances:
459
      instance = lu.cfg.ExpandInstanceName(name)
460
      if instance is None:
461
        raise errors.OpPrereqError("No such instance name '%s'" % name,
462
                                   errors.ECODE_NOENT)
463
      wanted.append(instance)
464

    
465
  else:
466
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
467
  return wanted
468

    
469

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

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

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

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

    
488

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

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

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

    
502

    
503
def _CheckNodeOnline(lu, node):
504
  """Ensure that a given node is online.
505

506
  @param lu: the LU on behalf of which we make the check
507
  @param node: the node to check
508
  @raise errors.OpPrereqError: if the node is offline
509

510
  """
511
  if lu.cfg.GetNodeInfo(node).offline:
512
    raise errors.OpPrereqError("Can't use offline node %s" % node,
513
                               errors.ECODE_INVAL)
514

    
515

    
516
def _CheckNodeNotDrained(lu, node):
517
  """Ensure that a given node is not drained.
518

519
  @param lu: the LU on behalf of which we make the check
520
  @param node: the node to check
521
  @raise errors.OpPrereqError: if the node is drained
522

523
  """
524
  if lu.cfg.GetNodeInfo(node).drained:
525
    raise errors.OpPrereqError("Can't use drained node %s" % node,
526
                               errors.ECODE_INVAL)
527

    
528

    
529
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
530
                          memory, vcpus, nics, disk_template, disks,
531
                          bep, hvp, hypervisor_name):
532
  """Builds instance related env variables for hooks
533

534
  This builds the hook environment from individual variables.
535

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

566
  """
567
  if status:
568
    str_status = "up"
569
  else:
570
    str_status = "down"
571
  env = {
572
    "OP_TARGET": name,
573
    "INSTANCE_NAME": name,
574
    "INSTANCE_PRIMARY": primary_node,
575
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
576
    "INSTANCE_OS_TYPE": os_type,
577
    "INSTANCE_STATUS": str_status,
578
    "INSTANCE_MEMORY": memory,
579
    "INSTANCE_VCPUS": vcpus,
580
    "INSTANCE_DISK_TEMPLATE": disk_template,
581
    "INSTANCE_HYPERVISOR": hypervisor_name,
582
  }
583

    
584
  if nics:
585
    nic_count = len(nics)
586
    for idx, (ip, mac, mode, link) in enumerate(nics):
587
      if ip is None:
588
        ip = ""
589
      env["INSTANCE_NIC%d_IP" % idx] = ip
590
      env["INSTANCE_NIC%d_MAC" % idx] = mac
591
      env["INSTANCE_NIC%d_MODE" % idx] = mode
592
      env["INSTANCE_NIC%d_LINK" % idx] = link
593
      if mode == constants.NIC_MODE_BRIDGED:
594
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
595
  else:
596
    nic_count = 0
597

    
598
  env["INSTANCE_NIC_COUNT"] = nic_count
599

    
600
  if disks:
601
    disk_count = len(disks)
602
    for idx, (size, mode) in enumerate(disks):
603
      env["INSTANCE_DISK%d_SIZE" % idx] = size
604
      env["INSTANCE_DISK%d_MODE" % idx] = mode
605
  else:
606
    disk_count = 0
607

    
608
  env["INSTANCE_DISK_COUNT"] = disk_count
609

    
610
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
611
    for key, value in source.items():
612
      env["INSTANCE_%s_%s" % (kind, key)] = value
613

    
614
  return env
615

    
616

    
617
def _NICListToTuple(lu, nics):
618
  """Build a list of nic information tuples.
619

620
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
621
  value in LUQueryInstanceData.
622

623
  @type lu:  L{LogicalUnit}
624
  @param lu: the logical unit on whose behalf we execute
625
  @type nics: list of L{objects.NIC}
626
  @param nics: list of nics to convert to hooks tuples
627

628
  """
629
  hooks_nics = []
630
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
631
  for nic in nics:
632
    ip = nic.ip
633
    mac = nic.mac
634
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
635
    mode = filled_params[constants.NIC_MODE]
636
    link = filled_params[constants.NIC_LINK]
637
    hooks_nics.append((ip, mac, mode, link))
638
  return hooks_nics
639

    
640

    
641
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
642
  """Builds instance related env variables for hooks from an object.
643

644
  @type lu: L{LogicalUnit}
645
  @param lu: the logical unit on whose behalf we execute
646
  @type instance: L{objects.Instance}
647
  @param instance: the instance for which we should build the
648
      environment
649
  @type override: dict
650
  @param override: dictionary with key/values that will override
651
      our values
652
  @rtype: dict
653
  @return: the hook environment dictionary
654

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

    
678

    
679
def _AdjustCandidatePool(lu, exceptions):
680
  """Adjust the candidate pool after node operations.
681

682
  """
683
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
684
  if mod_list:
685
    lu.LogInfo("Promoted nodes to master candidate role: %s",
686
               ", ".join(node.name for node in mod_list))
687
    for name in mod_list:
688
      lu.context.ReaddNode(name)
689
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
690
  if mc_now > mc_max:
691
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
692
               (mc_now, mc_max))
693

    
694

    
695
def _DecideSelfPromotion(lu, exceptions=None):
696
  """Decide whether I should promote myself as a master candidate.
697

698
  """
699
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
700
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
701
  # the new node will increase mc_max with one, so:
702
  mc_should = min(mc_should + 1, cp_size)
703
  return mc_now < mc_should
704

    
705

    
706
def _CheckNicsBridgesExist(lu, target_nics, target_node,
707
                               profile=constants.PP_DEFAULT):
708
  """Check that the brigdes needed by a list of nics exist.
709

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

    
721

    
722
def _CheckInstanceBridgesExist(lu, instance, node=None):
723
  """Check that the brigdes needed by an instance exist.
724

725
  """
726
  if node is None:
727
    node = instance.primary_node
728
  _CheckNicsBridgesExist(lu, instance.nics, node)
729

    
730

    
731
def _CheckOSVariant(os_obj, name):
732
  """Check whether an OS name conforms to the os variants specification.
733

734
  @type os_obj: L{objects.OS}
735
  @param os_obj: OS object to check
736
  @type name: string
737
  @param name: OS name passed by the user, to check for validity
738

739
  """
740
  if not os_obj.supported_variants:
741
    return
742
  try:
743
    variant = name.split("+", 1)[1]
744
  except IndexError:
745
    raise errors.OpPrereqError("OS name must include a variant",
746
                               errors.ECODE_INVAL)
747

    
748
  if variant not in os_obj.supported_variants:
749
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
750

    
751

    
752
def _GetNodeInstancesInner(cfg, fn):
753
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
754

    
755

    
756
def _GetNodeInstances(cfg, node_name):
757
  """Returns a list of all primary and secondary instances on a node.
758

759
  """
760

    
761
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
762

    
763

    
764
def _GetNodePrimaryInstances(cfg, node_name):
765
  """Returns primary instances on a node.
766

767
  """
768
  return _GetNodeInstancesInner(cfg,
769
                                lambda inst: node_name == inst.primary_node)
770

    
771

    
772
def _GetNodeSecondaryInstances(cfg, node_name):
773
  """Returns secondary instances on a node.
774

775
  """
776
  return _GetNodeInstancesInner(cfg,
777
                                lambda inst: node_name in inst.secondary_nodes)
778

    
779

    
780
def _GetStorageTypeArgs(cfg, storage_type):
781
  """Returns the arguments for a storage type.
782

783
  """
784
  # Special case for file storage
785
  if storage_type == constants.ST_FILE:
786
    # storage.FileStorage wants a list of storage directories
787
    return [[cfg.GetFileStorageDir()]]
788

    
789
  return []
790

    
791

    
792
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
793
  faulty = []
794

    
795
  for dev in instance.disks:
796
    cfg.SetDiskID(dev, node_name)
797

    
798
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
799
  result.Raise("Failed to get disk status from node %s" % node_name,
800
               prereq=prereq)
801

    
802
  for idx, bdev_status in enumerate(result.payload):
803
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
804
      faulty.append(idx)
805

    
806
  return faulty
807

    
808

    
809
class LUPostInitCluster(LogicalUnit):
810
  """Logical unit for running hooks after cluster initialization.
811

812
  """
813
  HPATH = "cluster-init"
814
  HTYPE = constants.HTYPE_CLUSTER
815
  _OP_REQP = []
816

    
817
  def BuildHooksEnv(self):
818
    """Build hooks env.
819

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

    
825
  def CheckPrereq(self):
826
    """No prerequisites to check.
827

828
    """
829
    return True
830

    
831
  def Exec(self, feedback_fn):
832
    """Nothing to do.
833

834
    """
835
    return True
836

    
837

    
838
class LUDestroyCluster(LogicalUnit):
839
  """Logical unit for destroying the cluster.
840

841
  """
842
  HPATH = "cluster-destroy"
843
  HTYPE = constants.HTYPE_CLUSTER
844
  _OP_REQP = []
845

    
846
  def BuildHooksEnv(self):
847
    """Build hooks env.
848

849
    """
850
    env = {"OP_TARGET": self.cfg.GetClusterName()}
851
    return env, [], []
852

    
853
  def CheckPrereq(self):
854
    """Check prerequisites.
855

856
    This checks whether the cluster is empty.
857

858
    Any errors are signaled by raising errors.OpPrereqError.
859

860
    """
861
    master = self.cfg.GetMasterNode()
862

    
863
    nodelist = self.cfg.GetNodeList()
864
    if len(nodelist) != 1 or nodelist[0] != master:
865
      raise errors.OpPrereqError("There are still %d node(s) in"
866
                                 " this cluster." % (len(nodelist) - 1),
867
                                 errors.ECODE_INVAL)
868
    instancelist = self.cfg.GetInstanceList()
869
    if instancelist:
870
      raise errors.OpPrereqError("There are still %d instance(s) in"
871
                                 " this cluster." % len(instancelist),
872
                                 errors.ECODE_INVAL)
873

    
874
  def Exec(self, feedback_fn):
875
    """Destroys the cluster.
876

877
    """
878
    master = self.cfg.GetMasterNode()
879
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
880

    
881
    # Run post hooks on master node before it's removed
882
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
883
    try:
884
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
885
    except:
886
      self.LogWarning("Errors occurred running hooks on %s" % master)
887

    
888
    result = self.rpc.call_node_stop_master(master, False)
889
    result.Raise("Could not disable the master role")
890

    
891
    if modify_ssh_setup:
892
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
893
      utils.CreateBackup(priv_key)
894
      utils.CreateBackup(pub_key)
895

    
896
    return master
897

    
898

    
899
class LUVerifyCluster(LogicalUnit):
900
  """Verifies the cluster status.
901

902
  """
903
  HPATH = "cluster-verify"
904
  HTYPE = constants.HTYPE_CLUSTER
905
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
906
  REQ_BGL = False
907

    
908
  TCLUSTER = "cluster"
909
  TNODE = "node"
910
  TINSTANCE = "instance"
911

    
912
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
913
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
914
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
915
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
916
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
917
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
918
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
919
  ENODEDRBD = (TNODE, "ENODEDRBD")
920
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
921
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
922
  ENODEHV = (TNODE, "ENODEHV")
923
  ENODELVM = (TNODE, "ENODELVM")
924
  ENODEN1 = (TNODE, "ENODEN1")
925
  ENODENET = (TNODE, "ENODENET")
926
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
927
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
928
  ENODERPC = (TNODE, "ENODERPC")
929
  ENODESSH = (TNODE, "ENODESSH")
930
  ENODEVERSION = (TNODE, "ENODEVERSION")
931
  ENODESETUP = (TNODE, "ENODESETUP")
932

    
933
  ETYPE_FIELD = "code"
934
  ETYPE_ERROR = "ERROR"
935
  ETYPE_WARNING = "WARNING"
936

    
937
  def ExpandNames(self):
938
    self.needed_locks = {
939
      locking.LEVEL_NODE: locking.ALL_SET,
940
      locking.LEVEL_INSTANCE: locking.ALL_SET,
941
    }
942
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
943

    
944
  def _Error(self, ecode, item, msg, *args, **kwargs):
945
    """Format an error message.
946

947
    Based on the opcode's error_codes parameter, either format a
948
    parseable error code, or a simpler error string.
949

950
    This must be called only from Exec and functions called from Exec.
951

952
    """
953
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
954
    itype, etxt = ecode
955
    # first complete the msg
956
    if args:
957
      msg = msg % args
958
    # then format the whole message
959
    if self.op.error_codes:
960
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
961
    else:
962
      if item:
963
        item = " " + item
964
      else:
965
        item = ""
966
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
967
    # and finally report it via the feedback_fn
968
    self._feedback_fn("  - %s" % msg)
969

    
970
  def _ErrorIf(self, cond, *args, **kwargs):
971
    """Log an error message if the passed condition is True.
972

973
    """
974
    cond = bool(cond) or self.op.debug_simulate_errors
975
    if cond:
976
      self._Error(*args, **kwargs)
977
    # do not mark the operation as failed for WARN cases only
978
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
979
      self.bad = self.bad or cond
980

    
981
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
982
                  node_result, master_files, drbd_map, vg_name):
983
    """Run multiple tests against a node.
984

985
    Test list:
986

987
      - compares ganeti version
988
      - checks vg existence and size > 20G
989
      - checks config file checksum
990
      - checks ssh to other nodes
991

992
    @type nodeinfo: L{objects.Node}
993
    @param nodeinfo: the node to check
994
    @param file_list: required list of files
995
    @param local_cksum: dictionary of local files and their checksums
996
    @param node_result: the results from the node
997
    @param master_files: list of files that only masters should have
998
    @param drbd_map: the useddrbd minors for this node, in
999
        form of minor: (instance, must_exist) which correspond to instances
1000
        and their running status
1001
    @param vg_name: Ganeti Volume Group (result of self.cfg.GetVGName())
1002

1003
    """
1004
    node = nodeinfo.name
1005
    _ErrorIf = self._ErrorIf
1006

    
1007
    # main result, node_result should be a non-empty dict
1008
    test = not node_result or not isinstance(node_result, dict)
1009
    _ErrorIf(test, self.ENODERPC, node,
1010
                  "unable to verify node: no data returned")
1011
    if test:
1012
      return
1013

    
1014
    # compares ganeti version
1015
    local_version = constants.PROTOCOL_VERSION
1016
    remote_version = node_result.get('version', None)
1017
    test = not (remote_version and
1018
                isinstance(remote_version, (list, tuple)) and
1019
                len(remote_version) == 2)
1020
    _ErrorIf(test, self.ENODERPC, node,
1021
             "connection to node returned invalid data")
1022
    if test:
1023
      return
1024

    
1025
    test = local_version != remote_version[0]
1026
    _ErrorIf(test, self.ENODEVERSION, node,
1027
             "incompatible protocol versions: master %s,"
1028
             " node %s", local_version, remote_version[0])
1029
    if test:
1030
      return
1031

    
1032
    # node seems compatible, we can actually try to look into its results
1033

    
1034
    # full package version
1035
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1036
                  self.ENODEVERSION, node,
1037
                  "software version mismatch: master %s, node %s",
1038
                  constants.RELEASE_VERSION, remote_version[1],
1039
                  code=self.ETYPE_WARNING)
1040

    
1041
    # checks vg existence and size > 20G
1042
    if vg_name is not None:
1043
      vglist = node_result.get(constants.NV_VGLIST, None)
1044
      test = not vglist
1045
      _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1046
      if not test:
1047
        vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1048
                                              constants.MIN_VG_SIZE)
1049
        _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1050

    
1051
    # checks config file checksum
1052

    
1053
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
1054
    test = not isinstance(remote_cksum, dict)
1055
    _ErrorIf(test, self.ENODEFILECHECK, node,
1056
             "node hasn't returned file checksum data")
1057
    if not test:
1058
      for file_name in file_list:
1059
        node_is_mc = nodeinfo.master_candidate
1060
        must_have = (file_name not in master_files) or node_is_mc
1061
        # missing
1062
        test1 = file_name not in remote_cksum
1063
        # invalid checksum
1064
        test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1065
        # existing and good
1066
        test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1067
        _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1068
                 "file '%s' missing", file_name)
1069
        _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1070
                 "file '%s' has wrong checksum", file_name)
1071
        # not candidate and this is not a must-have file
1072
        _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1073
                 "file '%s' should not exist on non master"
1074
                 " candidates (and the file is outdated)", file_name)
1075
        # all good, except non-master/non-must have combination
1076
        _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1077
                 "file '%s' should not exist"
1078
                 " on non master candidates", file_name)
1079

    
1080
    # checks ssh to any
1081

    
1082
    test = constants.NV_NODELIST not in node_result
1083
    _ErrorIf(test, self.ENODESSH, node,
1084
             "node hasn't returned node ssh connectivity data")
1085
    if not test:
1086
      if node_result[constants.NV_NODELIST]:
1087
        for a_node, a_msg in node_result[constants.NV_NODELIST].items():
1088
          _ErrorIf(True, self.ENODESSH, node,
1089
                   "ssh communication with node '%s': %s", a_node, a_msg)
1090

    
1091
    test = constants.NV_NODENETTEST not in node_result
1092
    _ErrorIf(test, self.ENODENET, node,
1093
             "node hasn't returned node tcp connectivity data")
1094
    if not test:
1095
      if node_result[constants.NV_NODENETTEST]:
1096
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
1097
        for anode in nlist:
1098
          _ErrorIf(True, self.ENODENET, node,
1099
                   "tcp communication with node '%s': %s",
1100
                   anode, node_result[constants.NV_NODENETTEST][anode])
1101

    
1102
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
1103
    if isinstance(hyp_result, dict):
1104
      for hv_name, hv_result in hyp_result.iteritems():
1105
        test = hv_result is not None
1106
        _ErrorIf(test, self.ENODEHV, node,
1107
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1108

    
1109
    # check used drbd list
1110
    if vg_name is not None:
1111
      used_minors = node_result.get(constants.NV_DRBDLIST, [])
1112
      test = not isinstance(used_minors, (tuple, list))
1113
      _ErrorIf(test, self.ENODEDRBD, node,
1114
               "cannot parse drbd status file: %s", str(used_minors))
1115
      if not test:
1116
        for minor, (iname, must_exist) in drbd_map.items():
1117
          test = minor not in used_minors and must_exist
1118
          _ErrorIf(test, self.ENODEDRBD, node,
1119
                   "drbd minor %d of instance %s is not active",
1120
                   minor, iname)
1121
        for minor in used_minors:
1122
          test = minor not in drbd_map
1123
          _ErrorIf(test, self.ENODEDRBD, node,
1124
                   "unallocated drbd minor %d is in use", minor)
1125
    test = node_result.get(constants.NV_NODESETUP,
1126
                           ["Missing NODESETUP results"])
1127
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1128
             "; ".join(test))
1129

    
1130
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
1131
                      node_instance, n_offline):
1132
    """Verify an instance.
1133

1134
    This function checks to see if the required block devices are
1135
    available on the instance's node.
1136

1137
    """
1138
    _ErrorIf = self._ErrorIf
1139
    node_current = instanceconfig.primary_node
1140

    
1141
    node_vol_should = {}
1142
    instanceconfig.MapLVsByNode(node_vol_should)
1143

    
1144
    for node in node_vol_should:
1145
      if node in n_offline:
1146
        # ignore missing volumes on offline nodes
1147
        continue
1148
      for volume in node_vol_should[node]:
1149
        test = node not in node_vol_is or volume not in node_vol_is[node]
1150
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1151
                 "volume %s missing on node %s", volume, node)
1152

    
1153
    if instanceconfig.admin_up:
1154
      test = ((node_current not in node_instance or
1155
               not instance in node_instance[node_current]) and
1156
              node_current not in n_offline)
1157
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1158
               "instance not running on its primary node %s",
1159
               node_current)
1160

    
1161
    for node in node_instance:
1162
      if (not node == node_current):
1163
        test = instance in node_instance[node]
1164
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1165
                 "instance should not run on node %s", node)
1166

    
1167
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is):
1168
    """Verify if there are any unknown volumes in the cluster.
1169

1170
    The .os, .swap and backup volumes are ignored. All other volumes are
1171
    reported as unknown.
1172

1173
    """
1174
    for node in node_vol_is:
1175
      for volume in node_vol_is[node]:
1176
        test = (node not in node_vol_should or
1177
                volume not in node_vol_should[node])
1178
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1179
                      "volume %s is unknown", volume)
1180

    
1181
  def _VerifyOrphanInstances(self, instancelist, node_instance):
1182
    """Verify the list of running instances.
1183

1184
    This checks what instances are running but unknown to the cluster.
1185

1186
    """
1187
    for node in node_instance:
1188
      for o_inst in node_instance[node]:
1189
        test = o_inst not in instancelist
1190
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1191
                      "instance %s on node %s should not exist", o_inst, node)
1192

    
1193
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg):
1194
    """Verify N+1 Memory Resilience.
1195

1196
    Check that if one single node dies we can still start all the instances it
1197
    was primary for.
1198

1199
    """
1200
    for node, nodeinfo in node_info.iteritems():
1201
      # This code checks that every node which is now listed as secondary has
1202
      # enough memory to host all instances it is supposed to should a single
1203
      # other node in the cluster fail.
1204
      # FIXME: not ready for failover to an arbitrary node
1205
      # FIXME: does not support file-backed instances
1206
      # WARNING: we currently take into account down instances as well as up
1207
      # ones, considering that even if they're down someone might want to start
1208
      # them even in the event of a node failure.
1209
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
1210
        needed_mem = 0
1211
        for instance in instances:
1212
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1213
          if bep[constants.BE_AUTO_BALANCE]:
1214
            needed_mem += bep[constants.BE_MEMORY]
1215
        test = nodeinfo['mfree'] < needed_mem
1216
        self._ErrorIf(test, self.ENODEN1, node,
1217
                      "not enough memory on to accommodate"
1218
                      " failovers should peer node %s fail", prinode)
1219

    
1220
  def CheckPrereq(self):
1221
    """Check prerequisites.
1222

1223
    Transform the list of checks we're going to skip into a set and check that
1224
    all its members are valid.
1225

1226
    """
1227
    self.skip_set = frozenset(self.op.skip_checks)
1228
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1229
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1230
                                 errors.ECODE_INVAL)
1231

    
1232
  def BuildHooksEnv(self):
1233
    """Build hooks env.
1234

1235
    Cluster-Verify hooks just ran in the post phase and their failure makes
1236
    the output be logged in the verify output and the verification to fail.
1237

1238
    """
1239
    all_nodes = self.cfg.GetNodeList()
1240
    env = {
1241
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1242
      }
1243
    for node in self.cfg.GetAllNodesInfo().values():
1244
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1245

    
1246
    return env, [], all_nodes
1247

    
1248
  def Exec(self, feedback_fn):
1249
    """Verify integrity of cluster, performing various test on nodes.
1250

1251
    """
1252
    self.bad = False
1253
    _ErrorIf = self._ErrorIf
1254
    verbose = self.op.verbose
1255
    self._feedback_fn = feedback_fn
1256
    feedback_fn("* Verifying global settings")
1257
    for msg in self.cfg.VerifyConfig():
1258
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1259

    
1260
    vg_name = self.cfg.GetVGName()
1261
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1262
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1263
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1264
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1265
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1266
                        for iname in instancelist)
1267
    i_non_redundant = [] # Non redundant instances
1268
    i_non_a_balanced = [] # Non auto-balanced instances
1269
    n_offline = [] # List of offline nodes
1270
    n_drained = [] # List of nodes being drained
1271
    node_volume = {}
1272
    node_instance = {}
1273
    node_info = {}
1274
    instance_cfg = {}
1275

    
1276
    # FIXME: verify OS list
1277
    # do local checksums
1278
    master_files = [constants.CLUSTER_CONF_FILE]
1279

    
1280
    file_names = ssconf.SimpleStore().GetFileList()
1281
    file_names.append(constants.SSL_CERT_FILE)
1282
    file_names.append(constants.RAPI_CERT_FILE)
1283
    file_names.extend(master_files)
1284

    
1285
    local_checksums = utils.FingerprintFiles(file_names)
1286

    
1287
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1288
    node_verify_param = {
1289
      constants.NV_FILELIST: file_names,
1290
      constants.NV_NODELIST: [node.name for node in nodeinfo
1291
                              if not node.offline],
1292
      constants.NV_HYPERVISOR: hypervisors,
1293
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1294
                                  node.secondary_ip) for node in nodeinfo
1295
                                 if not node.offline],
1296
      constants.NV_INSTANCELIST: hypervisors,
1297
      constants.NV_VERSION: None,
1298
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1299
      constants.NV_NODESETUP: None,
1300
      }
1301
    if vg_name is not None:
1302
      node_verify_param[constants.NV_VGLIST] = None
1303
      node_verify_param[constants.NV_LVLIST] = vg_name
1304
      node_verify_param[constants.NV_DRBDLIST] = None
1305
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1306
                                           self.cfg.GetClusterName())
1307

    
1308
    cluster = self.cfg.GetClusterInfo()
1309
    master_node = self.cfg.GetMasterNode()
1310
    all_drbd_map = self.cfg.ComputeDRBDMap()
1311

    
1312
    feedback_fn("* Verifying node status")
1313
    for node_i in nodeinfo:
1314
      node = node_i.name
1315

    
1316
      if node_i.offline:
1317
        if verbose:
1318
          feedback_fn("* Skipping offline node %s" % (node,))
1319
        n_offline.append(node)
1320
        continue
1321

    
1322
      if node == master_node:
1323
        ntype = "master"
1324
      elif node_i.master_candidate:
1325
        ntype = "master candidate"
1326
      elif node_i.drained:
1327
        ntype = "drained"
1328
        n_drained.append(node)
1329
      else:
1330
        ntype = "regular"
1331
      if verbose:
1332
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1333

    
1334
      msg = all_nvinfo[node].fail_msg
1335
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1336
      if msg:
1337
        continue
1338

    
1339
      nresult = all_nvinfo[node].payload
1340
      node_drbd = {}
1341
      for minor, instance in all_drbd_map[node].items():
1342
        test = instance not in instanceinfo
1343
        _ErrorIf(test, self.ECLUSTERCFG, None,
1344
                 "ghost instance '%s' in temporary DRBD map", instance)
1345
          # ghost instance should not be running, but otherwise we
1346
          # don't give double warnings (both ghost instance and
1347
          # unallocated minor in use)
1348
        if test:
1349
          node_drbd[minor] = (instance, False)
1350
        else:
1351
          instance = instanceinfo[instance]
1352
          node_drbd[minor] = (instance.name, instance.admin_up)
1353
      self._VerifyNode(node_i, file_names, local_checksums,
1354
                       nresult, master_files, node_drbd, vg_name)
1355

    
1356
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1357
      if vg_name is None:
1358
        node_volume[node] = {}
1359
      elif isinstance(lvdata, basestring):
1360
        _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1361
                 utils.SafeEncode(lvdata))
1362
        node_volume[node] = {}
1363
      elif not isinstance(lvdata, dict):
1364
        _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1365
        continue
1366
      else:
1367
        node_volume[node] = lvdata
1368

    
1369
      # node_instance
1370
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1371
      test = not isinstance(idata, list)
1372
      _ErrorIf(test, self.ENODEHV, node,
1373
               "rpc call to node failed (instancelist)")
1374
      if test:
1375
        continue
1376

    
1377
      node_instance[node] = idata
1378

    
1379
      # node_info
1380
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1381
      test = not isinstance(nodeinfo, dict)
1382
      _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1383
      if test:
1384
        continue
1385

    
1386
      try:
1387
        node_info[node] = {
1388
          "mfree": int(nodeinfo['memory_free']),
1389
          "pinst": [],
1390
          "sinst": [],
1391
          # dictionary holding all instances this node is secondary for,
1392
          # grouped by their primary node. Each key is a cluster node, and each
1393
          # value is a list of instances which have the key as primary and the
1394
          # current node as secondary.  this is handy to calculate N+1 memory
1395
          # availability if you can only failover from a primary to its
1396
          # secondary.
1397
          "sinst-by-pnode": {},
1398
        }
1399
        # FIXME: devise a free space model for file based instances as well
1400
        if vg_name is not None:
1401
          test = (constants.NV_VGLIST not in nresult or
1402
                  vg_name not in nresult[constants.NV_VGLIST])
1403
          _ErrorIf(test, self.ENODELVM, node,
1404
                   "node didn't return data for the volume group '%s'"
1405
                   " - it is either missing or broken", vg_name)
1406
          if test:
1407
            continue
1408
          node_info[node]["dfree"] = int(nresult[constants.NV_VGLIST][vg_name])
1409
      except (ValueError, KeyError):
1410
        _ErrorIf(True, self.ENODERPC, node,
1411
                 "node returned invalid nodeinfo, check lvm/hypervisor")
1412
        continue
1413

    
1414
    node_vol_should = {}
1415

    
1416
    feedback_fn("* Verifying instance status")
1417
    for instance in instancelist:
1418
      if verbose:
1419
        feedback_fn("* Verifying instance %s" % instance)
1420
      inst_config = instanceinfo[instance]
1421
      self._VerifyInstance(instance, inst_config, node_volume,
1422
                           node_instance, n_offline)
1423
      inst_nodes_offline = []
1424

    
1425
      inst_config.MapLVsByNode(node_vol_should)
1426

    
1427
      instance_cfg[instance] = inst_config
1428

    
1429
      pnode = inst_config.primary_node
1430
      _ErrorIf(pnode not in node_info and pnode not in n_offline,
1431
               self.ENODERPC, pnode, "instance %s, connection to"
1432
               " primary node failed", instance)
1433
      if pnode in node_info:
1434
        node_info[pnode]['pinst'].append(instance)
1435

    
1436
      if pnode in n_offline:
1437
        inst_nodes_offline.append(pnode)
1438

    
1439
      # If the instance is non-redundant we cannot survive losing its primary
1440
      # node, so we are not N+1 compliant. On the other hand we have no disk
1441
      # templates with more than one secondary so that situation is not well
1442
      # supported either.
1443
      # FIXME: does not support file-backed instances
1444
      if len(inst_config.secondary_nodes) == 0:
1445
        i_non_redundant.append(instance)
1446
      _ErrorIf(len(inst_config.secondary_nodes) > 1,
1447
               self.EINSTANCELAYOUT, instance,
1448
               "instance has multiple secondary nodes", code="WARNING")
1449

    
1450
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1451
        i_non_a_balanced.append(instance)
1452

    
1453
      for snode in inst_config.secondary_nodes:
1454
        _ErrorIf(snode not in node_info and snode not in n_offline,
1455
                 self.ENODERPC, snode,
1456
                 "instance %s, connection to secondary node"
1457
                 "failed", instance)
1458

    
1459
        if snode in node_info:
1460
          node_info[snode]['sinst'].append(instance)
1461
          if pnode not in node_info[snode]['sinst-by-pnode']:
1462
            node_info[snode]['sinst-by-pnode'][pnode] = []
1463
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1464

    
1465
        if snode in n_offline:
1466
          inst_nodes_offline.append(snode)
1467

    
1468
      # warn that the instance lives on offline nodes
1469
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1470
               "instance lives on offline node(s) %s",
1471
               ", ".join(inst_nodes_offline))
1472

    
1473
    feedback_fn("* Verifying orphan volumes")
1474
    self._VerifyOrphanVolumes(node_vol_should, node_volume)
1475

    
1476
    feedback_fn("* Verifying remaining instances")
1477
    self._VerifyOrphanInstances(instancelist, node_instance)
1478

    
1479
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1480
      feedback_fn("* Verifying N+1 Memory redundancy")
1481
      self._VerifyNPlusOneMemory(node_info, instance_cfg)
1482

    
1483
    feedback_fn("* Other Notes")
1484
    if i_non_redundant:
1485
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1486
                  % len(i_non_redundant))
1487

    
1488
    if i_non_a_balanced:
1489
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1490
                  % len(i_non_a_balanced))
1491

    
1492
    if n_offline:
1493
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1494

    
1495
    if n_drained:
1496
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1497

    
1498
    return not self.bad
1499

    
1500
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1501
    """Analyze the post-hooks' result
1502

1503
    This method analyses the hook result, handles it, and sends some
1504
    nicely-formatted feedback back to the user.
1505

1506
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1507
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1508
    @param hooks_results: the results of the multi-node hooks rpc call
1509
    @param feedback_fn: function used send feedback back to the caller
1510
    @param lu_result: previous Exec result
1511
    @return: the new Exec result, based on the previous result
1512
        and hook results
1513

1514
    """
1515
    # We only really run POST phase hooks, and are only interested in
1516
    # their results
1517
    if phase == constants.HOOKS_PHASE_POST:
1518
      # Used to change hooks' output to proper indentation
1519
      indent_re = re.compile('^', re.M)
1520
      feedback_fn("* Hooks Results")
1521
      assert hooks_results, "invalid result from hooks"
1522

    
1523
      for node_name in hooks_results:
1524
        show_node_header = True
1525
        res = hooks_results[node_name]
1526
        msg = res.fail_msg
1527
        test = msg and not res.offline
1528
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1529
                      "Communication failure in hooks execution: %s", msg)
1530
        if test:
1531
          # override manually lu_result here as _ErrorIf only
1532
          # overrides self.bad
1533
          lu_result = 1
1534
          continue
1535
        for script, hkr, output in res.payload:
1536
          test = hkr == constants.HKR_FAIL
1537
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1538
                        "Script %s failed, output:", script)
1539
          if test:
1540
            output = indent_re.sub('      ', output)
1541
            feedback_fn("%s" % output)
1542
            lu_result = 1
1543

    
1544
      return lu_result
1545

    
1546

    
1547
class LUVerifyDisks(NoHooksLU):
1548
  """Verifies the cluster disks status.
1549

1550
  """
1551
  _OP_REQP = []
1552
  REQ_BGL = False
1553

    
1554
  def ExpandNames(self):
1555
    self.needed_locks = {
1556
      locking.LEVEL_NODE: locking.ALL_SET,
1557
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1558
    }
1559
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1560

    
1561
  def CheckPrereq(self):
1562
    """Check prerequisites.
1563

1564
    This has no prerequisites.
1565

1566
    """
1567
    pass
1568

    
1569
  def Exec(self, feedback_fn):
1570
    """Verify integrity of cluster disks.
1571

1572
    @rtype: tuple of three items
1573
    @return: a tuple of (dict of node-to-node_error, list of instances
1574
        which need activate-disks, dict of instance: (node, volume) for
1575
        missing volumes
1576

1577
    """
1578
    result = res_nodes, res_instances, res_missing = {}, [], {}
1579

    
1580
    vg_name = self.cfg.GetVGName()
1581
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1582
    instances = [self.cfg.GetInstanceInfo(name)
1583
                 for name in self.cfg.GetInstanceList()]
1584

    
1585
    nv_dict = {}
1586
    for inst in instances:
1587
      inst_lvs = {}
1588
      if (not inst.admin_up or
1589
          inst.disk_template not in constants.DTS_NET_MIRROR):
1590
        continue
1591
      inst.MapLVsByNode(inst_lvs)
1592
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1593
      for node, vol_list in inst_lvs.iteritems():
1594
        for vol in vol_list:
1595
          nv_dict[(node, vol)] = inst
1596

    
1597
    if not nv_dict:
1598
      return result
1599

    
1600
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1601

    
1602
    for node in nodes:
1603
      # node_volume
1604
      node_res = node_lvs[node]
1605
      if node_res.offline:
1606
        continue
1607
      msg = node_res.fail_msg
1608
      if msg:
1609
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1610
        res_nodes[node] = msg
1611
        continue
1612

    
1613
      lvs = node_res.payload
1614
      for lv_name, (_, lv_inactive, lv_online) in lvs.items():
1615
        inst = nv_dict.pop((node, lv_name), None)
1616
        if (not lv_online and inst is not None
1617
            and inst.name not in res_instances):
1618
          res_instances.append(inst.name)
1619

    
1620
    # any leftover items in nv_dict are missing LVs, let's arrange the
1621
    # data better
1622
    for key, inst in nv_dict.iteritems():
1623
      if inst.name not in res_missing:
1624
        res_missing[inst.name] = []
1625
      res_missing[inst.name].append(key)
1626

    
1627
    return result
1628

    
1629

    
1630
class LURepairDiskSizes(NoHooksLU):
1631
  """Verifies the cluster disks sizes.
1632

1633
  """
1634
  _OP_REQP = ["instances"]
1635
  REQ_BGL = False
1636

    
1637
  def ExpandNames(self):
1638
    if not isinstance(self.op.instances, list):
1639
      raise errors.OpPrereqError("Invalid argument type 'instances'",
1640
                                 errors.ECODE_INVAL)
1641

    
1642
    if self.op.instances:
1643
      self.wanted_names = []
1644
      for name in self.op.instances:
1645
        full_name = self.cfg.ExpandInstanceName(name)
1646
        if full_name is None:
1647
          raise errors.OpPrereqError("Instance '%s' not known" % name,
1648
                                     errors.ECODE_NOENT)
1649
        self.wanted_names.append(full_name)
1650
      self.needed_locks = {
1651
        locking.LEVEL_NODE: [],
1652
        locking.LEVEL_INSTANCE: self.wanted_names,
1653
        }
1654
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1655
    else:
1656
      self.wanted_names = None
1657
      self.needed_locks = {
1658
        locking.LEVEL_NODE: locking.ALL_SET,
1659
        locking.LEVEL_INSTANCE: locking.ALL_SET,
1660
        }
1661
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1662

    
1663
  def DeclareLocks(self, level):
1664
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
1665
      self._LockInstancesNodes(primary_only=True)
1666

    
1667
  def CheckPrereq(self):
1668
    """Check prerequisites.
1669

1670
    This only checks the optional instance list against the existing names.
1671

1672
    """
1673
    if self.wanted_names is None:
1674
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
1675

    
1676
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
1677
                             in self.wanted_names]
1678

    
1679
  def _EnsureChildSizes(self, disk):
1680
    """Ensure children of the disk have the needed disk size.
1681

1682
    This is valid mainly for DRBD8 and fixes an issue where the
1683
    children have smaller disk size.
1684

1685
    @param disk: an L{ganeti.objects.Disk} object
1686

1687
    """
1688
    if disk.dev_type == constants.LD_DRBD8:
1689
      assert disk.children, "Empty children for DRBD8?"
1690
      fchild = disk.children[0]
1691
      mismatch = fchild.size < disk.size
1692
      if mismatch:
1693
        self.LogInfo("Child disk has size %d, parent %d, fixing",
1694
                     fchild.size, disk.size)
1695
        fchild.size = disk.size
1696

    
1697
      # and we recurse on this child only, not on the metadev
1698
      return self._EnsureChildSizes(fchild) or mismatch
1699
    else:
1700
      return False
1701

    
1702
  def Exec(self, feedback_fn):
1703
    """Verify the size of cluster disks.
1704

1705
    """
1706
    # TODO: check child disks too
1707
    # TODO: check differences in size between primary/secondary nodes
1708
    per_node_disks = {}
1709
    for instance in self.wanted_instances:
1710
      pnode = instance.primary_node
1711
      if pnode not in per_node_disks:
1712
        per_node_disks[pnode] = []
1713
      for idx, disk in enumerate(instance.disks):
1714
        per_node_disks[pnode].append((instance, idx, disk))
1715

    
1716
    changed = []
1717
    for node, dskl in per_node_disks.items():
1718
      newl = [v[2].Copy() for v in dskl]
1719
      for dsk in newl:
1720
        self.cfg.SetDiskID(dsk, node)
1721
      result = self.rpc.call_blockdev_getsizes(node, newl)
1722
      if result.fail_msg:
1723
        self.LogWarning("Failure in blockdev_getsizes call to node"
1724
                        " %s, ignoring", node)
1725
        continue
1726
      if len(result.data) != len(dskl):
1727
        self.LogWarning("Invalid result from node %s, ignoring node results",
1728
                        node)
1729
        continue
1730
      for ((instance, idx, disk), size) in zip(dskl, result.data):
1731
        if size is None:
1732
          self.LogWarning("Disk %d of instance %s did not return size"
1733
                          " information, ignoring", idx, instance.name)
1734
          continue
1735
        if not isinstance(size, (int, long)):
1736
          self.LogWarning("Disk %d of instance %s did not return valid"
1737
                          " size information, ignoring", idx, instance.name)
1738
          continue
1739
        size = size >> 20
1740
        if size != disk.size:
1741
          self.LogInfo("Disk %d of instance %s has mismatched size,"
1742
                       " correcting: recorded %d, actual %d", idx,
1743
                       instance.name, disk.size, size)
1744
          disk.size = size
1745
          self.cfg.Update(instance, feedback_fn)
1746
          changed.append((instance.name, idx, size))
1747
        if self._EnsureChildSizes(disk):
1748
          self.cfg.Update(instance, feedback_fn)
1749
          changed.append((instance.name, idx, disk.size))
1750
    return changed
1751

    
1752

    
1753
class LURenameCluster(LogicalUnit):
1754
  """Rename the cluster.
1755

1756
  """
1757
  HPATH = "cluster-rename"
1758
  HTYPE = constants.HTYPE_CLUSTER
1759
  _OP_REQP = ["name"]
1760

    
1761
  def BuildHooksEnv(self):
1762
    """Build hooks env.
1763

1764
    """
1765
    env = {
1766
      "OP_TARGET": self.cfg.GetClusterName(),
1767
      "NEW_NAME": self.op.name,
1768
      }
1769
    mn = self.cfg.GetMasterNode()
1770
    return env, [mn], [mn]
1771

    
1772
  def CheckPrereq(self):
1773
    """Verify that the passed name is a valid one.
1774

1775
    """
1776
    hostname = utils.HostInfo(self.op.name)
1777

    
1778
    new_name = hostname.name
1779
    self.ip = new_ip = hostname.ip
1780
    old_name = self.cfg.GetClusterName()
1781
    old_ip = self.cfg.GetMasterIP()
1782
    if new_name == old_name and new_ip == old_ip:
1783
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1784
                                 " cluster has changed",
1785
                                 errors.ECODE_INVAL)
1786
    if new_ip != old_ip:
1787
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1788
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1789
                                   " reachable on the network. Aborting." %
1790
                                   new_ip, errors.ECODE_NOTUNIQUE)
1791

    
1792
    self.op.name = new_name
1793

    
1794
  def Exec(self, feedback_fn):
1795
    """Rename the cluster.
1796

1797
    """
1798
    clustername = self.op.name
1799
    ip = self.ip
1800

    
1801
    # shutdown the master IP
1802
    master = self.cfg.GetMasterNode()
1803
    result = self.rpc.call_node_stop_master(master, False)
1804
    result.Raise("Could not disable the master role")
1805

    
1806
    try:
1807
      cluster = self.cfg.GetClusterInfo()
1808
      cluster.cluster_name = clustername
1809
      cluster.master_ip = ip
1810
      self.cfg.Update(cluster, feedback_fn)
1811

    
1812
      # update the known hosts file
1813
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1814
      node_list = self.cfg.GetNodeList()
1815
      try:
1816
        node_list.remove(master)
1817
      except ValueError:
1818
        pass
1819
      result = self.rpc.call_upload_file(node_list,
1820
                                         constants.SSH_KNOWN_HOSTS_FILE)
1821
      for to_node, to_result in result.iteritems():
1822
        msg = to_result.fail_msg
1823
        if msg:
1824
          msg = ("Copy of file %s to node %s failed: %s" %
1825
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
1826
          self.proc.LogWarning(msg)
1827

    
1828
    finally:
1829
      result = self.rpc.call_node_start_master(master, False, False)
1830
      msg = result.fail_msg
1831
      if msg:
1832
        self.LogWarning("Could not re-enable the master role on"
1833
                        " the master, please restart manually: %s", msg)
1834

    
1835

    
1836
def _RecursiveCheckIfLVMBased(disk):
1837
  """Check if the given disk or its children are lvm-based.
1838

1839
  @type disk: L{objects.Disk}
1840
  @param disk: the disk to check
1841
  @rtype: boolean
1842
  @return: boolean indicating whether a LD_LV dev_type was found or not
1843

1844
  """
1845
  if disk.children:
1846
    for chdisk in disk.children:
1847
      if _RecursiveCheckIfLVMBased(chdisk):
1848
        return True
1849
  return disk.dev_type == constants.LD_LV
1850

    
1851

    
1852
class LUSetClusterParams(LogicalUnit):
1853
  """Change the parameters of the cluster.
1854

1855
  """
1856
  HPATH = "cluster-modify"
1857
  HTYPE = constants.HTYPE_CLUSTER
1858
  _OP_REQP = []
1859
  REQ_BGL = False
1860

    
1861
  def CheckArguments(self):
1862
    """Check parameters
1863

1864
    """
1865
    if not hasattr(self.op, "candidate_pool_size"):
1866
      self.op.candidate_pool_size = None
1867
    if self.op.candidate_pool_size is not None:
1868
      try:
1869
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1870
      except (ValueError, TypeError), err:
1871
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1872
                                   str(err), errors.ECODE_INVAL)
1873
      if self.op.candidate_pool_size < 1:
1874
        raise errors.OpPrereqError("At least one master candidate needed",
1875
                                   errors.ECODE_INVAL)
1876

    
1877
  def ExpandNames(self):
1878
    # FIXME: in the future maybe other cluster params won't require checking on
1879
    # all nodes to be modified.
1880
    self.needed_locks = {
1881
      locking.LEVEL_NODE: locking.ALL_SET,
1882
    }
1883
    self.share_locks[locking.LEVEL_NODE] = 1
1884

    
1885
  def BuildHooksEnv(self):
1886
    """Build hooks env.
1887

1888
    """
1889
    env = {
1890
      "OP_TARGET": self.cfg.GetClusterName(),
1891
      "NEW_VG_NAME": self.op.vg_name,
1892
      }
1893
    mn = self.cfg.GetMasterNode()
1894
    return env, [mn], [mn]
1895

    
1896
  def CheckPrereq(self):
1897
    """Check prerequisites.
1898

1899
    This checks whether the given params don't conflict and
1900
    if the given volume group is valid.
1901

1902
    """
1903
    if self.op.vg_name is not None and not self.op.vg_name:
1904
      instances = self.cfg.GetAllInstancesInfo().values()
1905
      for inst in instances:
1906
        for disk in inst.disks:
1907
          if _RecursiveCheckIfLVMBased(disk):
1908
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1909
                                       " lvm-based instances exist",
1910
                                       errors.ECODE_INVAL)
1911

    
1912
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1913

    
1914
    # if vg_name not None, checks given volume group on all nodes
1915
    if self.op.vg_name:
1916
      vglist = self.rpc.call_vg_list(node_list)
1917
      for node in node_list:
1918
        msg = vglist[node].fail_msg
1919
        if msg:
1920
          # ignoring down node
1921
          self.LogWarning("Error while gathering data on node %s"
1922
                          " (ignoring node): %s", node, msg)
1923
          continue
1924
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
1925
                                              self.op.vg_name,
1926
                                              constants.MIN_VG_SIZE)
1927
        if vgstatus:
1928
          raise errors.OpPrereqError("Error on node '%s': %s" %
1929
                                     (node, vgstatus), errors.ECODE_ENVIRON)
1930

    
1931
    self.cluster = cluster = self.cfg.GetClusterInfo()
1932
    # validate params changes
1933
    if self.op.beparams:
1934
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
1935
      self.new_beparams = objects.FillDict(
1936
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
1937

    
1938
    if self.op.nicparams:
1939
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
1940
      self.new_nicparams = objects.FillDict(
1941
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
1942
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
1943

    
1944
    # hypervisor list/parameters
1945
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
1946
    if self.op.hvparams:
1947
      if not isinstance(self.op.hvparams, dict):
1948
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
1949
                                   errors.ECODE_INVAL)
1950
      for hv_name, hv_dict in self.op.hvparams.items():
1951
        if hv_name not in self.new_hvparams:
1952
          self.new_hvparams[hv_name] = hv_dict
1953
        else:
1954
          self.new_hvparams[hv_name].update(hv_dict)
1955

    
1956
    if self.op.enabled_hypervisors is not None:
1957
      self.hv_list = self.op.enabled_hypervisors
1958
      if not self.hv_list:
1959
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
1960
                                   " least one member",
1961
                                   errors.ECODE_INVAL)
1962
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
1963
      if invalid_hvs:
1964
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
1965
                                   " entries: %s" % " ,".join(invalid_hvs),
1966
                                   errors.ECODE_INVAL)
1967
    else:
1968
      self.hv_list = cluster.enabled_hypervisors
1969

    
1970
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1971
      # either the enabled list has changed, or the parameters have, validate
1972
      for hv_name, hv_params in self.new_hvparams.items():
1973
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1974
            (self.op.enabled_hypervisors and
1975
             hv_name in self.op.enabled_hypervisors)):
1976
          # either this is a new hypervisor, or its parameters have changed
1977
          hv_class = hypervisor.GetHypervisor(hv_name)
1978
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1979
          hv_class.CheckParameterSyntax(hv_params)
1980
          _CheckHVParams(self, node_list, hv_name, hv_params)
1981

    
1982
  def Exec(self, feedback_fn):
1983
    """Change the parameters of the cluster.
1984

1985
    """
1986
    if self.op.vg_name is not None:
1987
      new_volume = self.op.vg_name
1988
      if not new_volume:
1989
        new_volume = None
1990
      if new_volume != self.cfg.GetVGName():
1991
        self.cfg.SetVGName(new_volume)
1992
      else:
1993
        feedback_fn("Cluster LVM configuration already in desired"
1994
                    " state, not changing")
1995
    if self.op.hvparams:
1996
      self.cluster.hvparams = self.new_hvparams
1997
    if self.op.enabled_hypervisors is not None:
1998
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1999
    if self.op.beparams:
2000
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2001
    if self.op.nicparams:
2002
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2003

    
2004
    if self.op.candidate_pool_size is not None:
2005
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2006
      # we need to update the pool size here, otherwise the save will fail
2007
      _AdjustCandidatePool(self, [])
2008

    
2009
    self.cfg.Update(self.cluster, feedback_fn)
2010

    
2011

    
2012
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2013
  """Distribute additional files which are part of the cluster configuration.
2014

2015
  ConfigWriter takes care of distributing the config and ssconf files, but
2016
  there are more files which should be distributed to all nodes. This function
2017
  makes sure those are copied.
2018

2019
  @param lu: calling logical unit
2020
  @param additional_nodes: list of nodes not in the config to distribute to
2021

2022
  """
2023
  # 1. Gather target nodes
2024
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2025
  dist_nodes = lu.cfg.GetNodeList()
2026
  if additional_nodes is not None:
2027
    dist_nodes.extend(additional_nodes)
2028
  if myself.name in dist_nodes:
2029
    dist_nodes.remove(myself.name)
2030

    
2031
  # 2. Gather files to distribute
2032
  dist_files = set([constants.ETC_HOSTS,
2033
                    constants.SSH_KNOWN_HOSTS_FILE,
2034
                    constants.RAPI_CERT_FILE,
2035
                    constants.RAPI_USERS_FILE,
2036
                    constants.HMAC_CLUSTER_KEY,
2037
                   ])
2038

    
2039
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2040
  for hv_name in enabled_hypervisors:
2041
    hv_class = hypervisor.GetHypervisor(hv_name)
2042
    dist_files.update(hv_class.GetAncillaryFiles())
2043

    
2044
  # 3. Perform the files upload
2045
  for fname in dist_files:
2046
    if os.path.exists(fname):
2047
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2048
      for to_node, to_result in result.items():
2049
        msg = to_result.fail_msg
2050
        if msg:
2051
          msg = ("Copy of file %s to node %s failed: %s" %
2052
                 (fname, to_node, msg))
2053
          lu.proc.LogWarning(msg)
2054

    
2055

    
2056
class LURedistributeConfig(NoHooksLU):
2057
  """Force the redistribution of cluster configuration.
2058

2059
  This is a very simple LU.
2060

2061
  """
2062
  _OP_REQP = []
2063
  REQ_BGL = False
2064

    
2065
  def ExpandNames(self):
2066
    self.needed_locks = {
2067
      locking.LEVEL_NODE: locking.ALL_SET,
2068
    }
2069
    self.share_locks[locking.LEVEL_NODE] = 1
2070

    
2071
  def CheckPrereq(self):
2072
    """Check prerequisites.
2073

2074
    """
2075

    
2076
  def Exec(self, feedback_fn):
2077
    """Redistribute the configuration.
2078

2079
    """
2080
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2081
    _RedistributeAncillaryFiles(self)
2082

    
2083

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

2087
  """
2088
  if not instance.disks:
2089
    return True
2090

    
2091
  if not oneshot:
2092
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2093

    
2094
  node = instance.primary_node
2095

    
2096
  for dev in instance.disks:
2097
    lu.cfg.SetDiskID(dev, node)
2098

    
2099
  retries = 0
2100
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2101
  while True:
2102
    max_time = 0
2103
    done = True
2104
    cumul_degraded = False
2105
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2106
    msg = rstats.fail_msg
2107
    if msg:
2108
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2109
      retries += 1
2110
      if retries >= 10:
2111
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2112
                                 " aborting." % node)
2113
      time.sleep(6)
2114
      continue
2115
    rstats = rstats.payload
2116
    retries = 0
2117
    for i, mstat in enumerate(rstats):
2118
      if mstat is None:
2119
        lu.LogWarning("Can't compute data for node %s/%s",
2120
                           node, instance.disks[i].iv_name)
2121
        continue
2122

    
2123
      cumul_degraded = (cumul_degraded or
2124
                        (mstat.is_degraded and mstat.sync_percent is None))
2125
      if mstat.sync_percent is not None:
2126
        done = False
2127
        if mstat.estimated_time is not None:
2128
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2129
          max_time = mstat.estimated_time
2130
        else:
2131
          rem_time = "no time estimate"
2132
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2133
                        (instance.disks[i].iv_name, mstat.sync_percent,
2134
                         rem_time))
2135

    
2136
    # if we're done but degraded, let's do a few small retries, to
2137
    # make sure we see a stable and not transient situation; therefore
2138
    # we force restart of the loop
2139
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2140
      logging.info("Degraded disks found, %d retries left", degr_retries)
2141
      degr_retries -= 1
2142
      time.sleep(1)
2143
      continue
2144

    
2145
    if done or oneshot:
2146
      break
2147

    
2148
    time.sleep(min(60, max_time))
2149

    
2150
  if done:
2151
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2152
  return not cumul_degraded
2153

    
2154

    
2155
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2156
  """Check that mirrors are not degraded.
2157

2158
  The ldisk parameter, if True, will change the test from the
2159
  is_degraded attribute (which represents overall non-ok status for
2160
  the device(s)) to the ldisk (representing the local storage status).
2161

2162
  """
2163
  lu.cfg.SetDiskID(dev, node)
2164

    
2165
  result = True
2166

    
2167
  if on_primary or dev.AssembleOnSecondary():
2168
    rstats = lu.rpc.call_blockdev_find(node, dev)
2169
    msg = rstats.fail_msg
2170
    if msg:
2171
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2172
      result = False
2173
    elif not rstats.payload:
2174
      lu.LogWarning("Can't find disk on node %s", node)
2175
      result = False
2176
    else:
2177
      if ldisk:
2178
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2179
      else:
2180
        result = result and not rstats.payload.is_degraded
2181

    
2182
  if dev.children:
2183
    for child in dev.children:
2184
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2185

    
2186
  return result
2187

    
2188

    
2189
class LUDiagnoseOS(NoHooksLU):
2190
  """Logical unit for OS diagnose/query.
2191

2192
  """
2193
  _OP_REQP = ["output_fields", "names"]
2194
  REQ_BGL = False
2195
  _FIELDS_STATIC = utils.FieldSet()
2196
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2197
  # Fields that need calculation of global os validity
2198
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2199

    
2200
  def ExpandNames(self):
2201
    if self.op.names:
2202
      raise errors.OpPrereqError("Selective OS query not supported",
2203
                                 errors.ECODE_INVAL)
2204

    
2205
    _CheckOutputFields(static=self._FIELDS_STATIC,
2206
                       dynamic=self._FIELDS_DYNAMIC,
2207
                       selected=self.op.output_fields)
2208

    
2209
    # Lock all nodes, in shared mode
2210
    # Temporary removal of locks, should be reverted later
2211
    # TODO: reintroduce locks when they are lighter-weight
2212
    self.needed_locks = {}
2213
    #self.share_locks[locking.LEVEL_NODE] = 1
2214
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2215

    
2216
  def CheckPrereq(self):
2217
    """Check prerequisites.
2218

2219
    """
2220

    
2221
  @staticmethod
2222
  def _DiagnoseByOS(node_list, rlist):
2223
    """Remaps a per-node return list into an a per-os per-node dictionary
2224

2225
    @param node_list: a list with the names of all nodes
2226
    @param rlist: a map with node names as keys and OS objects as values
2227

2228
    @rtype: dict
2229
    @return: a dictionary with osnames as keys and as value another map, with
2230
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2231

2232
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2233
                                     (/srv/..., False, "invalid api")],
2234
                           "node2": [(/srv/..., True, "")]}
2235
          }
2236

2237
    """
2238
    all_os = {}
2239
    # we build here the list of nodes that didn't fail the RPC (at RPC
2240
    # level), so that nodes with a non-responding node daemon don't
2241
    # make all OSes invalid
2242
    good_nodes = [node_name for node_name in rlist
2243
                  if not rlist[node_name].fail_msg]
2244
    for node_name, nr in rlist.items():
2245
      if nr.fail_msg or not nr.payload:
2246
        continue
2247
      for name, path, status, diagnose, variants in nr.payload:
2248
        if name not in all_os:
2249
          # build a list of nodes for this os containing empty lists
2250
          # for each node in node_list
2251
          all_os[name] = {}
2252
          for nname in good_nodes:
2253
            all_os[name][nname] = []
2254
        all_os[name][node_name].append((path, status, diagnose, variants))
2255
    return all_os
2256

    
2257
  def Exec(self, feedback_fn):
2258
    """Compute the list of OSes.
2259

2260
    """
2261
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2262
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2263
    pol = self._DiagnoseByOS(valid_nodes, node_data)
2264
    output = []
2265
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2266
    calc_variants = "variants" in self.op.output_fields
2267

    
2268
    for os_name, os_data in pol.items():
2269
      row = []
2270
      if calc_valid:
2271
        valid = True
2272
        variants = None
2273
        for osl in os_data.values():
2274
          valid = valid and osl and osl[0][1]
2275
          if not valid:
2276
            variants = None
2277
            break
2278
          if calc_variants:
2279
            node_variants = osl[0][3]
2280
            if variants is None:
2281
              variants = node_variants
2282
            else:
2283
              variants = [v for v in variants if v in node_variants]
2284

    
2285
      for field in self.op.output_fields:
2286
        if field == "name":
2287
          val = os_name
2288
        elif field == "valid":
2289
          val = valid
2290
        elif field == "node_status":
2291
          # this is just a copy of the dict
2292
          val = {}
2293
          for node_name, nos_list in os_data.items():
2294
            val[node_name] = nos_list
2295
        elif field == "variants":
2296
          val =  variants
2297
        else:
2298
          raise errors.ParameterError(field)
2299
        row.append(val)
2300
      output.append(row)
2301

    
2302
    return output
2303

    
2304

    
2305
class LURemoveNode(LogicalUnit):
2306
  """Logical unit for removing a node.
2307

2308
  """
2309
  HPATH = "node-remove"
2310
  HTYPE = constants.HTYPE_NODE
2311
  _OP_REQP = ["node_name"]
2312

    
2313
  def BuildHooksEnv(self):
2314
    """Build hooks env.
2315

2316
    This doesn't run on the target node in the pre phase as a failed
2317
    node would then be impossible to remove.
2318

2319
    """
2320
    env = {
2321
      "OP_TARGET": self.op.node_name,
2322
      "NODE_NAME": self.op.node_name,
2323
      }
2324
    all_nodes = self.cfg.GetNodeList()
2325
    if self.op.node_name in all_nodes:
2326
      all_nodes.remove(self.op.node_name)
2327
    return env, all_nodes, all_nodes
2328

    
2329
  def CheckPrereq(self):
2330
    """Check prerequisites.
2331

2332
    This checks:
2333
     - the node exists in the configuration
2334
     - it does not have primary or secondary instances
2335
     - it's not the master
2336

2337
    Any errors are signaled by raising errors.OpPrereqError.
2338

2339
    """
2340
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
2341
    if node is None:
2342
      raise errors.OpPrereqError("Node '%s' is unknown." % self.op.node_name,
2343
                                 errors.ECODE_NOENT)
2344

    
2345
    instance_list = self.cfg.GetInstanceList()
2346

    
2347
    masternode = self.cfg.GetMasterNode()
2348
    if node.name == masternode:
2349
      raise errors.OpPrereqError("Node is the master node,"
2350
                                 " you need to failover first.",
2351
                                 errors.ECODE_INVAL)
2352

    
2353
    for instance_name in instance_list:
2354
      instance = self.cfg.GetInstanceInfo(instance_name)
2355
      if node.name in instance.all_nodes:
2356
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2357
                                   " please remove first." % instance_name,
2358
                                   errors.ECODE_INVAL)
2359
    self.op.node_name = node.name
2360
    self.node = node
2361

    
2362
  def Exec(self, feedback_fn):
2363
    """Removes the node from the cluster.
2364

2365
    """
2366
    node = self.node
2367
    logging.info("Stopping the node daemon and removing configs from node %s",
2368
                 node.name)
2369

    
2370
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2371

    
2372
    # Promote nodes to master candidate as needed
2373
    _AdjustCandidatePool(self, exceptions=[node.name])
2374
    self.context.RemoveNode(node.name)
2375

    
2376
    # Run post hooks on the node before it's removed
2377
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2378
    try:
2379
      h_results = hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2380
    except:
2381
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2382

    
2383
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2384
    msg = result.fail_msg
2385
    if msg:
2386
      self.LogWarning("Errors encountered on the remote node while leaving"
2387
                      " the cluster: %s", msg)
2388

    
2389

    
2390
class LUQueryNodes(NoHooksLU):
2391
  """Logical unit for querying nodes.
2392

2393
  """
2394
  _OP_REQP = ["output_fields", "names", "use_locking"]
2395
  REQ_BGL = False
2396

    
2397
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2398
                    "master_candidate", "offline", "drained"]
2399

    
2400
  _FIELDS_DYNAMIC = utils.FieldSet(
2401
    "dtotal", "dfree",
2402
    "mtotal", "mnode", "mfree",
2403
    "bootid",
2404
    "ctotal", "cnodes", "csockets",
2405
    )
2406

    
2407
  _FIELDS_STATIC = utils.FieldSet(*[
2408
    "pinst_cnt", "sinst_cnt",
2409
    "pinst_list", "sinst_list",
2410
    "pip", "sip", "tags",
2411
    "master",
2412
    "role"] + _SIMPLE_FIELDS
2413
    )
2414

    
2415
  def ExpandNames(self):
2416
    _CheckOutputFields(static=self._FIELDS_STATIC,
2417
                       dynamic=self._FIELDS_DYNAMIC,
2418
                       selected=self.op.output_fields)
2419

    
2420
    self.needed_locks = {}
2421
    self.share_locks[locking.LEVEL_NODE] = 1
2422

    
2423
    if self.op.names:
2424
      self.wanted = _GetWantedNodes(self, self.op.names)
2425
    else:
2426
      self.wanted = locking.ALL_SET
2427

    
2428
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2429
    self.do_locking = self.do_node_query and self.op.use_locking
2430
    if self.do_locking:
2431
      # if we don't request only static fields, we need to lock the nodes
2432
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2433

    
2434
  def CheckPrereq(self):
2435
    """Check prerequisites.
2436

2437
    """
2438
    # The validation of the node list is done in the _GetWantedNodes,
2439
    # if non empty, and if empty, there's no validation to do
2440
    pass
2441

    
2442
  def Exec(self, feedback_fn):
2443
    """Computes the list of nodes and their attributes.
2444

2445
    """
2446
    all_info = self.cfg.GetAllNodesInfo()
2447
    if self.do_locking:
2448
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2449
    elif self.wanted != locking.ALL_SET:
2450
      nodenames = self.wanted
2451
      missing = set(nodenames).difference(all_info.keys())
2452
      if missing:
2453
        raise errors.OpExecError(
2454
          "Some nodes were removed before retrieving their data: %s" % missing)
2455
    else:
2456
      nodenames = all_info.keys()
2457

    
2458
    nodenames = utils.NiceSort(nodenames)
2459
    nodelist = [all_info[name] for name in nodenames]
2460

    
2461
    # begin data gathering
2462

    
2463
    if self.do_node_query:
2464
      live_data = {}
2465
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2466
                                          self.cfg.GetHypervisorType())
2467
      for name in nodenames:
2468
        nodeinfo = node_data[name]
2469
        if not nodeinfo.fail_msg and nodeinfo.payload:
2470
          nodeinfo = nodeinfo.payload
2471
          fn = utils.TryConvert
2472
          live_data[name] = {
2473
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2474
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2475
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2476
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2477
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2478
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2479
            "bootid": nodeinfo.get('bootid', None),
2480
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2481
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2482
            }
2483
        else:
2484
          live_data[name] = {}
2485
    else:
2486
      live_data = dict.fromkeys(nodenames, {})
2487

    
2488
    node_to_primary = dict([(name, set()) for name in nodenames])
2489
    node_to_secondary = dict([(name, set()) for name in nodenames])
2490

    
2491
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2492
                             "sinst_cnt", "sinst_list"))
2493
    if inst_fields & frozenset(self.op.output_fields):
2494
      instancelist = self.cfg.GetInstanceList()
2495

    
2496
      for instance_name in instancelist:
2497
        inst = self.cfg.GetInstanceInfo(instance_name)
2498
        if inst.primary_node in node_to_primary:
2499
          node_to_primary[inst.primary_node].add(inst.name)
2500
        for secnode in inst.secondary_nodes:
2501
          if secnode in node_to_secondary:
2502
            node_to_secondary[secnode].add(inst.name)
2503

    
2504
    master_node = self.cfg.GetMasterNode()
2505

    
2506
    # end data gathering
2507

    
2508
    output = []
2509
    for node in nodelist:
2510
      node_output = []
2511
      for field in self.op.output_fields:
2512
        if field in self._SIMPLE_FIELDS:
2513
          val = getattr(node, field)
2514
        elif field == "pinst_list":
2515
          val = list(node_to_primary[node.name])
2516
        elif field == "sinst_list":
2517
          val = list(node_to_secondary[node.name])
2518
        elif field == "pinst_cnt":
2519
          val = len(node_to_primary[node.name])
2520
        elif field == "sinst_cnt":
2521
          val = len(node_to_secondary[node.name])
2522
        elif field == "pip":
2523
          val = node.primary_ip
2524
        elif field == "sip":
2525
          val = node.secondary_ip
2526
        elif field == "tags":
2527
          val = list(node.GetTags())
2528
        elif field == "master":
2529
          val = node.name == master_node
2530
        elif self._FIELDS_DYNAMIC.Matches(field):
2531
          val = live_data[node.name].get(field, None)
2532
        elif field == "role":
2533
          if node.name == master_node:
2534
            val = "M"
2535
          elif node.master_candidate:
2536
            val = "C"
2537
          elif node.drained:
2538
            val = "D"
2539
          elif node.offline:
2540
            val = "O"
2541
          else:
2542
            val = "R"
2543
        else:
2544
          raise errors.ParameterError(field)
2545
        node_output.append(val)
2546
      output.append(node_output)
2547

    
2548
    return output
2549

    
2550

    
2551
class LUQueryNodeVolumes(NoHooksLU):
2552
  """Logical unit for getting volumes on node(s).
2553

2554
  """
2555
  _OP_REQP = ["nodes", "output_fields"]
2556
  REQ_BGL = False
2557
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2558
  _FIELDS_STATIC = utils.FieldSet("node")
2559

    
2560
  def ExpandNames(self):
2561
    _CheckOutputFields(static=self._FIELDS_STATIC,
2562
                       dynamic=self._FIELDS_DYNAMIC,
2563
                       selected=self.op.output_fields)
2564

    
2565
    self.needed_locks = {}
2566
    self.share_locks[locking.LEVEL_NODE] = 1
2567
    if not self.op.nodes:
2568
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2569
    else:
2570
      self.needed_locks[locking.LEVEL_NODE] = \
2571
        _GetWantedNodes(self, self.op.nodes)
2572

    
2573
  def CheckPrereq(self):
2574
    """Check prerequisites.
2575

2576
    This checks that the fields required are valid output fields.
2577

2578
    """
2579
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2580

    
2581
  def Exec(self, feedback_fn):
2582
    """Computes the list of nodes and their attributes.
2583

2584
    """
2585
    nodenames = self.nodes
2586
    volumes = self.rpc.call_node_volumes(nodenames)
2587

    
2588
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2589
             in self.cfg.GetInstanceList()]
2590

    
2591
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2592

    
2593
    output = []
2594
    for node in nodenames:
2595
      nresult = volumes[node]
2596
      if nresult.offline:
2597
        continue
2598
      msg = nresult.fail_msg
2599
      if msg:
2600
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
2601
        continue
2602

    
2603
      node_vols = nresult.payload[:]
2604
      node_vols.sort(key=lambda vol: vol['dev'])
2605

    
2606
      for vol in node_vols:
2607
        node_output = []
2608
        for field in self.op.output_fields:
2609
          if field == "node":
2610
            val = node
2611
          elif field == "phys":
2612
            val = vol['dev']
2613
          elif field == "vg":
2614
            val = vol['vg']
2615
          elif field == "name":
2616
            val = vol['name']
2617
          elif field == "size":
2618
            val = int(float(vol['size']))
2619
          elif field == "instance":
2620
            for inst in ilist:
2621
              if node not in lv_by_node[inst]:
2622
                continue
2623
              if vol['name'] in lv_by_node[inst][node]:
2624
                val = inst.name
2625
                break
2626
            else:
2627
              val = '-'
2628
          else:
2629
            raise errors.ParameterError(field)
2630
          node_output.append(str(val))
2631

    
2632
        output.append(node_output)
2633

    
2634
    return output
2635

    
2636

    
2637
class LUQueryNodeStorage(NoHooksLU):
2638
  """Logical unit for getting information on storage units on node(s).
2639

2640
  """
2641
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
2642
  REQ_BGL = False
2643
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
2644

    
2645
  def ExpandNames(self):
2646
    storage_type = self.op.storage_type
2647

    
2648
    if storage_type not in constants.VALID_STORAGE_TYPES:
2649
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2650
                                 errors.ECODE_INVAL)
2651

    
2652
    _CheckOutputFields(static=self._FIELDS_STATIC,
2653
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
2654
                       selected=self.op.output_fields)
2655

    
2656
    self.needed_locks = {}
2657
    self.share_locks[locking.LEVEL_NODE] = 1
2658

    
2659
    if self.op.nodes:
2660
      self.needed_locks[locking.LEVEL_NODE] = \
2661
        _GetWantedNodes(self, self.op.nodes)
2662
    else:
2663
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2664

    
2665
  def CheckPrereq(self):
2666
    """Check prerequisites.
2667

2668
    This checks that the fields required are valid output fields.
2669

2670
    """
2671
    self.op.name = getattr(self.op, "name", None)
2672

    
2673
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2674

    
2675
  def Exec(self, feedback_fn):
2676
    """Computes the list of nodes and their attributes.
2677

2678
    """
2679
    # Always get name to sort by
2680
    if constants.SF_NAME in self.op.output_fields:
2681
      fields = self.op.output_fields[:]
2682
    else:
2683
      fields = [constants.SF_NAME] + self.op.output_fields
2684

    
2685
    # Never ask for node or type as it's only known to the LU
2686
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
2687
      while extra in fields:
2688
        fields.remove(extra)
2689

    
2690
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
2691
    name_idx = field_idx[constants.SF_NAME]
2692

    
2693
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2694
    data = self.rpc.call_storage_list(self.nodes,
2695
                                      self.op.storage_type, st_args,
2696
                                      self.op.name, fields)
2697

    
2698
    result = []
2699

    
2700
    for node in utils.NiceSort(self.nodes):
2701
      nresult = data[node]
2702
      if nresult.offline:
2703
        continue
2704

    
2705
      msg = nresult.fail_msg
2706
      if msg:
2707
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
2708
        continue
2709

    
2710
      rows = dict([(row[name_idx], row) for row in nresult.payload])
2711

    
2712
      for name in utils.NiceSort(rows.keys()):
2713
        row = rows[name]
2714

    
2715
        out = []
2716

    
2717
        for field in self.op.output_fields:
2718
          if field == constants.SF_NODE:
2719
            val = node
2720
          elif field == constants.SF_TYPE:
2721
            val = self.op.storage_type
2722
          elif field in field_idx:
2723
            val = row[field_idx[field]]
2724
          else:
2725
            raise errors.ParameterError(field)
2726

    
2727
          out.append(val)
2728

    
2729
        result.append(out)
2730

    
2731
    return result
2732

    
2733

    
2734
class LUModifyNodeStorage(NoHooksLU):
2735
  """Logical unit for modifying a storage volume on a node.
2736

2737
  """
2738
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
2739
  REQ_BGL = False
2740

    
2741
  def CheckArguments(self):
2742
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2743
    if node_name is None:
2744
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
2745
                                 errors.ECODE_NOENT)
2746

    
2747
    self.op.node_name = node_name
2748

    
2749
    storage_type = self.op.storage_type
2750
    if storage_type not in constants.VALID_STORAGE_TYPES:
2751
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2752
                                 errors.ECODE_INVAL)
2753

    
2754
  def ExpandNames(self):
2755
    self.needed_locks = {
2756
      locking.LEVEL_NODE: self.op.node_name,
2757
      }
2758

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

2762
    """
2763
    storage_type = self.op.storage_type
2764

    
2765
    try:
2766
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
2767
    except KeyError:
2768
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
2769
                                 " modified" % storage_type,
2770
                                 errors.ECODE_INVAL)
2771

    
2772
    diff = set(self.op.changes.keys()) - modifiable
2773
    if diff:
2774
      raise errors.OpPrereqError("The following fields can not be modified for"
2775
                                 " storage units of type '%s': %r" %
2776
                                 (storage_type, list(diff)),
2777
                                 errors.ECODE_INVAL)
2778

    
2779
  def Exec(self, feedback_fn):
2780
    """Computes the list of nodes and their attributes.
2781

2782
    """
2783
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2784
    result = self.rpc.call_storage_modify(self.op.node_name,
2785
                                          self.op.storage_type, st_args,
2786
                                          self.op.name, self.op.changes)
2787
    result.Raise("Failed to modify storage unit '%s' on %s" %
2788
                 (self.op.name, self.op.node_name))
2789

    
2790

    
2791
class LUAddNode(LogicalUnit):
2792
  """Logical unit for adding node to the cluster.
2793

2794
  """
2795
  HPATH = "node-add"
2796
  HTYPE = constants.HTYPE_NODE
2797
  _OP_REQP = ["node_name"]
2798

    
2799
  def BuildHooksEnv(self):
2800
    """Build hooks env.
2801

2802
    This will run on all nodes before, and on all nodes + the new node after.
2803

2804
    """
2805
    env = {
2806
      "OP_TARGET": self.op.node_name,
2807
      "NODE_NAME": self.op.node_name,
2808
      "NODE_PIP": self.op.primary_ip,
2809
      "NODE_SIP": self.op.secondary_ip,
2810
      }
2811
    nodes_0 = self.cfg.GetNodeList()
2812
    nodes_1 = nodes_0 + [self.op.node_name, ]
2813
    return env, nodes_0, nodes_1
2814

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

2818
    This checks:
2819
     - the new node is not already in the config
2820
     - it is resolvable
2821
     - its parameters (single/dual homed) matches the cluster
2822

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

2825
    """
2826
    node_name = self.op.node_name
2827
    cfg = self.cfg
2828

    
2829
    dns_data = utils.HostInfo(node_name)
2830

    
2831
    node = dns_data.name
2832
    primary_ip = self.op.primary_ip = dns_data.ip
2833
    secondary_ip = getattr(self.op, "secondary_ip", None)
2834
    if secondary_ip is None:
2835
      secondary_ip = primary_ip
2836
    if not utils.IsValidIP(secondary_ip):
2837
      raise errors.OpPrereqError("Invalid secondary IP given",
2838
                                 errors.ECODE_INVAL)
2839
    self.op.secondary_ip = secondary_ip
2840

    
2841
    node_list = cfg.GetNodeList()
2842
    if not self.op.readd and node in node_list:
2843
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2844
                                 node, errors.ECODE_EXISTS)
2845
    elif self.op.readd and node not in node_list:
2846
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
2847
                                 errors.ECODE_NOENT)
2848

    
2849
    for existing_node_name in node_list:
2850
      existing_node = cfg.GetNodeInfo(existing_node_name)
2851

    
2852
      if self.op.readd and node == existing_node_name:
2853
        if (existing_node.primary_ip != primary_ip or
2854
            existing_node.secondary_ip != secondary_ip):
2855
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2856
                                     " address configuration as before",
2857
                                     errors.ECODE_INVAL)
2858
        continue
2859

    
2860
      if (existing_node.primary_ip == primary_ip or
2861
          existing_node.secondary_ip == primary_ip or
2862
          existing_node.primary_ip == secondary_ip or
2863
          existing_node.secondary_ip == secondary_ip):
2864
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2865
                                   " existing node %s" % existing_node.name,
2866
                                   errors.ECODE_NOTUNIQUE)
2867

    
2868
    # check that the type of the node (single versus dual homed) is the
2869
    # same as for the master
2870
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2871
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2872
    newbie_singlehomed = secondary_ip == primary_ip
2873
    if master_singlehomed != newbie_singlehomed:
2874
      if master_singlehomed:
2875
        raise errors.OpPrereqError("The master has no private ip but the"
2876
                                   " new node has one",
2877
                                   errors.ECODE_INVAL)
2878
      else:
2879
        raise errors.OpPrereqError("The master has a private ip but the"
2880
                                   " new node doesn't have one",
2881
                                   errors.ECODE_INVAL)
2882

    
2883
    # checks reachability
2884
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2885
      raise errors.OpPrereqError("Node not reachable by ping",
2886
                                 errors.ECODE_ENVIRON)
2887

    
2888
    if not newbie_singlehomed:
2889
      # check reachability from my secondary ip to newbie's secondary ip
2890
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2891
                           source=myself.secondary_ip):
2892
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2893
                                   " based ping to noded port",
2894
                                   errors.ECODE_ENVIRON)
2895

    
2896
    if self.op.readd:
2897
      exceptions = [node]
2898
    else:
2899
      exceptions = []
2900

    
2901
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
2902

    
2903
    if self.op.readd:
2904
      self.new_node = self.cfg.GetNodeInfo(node)
2905
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
2906
    else:
2907
      self.new_node = objects.Node(name=node,
2908
                                   primary_ip=primary_ip,
2909
                                   secondary_ip=secondary_ip,
2910
                                   master_candidate=self.master_candidate,
2911
                                   offline=False, drained=False)
2912

    
2913
  def Exec(self, feedback_fn):
2914
    """Adds the new node to the cluster.
2915

2916
    """
2917
    new_node = self.new_node
2918
    node = new_node.name
2919

    
2920
    # for re-adds, reset the offline/drained/master-candidate flags;
2921
    # we need to reset here, otherwise offline would prevent RPC calls
2922
    # later in the procedure; this also means that if the re-add
2923
    # fails, we are left with a non-offlined, broken node
2924
    if self.op.readd:
2925
      new_node.drained = new_node.offline = False
2926
      self.LogInfo("Readding a node, the offline/drained flags were reset")
2927
      # if we demote the node, we do cleanup later in the procedure
2928
      new_node.master_candidate = self.master_candidate
2929

    
2930
    # notify the user about any possible mc promotion
2931
    if new_node.master_candidate:
2932
      self.LogInfo("Node will be a master candidate")
2933

    
2934
    # check connectivity
2935
    result = self.rpc.call_version([node])[node]
2936
    result.Raise("Can't get version information from node %s" % node)
2937
    if constants.PROTOCOL_VERSION == result.payload:
2938
      logging.info("Communication to node %s fine, sw version %s match",
2939
                   node, result.payload)
2940
    else:
2941
      raise errors.OpExecError("Version mismatch master version %s,"
2942
                               " node version %s" %
2943
                               (constants.PROTOCOL_VERSION, result.payload))
2944

    
2945
    # setup ssh on node
2946
    if self.cfg.GetClusterInfo().modify_ssh_setup:
2947
      logging.info("Copy ssh key to node %s", node)
2948
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2949
      keyarray = []
2950
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2951
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2952
                  priv_key, pub_key]
2953

    
2954
      for i in keyfiles:
2955
        keyarray.append(utils.ReadFile(i))
2956

    
2957
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2958
                                      keyarray[2], keyarray[3], keyarray[4],
2959
                                      keyarray[5])
2960
      result.Raise("Cannot transfer ssh keys to the new node")
2961

    
2962
    # Add node to our /etc/hosts, and add key to known_hosts
2963
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2964
      utils.AddHostToEtcHosts(new_node.name)
2965

    
2966
    if new_node.secondary_ip != new_node.primary_ip:
2967
      result = self.rpc.call_node_has_ip_address(new_node.name,
2968
                                                 new_node.secondary_ip)
2969
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
2970
                   prereq=True)
2971
      if not result.payload:
2972
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2973
                                 " you gave (%s). Please fix and re-run this"
2974
                                 " command." % new_node.secondary_ip)
2975

    
2976
    node_verify_list = [self.cfg.GetMasterNode()]
2977
    node_verify_param = {
2978
      constants.NV_NODELIST: [node],
2979
      # TODO: do a node-net-test as well?
2980
    }
2981

    
2982
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2983
                                       self.cfg.GetClusterName())
2984
    for verifier in node_verify_list:
2985
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
2986
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
2987
      if nl_payload:
2988
        for failed in nl_payload:
2989
          feedback_fn("ssh/hostname verification failed"
2990
                      " (checking from %s): %s" %
2991
                      (verifier, nl_payload[failed]))
2992
        raise errors.OpExecError("ssh/hostname verification failed.")
2993

    
2994
    if self.op.readd:
2995
      _RedistributeAncillaryFiles(self)
2996
      self.context.ReaddNode(new_node)
2997
      # make sure we redistribute the config
2998
      self.cfg.Update(new_node, feedback_fn)
2999
      # and make sure the new node will not have old files around
3000
      if not new_node.master_candidate:
3001
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3002
        msg = result.fail_msg
3003
        if msg:
3004
          self.LogWarning("Node failed to demote itself from master"
3005
                          " candidate status: %s" % msg)
3006
    else:
3007
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3008
      self.context.AddNode(new_node)
3009

    
3010

    
3011
class LUSetNodeParams(LogicalUnit):
3012
  """Modifies the parameters of a node.
3013

3014
  """
3015
  HPATH = "node-modify"
3016
  HTYPE = constants.HTYPE_NODE
3017
  _OP_REQP = ["node_name"]
3018
  REQ_BGL = False
3019

    
3020
  def CheckArguments(self):
3021
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3022
    if node_name is None:
3023
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3024
                                 errors.ECODE_INVAL)
3025
    self.op.node_name = node_name
3026
    _CheckBooleanOpField(self.op, 'master_candidate')
3027
    _CheckBooleanOpField(self.op, 'offline')
3028
    _CheckBooleanOpField(self.op, 'drained')
3029
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3030
    if all_mods.count(None) == 3:
3031
      raise errors.OpPrereqError("Please pass at least one modification",
3032
                                 errors.ECODE_INVAL)
3033
    if all_mods.count(True) > 1:
3034
      raise errors.OpPrereqError("Can't set the node into more than one"
3035
                                 " state at the same time",
3036
                                 errors.ECODE_INVAL)
3037

    
3038
  def ExpandNames(self):
3039
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3040

    
3041
  def BuildHooksEnv(self):
3042
    """Build hooks env.
3043

3044
    This runs on the master node.
3045

3046
    """
3047
    env = {
3048
      "OP_TARGET": self.op.node_name,
3049
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3050
      "OFFLINE": str(self.op.offline),
3051
      "DRAINED": str(self.op.drained),
3052
      }
3053
    nl = [self.cfg.GetMasterNode(),
3054
          self.op.node_name]
3055
    return env, nl, nl
3056

    
3057
  def CheckPrereq(self):
3058
    """Check prerequisites.
3059

3060
    This only checks the instance list against the existing names.
3061

3062
    """
3063
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3064

    
3065
    if (self.op.master_candidate is not None or
3066
        self.op.drained is not None or
3067
        self.op.offline is not None):
3068
      # we can't change the master's node flags
3069
      if self.op.node_name == self.cfg.GetMasterNode():
3070
        raise errors.OpPrereqError("The master role can be changed"
3071
                                   " only via masterfailover",
3072
                                   errors.ECODE_INVAL)
3073

    
3074
    # Boolean value that tells us whether we're offlining or draining the node
3075
    offline_or_drain = self.op.offline == True or self.op.drained == True
3076
    deoffline_or_drain = self.op.offline == False or self.op.drained == False
3077

    
3078
    if (node.master_candidate and
3079
        (self.op.master_candidate == False or offline_or_drain)):
3080
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
3081
      mc_now, mc_should, mc_max = self.cfg.GetMasterCandidateStats()
3082
      if mc_now <= cp_size:
3083
        msg = ("Not enough master candidates (desired"
3084
               " %d, new value will be %d)" % (cp_size, mc_now-1))
3085
        # Only allow forcing the operation if it's an offline/drain operation,
3086
        # and we could not possibly promote more nodes.
3087
        # FIXME: this can still lead to issues if in any way another node which
3088
        # could be promoted appears in the meantime.
3089
        if self.op.force and offline_or_drain and mc_should == mc_max:
3090
          self.LogWarning(msg)
3091
        else:
3092
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
3093

    
3094
    if (self.op.master_candidate == True and
3095
        ((node.offline and not self.op.offline == False) or
3096
         (node.drained and not self.op.drained == False))):
3097
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3098
                                 " to master_candidate" % node.name,
3099
                                 errors.ECODE_INVAL)
3100

    
3101
    # If we're being deofflined/drained, we'll MC ourself if needed
3102
    if (deoffline_or_drain and not offline_or_drain and not
3103
        self.op.master_candidate == True):
3104
      self.op.master_candidate = _DecideSelfPromotion(self)
3105
      if self.op.master_candidate:
3106
        self.LogInfo("Autopromoting node to master candidate")
3107

    
3108
    return
3109

    
3110
  def Exec(self, feedback_fn):
3111
    """Modifies a node.
3112

3113
    """
3114
    node = self.node
3115

    
3116
    result = []
3117
    changed_mc = False
3118

    
3119
    if self.op.offline is not None:
3120
      node.offline = self.op.offline
3121
      result.append(("offline", str(self.op.offline)))
3122
      if self.op.offline == True:
3123
        if node.master_candidate:
3124
          node.master_candidate = False
3125
          changed_mc = True
3126
          result.append(("master_candidate", "auto-demotion due to offline"))
3127
        if node.drained:
3128
          node.drained = False
3129
          result.append(("drained", "clear drained status due to offline"))
3130

    
3131
    if self.op.master_candidate is not None:
3132
      node.master_candidate = self.op.master_candidate
3133
      changed_mc = True
3134
      result.append(("master_candidate", str(self.op.master_candidate)))
3135
      if self.op.master_candidate == False:
3136
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3137
        msg = rrc.fail_msg
3138
        if msg:
3139
          self.LogWarning("Node failed to demote itself: %s" % msg)
3140

    
3141
    if self.op.drained is not None:
3142
      node.drained = self.op.drained
3143
      result.append(("drained", str(self.op.drained)))
3144
      if self.op.drained == True:
3145
        if node.master_candidate:
3146
          node.master_candidate = False
3147
          changed_mc = True
3148
          result.append(("master_candidate", "auto-demotion due to drain"))
3149
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3150
          msg = rrc.fail_msg
3151
          if msg:
3152
            self.LogWarning("Node failed to demote itself: %s" % msg)
3153
        if node.offline:
3154
          node.offline = False
3155
          result.append(("offline", "clear offline status due to drain"))
3156

    
3157
    # this will trigger configuration file update, if needed
3158
    self.cfg.Update(node, feedback_fn)
3159
    # this will trigger job queue propagation or cleanup
3160
    if changed_mc:
3161
      self.context.ReaddNode(node)
3162

    
3163
    return result
3164

    
3165

    
3166
class LUPowercycleNode(NoHooksLU):
3167
  """Powercycles a node.
3168

3169
  """
3170
  _OP_REQP = ["node_name", "force"]
3171
  REQ_BGL = False
3172

    
3173
  def CheckArguments(self):
3174
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3175
    if node_name is None:
3176
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3177
                                 errors.ECODE_NOENT)
3178
    self.op.node_name = node_name
3179
    if node_name == self.cfg.GetMasterNode() and not self.op.force:
3180
      raise errors.OpPrereqError("The node is the master and the force"
3181
                                 " parameter was not set",
3182
                                 errors.ECODE_INVAL)
3183

    
3184
  def ExpandNames(self):
3185
    """Locking for PowercycleNode.
3186

3187
    This is a last-resort option and shouldn't block on other
3188
    jobs. Therefore, we grab no locks.
3189

3190
    """
3191
    self.needed_locks = {}
3192

    
3193
  def CheckPrereq(self):
3194
    """Check prerequisites.
3195

3196
    This LU has no prereqs.
3197

3198
    """
3199
    pass
3200

    
3201
  def Exec(self, feedback_fn):
3202
    """Reboots a node.
3203

3204
    """
3205
    result = self.rpc.call_node_powercycle(self.op.node_name,
3206
                                           self.cfg.GetHypervisorType())
3207
    result.Raise("Failed to schedule the reboot")
3208
    return result.payload
3209

    
3210

    
3211
class LUQueryClusterInfo(NoHooksLU):
3212
  """Query cluster configuration.
3213

3214
  """
3215
  _OP_REQP = []
3216
  REQ_BGL = False
3217

    
3218
  def ExpandNames(self):
3219
    self.needed_locks = {}
3220

    
3221
  def CheckPrereq(self):
3222
    """No prerequsites needed for this LU.
3223

3224
    """
3225
    pass
3226

    
3227
  def Exec(self, feedback_fn):
3228
    """Return cluster config.
3229

3230
    """
3231
    cluster = self.cfg.GetClusterInfo()
3232
    result = {
3233
      "software_version": constants.RELEASE_VERSION,
3234
      "protocol_version": constants.PROTOCOL_VERSION,
3235
      "config_version": constants.CONFIG_VERSION,
3236
      "os_api_version": max(constants.OS_API_VERSIONS),
3237
      "export_version": constants.EXPORT_VERSION,
3238
      "architecture": (platform.architecture()[0], platform.machine()),
3239
      "name": cluster.cluster_name,
3240
      "master": cluster.master_node,
3241
      "default_hypervisor": cluster.enabled_hypervisors[0],
3242
      "enabled_hypervisors": cluster.enabled_hypervisors,
3243
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3244
                        for hypervisor_name in cluster.enabled_hypervisors]),
3245
      "beparams": cluster.beparams,
3246
      "nicparams": cluster.nicparams,
3247
      "candidate_pool_size": cluster.candidate_pool_size,
3248
      "master_netdev": cluster.master_netdev,
3249
      "volume_group_name": cluster.volume_group_name,
3250
      "file_storage_dir": cluster.file_storage_dir,
3251
      "ctime": cluster.ctime,
3252
      "mtime": cluster.mtime,
3253
      "uuid": cluster.uuid,
3254
      "tags": list(cluster.GetTags()),
3255
      }
3256

    
3257
    return result
3258

    
3259

    
3260
class LUQueryConfigValues(NoHooksLU):
3261
  """Return configuration values.
3262

3263
  """
3264
  _OP_REQP = []
3265
  REQ_BGL = False
3266
  _FIELDS_DYNAMIC = utils.FieldSet()
3267
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3268
                                  "watcher_pause")
3269

    
3270
  def ExpandNames(self):
3271
    self.needed_locks = {}
3272

    
3273
    _CheckOutputFields(static=self._FIELDS_STATIC,
3274
                       dynamic=self._FIELDS_DYNAMIC,
3275
                       selected=self.op.output_fields)
3276

    
3277
  def CheckPrereq(self):
3278
    """No prerequisites.
3279

3280
    """
3281
    pass
3282

    
3283
  def Exec(self, feedback_fn):
3284
    """Dump a representation of the cluster config to the standard output.
3285

3286
    """
3287
    values = []
3288
    for field in self.op.output_fields:
3289
      if field == "cluster_name":
3290
        entry = self.cfg.GetClusterName()
3291
      elif field == "master_node":
3292
        entry = self.cfg.GetMasterNode()
3293
      elif field == "drain_flag":
3294
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3295
      elif field == "watcher_pause":
3296
        return utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3297
      else:
3298
        raise errors.ParameterError(field)
3299
      values.append(entry)
3300
    return values
3301

    
3302

    
3303
class LUActivateInstanceDisks(NoHooksLU):
3304
  """Bring up an instance's disks.
3305

3306
  """
3307
  _OP_REQP = ["instance_name"]
3308
  REQ_BGL = False
3309

    
3310
  def ExpandNames(self):
3311
    self._ExpandAndLockInstance()
3312
    self.needed_locks[locking.LEVEL_NODE] = []
3313
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3314

    
3315
  def DeclareLocks(self, level):
3316
    if level == locking.LEVEL_NODE:
3317
      self._LockInstancesNodes()
3318

    
3319
  def CheckPrereq(self):
3320
    """Check prerequisites.
3321

3322
    This checks that the instance is in the cluster.
3323

3324
    """
3325
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3326
    assert self.instance is not None, \
3327
      "Cannot retrieve locked instance %s" % self.op.instance_name
3328
    _CheckNodeOnline(self, self.instance.primary_node)
3329
    if not hasattr(self.op, "ignore_size"):
3330
      self.op.ignore_size = False
3331

    
3332
  def Exec(self, feedback_fn):
3333
    """Activate the disks.
3334

3335
    """
3336
    disks_ok, disks_info = \
3337
              _AssembleInstanceDisks(self, self.instance,
3338
                                     ignore_size=self.op.ignore_size)
3339
    if not disks_ok:
3340
      raise errors.OpExecError("Cannot activate block devices")
3341

    
3342
    return disks_info
3343

    
3344

    
3345
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3346
                           ignore_size=False):
3347
  """Prepare the block devices for an instance.
3348

3349
  This sets up the block devices on all nodes.
3350

3351
  @type lu: L{LogicalUnit}
3352
  @param lu: the logical unit on whose behalf we execute
3353
  @type instance: L{objects.Instance}
3354
  @param instance: the instance for whose disks we assemble
3355
  @type ignore_secondaries: boolean
3356
  @param ignore_secondaries: if true, errors on secondary nodes
3357
      won't result in an error return from the function
3358
  @type ignore_size: boolean
3359
  @param ignore_size: if true, the current known size of the disk
3360
      will not be used during the disk activation, useful for cases
3361
      when the size is wrong
3362
  @return: False if the operation failed, otherwise a list of
3363
      (host, instance_visible_name, node_visible_name)
3364
      with the mapping from node devices to instance devices
3365

3366
  """
3367
  device_info = []
3368
  disks_ok = True
3369
  iname = instance.name
3370
  # With the two passes mechanism we try to reduce the window of
3371
  # opportunity for the race condition of switching DRBD to primary
3372
  # before handshaking occured, but we do not eliminate it
3373

    
3374
  # The proper fix would be to wait (with some limits) until the
3375
  # connection has been made and drbd transitions from WFConnection
3376
  # into any other network-connected state (Connected, SyncTarget,
3377
  # SyncSource, etc.)
3378

    
3379
  # 1st pass, assemble on all nodes in secondary mode
3380
  for inst_disk in instance.disks:
3381
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3382
      if ignore_size:
3383
        node_disk = node_disk.Copy()
3384
        node_disk.UnsetSize()
3385
      lu.cfg.SetDiskID(node_disk, node)
3386
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3387
      msg = result.fail_msg
3388
      if msg:
3389
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3390
                           " (is_primary=False, pass=1): %s",
3391
                           inst_disk.iv_name, node, msg)
3392
        if not ignore_secondaries:
3393
          disks_ok = False
3394

    
3395
  # FIXME: race condition on drbd migration to primary
3396

    
3397
  # 2nd pass, do only the primary node
3398
  for inst_disk in instance.disks:
3399
    dev_path = None
3400

    
3401
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3402
      if node != instance.primary_node:
3403
        continue
3404
      if ignore_size:
3405
        node_disk = node_disk.Copy()
3406
        node_disk.UnsetSize()
3407
      lu.cfg.SetDiskID(node_disk, node)
3408
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3409
      msg = result.fail_msg
3410
      if msg:
3411
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3412
                           " (is_primary=True, pass=2): %s",
3413
                           inst_disk.iv_name, node, msg)
3414
        disks_ok = False
3415
      else:
3416
        dev_path = result.payload
3417

    
3418
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3419

    
3420
  # leave the disks configured for the primary node
3421
  # this is a workaround that would be fixed better by
3422
  # improving the logical/physical id handling
3423
  for disk in instance.disks:
3424
    lu.cfg.SetDiskID(disk, instance.primary_node)
3425

    
3426
  return disks_ok, device_info
3427

    
3428

    
3429
def _StartInstanceDisks(lu, instance, force):
3430
  """Start the disks of an instance.
3431

3432
  """
3433
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3434
                                           ignore_secondaries=force)
3435
  if not disks_ok:
3436
    _ShutdownInstanceDisks(lu, instance)
3437
    if force is not None and not force:
3438
      lu.proc.LogWarning("", hint="If the message above refers to a"
3439
                         " secondary node,"
3440
                         " you can retry the operation using '--force'.")
3441
    raise errors.OpExecError("Disk consistency error")
3442

    
3443

    
3444
class LUDeactivateInstanceDisks(NoHooksLU):
3445
  """Shutdown an instance's disks.
3446

3447
  """
3448
  _OP_REQP = ["instance_name"]
3449
  REQ_BGL = False
3450

    
3451
  def ExpandNames(self):
3452
    self._ExpandAndLockInstance()
3453
    self.needed_locks[locking.LEVEL_NODE] = []
3454
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3455

    
3456
  def DeclareLocks(self, level):
3457
    if level == locking.LEVEL_NODE:
3458
      self._LockInstancesNodes()
3459

    
3460
  def CheckPrereq(self):
3461
    """Check prerequisites.
3462

3463
    This checks that the instance is in the cluster.
3464

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

    
3470
  def Exec(self, feedback_fn):
3471
    """Deactivate the disks
3472

3473
    """
3474
    instance = self.instance
3475
    _SafeShutdownInstanceDisks(self, instance)
3476

    
3477

    
3478
def _SafeShutdownInstanceDisks(lu, instance):
3479
  """Shutdown block devices of an instance.
3480

3481
  This function checks if an instance is running, before calling
3482
  _ShutdownInstanceDisks.
3483

3484
  """
3485
  pnode = instance.primary_node
3486
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
3487
  ins_l.Raise("Can't contact node %s" % pnode)
3488

    
3489
  if instance.name in ins_l.payload:
3490
    raise errors.OpExecError("Instance is running, can't shutdown"
3491
                             " block devices.")
3492

    
3493
  _ShutdownInstanceDisks(lu, instance)
3494

    
3495

    
3496
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3497
  """Shutdown block devices of an instance.
3498

3499
  This does the shutdown on all nodes of the instance.
3500

3501
  If the ignore_primary is false, errors on the primary node are
3502
  ignored.
3503

3504
  """
3505
  all_result = True
3506
  for disk in instance.disks:
3507
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3508
      lu.cfg.SetDiskID(top_disk, node)
3509
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3510
      msg = result.fail_msg
3511
      if msg:
3512
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3513
                      disk.iv_name, node, msg)
3514
        if not ignore_primary or node != instance.primary_node:
3515
          all_result = False
3516
  return all_result
3517

    
3518

    
3519
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3520
  """Checks if a node has enough free memory.
3521

3522
  This function check if a given node has the needed amount of free
3523
  memory. In case the node has less memory or we cannot get the
3524
  information from the node, this function raise an OpPrereqError
3525
  exception.
3526

3527
  @type lu: C{LogicalUnit}
3528
  @param lu: a logical unit from which we get configuration data
3529
  @type node: C{str}
3530
  @param node: the node to check
3531
  @type reason: C{str}
3532
  @param reason: string to use in the error message
3533
  @type requested: C{int}
3534
  @param requested: the amount of memory in MiB to check for
3535
  @type hypervisor_name: C{str}
3536
  @param hypervisor_name: the hypervisor to ask for memory stats
3537
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3538
      we cannot check the node
3539

3540
  """
3541
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3542
  nodeinfo[node].Raise("Can't get data from node %s" % node, prereq=True)
3543
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3544
  if not isinstance(free_mem, int):
3545
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3546
                               " was '%s'" % (node, free_mem),
3547
                               errors.ECODE_ENVIRON)
3548
  if requested > free_mem:
3549
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3550
                               " needed %s MiB, available %s MiB" %
3551
                               (node, reason, requested, free_mem),
3552
                               errors.ECODE_NORES)
3553

    
3554

    
3555
class LUStartupInstance(LogicalUnit):
3556
  """Starts an instance.
3557

3558
  """
3559
  HPATH = "instance-start"
3560
  HTYPE = constants.HTYPE_INSTANCE
3561
  _OP_REQP = ["instance_name", "force"]
3562
  REQ_BGL = False
3563

    
3564
  def ExpandNames(self):
3565
    self._ExpandAndLockInstance()
3566

    
3567
  def BuildHooksEnv(self):
3568
    """Build hooks env.
3569

3570
    This runs on master, primary and secondary nodes of the instance.
3571

3572
    """
3573
    env = {
3574
      "FORCE": self.op.force,
3575
      }
3576
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3577
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3578
    return env, nl, nl
3579

    
3580
  def CheckPrereq(self):
3581
    """Check prerequisites.
3582

3583
    This checks that the instance is in the cluster.
3584

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

    
3590
    # extra beparams
3591
    self.beparams = getattr(self.op, "beparams", {})
3592
    if self.beparams:
3593
      if not isinstance(self.beparams, dict):
3594
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3595
                                   " dict" % (type(self.beparams), ),
3596
                                   errors.ECODE_INVAL)
3597
      # fill the beparams dict
3598
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3599
      self.op.beparams = self.beparams
3600

    
3601
    # extra hvparams
3602
    self.hvparams = getattr(self.op, "hvparams", {})
3603
    if self.hvparams:
3604
      if not isinstance(self.hvparams, dict):
3605
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3606
                                   " dict" % (type(self.hvparams), ),
3607
                                   errors.ECODE_INVAL)
3608

    
3609
      # check hypervisor parameter syntax (locally)
3610
      cluster = self.cfg.GetClusterInfo()
3611
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3612
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
3613
                                    instance.hvparams)
3614
      filled_hvp.update(self.hvparams)
3615
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3616
      hv_type.CheckParameterSyntax(filled_hvp)
3617
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3618
      self.op.hvparams = self.hvparams
3619

    
3620
    _CheckNodeOnline(self, instance.primary_node)
3621

    
3622
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3623
    # check bridges existence
3624
    _CheckInstanceBridgesExist(self, instance)
3625

    
3626
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3627
                                              instance.name,
3628
                                              instance.hypervisor)
3629
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3630
                      prereq=True)
3631
    if not remote_info.payload: # not running already
3632
      _CheckNodeFreeMemory(self, instance.primary_node,
3633
                           "starting instance %s" % instance.name,
3634
                           bep[constants.BE_MEMORY], instance.hypervisor)
3635

    
3636
  def Exec(self, feedback_fn):
3637
    """Start the instance.
3638

3639
    """
3640
    instance = self.instance
3641
    force = self.op.force
3642

    
3643
    self.cfg.MarkInstanceUp(instance.name)
3644

    
3645
    node_current = instance.primary_node
3646

    
3647
    _StartInstanceDisks(self, instance, force)
3648

    
3649
    result = self.rpc.call_instance_start(node_current, instance,
3650
                                          self.hvparams, self.beparams)
3651
    msg = result.fail_msg
3652
    if msg:
3653
      _ShutdownInstanceDisks(self, instance)
3654
      raise errors.OpExecError("Could not start instance: %s" % msg)
3655

    
3656

    
3657
class LURebootInstance(LogicalUnit):
3658
  """Reboot an instance.
3659

3660
  """
3661
  HPATH = "instance-reboot"
3662
  HTYPE = constants.HTYPE_INSTANCE
3663
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3664
  REQ_BGL = False
3665

    
3666
  def CheckArguments(self):
3667
    """Check the arguments.
3668

3669
    """
3670
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
3671
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
3672

    
3673
  def ExpandNames(self):
3674
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3675
                                   constants.INSTANCE_REBOOT_HARD,
3676
                                   constants.INSTANCE_REBOOT_FULL]:
3677
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3678
                                  (constants.INSTANCE_REBOOT_SOFT,
3679
                                   constants.INSTANCE_REBOOT_HARD,
3680
                                   constants.INSTANCE_REBOOT_FULL))
3681
    self._ExpandAndLockInstance()
3682

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

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

3688
    """
3689
    env = {
3690
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3691
      "REBOOT_TYPE": self.op.reboot_type,
3692
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
3693
      }
3694
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3695
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3696
    return env, nl, nl
3697

    
3698
  def CheckPrereq(self):
3699
    """Check prerequisites.
3700

3701
    This checks that the instance is in the cluster.
3702

3703
    """
3704
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3705
    assert self.instance is not None, \
3706
      "Cannot retrieve locked instance %s" % self.op.instance_name
3707

    
3708
    _CheckNodeOnline(self, instance.primary_node)
3709

    
3710
    # check bridges existence
3711
    _CheckInstanceBridgesExist(self, instance)
3712

    
3713
  def Exec(self, feedback_fn):
3714
    """Reboot the instance.
3715

3716
    """
3717
    instance = self.instance
3718
    ignore_secondaries = self.op.ignore_secondaries
3719
    reboot_type = self.op.reboot_type
3720

    
3721
    node_current = instance.primary_node
3722

    
3723
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3724
                       constants.INSTANCE_REBOOT_HARD]:
3725
      for disk in instance.disks:
3726
        self.cfg.SetDiskID(disk, node_current)
3727
      result = self.rpc.call_instance_reboot(node_current, instance,
3728
                                             reboot_type,
3729
                                             self.shutdown_timeout)
3730
      result.Raise("Could not reboot instance")
3731
    else:
3732
      result = self.rpc.call_instance_shutdown(node_current, instance,
3733
                                               self.shutdown_timeout)
3734
      result.Raise("Could not shutdown instance for full reboot")
3735
      _ShutdownInstanceDisks(self, instance)
3736
      _StartInstanceDisks(self, instance, ignore_secondaries)
3737
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3738
      msg = result.fail_msg
3739
      if msg:
3740
        _ShutdownInstanceDisks(self, instance)
3741
        raise errors.OpExecError("Could not start instance for"
3742
                                 " full reboot: %s" % msg)
3743

    
3744
    self.cfg.MarkInstanceUp(instance.name)
3745

    
3746

    
3747
class LUShutdownInstance(LogicalUnit):
3748
  """Shutdown an instance.
3749

3750
  """
3751
  HPATH = "instance-stop"
3752
  HTYPE = constants.HTYPE_INSTANCE
3753
  _OP_REQP = ["instance_name"]
3754
  REQ_BGL = False
3755

    
3756
  def CheckArguments(self):
3757
    """Check the arguments.
3758

3759
    """
3760
    self.timeout = getattr(self.op, "timeout",
3761
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
3762

    
3763
  def ExpandNames(self):
3764
    self._ExpandAndLockInstance()
3765

    
3766
  def BuildHooksEnv(self):
3767
    """Build hooks env.
3768

3769
    This runs on master, primary and secondary nodes of the instance.
3770

3771
    """
3772
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3773
    env["TIMEOUT"] = self.timeout
3774
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3775
    return env, nl, nl
3776

    
3777
  def CheckPrereq(self):
3778
    """Check prerequisites.
3779

3780
    This checks that the instance is in the cluster.
3781

3782
    """
3783
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3784
    assert self.instance is not None, \
3785
      "Cannot retrieve locked instance %s" % self.op.instance_name
3786
    _CheckNodeOnline(self, self.instance.primary_node)
3787

    
3788
  def Exec(self, feedback_fn):
3789
    """Shutdown the instance.
3790

3791
    """
3792
    instance = self.instance
3793
    node_current = instance.primary_node
3794
    timeout = self.timeout
3795
    self.cfg.MarkInstanceDown(instance.name)
3796
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
3797
    msg = result.fail_msg
3798
    if msg:
3799
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
3800

    
3801
    _ShutdownInstanceDisks(self, instance)
3802

    
3803

    
3804
class LUReinstallInstance(LogicalUnit):
3805
  """Reinstall an instance.
3806

3807
  """
3808
  HPATH = "instance-reinstall"
3809
  HTYPE = constants.HTYPE_INSTANCE
3810
  _OP_REQP = ["instance_name"]
3811
  REQ_BGL = False
3812

    
3813
  def ExpandNames(self):
3814
    self._ExpandAndLockInstance()
3815

    
3816
  def BuildHooksEnv(self):
3817
    """Build hooks env.
3818

3819
    This runs on master, primary and secondary nodes of the instance.
3820

3821
    """
3822
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3823
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3824
    return env, nl, nl
3825

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

3829
    This checks that the instance is in the cluster and is not running.
3830

3831
    """
3832
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3833
    assert instance is not None, \
3834
      "Cannot retrieve locked instance %s" % self.op.instance_name
3835
    _CheckNodeOnline(self, instance.primary_node)
3836

    
3837
    if instance.disk_template == constants.DT_DISKLESS:
3838
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3839
                                 self.op.instance_name,
3840
                                 errors.ECODE_INVAL)
3841
    if instance.admin_up:
3842
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3843
                                 self.op.instance_name,
3844
                                 errors.ECODE_STATE)
3845
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3846
                                              instance.name,
3847
                                              instance.hypervisor)
3848
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3849
                      prereq=True)
3850
    if remote_info.payload:
3851
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3852
                                 (self.op.instance_name,
3853
                                  instance.primary_node),
3854
                                 errors.ECODE_STATE)
3855

    
3856
    self.op.os_type = getattr(self.op, "os_type", None)
3857
    self.op.force_variant = getattr(self.op, "force_variant", False)
3858
    if self.op.os_type is not None:
3859
      # OS verification
3860
      pnode = self.cfg.GetNodeInfo(
3861
        self.cfg.ExpandNodeName(instance.primary_node))
3862
      if pnode is None:
3863
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
3864
                                   self.op.pnode, errors.ECODE_NOENT)
3865
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
3866
      result.Raise("OS '%s' not in supported OS list for primary node %s" %
3867
                   (self.op.os_type, pnode.name), prereq=True)
3868
      if not self.op.force_variant:
3869
        _CheckOSVariant(result.payload, self.op.os_type)
3870

    
3871
    self.instance = instance
3872

    
3873
  def Exec(self, feedback_fn):
3874
    """Reinstall the instance.
3875

3876
    """
3877
    inst = self.instance
3878

    
3879
    if self.op.os_type is not None:
3880
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
3881
      inst.os = self.op.os_type
3882
      self.cfg.Update(inst, feedback_fn)
3883

    
3884
    _StartInstanceDisks(self, inst, None)
3885
    try:
3886
      feedback_fn("Running the instance OS create scripts...")
3887
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True)
3888
      result.Raise("Could not install OS for instance %s on node %s" %
3889
                   (inst.name, inst.primary_node))
3890
    finally:
3891
      _ShutdownInstanceDisks(self, inst)
3892

    
3893

    
3894
class LURecreateInstanceDisks(LogicalUnit):
3895
  """Recreate an instance's missing disks.
3896

3897
  """
3898
  HPATH = "instance-recreate-disks"
3899
  HTYPE = constants.HTYPE_INSTANCE
3900
  _OP_REQP = ["instance_name", "disks"]
3901
  REQ_BGL = False
3902

    
3903
  def CheckArguments(self):
3904
    """Check the arguments.
3905

3906
    """
3907
    if not isinstance(self.op.disks, list):
3908
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
3909
    for item in self.op.disks:
3910
      if (not isinstance(item, int) or
3911
          item < 0):
3912
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
3913
                                   str(item), errors.ECODE_INVAL)
3914

    
3915
  def ExpandNames(self):
3916
    self._ExpandAndLockInstance()
3917

    
3918
  def BuildHooksEnv(self):
3919
    """Build hooks env.
3920

3921
    This runs on master, primary and secondary nodes of the instance.
3922

3923
    """
3924
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3925
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3926
    return env, nl, nl
3927

    
3928
  def CheckPrereq(self):
3929
    """Check prerequisites.
3930

3931
    This checks that the instance is in the cluster and is not running.
3932

3933
    """
3934
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3935
    assert instance is not None, \
3936
      "Cannot retrieve locked instance %s" % self.op.instance_name
3937
    _CheckNodeOnline(self, instance.primary_node)
3938

    
3939
    if instance.disk_template == constants.DT_DISKLESS:
3940
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3941
                                 self.op.instance_name, errors.ECODE_INVAL)
3942
    if instance.admin_up:
3943
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3944
                                 self.op.instance_name, errors.ECODE_STATE)
3945
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3946
                                              instance.name,
3947
                                              instance.hypervisor)
3948
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3949
                      prereq=True)
3950
    if remote_info.payload:
3951
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3952
                                 (self.op.instance_name,
3953
                                  instance.primary_node), errors.ECODE_STATE)
3954

    
3955
    if not self.op.disks:
3956
      self.op.disks = range(len(instance.disks))
3957
    else:
3958
      for idx in self.op.disks:
3959
        if idx >= len(instance.disks):
3960
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
3961
                                     errors.ECODE_INVAL)
3962

    
3963
    self.instance = instance
3964

    
3965
  def Exec(self, feedback_fn):
3966
    """Recreate the disks.
3967

3968
    """
3969
    to_skip = []
3970
    for idx, disk in enumerate(self.instance.disks):
3971
      if idx not in self.op.disks: # disk idx has not been passed in
3972
        to_skip.append(idx)
3973
        continue
3974

    
3975
    _CreateDisks(self, self.instance, to_skip=to_skip)
3976

    
3977

    
3978
class LURenameInstance(LogicalUnit):
3979
  """Rename an instance.
3980

3981
  """
3982
  HPATH = "instance-rename"
3983
  HTYPE = constants.HTYPE_INSTANCE
3984
  _OP_REQP = ["instance_name", "new_name"]
3985

    
3986
  def BuildHooksEnv(self):
3987
    """Build hooks env.
3988

3989
    This runs on master, primary and secondary nodes of the instance.
3990

3991
    """
3992
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3993
    env["INSTANCE_NEW_NAME"] = self.op.new_name
3994
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3995
    return env, nl, nl
3996

    
3997
  def CheckPrereq(self):
3998
    """Check prerequisites.
3999

4000
    This checks that the instance is in the cluster and is not running.
4001

4002
    """