Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 104f4ca1

History | View | Annotate | Download (304.5 kB)

1
#
2
#
3

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

    
21

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

    
24
# pylint: disable-msg=W0613,W0201
25

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

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

    
44

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

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

57
  Note that all commands require root permissions.
58

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

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

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

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

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

    
96
    # Tasklets
97
    self.tasklets = None
98

    
99
    for attr_name in self._OP_REQP:
100
      attr_val = getattr(op, attr_name, None)
101
      if attr_val is None:
102
        raise errors.OpPrereqError("Required parameter '%s' missing" %
103
                                   attr_name, 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, ecode=errors.ECODE_ENVIRON)
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, ecode=errors.ECODE_ENVIRON)
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
    # check pv names
1131
    if vg_name is not None:
1132
      pvlist = node_result.get(constants.NV_PVLIST, None)
1133
      test = pvlist is None
1134
      _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1135
      if not test:
1136
        # check that ':' is not present in PV names, since it's a
1137
        # special character for lvcreate (denotes the range of PEs to
1138
        # use on the PV)
1139
        for size, pvname, owner_vg in pvlist:
1140
          test = ":" in pvname
1141
          _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1142
                   " '%s' of VG '%s'", pvname, owner_vg)
1143

    
1144
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
1145
                      node_instance, n_offline):
1146
    """Verify an instance.
1147

1148
    This function checks to see if the required block devices are
1149
    available on the instance's node.
1150

1151
    """
1152
    _ErrorIf = self._ErrorIf
1153
    node_current = instanceconfig.primary_node
1154

    
1155
    node_vol_should = {}
1156
    instanceconfig.MapLVsByNode(node_vol_should)
1157

    
1158
    for node in node_vol_should:
1159
      if node in n_offline:
1160
        # ignore missing volumes on offline nodes
1161
        continue
1162
      for volume in node_vol_should[node]:
1163
        test = node not in node_vol_is or volume not in node_vol_is[node]
1164
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1165
                 "volume %s missing on node %s", volume, node)
1166

    
1167
    if instanceconfig.admin_up:
1168
      test = ((node_current not in node_instance or
1169
               not instance in node_instance[node_current]) and
1170
              node_current not in n_offline)
1171
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1172
               "instance not running on its primary node %s",
1173
               node_current)
1174

    
1175
    for node in node_instance:
1176
      if (not node == node_current):
1177
        test = instance in node_instance[node]
1178
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1179
                 "instance should not run on node %s", node)
1180

    
1181
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is):
1182
    """Verify if there are any unknown volumes in the cluster.
1183

1184
    The .os, .swap and backup volumes are ignored. All other volumes are
1185
    reported as unknown.
1186

1187
    """
1188
    for node in node_vol_is:
1189
      for volume in node_vol_is[node]:
1190
        test = (node not in node_vol_should or
1191
                volume not in node_vol_should[node])
1192
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1193
                      "volume %s is unknown", volume)
1194

    
1195
  def _VerifyOrphanInstances(self, instancelist, node_instance):
1196
    """Verify the list of running instances.
1197

1198
    This checks what instances are running but unknown to the cluster.
1199

1200
    """
1201
    for node in node_instance:
1202
      for o_inst in node_instance[node]:
1203
        test = o_inst not in instancelist
1204
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1205
                      "instance %s on node %s should not exist", o_inst, node)
1206

    
1207
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg):
1208
    """Verify N+1 Memory Resilience.
1209

1210
    Check that if one single node dies we can still start all the instances it
1211
    was primary for.
1212

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

    
1234
  def CheckPrereq(self):
1235
    """Check prerequisites.
1236

1237
    Transform the list of checks we're going to skip into a set and check that
1238
    all its members are valid.
1239

1240
    """
1241
    self.skip_set = frozenset(self.op.skip_checks)
1242
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1243
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1244
                                 errors.ECODE_INVAL)
1245

    
1246
  def BuildHooksEnv(self):
1247
    """Build hooks env.
1248

1249
    Cluster-Verify hooks just ran in the post phase and their failure makes
1250
    the output be logged in the verify output and the verification to fail.
1251

1252
    """
1253
    all_nodes = self.cfg.GetNodeList()
1254
    env = {
1255
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1256
      }
1257
    for node in self.cfg.GetAllNodesInfo().values():
1258
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1259

    
1260
    return env, [], all_nodes
1261

    
1262
  def Exec(self, feedback_fn):
1263
    """Verify integrity of cluster, performing various test on nodes.
1264

1265
    """
1266
    self.bad = False
1267
    _ErrorIf = self._ErrorIf
1268
    verbose = self.op.verbose
1269
    self._feedback_fn = feedback_fn
1270
    feedback_fn("* Verifying global settings")
1271
    for msg in self.cfg.VerifyConfig():
1272
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1273

    
1274
    vg_name = self.cfg.GetVGName()
1275
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1276
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1277
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1278
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1279
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1280
                        for iname in instancelist)
1281
    i_non_redundant = [] # Non redundant instances
1282
    i_non_a_balanced = [] # Non auto-balanced instances
1283
    n_offline = [] # List of offline nodes
1284
    n_drained = [] # List of nodes being drained
1285
    node_volume = {}
1286
    node_instance = {}
1287
    node_info = {}
1288
    instance_cfg = {}
1289

    
1290
    # FIXME: verify OS list
1291
    # do local checksums
1292
    master_files = [constants.CLUSTER_CONF_FILE]
1293

    
1294
    file_names = ssconf.SimpleStore().GetFileList()
1295
    file_names.append(constants.SSL_CERT_FILE)
1296
    file_names.append(constants.RAPI_CERT_FILE)
1297
    file_names.extend(master_files)
1298

    
1299
    local_checksums = utils.FingerprintFiles(file_names)
1300

    
1301
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1302
    node_verify_param = {
1303
      constants.NV_FILELIST: file_names,
1304
      constants.NV_NODELIST: [node.name for node in nodeinfo
1305
                              if not node.offline],
1306
      constants.NV_HYPERVISOR: hypervisors,
1307
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1308
                                  node.secondary_ip) for node in nodeinfo
1309
                                 if not node.offline],
1310
      constants.NV_INSTANCELIST: hypervisors,
1311
      constants.NV_VERSION: None,
1312
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1313
      constants.NV_NODESETUP: None,
1314
      }
1315
    if vg_name is not None:
1316
      node_verify_param[constants.NV_VGLIST] = None
1317
      node_verify_param[constants.NV_LVLIST] = vg_name
1318
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1319
      node_verify_param[constants.NV_DRBDLIST] = None
1320
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1321
                                           self.cfg.GetClusterName())
1322

    
1323
    cluster = self.cfg.GetClusterInfo()
1324
    master_node = self.cfg.GetMasterNode()
1325
    all_drbd_map = self.cfg.ComputeDRBDMap()
1326

    
1327
    feedback_fn("* Verifying node status")
1328
    for node_i in nodeinfo:
1329
      node = node_i.name
1330

    
1331
      if node_i.offline:
1332
        if verbose:
1333
          feedback_fn("* Skipping offline node %s" % (node,))
1334
        n_offline.append(node)
1335
        continue
1336

    
1337
      if node == master_node:
1338
        ntype = "master"
1339
      elif node_i.master_candidate:
1340
        ntype = "master candidate"
1341
      elif node_i.drained:
1342
        ntype = "drained"
1343
        n_drained.append(node)
1344
      else:
1345
        ntype = "regular"
1346
      if verbose:
1347
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1348

    
1349
      msg = all_nvinfo[node].fail_msg
1350
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1351
      if msg:
1352
        continue
1353

    
1354
      nresult = all_nvinfo[node].payload
1355
      node_drbd = {}
1356
      for minor, instance in all_drbd_map[node].items():
1357
        test = instance not in instanceinfo
1358
        _ErrorIf(test, self.ECLUSTERCFG, None,
1359
                 "ghost instance '%s' in temporary DRBD map", instance)
1360
          # ghost instance should not be running, but otherwise we
1361
          # don't give double warnings (both ghost instance and
1362
          # unallocated minor in use)
1363
        if test:
1364
          node_drbd[minor] = (instance, False)
1365
        else:
1366
          instance = instanceinfo[instance]
1367
          node_drbd[minor] = (instance.name, instance.admin_up)
1368
      self._VerifyNode(node_i, file_names, local_checksums,
1369
                       nresult, master_files, node_drbd, vg_name)
1370

    
1371
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1372
      if vg_name is None:
1373
        node_volume[node] = {}
1374
      elif isinstance(lvdata, basestring):
1375
        _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1376
                 utils.SafeEncode(lvdata))
1377
        node_volume[node] = {}
1378
      elif not isinstance(lvdata, dict):
1379
        _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1380
        continue
1381
      else:
1382
        node_volume[node] = lvdata
1383

    
1384
      # node_instance
1385
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1386
      test = not isinstance(idata, list)
1387
      _ErrorIf(test, self.ENODEHV, node,
1388
               "rpc call to node failed (instancelist)")
1389
      if test:
1390
        continue
1391

    
1392
      node_instance[node] = idata
1393

    
1394
      # node_info
1395
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1396
      test = not isinstance(nodeinfo, dict)
1397
      _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1398
      if test:
1399
        continue
1400

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

    
1429
    node_vol_should = {}
1430

    
1431
    feedback_fn("* Verifying instance status")
1432
    for instance in instancelist:
1433
      if verbose:
1434
        feedback_fn("* Verifying instance %s" % instance)
1435
      inst_config = instanceinfo[instance]
1436
      self._VerifyInstance(instance, inst_config, node_volume,
1437
                           node_instance, n_offline)
1438
      inst_nodes_offline = []
1439

    
1440
      inst_config.MapLVsByNode(node_vol_should)
1441

    
1442
      instance_cfg[instance] = inst_config
1443

    
1444
      pnode = inst_config.primary_node
1445
      _ErrorIf(pnode not in node_info and pnode not in n_offline,
1446
               self.ENODERPC, pnode, "instance %s, connection to"
1447
               " primary node failed", instance)
1448
      if pnode in node_info:
1449
        node_info[pnode]['pinst'].append(instance)
1450

    
1451
      if pnode in n_offline:
1452
        inst_nodes_offline.append(pnode)
1453

    
1454
      # If the instance is non-redundant we cannot survive losing its primary
1455
      # node, so we are not N+1 compliant. On the other hand we have no disk
1456
      # templates with more than one secondary so that situation is not well
1457
      # supported either.
1458
      # FIXME: does not support file-backed instances
1459
      if len(inst_config.secondary_nodes) == 0:
1460
        i_non_redundant.append(instance)
1461
      _ErrorIf(len(inst_config.secondary_nodes) > 1,
1462
               self.EINSTANCELAYOUT, instance,
1463
               "instance has multiple secondary nodes", code="WARNING")
1464

    
1465
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1466
        i_non_a_balanced.append(instance)
1467

    
1468
      for snode in inst_config.secondary_nodes:
1469
        _ErrorIf(snode not in node_info and snode not in n_offline,
1470
                 self.ENODERPC, snode,
1471
                 "instance %s, connection to secondary node"
1472
                 "failed", instance)
1473

    
1474
        if snode in node_info:
1475
          node_info[snode]['sinst'].append(instance)
1476
          if pnode not in node_info[snode]['sinst-by-pnode']:
1477
            node_info[snode]['sinst-by-pnode'][pnode] = []
1478
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1479

    
1480
        if snode in n_offline:
1481
          inst_nodes_offline.append(snode)
1482

    
1483
      # warn that the instance lives on offline nodes
1484
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1485
               "instance lives on offline node(s) %s",
1486
               ", ".join(inst_nodes_offline))
1487

    
1488
    feedback_fn("* Verifying orphan volumes")
1489
    self._VerifyOrphanVolumes(node_vol_should, node_volume)
1490

    
1491
    feedback_fn("* Verifying remaining instances")
1492
    self._VerifyOrphanInstances(instancelist, node_instance)
1493

    
1494
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1495
      feedback_fn("* Verifying N+1 Memory redundancy")
1496
      self._VerifyNPlusOneMemory(node_info, instance_cfg)
1497

    
1498
    feedback_fn("* Other Notes")
1499
    if i_non_redundant:
1500
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1501
                  % len(i_non_redundant))
1502

    
1503
    if i_non_a_balanced:
1504
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1505
                  % len(i_non_a_balanced))
1506

    
1507
    if n_offline:
1508
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1509

    
1510
    if n_drained:
1511
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1512

    
1513
    return not self.bad
1514

    
1515
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1516
    """Analyze the post-hooks' result
1517

1518
    This method analyses the hook result, handles it, and sends some
1519
    nicely-formatted feedback back to the user.
1520

1521
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1522
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1523
    @param hooks_results: the results of the multi-node hooks rpc call
1524
    @param feedback_fn: function used send feedback back to the caller
1525
    @param lu_result: previous Exec result
1526
    @return: the new Exec result, based on the previous result
1527
        and hook results
1528

1529
    """
1530
    # We only really run POST phase hooks, and are only interested in
1531
    # their results
1532
    if phase == constants.HOOKS_PHASE_POST:
1533
      # Used to change hooks' output to proper indentation
1534
      indent_re = re.compile('^', re.M)
1535
      feedback_fn("* Hooks Results")
1536
      assert hooks_results, "invalid result from hooks"
1537

    
1538
      for node_name in hooks_results:
1539
        show_node_header = True
1540
        res = hooks_results[node_name]
1541
        msg = res.fail_msg
1542
        test = msg and not res.offline
1543
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1544
                      "Communication failure in hooks execution: %s", msg)
1545
        if test:
1546
          # override manually lu_result here as _ErrorIf only
1547
          # overrides self.bad
1548
          lu_result = 1
1549
          continue
1550
        for script, hkr, output in res.payload:
1551
          test = hkr == constants.HKR_FAIL
1552
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1553
                        "Script %s failed, output:", script)
1554
          if test:
1555
            output = indent_re.sub('      ', output)
1556
            feedback_fn("%s" % output)
1557
            lu_result = 1
1558

    
1559
      return lu_result
1560

    
1561

    
1562
class LUVerifyDisks(NoHooksLU):
1563
  """Verifies the cluster disks status.
1564

1565
  """
1566
  _OP_REQP = []
1567
  REQ_BGL = False
1568

    
1569
  def ExpandNames(self):
1570
    self.needed_locks = {
1571
      locking.LEVEL_NODE: locking.ALL_SET,
1572
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1573
    }
1574
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1575

    
1576
  def CheckPrereq(self):
1577
    """Check prerequisites.
1578

1579
    This has no prerequisites.
1580

1581
    """
1582
    pass
1583

    
1584
  def Exec(self, feedback_fn):
1585
    """Verify integrity of cluster disks.
1586

1587
    @rtype: tuple of three items
1588
    @return: a tuple of (dict of node-to-node_error, list of instances
1589
        which need activate-disks, dict of instance: (node, volume) for
1590
        missing volumes
1591

1592
    """
1593
    result = res_nodes, res_instances, res_missing = {}, [], {}
1594

    
1595
    vg_name = self.cfg.GetVGName()
1596
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1597
    instances = [self.cfg.GetInstanceInfo(name)
1598
                 for name in self.cfg.GetInstanceList()]
1599

    
1600
    nv_dict = {}
1601
    for inst in instances:
1602
      inst_lvs = {}
1603
      if (not inst.admin_up or
1604
          inst.disk_template not in constants.DTS_NET_MIRROR):
1605
        continue
1606
      inst.MapLVsByNode(inst_lvs)
1607
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1608
      for node, vol_list in inst_lvs.iteritems():
1609
        for vol in vol_list:
1610
          nv_dict[(node, vol)] = inst
1611

    
1612
    if not nv_dict:
1613
      return result
1614

    
1615
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1616

    
1617
    for node in nodes:
1618
      # node_volume
1619
      node_res = node_lvs[node]
1620
      if node_res.offline:
1621
        continue
1622
      msg = node_res.fail_msg
1623
      if msg:
1624
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1625
        res_nodes[node] = msg
1626
        continue
1627

    
1628
      lvs = node_res.payload
1629
      for lv_name, (_, lv_inactive, lv_online) in lvs.items():
1630
        inst = nv_dict.pop((node, lv_name), None)
1631
        if (not lv_online and inst is not None
1632
            and inst.name not in res_instances):
1633
          res_instances.append(inst.name)
1634

    
1635
    # any leftover items in nv_dict are missing LVs, let's arrange the
1636
    # data better
1637
    for key, inst in nv_dict.iteritems():
1638
      if inst.name not in res_missing:
1639
        res_missing[inst.name] = []
1640
      res_missing[inst.name].append(key)
1641

    
1642
    return result
1643

    
1644

    
1645
class LURepairDiskSizes(NoHooksLU):
1646
  """Verifies the cluster disks sizes.
1647

1648
  """
1649
  _OP_REQP = ["instances"]
1650
  REQ_BGL = False
1651

    
1652
  def ExpandNames(self):
1653
    if not isinstance(self.op.instances, list):
1654
      raise errors.OpPrereqError("Invalid argument type 'instances'",
1655
                                 errors.ECODE_INVAL)
1656

    
1657
    if self.op.instances:
1658
      self.wanted_names = []
1659
      for name in self.op.instances:
1660
        full_name = self.cfg.ExpandInstanceName(name)
1661
        if full_name is None:
1662
          raise errors.OpPrereqError("Instance '%s' not known" % name,
1663
                                     errors.ECODE_NOENT)
1664
        self.wanted_names.append(full_name)
1665
      self.needed_locks = {
1666
        locking.LEVEL_NODE: [],
1667
        locking.LEVEL_INSTANCE: self.wanted_names,
1668
        }
1669
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1670
    else:
1671
      self.wanted_names = None
1672
      self.needed_locks = {
1673
        locking.LEVEL_NODE: locking.ALL_SET,
1674
        locking.LEVEL_INSTANCE: locking.ALL_SET,
1675
        }
1676
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1677

    
1678
  def DeclareLocks(self, level):
1679
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
1680
      self._LockInstancesNodes(primary_only=True)
1681

    
1682
  def CheckPrereq(self):
1683
    """Check prerequisites.
1684

1685
    This only checks the optional instance list against the existing names.
1686

1687
    """
1688
    if self.wanted_names is None:
1689
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
1690

    
1691
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
1692
                             in self.wanted_names]
1693

    
1694
  def _EnsureChildSizes(self, disk):
1695
    """Ensure children of the disk have the needed disk size.
1696

1697
    This is valid mainly for DRBD8 and fixes an issue where the
1698
    children have smaller disk size.
1699

1700
    @param disk: an L{ganeti.objects.Disk} object
1701

1702
    """
1703
    if disk.dev_type == constants.LD_DRBD8:
1704
      assert disk.children, "Empty children for DRBD8?"
1705
      fchild = disk.children[0]
1706
      mismatch = fchild.size < disk.size
1707
      if mismatch:
1708
        self.LogInfo("Child disk has size %d, parent %d, fixing",
1709
                     fchild.size, disk.size)
1710
        fchild.size = disk.size
1711

    
1712
      # and we recurse on this child only, not on the metadev
1713
      return self._EnsureChildSizes(fchild) or mismatch
1714
    else:
1715
      return False
1716

    
1717
  def Exec(self, feedback_fn):
1718
    """Verify the size of cluster disks.
1719

1720
    """
1721
    # TODO: check child disks too
1722
    # TODO: check differences in size between primary/secondary nodes
1723
    per_node_disks = {}
1724
    for instance in self.wanted_instances:
1725
      pnode = instance.primary_node
1726
      if pnode not in per_node_disks:
1727
        per_node_disks[pnode] = []
1728
      for idx, disk in enumerate(instance.disks):
1729
        per_node_disks[pnode].append((instance, idx, disk))
1730

    
1731
    changed = []
1732
    for node, dskl in per_node_disks.items():
1733
      newl = [v[2].Copy() for v in dskl]
1734
      for dsk in newl:
1735
        self.cfg.SetDiskID(dsk, node)
1736
      result = self.rpc.call_blockdev_getsizes(node, newl)
1737
      if result.fail_msg:
1738
        self.LogWarning("Failure in blockdev_getsizes call to node"
1739
                        " %s, ignoring", node)
1740
        continue
1741
      if len(result.data) != len(dskl):
1742
        self.LogWarning("Invalid result from node %s, ignoring node results",
1743
                        node)
1744
        continue
1745
      for ((instance, idx, disk), size) in zip(dskl, result.data):
1746
        if size is None:
1747
          self.LogWarning("Disk %d of instance %s did not return size"
1748
                          " information, ignoring", idx, instance.name)
1749
          continue
1750
        if not isinstance(size, (int, long)):
1751
          self.LogWarning("Disk %d of instance %s did not return valid"
1752
                          " size information, ignoring", idx, instance.name)
1753
          continue
1754
        size = size >> 20
1755
        if size != disk.size:
1756
          self.LogInfo("Disk %d of instance %s has mismatched size,"
1757
                       " correcting: recorded %d, actual %d", idx,
1758
                       instance.name, disk.size, size)
1759
          disk.size = size
1760
          self.cfg.Update(instance, feedback_fn)
1761
          changed.append((instance.name, idx, size))
1762
        if self._EnsureChildSizes(disk):
1763
          self.cfg.Update(instance, feedback_fn)
1764
          changed.append((instance.name, idx, disk.size))
1765
    return changed
1766

    
1767

    
1768
class LURenameCluster(LogicalUnit):
1769
  """Rename the cluster.
1770

1771
  """
1772
  HPATH = "cluster-rename"
1773
  HTYPE = constants.HTYPE_CLUSTER
1774
  _OP_REQP = ["name"]
1775

    
1776
  def BuildHooksEnv(self):
1777
    """Build hooks env.
1778

1779
    """
1780
    env = {
1781
      "OP_TARGET": self.cfg.GetClusterName(),
1782
      "NEW_NAME": self.op.name,
1783
      }
1784
    mn = self.cfg.GetMasterNode()
1785
    return env, [mn], [mn]
1786

    
1787
  def CheckPrereq(self):
1788
    """Verify that the passed name is a valid one.
1789

1790
    """
1791
    hostname = utils.GetHostInfo(self.op.name)
1792

    
1793
    new_name = hostname.name
1794
    self.ip = new_ip = hostname.ip
1795
    old_name = self.cfg.GetClusterName()
1796
    old_ip = self.cfg.GetMasterIP()
1797
    if new_name == old_name and new_ip == old_ip:
1798
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1799
                                 " cluster has changed",
1800
                                 errors.ECODE_INVAL)
1801
    if new_ip != old_ip:
1802
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1803
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1804
                                   " reachable on the network. Aborting." %
1805
                                   new_ip, errors.ECODE_NOTUNIQUE)
1806

    
1807
    self.op.name = new_name
1808

    
1809
  def Exec(self, feedback_fn):
1810
    """Rename the cluster.
1811

1812
    """
1813
    clustername = self.op.name
1814
    ip = self.ip
1815

    
1816
    # shutdown the master IP
1817
    master = self.cfg.GetMasterNode()
1818
    result = self.rpc.call_node_stop_master(master, False)
1819
    result.Raise("Could not disable the master role")
1820

    
1821
    try:
1822
      cluster = self.cfg.GetClusterInfo()
1823
      cluster.cluster_name = clustername
1824
      cluster.master_ip = ip
1825
      self.cfg.Update(cluster, feedback_fn)
1826

    
1827
      # update the known hosts file
1828
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1829
      node_list = self.cfg.GetNodeList()
1830
      try:
1831
        node_list.remove(master)
1832
      except ValueError:
1833
        pass
1834
      result = self.rpc.call_upload_file(node_list,
1835
                                         constants.SSH_KNOWN_HOSTS_FILE)
1836
      for to_node, to_result in result.iteritems():
1837
        msg = to_result.fail_msg
1838
        if msg:
1839
          msg = ("Copy of file %s to node %s failed: %s" %
1840
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
1841
          self.proc.LogWarning(msg)
1842

    
1843
    finally:
1844
      result = self.rpc.call_node_start_master(master, False, False)
1845
      msg = result.fail_msg
1846
      if msg:
1847
        self.LogWarning("Could not re-enable the master role on"
1848
                        " the master, please restart manually: %s", msg)
1849

    
1850

    
1851
def _RecursiveCheckIfLVMBased(disk):
1852
  """Check if the given disk or its children are lvm-based.
1853

1854
  @type disk: L{objects.Disk}
1855
  @param disk: the disk to check
1856
  @rtype: boolean
1857
  @return: boolean indicating whether a LD_LV dev_type was found or not
1858

1859
  """
1860
  if disk.children:
1861
    for chdisk in disk.children:
1862
      if _RecursiveCheckIfLVMBased(chdisk):
1863
        return True
1864
  return disk.dev_type == constants.LD_LV
1865

    
1866

    
1867
class LUSetClusterParams(LogicalUnit):
1868
  """Change the parameters of the cluster.
1869

1870
  """
1871
  HPATH = "cluster-modify"
1872
  HTYPE = constants.HTYPE_CLUSTER
1873
  _OP_REQP = []
1874
  REQ_BGL = False
1875

    
1876
  def CheckArguments(self):
1877
    """Check parameters
1878

1879
    """
1880
    if not hasattr(self.op, "candidate_pool_size"):
1881
      self.op.candidate_pool_size = None
1882
    if self.op.candidate_pool_size is not None:
1883
      try:
1884
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1885
      except (ValueError, TypeError), err:
1886
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1887
                                   str(err), errors.ECODE_INVAL)
1888
      if self.op.candidate_pool_size < 1:
1889
        raise errors.OpPrereqError("At least one master candidate needed",
1890
                                   errors.ECODE_INVAL)
1891

    
1892
  def ExpandNames(self):
1893
    # FIXME: in the future maybe other cluster params won't require checking on
1894
    # all nodes to be modified.
1895
    self.needed_locks = {
1896
      locking.LEVEL_NODE: locking.ALL_SET,
1897
    }
1898
    self.share_locks[locking.LEVEL_NODE] = 1
1899

    
1900
  def BuildHooksEnv(self):
1901
    """Build hooks env.
1902

1903
    """
1904
    env = {
1905
      "OP_TARGET": self.cfg.GetClusterName(),
1906
      "NEW_VG_NAME": self.op.vg_name,
1907
      }
1908
    mn = self.cfg.GetMasterNode()
1909
    return env, [mn], [mn]
1910

    
1911
  def CheckPrereq(self):
1912
    """Check prerequisites.
1913

1914
    This checks whether the given params don't conflict and
1915
    if the given volume group is valid.
1916

1917
    """
1918
    if self.op.vg_name is not None and not self.op.vg_name:
1919
      instances = self.cfg.GetAllInstancesInfo().values()
1920
      for inst in instances:
1921
        for disk in inst.disks:
1922
          if _RecursiveCheckIfLVMBased(disk):
1923
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1924
                                       " lvm-based instances exist",
1925
                                       errors.ECODE_INVAL)
1926

    
1927
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1928

    
1929
    # if vg_name not None, checks given volume group on all nodes
1930
    if self.op.vg_name:
1931
      vglist = self.rpc.call_vg_list(node_list)
1932
      for node in node_list:
1933
        msg = vglist[node].fail_msg
1934
        if msg:
1935
          # ignoring down node
1936
          self.LogWarning("Error while gathering data on node %s"
1937
                          " (ignoring node): %s", node, msg)
1938
          continue
1939
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
1940
                                              self.op.vg_name,
1941
                                              constants.MIN_VG_SIZE)
1942
        if vgstatus:
1943
          raise errors.OpPrereqError("Error on node '%s': %s" %
1944
                                     (node, vgstatus), errors.ECODE_ENVIRON)
1945

    
1946
    self.cluster = cluster = self.cfg.GetClusterInfo()
1947
    # validate params changes
1948
    if self.op.beparams:
1949
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
1950
      self.new_beparams = objects.FillDict(
1951
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
1952

    
1953
    if self.op.nicparams:
1954
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
1955
      self.new_nicparams = objects.FillDict(
1956
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
1957
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
1958

    
1959
    # hypervisor list/parameters
1960
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
1961
    if self.op.hvparams:
1962
      if not isinstance(self.op.hvparams, dict):
1963
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
1964
                                   errors.ECODE_INVAL)
1965
      for hv_name, hv_dict in self.op.hvparams.items():
1966
        if hv_name not in self.new_hvparams:
1967
          self.new_hvparams[hv_name] = hv_dict
1968
        else:
1969
          self.new_hvparams[hv_name].update(hv_dict)
1970

    
1971
    if self.op.enabled_hypervisors is not None:
1972
      self.hv_list = self.op.enabled_hypervisors
1973
      if not self.hv_list:
1974
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
1975
                                   " least one member",
1976
                                   errors.ECODE_INVAL)
1977
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
1978
      if invalid_hvs:
1979
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
1980
                                   " entries: %s" % " ,".join(invalid_hvs),
1981
                                   errors.ECODE_INVAL)
1982
    else:
1983
      self.hv_list = cluster.enabled_hypervisors
1984

    
1985
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1986
      # either the enabled list has changed, or the parameters have, validate
1987
      for hv_name, hv_params in self.new_hvparams.items():
1988
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1989
            (self.op.enabled_hypervisors and
1990
             hv_name in self.op.enabled_hypervisors)):
1991
          # either this is a new hypervisor, or its parameters have changed
1992
          hv_class = hypervisor.GetHypervisor(hv_name)
1993
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1994
          hv_class.CheckParameterSyntax(hv_params)
1995
          _CheckHVParams(self, node_list, hv_name, hv_params)
1996

    
1997
  def Exec(self, feedback_fn):
1998
    """Change the parameters of the cluster.
1999

2000
    """
2001
    if self.op.vg_name is not None:
2002
      new_volume = self.op.vg_name
2003
      if not new_volume:
2004
        new_volume = None
2005
      if new_volume != self.cfg.GetVGName():
2006
        self.cfg.SetVGName(new_volume)
2007
      else:
2008
        feedback_fn("Cluster LVM configuration already in desired"
2009
                    " state, not changing")
2010
    if self.op.hvparams:
2011
      self.cluster.hvparams = self.new_hvparams
2012
    if self.op.enabled_hypervisors is not None:
2013
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2014
    if self.op.beparams:
2015
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2016
    if self.op.nicparams:
2017
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2018

    
2019
    if self.op.candidate_pool_size is not None:
2020
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2021
      # we need to update the pool size here, otherwise the save will fail
2022
      _AdjustCandidatePool(self, [])
2023

    
2024
    self.cfg.Update(self.cluster, feedback_fn)
2025

    
2026

    
2027
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2028
  """Distribute additional files which are part of the cluster configuration.
2029

2030
  ConfigWriter takes care of distributing the config and ssconf files, but
2031
  there are more files which should be distributed to all nodes. This function
2032
  makes sure those are copied.
2033

2034
  @param lu: calling logical unit
2035
  @param additional_nodes: list of nodes not in the config to distribute to
2036

2037
  """
2038
  # 1. Gather target nodes
2039
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2040
  dist_nodes = lu.cfg.GetNodeList()
2041
  if additional_nodes is not None:
2042
    dist_nodes.extend(additional_nodes)
2043
  if myself.name in dist_nodes:
2044
    dist_nodes.remove(myself.name)
2045

    
2046
  # 2. Gather files to distribute
2047
  dist_files = set([constants.ETC_HOSTS,
2048
                    constants.SSH_KNOWN_HOSTS_FILE,
2049
                    constants.RAPI_CERT_FILE,
2050
                    constants.RAPI_USERS_FILE,
2051
                    constants.HMAC_CLUSTER_KEY,
2052
                   ])
2053

    
2054
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2055
  for hv_name in enabled_hypervisors:
2056
    hv_class = hypervisor.GetHypervisor(hv_name)
2057
    dist_files.update(hv_class.GetAncillaryFiles())
2058

    
2059
  # 3. Perform the files upload
2060
  for fname in dist_files:
2061
    if os.path.exists(fname):
2062
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2063
      for to_node, to_result in result.items():
2064
        msg = to_result.fail_msg
2065
        if msg:
2066
          msg = ("Copy of file %s to node %s failed: %s" %
2067
                 (fname, to_node, msg))
2068
          lu.proc.LogWarning(msg)
2069

    
2070

    
2071
class LURedistributeConfig(NoHooksLU):
2072
  """Force the redistribution of cluster configuration.
2073

2074
  This is a very simple LU.
2075

2076
  """
2077
  _OP_REQP = []
2078
  REQ_BGL = False
2079

    
2080
  def ExpandNames(self):
2081
    self.needed_locks = {
2082
      locking.LEVEL_NODE: locking.ALL_SET,
2083
    }
2084
    self.share_locks[locking.LEVEL_NODE] = 1
2085

    
2086
  def CheckPrereq(self):
2087
    """Check prerequisites.
2088

2089
    """
2090

    
2091
  def Exec(self, feedback_fn):
2092
    """Redistribute the configuration.
2093

2094
    """
2095
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2096
    _RedistributeAncillaryFiles(self)
2097

    
2098

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

2102
  """
2103
  if not instance.disks:
2104
    return True
2105

    
2106
  if not oneshot:
2107
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2108

    
2109
  node = instance.primary_node
2110

    
2111
  for dev in instance.disks:
2112
    lu.cfg.SetDiskID(dev, node)
2113

    
2114
  # TODO: Convert to utils.Retry
2115

    
2116
  retries = 0
2117
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2118
  while True:
2119
    max_time = 0
2120
    done = True
2121
    cumul_degraded = False
2122
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2123
    msg = rstats.fail_msg
2124
    if msg:
2125
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2126
      retries += 1
2127
      if retries >= 10:
2128
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2129
                                 " aborting." % node)
2130
      time.sleep(6)
2131
      continue
2132
    rstats = rstats.payload
2133
    retries = 0
2134
    for i, mstat in enumerate(rstats):
2135
      if mstat is None:
2136
        lu.LogWarning("Can't compute data for node %s/%s",
2137
                           node, instance.disks[i].iv_name)
2138
        continue
2139

    
2140
      cumul_degraded = (cumul_degraded or
2141
                        (mstat.is_degraded and mstat.sync_percent is None))
2142
      if mstat.sync_percent is not None:
2143
        done = False
2144
        if mstat.estimated_time is not None:
2145
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2146
          max_time = mstat.estimated_time
2147
        else:
2148
          rem_time = "no time estimate"
2149
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2150
                        (instance.disks[i].iv_name, mstat.sync_percent,
2151
                         rem_time))
2152

    
2153
    # if we're done but degraded, let's do a few small retries, to
2154
    # make sure we see a stable and not transient situation; therefore
2155
    # we force restart of the loop
2156
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2157
      logging.info("Degraded disks found, %d retries left", degr_retries)
2158
      degr_retries -= 1
2159
      time.sleep(1)
2160
      continue
2161

    
2162
    if done or oneshot:
2163
      break
2164

    
2165
    time.sleep(min(60, max_time))
2166

    
2167
  if done:
2168
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2169
  return not cumul_degraded
2170

    
2171

    
2172
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2173
  """Check that mirrors are not degraded.
2174

2175
  The ldisk parameter, if True, will change the test from the
2176
  is_degraded attribute (which represents overall non-ok status for
2177
  the device(s)) to the ldisk (representing the local storage status).
2178

2179
  """
2180
  lu.cfg.SetDiskID(dev, node)
2181

    
2182
  result = True
2183

    
2184
  if on_primary or dev.AssembleOnSecondary():
2185
    rstats = lu.rpc.call_blockdev_find(node, dev)
2186
    msg = rstats.fail_msg
2187
    if msg:
2188
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2189
      result = False
2190
    elif not rstats.payload:
2191
      lu.LogWarning("Can't find disk on node %s", node)
2192
      result = False
2193
    else:
2194
      if ldisk:
2195
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2196
      else:
2197
        result = result and not rstats.payload.is_degraded
2198

    
2199
  if dev.children:
2200
    for child in dev.children:
2201
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2202

    
2203
  return result
2204

    
2205

    
2206
class LUDiagnoseOS(NoHooksLU):
2207
  """Logical unit for OS diagnose/query.
2208

2209
  """
2210
  _OP_REQP = ["output_fields", "names"]
2211
  REQ_BGL = False
2212
  _FIELDS_STATIC = utils.FieldSet()
2213
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2214
  # Fields that need calculation of global os validity
2215
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2216

    
2217
  def ExpandNames(self):
2218
    if self.op.names:
2219
      raise errors.OpPrereqError("Selective OS query not supported",
2220
                                 errors.ECODE_INVAL)
2221

    
2222
    _CheckOutputFields(static=self._FIELDS_STATIC,
2223
                       dynamic=self._FIELDS_DYNAMIC,
2224
                       selected=self.op.output_fields)
2225

    
2226
    # Lock all nodes, in shared mode
2227
    # Temporary removal of locks, should be reverted later
2228
    # TODO: reintroduce locks when they are lighter-weight
2229
    self.needed_locks = {}
2230
    #self.share_locks[locking.LEVEL_NODE] = 1
2231
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2232

    
2233
  def CheckPrereq(self):
2234
    """Check prerequisites.
2235

2236
    """
2237

    
2238
  @staticmethod
2239
  def _DiagnoseByOS(node_list, rlist):
2240
    """Remaps a per-node return list into an a per-os per-node dictionary
2241

2242
    @param node_list: a list with the names of all nodes
2243
    @param rlist: a map with node names as keys and OS objects as values
2244

2245
    @rtype: dict
2246
    @return: a dictionary with osnames as keys and as value another map, with
2247
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2248

2249
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2250
                                     (/srv/..., False, "invalid api")],
2251
                           "node2": [(/srv/..., True, "")]}
2252
          }
2253

2254
    """
2255
    all_os = {}
2256
    # we build here the list of nodes that didn't fail the RPC (at RPC
2257
    # level), so that nodes with a non-responding node daemon don't
2258
    # make all OSes invalid
2259
    good_nodes = [node_name for node_name in rlist
2260
                  if not rlist[node_name].fail_msg]
2261
    for node_name, nr in rlist.items():
2262
      if nr.fail_msg or not nr.payload:
2263
        continue
2264
      for name, path, status, diagnose, variants in nr.payload:
2265
        if name not in all_os:
2266
          # build a list of nodes for this os containing empty lists
2267
          # for each node in node_list
2268
          all_os[name] = {}
2269
          for nname in good_nodes:
2270
            all_os[name][nname] = []
2271
        all_os[name][node_name].append((path, status, diagnose, variants))
2272
    return all_os
2273

    
2274
  def Exec(self, feedback_fn):
2275
    """Compute the list of OSes.
2276

2277
    """
2278
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2279
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2280
    pol = self._DiagnoseByOS(valid_nodes, node_data)
2281
    output = []
2282
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2283
    calc_variants = "variants" in self.op.output_fields
2284

    
2285
    for os_name, os_data in pol.items():
2286
      row = []
2287
      if calc_valid:
2288
        valid = True
2289
        variants = None
2290
        for osl in os_data.values():
2291
          valid = valid and osl and osl[0][1]
2292
          if not valid:
2293
            variants = None
2294
            break
2295
          if calc_variants:
2296
            node_variants = osl[0][3]
2297
            if variants is None:
2298
              variants = node_variants
2299
            else:
2300
              variants = [v for v in variants if v in node_variants]
2301

    
2302
      for field in self.op.output_fields:
2303
        if field == "name":
2304
          val = os_name
2305
        elif field == "valid":
2306
          val = valid
2307
        elif field == "node_status":
2308
          # this is just a copy of the dict
2309
          val = {}
2310
          for node_name, nos_list in os_data.items():
2311
            val[node_name] = nos_list
2312
        elif field == "variants":
2313
          val =  variants
2314
        else:
2315
          raise errors.ParameterError(field)
2316
        row.append(val)
2317
      output.append(row)
2318

    
2319
    return output
2320

    
2321

    
2322
class LURemoveNode(LogicalUnit):
2323
  """Logical unit for removing a node.
2324

2325
  """
2326
  HPATH = "node-remove"
2327
  HTYPE = constants.HTYPE_NODE
2328
  _OP_REQP = ["node_name"]
2329

    
2330
  def BuildHooksEnv(self):
2331
    """Build hooks env.
2332

2333
    This doesn't run on the target node in the pre phase as a failed
2334
    node would then be impossible to remove.
2335

2336
    """
2337
    env = {
2338
      "OP_TARGET": self.op.node_name,
2339
      "NODE_NAME": self.op.node_name,
2340
      }
2341
    all_nodes = self.cfg.GetNodeList()
2342
    if self.op.node_name in all_nodes:
2343
      all_nodes.remove(self.op.node_name)
2344
    return env, all_nodes, all_nodes
2345

    
2346
  def CheckPrereq(self):
2347
    """Check prerequisites.
2348

2349
    This checks:
2350
     - the node exists in the configuration
2351
     - it does not have primary or secondary instances
2352
     - it's not the master
2353

2354
    Any errors are signaled by raising errors.OpPrereqError.
2355

2356
    """
2357
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
2358
    if node is None:
2359
      raise errors.OpPrereqError("Node '%s' is unknown." % self.op.node_name,
2360
                                 errors.ECODE_NOENT)
2361

    
2362
    instance_list = self.cfg.GetInstanceList()
2363

    
2364
    masternode = self.cfg.GetMasterNode()
2365
    if node.name == masternode:
2366
      raise errors.OpPrereqError("Node is the master node,"
2367
                                 " you need to failover first.",
2368
                                 errors.ECODE_INVAL)
2369

    
2370
    for instance_name in instance_list:
2371
      instance = self.cfg.GetInstanceInfo(instance_name)
2372
      if node.name in instance.all_nodes:
2373
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2374
                                   " please remove first." % instance_name,
2375
                                   errors.ECODE_INVAL)
2376
    self.op.node_name = node.name
2377
    self.node = node
2378

    
2379
  def Exec(self, feedback_fn):
2380
    """Removes the node from the cluster.
2381

2382
    """
2383
    node = self.node
2384
    logging.info("Stopping the node daemon and removing configs from node %s",
2385
                 node.name)
2386

    
2387
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2388

    
2389
    # Promote nodes to master candidate as needed
2390
    _AdjustCandidatePool(self, exceptions=[node.name])
2391
    self.context.RemoveNode(node.name)
2392

    
2393
    # Run post hooks on the node before it's removed
2394
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2395
    try:
2396
      h_results = hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2397
    except:
2398
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2399

    
2400
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2401
    msg = result.fail_msg
2402
    if msg:
2403
      self.LogWarning("Errors encountered on the remote node while leaving"
2404
                      " the cluster: %s", msg)
2405

    
2406

    
2407
class LUQueryNodes(NoHooksLU):
2408
  """Logical unit for querying nodes.
2409

2410
  """
2411
  _OP_REQP = ["output_fields", "names", "use_locking"]
2412
  REQ_BGL = False
2413

    
2414
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2415
                    "master_candidate", "offline", "drained"]
2416

    
2417
  _FIELDS_DYNAMIC = utils.FieldSet(
2418
    "dtotal", "dfree",
2419
    "mtotal", "mnode", "mfree",
2420
    "bootid",
2421
    "ctotal", "cnodes", "csockets",
2422
    )
2423

    
2424
  _FIELDS_STATIC = utils.FieldSet(*[
2425
    "pinst_cnt", "sinst_cnt",
2426
    "pinst_list", "sinst_list",
2427
    "pip", "sip", "tags",
2428
    "master",
2429
    "role"] + _SIMPLE_FIELDS
2430
    )
2431

    
2432
  def ExpandNames(self):
2433
    _CheckOutputFields(static=self._FIELDS_STATIC,
2434
                       dynamic=self._FIELDS_DYNAMIC,
2435
                       selected=self.op.output_fields)
2436

    
2437
    self.needed_locks = {}
2438
    self.share_locks[locking.LEVEL_NODE] = 1
2439

    
2440
    if self.op.names:
2441
      self.wanted = _GetWantedNodes(self, self.op.names)
2442
    else:
2443
      self.wanted = locking.ALL_SET
2444

    
2445
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2446
    self.do_locking = self.do_node_query and self.op.use_locking
2447
    if self.do_locking:
2448
      # if we don't request only static fields, we need to lock the nodes
2449
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2450

    
2451
  def CheckPrereq(self):
2452
    """Check prerequisites.
2453

2454
    """
2455
    # The validation of the node list is done in the _GetWantedNodes,
2456
    # if non empty, and if empty, there's no validation to do
2457
    pass
2458

    
2459
  def Exec(self, feedback_fn):
2460
    """Computes the list of nodes and their attributes.
2461

2462
    """
2463
    all_info = self.cfg.GetAllNodesInfo()
2464
    if self.do_locking:
2465
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2466
    elif self.wanted != locking.ALL_SET:
2467
      nodenames = self.wanted
2468
      missing = set(nodenames).difference(all_info.keys())
2469
      if missing:
2470
        raise errors.OpExecError(
2471
          "Some nodes were removed before retrieving their data: %s" % missing)
2472
    else:
2473
      nodenames = all_info.keys()
2474

    
2475
    nodenames = utils.NiceSort(nodenames)
2476
    nodelist = [all_info[name] for name in nodenames]
2477

    
2478
    # begin data gathering
2479

    
2480
    if self.do_node_query:
2481
      live_data = {}
2482
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2483
                                          self.cfg.GetHypervisorType())
2484
      for name in nodenames:
2485
        nodeinfo = node_data[name]
2486
        if not nodeinfo.fail_msg and nodeinfo.payload:
2487
          nodeinfo = nodeinfo.payload
2488
          fn = utils.TryConvert
2489
          live_data[name] = {
2490
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2491
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2492
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2493
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2494
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2495
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2496
            "bootid": nodeinfo.get('bootid', None),
2497
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2498
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2499
            }
2500
        else:
2501
          live_data[name] = {}
2502
    else:
2503
      live_data = dict.fromkeys(nodenames, {})
2504

    
2505
    node_to_primary = dict([(name, set()) for name in nodenames])
2506
    node_to_secondary = dict([(name, set()) for name in nodenames])
2507

    
2508
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2509
                             "sinst_cnt", "sinst_list"))
2510
    if inst_fields & frozenset(self.op.output_fields):
2511
      instancelist = self.cfg.GetInstanceList()
2512

    
2513
      for instance_name in instancelist:
2514
        inst = self.cfg.GetInstanceInfo(instance_name)
2515
        if inst.primary_node in node_to_primary:
2516
          node_to_primary[inst.primary_node].add(inst.name)
2517
        for secnode in inst.secondary_nodes:
2518
          if secnode in node_to_secondary:
2519
            node_to_secondary[secnode].add(inst.name)
2520

    
2521
    master_node = self.cfg.GetMasterNode()
2522

    
2523
    # end data gathering
2524

    
2525
    output = []
2526
    for node in nodelist:
2527
      node_output = []
2528
      for field in self.op.output_fields:
2529
        if field in self._SIMPLE_FIELDS:
2530
          val = getattr(node, field)
2531
        elif field == "pinst_list":
2532
          val = list(node_to_primary[node.name])
2533
        elif field == "sinst_list":
2534
          val = list(node_to_secondary[node.name])
2535
        elif field == "pinst_cnt":
2536
          val = len(node_to_primary[node.name])
2537
        elif field == "sinst_cnt":
2538
          val = len(node_to_secondary[node.name])
2539
        elif field == "pip":
2540
          val = node.primary_ip
2541
        elif field == "sip":
2542
          val = node.secondary_ip
2543
        elif field == "tags":
2544
          val = list(node.GetTags())
2545
        elif field == "master":
2546
          val = node.name == master_node
2547
        elif self._FIELDS_DYNAMIC.Matches(field):
2548
          val = live_data[node.name].get(field, None)
2549
        elif field == "role":
2550
          if node.name == master_node:
2551
            val = "M"
2552
          elif node.master_candidate:
2553
            val = "C"
2554
          elif node.drained:
2555
            val = "D"
2556
          elif node.offline:
2557
            val = "O"
2558
          else:
2559
            val = "R"
2560
        else:
2561
          raise errors.ParameterError(field)
2562
        node_output.append(val)
2563
      output.append(node_output)
2564

    
2565
    return output
2566

    
2567

    
2568
class LUQueryNodeVolumes(NoHooksLU):
2569
  """Logical unit for getting volumes on node(s).
2570

2571
  """
2572
  _OP_REQP = ["nodes", "output_fields"]
2573
  REQ_BGL = False
2574
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2575
  _FIELDS_STATIC = utils.FieldSet("node")
2576

    
2577
  def ExpandNames(self):
2578
    _CheckOutputFields(static=self._FIELDS_STATIC,
2579
                       dynamic=self._FIELDS_DYNAMIC,
2580
                       selected=self.op.output_fields)
2581

    
2582
    self.needed_locks = {}
2583
    self.share_locks[locking.LEVEL_NODE] = 1
2584
    if not self.op.nodes:
2585
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2586
    else:
2587
      self.needed_locks[locking.LEVEL_NODE] = \
2588
        _GetWantedNodes(self, self.op.nodes)
2589

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

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

2595
    """
2596
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2597

    
2598
  def Exec(self, feedback_fn):
2599
    """Computes the list of nodes and their attributes.
2600

2601
    """
2602
    nodenames = self.nodes
2603
    volumes = self.rpc.call_node_volumes(nodenames)
2604

    
2605
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2606
             in self.cfg.GetInstanceList()]
2607

    
2608
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2609

    
2610
    output = []
2611
    for node in nodenames:
2612
      nresult = volumes[node]
2613
      if nresult.offline:
2614
        continue
2615
      msg = nresult.fail_msg
2616
      if msg:
2617
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
2618
        continue
2619

    
2620
      node_vols = nresult.payload[:]
2621
      node_vols.sort(key=lambda vol: vol['dev'])
2622

    
2623
      for vol in node_vols:
2624
        node_output = []
2625
        for field in self.op.output_fields:
2626
          if field == "node":
2627
            val = node
2628
          elif field == "phys":
2629
            val = vol['dev']
2630
          elif field == "vg":
2631
            val = vol['vg']
2632
          elif field == "name":
2633
            val = vol['name']
2634
          elif field == "size":
2635
            val = int(float(vol['size']))
2636
          elif field == "instance":
2637
            for inst in ilist:
2638
              if node not in lv_by_node[inst]:
2639
                continue
2640
              if vol['name'] in lv_by_node[inst][node]:
2641
                val = inst.name
2642
                break
2643
            else:
2644
              val = '-'
2645
          else:
2646
            raise errors.ParameterError(field)
2647
          node_output.append(str(val))
2648

    
2649
        output.append(node_output)
2650

    
2651
    return output
2652

    
2653

    
2654
class LUQueryNodeStorage(NoHooksLU):
2655
  """Logical unit for getting information on storage units on node(s).
2656

2657
  """
2658
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
2659
  REQ_BGL = False
2660
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
2661

    
2662
  def ExpandNames(self):
2663
    storage_type = self.op.storage_type
2664

    
2665
    if storage_type not in constants.VALID_STORAGE_TYPES:
2666
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2667
                                 errors.ECODE_INVAL)
2668

    
2669
    _CheckOutputFields(static=self._FIELDS_STATIC,
2670
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
2671
                       selected=self.op.output_fields)
2672

    
2673
    self.needed_locks = {}
2674
    self.share_locks[locking.LEVEL_NODE] = 1
2675

    
2676
    if self.op.nodes:
2677
      self.needed_locks[locking.LEVEL_NODE] = \
2678
        _GetWantedNodes(self, self.op.nodes)
2679
    else:
2680
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2681

    
2682
  def CheckPrereq(self):
2683
    """Check prerequisites.
2684

2685
    This checks that the fields required are valid output fields.
2686

2687
    """
2688
    self.op.name = getattr(self.op, "name", None)
2689

    
2690
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2691

    
2692
  def Exec(self, feedback_fn):
2693
    """Computes the list of nodes and their attributes.
2694

2695
    """
2696
    # Always get name to sort by
2697
    if constants.SF_NAME in self.op.output_fields:
2698
      fields = self.op.output_fields[:]
2699
    else:
2700
      fields = [constants.SF_NAME] + self.op.output_fields
2701

    
2702
    # Never ask for node or type as it's only known to the LU
2703
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
2704
      while extra in fields:
2705
        fields.remove(extra)
2706

    
2707
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
2708
    name_idx = field_idx[constants.SF_NAME]
2709

    
2710
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2711
    data = self.rpc.call_storage_list(self.nodes,
2712
                                      self.op.storage_type, st_args,
2713
                                      self.op.name, fields)
2714

    
2715
    result = []
2716

    
2717
    for node in utils.NiceSort(self.nodes):
2718
      nresult = data[node]
2719
      if nresult.offline:
2720
        continue
2721

    
2722
      msg = nresult.fail_msg
2723
      if msg:
2724
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
2725
        continue
2726

    
2727
      rows = dict([(row[name_idx], row) for row in nresult.payload])
2728

    
2729
      for name in utils.NiceSort(rows.keys()):
2730
        row = rows[name]
2731

    
2732
        out = []
2733

    
2734
        for field in self.op.output_fields:
2735
          if field == constants.SF_NODE:
2736
            val = node
2737
          elif field == constants.SF_TYPE:
2738
            val = self.op.storage_type
2739
          elif field in field_idx:
2740
            val = row[field_idx[field]]
2741
          else:
2742
            raise errors.ParameterError(field)
2743

    
2744
          out.append(val)
2745

    
2746
        result.append(out)
2747

    
2748
    return result
2749

    
2750

    
2751
class LUModifyNodeStorage(NoHooksLU):
2752
  """Logical unit for modifying a storage volume on a node.
2753

2754
  """
2755
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
2756
  REQ_BGL = False
2757

    
2758
  def CheckArguments(self):
2759
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2760
    if node_name is None:
2761
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
2762
                                 errors.ECODE_NOENT)
2763

    
2764
    self.op.node_name = node_name
2765

    
2766
    storage_type = self.op.storage_type
2767
    if storage_type not in constants.VALID_STORAGE_TYPES:
2768
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2769
                                 errors.ECODE_INVAL)
2770

    
2771
  def ExpandNames(self):
2772
    self.needed_locks = {
2773
      locking.LEVEL_NODE: self.op.node_name,
2774
      }
2775

    
2776
  def CheckPrereq(self):
2777
    """Check prerequisites.
2778

2779
    """
2780
    storage_type = self.op.storage_type
2781

    
2782
    try:
2783
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
2784
    except KeyError:
2785
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
2786
                                 " modified" % storage_type,
2787
                                 errors.ECODE_INVAL)
2788

    
2789
    diff = set(self.op.changes.keys()) - modifiable
2790
    if diff:
2791
      raise errors.OpPrereqError("The following fields can not be modified for"
2792
                                 " storage units of type '%s': %r" %
2793
                                 (storage_type, list(diff)),
2794
                                 errors.ECODE_INVAL)
2795

    
2796
  def Exec(self, feedback_fn):
2797
    """Computes the list of nodes and their attributes.
2798

2799
    """
2800
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2801
    result = self.rpc.call_storage_modify(self.op.node_name,
2802
                                          self.op.storage_type, st_args,
2803
                                          self.op.name, self.op.changes)
2804
    result.Raise("Failed to modify storage unit '%s' on %s" %
2805
                 (self.op.name, self.op.node_name))
2806

    
2807

    
2808
class LUAddNode(LogicalUnit):
2809
  """Logical unit for adding node to the cluster.
2810

2811
  """
2812
  HPATH = "node-add"
2813
  HTYPE = constants.HTYPE_NODE
2814
  _OP_REQP = ["node_name"]
2815

    
2816
  def BuildHooksEnv(self):
2817
    """Build hooks env.
2818

2819
    This will run on all nodes before, and on all nodes + the new node after.
2820

2821
    """
2822
    env = {
2823
      "OP_TARGET": self.op.node_name,
2824
      "NODE_NAME": self.op.node_name,
2825
      "NODE_PIP": self.op.primary_ip,
2826
      "NODE_SIP": self.op.secondary_ip,
2827
      }
2828
    nodes_0 = self.cfg.GetNodeList()
2829
    nodes_1 = nodes_0 + [self.op.node_name, ]
2830
    return env, nodes_0, nodes_1
2831

    
2832
  def CheckPrereq(self):
2833
    """Check prerequisites.
2834

2835
    This checks:
2836
     - the new node is not already in the config
2837
     - it is resolvable
2838
     - its parameters (single/dual homed) matches the cluster
2839

2840
    Any errors are signaled by raising errors.OpPrereqError.
2841

2842
    """
2843
    node_name = self.op.node_name
2844
    cfg = self.cfg
2845

    
2846
    dns_data = utils.GetHostInfo(node_name)
2847

    
2848
    node = dns_data.name
2849
    primary_ip = self.op.primary_ip = dns_data.ip
2850
    secondary_ip = getattr(self.op, "secondary_ip", None)
2851
    if secondary_ip is None:
2852
      secondary_ip = primary_ip
2853
    if not utils.IsValidIP(secondary_ip):
2854
      raise errors.OpPrereqError("Invalid secondary IP given",
2855
                                 errors.ECODE_INVAL)
2856
    self.op.secondary_ip = secondary_ip
2857

    
2858
    node_list = cfg.GetNodeList()
2859
    if not self.op.readd and node in node_list:
2860
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2861
                                 node, errors.ECODE_EXISTS)
2862
    elif self.op.readd and node not in node_list:
2863
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
2864
                                 errors.ECODE_NOENT)
2865

    
2866
    for existing_node_name in node_list:
2867
      existing_node = cfg.GetNodeInfo(existing_node_name)
2868

    
2869
      if self.op.readd and node == existing_node_name:
2870
        if (existing_node.primary_ip != primary_ip or
2871
            existing_node.secondary_ip != secondary_ip):
2872
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2873
                                     " address configuration as before",
2874
                                     errors.ECODE_INVAL)
2875
        continue
2876

    
2877
      if (existing_node.primary_ip == primary_ip or
2878
          existing_node.secondary_ip == primary_ip or
2879
          existing_node.primary_ip == secondary_ip or
2880
          existing_node.secondary_ip == secondary_ip):
2881
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2882
                                   " existing node %s" % existing_node.name,
2883
                                   errors.ECODE_NOTUNIQUE)
2884

    
2885
    # check that the type of the node (single versus dual homed) is the
2886
    # same as for the master
2887
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2888
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2889
    newbie_singlehomed = secondary_ip == primary_ip
2890
    if master_singlehomed != newbie_singlehomed:
2891
      if master_singlehomed:
2892
        raise errors.OpPrereqError("The master has no private ip but the"
2893
                                   " new node has one",
2894
                                   errors.ECODE_INVAL)
2895
      else:
2896
        raise errors.OpPrereqError("The master has a private ip but the"
2897
                                   " new node doesn't have one",
2898
                                   errors.ECODE_INVAL)
2899

    
2900
    # checks reachability
2901
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2902
      raise errors.OpPrereqError("Node not reachable by ping",
2903
                                 errors.ECODE_ENVIRON)
2904

    
2905
    if not newbie_singlehomed:
2906
      # check reachability from my secondary ip to newbie's secondary ip
2907
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2908
                           source=myself.secondary_ip):
2909
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2910
                                   " based ping to noded port",
2911
                                   errors.ECODE_ENVIRON)
2912

    
2913
    if self.op.readd:
2914
      exceptions = [node]
2915
    else:
2916
      exceptions = []
2917

    
2918
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
2919

    
2920
    if self.op.readd:
2921
      self.new_node = self.cfg.GetNodeInfo(node)
2922
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
2923
    else:
2924
      self.new_node = objects.Node(name=node,
2925
                                   primary_ip=primary_ip,
2926
                                   secondary_ip=secondary_ip,
2927
                                   master_candidate=self.master_candidate,
2928
                                   offline=False, drained=False)
2929

    
2930
  def Exec(self, feedback_fn):
2931
    """Adds the new node to the cluster.
2932

2933
    """
2934
    new_node = self.new_node
2935
    node = new_node.name
2936

    
2937
    # for re-adds, reset the offline/drained/master-candidate flags;
2938
    # we need to reset here, otherwise offline would prevent RPC calls
2939
    # later in the procedure; this also means that if the re-add
2940
    # fails, we are left with a non-offlined, broken node
2941
    if self.op.readd:
2942
      new_node.drained = new_node.offline = False
2943
      self.LogInfo("Readding a node, the offline/drained flags were reset")
2944
      # if we demote the node, we do cleanup later in the procedure
2945
      new_node.master_candidate = self.master_candidate
2946

    
2947
    # notify the user about any possible mc promotion
2948
    if new_node.master_candidate:
2949
      self.LogInfo("Node will be a master candidate")
2950

    
2951
    # check connectivity
2952
    result = self.rpc.call_version([node])[node]
2953
    result.Raise("Can't get version information from node %s" % node)
2954
    if constants.PROTOCOL_VERSION == result.payload:
2955
      logging.info("Communication to node %s fine, sw version %s match",
2956
                   node, result.payload)
2957
    else:
2958
      raise errors.OpExecError("Version mismatch master version %s,"
2959
                               " node version %s" %
2960
                               (constants.PROTOCOL_VERSION, result.payload))
2961

    
2962
    # setup ssh on node
2963
    if self.cfg.GetClusterInfo().modify_ssh_setup:
2964
      logging.info("Copy ssh key to node %s", node)
2965
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2966
      keyarray = []
2967
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2968
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2969
                  priv_key, pub_key]
2970

    
2971
      for i in keyfiles:
2972
        keyarray.append(utils.ReadFile(i))
2973

    
2974
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2975
                                      keyarray[2], keyarray[3], keyarray[4],
2976
                                      keyarray[5])
2977
      result.Raise("Cannot transfer ssh keys to the new node")
2978

    
2979
    # Add node to our /etc/hosts, and add key to known_hosts
2980
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2981
      utils.AddHostToEtcHosts(new_node.name)
2982

    
2983
    if new_node.secondary_ip != new_node.primary_ip:
2984
      result = self.rpc.call_node_has_ip_address(new_node.name,
2985
                                                 new_node.secondary_ip)
2986
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
2987
                   prereq=True, ecode=errors.ECODE_ENVIRON)
2988
      if not result.payload:
2989
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2990
                                 " you gave (%s). Please fix and re-run this"
2991
                                 " command." % new_node.secondary_ip)
2992

    
2993
    node_verify_list = [self.cfg.GetMasterNode()]
2994
    node_verify_param = {
2995
      constants.NV_NODELIST: [node],
2996
      # TODO: do a node-net-test as well?
2997
    }
2998

    
2999
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3000
                                       self.cfg.GetClusterName())
3001
    for verifier in node_verify_list:
3002
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3003
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3004
      if nl_payload:
3005
        for failed in nl_payload:
3006
          feedback_fn("ssh/hostname verification failed"
3007
                      " (checking from %s): %s" %
3008
                      (verifier, nl_payload[failed]))
3009
        raise errors.OpExecError("ssh/hostname verification failed.")
3010

    
3011
    if self.op.readd:
3012
      _RedistributeAncillaryFiles(self)
3013
      self.context.ReaddNode(new_node)
3014
      # make sure we redistribute the config
3015
      self.cfg.Update(new_node, feedback_fn)
3016
      # and make sure the new node will not have old files around
3017
      if not new_node.master_candidate:
3018
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3019
        msg = result.fail_msg
3020
        if msg:
3021
          self.LogWarning("Node failed to demote itself from master"
3022
                          " candidate status: %s" % msg)
3023
    else:
3024
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3025
      self.context.AddNode(new_node)
3026

    
3027

    
3028
class LUSetNodeParams(LogicalUnit):
3029
  """Modifies the parameters of a node.
3030

3031
  """
3032
  HPATH = "node-modify"
3033
  HTYPE = constants.HTYPE_NODE
3034
  _OP_REQP = ["node_name"]
3035
  REQ_BGL = False
3036

    
3037
  def CheckArguments(self):
3038
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3039
    if node_name is None:
3040
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3041
                                 errors.ECODE_INVAL)
3042
    self.op.node_name = node_name
3043
    _CheckBooleanOpField(self.op, 'master_candidate')
3044
    _CheckBooleanOpField(self.op, 'offline')
3045
    _CheckBooleanOpField(self.op, 'drained')
3046
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3047
    if all_mods.count(None) == 3:
3048
      raise errors.OpPrereqError("Please pass at least one modification",
3049
                                 errors.ECODE_INVAL)
3050
    if all_mods.count(True) > 1:
3051
      raise errors.OpPrereqError("Can't set the node into more than one"
3052
                                 " state at the same time",
3053
                                 errors.ECODE_INVAL)
3054

    
3055
  def ExpandNames(self):
3056
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3057

    
3058
  def BuildHooksEnv(self):
3059
    """Build hooks env.
3060

3061
    This runs on the master node.
3062

3063
    """
3064
    env = {
3065
      "OP_TARGET": self.op.node_name,
3066
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3067
      "OFFLINE": str(self.op.offline),
3068
      "DRAINED": str(self.op.drained),
3069
      }
3070
    nl = [self.cfg.GetMasterNode(),
3071
          self.op.node_name]
3072
    return env, nl, nl
3073

    
3074
  def CheckPrereq(self):
3075
    """Check prerequisites.
3076

3077
    This only checks the instance list against the existing names.
3078

3079
    """
3080
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3081

    
3082
    if (self.op.master_candidate is not None or
3083
        self.op.drained is not None or
3084
        self.op.offline is not None):
3085
      # we can't change the master's node flags
3086
      if self.op.node_name == self.cfg.GetMasterNode():
3087
        raise errors.OpPrereqError("The master role can be changed"
3088
                                   " only via masterfailover",
3089
                                   errors.ECODE_INVAL)
3090

    
3091
    # Boolean value that tells us whether we're offlining or draining the node
3092
    offline_or_drain = self.op.offline == True or self.op.drained == True
3093
    deoffline_or_drain = self.op.offline == False or self.op.drained == False
3094

    
3095
    if (node.master_candidate and
3096
        (self.op.master_candidate == False or offline_or_drain)):
3097
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
3098
      mc_now, mc_should, mc_max = self.cfg.GetMasterCandidateStats()
3099
      if mc_now <= cp_size:
3100
        msg = ("Not enough master candidates (desired"
3101
               " %d, new value will be %d)" % (cp_size, mc_now-1))
3102
        # Only allow forcing the operation if it's an offline/drain operation,
3103
        # and we could not possibly promote more nodes.
3104
        # FIXME: this can still lead to issues if in any way another node which
3105
        # could be promoted appears in the meantime.
3106
        if self.op.force and offline_or_drain and mc_should == mc_max:
3107
          self.LogWarning(msg)
3108
        else:
3109
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
3110

    
3111
    if (self.op.master_candidate == True and
3112
        ((node.offline and not self.op.offline == False) or
3113
         (node.drained and not self.op.drained == False))):
3114
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3115
                                 " to master_candidate" % node.name,
3116
                                 errors.ECODE_INVAL)
3117

    
3118
    # If we're being deofflined/drained, we'll MC ourself if needed
3119
    if (deoffline_or_drain and not offline_or_drain and not
3120
        self.op.master_candidate == True):
3121
      self.op.master_candidate = _DecideSelfPromotion(self)
3122
      if self.op.master_candidate:
3123
        self.LogInfo("Autopromoting node to master candidate")
3124

    
3125
    return
3126

    
3127
  def Exec(self, feedback_fn):
3128
    """Modifies a node.
3129

3130
    """
3131
    node = self.node
3132

    
3133
    result = []
3134
    changed_mc = False
3135

    
3136
    if self.op.offline is not None:
3137
      node.offline = self.op.offline
3138
      result.append(("offline", str(self.op.offline)))
3139
      if self.op.offline == True:
3140
        if node.master_candidate:
3141
          node.master_candidate = False
3142
          changed_mc = True
3143
          result.append(("master_candidate", "auto-demotion due to offline"))
3144
        if node.drained:
3145
          node.drained = False
3146
          result.append(("drained", "clear drained status due to offline"))
3147

    
3148
    if self.op.master_candidate is not None:
3149
      node.master_candidate = self.op.master_candidate
3150
      changed_mc = True
3151
      result.append(("master_candidate", str(self.op.master_candidate)))
3152
      if self.op.master_candidate == False:
3153
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3154
        msg = rrc.fail_msg
3155
        if msg:
3156
          self.LogWarning("Node failed to demote itself: %s" % msg)
3157

    
3158
    if self.op.drained is not None:
3159
      node.drained = self.op.drained
3160
      result.append(("drained", str(self.op.drained)))
3161
      if self.op.drained == True:
3162
        if node.master_candidate:
3163
          node.master_candidate = False
3164
          changed_mc = True
3165
          result.append(("master_candidate", "auto-demotion due to drain"))
3166
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3167
          msg = rrc.fail_msg
3168
          if msg:
3169
            self.LogWarning("Node failed to demote itself: %s" % msg)
3170
        if node.offline:
3171
          node.offline = False
3172
          result.append(("offline", "clear offline status due to drain"))
3173

    
3174
    # this will trigger configuration file update, if needed
3175
    self.cfg.Update(node, feedback_fn)
3176
    # this will trigger job queue propagation or cleanup
3177
    if changed_mc:
3178
      self.context.ReaddNode(node)
3179

    
3180
    return result
3181

    
3182

    
3183
class LUPowercycleNode(NoHooksLU):
3184
  """Powercycles a node.
3185

3186
  """
3187
  _OP_REQP = ["node_name", "force"]
3188
  REQ_BGL = False
3189

    
3190
  def CheckArguments(self):
3191
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3192
    if node_name is None:
3193
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3194
                                 errors.ECODE_NOENT)
3195
    self.op.node_name = node_name
3196
    if node_name == self.cfg.GetMasterNode() and not self.op.force:
3197
      raise errors.OpPrereqError("The node is the master and the force"
3198
                                 " parameter was not set",
3199
                                 errors.ECODE_INVAL)
3200

    
3201
  def ExpandNames(self):
3202
    """Locking for PowercycleNode.
3203

3204
    This is a last-resort option and shouldn't block on other
3205
    jobs. Therefore, we grab no locks.
3206

3207
    """
3208
    self.needed_locks = {}
3209

    
3210
  def CheckPrereq(self):
3211
    """Check prerequisites.
3212

3213
    This LU has no prereqs.
3214

3215
    """
3216
    pass
3217

    
3218
  def Exec(self, feedback_fn):
3219
    """Reboots a node.
3220

3221
    """
3222
    result = self.rpc.call_node_powercycle(self.op.node_name,
3223
                                           self.cfg.GetHypervisorType())
3224
    result.Raise("Failed to schedule the reboot")
3225
    return result.payload
3226

    
3227

    
3228
class LUQueryClusterInfo(NoHooksLU):
3229
  """Query cluster configuration.
3230

3231
  """
3232
  _OP_REQP = []
3233
  REQ_BGL = False
3234

    
3235
  def ExpandNames(self):
3236
    self.needed_locks = {}
3237

    
3238
  def CheckPrereq(self):
3239
    """No prerequsites needed for this LU.
3240

3241
    """
3242
    pass
3243

    
3244
  def Exec(self, feedback_fn):
3245
    """Return cluster config.
3246

3247
    """
3248
    cluster = self.cfg.GetClusterInfo()
3249
    result = {
3250
      "software_version": constants.RELEASE_VERSION,
3251
      "protocol_version": constants.PROTOCOL_VERSION,
3252
      "config_version": constants.CONFIG_VERSION,
3253
      "os_api_version": max(constants.OS_API_VERSIONS),
3254
      "export_version": constants.EXPORT_VERSION,
3255
      "architecture": (platform.architecture()[0], platform.machine()),
3256
      "name": cluster.cluster_name,
3257
      "master": cluster.master_node,
3258
      "default_hypervisor": cluster.enabled_hypervisors[0],
3259
      "enabled_hypervisors": cluster.enabled_hypervisors,
3260
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3261
                        for hypervisor_name in cluster.enabled_hypervisors]),
3262
      "beparams": cluster.beparams,
3263
      "nicparams": cluster.nicparams,
3264
      "candidate_pool_size": cluster.candidate_pool_size,
3265
      "master_netdev": cluster.master_netdev,
3266
      "volume_group_name": cluster.volume_group_name,
3267
      "file_storage_dir": cluster.file_storage_dir,
3268
      "ctime": cluster.ctime,
3269
      "mtime": cluster.mtime,
3270
      "uuid": cluster.uuid,
3271
      "tags": list(cluster.GetTags()),
3272
      }
3273

    
3274
    return result
3275

    
3276

    
3277
class LUQueryConfigValues(NoHooksLU):
3278
  """Return configuration values.
3279

3280
  """
3281
  _OP_REQP = []
3282
  REQ_BGL = False
3283
  _FIELDS_DYNAMIC = utils.FieldSet()
3284
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3285
                                  "watcher_pause")
3286

    
3287
  def ExpandNames(self):
3288
    self.needed_locks = {}
3289

    
3290
    _CheckOutputFields(static=self._FIELDS_STATIC,
3291
                       dynamic=self._FIELDS_DYNAMIC,
3292
                       selected=self.op.output_fields)
3293

    
3294
  def CheckPrereq(self):
3295
    """No prerequisites.
3296

3297
    """
3298
    pass
3299

    
3300
  def Exec(self, feedback_fn):
3301
    """Dump a representation of the cluster config to the standard output.
3302

3303
    """
3304
    values = []
3305
    for field in self.op.output_fields:
3306
      if field == "cluster_name":
3307
        entry = self.cfg.GetClusterName()
3308
      elif field == "master_node":
3309
        entry = self.cfg.GetMasterNode()
3310
      elif field == "drain_flag":
3311
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3312
      elif field == "watcher_pause":
3313
        return utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3314
      else:
3315
        raise errors.ParameterError(field)
3316
      values.append(entry)
3317
    return values
3318

    
3319

    
3320
class LUActivateInstanceDisks(NoHooksLU):
3321
  """Bring up an instance's disks.
3322

3323
  """
3324
  _OP_REQP = ["instance_name"]
3325
  REQ_BGL = False
3326

    
3327
  def ExpandNames(self):
3328
    self._ExpandAndLockInstance()
3329
    self.needed_locks[locking.LEVEL_NODE] = []
3330
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3331

    
3332
  def DeclareLocks(self, level):
3333
    if level == locking.LEVEL_NODE:
3334
      self._LockInstancesNodes()
3335

    
3336
  def CheckPrereq(self):
3337
    """Check prerequisites.
3338

3339
    This checks that the instance is in the cluster.
3340

3341
    """
3342
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3343
    assert self.instance is not None, \
3344
      "Cannot retrieve locked instance %s" % self.op.instance_name
3345
    _CheckNodeOnline(self, self.instance.primary_node)
3346
    if not hasattr(self.op, "ignore_size"):
3347
      self.op.ignore_size = False
3348

    
3349
  def Exec(self, feedback_fn):
3350
    """Activate the disks.
3351

3352
    """
3353
    disks_ok, disks_info = \
3354
              _AssembleInstanceDisks(self, self.instance,
3355
                                     ignore_size=self.op.ignore_size)
3356
    if not disks_ok:
3357
      raise errors.OpExecError("Cannot activate block devices")
3358

    
3359
    return disks_info
3360

    
3361

    
3362
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3363
                           ignore_size=False):
3364
  """Prepare the block devices for an instance.
3365

3366
  This sets up the block devices on all nodes.
3367

3368
  @type lu: L{LogicalUnit}
3369
  @param lu: the logical unit on whose behalf we execute
3370
  @type instance: L{objects.Instance}
3371
  @param instance: the instance for whose disks we assemble
3372
  @type ignore_secondaries: boolean
3373
  @param ignore_secondaries: if true, errors on secondary nodes
3374
      won't result in an error return from the function
3375
  @type ignore_size: boolean
3376
  @param ignore_size: if true, the current known size of the disk
3377
      will not be used during the disk activation, useful for cases
3378
      when the size is wrong
3379
  @return: False if the operation failed, otherwise a list of
3380
      (host, instance_visible_name, node_visible_name)
3381
      with the mapping from node devices to instance devices
3382

3383
  """
3384
  device_info = []
3385
  disks_ok = True
3386
  iname = instance.name
3387
  # With the two passes mechanism we try to reduce the window of
3388
  # opportunity for the race condition of switching DRBD to primary
3389
  # before handshaking occured, but we do not eliminate it
3390

    
3391
  # The proper fix would be to wait (with some limits) until the
3392
  # connection has been made and drbd transitions from WFConnection
3393
  # into any other network-connected state (Connected, SyncTarget,
3394
  # SyncSource, etc.)
3395

    
3396
  # 1st pass, assemble on all nodes in secondary mode
3397
  for inst_disk in instance.disks:
3398
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3399
      if ignore_size:
3400
        node_disk = node_disk.Copy()
3401
        node_disk.UnsetSize()
3402
      lu.cfg.SetDiskID(node_disk, node)
3403
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3404
      msg = result.fail_msg
3405
      if msg:
3406
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3407
                           " (is_primary=False, pass=1): %s",
3408
                           inst_disk.iv_name, node, msg)
3409
        if not ignore_secondaries:
3410
          disks_ok = False
3411

    
3412
  # FIXME: race condition on drbd migration to primary
3413

    
3414
  # 2nd pass, do only the primary node
3415
  for inst_disk in instance.disks:
3416
    dev_path = None
3417

    
3418
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3419
      if node != instance.primary_node:
3420
        continue
3421
      if ignore_size:
3422
        node_disk = node_disk.Copy()
3423
        node_disk.UnsetSize()
3424
      lu.cfg.SetDiskID(node_disk, node)
3425
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3426
      msg = result.fail_msg
3427
      if msg:
3428
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3429
                           " (is_primary=True, pass=2): %s",
3430
                           inst_disk.iv_name, node, msg)
3431
        disks_ok = False
3432
      else:
3433
        dev_path = result.payload
3434

    
3435
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3436

    
3437
  # leave the disks configured for the primary node
3438
  # this is a workaround that would be fixed better by
3439
  # improving the logical/physical id handling
3440
  for disk in instance.disks:
3441
    lu.cfg.SetDiskID(disk, instance.primary_node)
3442

    
3443
  return disks_ok, device_info
3444

    
3445

    
3446
def _StartInstanceDisks(lu, instance, force):
3447
  """Start the disks of an instance.
3448

3449
  """
3450
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3451
                                           ignore_secondaries=force)
3452
  if not disks_ok:
3453
    _ShutdownInstanceDisks(lu, instance)
3454
    if force is not None and not force:
3455
      lu.proc.LogWarning("", hint="If the message above refers to a"
3456
                         " secondary node,"
3457
                         " you can retry the operation using '--force'.")
3458
    raise errors.OpExecError("Disk consistency error")
3459

    
3460

    
3461
class LUDeactivateInstanceDisks(NoHooksLU):
3462
  """Shutdown an instance's disks.
3463

3464
  """
3465
  _OP_REQP = ["instance_name"]
3466
  REQ_BGL = False
3467

    
3468
  def ExpandNames(self):
3469
    self._ExpandAndLockInstance()
3470
    self.needed_locks[locking.LEVEL_NODE] = []
3471
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3472

    
3473
  def DeclareLocks(self, level):
3474
    if level == locking.LEVEL_NODE:
3475
      self._LockInstancesNodes()
3476

    
3477
  def CheckPrereq(self):
3478
    """Check prerequisites.
3479

3480
    This checks that the instance is in the cluster.
3481

3482
    """
3483
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3484
    assert self.instance is not None, \
3485
      "Cannot retrieve locked instance %s" % self.op.instance_name
3486

    
3487
  def Exec(self, feedback_fn):
3488
    """Deactivate the disks
3489

3490
    """
3491
    instance = self.instance
3492
    _SafeShutdownInstanceDisks(self, instance)
3493

    
3494

    
3495
def _SafeShutdownInstanceDisks(lu, instance):
3496
  """Shutdown block devices of an instance.
3497

3498
  This function checks if an instance is running, before calling
3499
  _ShutdownInstanceDisks.
3500

3501
  """
3502
  pnode = instance.primary_node
3503
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
3504
  ins_l.Raise("Can't contact node %s" % pnode)
3505

    
3506
  if instance.name in ins_l.payload:
3507
    raise errors.OpExecError("Instance is running, can't shutdown"
3508
                             " block devices.")
3509

    
3510
  _ShutdownInstanceDisks(lu, instance)
3511

    
3512

    
3513
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3514
  """Shutdown block devices of an instance.
3515

3516
  This does the shutdown on all nodes of the instance.
3517

3518
  If the ignore_primary is false, errors on the primary node are
3519
  ignored.
3520

3521
  """
3522
  all_result = True
3523
  for disk in instance.disks:
3524
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3525
      lu.cfg.SetDiskID(top_disk, node)
3526
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3527
      msg = result.fail_msg
3528
      if msg:
3529
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3530
                      disk.iv_name, node, msg)
3531
        if not ignore_primary or node != instance.primary_node:
3532
          all_result = False
3533
  return all_result
3534

    
3535

    
3536
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3537
  """Checks if a node has enough free memory.
3538

3539
  This function check if a given node has the needed amount of free
3540
  memory. In case the node has less memory or we cannot get the
3541
  information from the node, this function raise an OpPrereqError
3542
  exception.
3543

3544
  @type lu: C{LogicalUnit}
3545
  @param lu: a logical unit from which we get configuration data
3546
  @type node: C{str}
3547
  @param node: the node to check
3548
  @type reason: C{str}
3549
  @param reason: string to use in the error message
3550
  @type requested: C{int}
3551
  @param requested: the amount of memory in MiB to check for
3552
  @type hypervisor_name: C{str}
3553
  @param hypervisor_name: the hypervisor to ask for memory stats
3554
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3555
      we cannot check the node
3556

3557
  """
3558
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3559
  nodeinfo[node].Raise("Can't get data from node %s" % node,
3560
                       prereq=True, ecode=errors.ECODE_ENVIRON)
3561
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3562
  if not isinstance(free_mem, int):
3563
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3564
                               " was '%s'" % (node, free_mem),
3565
                               errors.ECODE_ENVIRON)
3566
  if requested > free_mem:
3567
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3568
                               " needed %s MiB, available %s MiB" %
3569
                               (node, reason, requested, free_mem),
3570
                               errors.ECODE_NORES)
3571

    
3572

    
3573
class LUStartupInstance(LogicalUnit):
3574
  """Starts an instance.
3575

3576
  """
3577
  HPATH = "instance-start"
3578
  HTYPE = constants.HTYPE_INSTANCE
3579
  _OP_REQP = ["instance_name", "force"]
3580
  REQ_BGL = False
3581

    
3582
  def ExpandNames(self):
3583
    self._ExpandAndLockInstance()
3584

    
3585
  def BuildHooksEnv(self):
3586
    """Build hooks env.
3587

3588
    This runs on master, primary and secondary nodes of the instance.
3589

3590
    """
3591
    env = {
3592
      "FORCE": self.op.force,
3593
      }
3594
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3595
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3596
    return env, nl, nl
3597

    
3598
  def CheckPrereq(self):
3599
    """Check prerequisites.
3600

3601
    This checks that the instance is in the cluster.
3602

3603
    """
3604
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3605
    assert self.instance is not None, \
3606
      "Cannot retrieve locked instance %s" % self.op.instance_name
3607

    
3608
    # extra beparams
3609
    self.beparams = getattr(self.op, "beparams", {})
3610
    if self.beparams:
3611
      if not isinstance(self.beparams, dict):
3612
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3613
                                   " dict" % (type(self.beparams), ),
3614
                                   errors.ECODE_INVAL)
3615
      # fill the beparams dict
3616
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3617
      self.op.beparams = self.beparams
3618

    
3619
    # extra hvparams
3620
    self.hvparams = getattr(self.op, "hvparams", {})
3621
    if self.hvparams:
3622
      if not isinstance(self.hvparams, dict):
3623
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3624
                                   " dict" % (type(self.hvparams), ),
3625
                                   errors.ECODE_INVAL)
3626

    
3627
      # check hypervisor parameter syntax (locally)
3628
      cluster = self.cfg.GetClusterInfo()
3629
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3630
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
3631
                                    instance.hvparams)
3632
      filled_hvp.update(self.hvparams)
3633
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3634
      hv_type.CheckParameterSyntax(filled_hvp)
3635
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3636
      self.op.hvparams = self.hvparams
3637

    
3638
    _CheckNodeOnline(self, instance.primary_node)
3639

    
3640
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3641
    # check bridges existence
3642
    _CheckInstanceBridgesExist(self, instance)
3643

    
3644
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3645
                                              instance.name,
3646
                                              instance.hypervisor)
3647
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3648
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3649
    if not remote_info.payload: # not running already
3650
      _CheckNodeFreeMemory(self, instance.primary_node,
3651
                           "starting instance %s" % instance.name,
3652
                           bep[constants.BE_MEMORY], instance.hypervisor)
3653

    
3654
  def Exec(self, feedback_fn):
3655
    """Start the instance.
3656

3657
    """
3658
    instance = self.instance
3659
    force = self.op.force
3660

    
3661
    self.cfg.MarkInstanceUp(instance.name)
3662

    
3663
    node_current = instance.primary_node
3664

    
3665
    _StartInstanceDisks(self, instance, force)
3666

    
3667
    result = self.rpc.call_instance_start(node_current, instance,
3668
                                          self.hvparams, self.beparams)
3669
    msg = result.fail_msg
3670
    if msg:
3671
      _ShutdownInstanceDisks(self, instance)
3672
      raise errors.OpExecError("Could not start instance: %s" % msg)
3673

    
3674

    
3675
class LURebootInstance(LogicalUnit):
3676
  """Reboot an instance.
3677

3678
  """
3679
  HPATH = "instance-reboot"
3680
  HTYPE = constants.HTYPE_INSTANCE
3681
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3682
  REQ_BGL = False
3683

    
3684
  def CheckArguments(self):
3685
    """Check the arguments.
3686

3687
    """
3688
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
3689
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
3690

    
3691
  def ExpandNames(self):
3692
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3693
                                   constants.INSTANCE_REBOOT_HARD,
3694
                                   constants.INSTANCE_REBOOT_FULL]:
3695
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3696
                                  (constants.INSTANCE_REBOOT_SOFT,
3697
                                   constants.INSTANCE_REBOOT_HARD,
3698
                                   constants.INSTANCE_REBOOT_FULL))
3699
    self._ExpandAndLockInstance()
3700

    
3701
  def BuildHooksEnv(self):
3702
    """Build hooks env.
3703

3704
    This runs on master, primary and secondary nodes of the instance.
3705

3706
    """
3707
    env = {
3708
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3709
      "REBOOT_TYPE": self.op.reboot_type,
3710
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
3711
      }
3712
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3713
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3714
    return env, nl, nl
3715

    
3716
  def CheckPrereq(self):
3717
    """Check prerequisites.
3718

3719
    This checks that the instance is in the cluster.
3720

3721
    """
3722
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3723
    assert self.instance is not None, \
3724
      "Cannot retrieve locked instance %s" % self.op.instance_name
3725

    
3726
    _CheckNodeOnline(self, instance.primary_node)
3727

    
3728
    # check bridges existence
3729
    _CheckInstanceBridgesExist(self, instance)
3730

    
3731
  def Exec(self, feedback_fn):
3732
    """Reboot the instance.
3733

3734
    """
3735
    instance = self.instance
3736
    ignore_secondaries = self.op.ignore_secondaries
3737
    reboot_type = self.op.reboot_type
3738

    
3739
    node_current = instance.primary_node
3740

    
3741
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3742
                       constants.INSTANCE_REBOOT_HARD]:
3743
      for disk in instance.disks:
3744
        self.cfg.SetDiskID(disk, node_current)
3745
      result = self.rpc.call_instance_reboot(node_current, instance,
3746
                                             reboot_type,
3747
                                             self.shutdown_timeout)
3748
      result.Raise("Could not reboot instance")
3749
    else:
3750
      result = self.rpc.call_instance_shutdown(node_current, instance,
3751
                                               self.shutdown_timeout)
3752
      result.Raise("Could not shutdown instance for full reboot")
3753
      _ShutdownInstanceDisks(self, instance)
3754
      _StartInstanceDisks(self, instance, ignore_secondaries)
3755
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3756
      msg = result.fail_msg
3757
      if msg:
3758
        _ShutdownInstanceDisks(self, instance)
3759
        raise errors.OpExecError("Could not start instance for"
3760
                                 " full reboot: %s" % msg)
3761

    
3762
    self.cfg.MarkInstanceUp(instance.name)
3763

    
3764

    
3765
class LUShutdownInstance(LogicalUnit):
3766
  """Shutdown an instance.
3767

3768
  """
3769
  HPATH = "instance-stop"
3770
  HTYPE = constants.HTYPE_INSTANCE
3771
  _OP_REQP = ["instance_name"]
3772
  REQ_BGL = False
3773

    
3774
  def CheckArguments(self):
3775
    """Check the arguments.
3776

3777
    """
3778
    self.timeout = getattr(self.op, "timeout",
3779
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
3780

    
3781
  def ExpandNames(self):
3782
    self._ExpandAndLockInstance()
3783

    
3784
  def BuildHooksEnv(self):
3785
    """Build hooks env.
3786

3787
    This runs on master, primary and secondary nodes of the instance.
3788

3789
    """
3790
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3791
    env["TIMEOUT"] = self.timeout
3792
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3793
    return env, nl, nl
3794

    
3795
  def CheckPrereq(self):
3796
    """Check prerequisites.
3797

3798
    This checks that the instance is in the cluster.
3799

3800
    """
3801
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3802
    assert self.instance is not None, \
3803
      "Cannot retrieve locked instance %s" % self.op.instance_name
3804
    _CheckNodeOnline(self, self.instance.primary_node)
3805

    
3806
  def Exec(self, feedback_fn):
3807
    """Shutdown the instance.
3808

3809
    """
3810
    instance = self.instance
3811
    node_current = instance.primary_node
3812
    timeout = self.timeout
3813
    self.cfg.MarkInstanceDown(instance.name)
3814
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
3815
    msg = result.fail_msg
3816
    if msg:
3817
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
3818

    
3819
    _ShutdownInstanceDisks(self, instance)
3820

    
3821

    
3822
class LUReinstallInstance(LogicalUnit):
3823
  """Reinstall an instance.
3824

3825
  """
3826
  HPATH = "instance-reinstall"
3827
  HTYPE = constants.HTYPE_INSTANCE
3828
  _OP_REQP = ["instance_name"]
3829
  REQ_BGL = False
3830

    
3831
  def ExpandNames(self):
3832
    self._ExpandAndLockInstance()
3833

    
3834
  def BuildHooksEnv(self):
3835
    """Build hooks env.
3836

3837
    This runs on master, primary and secondary nodes of the instance.
3838

3839
    """
3840
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3841
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3842
    return env, nl, nl
3843

    
3844
  def CheckPrereq(self):
3845
    """Check prerequisites.
3846

3847
    This checks that the instance is in the cluster and is not running.
3848

3849
    """
3850
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3851
    assert instance is not None, \
3852
      "Cannot retrieve locked instance %s" % self.op.instance_name
3853
    _CheckNodeOnline(self, instance.primary_node)
3854

    
3855
    if instance.disk_template == constants.DT_DISKLESS:
3856
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3857
                                 self.op.instance_name,
3858
                                 errors.ECODE_INVAL)
3859
    if instance.admin_up:
3860
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3861
                                 self.op.instance_name,
3862
                                 errors.ECODE_STATE)
3863
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3864
                                              instance.name,
3865
                                              instance.hypervisor)
3866
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3867
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3868
    if remote_info.payload:
3869
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3870
                                 (self.op.instance_name,
3871
                                  instance.primary_node),
3872
                                 errors.ECODE_STATE)
3873

    
3874
    self.op.os_type = getattr(self.op, "os_type", None)
3875
    self.op.force_variant = getattr(self.op, "force_variant", False)
3876
    if self.op.os_type is not None:
3877
      # OS verification
3878
      pnode = self.cfg.GetNodeInfo(
3879
        self.cfg.ExpandNodeName(instance.primary_node))
3880
      if pnode is None:
3881
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
3882
                                   self.op.pnode, errors.ECODE_NOENT)
3883
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
3884
      result.Raise("OS '%s' not in supported OS list for primary node %s" %
3885
                   (self.op.os_type, pnode.name),
3886
                   prereq=True, ecode=errors.ECODE_INVAL)
3887
      if not self.op.force_variant:
3888
        _CheckOSVariant(result.payload, self.op.os_type)
3889

    
3890
    self.instance = instance
3891

    
3892
  def Exec(self, feedback_fn):
3893
    """Reinstall the instance.
3894

3895
    """
3896
    inst = self.instance
3897

    
3898
    if self.op.os_type is not None:
3899
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
3900
      inst.os = self.op.os_type
3901
      self.cfg.Update(inst, feedback_fn)
3902

    
3903
    _StartInstanceDisks(self, inst, None)
3904
    try:
3905
      feedback_fn("Running the instance OS create scripts...")
3906
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True)
3907
      result.Raise("Could not install OS for instance %s on node %s" %
3908
                   (inst.name, inst.primary_node))
3909
    finally:
3910
      _ShutdownInstanceDisks(self, inst)
3911

    
3912

    
3913
class LURecreateInstanceDisks(LogicalUnit):
3914
  """Recreate an instance's missing disks.
3915

3916
  """
3917
  HPATH = "instance-recreate-disks"
3918
  HTYPE = constants.HTYPE_INSTANCE
3919
  _OP_REQP = ["instance_name", "disks"]
3920
  REQ_BGL = False
3921

    
3922
  def CheckArguments(self):
3923
    """Check the arguments.
3924

3925
    """
3926
    if not isinstance(self.op.disks, list):
3927
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
3928
    for item in self.op.disks:
3929
      if (not isinstance(item, int) or
3930
          item < 0):
3931
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
3932
                                   str(item), errors.ECODE_INVAL)
3933

    
3934
  def ExpandNames(self):
3935
    self._ExpandAndLockInstance()
3936

    
3937
  def BuildHooksEnv(self):
3938
    """Build hooks env.
3939

3940
    This runs on master, primary and secondary nodes of the instance.
3941

3942
    """
3943
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3944
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3945
    return env, nl, nl
3946

    
3947
  def CheckPrereq(self):
3948
    """Check prerequisites.
3949

3950
    This checks that the instance is in the cluster and is not running.
3951

3952
    """
3953
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3954
    assert instance is not None, \
3955
      "Cannot retrieve locked instance %s" % self.op.instance_name
3956
    _CheckNodeOnline(self, instance.primary_node)
3957

    
3958
    if instance.disk_template == constants.DT_DISKLESS:
3959
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3960
                                 self.op.instance_name, errors.ECODE_INVAL)
3961
    if instance.admin_up:
3962
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3963
                                 self.op.instance_name, errors.ECODE_STATE)
3964
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3965
                                              instance.name,
3966
                                              instance.hypervisor)
3967
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3968
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3969
    if remote_info.payload:
3970
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3971
                                 (self.op.instance_name,
3972
                                  instance.primary_node), errors.ECODE_STATE)
3973

    
3974
    if not self.op.disks:
3975
      self.op.disks = range(len(instance.disks))
3976
    else:
3977
      for idx in self.op.disks:
3978
        if idx >= len(instance.disks):
3979
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
3980
                                     errors.ECODE_INVAL)
3981

    
3982
    self.instance = instance
3983

    
3984
  def Exec(self, feedback_fn):
3985
    """Recreate the disks.
3986

3987
    """
3988
    to_skip = []
3989
    for idx, disk in enumerate(self.instance.disks):
3990
      if idx not in self.op.disks: # disk idx has not been passed in
3991
        to_skip.append(idx)
3992
        continue
3993

    
3994
    _CreateDisks(self, self.instance, to_skip=to_skip)
3995

    
3996

    
3997
class LURenameInstance(LogicalUnit):
3998
  """Rename an instance.
3999

4000
  """
4001
  HPATH = "instance-rename"
4002
  HTYPE = constants.HTYPE_INSTANCE
4003
  _OP_REQP = ["instance_name", "new_name"]
4004

    
4005
  def BuildHooksEnv(self):
4006
    """Build hooks env.
4007

4008
    This runs on master, primary and secondary nodes of the instance.
4009

4010
    """
4011
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4012
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4013
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4014
    return env, nl, nl
4015

    
4016
  def CheckPrereq(self):
4017
    """Check prerequisites.
4018

4019
    This checks that the instance is in the cluster and is not running.
4020

4021
    """
4022
    instance = self.cfg.GetInstanceInfo(
4023
      self.cfg.ExpandInstanceName(self.op.instance_name))
4024
    if instance is None:
4025
      raise errors.OpPrereqError("Instance '%s' not known" %
4026
                                 self.op.instance_name, errors.ECODE_NOENT)
4027
    _CheckNodeOnline(self, instance.primary_node)
4028

    
4029
    if instance.admin_up:
4030
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
4031
                                 self.op.instance_name, errors.ECODE_STATE)
4032
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4033
                                              instance.name,
4034
                                              instance.hypervisor)
4035
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4036
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4037
    if remote_info.payload:
4038
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
4039
                                 (self.op.instance_name,
4040
                                  instance.primary_node), errors.ECODE_STATE)
4041
    self.instance = instance
4042

    
4043
    # new name verification
4044
    name_info = utils.GetHostInfo(self.op.new_name)
4045

    
4046
    self.op.new_name = new_name = name_info.name
4047
    instance_list = self.cfg.GetInstanceList()
4048
    if new_name in instance_list:
4049
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4050
                                 new_name, errors.ECODE_EXISTS)
4051

    
4052
    if not getattr(self.op, "ignore_ip", False):
4053
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4054
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4055
                                   (name_info.ip, new_name),
4056
                                   errors.ECODE_NOTUNIQUE)
4057

    
4058

    
4059
  def Exec(self, feedback_fn):
4060
    """Reinstall the instance.
4061

4062
    """
4063
    inst = self.instance
4064
    old_name = inst.name
4065

    
4066
    if inst.disk_template == constants.DT_FILE:
4067
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4068

    
4069
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4070
    # Change the instance lock. This is definitely safe while we hold the BGL
4071
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4072
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4073

    
4074
    # re-read the instance from the configuration after rename
4075
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4076

    
4077
    if inst.disk_template == constants.DT_FILE:
4078
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4079
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4080
                                                     old_file_storage_dir,
4081
                                                     new_file_storage_dir)
4082
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4083
                   " (but the instance has been renamed in Ganeti)" %
4084
                   (inst.primary_node, old_file_storage_dir,
4085
                    new_file_storage_dir))
4086

    
4087
    _StartInstanceDisks(self, inst, None)
4088
    try:
4089
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4090
                                                 old_name)
4091
      msg = result.fail_msg
4092
      if msg:
4093
        msg = ("Could not run OS rename script for instance %s on node %s"
4094
               " (but the instance has been renamed in Ganeti): %s" %
4095
               (inst.name, inst.primary_node, msg))
4096
        self.proc.LogWarning(msg)
4097
    finally:
4098
      _ShutdownInstanceDisks(self, inst)
4099

    
4100

    
4101
class LURemoveInstance(LogicalUnit):
4102
  """Remove an instance.
4103

4104
  """
4105
  HPATH = "instance-remove"
4106
  HTYPE = constants.HTYPE_INSTANCE
4107
  _OP_REQP = ["instance_name", "ignore_failures"]
4108
  REQ_BGL = False
4109

    
4110
  def CheckArguments(self):
4111
    """Check the arguments.
4112

4113
    """
4114
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4115
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4116

    
4117
  def ExpandNames(self):
4118
    self._ExpandAndLockInstance()
4119
    self.needed_locks[locking.LEVEL_NODE] = []
4120
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4121

    
4122
  def DeclareLocks(self, level):
4123
    if level == locking.LEVEL_NODE:
4124
      self._LockInstancesNodes()
4125

    
4126
  def BuildHooksEnv(self):
4127
    """Build hooks env.
4128

4129
    This runs on master, primary and secondary nodes of the instance.
4130

4131
    """
4132
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4133
    env["SHUTDOWN_TIMEOUT"] = self.shutdown_timeout
4134
    nl = [self.cfg.GetMasterNode()]
4135
    return env, nl, nl
4136

    
4137
  def CheckPrereq(self):
4138
    """Check prerequisites.
4139

4140
    This checks that the instance is in the cluster.
4141

4142
    """
4143
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4144
    assert self.instance is not None, \
4145
      "Cannot retrieve locked instance %s" % self.op.instance_name
4146

    
4147
  def Exec(self, feedback_fn):
4148
    """Remove the instance.
4149

4150
    """
4151
    instance = self.instance
4152
    logging.info("Shutting down instance %s on node %s",
4153
                 instance.name, instance.primary_node)
4154

    
4155
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4156
                                             self.shutdown_timeout)
4157
    msg = result.fail_msg
4158
    if msg:
4159
      if self.op.ignore_failures:
4160
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4161
      else:
4162
        raise errors.OpExecError("Could not shutdown instance %s on"
4163
                                 " node %s: %s" %
4164
                                 (instance.name, instance.primary_node, msg))
4165

    
4166
    logging.info("Removing block devices for instance %s", instance.name)
4167

    
4168
    if not _RemoveDisks(self, instance):
4169
      if self.op.ignore_failures:
4170
        feedback_fn("Warning: can't remove instance's disks")
4171
      else:
4172
        raise errors.OpExecError("Can't remove instance's disks")
4173

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

    
4176
    self.cfg.RemoveInstance(instance.name)
4177
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4178

    
4179

    
4180
class LUQueryInstances(NoHooksLU):
4181
  """Logical unit for querying instances.
4182

4183
  """
4184
  _OP_REQP = ["output_fields", "names", "use_locking"]
4185
  REQ_BGL = False
4186
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4187
                    "serial_no", "ctime", "mtime", "uuid"]
4188
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4189
                                    "admin_state",
4190
                                    "disk_template", "ip", "mac", "bridge",
4191
                                    "nic_mode", "nic_link",
4192
                                    "sda_size", "sdb_size", "vcpus", "tags",
4193
                                    "network_port", "beparams",
4194
                                    r"(disk)\.(size)/([0-9]+)",
4195
                                    r"(disk)\.(sizes)", "disk_usage",
4196
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4197
                                    r"(nic)\.(bridge)/([0-9]+)",
4198
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4199
                                    r"(disk|nic)\.(count)",
4200
                                    "hvparams",
4201
                                    ] + _SIMPLE_FIELDS +
4202
                                  ["hv/%s" % name
4203
                                   for name in constants.HVS_PARAMETERS] +
4204
                                  ["be/%s" % name
4205
                                   for name in constants.BES_PARAMETERS])
4206
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4207

    
4208

    
4209
  def ExpandNames(self):
4210
    _CheckOutputFields(static=self._FIELDS_STATIC,
4211
                       dynamic=self._FIELDS_DYNAMIC,
4212
                       selected=self.op.output_fields)
4213

    
4214
    self.needed_locks = {}
4215
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4216
    self.share_locks[locking.LEVEL_NODE] = 1
4217

    
4218
    if self.op.names:
4219
      self.wanted = _GetWantedInstances(self, self.op.names)
4220
    else:
4221
      self.wanted = locking.ALL_SET
4222

    
4223
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4224
    self.do_locking = self.do_node_query and self.op.use_locking
4225
    if self.do_locking:
4226
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4227
      self.needed_locks[locking.LEVEL_NODE] = []
4228
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4229

    
4230
  def DeclareLocks(self, level):
4231
    if level == locking.LEVEL_NODE and self.do_locking:
4232
      self._LockInstancesNodes()
4233

    
4234
  def CheckPrereq(self):
4235
    """Check prerequisites.
4236

4237
    """
4238
    pass
4239

    
4240
  def Exec(self, feedback_fn):
4241
    """Computes the list of nodes and their attributes.
4242

4243
    """
4244
    all_info = self.cfg.GetAllInstancesInfo()
4245
    if self.wanted == locking.ALL_SET:
4246
      # caller didn't specify instance names, so ordering is not important
4247
      if self.do_locking:
4248
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4249
      else:
4250
        instance_names = all_info.keys()
4251
      instance_names = utils.NiceSort(instance_names)
4252
    else:
4253
      # caller did specify names, so we must keep the ordering
4254
      if self.do_locking:
4255
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4256
      else:
4257
        tgt_set = all_info.keys()
4258
      missing = set(self.wanted).difference(tgt_set)
4259
      if missing:
4260
        raise errors.OpExecError("Some instances were removed before"
4261
                                 " retrieving their data: %s" % missing)
4262
      instance_names = self.wanted
4263

    
4264
    instance_list = [all_info[iname] for iname in instance_names]
4265

    
4266
    # begin data gathering
4267

    
4268
    nodes = frozenset([inst.primary_node for inst in instance_list])
4269
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4270

    
4271
    bad_nodes = []
4272
    off_nodes = []
4273
    if self.do_node_query:
4274
      live_data = {}
4275
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4276
      for name in nodes:
4277
        result = node_data[name]
4278
        if result.offline:
4279
          # offline nodes will be in both lists
4280
          off_nodes.append(name)
4281
        if result.fail_msg:
4282
          bad_nodes.append(name)
4283
        else:
4284
          if result.payload:
4285
            live_data.update(result.payload)
4286
          # else no instance is alive
4287
    else:
4288
      live_data = dict([(name, {}) for name in instance_names])
4289

    
4290
    # end data gathering
4291

    
4292
    HVPREFIX = "hv/"
4293
    BEPREFIX = "be/"
4294
    output = []
4295
    cluster = self.cfg.GetClusterInfo()
4296
    for instance in instance_list:
4297
      iout = []
4298
      i_hv = cluster.FillHV(instance)
4299
      i_be = cluster.FillBE(instance)
4300
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
4301
                                 nic.nicparams) for nic in instance.nics]
4302
      for field in self.op.output_fields:
4303
        st_match = self._FIELDS_STATIC.Matches(field)
4304
        if field in self._SIMPLE_FIELDS:
4305
          val = getattr(instance, field)
4306
        elif field == "pnode":
4307
          val = instance.primary_node
4308
        elif field == "snodes":
4309
          val = list(instance.secondary_nodes)
4310
        elif field == "admin_state":
4311
          val = instance.admin_up
4312
        elif field == "oper_state":
4313
          if instance.primary_node in bad_nodes:
4314
            val = None
4315
          else:
4316
            val = bool(live_data.get(instance.name))
4317
        elif field == "status":
4318
          if instance.primary_node in off_nodes:
4319
            val = "ERROR_nodeoffline"
4320
          elif instance.primary_node in bad_nodes:
4321
            val = "ERROR_nodedown"
4322
          else:
4323
            running = bool(live_data.get(instance.name))
4324
            if running:
4325
              if instance.admin_up:
4326
                val = "running"
4327
              else:
4328
                val = "ERROR_up"
4329
            else:
4330
              if instance.admin_up:
4331
                val = "ERROR_down"
4332
              else:
4333
                val = "ADMIN_down"
4334
        elif field == "oper_ram":
4335
          if instance.primary_node in bad_nodes:
4336
            val = None
4337
          elif instance.name in live_data:
4338
            val = live_data[instance.name].get("memory", "?")
4339
          else:
4340
            val = "-"
4341
        elif field == "vcpus":
4342
          val = i_be[constants.BE_VCPUS]
4343
        elif field == "disk_template":
4344
          val = instance.disk_template
4345
        elif field == "ip":
4346
          if instance.nics:
4347
            val = instance.nics[0].ip
4348
          else:
4349
            val = None
4350
        elif field == "nic_mode":
4351
          if instance.nics:
4352
            val = i_nicp[0][constants.NIC_MODE]
4353
          else:
4354
            val = None
4355
        elif field == "nic_link":
4356
          if instance.nics:
4357
            val = i_nicp[0][constants.NIC_LINK]
4358
          else:
4359
            val = None
4360
        elif field == "bridge":
4361
          if (instance.nics and
4362
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4363
            val = i_nicp[0][constants.NIC_LINK]
4364
          else:
4365
            val = None
4366
        elif field == "mac":
4367
          if instance.nics:
4368
            val = instance.nics[0].mac
4369
          else:
4370
            val = None
4371
        elif field == "sda_size" or field == "sdb_size":
4372
          idx = ord(field[2]) - ord('a')
4373
          try:
4374
            val = instance.FindDisk(idx).size
4375
          except errors.OpPrereqError:
4376
            val = None
4377
        elif field == "disk_usage": # total disk usage per node
4378
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4379
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4380
        elif field == "tags":
4381
          val = list(instance.GetTags())
4382
        elif field == "hvparams":
4383
          val = i_hv
4384
        elif (field.startswith(HVPREFIX) and
4385
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
4386
          val = i_hv.get(field[len(HVPREFIX):], None)
4387
        elif field == "beparams":
4388
          val = i_be
4389
        elif (field.startswith(BEPREFIX) and
4390
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4391
          val = i_be.get(field[len(BEPREFIX):], None)
4392
        elif st_match and st_match.groups():
4393
          # matches a variable list
4394
          st_groups = st_match.groups()
4395
          if st_groups and st_groups[0] == "disk":
4396
            if st_groups[1] == "count":
4397
              val = len(instance.disks)
4398
            elif st_groups[1] == "sizes":
4399
              val = [disk.size for disk in instance.disks]
4400
            elif st_groups[1] == "size":
4401
              try:
4402
                val = instance.FindDisk(st_groups[2]).size
4403
              except errors.OpPrereqError:
4404
                val = None
4405
            else:
4406
              assert False, "Unhandled disk parameter"
4407
          elif st_groups[0] == "nic":
4408
            if st_groups[1] == "count":
4409
              val = len(instance.nics)
4410
            elif st_groups[1] == "macs":
4411
              val = [nic.mac for nic in instance.nics]
4412
            elif st_groups[1] == "ips":
4413
              val = [nic.ip for nic in instance.nics]
4414
            elif st_groups[1] == "modes":
4415
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4416
            elif st_groups[1] == "links":
4417
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4418
            elif st_groups[1] == "bridges":
4419
              val = []
4420
              for nicp in i_nicp:
4421
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4422
                  val.append(nicp[constants.NIC_LINK])
4423
                else:
4424
                  val.append(None)
4425
            else:
4426
              # index-based item
4427
              nic_idx = int(st_groups[2])
4428
              if nic_idx >= len(instance.nics):
4429
                val = None
4430
              else:
4431
                if st_groups[1] == "mac":
4432
                  val = instance.nics[nic_idx].mac
4433
                elif st_groups[1] == "ip":
4434
                  val = instance.nics[nic_idx].ip
4435
                elif st_groups[1] == "mode":
4436
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4437
                elif st_groups[1] == "link":
4438
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4439
                elif st_groups[1] == "bridge":
4440
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4441
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4442
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4443
                  else:
4444
                    val = None
4445
                else:
4446
                  assert False, "Unhandled NIC parameter"
4447
          else:
4448
            assert False, ("Declared but unhandled variable parameter '%s'" %
4449
                           field)
4450
        else:
4451
          assert False, "Declared but unhandled parameter '%s'" % field
4452
        iout.append(val)
4453
      output.append(iout)
4454

    
4455
    return output
4456

    
4457

    
4458
class LUFailoverInstance(LogicalUnit):
4459
  """Failover an instance.
4460

4461
  """
4462
  HPATH = "instance-failover"
4463
  HTYPE = constants.HTYPE_INSTANCE
4464
  _OP_REQP = ["instance_name", "ignore_consistency"]
4465
  REQ_BGL = False
4466

    
4467
  def CheckArguments(self):
4468
    """Check the arguments.
4469

4470
    """
4471
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4472
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4473

    
4474
  def ExpandNames(self):
4475
    self._ExpandAndLockInstance()
4476
    self.needed_locks[locking.LEVEL_NODE] = []
4477
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4478

    
4479
  def DeclareLocks(self, level):
4480
    if level == locking.LEVEL_NODE:
4481
      self._LockInstancesNodes()
4482

    
4483
  def BuildHooksEnv(self):
4484
    """Build hooks env.
4485

4486
    This runs on master, primary and secondary nodes of the instance.
4487

4488
    """
4489
    env = {
4490
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4491
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4492
      }
4493
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4494
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
4495
    return env, nl, nl
4496

    
4497
  def CheckPrereq(self):
4498
    """Check prerequisites.
4499

4500
    This checks that the instance is in the cluster.
4501

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

    
4507
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4508
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4509
      raise errors.OpPrereqError("Instance's disk layout is not"
4510
                                 " network mirrored, cannot failover.",
4511
                                 errors.ECODE_STATE)
4512

    
4513
    secondary_nodes = instance.secondary_nodes
4514
    if not secondary_nodes:
4515
      raise errors.ProgrammerError("no secondary node but using "
4516
                                   "a mirrored disk template")
4517

    
4518
    target_node = secondary_nodes[0]
4519
    _CheckNodeOnline(self, target_node)
4520
    _CheckNodeNotDrained(self, target_node)
4521
    if instance.admin_up:
4522
      # check memory requirements on the secondary node
4523
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4524
                           instance.name, bep[constants.BE_MEMORY],
4525
                           instance.hypervisor)
4526
    else:
4527
      self.LogInfo("Not checking memory on the secondary node as"
4528
                   " instance will not be started")
4529

    
4530
    # check bridge existance
4531
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4532

    
4533
  def Exec(self, feedback_fn):
4534
    """Failover an instance.
4535

4536
    The failover is done by shutting it down on its present node and
4537
    starting it on the secondary.
4538

4539
    """
4540
    instance = self.instance
4541

    
4542
    source_node = instance.primary_node
4543
    target_node = instance.secondary_nodes[0]
4544

    
4545
    if instance.admin_up:
4546
      feedback_fn("* checking disk consistency between source and target")
4547
      for dev in instance.disks:
4548
        # for drbd, these are drbd over lvm
4549
        if not _CheckDiskConsistency(self, dev, target_node, False):
4550
          if not self.op.ignore_consistency:
4551
            raise errors.OpExecError("Disk %s is degraded on target node,"
4552
                                     " aborting failover." % dev.iv_name)
4553
    else:
4554
      feedback_fn("* not checking disk consistency as instance is not running")
4555

    
4556
    feedback_fn("* shutting down instance on source node")
4557
    logging.info("Shutting down instance %s on node %s",
4558
                 instance.name, source_node)
4559

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

    
4574
    feedback_fn("* deactivating the instance's disks on source node")
4575
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
4576
      raise errors.OpExecError("Can't shut down the instance's disks.")
4577

    
4578
    instance.primary_node = target_node
4579
    # distribute new instance config to the other nodes
4580
    self.cfg.Update(instance, feedback_fn)
4581

    
4582
    # Only start the instance if it's marked as up
4583
    if instance.admin_up:
4584
      feedback_fn("* activating the instance's disks on target node")
4585
      logging.info("Starting instance %s on node %s",
4586
                   instance.name, target_node)
4587

    
4588
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4589
                                               ignore_secondaries=True)
4590
      if not disks_ok:
4591
        _ShutdownInstanceDisks(self, instance)
4592
        raise errors.OpExecError("Can't activate the instance's disks")
4593

    
4594
      feedback_fn("* starting the instance on the target node")
4595
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4596
      msg = result.fail_msg
4597
      if msg:
4598
        _ShutdownInstanceDisks(self, instance)
4599
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4600
                                 (instance.name, target_node, msg))
4601

    
4602

    
4603
class LUMigrateInstance(LogicalUnit):
4604
  """Migrate an instance.
4605

4606
  This is migration without shutting down, compared to the failover,
4607
  which is done with shutdown.
4608

4609
  """
4610
  HPATH = "instance-migrate"
4611
  HTYPE = constants.HTYPE_INSTANCE
4612
  _OP_REQP = ["instance_name", "live", "cleanup"]
4613

    
4614
  REQ_BGL = False
4615

    
4616
  def ExpandNames(self):
4617
    self._ExpandAndLockInstance()
4618

    
4619
    self.needed_locks[locking.LEVEL_NODE] = []
4620
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4621

    
4622
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
4623
                                       self.op.live, self.op.cleanup)
4624
    self.tasklets = [self._migrater]
4625

    
4626
  def DeclareLocks(self, level):
4627
    if level == locking.LEVEL_NODE:
4628
      self._LockInstancesNodes()
4629

    
4630
  def BuildHooksEnv(self):
4631
    """Build hooks env.
4632

4633
    This runs on master, primary and secondary nodes of the instance.
4634

4635
    """
4636
    instance = self._migrater.instance
4637
    env = _BuildInstanceHookEnvByObject(self, instance)
4638
    env["MIGRATE_LIVE"] = self.op.live
4639
    env["MIGRATE_CLEANUP"] = self.op.cleanup
4640
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4641
    return env, nl, nl
4642

    
4643

    
4644
class LUMoveInstance(LogicalUnit):
4645
  """Move an instance by data-copying.
4646

4647
  """
4648
  HPATH = "instance-move"
4649
  HTYPE = constants.HTYPE_INSTANCE
4650
  _OP_REQP = ["instance_name", "target_node"]
4651
  REQ_BGL = False
4652

    
4653
  def CheckArguments(self):
4654
    """Check the arguments.
4655

4656
    """
4657
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4658
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4659

    
4660
  def ExpandNames(self):
4661
    self._ExpandAndLockInstance()
4662
    target_node = self.cfg.ExpandNodeName(self.op.target_node)
4663
    if target_node is None:
4664
      raise errors.OpPrereqError("Node '%s' not known" %
4665
                                  self.op.target_node, errors.ECODE_NOENT)
4666
    self.op.target_node = target_node
4667
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
4668
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4669

    
4670
  def DeclareLocks(self, level):
4671
    if level == locking.LEVEL_NODE:
4672
      self._LockInstancesNodes(primary_only=True)
4673

    
4674
  def BuildHooksEnv(self):
4675
    """Build hooks env.
4676

4677
    This runs on master, primary and secondary nodes of the instance.
4678

4679
    """
4680
    env = {
4681
      "TARGET_NODE": self.op.target_node,
4682
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4683
      }
4684
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4685
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
4686
                                       self.op.target_node]
4687
    return env, nl, nl
4688

    
4689
  def CheckPrereq(self):
4690
    """Check prerequisites.
4691

4692
    This checks that the instance is in the cluster.
4693

4694
    """
4695
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4696
    assert self.instance is not None, \
4697
      "Cannot retrieve locked instance %s" % self.op.instance_name
4698

    
4699
    node = self.cfg.GetNodeInfo(self.op.target_node)
4700
    assert node is not None, \
4701
      "Cannot retrieve locked node %s" % self.op.target_node
4702

    
4703
    self.target_node = target_node = node.name
4704

    
4705
    if target_node == instance.primary_node:
4706
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
4707
                                 (instance.name, target_node),
4708
                                 errors.ECODE_STATE)
4709

    
4710
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4711

    
4712
    for idx, dsk in enumerate(instance.disks):
4713
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
4714
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
4715
                                   " cannot copy", errors.ECODE_STATE)
4716

    
4717
    _CheckNodeOnline(self, target_node)
4718
    _CheckNodeNotDrained(self, target_node)
4719

    
4720
    if instance.admin_up:
4721
      # check memory requirements on the secondary node
4722
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4723
                           instance.name, bep[constants.BE_MEMORY],
4724
                           instance.hypervisor)
4725
    else:
4726
      self.LogInfo("Not checking memory on the secondary node as"
4727
                   " instance will not be started")
4728

    
4729
    # check bridge existance
4730
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4731

    
4732
  def Exec(self, feedback_fn):
4733
    """Move an instance.
4734

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

4738
    """
4739
    instance = self.instance
4740

    
4741
    source_node = instance.primary_node
4742
    target_node = self.target_node
4743

    
4744
    self.LogInfo("Shutting down instance %s on source node %s",
4745
                 instance.name, source_node)
4746

    
4747
    result = self.rpc.call_instance_shutdown(source_node, instance,
4748
                                             self.shutdown_timeout)
4749
    msg = result.fail_msg
4750
    if msg:
4751
      if self.op.ignore_consistency:
4752
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4753
                             " Proceeding anyway. Please make sure node"
4754
                             " %s is down. Error details: %s",
4755
                             instance.name, source_node, source_node, msg)
4756
      else:
4757
        raise errors.OpExecError("Could not shutdown instance %s on"
4758
                                 " node %s: %s" %
4759
                                 (instance.name, source_node, msg))
4760

    
4761
    # create the target disks
4762
    try:
4763
      _CreateDisks(self, instance, target_node=target_node)
4764
    except errors.OpExecError:
4765
      self.LogWarning("Device creation failed, reverting...")
4766
      try:
4767
        _RemoveDisks(self, instance, target_node=target_node)
4768
      finally:
4769
        self.cfg.ReleaseDRBDMinors(instance.name)
4770
        raise
4771

    
4772
    cluster_name = self.cfg.GetClusterInfo().cluster_name
4773

    
4774
    errs = []
4775
    # activate, get path, copy the data over
4776
    for idx, disk in enumerate(instance.disks):
4777
      self.LogInfo("Copying data for disk %d", idx)
4778
      result = self.rpc.call_blockdev_assemble(target_node, disk,
4779
                                               instance.name, True)
4780
      if result.fail_msg:
4781
        self.LogWarning("Can't assemble newly created disk %d: %s",
4782
                        idx, result.fail_msg)
4783
        errs.append(result.fail_msg)
4784
        break
4785
      dev_path = result.payload
4786
      result = self.rpc.call_blockdev_export(source_node, disk,
4787
                                             target_node, dev_path,
4788
                                             cluster_name)
4789
      if result.fail_msg:
4790
        self.LogWarning("Can't copy data over for disk %d: %s",
4791
                        idx, result.fail_msg)
4792
        errs.append(result.fail_msg)
4793
        break
4794

    
4795
    if errs:
4796
      self.LogWarning("Some disks failed to copy, aborting")
4797
      try:
4798
        _RemoveDisks(self, instance, target_node=target_node)
4799
      finally:
4800
        self.cfg.ReleaseDRBDMinors(instance.name)
4801
        raise errors.OpExecError("Errors during disk copy: %s" %
4802
                                 (",".join(errs),))
4803

    
4804
    instance.primary_node = target_node
4805
    self.cfg.Update(instance, feedback_fn)
4806

    
4807
    self.LogInfo("Removing the disks on the original node")
4808
    _RemoveDisks(self, instance, target_node=source_node)
4809

    
4810
    # Only start the instance if it's marked as up
4811
    if instance.admin_up:
4812
      self.LogInfo("Starting instance %s on node %s",
4813
                   instance.name, target_node)
4814

    
4815
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4816
                                           ignore_secondaries=True)
4817
      if not disks_ok:
4818
        _ShutdownInstanceDisks(self, instance)
4819
        raise errors.OpExecError("Can't activate the instance's disks")
4820

    
4821
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4822
      msg = result.fail_msg
4823
      if msg:
4824
        _ShutdownInstanceDisks(self, instance)
4825
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4826
                                 (instance.name, target_node, msg))
4827

    
4828

    
4829
class LUMigrateNode(LogicalUnit):
4830
  """Migrate all instances from a node.
4831

4832
  """
4833
  HPATH = "node-migrate"
4834
  HTYPE = constants.HTYPE_NODE
4835
  _OP_REQP = ["node_name", "live"]
4836
  REQ_BGL = False
4837

    
4838
  def ExpandNames(self):
4839
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
4840
    if self.op.node_name is None:
4841
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name,
4842
                                 errors.ECODE_NOENT)
4843

    
4844
    self.needed_locks = {
4845
      locking.LEVEL_NODE: [self.op.node_name],
4846
      }
4847

    
4848
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4849

    
4850
    # Create tasklets for migrating instances for all instances on this node
4851
    names = []
4852
    tasklets = []
4853

    
4854
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
4855
      logging.debug("Migrating instance %s", inst.name)
4856
      names.append(inst.name)
4857

    
4858
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
4859

    
4860
    self.tasklets = tasklets
4861

    
4862
    # Declare instance locks
4863
    self.needed_locks[locking.LEVEL_INSTANCE] = names
4864

    
4865
  def DeclareLocks(self, level):
4866
    if level == locking.LEVEL_NODE:
4867
      self._LockInstancesNodes()
4868

    
4869
  def BuildHooksEnv(self):
4870
    """Build hooks env.
4871

4872
    This runs on the master, the primary and all the secondaries.
4873

4874
    """
4875
    env = {
4876
      "NODE_NAME": self.op.node_name,
4877
      }
4878

    
4879
    nl = [self.cfg.GetMasterNode()]
4880

    
4881
    return (env, nl, nl)
4882

    
4883

    
4884
class TLMigrateInstance(Tasklet):
4885
  def __init__(self, lu, instance_name, live, cleanup):
4886
    """Initializes this class.
4887

4888
    """
4889
    Tasklet.__init__(self, lu)
4890

    
4891
    # Parameters
4892
    self.instance_name = instance_name
4893
    self.live = live
4894
    self.cleanup = cleanup
4895

    
4896
  def CheckPrereq(self):
4897
    """Check prerequisites.
4898

4899
    This checks that the instance is in the cluster.
4900

4901
    """
4902
    instance = self.cfg.GetInstanceInfo(
4903
      self.cfg.ExpandInstanceName(self.instance_name))
4904
    if instance is None:
4905
      raise errors.OpPrereqError("Instance '%s' not known" %
4906
                                 self.instance_name, errors.ECODE_NOENT)
4907

    
4908
    if instance.disk_template != constants.DT_DRBD8:
4909
      raise errors.OpPrereqError("Instance's disk layout is not"
4910
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
4911

    
4912
    secondary_nodes = instance.secondary_nodes
4913
    if not secondary_nodes:
4914
      raise errors.ConfigurationError("No secondary node but using"
4915
                                      " drbd8 disk template")
4916

    
4917
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
4918

    
4919
    target_node = secondary_nodes[0]
4920
    # check memory requirements on the secondary node
4921
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
4922
                         instance.name, i_be[constants.BE_MEMORY],
4923
                         instance.hypervisor)
4924

    
4925
    # check bridge existance
4926
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4927

    
4928
    if not self.cleanup:
4929
      _CheckNodeNotDrained(self, target_node)
4930
      result = self.rpc.call_instance_migratable(instance.primary_node,
4931
                                                 instance)
4932
      result.Raise("Can't migrate, please use failover",
4933
                   prereq=True, ecode=errors.ECODE_STATE)
4934

    
4935
    self.instance = instance
4936

    
4937
  def _WaitUntilSync(self):
4938
    """Poll with custom rpc for disk sync.
4939

4940
    This uses our own step-based rpc call.
4941

4942
    """
4943
    self.feedback_fn("* wait until resync is done")
4944
    all_done = False
4945
    while not all_done:
4946
      all_done = True
4947
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
4948
                                            self.nodes_ip,
4949
                                            self.instance.disks)
4950
      min_percent = 100
4951
      for node, nres in result.items():
4952
        nres.Raise("Cannot resync disks on node %s" % node)
4953
        node_done, node_percent = nres.payload
4954
        all_done = all_done and node_done
4955
        if node_percent is not None:
4956
          min_percent = min(min_percent, node_percent)
4957
      if not all_done:
4958
        if min_percent < 100:
4959
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
4960
        time.sleep(2)
4961

    
4962
  def _EnsureSecondary(self, node):
4963
    """Demote a node to secondary.
4964

4965
    """
4966
    self.feedback_fn("* switching node %s to secondary mode" % node)
4967

    
4968
    for dev in self.instance.disks:
4969
      self.cfg.SetDiskID(dev, node)
4970

    
4971
    result = self.rpc.call_blockdev_close(node, self.instance.name,
4972
                                          self.instance.disks)
4973
    result.Raise("Cannot change disk to secondary on node %s" % node)
4974

    
4975
  def _GoStandalone(self):
4976
    """Disconnect from the network.
4977

4978
    """
4979
    self.feedback_fn("* changing into standalone mode")
4980
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
4981
                                               self.instance.disks)
4982
    for node, nres in result.items():
4983
      nres.Raise("Cannot disconnect disks node %s" % node)
4984

    
4985
  def _GoReconnect(self, multimaster):
4986
    """Reconnect to the network.
4987

4988
    """
4989
    if multimaster:
4990
      msg = "dual-master"
4991
    else:
4992
      msg = "single-master"
4993
    self.feedback_fn("* changing disks into %s mode" % msg)
4994
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
4995
                                           self.instance.disks,
4996
                                           self.instance.name, multimaster)
4997
    for node, nres in result.items():
4998
      nres.Raise("Cannot change disks config on node %s" % node)
4999

    
5000
  def _ExecCleanup(self):
5001
    """Try to cleanup after a failed migration.
5002

5003
    The cleanup is done by:
5004
      - check that the instance is running only on one node
5005
        (and update the config if needed)
5006
      - change disks on its secondary node to secondary
5007
      - wait until disks are fully synchronized
5008
      - disconnect from the network
5009
      - change disks into single-master mode
5010
      - wait again until disks are fully synchronized
5011

5012
    """
5013
    instance = self.instance
5014
    target_node = self.target_node
5015
    source_node = self.source_node
5016

    
5017
    # check running on only one node
5018
    self.feedback_fn("* checking where the instance actually runs"
5019
                     " (if this hangs, the hypervisor might be in"
5020
                     " a bad state)")
5021
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5022
    for node, result in ins_l.items():
5023
      result.Raise("Can't contact node %s" % node)
5024

    
5025
    runningon_source = instance.name in ins_l[source_node].payload
5026
    runningon_target = instance.name in ins_l[target_node].payload
5027

    
5028
    if runningon_source and runningon_target:
5029
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5030
                               " or the hypervisor is confused. You will have"
5031
                               " to ensure manually that it runs only on one"
5032
                               " and restart this operation.")
5033

    
5034
    if not (runningon_source or runningon_target):
5035
      raise errors.OpExecError("Instance does not seem to be running at all."
5036
                               " In this case, it's safer to repair by"
5037
                               " running 'gnt-instance stop' to ensure disk"
5038
                               " shutdown, and then restarting it.")
5039

    
5040
    if runningon_target:
5041
      # the migration has actually succeeded, we need to update the config
5042
      self.feedback_fn("* instance running on secondary node (%s),"
5043
                       " updating config" % target_node)
5044
      instance.primary_node = target_node
5045
      self.cfg.Update(instance, self.feedback_fn)
5046
      demoted_node = source_node
5047
    else:
5048
      self.feedback_fn("* instance confirmed to be running on its"
5049
                       " primary node (%s)" % source_node)
5050
      demoted_node = target_node
5051

    
5052
    self._EnsureSecondary(demoted_node)
5053
    try:
5054
      self._WaitUntilSync()
5055
    except errors.OpExecError:
5056
      # we ignore here errors, since if the device is standalone, it
5057
      # won't be able to sync
5058
      pass
5059
    self._GoStandalone()
5060
    self._GoReconnect(False)
5061
    self._WaitUntilSync()
5062

    
5063
    self.feedback_fn("* done")
5064

    
5065
  def _RevertDiskStatus(self):
5066
    """Try to revert the disk status after a failed migration.
5067

5068
    """
5069
    target_node = self.target_node
5070
    try:
5071
      self._EnsureSecondary(target_node)
5072
      self._GoStandalone()
5073
      self._GoReconnect(False)
5074
      self._WaitUntilSync()
5075
    except errors.OpExecError, err:
5076
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5077
                         " drives: error '%s'\n"
5078
                         "Please look and recover the instance status" %
5079
                         str(err))
5080

    
5081
  def _AbortMigration(self):
5082
    """Call the hypervisor code to abort a started migration.
5083

5084
    """
5085
    instance = self.instance
5086
    target_node = self.target_node
5087
    migration_info = self.migration_info
5088

    
5089
    abort_result = self.rpc.call_finalize_migration(target_node,
5090
                                                    instance,
5091
                                                    migration_info,
5092
                                                    False)
5093
    abort_msg = abort_result.fail_msg
5094
    if abort_msg:
5095
      logging.error("Aborting migration failed on target node %s: %s",
5096
                    target_node, abort_msg)
5097
      # Don't raise an exception here, as we stil have to try to revert the
5098
      # disk status, even if this step failed.
5099

    
5100
  def _ExecMigration(self):
5101
    """Migrate an instance.
5102

5103
    The migrate is done by:
5104
      - change the disks into dual-master mode
5105
      - wait until disks are fully synchronized again
5106
      - migrate the instance
5107
      - change disks on the new secondary node (the old primary) to secondary
5108
      - wait until disks are fully synchronized
5109
      - change disks into single-master mode
5110

5111
    """
5112
    instance = self.instance
5113
    target_node = self.target_node
5114
    source_node = self.source_node
5115

    
5116
    self.feedback_fn("* checking disk consistency between source and target")
5117
    for dev in instance.disks:
5118
      if not _CheckDiskConsistency(self, dev, target_node, False):
5119
        raise errors.OpExecError("Disk %s is degraded or not fully"
5120
                                 " synchronized on target node,"
5121
                                 " aborting migrate." % dev.iv_name)
5122

    
5123
    # First get the migration information from the remote node
5124
    result = self.rpc.call_migration_info(source_node, instance)
5125
    msg = result.fail_msg
5126
    if msg:
5127
      log_err = ("Failed fetching source migration information from %s: %s" %
5128
                 (source_node, msg))
5129
      logging.error(log_err)
5130
      raise errors.OpExecError(log_err)
5131

    
5132
    self.migration_info = migration_info = result.payload
5133

    
5134
    # Then switch the disks to master/master mode
5135
    self._EnsureSecondary(target_node)
5136
    self._GoStandalone()
5137
    self._GoReconnect(True)
5138
    self._WaitUntilSync()
5139

    
5140
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5141
    result = self.rpc.call_accept_instance(target_node,
5142
                                           instance,
5143
                                           migration_info,
5144
                                           self.nodes_ip[target_node])
5145

    
5146
    msg = result.fail_msg
5147
    if msg:
5148
      logging.error("Instance pre-migration failed, trying to revert"
5149
                    " disk status: %s", msg)
5150
      self._AbortMigration()
5151
      self._RevertDiskStatus()
5152
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5153
                               (instance.name, msg))
5154

    
5155
    self.feedback_fn("* migrating instance to %s" % target_node)
5156
    time.sleep(10)
5157
    result = self.rpc.call_instance_migrate(source_node, instance,
5158
                                            self.nodes_ip[target_node],
5159
                                            self.live)
5160
    msg = result.fail_msg
5161
    if msg:
5162
      logging.error("Instance migration failed, trying to revert"
5163
                    " disk status: %s", msg)
5164
      self._AbortMigration()
5165
      self._RevertDiskStatus()
5166
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5167
                               (instance.name, msg))
5168
    time.sleep(10)
5169

    
5170
    instance.primary_node = target_node
5171
    # distribute new instance config to the other nodes
5172
    self.cfg.Update(instance, self.feedback_fn)
5173

    
5174
    result = self.rpc.call_finalize_migration(target_node,
5175
                                              instance,
5176
                                              migration_info,
5177
                                              True)
5178
    msg = result.fail_msg
5179
    if msg:
5180
      logging.error("Instance migration succeeded, but finalization failed:"
5181
                    " %s", msg)
5182
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5183
                               msg)
5184

    
5185
    self._EnsureSecondary(source_node)
5186
    self._WaitUntilSync()
5187
    self._GoStandalone()
5188
    self._GoReconnect(False)
5189
    self._WaitUntilSync()
5190

    
5191
    self.feedback_fn("* done")
5192

    
5193
  def Exec(self, feedback_fn):
5194
    """Perform the migration.
5195

5196
    """
5197
    feedback_fn("Migrating instance %s" % self.instance.name)
5198

    
5199
    self.feedback_fn = feedback_fn
5200

    
5201
    self.source_node = self.instance.primary_node
5202
    self.target_node = self.instance.secondary_nodes[0]
5203
    self.all_nodes = [self.source_node, self.target_node]
5204
    self.nodes_ip = {
5205
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5206
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5207
      }
5208

    
5209
    if self.cleanup:
5210
      return self._ExecCleanup()
5211
    else:
5212
      return self._ExecMigration()
5213

    
5214

    
5215
def _CreateBlockDev(lu, node, instance, device, force_create,
5216
                    info, force_open):
5217
  """Create a tree of block devices on a given node.
5218

5219
  If this device type has to be created on secondaries, create it and
5220
  all its children.
5221

5222
  If not, just recurse to children keeping the same 'force' value.
5223

5224
  @param lu: the lu on whose behalf we execute
5225
  @param node: the node on which to create the device
5226
  @type instance: L{objects.Instance}
5227
  @param instance: the instance which owns the device
5228
  @type device: L{objects.Disk}
5229
  @param device: the device to create
5230
  @type force_create: boolean
5231
  @param force_create: whether to force creation of this device; this
5232
      will be change to True whenever we find a device which has
5233
      CreateOnSecondary() attribute
5234
  @param info: the extra 'metadata' we should attach to the device
5235
      (this will be represented as a LVM tag)
5236
  @type force_open: boolean
5237
  @param force_open: this parameter will be passes to the
5238
      L{backend.BlockdevCreate} function where it specifies
5239
      whether we run on primary or not, and it affects both
5240
      the child assembly and the device own Open() execution
5241

5242
  """
5243
  if device.CreateOnSecondary():
5244
    force_create = True
5245

    
5246
  if device.children:
5247
    for child in device.children:
5248
      _CreateBlockDev(lu, node, instance, child, force_create,
5249
                      info, force_open)
5250

    
5251
  if not force_create:
5252
    return
5253

    
5254
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5255

    
5256

    
5257
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5258
  """Create a single block device on a given node.
5259

5260
  This will not recurse over children of the device, so they must be
5261
  created in advance.
5262

5263
  @param lu: the lu on whose behalf we execute
5264
  @param node: the node on which to create the device
5265
  @type instance: L{objects.Instance}
5266
  @param instance: the instance which owns the device
5267
  @type device: L{objects.Disk}
5268
  @param device: the device to create
5269
  @param info: the extra 'metadata' we should attach to the device
5270
      (this will be represented as a LVM tag)
5271
  @type force_open: boolean
5272
  @param force_open: this parameter will be passes to the
5273
      L{backend.BlockdevCreate} function where it specifies
5274
      whether we run on primary or not, and it affects both
5275
      the child assembly and the device own Open() execution
5276

5277
  """
5278
  lu.cfg.SetDiskID(device, node)
5279
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5280
                                       instance.name, force_open, info)
5281
  result.Raise("Can't create block device %s on"
5282
               " node %s for instance %s" % (device, node, instance.name))
5283
  if device.physical_id is None:
5284
    device.physical_id = result.payload
5285

    
5286

    
5287
def _GenerateUniqueNames(lu, exts):
5288
  """Generate a suitable LV name.
5289

5290
  This will generate a logical volume name for the given instance.
5291

5292
  """
5293
  results = []
5294
  for val in exts:
5295
    new_id = lu.cfg.GenerateUniqueID()
5296
    results.append("%s%s" % (new_id, val))
5297
  return results
5298

    
5299

    
5300
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5301
                         p_minor, s_minor):
5302
  """Generate a drbd8 device complete with its children.
5303

5304
  """
5305
  port = lu.cfg.AllocatePort()
5306
  vgname = lu.cfg.GetVGName()
5307
  shared_secret = lu.cfg.GenerateDRBDSecret()
5308
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5309
                          logical_id=(vgname, names[0]))
5310
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5311
                          logical_id=(vgname, names[1]))
5312
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5313
                          logical_id=(primary, secondary, port,
5314
                                      p_minor, s_minor,
5315
                                      shared_secret),
5316
                          children=[dev_data, dev_meta],
5317
                          iv_name=iv_name)
5318
  return drbd_dev
5319

    
5320

    
5321
def _GenerateDiskTemplate(lu, template_name,
5322
                          instance_name, primary_node,
5323
                          secondary_nodes, disk_info,
5324
                          file_storage_dir, file_driver,
5325
                          base_index):
5326
  """Generate the entire disk layout for a given template type.
5327

5328
  """
5329
  #TODO: compute space requirements
5330

    
5331
  vgname = lu.cfg.GetVGName()
5332
  disk_count = len(disk_info)
5333
  disks = []
5334
  if template_name == constants.DT_DISKLESS:
5335
    pass
5336
  elif template_name == constants.DT_PLAIN:
5337
    if len(secondary_nodes) != 0:
5338
      raise errors.ProgrammerError("Wrong template configuration")
5339

    
5340
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5341
                                      for i in range(disk_count)])
5342
    for idx, disk in enumerate(disk_info):
5343
      disk_index = idx + base_index
5344
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5345
                              logical_id=(vgname, names[idx]),
5346
                              iv_name="disk/%d" % disk_index,
5347
                              mode=disk["mode"])
5348
      disks.append(disk_dev)
5349
  elif template_name == constants.DT_DRBD8:
5350
    if len(secondary_nodes) != 1:
5351
      raise errors.ProgrammerError("Wrong template configuration")
5352
    remote_node = secondary_nodes[0]
5353
    minors = lu.cfg.AllocateDRBDMinor(
5354
      [primary_node, remote_node] * len(disk_info), instance_name)
5355

    
5356
    names = []
5357
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5358
                                               for i in range(disk_count)]):
5359
      names.append(lv_prefix + "_data")
5360
      names.append(lv_prefix + "_meta")
5361
    for idx, disk in enumerate(disk_info):
5362
      disk_index = idx + base_index
5363
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5364
                                      disk["size"], names[idx*2:idx*2+2],
5365
                                      "disk/%d" % disk_index,
5366
                                      minors[idx*2], minors[idx*2+1])
5367
      disk_dev.mode = disk["mode"]
5368
      disks.append(disk_dev)
5369
  elif template_name == constants.DT_FILE:
5370
    if len(secondary_nodes) != 0:
5371
      raise errors.ProgrammerError("Wrong template configuration")
5372

    
5373
    for idx, disk in enumerate(disk_info):
5374
      disk_index = idx + base_index
5375
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5376
                              iv_name="disk/%d" % disk_index,
5377
                              logical_id=(file_driver,
5378
                                          "%s/disk%d" % (file_storage_dir,
5379
                                                         disk_index)),
5380
                              mode=disk["mode"])
5381
      disks.append(disk_dev)
5382
  else:
5383
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5384
  return disks
5385

    
5386

    
5387
def _GetInstanceInfoText(instance):
5388
  """Compute that text that should be added to the disk's metadata.
5389

5390
  """
5391
  return "originstname+%s" % instance.name
5392

    
5393

    
5394
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5395
  """Create all disks for an instance.
5396

5397
  This abstracts away some work from AddInstance.
5398

5399
  @type lu: L{LogicalUnit}
5400
  @param lu: the logical unit on whose behalf we execute
5401
  @type instance: L{objects.Instance}
5402
  @param instance: the instance whose disks we should create
5403
  @type to_skip: list
5404
  @param to_skip: list of indices to skip
5405
  @type target_node: string
5406
  @param target_node: if passed, overrides the target node for creation
5407
  @rtype: boolean
5408
  @return: the success of the creation
5409

5410
  """
5411
  info = _GetInstanceInfoText(instance)
5412
  if target_node is None:
5413
    pnode = instance.primary_node
5414
    all_nodes = instance.all_nodes
5415
  else:
5416
    pnode = target_node
5417
    all_nodes = [pnode]
5418

    
5419
  if instance.disk_template == constants.DT_FILE:
5420
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5421
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5422

    
5423
    result.Raise("Failed to create directory '%s' on"
5424
                 " node %s" % (file_storage_dir, pnode))
5425

    
5426
  # Note: this needs to be kept in sync with adding of disks in
5427
  # LUSetInstanceParams
5428
  for idx, device in enumerate(instance.disks):
5429
    if to_skip and idx in to_skip:
5430
      continue
5431
    logging.info("Creating volume %s for instance %s",
5432
                 device.iv_name, instance.name)
5433
    #HARDCODE
5434
    for node in all_nodes:
5435
      f_create = node == pnode
5436
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5437

    
5438

    
5439
def _RemoveDisks(lu, instance, target_node=None):
5440
  """Remove all disks for an instance.
5441

5442
  This abstracts away some work from `AddInstance()` and
5443
  `RemoveInstance()`. Note that in case some of the devices couldn't
5444
  be removed, the removal will continue with the other ones (compare
5445
  with `_CreateDisks()`).
5446

5447
  @type lu: L{LogicalUnit}
5448
  @param lu: the logical unit on whose behalf we execute
5449
  @type instance: L{objects.Instance}
5450
  @param instance: the instance whose disks we should remove
5451
  @type target_node: string
5452
  @param target_node: used to override the node on which to remove the disks
5453
  @rtype: boolean
5454
  @return: the success of the removal
5455

5456
  """
5457
  logging.info("Removing block devices for instance %s", instance.name)
5458

    
5459
  all_result = True
5460
  for device in instance.disks:
5461
    if target_node:
5462
      edata = [(target_node, device)]
5463
    else:
5464
      edata = device.ComputeNodeTree(instance.primary_node)
5465
    for node, disk in edata:
5466
      lu.cfg.SetDiskID(disk, node)
5467
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5468
      if msg:
5469
        lu.LogWarning("Could not remove block device %s on node %s,"
5470
                      " continuing anyway: %s", device.iv_name, node, msg)
5471
        all_result = False
5472

    
5473
  if instance.disk_template == constants.DT_FILE:
5474
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5475
    if target_node:
5476
      tgt = target_node
5477
    else:
5478
      tgt = instance.primary_node
5479
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5480
    if result.fail_msg:
5481
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5482
                    file_storage_dir, instance.primary_node, result.fail_msg)
5483
      all_result = False
5484

    
5485
  return all_result
5486

    
5487

    
5488
def _ComputeDiskSize(disk_template, disks):
5489
  """Compute disk size requirements in the volume group
5490

5491
  """
5492
  # Required free disk space as a function of disk and swap space
5493
  req_size_dict = {
5494
    constants.DT_DISKLESS: None,
5495
    constants.DT_PLAIN: sum(d["size"] for d in disks),
5496
    # 128 MB are added for drbd metadata for each disk
5497
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
5498
    constants.DT_FILE: None,
5499
  }
5500

    
5501
  if disk_template not in req_size_dict:
5502
    raise errors.ProgrammerError("Disk template '%s' size requirement"
5503
                                 " is unknown" %  disk_template)
5504

    
5505
  return req_size_dict[disk_template]
5506

    
5507

    
5508
def _CheckHVParams(lu, nodenames, hvname, hvparams):
5509
  """Hypervisor parameter validation.
5510

5511
  This function abstract the hypervisor parameter validation to be
5512
  used in both instance create and instance modify.
5513

5514
  @type lu: L{LogicalUnit}
5515
  @param lu: the logical unit for which we check
5516
  @type nodenames: list
5517
  @param nodenames: the list of nodes on which we should check
5518
  @type hvname: string
5519
  @param hvname: the name of the hypervisor we should use
5520
  @type hvparams: dict
5521
  @param hvparams: the parameters which we need to check
5522
  @raise errors.OpPrereqError: if the parameters are not valid
5523

5524
  """
5525
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
5526
                                                  hvname,
5527
                                                  hvparams)
5528
  for node in nodenames:
5529
    info = hvinfo[node]
5530
    if info.offline:
5531
      continue
5532
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
5533

    
5534

    
5535
class LUCreateInstance(LogicalUnit):
5536
  """Create an instance.
5537

5538
  """
5539
  HPATH = "instance-add"
5540
  HTYPE = constants.HTYPE_INSTANCE
5541
  _OP_REQP = ["instance_name", "disks", "disk_template",
5542
              "mode", "start",
5543
              "wait_for_sync", "ip_check", "nics",
5544
              "hvparams", "beparams"]
5545
  REQ_BGL = False
5546

    
5547
  def _ExpandNode(self, node):
5548
    """Expands and checks one node name.
5549

5550
    """
5551
    node_full = self.cfg.ExpandNodeName(node)
5552
    if node_full is None:
5553
      raise errors.OpPrereqError("Unknown node %s" % node, errors.ECODE_NOENT)
5554
    return node_full
5555

    
5556
  def ExpandNames(self):
5557
    """ExpandNames for CreateInstance.
5558

5559
    Figure out the right locks for instance creation.
5560

5561
    """
5562
    self.needed_locks = {}
5563

    
5564
    # set optional parameters to none if they don't exist
5565
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
5566
      if not hasattr(self.op, attr):
5567
        setattr(self.op, attr, None)
5568

    
5569
    # cheap checks, mostly valid constants given
5570

    
5571
    # verify creation mode
5572
    if self.op.mode not in (constants.INSTANCE_CREATE,
5573
                            constants.INSTANCE_IMPORT):
5574
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
5575
                                 self.op.mode, errors.ECODE_INVAL)
5576

    
5577
    # disk template and mirror node verification
5578
    if self.op.disk_template not in constants.DISK_TEMPLATES:
5579
      raise errors.OpPrereqError("Invalid disk template name",
5580
                                 errors.ECODE_INVAL)
5581

    
5582
    if self.op.hypervisor is None:
5583
      self.op.hypervisor = self.cfg.GetHypervisorType()
5584

    
5585
    cluster = self.cfg.GetClusterInfo()
5586
    enabled_hvs = cluster.enabled_hypervisors
5587
    if self.op.hypervisor not in enabled_hvs:
5588
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
5589
                                 " cluster (%s)" % (self.op.hypervisor,
5590
                                  ",".join(enabled_hvs)),
5591
                                 errors.ECODE_STATE)
5592

    
5593
    # check hypervisor parameter syntax (locally)
5594
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5595
    filled_hvp = objects.FillDict(cluster.hvparams[self.op.hypervisor],
5596
                                  self.op.hvparams)
5597
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
5598
    hv_type.CheckParameterSyntax(filled_hvp)
5599
    self.hv_full = filled_hvp
5600

    
5601
    # fill and remember the beparams dict
5602
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5603
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
5604
                                    self.op.beparams)
5605

    
5606
    #### instance parameters check
5607

    
5608
    # instance name verification
5609
    hostname1 = utils.GetHostInfo(self.op.instance_name)
5610
    self.op.instance_name = instance_name = hostname1.name
5611

    
5612
    # this is just a preventive check, but someone might still add this
5613
    # instance in the meantime, and creation will fail at lock-add time
5614
    if instance_name in self.cfg.GetInstanceList():
5615
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5616
                                 instance_name, errors.ECODE_EXISTS)
5617

    
5618
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
5619

    
5620
    # NIC buildup
5621
    self.nics = []
5622
    for idx, nic in enumerate(self.op.nics):
5623
      nic_mode_req = nic.get("mode", None)
5624
      nic_mode = nic_mode_req
5625
      if nic_mode is None:
5626
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
5627

    
5628
      # in routed mode, for the first nic, the default ip is 'auto'
5629
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
5630
        default_ip_mode = constants.VALUE_AUTO
5631
      else:
5632
        default_ip_mode = constants.VALUE_NONE
5633

    
5634
      # ip validity checks
5635
      ip = nic.get("ip", default_ip_mode)
5636
      if ip is None or ip.lower() == constants.VALUE_NONE:
5637
        nic_ip = None
5638
      elif ip.lower() == constants.VALUE_AUTO:
5639
        nic_ip = hostname1.ip
5640
      else:
5641
        if not utils.IsValidIP(ip):
5642
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
5643
                                     " like a valid IP" % ip,
5644
                                     errors.ECODE_INVAL)
5645
        nic_ip = ip
5646

    
5647
      # TODO: check the ip for uniqueness !!
5648
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
5649
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
5650
                                   errors.ECODE_INVAL)
5651

    
5652
      # MAC address verification
5653
      mac = nic.get("mac", constants.VALUE_AUTO)
5654
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5655
        if not utils.IsValidMac(mac.lower()):
5656
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
5657
                                     mac, errors.ECODE_INVAL)
5658
        else:
5659
          # or validate/reserve the current one
5660
          if self.cfg.IsMacInUse(mac):
5661
            raise errors.OpPrereqError("MAC address %s already in use"
5662
                                       " in cluster" % mac,
5663
                                       errors.ECODE_NOTUNIQUE)
5664

    
5665
      # bridge verification
5666
      bridge = nic.get("bridge", None)
5667
      link = nic.get("link", None)
5668
      if bridge and link:
5669
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
5670
                                   " at the same time", errors.ECODE_INVAL)
5671
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
5672
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
5673
                                   errors.ECODE_INVAL)
5674
      elif bridge:
5675
        link = bridge
5676

    
5677
      nicparams = {}
5678
      if nic_mode_req:
5679
        nicparams[constants.NIC_MODE] = nic_mode_req
5680
      if link:
5681
        nicparams[constants.NIC_LINK] = link
5682

    
5683
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
5684
                                      nicparams)
5685
      objects.NIC.CheckParameterSyntax(check_params)
5686
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
5687

    
5688
    # disk checks/pre-build
5689
    self.disks = []
5690
    for disk in self.op.disks:
5691
      mode = disk.get("mode", constants.DISK_RDWR)
5692
      if mode not in constants.DISK_ACCESS_SET:
5693
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
5694
                                   mode, errors.ECODE_INVAL)
5695
      size = disk.get("size", None)
5696
      if size is None:
5697
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
5698
      try:
5699
        size = int(size)
5700
      except ValueError:
5701
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
5702
                                   errors.ECODE_INVAL)
5703
      self.disks.append({"size": size, "mode": mode})
5704

    
5705
    # used in CheckPrereq for ip ping check
5706
    self.check_ip = hostname1.ip
5707

    
5708
    # file storage checks
5709
    if (self.op.file_driver and
5710
        not self.op.file_driver in constants.FILE_DRIVER):
5711
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
5712
                                 self.op.file_driver, errors.ECODE_INVAL)
5713

    
5714
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
5715
      raise errors.OpPrereqError("File storage directory path not absolute",
5716
                                 errors.ECODE_INVAL)
5717

    
5718
    ### Node/iallocator related checks
5719
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
5720
      raise errors.OpPrereqError("One and only one of iallocator and primary"
5721
                                 " node must be given",
5722
                                 errors.ECODE_INVAL)
5723

    
5724
    if self.op.iallocator:
5725
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5726
    else:
5727
      self.op.pnode = self._ExpandNode(self.op.pnode)
5728
      nodelist = [self.op.pnode]
5729
      if self.op.snode is not None:
5730
        self.op.snode = self._ExpandNode(self.op.snode)
5731
        nodelist.append(self.op.snode)
5732
      self.needed_locks[locking.LEVEL_NODE] = nodelist
5733

    
5734
    # in case of import lock the source node too
5735
    if self.op.mode == constants.INSTANCE_IMPORT:
5736
      src_node = getattr(self.op, "src_node", None)
5737
      src_path = getattr(self.op, "src_path", None)
5738

    
5739
      if src_path is None:
5740
        self.op.src_path = src_path = self.op.instance_name
5741

    
5742
      if src_node is None:
5743
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5744
        self.op.src_node = None
5745
        if os.path.isabs(src_path):
5746
          raise errors.OpPrereqError("Importing an instance from an absolute"
5747
                                     " path requires a source node option.",
5748
                                     errors.ECODE_INVAL)
5749
      else:
5750
        self.op.src_node = src_node = self._ExpandNode(src_node)
5751
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
5752
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
5753
        if not os.path.isabs(src_path):
5754
          self.op.src_path = src_path = \
5755
            os.path.join(constants.EXPORT_DIR, src_path)
5756

    
5757
      # On import force_variant must be True, because if we forced it at
5758
      # initial install, our only chance when importing it back is that it
5759
      # works again!
5760
      self.op.force_variant = True
5761

    
5762
    else: # INSTANCE_CREATE
5763
      if getattr(self.op, "os_type", None) is None:
5764
        raise errors.OpPrereqError("No guest OS specified",
5765
                                   errors.ECODE_INVAL)
5766
      self.op.force_variant = getattr(self.op, "force_variant", False)
5767

    
5768
  def _RunAllocator(self):
5769
    """Run the allocator based on input opcode.
5770

5771
    """
5772
    nics = [n.ToDict() for n in self.nics]
5773
    ial = IAllocator(self.cfg, self.rpc,
5774
                     mode=constants.IALLOCATOR_MODE_ALLOC,
5775
                     name=self.op.instance_name,
5776
                     disk_template=self.op.disk_template,
5777
                     tags=[],
5778
                     os=self.op.os_type,
5779
                     vcpus=self.be_full[constants.BE_VCPUS],
5780
                     mem_size=self.be_full[constants.BE_MEMORY],
5781
                     disks=self.disks,
5782
                     nics=nics,
5783
                     hypervisor=self.op.hypervisor,
5784
                     )
5785

    
5786
    ial.Run(self.op.iallocator)
5787

    
5788
    if not ial.success:
5789
      raise errors.OpPrereqError("Can't compute nodes using"
5790
                                 " iallocator '%s': %s" %
5791
                                 (self.op.iallocator, ial.info),
5792
                                 errors.ECODE_NORES)
5793
    if len(ial.nodes) != ial.required_nodes:
5794
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5795
                                 " of nodes (%s), required %s" %
5796
                                 (self.op.iallocator, len(ial.nodes),
5797
                                  ial.required_nodes), errors.ECODE_FAULT)
5798
    self.op.pnode = ial.nodes[0]
5799
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5800
                 self.op.instance_name, self.op.iallocator,
5801
                 ", ".join(ial.nodes))
5802
    if ial.required_nodes == 2:
5803
      self.op.snode = ial.nodes[1]
5804

    
5805
  def BuildHooksEnv(self):
5806
    """Build hooks env.
5807

5808
    This runs on master, primary and secondary nodes of the instance.
5809

5810
    """
5811
    env = {
5812
      "ADD_MODE": self.op.mode,
5813
      }
5814
    if self.op.mode == constants.INSTANCE_IMPORT:
5815
      env["SRC_NODE"] = self.op.src_node
5816
      env["SRC_PATH"] = self.op.src_path
5817
      env["SRC_IMAGES"] = self.src_images
5818

    
5819
    env.update(_BuildInstanceHookEnv(
5820
      name=self.op.instance_name,
5821
      primary_node=self.op.pnode,
5822
      secondary_nodes=self.secondaries,
5823
      status=self.op.start,
5824
      os_type=self.op.os_type,
5825
      memory=self.be_full[constants.BE_MEMORY],
5826
      vcpus=self.be_full[constants.BE_VCPUS],
5827
      nics=_NICListToTuple(self, self.nics),
5828
      disk_template=self.op.disk_template,
5829
      disks=[(d["size"], d["mode"]) for d in self.disks],
5830
      bep=self.be_full,
5831
      hvp=self.hv_full,
5832
      hypervisor_name=self.op.hypervisor,
5833
    ))
5834

    
5835
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
5836
          self.secondaries)
5837
    return env, nl, nl
5838

    
5839

    
5840
  def CheckPrereq(self):
5841
    """Check prerequisites.
5842

5843
    """
5844
    if (not self.cfg.GetVGName() and
5845
        self.op.disk_template not in constants.DTS_NOT_LVM):
5846
      raise errors.OpPrereqError("Cluster does not support lvm-based"
5847
                                 " instances", errors.ECODE_STATE)
5848

    
5849
    if self.op.mode == constants.INSTANCE_IMPORT:
5850
      src_node = self.op.src_node
5851
      src_path = self.op.src_path
5852

    
5853
      if src_node is None:
5854
        locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
5855
        exp_list = self.rpc.call_export_list(locked_nodes)
5856
        found = False
5857
        for node in exp_list:
5858
          if exp_list[node].fail_msg:
5859
            continue
5860
          if src_path in exp_list[node].payload:
5861
            found = True
5862
            self.op.src_node = src_node = node
5863
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
5864
                                                       src_path)
5865
            break
5866
        if not found:
5867
          raise errors.OpPrereqError("No export found for relative path %s" %
5868
                                      src_path, errors.ECODE_INVAL)
5869

    
5870
      _CheckNodeOnline(self, src_node)
5871
      result = self.rpc.call_export_info(src_node, src_path)
5872
      result.Raise("No export or invalid export found in dir %s" % src_path)
5873

    
5874
      export_info = objects.SerializableConfigParser.Loads(str(result.payload))
5875
      if not export_info.has_section(constants.INISECT_EXP):
5876
        raise errors.ProgrammerError("Corrupted export config",
5877
                                     errors.ECODE_ENVIRON)
5878

    
5879
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
5880
      if (int(ei_version) != constants.EXPORT_VERSION):
5881
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
5882
                                   (ei_version, constants.EXPORT_VERSION),
5883
                                   errors.ECODE_ENVIRON)
5884

    
5885
      # Check that the new instance doesn't have less disks than the export
5886
      instance_disks = len(self.disks)
5887
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
5888
      if instance_disks < export_disks:
5889
        raise errors.OpPrereqError("Not enough disks to import."
5890
                                   " (instance: %d, export: %d)" %
5891
                                   (instance_disks, export_disks),
5892
                                   errors.ECODE_INVAL)
5893

    
5894
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
5895
      disk_images = []
5896
      for idx in range(export_disks):
5897
        option = 'disk%d_dump' % idx
5898
        if export_info.has_option(constants.INISECT_INS, option):
5899
          # FIXME: are the old os-es, disk sizes, etc. useful?
5900
          export_name = export_info.get(constants.INISECT_INS, option)
5901
          image = os.path.join(src_path, export_name)
5902
          disk_images.append(image)
5903
        else:
5904
          disk_images.append(False)
5905

    
5906
      self.src_images = disk_images
5907

    
5908
      old_name = export_info.get(constants.INISECT_INS, 'name')
5909
      # FIXME: int() here could throw a ValueError on broken exports
5910
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
5911
      if self.op.instance_name == old_name:
5912
        for idx, nic in enumerate(self.nics):
5913
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
5914
            nic_mac_ini = 'nic%d_mac' % idx
5915
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
5916

    
5917
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
5918
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
5919
    if self.op.start and not self.op.ip_check:
5920
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
5921
                                 " adding an instance in start mode",
5922
                                 errors.ECODE_INVAL)
5923

    
5924
    if self.op.ip_check:
5925
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
5926
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5927
                                   (self.check_ip, self.op.instance_name),
5928
                                   errors.ECODE_NOTUNIQUE)
5929

    
5930
    #### mac address generation
5931
    # By generating here the mac address both the allocator and the hooks get
5932
    # the real final mac address rather than the 'auto' or 'generate' value.
5933
    # There is a race condition between the generation and the instance object
5934
    # creation, which means that we know the mac is valid now, but we're not
5935
    # sure it will be when we actually add the instance. If things go bad
5936
    # adding the instance will abort because of a duplicate mac, and the
5937
    # creation job will fail.
5938
    for nic in self.nics:
5939
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5940
        nic.mac = self.cfg.GenerateMAC()
5941

    
5942
    #### allocator run
5943

    
5944
    if self.op.iallocator is not None:
5945
      self._RunAllocator()
5946

    
5947
    #### node related checks
5948

    
5949
    # check primary node
5950
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
5951
    assert self.pnode is not None, \
5952
      "Cannot retrieve locked node %s" % self.op.pnode
5953
    if pnode.offline:
5954
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
5955
                                 pnode.name, errors.ECODE_STATE)
5956
    if pnode.drained:
5957
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
5958
                                 pnode.name, errors.ECODE_STATE)
5959

    
5960
    self.secondaries = []
5961

    
5962
    # mirror node verification
5963
    if self.op.disk_template in constants.DTS_NET_MIRROR:
5964
      if self.op.snode is None:
5965
        raise errors.OpPrereqError("The networked disk templates need"
5966
                                   " a mirror node", errors.ECODE_INVAL)
5967
      if self.op.snode == pnode.name:
5968
        raise errors.OpPrereqError("The secondary node cannot be the"
5969
                                   " primary node.", errors.ECODE_INVAL)
5970
      _CheckNodeOnline(self, self.op.snode)
5971
      _CheckNodeNotDrained(self, self.op.snode)
5972
      self.secondaries.append(self.op.snode)
5973

    
5974
    nodenames = [pnode.name] + self.secondaries
5975

    
5976
    req_size = _ComputeDiskSize(self.op.disk_template,
5977
                                self.disks)
5978

    
5979
    # Check lv size requirements
5980
    if req_size is not None:
5981
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5982
                                         self.op.hypervisor)
5983
      for node in nodenames:
5984
        info = nodeinfo[node]
5985
        info.Raise("Cannot get current information from node %s" % node)
5986
        info = info.payload
5987
        vg_free = info.get('vg_free', None)
5988
        if not isinstance(vg_free, int):
5989
          raise errors.OpPrereqError("Can't compute free disk space on"
5990
                                     " node %s" % node, errors.ECODE_ENVIRON)
5991
        if req_size > vg_free:
5992
          raise errors.OpPrereqError("Not enough disk space on target node %s."
5993
                                     " %d MB available, %d MB required" %
5994
                                     (node, vg_free, req_size),
5995
                                     errors.ECODE_NORES)
5996

    
5997
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
5998

    
5999
    # os verification
6000
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
6001
    result.Raise("OS '%s' not in supported os list for primary node %s" %
6002
                 (self.op.os_type, pnode.name),
6003
                 prereq=True, ecode=errors.ECODE_INVAL)
6004
    if not self.op.force_variant:
6005
      _CheckOSVariant(result.payload, self.op.os_type)
6006

    
6007
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
6008

    
6009
    # memory check on primary node
6010
    if self.op.start:
6011
      _CheckNodeFreeMemory(self, self.pnode.name,
6012
                           "creating instance %s" % self.op.instance_name,
6013
                           self.be_full[constants.BE_MEMORY],
6014
                           self.op.hypervisor)
6015

    
6016
    self.dry_run_result = list(nodenames)
6017

    
6018
  def Exec(self, feedback_fn):
6019
    """Create and add the instance to the cluster.
6020

6021
    """
6022
    instance = self.op.instance_name
6023
    pnode_name = self.pnode.name
6024

    
6025
    ht_kind = self.op.hypervisor
6026
    if ht_kind in constants.HTS_REQ_PORT:
6027
      network_port = self.cfg.AllocatePort()
6028
    else:
6029
      network_port = None
6030

    
6031
    ##if self.op.vnc_bind_address is None:
6032
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
6033

    
6034
    # this is needed because os.path.join does not accept None arguments
6035
    if self.op.file_storage_dir is None:
6036
      string_file_storage_dir = ""
6037
    else:
6038
      string_file_storage_dir = self.op.file_storage_dir
6039

    
6040
    # build the full file storage dir path
6041
    file_storage_dir = os.path.normpath(os.path.join(
6042
                                        self.cfg.GetFileStorageDir(),
6043
                                        string_file_storage_dir, instance))
6044

    
6045

    
6046
    disks = _GenerateDiskTemplate(self,
6047
                                  self.op.disk_template,
6048
                                  instance, pnode_name,
6049
                                  self.secondaries,
6050
                                  self.disks,
6051
                                  file_storage_dir,
6052
                                  self.op.file_driver,
6053
                                  0)
6054

    
6055
    iobj = objects.Instance(name=instance, os=self.op.os_type,
6056
                            primary_node=pnode_name,
6057
                            nics=self.nics, disks=disks,
6058
                            disk_template=self.op.disk_template,
6059
                            admin_up=False,
6060
                            network_port=network_port,
6061
                            beparams=self.op.beparams,
6062
                            hvparams=self.op.hvparams,
6063
                            hypervisor=self.op.hypervisor,
6064
                            )
6065

    
6066
    feedback_fn("* creating instance disks...")
6067
    try:
6068
      _CreateDisks(self, iobj)
6069
    except errors.OpExecError:
6070
      self.LogWarning("Device creation failed, reverting...")
6071
      try:
6072
        _RemoveDisks(self, iobj)
6073
      finally:
6074
        self.cfg.ReleaseDRBDMinors(instance)
6075
        raise
6076

    
6077
    feedback_fn("adding instance %s to cluster config" % instance)
6078

    
6079
    self.cfg.AddInstance(iobj)
6080
    # Declare that we don't want to remove the instance lock anymore, as we've
6081
    # added the instance to the config
6082
    del self.remove_locks[locking.LEVEL_INSTANCE]
6083
    # Unlock all the nodes
6084
    if self.op.mode == constants.INSTANCE_IMPORT:
6085
      nodes_keep = [self.op.src_node]
6086
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
6087
                       if node != self.op.src_node]
6088
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
6089
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6090
    else:
6091
      self.context.glm.release(locking.LEVEL_NODE)
6092
      del self.acquired_locks[locking.LEVEL_NODE]
6093

    
6094
    if self.op.wait_for_sync:
6095
      disk_abort = not _WaitForSync(self, iobj)
6096
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
6097
      # make sure the disks are not degraded (still sync-ing is ok)
6098
      time.sleep(15)
6099
      feedback_fn("* checking mirrors status")
6100
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
6101
    else:
6102
      disk_abort = False
6103

    
6104
    if disk_abort:
6105
      _RemoveDisks(self, iobj)
6106
      self.cfg.RemoveInstance(iobj.name)
6107
      # Make sure the instance lock gets removed
6108
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
6109
      raise errors.OpExecError("There are some degraded disks for"
6110
                               " this instance")
6111

    
6112
    feedback_fn("creating os for instance %s on node %s" %
6113
                (instance, pnode_name))
6114

    
6115
    if iobj.disk_template != constants.DT_DISKLESS:
6116
      if self.op.mode == constants.INSTANCE_CREATE:
6117
        feedback_fn("* running the instance OS create scripts...")
6118
        result = self.rpc.call_instance_os_add(pnode_name, iobj, False)
6119
        result.Raise("Could not add os for instance %s"
6120
                     " on node %s" % (instance, pnode_name))
6121

    
6122
      elif self.op.mode == constants.INSTANCE_IMPORT:
6123
        feedback_fn("* running the instance OS import scripts...")
6124
        src_node = self.op.src_node
6125
        src_images = self.src_images
6126
        cluster_name = self.cfg.GetClusterName()
6127
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
6128
                                                         src_node, src_images,
6129
                                                         cluster_name)
6130
        msg = import_result.fail_msg
6131
        if msg:
6132
          self.LogWarning("Error while importing the disk images for instance"
6133
                          " %s on node %s: %s" % (instance, pnode_name, msg))
6134
      else:
6135
        # also checked in the prereq part
6136
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
6137
                                     % self.op.mode)
6138

    
6139
    if self.op.start:
6140
      iobj.admin_up = True
6141
      self.cfg.Update(iobj, feedback_fn)
6142
      logging.info("Starting instance %s on node %s", instance, pnode_name)
6143
      feedback_fn("* starting instance...")
6144
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
6145
      result.Raise("Could not start instance")
6146

    
6147
    return list(iobj.all_nodes)
6148

    
6149

    
6150
class LUConnectConsole(NoHooksLU):
6151
  """Connect to an instance's console.
6152

6153
  This is somewhat special in that it returns the command line that
6154
  you need to run on the master node in order to connect to the
6155
  console.
6156

6157
  """
6158
  _OP_REQP = ["instance_name"]
6159
  REQ_BGL = False
6160

    
6161
  def ExpandNames(self):
6162
    self._ExpandAndLockInstance()
6163

    
6164
  def CheckPrereq(self):
6165
    """Check prerequisites.
6166

6167
    This checks that the instance is in the cluster.
6168

6169
    """
6170
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6171
    assert self.instance is not None, \
6172
      "Cannot retrieve locked instance %s" % self.op.instance_name
6173
    _CheckNodeOnline(self, self.instance.primary_node)
6174

    
6175
  def Exec(self, feedback_fn):
6176
    """Connect to the console of an instance
6177

6178
    """
6179
    instance = self.instance
6180
    node = instance.primary_node
6181

    
6182
    node_insts = self.rpc.call_instance_list([node],
6183
                                             [instance.hypervisor])[node]
6184
    node_insts.Raise("Can't get node information from %s" % node)
6185

    
6186
    if instance.name not in node_insts.payload:
6187
      raise errors.OpExecError("Instance %s is not running." % instance.name)
6188

    
6189
    logging.debug("Connecting to console of %s on %s", instance.name, node)
6190

    
6191
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6192
    cluster = self.cfg.GetClusterInfo()
6193
    # beparams and hvparams are passed separately, to avoid editing the
6194
    # instance and then saving the defaults in the instance itself.
6195
    hvparams = cluster.FillHV(instance)
6196
    beparams = cluster.FillBE(instance)
6197
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6198

    
6199
    # build ssh cmdline
6200
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6201

    
6202

    
6203
class LUReplaceDisks(LogicalUnit):
6204
  """Replace the disks of an instance.
6205

6206
  """
6207
  HPATH = "mirrors-replace"
6208
  HTYPE = constants.HTYPE_INSTANCE
6209
  _OP_REQP = ["instance_name", "mode", "disks"]
6210
  REQ_BGL = False
6211

    
6212
  def CheckArguments(self):
6213
    if not hasattr(self.op, "remote_node"):
6214
      self.op.remote_node = None
6215
    if not hasattr(self.op, "iallocator"):
6216
      self.op.iallocator = None
6217

    
6218
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
6219
                                  self.op.iallocator)
6220

    
6221
  def ExpandNames(self):
6222
    self._ExpandAndLockInstance()
6223

    
6224
    if self.op.iallocator is not None:
6225
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6226

    
6227
    elif self.op.remote_node is not None:
6228
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6229
      if remote_node is None:
6230
        raise errors.OpPrereqError("Node '%s' not known" %
6231
                                   self.op.remote_node, errors.ECODE_NOENT)
6232

    
6233
      self.op.remote_node = remote_node
6234

    
6235
      # Warning: do not remove the locking of the new secondary here
6236
      # unless DRBD8.AddChildren is changed to work in parallel;
6237
      # currently it doesn't since parallel invocations of
6238
      # FindUnusedMinor will conflict
6239
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6240
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6241

    
6242
    else:
6243
      self.needed_locks[locking.LEVEL_NODE] = []
6244
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6245

    
6246
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
6247
                                   self.op.iallocator, self.op.remote_node,
6248
                                   self.op.disks)
6249

    
6250
    self.tasklets = [self.replacer]
6251

    
6252
  def DeclareLocks(self, level):
6253
    # If we're not already locking all nodes in the set we have to declare the
6254
    # instance's primary/secondary nodes.
6255
    if (level == locking.LEVEL_NODE and
6256
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6257
      self._LockInstancesNodes()
6258

    
6259
  def BuildHooksEnv(self):
6260
    """Build hooks env.
6261

6262
    This runs on the master, the primary and all the secondaries.
6263

6264
    """
6265
    instance = self.replacer.instance
6266
    env = {
6267
      "MODE": self.op.mode,
6268
      "NEW_SECONDARY": self.op.remote_node,
6269
      "OLD_SECONDARY": instance.secondary_nodes[0],
6270
      }
6271
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6272
    nl = [
6273
      self.cfg.GetMasterNode(),
6274
      instance.primary_node,
6275
      ]
6276
    if self.op.remote_node is not None:
6277
      nl.append(self.op.remote_node)
6278
    return env, nl, nl
6279

    
6280

    
6281
class LUEvacuateNode(LogicalUnit):
6282
  """Relocate the secondary instances from a node.
6283

6284
  """
6285
  HPATH = "node-evacuate"
6286
  HTYPE = constants.HTYPE_NODE
6287
  _OP_REQP = ["node_name"]
6288
  REQ_BGL = False
6289

    
6290
  def CheckArguments(self):
6291
    if not hasattr(self.op, "remote_node"):
6292
      self.op.remote_node = None
6293
    if not hasattr(self.op, "iallocator"):
6294
      self.op.iallocator = None
6295

    
6296
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
6297
                                  self.op.remote_node,
6298
                                  self.op.iallocator)
6299

    
6300
  def ExpandNames(self):
6301
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
6302
    if self.op.node_name is None:
6303
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name,
6304
                                 errors.ECODE_NOENT)
6305

    
6306
    self.needed_locks = {}
6307

    
6308
    # Declare node locks
6309
    if self.op.iallocator is not None:
6310
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6311

    
6312
    elif self.op.remote_node is not None:
6313
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6314
      if remote_node is None:
6315
        raise errors.OpPrereqError("Node '%s' not known" %
6316
                                   self.op.remote_node, errors.ECODE_NOENT)
6317

    
6318
      self.op.remote_node = remote_node
6319

    
6320
      # Warning: do not remove the locking of the new secondary here
6321
      # unless DRBD8.AddChildren is changed to work in parallel;
6322
      # currently it doesn't since parallel invocations of
6323
      # FindUnusedMinor will conflict
6324
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6325
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6326

    
6327
    else:
6328
      raise errors.OpPrereqError("Invalid parameters", errors.ECODE_INVAL)
6329

    
6330
    # Create tasklets for replacing disks for all secondary instances on this
6331
    # node
6332
    names = []
6333
    tasklets = []
6334

    
6335
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
6336
      logging.debug("Replacing disks for instance %s", inst.name)
6337
      names.append(inst.name)
6338

    
6339
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
6340
                                self.op.iallocator, self.op.remote_node, [])
6341
      tasklets.append(replacer)
6342

    
6343
    self.tasklets = tasklets
6344
    self.instance_names = names
6345

    
6346
    # Declare instance locks
6347
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
6348

    
6349
  def DeclareLocks(self, level):
6350
    # If we're not already locking all nodes in the set we have to declare the
6351
    # instance's primary/secondary nodes.
6352
    if (level == locking.LEVEL_NODE and
6353
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6354
      self._LockInstancesNodes()
6355

    
6356
  def BuildHooksEnv(self):
6357
    """Build hooks env.
6358

6359
    This runs on the master, the primary and all the secondaries.
6360

6361
    """
6362
    env = {
6363
      "NODE_NAME": self.op.node_name,
6364
      }
6365

    
6366
    nl = [self.cfg.GetMasterNode()]
6367

    
6368
    if self.op.remote_node is not None:
6369
      env["NEW_SECONDARY"] = self.op.remote_node
6370
      nl.append(self.op.remote_node)
6371

    
6372
    return (env, nl, nl)
6373

    
6374

    
6375
class TLReplaceDisks(Tasklet):
6376
  """Replaces disks for an instance.
6377

6378
  Note: Locking is not within the scope of this class.
6379

6380
  """
6381
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
6382
               disks):
6383
    """Initializes this class.
6384

6385
    """
6386
    Tasklet.__init__(self, lu)
6387

    
6388
    # Parameters
6389
    self.instance_name = instance_name
6390
    self.mode = mode
6391
    self.iallocator_name = iallocator_name
6392
    self.remote_node = remote_node
6393
    self.disks = disks
6394

    
6395
    # Runtime data
6396
    self.instance = None
6397
    self.new_node = None
6398
    self.target_node = None
6399
    self.other_node = None
6400
    self.remote_node_info = None
6401
    self.node_secondary_ip = None
6402

    
6403
  @staticmethod
6404
  def CheckArguments(mode, remote_node, iallocator):
6405
    """Helper function for users of this class.
6406

6407
    """
6408
    # check for valid parameter combination
6409
    if mode == constants.REPLACE_DISK_CHG:
6410
      if remote_node is None and iallocator is None:
6411
        raise errors.OpPrereqError("When changing the secondary either an"
6412
                                   " iallocator script must be used or the"
6413
                                   " new node given", errors.ECODE_INVAL)
6414

    
6415
      if remote_node is not None and iallocator is not None:
6416
        raise errors.OpPrereqError("Give either the iallocator or the new"
6417
                                   " secondary, not both", errors.ECODE_INVAL)
6418

    
6419
    elif remote_node is not None or iallocator is not None:
6420
      # Not replacing the secondary
6421
      raise errors.OpPrereqError("The iallocator and new node options can"
6422
                                 " only be used when changing the"
6423
                                 " secondary node", errors.ECODE_INVAL)
6424

    
6425
  @staticmethod
6426
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
6427
    """Compute a new secondary node using an IAllocator.
6428

6429
    """
6430
    ial = IAllocator(lu.cfg, lu.rpc,
6431
                     mode=constants.IALLOCATOR_MODE_RELOC,
6432
                     name=instance_name,
6433
                     relocate_from=relocate_from)
6434

    
6435
    ial.Run(iallocator_name)
6436

    
6437
    if not ial.success:
6438
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
6439
                                 " %s" % (iallocator_name, ial.info),
6440
                                 errors.ECODE_NORES)
6441

    
6442
    if len(ial.nodes) != ial.required_nodes:
6443
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6444
                                 " of nodes (%s), required %s" %
6445
                                 (len(ial.nodes), ial.required_nodes),
6446
                                 errors.ECODE_FAULT)
6447

    
6448
    remote_node_name = ial.nodes[0]
6449

    
6450
    lu.LogInfo("Selected new secondary for instance '%s': %s",
6451
               instance_name, remote_node_name)
6452

    
6453
    return remote_node_name
6454

    
6455
  def _FindFaultyDisks(self, node_name):
6456
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
6457
                                    node_name, True)
6458

    
6459
  def CheckPrereq(self):
6460
    """Check prerequisites.
6461

6462
    This checks that the instance is in the cluster.
6463

6464
    """
6465
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
6466
    assert instance is not None, \
6467
      "Cannot retrieve locked instance %s" % self.instance_name
6468

    
6469
    if instance.disk_template != constants.DT_DRBD8:
6470
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
6471
                                 " instances", errors.ECODE_INVAL)
6472

    
6473
    if len(instance.secondary_nodes) != 1:
6474
      raise errors.OpPrereqError("The instance has a strange layout,"
6475
                                 " expected one secondary but found %d" %
6476
                                 len(instance.secondary_nodes),
6477
                                 errors.ECODE_FAULT)
6478

    
6479
    secondary_node = instance.secondary_nodes[0]
6480

    
6481
    if self.iallocator_name is None:
6482
      remote_node = self.remote_node
6483
    else:
6484
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
6485
                                       instance.name, instance.secondary_nodes)
6486

    
6487
    if remote_node is not None:
6488
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
6489
      assert self.remote_node_info is not None, \
6490
        "Cannot retrieve locked node %s" % remote_node
6491
    else:
6492
      self.remote_node_info = None
6493

    
6494
    if remote_node == self.instance.primary_node:
6495
      raise errors.OpPrereqError("The specified node is the primary node of"
6496
                                 " the instance.", errors.ECODE_INVAL)
6497

    
6498
    if remote_node == secondary_node:
6499
      raise errors.OpPrereqError("The specified node is already the"
6500
                                 " secondary node of the instance.",
6501
                                 errors.ECODE_INVAL)
6502

    
6503
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
6504
                                    constants.REPLACE_DISK_CHG):
6505
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
6506
                                 errors.ECODE_INVAL)
6507

    
6508
    if self.mode == constants.REPLACE_DISK_AUTO:
6509
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
6510
      faulty_secondary = self._FindFaultyDisks(secondary_node)
6511

    
6512
      if faulty_primary and faulty_secondary:
6513
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
6514
                                   " one node and can not be repaired"
6515
                                   " automatically" % self.instance_name,
6516
                                   errors.ECODE_STATE)
6517

    
6518
      if faulty_primary:
6519
        self.disks = faulty_primary
6520
        self.target_node = instance.primary_node
6521
        self.other_node = secondary_node
6522
        check_nodes = [self.target_node, self.other_node]
6523
      elif faulty_secondary:
6524
        self.disks = faulty_secondary
6525
        self.target_node = secondary_node
6526
        self.other_node = instance.primary_node
6527
        check_nodes = [self.target_node, self.other_node]
6528
      else:
6529
        self.disks = []
6530
        check_nodes = []
6531

    
6532
    else:
6533
      # Non-automatic modes
6534
      if self.mode == constants.REPLACE_DISK_PRI:
6535
        self.target_node = instance.primary_node
6536
        self.other_node = secondary_node
6537
        check_nodes = [self.target_node, self.other_node]
6538

    
6539
      elif self.mode == constants.REPLACE_DISK_SEC:
6540
        self.target_node = secondary_node
6541
        self.other_node = instance.primary_node
6542
        check_nodes = [self.target_node, self.other_node]
6543

    
6544
      elif self.mode == constants.REPLACE_DISK_CHG:
6545
        self.new_node = remote_node
6546
        self.other_node = instance.primary_node
6547
        self.target_node = secondary_node
6548
        check_nodes = [self.new_node, self.other_node]
6549

    
6550
        _CheckNodeNotDrained(self.lu, remote_node)
6551

    
6552
      else:
6553
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
6554
                                     self.mode)
6555

    
6556
      # If not specified all disks should be replaced
6557
      if not self.disks:
6558
        self.disks = range(len(self.instance.disks))
6559

    
6560
    for node in check_nodes:
6561
      _CheckNodeOnline(self.lu, node)
6562

    
6563
    # Check whether disks are valid
6564
    for disk_idx in self.disks:
6565
      instance.FindDisk(disk_idx)
6566

    
6567
    # Get secondary node IP addresses
6568
    node_2nd_ip = {}
6569

    
6570
    for node_name in [self.target_node, self.other_node, self.new_node]:
6571
      if node_name is not None:
6572
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
6573

    
6574
    self.node_secondary_ip = node_2nd_ip
6575

    
6576
  def Exec(self, feedback_fn):
6577
    """Execute disk replacement.
6578

6579
    This dispatches the disk replacement to the appropriate handler.
6580

6581
    """
6582
    if not self.disks:
6583
      feedback_fn("No disks need replacement")
6584
      return
6585

    
6586
    feedback_fn("Replacing disk(s) %s for %s" %
6587
                (", ".join([str(i) for i in self.disks]), self.instance.name))
6588

    
6589
    activate_disks = (not self.instance.admin_up)
6590

    
6591
    # Activate the instance disks if we're replacing them on a down instance
6592
    if activate_disks:
6593
      _StartInstanceDisks(self.lu, self.instance, True)
6594

    
6595
    try:
6596
      # Should we replace the secondary node?
6597
      if self.new_node is not None:
6598
        fn = self._ExecDrbd8Secondary
6599
      else:
6600
        fn = self._ExecDrbd8DiskOnly
6601

    
6602
      return fn(feedback_fn)
6603

    
6604
    finally:
6605
      # Deactivate the instance disks if we're replacing them on a
6606
      # down instance
6607
      if activate_disks:
6608
        _SafeShutdownInstanceDisks(self.lu, self.instance)
6609

    
6610
  def _CheckVolumeGroup(self, nodes):
6611
    self.lu.LogInfo("Checking volume groups")
6612

    
6613
    vgname = self.cfg.GetVGName()
6614

    
6615
    # Make sure volume group exists on all involved nodes
6616
    results = self.rpc.call_vg_list(nodes)
6617
    if not results:
6618
      raise errors.OpExecError("Can't list volume groups on the nodes")
6619

    
6620
    for node in nodes:
6621
      res = results[node]
6622
      res.Raise("Error checking node %s" % node)
6623
      if vgname not in res.payload:
6624
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
6625
                                 (vgname, node))
6626

    
6627
  def _CheckDisksExistence(self, nodes):
6628
    # Check disk existence
6629
    for idx, dev in enumerate(self.instance.disks):
6630
      if idx not in self.disks:
6631
        continue
6632

    
6633
      for node in nodes:
6634
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
6635
        self.cfg.SetDiskID(dev, node)
6636

    
6637
        result = self.rpc.call_blockdev_find(node, dev)
6638

    
6639
        msg = result.fail_msg
6640
        if msg or not result.payload:
6641
          if not msg:
6642
            msg = "disk not found"
6643
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
6644
                                   (idx, node, msg))
6645

    
6646
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
6647
    for idx, dev in enumerate(self.instance.disks):
6648
      if idx not in self.disks:
6649
        continue
6650

    
6651
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
6652
                      (idx, node_name))
6653

    
6654
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
6655
                                   ldisk=ldisk):
6656
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
6657
                                 " replace disks for instance %s" %
6658
                                 (node_name, self.instance.name))
6659

    
6660
  def _CreateNewStorage(self, node_name):
6661
    vgname = self.cfg.GetVGName()
6662
    iv_names = {}
6663

    
6664
    for idx, dev in enumerate(self.instance.disks):
6665
      if idx not in self.disks:
6666
        continue
6667

    
6668
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
6669

    
6670
      self.cfg.SetDiskID(dev, node_name)
6671

    
6672
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
6673
      names = _GenerateUniqueNames(self.lu, lv_names)
6674

    
6675
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
6676
                             logical_id=(vgname, names[0]))
6677
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6678
                             logical_id=(vgname, names[1]))
6679

    
6680
      new_lvs = [lv_data, lv_meta]
6681
      old_lvs = dev.children
6682
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
6683

    
6684
      # we pass force_create=True to force the LVM creation
6685
      for new_lv in new_lvs:
6686
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
6687
                        _GetInstanceInfoText(self.instance), False)
6688

    
6689
    return iv_names
6690

    
6691
  def _CheckDevices(self, node_name, iv_names):
6692
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
6693
      self.cfg.SetDiskID(dev, node_name)
6694

    
6695
      result = self.rpc.call_blockdev_find(node_name, dev)
6696

    
6697
      msg = result.fail_msg
6698
      if msg or not result.payload:
6699
        if not msg:
6700
          msg = "disk not found"
6701
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
6702
                                 (name, msg))
6703

    
6704
      if result.payload.is_degraded:
6705
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
6706

    
6707
  def _RemoveOldStorage(self, node_name, iv_names):
6708
    for name, (dev, old_lvs, _) in iv_names.iteritems():
6709
      self.lu.LogInfo("Remove logical volumes for %s" % name)
6710

    
6711
      for lv in old_lvs:
6712
        self.cfg.SetDiskID(lv, node_name)
6713

    
6714
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
6715
        if msg:
6716
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
6717
                             hint="remove unused LVs manually")
6718

    
6719
  def _ExecDrbd8DiskOnly(self, feedback_fn):
6720
    """Replace a disk on the primary or secondary for DRBD 8.
6721

6722
    The algorithm for replace is quite complicated:
6723

6724
      1. for each disk to be replaced:
6725

6726
        1. create new LVs on the target node with unique names
6727
        1. detach old LVs from the drbd device
6728
        1. rename old LVs to name_replaced.<time_t>
6729
        1. rename new LVs to old LVs
6730
        1. attach the new LVs (with the old names now) to the drbd device
6731

6732
      1. wait for sync across all devices
6733

6734
      1. for each modified disk:
6735

6736
        1. remove old LVs (which have the name name_replaces.<time_t>)
6737

6738
    Failures are not very well handled.
6739

6740
    """
6741
    steps_total = 6
6742

    
6743
    # Step: check device activation
6744
    self.lu.LogStep(1, steps_total, "Check device existence")
6745
    self._CheckDisksExistence([self.other_node, self.target_node])
6746
    self._CheckVolumeGroup([self.target_node, self.other_node])
6747

    
6748
    # Step: check other node consistency
6749
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6750
    self._CheckDisksConsistency(self.other_node,
6751
                                self.other_node == self.instance.primary_node,
6752
                                False)
6753

    
6754
    # Step: create new storage
6755
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6756
    iv_names = self._CreateNewStorage(self.target_node)
6757

    
6758
    # Step: for each lv, detach+rename*2+attach
6759
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6760
    for dev, old_lvs, new_lvs in iv_names.itervalues():
6761
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
6762

    
6763
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
6764
                                                     old_lvs)
6765
      result.Raise("Can't detach drbd from local storage on node"
6766
                   " %s for device %s" % (self.target_node, dev.iv_name))
6767
      #dev.children = []
6768
      #cfg.Update(instance)
6769

    
6770
      # ok, we created the new LVs, so now we know we have the needed
6771
      # storage; as such, we proceed on the target node to rename
6772
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
6773
      # using the assumption that logical_id == physical_id (which in
6774
      # turn is the unique_id on that node)
6775

    
6776
      # FIXME(iustin): use a better name for the replaced LVs
6777
      temp_suffix = int(time.time())
6778
      ren_fn = lambda d, suff: (d.physical_id[0],
6779
                                d.physical_id[1] + "_replaced-%s" % suff)
6780

    
6781
      # Build the rename list based on what LVs exist on the node
6782
      rename_old_to_new = []
6783
      for to_ren in old_lvs:
6784
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
6785
        if not result.fail_msg and result.payload:
6786
          # device exists
6787
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
6788

    
6789
      self.lu.LogInfo("Renaming the old LVs on the target node")
6790
      result = self.rpc.call_blockdev_rename(self.target_node,
6791
                                             rename_old_to_new)
6792
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
6793

    
6794
      # Now we rename the new LVs to the old LVs
6795
      self.lu.LogInfo("Renaming the new LVs on the target node")
6796
      rename_new_to_old = [(new, old.physical_id)
6797
                           for old, new in zip(old_lvs, new_lvs)]
6798
      result = self.rpc.call_blockdev_rename(self.target_node,
6799
                                             rename_new_to_old)
6800
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
6801

    
6802
      for old, new in zip(old_lvs, new_lvs):
6803
        new.logical_id = old.logical_id
6804
        self.cfg.SetDiskID(new, self.target_node)
6805

    
6806
      for disk in old_lvs:
6807
        disk.logical_id = ren_fn(disk, temp_suffix)
6808
        self.cfg.SetDiskID(disk, self.target_node)
6809

    
6810
      # Now that the new lvs have the old name, we can add them to the device
6811
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
6812
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
6813
                                                  new_lvs)
6814
      msg = result.fail_msg
6815
      if msg:
6816
        for new_lv in new_lvs:
6817
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
6818
                                               new_lv).fail_msg
6819
          if msg2:
6820
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
6821
                               hint=("cleanup manually the unused logical"
6822
                                     "volumes"))
6823
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
6824

    
6825
      dev.children = new_lvs
6826

    
6827
      self.cfg.Update(self.instance, feedback_fn)
6828

    
6829
    # Wait for sync
6830
    # This can fail as the old devices are degraded and _WaitForSync
6831
    # does a combined result over all disks, so we don't check its return value
6832
    self.lu.LogStep(5, steps_total, "Sync devices")
6833
    _WaitForSync(self.lu, self.instance, unlock=True)
6834

    
6835
    # Check all devices manually
6836
    self._CheckDevices(self.instance.primary_node, iv_names)
6837

    
6838
    # Step: remove old storage
6839
    self.lu.LogStep(6, steps_total, "Removing old storage")
6840
    self._RemoveOldStorage(self.target_node, iv_names)
6841

    
6842
  def _ExecDrbd8Secondary(self, feedback_fn):
6843
    """Replace the secondary node for DRBD 8.
6844

6845
    The algorithm for replace is quite complicated:
6846
      - for all disks of the instance:
6847
        - create new LVs on the new node with same names
6848
        - shutdown the drbd device on the old secondary
6849
        - disconnect the drbd network on the primary
6850
        - create the drbd device on the new secondary
6851
        - network attach the drbd on the primary, using an artifice:
6852
          the drbd code for Attach() will connect to the network if it
6853
          finds a device which is connected to the good local disks but
6854
          not network enabled
6855
      - wait for sync across all devices
6856
      - remove all disks from the old secondary
6857

6858
    Failures are not very well handled.
6859

6860
    """
6861
    steps_total = 6
6862

    
6863
    # Step: check device activation
6864
    self.lu.LogStep(1, steps_total, "Check device existence")
6865
    self._CheckDisksExistence([self.instance.primary_node])
6866
    self._CheckVolumeGroup([self.instance.primary_node])
6867

    
6868
    # Step: check other node consistency
6869
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6870
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
6871

    
6872
    # Step: create new storage
6873
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6874
    for idx, dev in enumerate(self.instance.disks):
6875
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
6876
                      (self.new_node, idx))
6877
      # we pass force_create=True to force LVM creation
6878
      for new_lv in dev.children:
6879
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
6880
                        _GetInstanceInfoText(self.instance), False)
6881

    
6882
    # Step 4: dbrd minors and drbd setups changes
6883
    # after this, we must manually remove the drbd minors on both the
6884
    # error and the success paths
6885
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6886
    minors = self.cfg.AllocateDRBDMinor([self.new_node
6887
                                         for dev in self.instance.disks],
6888
                                        self.instance.name)
6889
    logging.debug("Allocated minors %r", minors)
6890

    
6891
    iv_names = {}
6892
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
6893
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
6894
                      (self.new_node, idx))
6895
      # create new devices on new_node; note that we create two IDs:
6896
      # one without port, so the drbd will be activated without
6897
      # networking information on the new node at this stage, and one
6898
      # with network, for the latter activation in step 4
6899
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
6900
      if self.instance.primary_node == o_node1:
6901
        p_minor = o_minor1
6902
      else:
6903
        p_minor = o_minor2
6904

    
6905
      new_alone_id = (self.instance.primary_node, self.new_node, None,
6906
                      p_minor, new_minor, o_secret)
6907
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
6908
                    p_minor, new_minor, o_secret)
6909

    
6910
      iv_names[idx] = (dev, dev.children, new_net_id)
6911
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
6912
                    new_net_id)
6913
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
6914
                              logical_id=new_alone_id,
6915
                              children=dev.children,
6916
                              size=dev.size)
6917
      try:
6918
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
6919
                              _GetInstanceInfoText(self.instance), False)
6920
      except errors.GenericError:
6921
        self.cfg.ReleaseDRBDMinors(self.instance.name)
6922
        raise
6923

    
6924
    # We have new devices, shutdown the drbd on the old secondary
6925
    for idx, dev in enumerate(self.instance.disks):
6926
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
6927
      self.cfg.SetDiskID(dev, self.target_node)
6928
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
6929
      if msg:
6930
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
6931
                           "node: %s" % (idx, msg),
6932
                           hint=("Please cleanup this device manually as"
6933
                                 " soon as possible"))
6934

    
6935
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
6936
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
6937
                                               self.node_secondary_ip,
6938
                                               self.instance.disks)\
6939
                                              [self.instance.primary_node]
6940

    
6941
    msg = result.fail_msg
6942
    if msg:
6943
      # detaches didn't succeed (unlikely)
6944
      self.cfg.ReleaseDRBDMinors(self.instance.name)
6945
      raise errors.OpExecError("Can't detach the disks from the network on"
6946
                               " old node: %s" % (msg,))
6947

    
6948
    # if we managed to detach at least one, we update all the disks of
6949
    # the instance to point to the new secondary
6950
    self.lu.LogInfo("Updating instance configuration")
6951
    for dev, _, new_logical_id in iv_names.itervalues():
6952
      dev.logical_id = new_logical_id
6953
      self.cfg.SetDiskID(dev, self.instance.primary_node)
6954

    
6955
    self.cfg.Update(self.instance, feedback_fn)
6956

    
6957
    # and now perform the drbd attach
6958
    self.lu.LogInfo("Attaching primary drbds to new secondary"
6959
                    " (standalone => connected)")
6960
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
6961
                                            self.new_node],
6962
                                           self.node_secondary_ip,
6963
                                           self.instance.disks,
6964
                                           self.instance.name,
6965
                                           False)
6966
    for to_node, to_result in result.items():
6967
      msg = to_result.fail_msg
6968
      if msg:
6969
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
6970
                           to_node, msg,
6971
                           hint=("please do a gnt-instance info to see the"
6972
                                 " status of disks"))
6973

    
6974
    # Wait for sync
6975
    # This can fail as the old devices are degraded and _WaitForSync
6976
    # does a combined result over all disks, so we don't check its return value
6977
    self.lu.LogStep(5, steps_total, "Sync devices")
6978
    _WaitForSync(self.lu, self.instance, unlock=True)
6979

    
6980
    # Check all devices manually
6981
    self._CheckDevices(self.instance.primary_node, iv_names)
6982

    
6983
    # Step: remove old storage
6984
    self.lu.LogStep(6, steps_total, "Removing old storage")
6985
    self._RemoveOldStorage(self.target_node, iv_names)
6986

    
6987

    
6988
class LURepairNodeStorage(NoHooksLU):
6989
  """Repairs the volume group on a node.
6990

6991
  """
6992
  _OP_REQP = ["node_name"]
6993
  REQ_BGL = False
6994

    
6995
  def CheckArguments(self):
6996
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
6997
    if node_name is None:
6998
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
6999
                                 errors.ECODE_NOENT)
7000

    
7001
    self.op.node_name = node_name
7002

    
7003
  def ExpandNames(self):
7004
    self.needed_locks = {
7005
      locking.LEVEL_NODE: [self.op.node_name],
7006
      }
7007

    
7008
  def _CheckFaultyDisks(self, instance, node_name):
7009
    """Ensure faulty disks abort the opcode or at least warn."""
7010
    try:
7011
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
7012
                                  node_name, True):
7013
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
7014
                                   " node '%s'" % (instance.name, node_name),
7015
                                   errors.ECODE_STATE)
7016
    except errors.OpPrereqError, err:
7017
      if self.op.ignore_consistency:
7018
        self.proc.LogWarning(str(err.args[0]))
7019
      else:
7020
        raise
7021

    
7022
  def CheckPrereq(self):
7023
    """Check prerequisites.
7024

7025
    """
7026
    storage_type = self.op.storage_type
7027

    
7028
    if (constants.SO_FIX_CONSISTENCY not in
7029
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
7030
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
7031
                                 " repaired" % storage_type,
7032
                                 errors.ECODE_INVAL)
7033

    
7034
    # Check whether any instance on this node has faulty disks
7035
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
7036
      if not inst.admin_up:
7037
        continue
7038
      check_nodes = set(inst.all_nodes)
7039
      check_nodes.discard(self.op.node_name)
7040
      for inst_node_name in check_nodes:
7041
        self._CheckFaultyDisks(inst, inst_node_name)
7042

    
7043
  def Exec(self, feedback_fn):
7044
    feedback_fn("Repairing storage unit '%s' on %s ..." %
7045
                (self.op.name, self.op.node_name))
7046

    
7047
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
7048
    result = self.rpc.call_storage_execute(self.op.node_name,
7049
                                           self.op.storage_type, st_args,
7050
                                           self.op.name,
7051
                                           constants.SO_FIX_CONSISTENCY)
7052
    result.Raise("Failed to repair storage unit '%s' on %s" %
7053
                 (self.op.name, self.op.node_name))
7054

    
7055

    
7056
class LUGrowDisk(LogicalUnit):
7057
  """Grow a disk of an instance.
7058

7059
  """
7060
  HPATH = "disk-grow"
7061
  HTYPE = constants.HTYPE_INSTANCE
7062
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
7063
  REQ_BGL = False
7064

    
7065
  def ExpandNames(self):
7066
    self._ExpandAndLockInstance()
7067
    self.needed_locks[locking.LEVEL_NODE] = []
7068
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7069

    
7070
  def DeclareLocks(self, level):
7071
    if level == locking.LEVEL_NODE:
7072
      self._LockInstancesNodes()
7073

    
7074
  def BuildHooksEnv(self):
7075
    """Build hooks env.
7076

7077
    This runs on the master, the primary and all the secondaries.
7078

7079
    """
7080
    env = {
7081
      "DISK": self.op.disk,
7082
      "AMOUNT": self.op.amount,
7083
      }
7084
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7085
    nl = [
7086
      self.cfg.GetMasterNode(),
7087
      self.instance.primary_node,
7088
      ]
7089
    return env, nl, nl
7090

    
7091
  def CheckPrereq(self):
7092
    """Check prerequisites.
7093

7094
    This checks that the instance is in the cluster.
7095

7096
    """
7097
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7098
    assert instance is not None, \
7099
      "Cannot retrieve locked instance %s" % self.op.instance_name
7100
    nodenames = list(instance.all_nodes)
7101
    for node in nodenames:
7102
      _CheckNodeOnline(self, node)
7103

    
7104

    
7105
    self.instance = instance
7106

    
7107
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
7108
      raise errors.OpPrereqError("Instance's disk layout does not support"
7109
                                 " growing.", errors.ECODE_INVAL)
7110

    
7111
    self.disk = instance.FindDisk(self.op.disk)
7112

    
7113
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
7114
                                       instance.hypervisor)
7115
    for node in nodenames:
7116
      info = nodeinfo[node]
7117
      info.Raise("Cannot get current information from node %s" % node)
7118
      vg_free = info.payload.get('vg_free', None)
7119
      if not isinstance(vg_free, int):
7120
        raise errors.OpPrereqError("Can't compute free disk space on"
7121
                                   " node %s" % node, errors.ECODE_ENVIRON)
7122
      if self.op.amount > vg_free:
7123
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
7124
                                   " %d MiB available, %d MiB required" %
7125
                                   (node, vg_free, self.op.amount),
7126
                                   errors.ECODE_NORES)
7127

    
7128
  def Exec(self, feedback_fn):
7129
    """Execute disk grow.
7130

7131
    """
7132
    instance = self.instance
7133
    disk = self.disk
7134
    for node in instance.all_nodes:
7135
      self.cfg.SetDiskID(disk, node)
7136
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
7137
      result.Raise("Grow request failed to node %s" % node)
7138
    disk.RecordGrow(self.op.amount)
7139
    self.cfg.Update(instance, feedback_fn)
7140
    if self.op.wait_for_sync:
7141
      disk_abort = not _WaitForSync(self, instance)
7142
      if disk_abort:
7143
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
7144
                             " status.\nPlease check the instance.")
7145

    
7146

    
7147
class LUQueryInstanceData(NoHooksLU):
7148
  """Query runtime instance data.
7149

7150
  """
7151
  _OP_REQP = ["instances", "static"]
7152
  REQ_BGL = False
7153

    
7154
  def ExpandNames(self):
7155
    self.needed_locks = {}
7156
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
7157

    
7158
    if not isinstance(self.op.instances, list):
7159
      raise errors.OpPrereqError("Invalid argument type 'instances'",
7160
                                 errors.ECODE_INVAL)
7161

    
7162
    if self.op.instances:
7163
      self.wanted_names = []
7164
      for name in self.op.instances:
7165
        full_name = self.cfg.ExpandInstanceName(name)
7166
        if full_name is None:
7167
          raise errors.OpPrereqError("Instance '%s' not known" % name,
7168
                                     errors.ECODE_NOENT)
7169
        self.wanted_names.append(full_name)
7170
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
7171
    else:
7172
      self.wanted_names = None
7173
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
7174

    
7175
    self.needed_locks[locking.LEVEL_NODE] = []
7176
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7177

    
7178
  def DeclareLocks(self, level):
7179
    if level == locking.LEVEL_NODE:
7180
      self._LockInstancesNodes()
7181

    
7182
  def CheckPrereq(self):
7183
    """Check prerequisites.
7184

7185
    This only checks the optional instance list against the existing names.
7186

7187
    """
7188
    if self.wanted_names is None:
7189
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
7190

    
7191
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
7192
                             in self.wanted_names]
7193
    return
7194

    
7195
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
7196
    """Returns the status of a block device
7197

7198
    """
7199
    if self.op.static or not node:
7200
      return None
7201

    
7202
    self.cfg.SetDiskID(dev, node)
7203

    
7204
    result = self.rpc.call_blockdev_find(node, dev)
7205
    if result.offline:
7206
      return None
7207

    
7208
    result.Raise("Can't compute disk status for %s" % instance_name)
7209

    
7210
    status = result.payload
7211
    if status is None:
7212
      return None
7213

    
7214
    return (status.dev_path, status.major, status.minor,
7215
            status.sync_percent, status.estimated_time,
7216
            status.is_degraded, status.ldisk_status)
7217

    
7218
  def _ComputeDiskStatus(self, instance, snode, dev):
7219
    """Compute block device status.
7220

7221
    """
7222
    if dev.dev_type in constants.LDS_DRBD:
7223
      # we change the snode then (otherwise we use the one passed in)
7224
      if dev.logical_id[0] == instance.primary_node:
7225
        snode = dev.logical_id[1]
7226
      else:
7227
        snode = dev.logical_id[0]
7228

    
7229
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
7230
                                              instance.name, dev)
7231
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
7232

    
7233
    if dev.children:
7234
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
7235
                      for child in dev.children]
7236
    else:
7237
      dev_children = []
7238

    
7239
    data = {
7240
      "iv_name": dev.iv_name,
7241
      "dev_type": dev.dev_type,
7242
      "logical_id": dev.logical_id,
7243
      "physical_id": dev.physical_id,
7244
      "pstatus": dev_pstatus,
7245
      "sstatus": dev_sstatus,
7246
      "children": dev_children,
7247
      "mode": dev.mode,
7248
      "size": dev.size,
7249
      }
7250

    
7251
    return data
7252

    
7253
  def Exec(self, feedback_fn):
7254
    """Gather and return data"""
7255
    result = {}
7256

    
7257
    cluster = self.cfg.GetClusterInfo()
7258

    
7259
    for instance in self.wanted_instances:
7260
      if not self.op.static:
7261
        remote_info = self.rpc.call_instance_info(instance.primary_node,
7262
                                                  instance.name,
7263
                                                  instance.hypervisor)
7264
        remote_info.Raise("Error checking node %s" % instance.primary_node)
7265
        remote_info = remote_info.payload
7266
        if remote_info and "state" in remote_info:
7267
          remote_state = "up"
7268
        else:
7269
          remote_state = "down"
7270
      else:
7271
        remote_state = None
7272
      if instance.admin_up:
7273
        config_state = "up"
7274
      else:
7275
        config_state = "down"
7276

    
7277
      disks = [self._ComputeDiskStatus(instance, None, device)
7278
               for device in instance.disks]
7279

    
7280
      idict = {
7281
        "name": instance.name,
7282
        "config_state": config_state,
7283
        "run_state": remote_state,
7284
        "pnode": instance.primary_node,
7285
        "snodes": instance.secondary_nodes,
7286
        "os": instance.os,
7287
        # this happens to be the same format used for hooks
7288
        "nics": _NICListToTuple(self, instance.nics),
7289
        "disks": disks,
7290
        "hypervisor": instance.hypervisor,
7291
        "network_port": instance.network_port,
7292
        "hv_instance": instance.hvparams,
7293
        "hv_actual": cluster.FillHV(instance),
7294
        "be_instance": instance.beparams,
7295
        "be_actual": cluster.FillBE(instance),
7296
        "serial_no": instance.serial_no,
7297
        "mtime": instance.mtime,
7298
        "ctime": instance.ctime,
7299
        "uuid": instance.uuid,
7300
        }
7301

    
7302
      result[instance.name] = idict
7303

    
7304
    return result
7305

    
7306

    
7307
class LUSetInstanceParams(LogicalUnit):
7308
  """Modifies an instances's parameters.
7309

7310
  """
7311
  HPATH = "instance-modify"
7312
  HTYPE = constants.HTYPE_INSTANCE
7313
  _OP_REQP = ["instance_name"]
7314
  REQ_BGL = False
7315

    
7316
  def CheckArguments(self):
7317
    if not hasattr(self.op, 'nics'):
7318
      self.op.nics = []
7319
    if not hasattr(self.op, 'disks'):
7320
      self.op.disks = []
7321
    if not hasattr(self.op, 'beparams'):
7322
      self.op.beparams = {}
7323
    if not hasattr(self.op, 'hvparams'):
7324
      self.op.hvparams = {}
7325
    self.op.force = getattr(self.op, "force", False)
7326
    if not (self.op.nics or self.op.disks or
7327
            self.op.hvparams or self.op.beparams):
7328
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
7329

    
7330
    # Disk validation
7331
    disk_addremove = 0
7332
    for disk_op, disk_dict in self.op.disks:
7333
      if disk_op == constants.DDM_REMOVE:
7334
        disk_addremove += 1
7335
        continue
7336
      elif disk_op == constants.DDM_ADD:
7337
        disk_addremove += 1
7338
      else:
7339
        if not isinstance(disk_op, int):
7340
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
7341
        if not isinstance(disk_dict, dict):
7342
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
7343
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7344

    
7345
      if disk_op == constants.DDM_ADD:
7346
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
7347
        if mode not in constants.DISK_ACCESS_SET:
7348
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
7349
                                     errors.ECODE_INVAL)
7350
        size = disk_dict.get('size', None)
7351
        if size is None:
7352
          raise errors.OpPrereqError("Required disk parameter size missing",
7353
                                     errors.ECODE_INVAL)
7354
        try:
7355
          size = int(size)
7356
        except ValueError, err:
7357
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
7358
                                     str(err), errors.ECODE_INVAL)
7359
        disk_dict['size'] = size
7360
      else:
7361
        # modification of disk
7362
        if 'size' in disk_dict:
7363
          raise errors.OpPrereqError("Disk size change not possible, use"
7364
                                     " grow-disk", errors.ECODE_INVAL)
7365

    
7366
    if disk_addremove > 1:
7367
      raise errors.OpPrereqError("Only one disk add or remove operation"
7368
                                 " supported at a time", errors.ECODE_INVAL)
7369

    
7370
    # NIC validation
7371
    nic_addremove = 0
7372
    for nic_op, nic_dict in self.op.nics:
7373
      if nic_op == constants.DDM_REMOVE:
7374
        nic_addremove += 1
7375
        continue
7376
      elif nic_op == constants.DDM_ADD:
7377
        nic_addremove += 1
7378
      else:
7379
        if not isinstance(nic_op, int):
7380
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
7381
        if not isinstance(nic_dict, dict):
7382
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
7383
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7384

    
7385
      # nic_dict should be a dict
7386
      nic_ip = nic_dict.get('ip', None)
7387
      if nic_ip is not None:
7388
        if nic_ip.lower() == constants.VALUE_NONE:
7389
          nic_dict['ip'] = None
7390
        else:
7391
          if not utils.IsValidIP(nic_ip):
7392
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
7393
                                       errors.ECODE_INVAL)
7394

    
7395
      nic_bridge = nic_dict.get('bridge', None)
7396
      nic_link = nic_dict.get('link', None)
7397
      if nic_bridge and nic_link:
7398
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7399
                                   " at the same time", errors.ECODE_INVAL)
7400
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
7401
        nic_dict['bridge'] = None
7402
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
7403
        nic_dict['link'] = None
7404

    
7405
      if nic_op == constants.DDM_ADD:
7406
        nic_mac = nic_dict.get('mac', None)
7407
        if nic_mac is None:
7408
          nic_dict['mac'] = constants.VALUE_AUTO
7409

    
7410
      if 'mac' in nic_dict:
7411
        nic_mac = nic_dict['mac']
7412
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7413
          if not utils.IsValidMac(nic_mac):
7414
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac,
7415
                                       errors.ECODE_INVAL)
7416
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
7417
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
7418
                                     " modifying an existing nic",
7419
                                     errors.ECODE_INVAL)
7420

    
7421
    if nic_addremove > 1:
7422
      raise errors.OpPrereqError("Only one NIC add or remove operation"
7423
                                 " supported at a time", errors.ECODE_INVAL)
7424

    
7425
  def ExpandNames(self):
7426
    self._ExpandAndLockInstance()
7427
    self.needed_locks[locking.LEVEL_NODE] = []
7428
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7429

    
7430
  def DeclareLocks(self, level):
7431
    if level == locking.LEVEL_NODE:
7432
      self._LockInstancesNodes()
7433

    
7434
  def BuildHooksEnv(self):
7435
    """Build hooks env.
7436

7437
    This runs on the master, primary and secondaries.
7438

7439
    """
7440
    args = dict()
7441
    if constants.BE_MEMORY in self.be_new:
7442
      args['memory'] = self.be_new[constants.BE_MEMORY]
7443
    if constants.BE_VCPUS in self.be_new:
7444
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
7445
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
7446
    # information at all.
7447
    if self.op.nics:
7448
      args['nics'] = []
7449
      nic_override = dict(self.op.nics)
7450
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
7451
      for idx, nic in enumerate(self.instance.nics):
7452
        if idx in nic_override:
7453
          this_nic_override = nic_override[idx]
7454
        else:
7455
          this_nic_override = {}
7456
        if 'ip' in this_nic_override:
7457
          ip = this_nic_override['ip']
7458
        else:
7459
          ip = nic.ip
7460
        if 'mac' in this_nic_override:
7461
          mac = this_nic_override['mac']
7462
        else:
7463
          mac = nic.mac
7464
        if idx in self.nic_pnew:
7465
          nicparams = self.nic_pnew[idx]
7466
        else:
7467
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
7468
        mode = nicparams[constants.NIC_MODE]
7469
        link = nicparams[constants.NIC_LINK]
7470
        args['nics'].append((ip, mac, mode, link))
7471
      if constants.DDM_ADD in nic_override:
7472
        ip = nic_override[constants.DDM_ADD].get('ip', None)
7473
        mac = nic_override[constants.DDM_ADD]['mac']
7474
        nicparams = self.nic_pnew[constants.DDM_ADD]
7475
        mode = nicparams[constants.NIC_MODE]
7476
        link = nicparams[constants.NIC_LINK]
7477
        args['nics'].append((ip, mac, mode, link))
7478
      elif constants.DDM_REMOVE in nic_override:
7479
        del args['nics'][-1]
7480

    
7481
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
7482
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7483
    return env, nl, nl
7484

    
7485
  def _GetUpdatedParams(self, old_params, update_dict,
7486
                        default_values, parameter_types):
7487
    """Return the new params dict for the given params.
7488

7489
    @type old_params: dict
7490
    @param old_params: old parameters
7491
    @type update_dict: dict
7492
    @param update_dict: dict containing new parameter values,
7493
                        or constants.VALUE_DEFAULT to reset the
7494
                        parameter to its default value
7495
    @type default_values: dict
7496
    @param default_values: default values for the filled parameters
7497
    @type parameter_types: dict
7498
    @param parameter_types: dict mapping target dict keys to types
7499
                            in constants.ENFORCEABLE_TYPES
7500
    @rtype: (dict, dict)
7501
    @return: (new_parameters, filled_parameters)
7502

7503
    """
7504
    params_copy = copy.deepcopy(old_params)
7505
    for key, val in update_dict.iteritems():
7506
      if val == constants.VALUE_DEFAULT:
7507
        try:
7508
          del params_copy[key]
7509
        except KeyError:
7510
          pass
7511
      else:
7512
        params_copy[key] = val
7513
    utils.ForceDictType(params_copy, parameter_types)
7514
    params_filled = objects.FillDict(default_values, params_copy)
7515
    return (params_copy, params_filled)
7516

    
7517
  def CheckPrereq(self):
7518
    """Check prerequisites.
7519

7520
    This only checks the instance list against the existing names.
7521

7522
    """
7523
    self.force = self.op.force
7524

    
7525
    # checking the new params on the primary/secondary nodes
7526

    
7527
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7528
    cluster = self.cluster = self.cfg.GetClusterInfo()
7529
    assert self.instance is not None, \
7530
      "Cannot retrieve locked instance %s" % self.op.instance_name
7531
    pnode = instance.primary_node
7532
    nodelist = list(instance.all_nodes)
7533

    
7534
    # hvparams processing
7535
    if self.op.hvparams:
7536
      i_hvdict, hv_new = self._GetUpdatedParams(
7537
                             instance.hvparams, self.op.hvparams,
7538
                             cluster.hvparams[instance.hypervisor],
7539
                             constants.HVS_PARAMETER_TYPES)
7540
      # local check
7541
      hypervisor.GetHypervisor(
7542
        instance.hypervisor).CheckParameterSyntax(hv_new)
7543
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
7544
      self.hv_new = hv_new # the new actual values
7545
      self.hv_inst = i_hvdict # the new dict (without defaults)
7546
    else:
7547
      self.hv_new = self.hv_inst = {}
7548

    
7549
    # beparams processing
7550
    if self.op.beparams:
7551
      i_bedict, be_new = self._GetUpdatedParams(
7552
                             instance.beparams, self.op.beparams,
7553
                             cluster.beparams[constants.PP_DEFAULT],
7554
                             constants.BES_PARAMETER_TYPES)
7555
      self.be_new = be_new # the new actual values
7556
      self.be_inst = i_bedict # the new dict (without defaults)
7557
    else:
7558
      self.be_new = self.be_inst = {}
7559

    
7560
    self.warn = []
7561

    
7562
    if constants.BE_MEMORY in self.op.beparams and not self.force:
7563
      mem_check_list = [pnode]
7564
      if be_new[constants.BE_AUTO_BALANCE]:
7565
        # either we changed auto_balance to yes or it was from before
7566
        mem_check_list.extend(instance.secondary_nodes)
7567
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
7568
                                                  instance.hypervisor)
7569
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
7570
                                         instance.hypervisor)
7571
      pninfo = nodeinfo[pnode]
7572
      msg = pninfo.fail_msg
7573
      if msg:
7574
        # Assume the primary node is unreachable and go ahead
7575
        self.warn.append("Can't get info from primary node %s: %s" %
7576
                         (pnode,  msg))
7577
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
7578
        self.warn.append("Node data from primary node %s doesn't contain"
7579
                         " free memory information" % pnode)
7580
      elif instance_info.fail_msg:
7581
        self.warn.append("Can't get instance runtime information: %s" %
7582
                        instance_info.fail_msg)
7583
      else:
7584
        if instance_info.payload:
7585
          current_mem = int(instance_info.payload['memory'])
7586
        else:
7587
          # Assume instance not running
7588
          # (there is a slight race condition here, but it's not very probable,
7589
          # and we have no other way to check)
7590
          current_mem = 0
7591
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
7592
                    pninfo.payload['memory_free'])
7593
        if miss_mem > 0:
7594
          raise errors.OpPrereqError("This change will prevent the instance"
7595
                                     " from starting, due to %d MB of memory"
7596
                                     " missing on its primary node" % miss_mem,
7597
                                     errors.ECODE_NORES)
7598

    
7599
      if be_new[constants.BE_AUTO_BALANCE]:
7600
        for node, nres in nodeinfo.items():
7601
          if node not in instance.secondary_nodes:
7602
            continue
7603
          msg = nres.fail_msg
7604
          if msg:
7605
            self.warn.append("Can't get info from secondary node %s: %s" %
7606
                             (node, msg))
7607
          elif not isinstance(nres.payload.get('memory_free', None), int):
7608
            self.warn.append("Secondary node %s didn't return free"
7609
                             " memory information" % node)
7610
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
7611
            self.warn.append("Not enough memory to failover instance to"
7612
                             " secondary node %s" % node)
7613

    
7614
    # NIC processing
7615
    self.nic_pnew = {}
7616
    self.nic_pinst = {}
7617
    for nic_op, nic_dict in self.op.nics:
7618
      if nic_op == constants.DDM_REMOVE:
7619
        if not instance.nics:
7620
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
7621
                                     errors.ECODE_INVAL)
7622
        continue
7623
      if nic_op != constants.DDM_ADD:
7624
        # an existing nic
7625
        if nic_op < 0 or nic_op >= len(instance.nics):
7626
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
7627
                                     " are 0 to %d" %
7628
                                     (nic_op, len(instance.nics)),
7629
                                     errors.ECODE_INVAL)
7630
        old_nic_params = instance.nics[nic_op].nicparams
7631
        old_nic_ip = instance.nics[nic_op].ip
7632
      else:
7633
        old_nic_params = {}
7634
        old_nic_ip = None
7635

    
7636
      update_params_dict = dict([(key, nic_dict[key])
7637
                                 for key in constants.NICS_PARAMETERS
7638
                                 if key in nic_dict])
7639

    
7640
      if 'bridge' in nic_dict:
7641
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
7642

    
7643
      new_nic_params, new_filled_nic_params = \
7644
          self._GetUpdatedParams(old_nic_params, update_params_dict,
7645
                                 cluster.nicparams[constants.PP_DEFAULT],
7646
                                 constants.NICS_PARAMETER_TYPES)
7647
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
7648
      self.nic_pinst[nic_op] = new_nic_params
7649
      self.nic_pnew[nic_op] = new_filled_nic_params
7650
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
7651

    
7652
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
7653
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
7654
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
7655
        if msg:
7656
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
7657
          if self.force:
7658
            self.warn.append(msg)
7659
          else:
7660
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
7661
      if new_nic_mode == constants.NIC_MODE_ROUTED:
7662
        if 'ip' in nic_dict:
7663
          nic_ip = nic_dict['ip']
7664
        else:
7665
          nic_ip = old_nic_ip
7666
        if nic_ip is None:
7667
          raise errors.OpPrereqError('Cannot set the nic ip to None'
7668
                                     ' on a routed nic', errors.ECODE_INVAL)
7669
      if 'mac' in nic_dict:
7670
        nic_mac = nic_dict['mac']
7671
        if nic_mac is None:
7672
          raise errors.OpPrereqError('Cannot set the nic mac to None',
7673
                                     errors.ECODE_INVAL)
7674
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7675
          # otherwise generate the mac
7676
          nic_dict['mac'] = self.cfg.GenerateMAC()
7677
        else:
7678
          # or validate/reserve the current one
7679
          if self.cfg.IsMacInUse(nic_mac):
7680
            raise errors.OpPrereqError("MAC address %s already in use"
7681
                                       " in cluster" % nic_mac,
7682
                                       errors.ECODE_NOTUNIQUE)
7683

    
7684
    # DISK processing
7685
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
7686
      raise errors.OpPrereqError("Disk operations not supported for"
7687
                                 " diskless instances",
7688
                                 errors.ECODE_INVAL)
7689
    for disk_op, disk_dict in self.op.disks:
7690
      if disk_op == constants.DDM_REMOVE:
7691
        if len(instance.disks) == 1:
7692
          raise errors.OpPrereqError("Cannot remove the last disk of"
7693
                                     " an instance",
7694
                                     errors.ECODE_INVAL)
7695
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
7696
        ins_l = ins_l[pnode]
7697
        msg = ins_l.fail_msg
7698
        if msg:
7699
          raise errors.OpPrereqError("Can't contact node %s: %s" %
7700
                                     (pnode, msg), errors.ECODE_ENVIRON)
7701
        if instance.name in ins_l.payload:
7702
          raise errors.OpPrereqError("Instance is running, can't remove"
7703
                                     " disks.", errors.ECODE_STATE)
7704

    
7705
      if (disk_op == constants.DDM_ADD and
7706
          len(instance.nics) >= constants.MAX_DISKS):
7707
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
7708
                                   " add more" % constants.MAX_DISKS,
7709
                                   errors.ECODE_STATE)
7710
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
7711
        # an existing disk
7712
        if disk_op < 0 or disk_op >= len(instance.disks):
7713
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
7714
                                     " are 0 to %d" %
7715
                                     (disk_op, len(instance.disks)),
7716
                                     errors.ECODE_INVAL)
7717

    
7718
    return
7719

    
7720
  def Exec(self, feedback_fn):
7721
    """Modifies an instance.
7722

7723
    All parameters take effect only at the next restart of the instance.
7724

7725
    """
7726
    # Process here the warnings from CheckPrereq, as we don't have a
7727
    # feedback_fn there.
7728
    for warn in self.warn:
7729
      feedback_fn("WARNING: %s" % warn)
7730

    
7731
    result = []
7732
    instance = self.instance
7733
    cluster = self.cluster
7734
    # disk changes
7735
    for disk_op, disk_dict in self.op.disks:
7736
      if disk_op == constants.DDM_REMOVE:
7737
        # remove the last disk
7738
        device = instance.disks.pop()
7739
        device_idx = len(instance.disks)
7740
        for node, disk in device.ComputeNodeTree(instance.primary_node):
7741
          self.cfg.SetDiskID(disk, node)
7742
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
7743
          if msg:
7744
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
7745
                            " continuing anyway", device_idx, node, msg)
7746
        result.append(("disk/%d" % device_idx, "remove"))
7747
      elif disk_op == constants.DDM_ADD:
7748
        # add a new disk
7749
        if instance.disk_template == constants.DT_FILE:
7750
          file_driver, file_path = instance.disks[0].logical_id
7751
          file_path = os.path.dirname(file_path)
7752
        else:
7753
          file_driver = file_path = None
7754
        disk_idx_base = len(instance.disks)
7755
        new_disk = _GenerateDiskTemplate(self,
7756
                                         instance.disk_template,
7757
                                         instance.name, instance.primary_node,
7758
                                         instance.secondary_nodes,
7759
                                         [disk_dict],
7760
                                         file_path,
7761
                                         file_driver,
7762
                                         disk_idx_base)[0]
7763
        instance.disks.append(new_disk)
7764
        info = _GetInstanceInfoText(instance)
7765

    
7766
        logging.info("Creating volume %s for instance %s",
7767
                     new_disk.iv_name, instance.name)
7768
        # Note: this needs to be kept in sync with _CreateDisks
7769
        #HARDCODE
7770
        for node in instance.all_nodes:
7771
          f_create = node == instance.primary_node
7772
          try:
7773
            _CreateBlockDev(self, node, instance, new_disk,
7774
                            f_create, info, f_create)
7775
          except errors.OpExecError, err:
7776
            self.LogWarning("Failed to create volume %s (%s) on"
7777
                            " node %s: %s",
7778
                            new_disk.iv_name, new_disk, node, err)
7779
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
7780
                       (new_disk.size, new_disk.mode)))
7781
      else:
7782
        # change a given disk
7783
        instance.disks[disk_op].mode = disk_dict['mode']
7784
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
7785
    # NIC changes
7786
    for nic_op, nic_dict in self.op.nics:
7787
      if nic_op == constants.DDM_REMOVE:
7788
        # remove the last nic
7789
        del instance.nics[-1]
7790
        result.append(("nic.%d" % len(instance.nics), "remove"))
7791
      elif nic_op == constants.DDM_ADD:
7792
        # mac and bridge should be set, by now
7793
        mac = nic_dict['mac']
7794
        ip = nic_dict.get('ip', None)
7795
        nicparams = self.nic_pinst[constants.DDM_ADD]
7796
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
7797
        instance.nics.append(new_nic)
7798
        result.append(("nic.%d" % (len(instance.nics) - 1),
7799
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
7800
                       (new_nic.mac, new_nic.ip,
7801
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
7802
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
7803
                       )))
7804
      else:
7805
        for key in 'mac', 'ip':
7806
          if key in nic_dict:
7807
            setattr(instance.nics[nic_op], key, nic_dict[key])
7808
        if nic_op in self.nic_pnew:
7809
          instance.nics[nic_op].nicparams = self.nic_pnew[nic_op]
7810
        for key, val in nic_dict.iteritems():
7811
          result.append(("nic.%s/%d" % (key, nic_op), val))
7812

    
7813
    # hvparams changes
7814
    if self.op.hvparams:
7815
      instance.hvparams = self.hv_inst
7816
      for key, val in self.op.hvparams.iteritems():
7817
        result.append(("hv/%s" % key, val))
7818

    
7819
    # beparams changes
7820
    if self.op.beparams:
7821
      instance.beparams = self.be_inst
7822
      for key, val in self.op.beparams.iteritems():
7823
        result.append(("be/%s" % key, val))
7824

    
7825
    self.cfg.Update(instance, feedback_fn)
7826

    
7827
    return result
7828

    
7829

    
7830
class LUQueryExports(NoHooksLU):
7831
  """Query the exports list
7832

7833
  """
7834
  _OP_REQP = ['nodes']
7835
  REQ_BGL = False
7836

    
7837
  def ExpandNames(self):
7838
    self.needed_locks = {}
7839
    self.share_locks[locking.LEVEL_NODE] = 1
7840
    if not self.op.nodes:
7841
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7842
    else:
7843
      self.needed_locks[locking.LEVEL_NODE] = \
7844
        _GetWantedNodes(self, self.op.nodes)
7845

    
7846
  def CheckPrereq(self):
7847
    """Check prerequisites.
7848

7849
    """
7850
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
7851

    
7852
  def Exec(self, feedback_fn):
7853
    """Compute the list of all the exported system images.
7854

7855
    @rtype: dict
7856
    @return: a dictionary with the structure node->(export-list)
7857
        where export-list is a list of the instances exported on
7858
        that node.
7859

7860
    """
7861
    rpcresult = self.rpc.call_export_list(self.nodes)
7862
    result = {}
7863
    for node in rpcresult:
7864
      if rpcresult[node].fail_msg:
7865
        result[node] = False
7866
      else:
7867
        result[node] = rpcresult[node].payload
7868

    
7869
    return result
7870

    
7871

    
7872
class LUExportInstance(LogicalUnit):
7873
  """Export an instance to an image in the cluster.
7874

7875
  """
7876
  HPATH = "instance-export"
7877
  HTYPE = constants.HTYPE_INSTANCE
7878
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
7879
  REQ_BGL = False
7880

    
7881
  def CheckArguments(self):
7882
    """Check the arguments.
7883

7884
    """
7885
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
7886
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
7887

    
7888
  def ExpandNames(self):
7889
    self._ExpandAndLockInstance()
7890
    # FIXME: lock only instance primary and destination node
7891
    #
7892
    # Sad but true, for now we have do lock all nodes, as we don't know where
7893
    # the previous export might be, and and in this LU we search for it and
7894
    # remove it from its current node. In the future we could fix this by:
7895
    #  - making a tasklet to search (share-lock all), then create the new one,
7896
    #    then one to remove, after
7897
    #  - removing the removal operation altogether
7898
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7899

    
7900
  def DeclareLocks(self, level):
7901
    """Last minute lock declaration."""
7902
    # All nodes are locked anyway, so nothing to do here.
7903

    
7904
  def BuildHooksEnv(self):
7905
    """Build hooks env.
7906

7907
    This will run on the master, primary node and target node.
7908

7909
    """
7910
    env = {
7911
      "EXPORT_NODE": self.op.target_node,
7912
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
7913
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
7914
      }
7915
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7916
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
7917
          self.op.target_node]
7918
    return env, nl, nl
7919

    
7920
  def CheckPrereq(self):
7921
    """Check prerequisites.
7922

7923
    This checks that the instance and node names are valid.
7924

7925
    """
7926
    instance_name = self.op.instance_name
7927
    self.instance = self.cfg.GetInstanceInfo(instance_name)
7928
    assert self.instance is not None, \
7929
          "Cannot retrieve locked instance %s" % self.op.instance_name
7930
    _CheckNodeOnline(self, self.instance.primary_node)
7931

    
7932
    self.dst_node = self.cfg.GetNodeInfo(
7933
      self.cfg.ExpandNodeName(self.op.target_node))
7934

    
7935
    if self.dst_node is None:
7936
      # This is wrong node name, not a non-locked node
7937
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node,
7938
                                 errors.ECODE_NOENT)
7939
    _CheckNodeOnline(self, self.dst_node.name)
7940
    _CheckNodeNotDrained(self, self.dst_node.name)
7941

    
7942
    # instance disk type verification
7943
    for disk in self.instance.disks:
7944
      if disk.dev_type == constants.LD_FILE:
7945
        raise errors.OpPrereqError("Export not supported for instances with"
7946
                                   " file-based disks", errors.ECODE_INVAL)
7947

    
7948
  def Exec(self, feedback_fn):
7949
    """Export an instance to an image in the cluster.
7950

7951
    """
7952
    instance = self.instance
7953
    dst_node = self.dst_node
7954
    src_node = instance.primary_node
7955

    
7956
    if self.op.shutdown:
7957
      # shutdown the instance, but not the disks
7958
      feedback_fn("Shutting down instance %s" % instance.name)
7959
      result = self.rpc.call_instance_shutdown(src_node, instance,
7960
                                               self.shutdown_timeout)
7961
      result.Raise("Could not shutdown instance %s on"
7962
                   " node %s" % (instance.name, src_node))
7963

    
7964
    vgname = self.cfg.GetVGName()
7965

    
7966
    snap_disks = []
7967

    
7968
    # set the disks ID correctly since call_instance_start needs the
7969
    # correct drbd minor to create the symlinks
7970
    for disk in instance.disks:
7971
      self.cfg.SetDiskID(disk, src_node)
7972

    
7973
    activate_disks = (not instance.admin_up)
7974

    
7975
    if activate_disks:
7976
      # Activate the instance disks if we'exporting a stopped instance
7977
      feedback_fn("Activating disks for %s" % instance.name)
7978
      _StartInstanceDisks(self, instance, None)
7979

    
7980
    try:
7981
      # per-disk results
7982
      dresults = []
7983
      try:
7984
        for idx, disk in enumerate(instance.disks):
7985
          feedback_fn("Creating a snapshot of disk/%s on node %s" %
7986
                      (idx, src_node))
7987

    
7988
          # result.payload will be a snapshot of an lvm leaf of the one we
7989
          # passed
7990
          result = self.rpc.call_blockdev_snapshot(src_node, disk)
7991
          msg = result.fail_msg
7992
          if msg:
7993
            self.LogWarning("Could not snapshot disk/%s on node %s: %s",
7994
                            idx, src_node, msg)
7995
            snap_disks.append(False)
7996
          else:
7997
            disk_id = (vgname, result.payload)
7998
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
7999
                                   logical_id=disk_id, physical_id=disk_id,
8000
                                   iv_name=disk.iv_name)
8001
            snap_disks.append(new_dev)
8002

    
8003
      finally:
8004
        if self.op.shutdown and instance.admin_up:
8005
          feedback_fn("Starting instance %s" % instance.name)
8006
          result = self.rpc.call_instance_start(src_node, instance, None, None)
8007
          msg = result.fail_msg
8008
          if msg:
8009
            _ShutdownInstanceDisks(self, instance)
8010
            raise errors.OpExecError("Could not start instance: %s" % msg)
8011

    
8012
      # TODO: check for size
8013

    
8014
      cluster_name = self.cfg.GetClusterName()
8015
      for idx, dev in enumerate(snap_disks):
8016
        feedback_fn("Exporting snapshot %s from %s to %s" %
8017
                    (idx, src_node, dst_node.name))
8018
        if dev:
8019
          result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
8020
                                                 instance, cluster_name, idx)
8021
          msg = result.fail_msg
8022
          if msg:
8023
            self.LogWarning("Could not export disk/%s from node %s to"
8024
                            " node %s: %s", idx, src_node, dst_node.name, msg)
8025
            dresults.append(False)
8026
          else:
8027
            dresults.append(True)
8028
          msg = self.rpc.call_blockdev_remove(src_node, dev).fail_msg
8029
          if msg:
8030
            self.LogWarning("Could not remove snapshot for disk/%d from node"
8031
                            " %s: %s", idx, src_node, msg)
8032
        else:
8033
          dresults.append(False)
8034

    
8035
      feedback_fn("Finalizing export on %s" % dst_node.name)
8036
      result = self.rpc.call_finalize_export(dst_node.name, instance,
8037
                                             snap_disks)
8038
      fin_resu = True
8039
      msg = result.fail_msg
8040
      if msg:
8041
        self.LogWarning("Could not finalize export for instance %s"
8042
                        " on node %s: %s", instance.name, dst_node.name, msg)
8043
        fin_resu = False
8044

    
8045
    finally:
8046
      if activate_disks:
8047
        feedback_fn("Deactivating disks for %s" % instance.name)
8048
        _ShutdownInstanceDisks(self, instance)
8049

    
8050
    nodelist = self.cfg.GetNodeList()
8051
    nodelist.remove(dst_node.name)
8052

    
8053
    # on one-node clusters nodelist will be empty after the removal
8054
    # if we proceed the backup would be removed because OpQueryExports
8055
    # substitutes an empty list with the full cluster node list.
8056
    iname = instance.name
8057
    if nodelist:
8058
      feedback_fn("Removing old exports for instance %s" % iname)
8059
      exportlist = self.rpc.call_export_list(nodelist)
8060
      for node in exportlist:
8061
        if exportlist[node].fail_msg:
8062
          continue
8063
        if iname in exportlist[node].payload:
8064
          msg = self.rpc.call_export_remove(node, iname).fail_msg
8065
          if msg:
8066
            self.LogWarning("Could not remove older export for instance %s"
8067
                            " on node %s: %s", iname, node, msg)
8068
    return fin_resu, dresults
8069

    
8070

    
8071
class LURemoveExport(NoHooksLU):
8072
  """Remove exports related to the named instance.
8073

8074
  """
8075
  _OP_REQP = ["instance_name"]
8076
  REQ_BGL = False
8077

    
8078
  def ExpandNames(self):
8079
    self.needed_locks = {}
8080
    # We need all nodes to be locked in order for RemoveExport to work, but we
8081
    # don't need to lock the instance itself, as nothing will happen to it (and
8082
    # we can remove exports also for a removed instance)
8083
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8084

    
8085
  def CheckPrereq(self):
8086
    """Check prerequisites.
8087
    """
8088
    pass
8089

    
8090
  def Exec(self, feedback_fn):
8091
    """Remove any export.
8092

8093
    """
8094
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
8095
    # If the instance was not found we'll try with the name that was passed in.
8096
    # This will only work if it was an FQDN, though.
8097
    fqdn_warn = False
8098
    if not instance_name:
8099
      fqdn_warn = True
8100
      instance_name = self.op.instance_name
8101

    
8102
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
8103
    exportlist = self.rpc.call_export_list(locked_nodes)
8104
    found = False
8105
    for node in exportlist:
8106
      msg = exportlist[node].fail_msg
8107
      if msg:
8108
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
8109
        continue
8110
      if instance_name in exportlist[node].payload:
8111
        found = True
8112
        result = self.rpc.call_export_remove(node, instance_name)
8113
        msg = result.fail_msg
8114
        if msg:
8115
          logging.error("Could not remove export for instance %s"
8116
                        " on node %s: %s", instance_name, node, msg)
8117

    
8118
    if fqdn_warn and not found:
8119
      feedback_fn("Export not found. If trying to remove an export belonging"
8120
                  " to a deleted instance please use its Fully Qualified"
8121
                  " Domain Name.")
8122

    
8123

    
8124
class TagsLU(NoHooksLU):
8125
  """Generic tags LU.
8126

8127
  This is an abstract class which is the parent of all the other tags LUs.
8128

8129
  """
8130

    
8131
  def ExpandNames(self):
8132
    self.needed_locks = {}
8133
    if self.op.kind == constants.TAG_NODE:
8134
      name = self.cfg.ExpandNodeName(self.op.name)
8135
      if name is None:
8136
        raise errors.OpPrereqError("Invalid node name (%s)" %
8137
                                   (self.op.name,), errors.ECODE_NOENT)
8138
      self.op.name = name
8139
      self.needed_locks[locking.LEVEL_NODE] = name
8140
    elif self.op.kind == constants.TAG_INSTANCE:
8141
      name = self.cfg.ExpandInstanceName(self.op.name)
8142
      if name is None:
8143
        raise errors.OpPrereqError("Invalid instance name (%s)" %
8144
                                   (self.op.name,), errors.ECODE_NOENT)
8145
      self.op.name = name
8146
      self.needed_locks[locking.LEVEL_INSTANCE] = name
8147

    
8148
  def CheckPrereq(self):
8149
    """Check prerequisites.
8150

8151
    """
8152
    if self.op.kind == constants.TAG_CLUSTER:
8153
      self.target = self.cfg.GetClusterInfo()
8154
    elif self.op.kind == constants.TAG_NODE:
8155
      self.target = self.cfg.GetNodeInfo(self.op.name)
8156
    elif self.op.kind == constants.TAG_INSTANCE:
8157
      self.target = self.cfg.GetInstanceInfo(self.op.name)
8158
    else:
8159
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
8160
                                 str(self.op.kind), errors.ECODE_INVAL)
8161

    
8162

    
8163
class LUGetTags(TagsLU):
8164
  """Returns the tags of a given object.
8165

8166
  """
8167
  _OP_REQP = ["kind", "name"]
8168
  REQ_BGL = False
8169

    
8170
  def Exec(self, feedback_fn):
8171
    """Returns the tag list.
8172

8173
    """
8174
    return list(self.target.GetTags())
8175

    
8176

    
8177
class LUSearchTags(NoHooksLU):
8178
  """Searches the tags for a given pattern.
8179

8180
  """
8181
  _OP_REQP = ["pattern"]
8182
  REQ_BGL = False
8183

    
8184
  def ExpandNames(self):
8185
    self.needed_locks = {}
8186

    
8187
  def CheckPrereq(self):
8188
    """Check prerequisites.
8189

8190
    This checks the pattern passed for validity by compiling it.
8191

8192
    """
8193
    try:
8194
      self.re = re.compile(self.op.pattern)
8195
    except re.error, err:
8196
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
8197
                                 (self.op.pattern, err), errors.ECODE_INVAL)
8198

    
8199
  def Exec(self, feedback_fn):
8200
    """Returns the tag list.
8201

8202
    """
8203
    cfg = self.cfg
8204
    tgts = [("/cluster", cfg.GetClusterInfo())]
8205
    ilist = cfg.GetAllInstancesInfo().values()
8206
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
8207
    nlist = cfg.GetAllNodesInfo().values()
8208
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
8209
    results = []
8210
    for path, target in tgts:
8211
      for tag in target.GetTags():
8212
        if self.re.search(tag):
8213
          results.append((path, tag))
8214
    return results
8215

    
8216

    
8217
class LUAddTags(TagsLU):
8218
  """Sets a tag on a given object.
8219

8220
  """
8221
  _OP_REQP = ["kind", "name", "tags"]
8222
  REQ_BGL = False
8223

    
8224
  def CheckPrereq(self):
8225
    """Check prerequisites.
8226

8227
    This checks the type and length of the tag name and value.
8228

8229
    """
8230
    TagsLU.CheckPrereq(self)
8231
    for tag in self.op.tags:
8232
      objects.TaggableObject.ValidateTag(tag)
8233

    
8234
  def Exec(self, feedback_fn):
8235
    """Sets the tag.
8236

8237
    """
8238
    try:
8239
      for tag in self.op.tags:
8240
        self.target.AddTag(tag)
8241
    except errors.TagError, err:
8242
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
8243
    self.cfg.Update(self.target, feedback_fn)
8244

    
8245

    
8246
class LUDelTags(TagsLU):
8247
  """Delete a list of tags from a given object.
8248

8249
  """
8250
  _OP_REQP = ["kind", "name", "tags"]
8251
  REQ_BGL = False
8252

    
8253
  def CheckPrereq(self):
8254
    """Check prerequisites.
8255

8256
    This checks that we have the given tag.
8257

8258
    """
8259
    TagsLU.CheckPrereq(self)
8260
    for tag in self.op.tags:
8261
      objects.TaggableObject.ValidateTag(tag)
8262
    del_tags = frozenset(self.op.tags)
8263
    cur_tags = self.target.GetTags()
8264
    if not del_tags <= cur_tags:
8265
      diff_tags = del_tags - cur_tags
8266
      diff_names = ["'%s'" % tag for tag in diff_tags]
8267
      diff_names.sort()
8268
      raise errors.OpPrereqError("Tag(s) %s not found" %
8269
                                 (",".join(diff_names)), errors.ECODE_NOENT)
8270

    
8271
  def Exec(self, feedback_fn):
8272
    """Remove the tag from the object.
8273

8274
    """
8275
    for tag in self.op.tags:
8276
      self.target.RemoveTag(tag)
8277
    self.cfg.Update(self.target, feedback_fn)
8278

    
8279

    
8280
class LUTestDelay(NoHooksLU):
8281
  """Sleep for a specified amount of time.
8282

8283
  This LU sleeps on the master and/or nodes for a specified amount of
8284
  time.
8285

8286
  """
8287
  _OP_REQP = ["duration", "on_master", "on_nodes"]
8288
  REQ_BGL = False
8289

    
8290
  def ExpandNames(self):
8291
    """Expand names and set required locks.
8292

8293
    This expands the node list, if any.
8294

8295
    """
8296
    self.needed_locks = {}
8297
    if self.op.on_nodes:
8298
      # _GetWantedNodes can be used here, but is not always appropriate to use
8299
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
8300
      # more information.
8301
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
8302
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
8303

    
8304
  def CheckPrereq(self):
8305
    """Check prerequisites.
8306

8307
    """
8308

    
8309
  def Exec(self, feedback_fn):
8310
    """Do the actual sleep.
8311

8312
    """
8313
    if self.op.on_master:
8314
      if not utils.TestDelay(self.op.duration):
8315
        raise errors.OpExecError("Error during master delay test")
8316
    if self.op.on_nodes:
8317
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
8318
      for node, node_result in result.items():
8319
        node_result.Raise("Failure during rpc call to node %s" % node)
8320

    
8321

    
8322
class IAllocator(object):
8323
  """IAllocator framework.
8324

8325
  An IAllocator instance has three sets of attributes:
8326
    - cfg that is needed to query the cluster
8327
    - input data (all members of the _KEYS class attribute are required)
8328
    - four buffer attributes (in|out_data|text), that represent the
8329
      input (to the external script) in text and data structure format,
8330
      and the output from it, again in two formats
8331
    - the result variables from the script (success, info, nodes) for
8332
      easy usage
8333

8334
  """
8335
  _ALLO_KEYS = [
8336
    "mem_size", "disks", "disk_template",
8337
    "os", "tags", "nics", "vcpus", "hypervisor",
8338
    ]
8339
  _RELO_KEYS = [
8340
    "relocate_from",
8341
    ]
8342

    
8343
  def __init__(self, cfg, rpc, mode, name, **kwargs):
8344
    self.cfg = cfg
8345
    self.rpc = rpc
8346
    # init buffer variables
8347
    self.in_text = self.out_text = self.in_data = self.out_data = None
8348
    # init all input fields so that pylint is happy
8349
    self.mode = mode
8350
    self.name = name
8351
    self.mem_size = self.disks = self.disk_template = None
8352
    self.os = self.tags = self.nics = self.vcpus = None
8353
    self.hypervisor = None
8354
    self.relocate_from = None
8355
    # computed fields
8356
    self.required_nodes = None
8357
    # init result fields
8358
    self.success = self.info = self.nodes = None
8359
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8360
      keyset = self._ALLO_KEYS
8361
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8362
      keyset = self._RELO_KEYS
8363
    else:
8364
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
8365
                                   " IAllocator" % self.mode)
8366
    for key in kwargs:
8367
      if key not in keyset:
8368
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
8369
                                     " IAllocator" % key)
8370
      setattr(self, key, kwargs[key])
8371
    for key in keyset:
8372
      if key not in kwargs:
8373
        raise errors.ProgrammerError("Missing input parameter '%s' to"
8374
                                     " IAllocator" % key)
8375
    self._BuildInputData()
8376

    
8377
  def _ComputeClusterData(self):
8378
    """Compute the generic allocator input data.
8379

8380
    This is the data that is independent of the actual operation.
8381

8382
    """
8383
    cfg = self.cfg
8384
    cluster_info = cfg.GetClusterInfo()
8385
    # cluster data
8386
    data = {
8387
      "version": constants.IALLOCATOR_VERSION,
8388
      "cluster_name": cfg.GetClusterName(),
8389
      "cluster_tags": list(cluster_info.GetTags()),
8390
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
8391
      # we don't have job IDs
8392
      }
8393
    iinfo = cfg.GetAllInstancesInfo().values()
8394
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
8395

    
8396
    # node data
8397
    node_results = {}
8398
    node_list = cfg.GetNodeList()
8399

    
8400
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8401
      hypervisor_name = self.hypervisor
8402
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8403
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
8404

    
8405
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
8406
                                        hypervisor_name)
8407
    node_iinfo = \
8408
      self.rpc.call_all_instances_info(node_list,
8409
                                       cluster_info.enabled_hypervisors)
8410
    for nname, nresult in node_data.items():
8411
      # first fill in static (config-based) values
8412
      ninfo = cfg.GetNodeInfo(nname)
8413
      pnr = {
8414
        "tags": list(ninfo.GetTags()),
8415
        "primary_ip": ninfo.primary_ip,
8416
        "secondary_ip": ninfo.secondary_ip,
8417
        "offline": ninfo.offline,
8418
        "drained": ninfo.drained,
8419
        "master_candidate": ninfo.master_candidate,
8420
        }
8421

    
8422
      if not (ninfo.offline or ninfo.drained):
8423
        nresult.Raise("Can't get data for node %s" % nname)
8424
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
8425
                                nname)
8426
        remote_info = nresult.payload
8427

    
8428
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
8429
                     'vg_size', 'vg_free', 'cpu_total']:
8430
          if attr not in remote_info:
8431
            raise errors.OpExecError("Node '%s' didn't return attribute"
8432
                                     " '%s'" % (nname, attr))
8433
          if not isinstance(remote_info[attr], int):
8434
            raise errors.OpExecError("Node '%s' returned invalid value"
8435
                                     " for '%s': %s" %
8436
                                     (nname, attr, remote_info[attr]))
8437
        # compute memory used by primary instances
8438
        i_p_mem = i_p_up_mem = 0
8439
        for iinfo, beinfo in i_list:
8440
          if iinfo.primary_node == nname:
8441
            i_p_mem += beinfo[constants.BE_MEMORY]
8442
            if iinfo.name not in node_iinfo[nname].payload:
8443
              i_used_mem = 0
8444
            else:
8445
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
8446
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
8447
            remote_info['memory_free'] -= max(0, i_mem_diff)
8448

    
8449
            if iinfo.admin_up:
8450
              i_p_up_mem += beinfo[constants.BE_MEMORY]
8451

    
8452
        # compute memory used by instances
8453
        pnr_dyn = {
8454
          "total_memory": remote_info['memory_total'],
8455
          "reserved_memory": remote_info['memory_dom0'],
8456
          "free_memory": remote_info['memory_free'],
8457
          "total_disk": remote_info['vg_size'],
8458
          "free_disk": remote_info['vg_free'],
8459
          "total_cpus": remote_info['cpu_total'],
8460
          "i_pri_memory": i_p_mem,
8461
          "i_pri_up_memory": i_p_up_mem,
8462
          }
8463
        pnr.update(pnr_dyn)
8464

    
8465
      node_results[nname] = pnr
8466
    data["nodes"] = node_results
8467

    
8468
    # instance data
8469
    instance_data = {}
8470
    for iinfo, beinfo in i_list:
8471
      nic_data = []
8472
      for nic in iinfo.nics:
8473
        filled_params = objects.FillDict(
8474
            cluster_info.nicparams[constants.PP_DEFAULT],
8475
            nic.nicparams)
8476
        nic_dict = {"mac": nic.mac,
8477
                    "ip": nic.ip,
8478
                    "mode": filled_params[constants.NIC_MODE],
8479
                    "link": filled_params[constants.NIC_LINK],
8480
                   }
8481
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
8482
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
8483
        nic_data.append(nic_dict)
8484
      pir = {
8485
        "tags": list(iinfo.GetTags()),
8486
        "admin_up": iinfo.admin_up,
8487
        "vcpus": beinfo[constants.BE_VCPUS],
8488
        "memory": beinfo[constants.BE_MEMORY],
8489
        "os": iinfo.os,
8490
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
8491
        "nics": nic_data,
8492
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
8493
        "disk_template": iinfo.disk_template,
8494
        "hypervisor": iinfo.hypervisor,
8495
        }
8496
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
8497
                                                 pir["disks"])
8498
      instance_data[iinfo.name] = pir
8499

    
8500
    data["instances"] = instance_data
8501

    
8502
    self.in_data = data
8503

    
8504
  def _AddNewInstance(self):
8505
    """Add new instance data to allocator structure.
8506

8507
    This in combination with _AllocatorGetClusterData will create the
8508
    correct structure needed as input for the allocator.
8509

8510
    The checks for the completeness of the opcode must have already been
8511
    done.
8512

8513
    """
8514
    data = self.in_data
8515

    
8516
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
8517

    
8518
    if self.disk_template in constants.DTS_NET_MIRROR:
8519
      self.required_nodes = 2
8520
    else:
8521
      self.required_nodes = 1
8522
    request = {
8523
      "type": "allocate",
8524
      "name": self.name,
8525
      "disk_template": self.disk_template,
8526
      "tags": self.tags,
8527
      "os": self.os,
8528
      "vcpus": self.vcpus,
8529
      "memory": self.mem_size,
8530
      "disks": self.disks,
8531
      "disk_space_total": disk_space,
8532
      "nics": self.nics,
8533
      "required_nodes": self.required_nodes,
8534
      }
8535
    data["request"] = request
8536

    
8537
  def _AddRelocateInstance(self):
8538
    """Add relocate instance data to allocator structure.
8539

8540
    This in combination with _IAllocatorGetClusterData will create the
8541
    correct structure needed as input for the allocator.
8542

8543
    The checks for the completeness of the opcode must have already been
8544
    done.
8545

8546
    """
8547
    instance = self.cfg.GetInstanceInfo(self.name)
8548
    if instance is None:
8549
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
8550
                                   " IAllocator" % self.name)
8551

    
8552
    if instance.disk_template not in constants.DTS_NET_MIRROR:
8553
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
8554
                                 errors.ECODE_INVAL)
8555

    
8556
    if len(instance.secondary_nodes) != 1:
8557
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
8558
                                 errors.ECODE_STATE)
8559

    
8560
    self.required_nodes = 1
8561
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
8562
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
8563

    
8564
    request = {
8565
      "type": "relocate",
8566
      "name": self.name,
8567
      "disk_space_total": disk_space,
8568
      "required_nodes": self.required_nodes,
8569
      "relocate_from": self.relocate_from,
8570
      }
8571
    self.in_data["request"] = request
8572

    
8573
  def _BuildInputData(self):
8574
    """Build input data structures.
8575

8576
    """
8577
    self._ComputeClusterData()
8578

    
8579
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8580
      self._AddNewInstance()
8581
    else:
8582
      self._AddRelocateInstance()
8583

    
8584
    self.in_text = serializer.Dump(self.in_data)
8585

    
8586
  def Run(self, name, validate=True, call_fn=None):
8587
    """Run an instance allocator and return the results.
8588

8589
    """
8590
    if call_fn is None:
8591
      call_fn = self.rpc.call_iallocator_runner
8592

    
8593
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
8594
    result.Raise("Failure while running the iallocator script")
8595

    
8596
    self.out_text = result.payload
8597
    if validate:
8598
      self._ValidateResult()
8599

    
8600
  def _ValidateResult(self):
8601
    """Process the allocator results.
8602

8603
    This will process and if successful save the result in
8604
    self.out_data and the other parameters.
8605

8606
    """
8607
    try:
8608
      rdict = serializer.Load(self.out_text)
8609
    except Exception, err:
8610
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
8611

    
8612
    if not isinstance(rdict, dict):
8613
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
8614

    
8615
    for key in "success", "info", "nodes":
8616
      if key not in rdict:
8617
        raise errors.OpExecError("Can't parse iallocator results:"
8618
                                 " missing key '%s'" % key)
8619
      setattr(self, key, rdict[key])
8620

    
8621
    if not isinstance(rdict["nodes"], list):
8622
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
8623
                               " is not a list")
8624
    self.out_data = rdict
8625

    
8626

    
8627
class LUTestAllocator(NoHooksLU):
8628
  """Run allocator tests.
8629

8630
  This LU runs the allocator tests
8631

8632
  """
8633
  _OP_REQP = ["direction", "mode", "name"]
8634

    
8635
  def CheckPrereq(self):
8636
    """Check prerequisites.
8637

8638
    This checks the opcode parameters depending on the director and mode test.
8639

8640
    """
8641
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8642
      for attr in ["name", "mem_size", "disks", "disk_template",
8643
                   "os", "tags", "nics", "vcpus"]:
8644
        if not hasattr(self.op, attr):
8645
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
8646
                                     attr, errors.ECODE_INVAL)
8647
      iname = self.cfg.ExpandInstanceName(self.op.name)
8648
      if iname is not None:
8649
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
8650
                                   iname, errors.ECODE_EXISTS)
8651
      if not isinstance(self.op.nics, list):
8652
        raise errors.OpPrereqError("Invalid parameter 'nics'",
8653
                                   errors.ECODE_INVAL)
8654
      for row in self.op.nics:
8655
        if (not isinstance(row, dict) or
8656
            "mac" not in row or
8657
            "ip" not in row or
8658
            "bridge" not in row):
8659
          raise errors.OpPrereqError("Invalid contents of the 'nics'"
8660
                                     " parameter", errors.ECODE_INVAL)
8661
      if not isinstance(self.op.disks, list):
8662
        raise errors.OpPrereqError("Invalid parameter 'disks'",
8663
                                   errors.ECODE_INVAL)
8664
      for row in self.op.disks:
8665
        if (not isinstance(row, dict) or
8666
            "size" not in row or
8667
            not isinstance(row["size"], int) or
8668
            "mode" not in row or
8669
            row["mode"] not in ['r', 'w']):
8670
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
8671
                                     " parameter", errors.ECODE_INVAL)
8672
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
8673
        self.op.hypervisor = self.cfg.GetHypervisorType()
8674
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
8675
      if not hasattr(self.op, "name"):
8676
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input",
8677
                                   errors.ECODE_INVAL)
8678
      fname = self.cfg.ExpandInstanceName(self.op.name)
8679
      if fname is None:
8680
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
8681
                                   self.op.name, errors.ECODE_NOENT)
8682
      self.op.name = fname
8683
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
8684
    else:
8685
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
8686
                                 self.op.mode, errors.ECODE_INVAL)
8687

    
8688
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
8689
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
8690
        raise errors.OpPrereqError("Missing allocator name",
8691
                                   errors.ECODE_INVAL)
8692
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
8693
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
8694
                                 self.op.direction, errors.ECODE_INVAL)
8695

    
8696
  def Exec(self, feedback_fn):
8697
    """Run the allocator test.
8698

8699
    """
8700
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8701
      ial = IAllocator(self.cfg, self.rpc,
8702
                       mode=self.op.mode,
8703
                       name=self.op.name,
8704
                       mem_size=self.op.mem_size,
8705
                       disks=self.op.disks,
8706
                       disk_template=self.op.disk_template,
8707
                       os=self.op.os,
8708
                       tags=self.op.tags,
8709
                       nics=self.op.nics,
8710
                       vcpus=self.op.vcpus,
8711
                       hypervisor=self.op.hypervisor,
8712
                       )
8713
    else:
8714
      ial = IAllocator(self.cfg, self.rpc,
8715
                       mode=self.op.mode,
8716
                       name=self.op.name,
8717
                       relocate_from=list(self.relocate_from),
8718
                       )
8719

    
8720
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
8721
      result = ial.in_text
8722
    else:
8723
      ial.Run(self.op.allocator, validate=False)
8724
      result = ial.out_text
8725
    return result