Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ b98bf262

History | View | Annotate | Download (318.9 kB)

1
#
2
#
3

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

    
21

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

    
24
# pylint: disable-msg=W0201
25

    
26
# W0201 since most LU attributes are defined in CheckPrereq or similar
27
# functions
28

    
29
import os
30
import os.path
31
import time
32
import re
33
import platform
34
import logging
35
import copy
36
import OpenSSL
37

    
38
from ganeti import ssh
39
from ganeti import utils
40
from ganeti import errors
41
from ganeti import hypervisor
42
from ganeti import locking
43
from ganeti import constants
44
from ganeti import objects
45
from ganeti import serializer
46
from ganeti import ssconf
47

    
48

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

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

61
  Note that all commands require root permissions.
62

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

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

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

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

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

    
104
    # Tasklets
105
    self.tasklets = None
106

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

    
113
    self.CheckArguments()
114

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

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

    
123
  ssh = property(fget=__GetSSH)
124

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

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

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

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

140
    """
141
    pass
142

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

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

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

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

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

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

168
    Examples::
169

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

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

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

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

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

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

207
    """
208

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

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

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

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

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

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

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

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

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

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

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

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

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

266
    """
267
    raise NotImplementedError
268

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
355
    del self.recalculate_locks[locking.LEVEL_NODE]
356

    
357

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

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

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

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

371
    This just raises an error.
372

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

    
376

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

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

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

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

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

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

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

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

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

409
    """
410
    raise NotImplementedError
411

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

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

419
    """
420
    raise NotImplementedError
421

    
422

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

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

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

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

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

    
446

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

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

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

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

    
470

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

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

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

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

    
489

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

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

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

    
503

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

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

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

    
518

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

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

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

    
531

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

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

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

    
544

    
545
def _ExpandItemName(fn, name, kind):
546
  """Expand an item name.
547

548
  @param fn: the function to use for expansion
549
  @param name: requested item name
550
  @param kind: text description ('Node' or 'Instance')
551
  @return: the resolved (full) name
552
  @raise errors.OpPrereqError: if the item is not found
553

554
  """
555
  full_name = fn(name)
556
  if full_name is None:
557
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
558
                               errors.ECODE_NOENT)
559
  return full_name
560

    
561

    
562
def _ExpandNodeName(cfg, name):
563
  """Wrapper over L{_ExpandItemName} for nodes."""
564
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
565

    
566

    
567
def _ExpandInstanceName(cfg, name):
568
  """Wrapper over L{_ExpandItemName} for instance."""
569
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
570

    
571

    
572
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
573
                          memory, vcpus, nics, disk_template, disks,
574
                          bep, hvp, hypervisor_name):
575
  """Builds instance related env variables for hooks
576

577
  This builds the hook environment from individual variables.
578

579
  @type name: string
580
  @param name: the name of the instance
581
  @type primary_node: string
582
  @param primary_node: the name of the instance's primary node
583
  @type secondary_nodes: list
584
  @param secondary_nodes: list of secondary nodes as strings
585
  @type os_type: string
586
  @param os_type: the name of the instance's OS
587
  @type status: boolean
588
  @param status: the should_run status of the instance
589
  @type memory: string
590
  @param memory: the memory size of the instance
591
  @type vcpus: string
592
  @param vcpus: the count of VCPUs the instance has
593
  @type nics: list
594
  @param nics: list of tuples (ip, mac, mode, link) representing
595
      the NICs the instance has
596
  @type disk_template: string
597
  @param disk_template: the disk template of the instance
598
  @type disks: list
599
  @param disks: the list of (size, mode) pairs
600
  @type bep: dict
601
  @param bep: the backend parameters for the instance
602
  @type hvp: dict
603
  @param hvp: the hypervisor parameters for the instance
604
  @type hypervisor_name: string
605
  @param hypervisor_name: the hypervisor for the instance
606
  @rtype: dict
607
  @return: the hook environment for this instance
608

609
  """
610
  if status:
611
    str_status = "up"
612
  else:
613
    str_status = "down"
614
  env = {
615
    "OP_TARGET": name,
616
    "INSTANCE_NAME": name,
617
    "INSTANCE_PRIMARY": primary_node,
618
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
619
    "INSTANCE_OS_TYPE": os_type,
620
    "INSTANCE_STATUS": str_status,
621
    "INSTANCE_MEMORY": memory,
622
    "INSTANCE_VCPUS": vcpus,
623
    "INSTANCE_DISK_TEMPLATE": disk_template,
624
    "INSTANCE_HYPERVISOR": hypervisor_name,
625
  }
626

    
627
  if nics:
628
    nic_count = len(nics)
629
    for idx, (ip, mac, mode, link) in enumerate(nics):
630
      if ip is None:
631
        ip = ""
632
      env["INSTANCE_NIC%d_IP" % idx] = ip
633
      env["INSTANCE_NIC%d_MAC" % idx] = mac
634
      env["INSTANCE_NIC%d_MODE" % idx] = mode
635
      env["INSTANCE_NIC%d_LINK" % idx] = link
636
      if mode == constants.NIC_MODE_BRIDGED:
637
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
638
  else:
639
    nic_count = 0
640

    
641
  env["INSTANCE_NIC_COUNT"] = nic_count
642

    
643
  if disks:
644
    disk_count = len(disks)
645
    for idx, (size, mode) in enumerate(disks):
646
      env["INSTANCE_DISK%d_SIZE" % idx] = size
647
      env["INSTANCE_DISK%d_MODE" % idx] = mode
648
  else:
649
    disk_count = 0
650

    
651
  env["INSTANCE_DISK_COUNT"] = disk_count
652

    
653
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
654
    for key, value in source.items():
655
      env["INSTANCE_%s_%s" % (kind, key)] = value
656

    
657
  return env
658

    
659

    
660
def _NICListToTuple(lu, nics):
661
  """Build a list of nic information tuples.
662

663
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
664
  value in LUQueryInstanceData.
665

666
  @type lu:  L{LogicalUnit}
667
  @param lu: the logical unit on whose behalf we execute
668
  @type nics: list of L{objects.NIC}
669
  @param nics: list of nics to convert to hooks tuples
670

671
  """
672
  hooks_nics = []
673
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
674
  for nic in nics:
675
    ip = nic.ip
676
    mac = nic.mac
677
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
678
    mode = filled_params[constants.NIC_MODE]
679
    link = filled_params[constants.NIC_LINK]
680
    hooks_nics.append((ip, mac, mode, link))
681
  return hooks_nics
682

    
683

    
684
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
685
  """Builds instance related env variables for hooks from an object.
686

687
  @type lu: L{LogicalUnit}
688
  @param lu: the logical unit on whose behalf we execute
689
  @type instance: L{objects.Instance}
690
  @param instance: the instance for which we should build the
691
      environment
692
  @type override: dict
693
  @param override: dictionary with key/values that will override
694
      our values
695
  @rtype: dict
696
  @return: the hook environment dictionary
697

698
  """
699
  cluster = lu.cfg.GetClusterInfo()
700
  bep = cluster.FillBE(instance)
701
  hvp = cluster.FillHV(instance)
702
  args = {
703
    'name': instance.name,
704
    'primary_node': instance.primary_node,
705
    'secondary_nodes': instance.secondary_nodes,
706
    'os_type': instance.os,
707
    'status': instance.admin_up,
708
    'memory': bep[constants.BE_MEMORY],
709
    'vcpus': bep[constants.BE_VCPUS],
710
    'nics': _NICListToTuple(lu, instance.nics),
711
    'disk_template': instance.disk_template,
712
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
713
    'bep': bep,
714
    'hvp': hvp,
715
    'hypervisor_name': instance.hypervisor,
716
  }
717
  if override:
718
    args.update(override)
719
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
720

    
721

    
722
def _AdjustCandidatePool(lu, exceptions):
723
  """Adjust the candidate pool after node operations.
724

725
  """
726
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
727
  if mod_list:
728
    lu.LogInfo("Promoted nodes to master candidate role: %s",
729
               utils.CommaJoin(node.name for node in mod_list))
730
    for name in mod_list:
731
      lu.context.ReaddNode(name)
732
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
733
  if mc_now > mc_max:
734
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
735
               (mc_now, mc_max))
736

    
737

    
738
def _DecideSelfPromotion(lu, exceptions=None):
739
  """Decide whether I should promote myself as a master candidate.
740

741
  """
742
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
743
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
744
  # the new node will increase mc_max with one, so:
745
  mc_should = min(mc_should + 1, cp_size)
746
  return mc_now < mc_should
747

    
748

    
749
def _CheckNicsBridgesExist(lu, target_nics, target_node,
750
                               profile=constants.PP_DEFAULT):
751
  """Check that the brigdes needed by a list of nics exist.
752

753
  """
754
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
755
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
756
                for nic in target_nics]
757
  brlist = [params[constants.NIC_LINK] for params in paramslist
758
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
759
  if brlist:
760
    result = lu.rpc.call_bridges_exist(target_node, brlist)
761
    result.Raise("Error checking bridges on destination node '%s'" %
762
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
763

    
764

    
765
def _CheckInstanceBridgesExist(lu, instance, node=None):
766
  """Check that the brigdes needed by an instance exist.
767

768
  """
769
  if node is None:
770
    node = instance.primary_node
771
  _CheckNicsBridgesExist(lu, instance.nics, node)
772

    
773

    
774
def _CheckOSVariant(os_obj, name):
775
  """Check whether an OS name conforms to the os variants specification.
776

777
  @type os_obj: L{objects.OS}
778
  @param os_obj: OS object to check
779
  @type name: string
780
  @param name: OS name passed by the user, to check for validity
781

782
  """
783
  if not os_obj.supported_variants:
784
    return
785
  try:
786
    variant = name.split("+", 1)[1]
787
  except IndexError:
788
    raise errors.OpPrereqError("OS name must include a variant",
789
                               errors.ECODE_INVAL)
790

    
791
  if variant not in os_obj.supported_variants:
792
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
793

    
794

    
795
def _GetNodeInstancesInner(cfg, fn):
796
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
797

    
798

    
799
def _GetNodeInstances(cfg, node_name):
800
  """Returns a list of all primary and secondary instances on a node.
801

802
  """
803

    
804
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
805

    
806

    
807
def _GetNodePrimaryInstances(cfg, node_name):
808
  """Returns primary instances on a node.
809

810
  """
811
  return _GetNodeInstancesInner(cfg,
812
                                lambda inst: node_name == inst.primary_node)
813

    
814

    
815
def _GetNodeSecondaryInstances(cfg, node_name):
816
  """Returns secondary instances on a node.
817

818
  """
819
  return _GetNodeInstancesInner(cfg,
820
                                lambda inst: node_name in inst.secondary_nodes)
821

    
822

    
823
def _GetStorageTypeArgs(cfg, storage_type):
824
  """Returns the arguments for a storage type.
825

826
  """
827
  # Special case for file storage
828
  if storage_type == constants.ST_FILE:
829
    # storage.FileStorage wants a list of storage directories
830
    return [[cfg.GetFileStorageDir()]]
831

    
832
  return []
833

    
834

    
835
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
836
  faulty = []
837

    
838
  for dev in instance.disks:
839
    cfg.SetDiskID(dev, node_name)
840

    
841
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
842
  result.Raise("Failed to get disk status from node %s" % node_name,
843
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
844

    
845
  for idx, bdev_status in enumerate(result.payload):
846
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
847
      faulty.append(idx)
848

    
849
  return faulty
850

    
851

    
852
def _FormatTimestamp(secs):
853
  """Formats a Unix timestamp with the local timezone.
854

855
  """
856
  return time.strftime("%F %T %Z", time.gmtime(secs))
857

    
858

    
859
class LUPostInitCluster(LogicalUnit):
860
  """Logical unit for running hooks after cluster initialization.
861

862
  """
863
  HPATH = "cluster-init"
864
  HTYPE = constants.HTYPE_CLUSTER
865
  _OP_REQP = []
866

    
867
  def BuildHooksEnv(self):
868
    """Build hooks env.
869

870
    """
871
    env = {"OP_TARGET": self.cfg.GetClusterName()}
872
    mn = self.cfg.GetMasterNode()
873
    return env, [], [mn]
874

    
875
  def CheckPrereq(self):
876
    """No prerequisites to check.
877

878
    """
879
    return True
880

    
881
  def Exec(self, feedback_fn):
882
    """Nothing to do.
883

884
    """
885
    return True
886

    
887

    
888
class LUDestroyCluster(LogicalUnit):
889
  """Logical unit for destroying the cluster.
890

891
  """
892
  HPATH = "cluster-destroy"
893
  HTYPE = constants.HTYPE_CLUSTER
894
  _OP_REQP = []
895

    
896
  def BuildHooksEnv(self):
897
    """Build hooks env.
898

899
    """
900
    env = {"OP_TARGET": self.cfg.GetClusterName()}
901
    return env, [], []
902

    
903
  def CheckPrereq(self):
904
    """Check prerequisites.
905

906
    This checks whether the cluster is empty.
907

908
    Any errors are signaled by raising errors.OpPrereqError.
909

910
    """
911
    master = self.cfg.GetMasterNode()
912

    
913
    nodelist = self.cfg.GetNodeList()
914
    if len(nodelist) != 1 or nodelist[0] != master:
915
      raise errors.OpPrereqError("There are still %d node(s) in"
916
                                 " this cluster." % (len(nodelist) - 1),
917
                                 errors.ECODE_INVAL)
918
    instancelist = self.cfg.GetInstanceList()
919
    if instancelist:
920
      raise errors.OpPrereqError("There are still %d instance(s) in"
921
                                 " this cluster." % len(instancelist),
922
                                 errors.ECODE_INVAL)
923

    
924
  def Exec(self, feedback_fn):
925
    """Destroys the cluster.
926

927
    """
928
    master = self.cfg.GetMasterNode()
929
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
930

    
931
    # Run post hooks on master node before it's removed
932
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
933
    try:
934
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
935
    except:
936
      # pylint: disable-msg=W0702
937
      self.LogWarning("Errors occurred running hooks on %s" % master)
938

    
939
    result = self.rpc.call_node_stop_master(master, False)
940
    result.Raise("Could not disable the master role")
941

    
942
    if modify_ssh_setup:
943
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
944
      utils.CreateBackup(priv_key)
945
      utils.CreateBackup(pub_key)
946

    
947
    return master
948

    
949

    
950
def _VerifyCertificateInner(filename, expired, not_before, not_after, now,
951
                            warn_days=constants.SSL_CERT_EXPIRATION_WARN,
952
                            error_days=constants.SSL_CERT_EXPIRATION_ERROR):
953
  """Verifies certificate details for LUVerifyCluster.
954

955
  """
956
  if expired:
957
    msg = "Certificate %s is expired" % filename
958

    
959
    if not_before is not None and not_after is not None:
960
      msg += (" (valid from %s to %s)" %
961
              (_FormatTimestamp(not_before),
962
               _FormatTimestamp(not_after)))
963
    elif not_before is not None:
964
      msg += " (valid from %s)" % _FormatTimestamp(not_before)
965
    elif not_after is not None:
966
      msg += " (valid until %s)" % _FormatTimestamp(not_after)
967

    
968
    return (LUVerifyCluster.ETYPE_ERROR, msg)
969

    
970
  elif not_before is not None and not_before > now:
971
    return (LUVerifyCluster.ETYPE_WARNING,
972
            "Certificate %s not yet valid (valid from %s)" %
973
            (filename, _FormatTimestamp(not_before)))
974

    
975
  elif not_after is not None:
976
    remaining_days = int((not_after - now) / (24 * 3600))
977

    
978
    msg = ("Certificate %s expires in %d days" % (filename, remaining_days))
979

    
980
    if remaining_days <= error_days:
981
      return (LUVerifyCluster.ETYPE_ERROR, msg)
982

    
983
    if remaining_days <= warn_days:
984
      return (LUVerifyCluster.ETYPE_WARNING, msg)
985

    
986
  return (None, None)
987

    
988

    
989
def _VerifyCertificate(filename):
990
  """Verifies a certificate for LUVerifyCluster.
991

992
  @type filename: string
993
  @param filename: Path to PEM file
994

995
  """
996
  try:
997
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
998
                                           utils.ReadFile(filename))
999
  except Exception, err: # pylint: disable-msg=W0703
1000
    return (LUVerifyCluster.ETYPE_ERROR,
1001
            "Failed to load X509 certificate %s: %s" % (filename, err))
1002

    
1003
  # Depending on the pyOpenSSL version, this can just return (None, None)
1004
  (not_before, not_after) = utils.GetX509CertValidity(cert)
1005

    
1006
  return _VerifyCertificateInner(filename, cert.has_expired(),
1007
                                 not_before, not_after, time.time())
1008

    
1009

    
1010
class LUVerifyCluster(LogicalUnit):
1011
  """Verifies the cluster status.
1012

1013
  """
1014
  HPATH = "cluster-verify"
1015
  HTYPE = constants.HTYPE_CLUSTER
1016
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
1017
  REQ_BGL = False
1018

    
1019
  TCLUSTER = "cluster"
1020
  TNODE = "node"
1021
  TINSTANCE = "instance"
1022

    
1023
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1024
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1025
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1026
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1027
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1028
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1029
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1030
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1031
  ENODEDRBD = (TNODE, "ENODEDRBD")
1032
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1033
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1034
  ENODEHV = (TNODE, "ENODEHV")
1035
  ENODELVM = (TNODE, "ENODELVM")
1036
  ENODEN1 = (TNODE, "ENODEN1")
1037
  ENODENET = (TNODE, "ENODENET")
1038
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1039
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1040
  ENODERPC = (TNODE, "ENODERPC")
1041
  ENODESSH = (TNODE, "ENODESSH")
1042
  ENODEVERSION = (TNODE, "ENODEVERSION")
1043
  ENODESETUP = (TNODE, "ENODESETUP")
1044
  ENODETIME = (TNODE, "ENODETIME")
1045

    
1046
  ETYPE_FIELD = "code"
1047
  ETYPE_ERROR = "ERROR"
1048
  ETYPE_WARNING = "WARNING"
1049

    
1050
  def ExpandNames(self):
1051
    self.needed_locks = {
1052
      locking.LEVEL_NODE: locking.ALL_SET,
1053
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1054
    }
1055
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1056

    
1057
  def _Error(self, ecode, item, msg, *args, **kwargs):
1058
    """Format an error message.
1059

1060
    Based on the opcode's error_codes parameter, either format a
1061
    parseable error code, or a simpler error string.
1062

1063
    This must be called only from Exec and functions called from Exec.
1064

1065
    """
1066
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1067
    itype, etxt = ecode
1068
    # first complete the msg
1069
    if args:
1070
      msg = msg % args
1071
    # then format the whole message
1072
    if self.op.error_codes:
1073
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1074
    else:
1075
      if item:
1076
        item = " " + item
1077
      else:
1078
        item = ""
1079
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1080
    # and finally report it via the feedback_fn
1081
    self._feedback_fn("  - %s" % msg)
1082

    
1083
  def _ErrorIf(self, cond, *args, **kwargs):
1084
    """Log an error message if the passed condition is True.
1085

1086
    """
1087
    cond = bool(cond) or self.op.debug_simulate_errors
1088
    if cond:
1089
      self._Error(*args, **kwargs)
1090
    # do not mark the operation as failed for WARN cases only
1091
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1092
      self.bad = self.bad or cond
1093

    
1094
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
1095
                  node_result, master_files, drbd_map, vg_name):
1096
    """Run multiple tests against a node.
1097

1098
    Test list:
1099

1100
      - compares ganeti version
1101
      - checks vg existence and size > 20G
1102
      - checks config file checksum
1103
      - checks ssh to other nodes
1104

1105
    @type nodeinfo: L{objects.Node}
1106
    @param nodeinfo: the node to check
1107
    @param file_list: required list of files
1108
    @param local_cksum: dictionary of local files and their checksums
1109
    @param node_result: the results from the node
1110
    @param master_files: list of files that only masters should have
1111
    @param drbd_map: the useddrbd minors for this node, in
1112
        form of minor: (instance, must_exist) which correspond to instances
1113
        and their running status
1114
    @param vg_name: Ganeti Volume Group (result of self.cfg.GetVGName())
1115

1116
    """
1117
    node = nodeinfo.name
1118
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1119

    
1120
    # main result, node_result should be a non-empty dict
1121
    test = not node_result or not isinstance(node_result, dict)
1122
    _ErrorIf(test, self.ENODERPC, node,
1123
                  "unable to verify node: no data returned")
1124
    if test:
1125
      return
1126

    
1127
    # compares ganeti version
1128
    local_version = constants.PROTOCOL_VERSION
1129
    remote_version = node_result.get('version', None)
1130
    test = not (remote_version and
1131
                isinstance(remote_version, (list, tuple)) and
1132
                len(remote_version) == 2)
1133
    _ErrorIf(test, self.ENODERPC, node,
1134
             "connection to node returned invalid data")
1135
    if test:
1136
      return
1137

    
1138
    test = local_version != remote_version[0]
1139
    _ErrorIf(test, self.ENODEVERSION, node,
1140
             "incompatible protocol versions: master %s,"
1141
             " node %s", local_version, remote_version[0])
1142
    if test:
1143
      return
1144

    
1145
    # node seems compatible, we can actually try to look into its results
1146

    
1147
    # full package version
1148
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1149
                  self.ENODEVERSION, node,
1150
                  "software version mismatch: master %s, node %s",
1151
                  constants.RELEASE_VERSION, remote_version[1],
1152
                  code=self.ETYPE_WARNING)
1153

    
1154
    # checks vg existence and size > 20G
1155
    if vg_name is not None:
1156
      vglist = node_result.get(constants.NV_VGLIST, None)
1157
      test = not vglist
1158
      _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1159
      if not test:
1160
        vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1161
                                              constants.MIN_VG_SIZE)
1162
        _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1163

    
1164
    # checks config file checksum
1165

    
1166
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
1167
    test = not isinstance(remote_cksum, dict)
1168
    _ErrorIf(test, self.ENODEFILECHECK, node,
1169
             "node hasn't returned file checksum data")
1170
    if not test:
1171
      for file_name in file_list:
1172
        node_is_mc = nodeinfo.master_candidate
1173
        must_have = (file_name not in master_files) or node_is_mc
1174
        # missing
1175
        test1 = file_name not in remote_cksum
1176
        # invalid checksum
1177
        test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1178
        # existing and good
1179
        test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1180
        _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1181
                 "file '%s' missing", file_name)
1182
        _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1183
                 "file '%s' has wrong checksum", file_name)
1184
        # not candidate and this is not a must-have file
1185
        _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1186
                 "file '%s' should not exist on non master"
1187
                 " candidates (and the file is outdated)", file_name)
1188
        # all good, except non-master/non-must have combination
1189
        _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1190
                 "file '%s' should not exist"
1191
                 " on non master candidates", file_name)
1192

    
1193
    # checks ssh to any
1194

    
1195
    test = constants.NV_NODELIST not in node_result
1196
    _ErrorIf(test, self.ENODESSH, node,
1197
             "node hasn't returned node ssh connectivity data")
1198
    if not test:
1199
      if node_result[constants.NV_NODELIST]:
1200
        for a_node, a_msg in node_result[constants.NV_NODELIST].items():
1201
          _ErrorIf(True, self.ENODESSH, node,
1202
                   "ssh communication with node '%s': %s", a_node, a_msg)
1203

    
1204
    test = constants.NV_NODENETTEST not in node_result
1205
    _ErrorIf(test, self.ENODENET, node,
1206
             "node hasn't returned node tcp connectivity data")
1207
    if not test:
1208
      if node_result[constants.NV_NODENETTEST]:
1209
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
1210
        for anode in nlist:
1211
          _ErrorIf(True, self.ENODENET, node,
1212
                   "tcp communication with node '%s': %s",
1213
                   anode, node_result[constants.NV_NODENETTEST][anode])
1214

    
1215
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
1216
    if isinstance(hyp_result, dict):
1217
      for hv_name, hv_result in hyp_result.iteritems():
1218
        test = hv_result is not None
1219
        _ErrorIf(test, self.ENODEHV, node,
1220
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1221

    
1222
    # check used drbd list
1223
    if vg_name is not None:
1224
      used_minors = node_result.get(constants.NV_DRBDLIST, [])
1225
      test = not isinstance(used_minors, (tuple, list))
1226
      _ErrorIf(test, self.ENODEDRBD, node,
1227
               "cannot parse drbd status file: %s", str(used_minors))
1228
      if not test:
1229
        for minor, (iname, must_exist) in drbd_map.items():
1230
          test = minor not in used_minors and must_exist
1231
          _ErrorIf(test, self.ENODEDRBD, node,
1232
                   "drbd minor %d of instance %s is not active",
1233
                   minor, iname)
1234
        for minor in used_minors:
1235
          test = minor not in drbd_map
1236
          _ErrorIf(test, self.ENODEDRBD, node,
1237
                   "unallocated drbd minor %d is in use", minor)
1238
    test = node_result.get(constants.NV_NODESETUP,
1239
                           ["Missing NODESETUP results"])
1240
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1241
             "; ".join(test))
1242

    
1243
    # check pv names
1244
    if vg_name is not None:
1245
      pvlist = node_result.get(constants.NV_PVLIST, None)
1246
      test = pvlist is None
1247
      _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1248
      if not test:
1249
        # check that ':' is not present in PV names, since it's a
1250
        # special character for lvcreate (denotes the range of PEs to
1251
        # use on the PV)
1252
        for _, pvname, owner_vg in pvlist:
1253
          test = ":" in pvname
1254
          _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1255
                   " '%s' of VG '%s'", pvname, owner_vg)
1256

    
1257
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
1258
                      node_instance, n_offline):
1259
    """Verify an instance.
1260

1261
    This function checks to see if the required block devices are
1262
    available on the instance's node.
1263

1264
    """
1265
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1266
    node_current = instanceconfig.primary_node
1267

    
1268
    node_vol_should = {}
1269
    instanceconfig.MapLVsByNode(node_vol_should)
1270

    
1271
    for node in node_vol_should:
1272
      if node in n_offline:
1273
        # ignore missing volumes on offline nodes
1274
        continue
1275
      for volume in node_vol_should[node]:
1276
        test = node not in node_vol_is or volume not in node_vol_is[node]
1277
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1278
                 "volume %s missing on node %s", volume, node)
1279

    
1280
    if instanceconfig.admin_up:
1281
      test = ((node_current not in node_instance or
1282
               not instance in node_instance[node_current]) and
1283
              node_current not in n_offline)
1284
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1285
               "instance not running on its primary node %s",
1286
               node_current)
1287

    
1288
    for node in node_instance:
1289
      if (not node == node_current):
1290
        test = instance in node_instance[node]
1291
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1292
                 "instance should not run on node %s", node)
1293

    
1294
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is):
1295
    """Verify if there are any unknown volumes in the cluster.
1296

1297
    The .os, .swap and backup volumes are ignored. All other volumes are
1298
    reported as unknown.
1299

1300
    """
1301
    for node in node_vol_is:
1302
      for volume in node_vol_is[node]:
1303
        test = (node not in node_vol_should or
1304
                volume not in node_vol_should[node])
1305
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1306
                      "volume %s is unknown", volume)
1307

    
1308
  def _VerifyOrphanInstances(self, instancelist, node_instance):
1309
    """Verify the list of running instances.
1310

1311
    This checks what instances are running but unknown to the cluster.
1312

1313
    """
1314
    for node in node_instance:
1315
      for o_inst in node_instance[node]:
1316
        test = o_inst not in instancelist
1317
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1318
                      "instance %s on node %s should not exist", o_inst, node)
1319

    
1320
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg):
1321
    """Verify N+1 Memory Resilience.
1322

1323
    Check that if one single node dies we can still start all the instances it
1324
    was primary for.
1325

1326
    """
1327
    for node, nodeinfo in node_info.iteritems():
1328
      # This code checks that every node which is now listed as secondary has
1329
      # enough memory to host all instances it is supposed to should a single
1330
      # other node in the cluster fail.
1331
      # FIXME: not ready for failover to an arbitrary node
1332
      # FIXME: does not support file-backed instances
1333
      # WARNING: we currently take into account down instances as well as up
1334
      # ones, considering that even if they're down someone might want to start
1335
      # them even in the event of a node failure.
1336
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
1337
        needed_mem = 0
1338
        for instance in instances:
1339
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1340
          if bep[constants.BE_AUTO_BALANCE]:
1341
            needed_mem += bep[constants.BE_MEMORY]
1342
        test = nodeinfo['mfree'] < needed_mem
1343
        self._ErrorIf(test, self.ENODEN1, node,
1344
                      "not enough memory on to accommodate"
1345
                      " failovers should peer node %s fail", prinode)
1346

    
1347
  def CheckPrereq(self):
1348
    """Check prerequisites.
1349

1350
    Transform the list of checks we're going to skip into a set and check that
1351
    all its members are valid.
1352

1353
    """
1354
    self.skip_set = frozenset(self.op.skip_checks)
1355
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1356
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1357
                                 errors.ECODE_INVAL)
1358

    
1359
  def BuildHooksEnv(self):
1360
    """Build hooks env.
1361

1362
    Cluster-Verify hooks just ran in the post phase and their failure makes
1363
    the output be logged in the verify output and the verification to fail.
1364

1365
    """
1366
    all_nodes = self.cfg.GetNodeList()
1367
    env = {
1368
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1369
      }
1370
    for node in self.cfg.GetAllNodesInfo().values():
1371
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1372

    
1373
    return env, [], all_nodes
1374

    
1375
  def Exec(self, feedback_fn):
1376
    """Verify integrity of cluster, performing various test on nodes.
1377

1378
    """
1379
    self.bad = False
1380
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1381
    verbose = self.op.verbose
1382
    self._feedback_fn = feedback_fn
1383
    feedback_fn("* Verifying global settings")
1384
    for msg in self.cfg.VerifyConfig():
1385
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1386

    
1387
    # Check the cluster certificates
1388
    for cert_filename in constants.ALL_CERT_FILES:
1389
      (errcode, msg) = _VerifyCertificate(cert_filename)
1390
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1391

    
1392
    vg_name = self.cfg.GetVGName()
1393
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1394
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1395
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1396
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1397
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1398
                        for iname in instancelist)
1399
    i_non_redundant = [] # Non redundant instances
1400
    i_non_a_balanced = [] # Non auto-balanced instances
1401
    n_offline = [] # List of offline nodes
1402
    n_drained = [] # List of nodes being drained
1403
    node_volume = {}
1404
    node_instance = {}
1405
    node_info = {}
1406
    instance_cfg = {}
1407

    
1408
    # FIXME: verify OS list
1409
    # do local checksums
1410
    master_files = [constants.CLUSTER_CONF_FILE]
1411

    
1412
    file_names = ssconf.SimpleStore().GetFileList()
1413
    file_names.extend(constants.ALL_CERT_FILES)
1414
    file_names.extend(master_files)
1415

    
1416
    local_checksums = utils.FingerprintFiles(file_names)
1417

    
1418
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1419
    node_verify_param = {
1420
      constants.NV_FILELIST: file_names,
1421
      constants.NV_NODELIST: [node.name for node in nodeinfo
1422
                              if not node.offline],
1423
      constants.NV_HYPERVISOR: hypervisors,
1424
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1425
                                  node.secondary_ip) for node in nodeinfo
1426
                                 if not node.offline],
1427
      constants.NV_INSTANCELIST: hypervisors,
1428
      constants.NV_VERSION: None,
1429
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1430
      constants.NV_NODESETUP: None,
1431
      constants.NV_TIME: None,
1432
      }
1433

    
1434
    if vg_name is not None:
1435
      node_verify_param[constants.NV_VGLIST] = None
1436
      node_verify_param[constants.NV_LVLIST] = vg_name
1437
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1438
      node_verify_param[constants.NV_DRBDLIST] = None
1439

    
1440
    # Due to the way our RPC system works, exact response times cannot be
1441
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
1442
    # time before and after executing the request, we can at least have a time
1443
    # window.
1444
    nvinfo_starttime = time.time()
1445
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1446
                                           self.cfg.GetClusterName())
1447
    nvinfo_endtime = time.time()
1448

    
1449
    cluster = self.cfg.GetClusterInfo()
1450
    master_node = self.cfg.GetMasterNode()
1451
    all_drbd_map = self.cfg.ComputeDRBDMap()
1452

    
1453
    feedback_fn("* Verifying node status")
1454
    for node_i in nodeinfo:
1455
      node = node_i.name
1456

    
1457
      if node_i.offline:
1458
        if verbose:
1459
          feedback_fn("* Skipping offline node %s" % (node,))
1460
        n_offline.append(node)
1461
        continue
1462

    
1463
      if node == master_node:
1464
        ntype = "master"
1465
      elif node_i.master_candidate:
1466
        ntype = "master candidate"
1467
      elif node_i.drained:
1468
        ntype = "drained"
1469
        n_drained.append(node)
1470
      else:
1471
        ntype = "regular"
1472
      if verbose:
1473
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1474

    
1475
      msg = all_nvinfo[node].fail_msg
1476
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1477
      if msg:
1478
        continue
1479

    
1480
      nresult = all_nvinfo[node].payload
1481
      node_drbd = {}
1482
      for minor, instance in all_drbd_map[node].items():
1483
        test = instance not in instanceinfo
1484
        _ErrorIf(test, self.ECLUSTERCFG, None,
1485
                 "ghost instance '%s' in temporary DRBD map", instance)
1486
          # ghost instance should not be running, but otherwise we
1487
          # don't give double warnings (both ghost instance and
1488
          # unallocated minor in use)
1489
        if test:
1490
          node_drbd[minor] = (instance, False)
1491
        else:
1492
          instance = instanceinfo[instance]
1493
          node_drbd[minor] = (instance.name, instance.admin_up)
1494

    
1495
      self._VerifyNode(node_i, file_names, local_checksums,
1496
                       nresult, master_files, node_drbd, vg_name)
1497

    
1498
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1499
      if vg_name is None:
1500
        node_volume[node] = {}
1501
      elif isinstance(lvdata, basestring):
1502
        _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1503
                 utils.SafeEncode(lvdata))
1504
        node_volume[node] = {}
1505
      elif not isinstance(lvdata, dict):
1506
        _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1507
        continue
1508
      else:
1509
        node_volume[node] = lvdata
1510

    
1511
      # node_instance
1512
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1513
      test = not isinstance(idata, list)
1514
      _ErrorIf(test, self.ENODEHV, node,
1515
               "rpc call to node failed (instancelist): %s",
1516
               utils.SafeEncode(str(idata)))
1517
      if test:
1518
        continue
1519

    
1520
      node_instance[node] = idata
1521

    
1522
      # node_info
1523
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1524
      test = not isinstance(nodeinfo, dict)
1525
      _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1526
      if test:
1527
        continue
1528

    
1529
      # Node time
1530
      ntime = nresult.get(constants.NV_TIME, None)
1531
      try:
1532
        ntime_merged = utils.MergeTime(ntime)
1533
      except (ValueError, TypeError):
1534
        _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1535

    
1536
      if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1537
        ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1538
      elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1539
        ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1540
      else:
1541
        ntime_diff = None
1542

    
1543
      _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1544
               "Node time diverges by at least %s from master node time",
1545
               ntime_diff)
1546

    
1547
      if ntime_diff is not None:
1548
        continue
1549

    
1550
      try:
1551
        node_info[node] = {
1552
          "mfree": int(nodeinfo['memory_free']),
1553
          "pinst": [],
1554
          "sinst": [],
1555
          # dictionary holding all instances this node is secondary for,
1556
          # grouped by their primary node. Each key is a cluster node, and each
1557
          # value is a list of instances which have the key as primary and the
1558
          # current node as secondary.  this is handy to calculate N+1 memory
1559
          # availability if you can only failover from a primary to its
1560
          # secondary.
1561
          "sinst-by-pnode": {},
1562
        }
1563
        # FIXME: devise a free space model for file based instances as well
1564
        if vg_name is not None:
1565
          test = (constants.NV_VGLIST not in nresult or
1566
                  vg_name not in nresult[constants.NV_VGLIST])
1567
          _ErrorIf(test, self.ENODELVM, node,
1568
                   "node didn't return data for the volume group '%s'"
1569
                   " - it is either missing or broken", vg_name)
1570
          if test:
1571
            continue
1572
          node_info[node]["dfree"] = int(nresult[constants.NV_VGLIST][vg_name])
1573
      except (ValueError, KeyError):
1574
        _ErrorIf(True, self.ENODERPC, node,
1575
                 "node returned invalid nodeinfo, check lvm/hypervisor")
1576
        continue
1577

    
1578
    node_vol_should = {}
1579

    
1580
    feedback_fn("* Verifying instance status")
1581
    for instance in instancelist:
1582
      if verbose:
1583
        feedback_fn("* Verifying instance %s" % instance)
1584
      inst_config = instanceinfo[instance]
1585
      self._VerifyInstance(instance, inst_config, node_volume,
1586
                           node_instance, n_offline)
1587
      inst_nodes_offline = []
1588

    
1589
      inst_config.MapLVsByNode(node_vol_should)
1590

    
1591
      instance_cfg[instance] = inst_config
1592

    
1593
      pnode = inst_config.primary_node
1594
      _ErrorIf(pnode not in node_info and pnode not in n_offline,
1595
               self.ENODERPC, pnode, "instance %s, connection to"
1596
               " primary node failed", instance)
1597
      if pnode in node_info:
1598
        node_info[pnode]['pinst'].append(instance)
1599

    
1600
      if pnode in n_offline:
1601
        inst_nodes_offline.append(pnode)
1602

    
1603
      # If the instance is non-redundant we cannot survive losing its primary
1604
      # node, so we are not N+1 compliant. On the other hand we have no disk
1605
      # templates with more than one secondary so that situation is not well
1606
      # supported either.
1607
      # FIXME: does not support file-backed instances
1608
      if len(inst_config.secondary_nodes) == 0:
1609
        i_non_redundant.append(instance)
1610
      _ErrorIf(len(inst_config.secondary_nodes) > 1,
1611
               self.EINSTANCELAYOUT, instance,
1612
               "instance has multiple secondary nodes", code="WARNING")
1613

    
1614
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1615
        i_non_a_balanced.append(instance)
1616

    
1617
      for snode in inst_config.secondary_nodes:
1618
        _ErrorIf(snode not in node_info and snode not in n_offline,
1619
                 self.ENODERPC, snode,
1620
                 "instance %s, connection to secondary node"
1621
                 " failed", instance)
1622

    
1623
        if snode in node_info:
1624
          node_info[snode]['sinst'].append(instance)
1625
          if pnode not in node_info[snode]['sinst-by-pnode']:
1626
            node_info[snode]['sinst-by-pnode'][pnode] = []
1627
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1628

    
1629
        if snode in n_offline:
1630
          inst_nodes_offline.append(snode)
1631

    
1632
      # warn that the instance lives on offline nodes
1633
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1634
               "instance lives on offline node(s) %s",
1635
               utils.CommaJoin(inst_nodes_offline))
1636

    
1637
    feedback_fn("* Verifying orphan volumes")
1638
    self._VerifyOrphanVolumes(node_vol_should, node_volume)
1639

    
1640
    feedback_fn("* Verifying remaining instances")
1641
    self._VerifyOrphanInstances(instancelist, node_instance)
1642

    
1643
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1644
      feedback_fn("* Verifying N+1 Memory redundancy")
1645
      self._VerifyNPlusOneMemory(node_info, instance_cfg)
1646

    
1647
    feedback_fn("* Other Notes")
1648
    if i_non_redundant:
1649
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1650
                  % len(i_non_redundant))
1651

    
1652
    if i_non_a_balanced:
1653
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1654
                  % len(i_non_a_balanced))
1655

    
1656
    if n_offline:
1657
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1658

    
1659
    if n_drained:
1660
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1661

    
1662
    return not self.bad
1663

    
1664
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1665
    """Analyze the post-hooks' result
1666

1667
    This method analyses the hook result, handles it, and sends some
1668
    nicely-formatted feedback back to the user.
1669

1670
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1671
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1672
    @param hooks_results: the results of the multi-node hooks rpc call
1673
    @param feedback_fn: function used send feedback back to the caller
1674
    @param lu_result: previous Exec result
1675
    @return: the new Exec result, based on the previous result
1676
        and hook results
1677

1678
    """
1679
    # We only really run POST phase hooks, and are only interested in
1680
    # their results
1681
    if phase == constants.HOOKS_PHASE_POST:
1682
      # Used to change hooks' output to proper indentation
1683
      indent_re = re.compile('^', re.M)
1684
      feedback_fn("* Hooks Results")
1685
      assert hooks_results, "invalid result from hooks"
1686

    
1687
      for node_name in hooks_results:
1688
        res = hooks_results[node_name]
1689
        msg = res.fail_msg
1690
        test = msg and not res.offline
1691
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1692
                      "Communication failure in hooks execution: %s", msg)
1693
        if res.offline or msg:
1694
          # No need to investigate payload if node is offline or gave an error.
1695
          # override manually lu_result here as _ErrorIf only
1696
          # overrides self.bad
1697
          lu_result = 1
1698
          continue
1699
        for script, hkr, output in res.payload:
1700
          test = hkr == constants.HKR_FAIL
1701
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1702
                        "Script %s failed, output:", script)
1703
          if test:
1704
            output = indent_re.sub('      ', output)
1705
            feedback_fn("%s" % output)
1706
            lu_result = 0
1707

    
1708
      return lu_result
1709

    
1710

    
1711
class LUVerifyDisks(NoHooksLU):
1712
  """Verifies the cluster disks status.
1713

1714
  """
1715
  _OP_REQP = []
1716
  REQ_BGL = False
1717

    
1718
  def ExpandNames(self):
1719
    self.needed_locks = {
1720
      locking.LEVEL_NODE: locking.ALL_SET,
1721
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1722
    }
1723
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1724

    
1725
  def CheckPrereq(self):
1726
    """Check prerequisites.
1727

1728
    This has no prerequisites.
1729

1730
    """
1731
    pass
1732

    
1733
  def Exec(self, feedback_fn):
1734
    """Verify integrity of cluster disks.
1735

1736
    @rtype: tuple of three items
1737
    @return: a tuple of (dict of node-to-node_error, list of instances
1738
        which need activate-disks, dict of instance: (node, volume) for
1739
        missing volumes
1740

1741
    """
1742
    result = res_nodes, res_instances, res_missing = {}, [], {}
1743

    
1744
    vg_name = self.cfg.GetVGName()
1745
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1746
    instances = [self.cfg.GetInstanceInfo(name)
1747
                 for name in self.cfg.GetInstanceList()]
1748

    
1749
    nv_dict = {}
1750
    for inst in instances:
1751
      inst_lvs = {}
1752
      if (not inst.admin_up or
1753
          inst.disk_template not in constants.DTS_NET_MIRROR):
1754
        continue
1755
      inst.MapLVsByNode(inst_lvs)
1756
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1757
      for node, vol_list in inst_lvs.iteritems():
1758
        for vol in vol_list:
1759
          nv_dict[(node, vol)] = inst
1760

    
1761
    if not nv_dict:
1762
      return result
1763

    
1764
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1765

    
1766
    for node in nodes:
1767
      # node_volume
1768
      node_res = node_lvs[node]
1769
      if node_res.offline:
1770
        continue
1771
      msg = node_res.fail_msg
1772
      if msg:
1773
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1774
        res_nodes[node] = msg
1775
        continue
1776

    
1777
      lvs = node_res.payload
1778
      for lv_name, (_, _, lv_online) in lvs.items():
1779
        inst = nv_dict.pop((node, lv_name), None)
1780
        if (not lv_online and inst is not None
1781
            and inst.name not in res_instances):
1782
          res_instances.append(inst.name)
1783

    
1784
    # any leftover items in nv_dict are missing LVs, let's arrange the
1785
    # data better
1786
    for key, inst in nv_dict.iteritems():
1787
      if inst.name not in res_missing:
1788
        res_missing[inst.name] = []
1789
      res_missing[inst.name].append(key)
1790

    
1791
    return result
1792

    
1793

    
1794
class LURepairDiskSizes(NoHooksLU):
1795
  """Verifies the cluster disks sizes.
1796

1797
  """
1798
  _OP_REQP = ["instances"]
1799
  REQ_BGL = False
1800

    
1801
  def ExpandNames(self):
1802
    if not isinstance(self.op.instances, list):
1803
      raise errors.OpPrereqError("Invalid argument type 'instances'",
1804
                                 errors.ECODE_INVAL)
1805

    
1806
    if self.op.instances:
1807
      self.wanted_names = []
1808
      for name in self.op.instances:
1809
        full_name = _ExpandInstanceName(self.cfg, name)
1810
        self.wanted_names.append(full_name)
1811
      self.needed_locks = {
1812
        locking.LEVEL_NODE: [],
1813
        locking.LEVEL_INSTANCE: self.wanted_names,
1814
        }
1815
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1816
    else:
1817
      self.wanted_names = None
1818
      self.needed_locks = {
1819
        locking.LEVEL_NODE: locking.ALL_SET,
1820
        locking.LEVEL_INSTANCE: locking.ALL_SET,
1821
        }
1822
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1823

    
1824
  def DeclareLocks(self, level):
1825
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
1826
      self._LockInstancesNodes(primary_only=True)
1827

    
1828
  def CheckPrereq(self):
1829
    """Check prerequisites.
1830

1831
    This only checks the optional instance list against the existing names.
1832

1833
    """
1834
    if self.wanted_names is None:
1835
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
1836

    
1837
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
1838
                             in self.wanted_names]
1839

    
1840
  def _EnsureChildSizes(self, disk):
1841
    """Ensure children of the disk have the needed disk size.
1842

1843
    This is valid mainly for DRBD8 and fixes an issue where the
1844
    children have smaller disk size.
1845

1846
    @param disk: an L{ganeti.objects.Disk} object
1847

1848
    """
1849
    if disk.dev_type == constants.LD_DRBD8:
1850
      assert disk.children, "Empty children for DRBD8?"
1851
      fchild = disk.children[0]
1852
      mismatch = fchild.size < disk.size
1853
      if mismatch:
1854
        self.LogInfo("Child disk has size %d, parent %d, fixing",
1855
                     fchild.size, disk.size)
1856
        fchild.size = disk.size
1857

    
1858
      # and we recurse on this child only, not on the metadev
1859
      return self._EnsureChildSizes(fchild) or mismatch
1860
    else:
1861
      return False
1862

    
1863
  def Exec(self, feedback_fn):
1864
    """Verify the size of cluster disks.
1865

1866
    """
1867
    # TODO: check child disks too
1868
    # TODO: check differences in size between primary/secondary nodes
1869
    per_node_disks = {}
1870
    for instance in self.wanted_instances:
1871
      pnode = instance.primary_node
1872
      if pnode not in per_node_disks:
1873
        per_node_disks[pnode] = []
1874
      for idx, disk in enumerate(instance.disks):
1875
        per_node_disks[pnode].append((instance, idx, disk))
1876

    
1877
    changed = []
1878
    for node, dskl in per_node_disks.items():
1879
      newl = [v[2].Copy() for v in dskl]
1880
      for dsk in newl:
1881
        self.cfg.SetDiskID(dsk, node)
1882
      result = self.rpc.call_blockdev_getsizes(node, newl)
1883
      if result.fail_msg:
1884
        self.LogWarning("Failure in blockdev_getsizes call to node"
1885
                        " %s, ignoring", node)
1886
        continue
1887
      if len(result.data) != len(dskl):
1888
        self.LogWarning("Invalid result from node %s, ignoring node results",
1889
                        node)
1890
        continue
1891
      for ((instance, idx, disk), size) in zip(dskl, result.data):
1892
        if size is None:
1893
          self.LogWarning("Disk %d of instance %s did not return size"
1894
                          " information, ignoring", idx, instance.name)
1895
          continue
1896
        if not isinstance(size, (int, long)):
1897
          self.LogWarning("Disk %d of instance %s did not return valid"
1898
                          " size information, ignoring", idx, instance.name)
1899
          continue
1900
        size = size >> 20
1901
        if size != disk.size:
1902
          self.LogInfo("Disk %d of instance %s has mismatched size,"
1903
                       " correcting: recorded %d, actual %d", idx,
1904
                       instance.name, disk.size, size)
1905
          disk.size = size
1906
          self.cfg.Update(instance, feedback_fn)
1907
          changed.append((instance.name, idx, size))
1908
        if self._EnsureChildSizes(disk):
1909
          self.cfg.Update(instance, feedback_fn)
1910
          changed.append((instance.name, idx, disk.size))
1911
    return changed
1912

    
1913

    
1914
class LURenameCluster(LogicalUnit):
1915
  """Rename the cluster.
1916

1917
  """
1918
  HPATH = "cluster-rename"
1919
  HTYPE = constants.HTYPE_CLUSTER
1920
  _OP_REQP = ["name"]
1921

    
1922
  def BuildHooksEnv(self):
1923
    """Build hooks env.
1924

1925
    """
1926
    env = {
1927
      "OP_TARGET": self.cfg.GetClusterName(),
1928
      "NEW_NAME": self.op.name,
1929
      }
1930
    mn = self.cfg.GetMasterNode()
1931
    all_nodes = self.cfg.GetNodeList()
1932
    return env, [mn], all_nodes
1933

    
1934
  def CheckPrereq(self):
1935
    """Verify that the passed name is a valid one.
1936

1937
    """
1938
    hostname = utils.GetHostInfo(self.op.name)
1939

    
1940
    new_name = hostname.name
1941
    self.ip = new_ip = hostname.ip
1942
    old_name = self.cfg.GetClusterName()
1943
    old_ip = self.cfg.GetMasterIP()
1944
    if new_name == old_name and new_ip == old_ip:
1945
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1946
                                 " cluster has changed",
1947
                                 errors.ECODE_INVAL)
1948
    if new_ip != old_ip:
1949
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1950
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1951
                                   " reachable on the network. Aborting." %
1952
                                   new_ip, errors.ECODE_NOTUNIQUE)
1953

    
1954
    self.op.name = new_name
1955

    
1956
  def Exec(self, feedback_fn):
1957
    """Rename the cluster.
1958

1959
    """
1960
    clustername = self.op.name
1961
    ip = self.ip
1962

    
1963
    # shutdown the master IP
1964
    master = self.cfg.GetMasterNode()
1965
    result = self.rpc.call_node_stop_master(master, False)
1966
    result.Raise("Could not disable the master role")
1967

    
1968
    try:
1969
      cluster = self.cfg.GetClusterInfo()
1970
      cluster.cluster_name = clustername
1971
      cluster.master_ip = ip
1972
      self.cfg.Update(cluster, feedback_fn)
1973

    
1974
      # update the known hosts file
1975
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1976
      node_list = self.cfg.GetNodeList()
1977
      try:
1978
        node_list.remove(master)
1979
      except ValueError:
1980
        pass
1981
      result = self.rpc.call_upload_file(node_list,
1982
                                         constants.SSH_KNOWN_HOSTS_FILE)
1983
      for to_node, to_result in result.iteritems():
1984
        msg = to_result.fail_msg
1985
        if msg:
1986
          msg = ("Copy of file %s to node %s failed: %s" %
1987
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
1988
          self.proc.LogWarning(msg)
1989

    
1990
    finally:
1991
      result = self.rpc.call_node_start_master(master, False, False)
1992
      msg = result.fail_msg
1993
      if msg:
1994
        self.LogWarning("Could not re-enable the master role on"
1995
                        " the master, please restart manually: %s", msg)
1996

    
1997

    
1998
def _RecursiveCheckIfLVMBased(disk):
1999
  """Check if the given disk or its children are lvm-based.
2000

2001
  @type disk: L{objects.Disk}
2002
  @param disk: the disk to check
2003
  @rtype: boolean
2004
  @return: boolean indicating whether a LD_LV dev_type was found or not
2005

2006
  """
2007
  if disk.children:
2008
    for chdisk in disk.children:
2009
      if _RecursiveCheckIfLVMBased(chdisk):
2010
        return True
2011
  return disk.dev_type == constants.LD_LV
2012

    
2013

    
2014
class LUSetClusterParams(LogicalUnit):
2015
  """Change the parameters of the cluster.
2016

2017
  """
2018
  HPATH = "cluster-modify"
2019
  HTYPE = constants.HTYPE_CLUSTER
2020
  _OP_REQP = []
2021
  REQ_BGL = False
2022

    
2023
  def CheckArguments(self):
2024
    """Check parameters
2025

2026
    """
2027
    if not hasattr(self.op, "candidate_pool_size"):
2028
      self.op.candidate_pool_size = None
2029
    if self.op.candidate_pool_size is not None:
2030
      try:
2031
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
2032
      except (ValueError, TypeError), err:
2033
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
2034
                                   str(err), errors.ECODE_INVAL)
2035
      if self.op.candidate_pool_size < 1:
2036
        raise errors.OpPrereqError("At least one master candidate needed",
2037
                                   errors.ECODE_INVAL)
2038

    
2039
  def ExpandNames(self):
2040
    # FIXME: in the future maybe other cluster params won't require checking on
2041
    # all nodes to be modified.
2042
    self.needed_locks = {
2043
      locking.LEVEL_NODE: locking.ALL_SET,
2044
    }
2045
    self.share_locks[locking.LEVEL_NODE] = 1
2046

    
2047
  def BuildHooksEnv(self):
2048
    """Build hooks env.
2049

2050
    """
2051
    env = {
2052
      "OP_TARGET": self.cfg.GetClusterName(),
2053
      "NEW_VG_NAME": self.op.vg_name,
2054
      }
2055
    mn = self.cfg.GetMasterNode()
2056
    return env, [mn], [mn]
2057

    
2058
  def CheckPrereq(self):
2059
    """Check prerequisites.
2060

2061
    This checks whether the given params don't conflict and
2062
    if the given volume group is valid.
2063

2064
    """
2065
    if self.op.vg_name is not None and not self.op.vg_name:
2066
      instances = self.cfg.GetAllInstancesInfo().values()
2067
      for inst in instances:
2068
        for disk in inst.disks:
2069
          if _RecursiveCheckIfLVMBased(disk):
2070
            raise errors.OpPrereqError("Cannot disable lvm storage while"
2071
                                       " lvm-based instances exist",
2072
                                       errors.ECODE_INVAL)
2073

    
2074
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2075

    
2076
    # if vg_name not None, checks given volume group on all nodes
2077
    if self.op.vg_name:
2078
      vglist = self.rpc.call_vg_list(node_list)
2079
      for node in node_list:
2080
        msg = vglist[node].fail_msg
2081
        if msg:
2082
          # ignoring down node
2083
          self.LogWarning("Error while gathering data on node %s"
2084
                          " (ignoring node): %s", node, msg)
2085
          continue
2086
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2087
                                              self.op.vg_name,
2088
                                              constants.MIN_VG_SIZE)
2089
        if vgstatus:
2090
          raise errors.OpPrereqError("Error on node '%s': %s" %
2091
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2092

    
2093
    self.cluster = cluster = self.cfg.GetClusterInfo()
2094
    # validate params changes
2095
    if self.op.beparams:
2096
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2097
      self.new_beparams = objects.FillDict(
2098
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
2099

    
2100
    if self.op.nicparams:
2101
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2102
      self.new_nicparams = objects.FillDict(
2103
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
2104
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2105
      nic_errors = []
2106

    
2107
      # check all instances for consistency
2108
      for instance in self.cfg.GetAllInstancesInfo().values():
2109
        for nic_idx, nic in enumerate(instance.nics):
2110
          params_copy = copy.deepcopy(nic.nicparams)
2111
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2112

    
2113
          # check parameter syntax
2114
          try:
2115
            objects.NIC.CheckParameterSyntax(params_filled)
2116
          except errors.ConfigurationError, err:
2117
            nic_errors.append("Instance %s, nic/%d: %s" %
2118
                              (instance.name, nic_idx, err))
2119

    
2120
          # if we're moving instances to routed, check that they have an ip
2121
          target_mode = params_filled[constants.NIC_MODE]
2122
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2123
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2124
                              (instance.name, nic_idx))
2125
      if nic_errors:
2126
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2127
                                   "\n".join(nic_errors))
2128

    
2129
    # hypervisor list/parameters
2130
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
2131
    if self.op.hvparams:
2132
      if not isinstance(self.op.hvparams, dict):
2133
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
2134
                                   errors.ECODE_INVAL)
2135
      for hv_name, hv_dict in self.op.hvparams.items():
2136
        if hv_name not in self.new_hvparams:
2137
          self.new_hvparams[hv_name] = hv_dict
2138
        else:
2139
          self.new_hvparams[hv_name].update(hv_dict)
2140

    
2141
    # os hypervisor parameters
2142
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2143
    if self.op.os_hvp:
2144
      if not isinstance(self.op.os_hvp, dict):
2145
        raise errors.OpPrereqError("Invalid 'os_hvp' parameter on input",
2146
                                   errors.ECODE_INVAL)
2147
      for os_name, hvs in self.op.os_hvp.items():
2148
        if not isinstance(hvs, dict):
2149
          raise errors.OpPrereqError(("Invalid 'os_hvp' parameter on"
2150
                                      " input"), errors.ECODE_INVAL)
2151
        if os_name not in self.new_os_hvp:
2152
          self.new_os_hvp[os_name] = hvs
2153
        else:
2154
          for hv_name, hv_dict in hvs.items():
2155
            if hv_name not in self.new_os_hvp[os_name]:
2156
              self.new_os_hvp[os_name][hv_name] = hv_dict
2157
            else:
2158
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2159

    
2160
    if self.op.enabled_hypervisors is not None:
2161
      self.hv_list = self.op.enabled_hypervisors
2162
      if not self.hv_list:
2163
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
2164
                                   " least one member",
2165
                                   errors.ECODE_INVAL)
2166
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
2167
      if invalid_hvs:
2168
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
2169
                                   " entries: %s" %
2170
                                   utils.CommaJoin(invalid_hvs),
2171
                                   errors.ECODE_INVAL)
2172
    else:
2173
      self.hv_list = cluster.enabled_hypervisors
2174

    
2175
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2176
      # either the enabled list has changed, or the parameters have, validate
2177
      for hv_name, hv_params in self.new_hvparams.items():
2178
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2179
            (self.op.enabled_hypervisors and
2180
             hv_name in self.op.enabled_hypervisors)):
2181
          # either this is a new hypervisor, or its parameters have changed
2182
          hv_class = hypervisor.GetHypervisor(hv_name)
2183
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2184
          hv_class.CheckParameterSyntax(hv_params)
2185
          _CheckHVParams(self, node_list, hv_name, hv_params)
2186

    
2187
    if self.op.os_hvp:
2188
      # no need to check any newly-enabled hypervisors, since the
2189
      # defaults have already been checked in the above code-block
2190
      for os_name, os_hvp in self.new_os_hvp.items():
2191
        for hv_name, hv_params in os_hvp.items():
2192
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2193
          # we need to fill in the new os_hvp on top of the actual hv_p
2194
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2195
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2196
          hv_class = hypervisor.GetHypervisor(hv_name)
2197
          hv_class.CheckParameterSyntax(new_osp)
2198
          _CheckHVParams(self, node_list, hv_name, new_osp)
2199

    
2200

    
2201
  def Exec(self, feedback_fn):
2202
    """Change the parameters of the cluster.
2203

2204
    """
2205
    if self.op.vg_name is not None:
2206
      new_volume = self.op.vg_name
2207
      if not new_volume:
2208
        new_volume = None
2209
      if new_volume != self.cfg.GetVGName():
2210
        self.cfg.SetVGName(new_volume)
2211
      else:
2212
        feedback_fn("Cluster LVM configuration already in desired"
2213
                    " state, not changing")
2214
    if self.op.hvparams:
2215
      self.cluster.hvparams = self.new_hvparams
2216
    if self.op.os_hvp:
2217
      self.cluster.os_hvp = self.new_os_hvp
2218
    if self.op.enabled_hypervisors is not None:
2219
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2220
    if self.op.beparams:
2221
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2222
    if self.op.nicparams:
2223
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2224

    
2225
    if self.op.candidate_pool_size is not None:
2226
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2227
      # we need to update the pool size here, otherwise the save will fail
2228
      _AdjustCandidatePool(self, [])
2229

    
2230
    self.cfg.Update(self.cluster, feedback_fn)
2231

    
2232

    
2233
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2234
  """Distribute additional files which are part of the cluster configuration.
2235

2236
  ConfigWriter takes care of distributing the config and ssconf files, but
2237
  there are more files which should be distributed to all nodes. This function
2238
  makes sure those are copied.
2239

2240
  @param lu: calling logical unit
2241
  @param additional_nodes: list of nodes not in the config to distribute to
2242

2243
  """
2244
  # 1. Gather target nodes
2245
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2246
  dist_nodes = lu.cfg.GetOnlineNodeList()
2247
  if additional_nodes is not None:
2248
    dist_nodes.extend(additional_nodes)
2249
  if myself.name in dist_nodes:
2250
    dist_nodes.remove(myself.name)
2251

    
2252
  # 2. Gather files to distribute
2253
  dist_files = set([constants.ETC_HOSTS,
2254
                    constants.SSH_KNOWN_HOSTS_FILE,
2255
                    constants.RAPI_CERT_FILE,
2256
                    constants.RAPI_USERS_FILE,
2257
                    constants.HMAC_CLUSTER_KEY,
2258
                   ])
2259

    
2260
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2261
  for hv_name in enabled_hypervisors:
2262
    hv_class = hypervisor.GetHypervisor(hv_name)
2263
    dist_files.update(hv_class.GetAncillaryFiles())
2264

    
2265
  # 3. Perform the files upload
2266
  for fname in dist_files:
2267
    if os.path.exists(fname):
2268
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2269
      for to_node, to_result in result.items():
2270
        msg = to_result.fail_msg
2271
        if msg:
2272
          msg = ("Copy of file %s to node %s failed: %s" %
2273
                 (fname, to_node, msg))
2274
          lu.proc.LogWarning(msg)
2275

    
2276

    
2277
class LURedistributeConfig(NoHooksLU):
2278
  """Force the redistribution of cluster configuration.
2279

2280
  This is a very simple LU.
2281

2282
  """
2283
  _OP_REQP = []
2284
  REQ_BGL = False
2285

    
2286
  def ExpandNames(self):
2287
    self.needed_locks = {
2288
      locking.LEVEL_NODE: locking.ALL_SET,
2289
    }
2290
    self.share_locks[locking.LEVEL_NODE] = 1
2291

    
2292
  def CheckPrereq(self):
2293
    """Check prerequisites.
2294

2295
    """
2296

    
2297
  def Exec(self, feedback_fn):
2298
    """Redistribute the configuration.
2299

2300
    """
2301
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2302
    _RedistributeAncillaryFiles(self)
2303

    
2304

    
2305
def _WaitForSync(lu, instance, oneshot=False):
2306
  """Sleep and poll for an instance's disk to sync.
2307

2308
  """
2309
  if not instance.disks:
2310
    return True
2311

    
2312
  if not oneshot:
2313
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2314

    
2315
  node = instance.primary_node
2316

    
2317
  for dev in instance.disks:
2318
    lu.cfg.SetDiskID(dev, node)
2319

    
2320
  # TODO: Convert to utils.Retry
2321

    
2322
  retries = 0
2323
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2324
  while True:
2325
    max_time = 0
2326
    done = True
2327
    cumul_degraded = False
2328
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2329
    msg = rstats.fail_msg
2330
    if msg:
2331
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2332
      retries += 1
2333
      if retries >= 10:
2334
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2335
                                 " aborting." % node)
2336
      time.sleep(6)
2337
      continue
2338
    rstats = rstats.payload
2339
    retries = 0
2340
    for i, mstat in enumerate(rstats):
2341
      if mstat is None:
2342
        lu.LogWarning("Can't compute data for node %s/%s",
2343
                           node, instance.disks[i].iv_name)
2344
        continue
2345

    
2346
      cumul_degraded = (cumul_degraded or
2347
                        (mstat.is_degraded and mstat.sync_percent is None))
2348
      if mstat.sync_percent is not None:
2349
        done = False
2350
        if mstat.estimated_time is not None:
2351
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2352
          max_time = mstat.estimated_time
2353
        else:
2354
          rem_time = "no time estimate"
2355
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2356
                        (instance.disks[i].iv_name, mstat.sync_percent,
2357
                         rem_time))
2358

    
2359
    # if we're done but degraded, let's do a few small retries, to
2360
    # make sure we see a stable and not transient situation; therefore
2361
    # we force restart of the loop
2362
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2363
      logging.info("Degraded disks found, %d retries left", degr_retries)
2364
      degr_retries -= 1
2365
      time.sleep(1)
2366
      continue
2367

    
2368
    if done or oneshot:
2369
      break
2370

    
2371
    time.sleep(min(60, max_time))
2372

    
2373
  if done:
2374
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2375
  return not cumul_degraded
2376

    
2377

    
2378
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2379
  """Check that mirrors are not degraded.
2380

2381
  The ldisk parameter, if True, will change the test from the
2382
  is_degraded attribute (which represents overall non-ok status for
2383
  the device(s)) to the ldisk (representing the local storage status).
2384

2385
  """
2386
  lu.cfg.SetDiskID(dev, node)
2387

    
2388
  result = True
2389

    
2390
  if on_primary or dev.AssembleOnSecondary():
2391
    rstats = lu.rpc.call_blockdev_find(node, dev)
2392
    msg = rstats.fail_msg
2393
    if msg:
2394
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2395
      result = False
2396
    elif not rstats.payload:
2397
      lu.LogWarning("Can't find disk on node %s", node)
2398
      result = False
2399
    else:
2400
      if ldisk:
2401
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2402
      else:
2403
        result = result and not rstats.payload.is_degraded
2404

    
2405
  if dev.children:
2406
    for child in dev.children:
2407
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2408

    
2409
  return result
2410

    
2411

    
2412
class LUDiagnoseOS(NoHooksLU):
2413
  """Logical unit for OS diagnose/query.
2414

2415
  """
2416
  _OP_REQP = ["output_fields", "names"]
2417
  REQ_BGL = False
2418
  _FIELDS_STATIC = utils.FieldSet()
2419
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2420
  # Fields that need calculation of global os validity
2421
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2422

    
2423
  def ExpandNames(self):
2424
    if self.op.names:
2425
      raise errors.OpPrereqError("Selective OS query not supported",
2426
                                 errors.ECODE_INVAL)
2427

    
2428
    _CheckOutputFields(static=self._FIELDS_STATIC,
2429
                       dynamic=self._FIELDS_DYNAMIC,
2430
                       selected=self.op.output_fields)
2431

    
2432
    # Lock all nodes, in shared mode
2433
    # Temporary removal of locks, should be reverted later
2434
    # TODO: reintroduce locks when they are lighter-weight
2435
    self.needed_locks = {}
2436
    #self.share_locks[locking.LEVEL_NODE] = 1
2437
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2438

    
2439
  def CheckPrereq(self):
2440
    """Check prerequisites.
2441

2442
    """
2443

    
2444
  @staticmethod
2445
  def _DiagnoseByOS(rlist):
2446
    """Remaps a per-node return list into an a per-os per-node dictionary
2447

2448
    @param rlist: a map with node names as keys and OS objects as values
2449

2450
    @rtype: dict
2451
    @return: a dictionary with osnames as keys and as value another map, with
2452
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2453

2454
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2455
                                     (/srv/..., False, "invalid api")],
2456
                           "node2": [(/srv/..., True, "")]}
2457
          }
2458

2459
    """
2460
    all_os = {}
2461
    # we build here the list of nodes that didn't fail the RPC (at RPC
2462
    # level), so that nodes with a non-responding node daemon don't
2463
    # make all OSes invalid
2464
    good_nodes = [node_name for node_name in rlist
2465
                  if not rlist[node_name].fail_msg]
2466
    for node_name, nr in rlist.items():
2467
      if nr.fail_msg or not nr.payload:
2468
        continue
2469
      for name, path, status, diagnose, variants in nr.payload:
2470
        if name not in all_os:
2471
          # build a list of nodes for this os containing empty lists
2472
          # for each node in node_list
2473
          all_os[name] = {}
2474
          for nname in good_nodes:
2475
            all_os[name][nname] = []
2476
        all_os[name][node_name].append((path, status, diagnose, variants))
2477
    return all_os
2478

    
2479
  def Exec(self, feedback_fn):
2480
    """Compute the list of OSes.
2481

2482
    """
2483
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2484
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2485
    pol = self._DiagnoseByOS(node_data)
2486
    output = []
2487
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2488
    calc_variants = "variants" in self.op.output_fields
2489

    
2490
    for os_name, os_data in pol.items():
2491
      row = []
2492
      if calc_valid:
2493
        valid = True
2494
        variants = None
2495
        for osl in os_data.values():
2496
          valid = valid and osl and osl[0][1]
2497
          if not valid:
2498
            variants = None
2499
            break
2500
          if calc_variants:
2501
            node_variants = osl[0][3]
2502
            if variants is None:
2503
              variants = node_variants
2504
            else:
2505
              variants = [v for v in variants if v in node_variants]
2506

    
2507
      for field in self.op.output_fields:
2508
        if field == "name":
2509
          val = os_name
2510
        elif field == "valid":
2511
          val = valid
2512
        elif field == "node_status":
2513
          # this is just a copy of the dict
2514
          val = {}
2515
          for node_name, nos_list in os_data.items():
2516
            val[node_name] = nos_list
2517
        elif field == "variants":
2518
          val =  variants
2519
        else:
2520
          raise errors.ParameterError(field)
2521
        row.append(val)
2522
      output.append(row)
2523

    
2524
    return output
2525

    
2526

    
2527
class LURemoveNode(LogicalUnit):
2528
  """Logical unit for removing a node.
2529

2530
  """
2531
  HPATH = "node-remove"
2532
  HTYPE = constants.HTYPE_NODE
2533
  _OP_REQP = ["node_name"]
2534

    
2535
  def BuildHooksEnv(self):
2536
    """Build hooks env.
2537

2538
    This doesn't run on the target node in the pre phase as a failed
2539
    node would then be impossible to remove.
2540

2541
    """
2542
    env = {
2543
      "OP_TARGET": self.op.node_name,
2544
      "NODE_NAME": self.op.node_name,
2545
      }
2546
    all_nodes = self.cfg.GetNodeList()
2547
    try:
2548
      all_nodes.remove(self.op.node_name)
2549
    except ValueError:
2550
      logging.warning("Node %s which is about to be removed not found"
2551
                      " in the all nodes list", self.op.node_name)
2552
    return env, all_nodes, all_nodes
2553

    
2554
  def CheckPrereq(self):
2555
    """Check prerequisites.
2556

2557
    This checks:
2558
     - the node exists in the configuration
2559
     - it does not have primary or secondary instances
2560
     - it's not the master
2561

2562
    Any errors are signaled by raising errors.OpPrereqError.
2563

2564
    """
2565
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
2566
    node = self.cfg.GetNodeInfo(self.op.node_name)
2567
    assert node is not None
2568

    
2569
    instance_list = self.cfg.GetInstanceList()
2570

    
2571
    masternode = self.cfg.GetMasterNode()
2572
    if node.name == masternode:
2573
      raise errors.OpPrereqError("Node is the master node,"
2574
                                 " you need to failover first.",
2575
                                 errors.ECODE_INVAL)
2576

    
2577
    for instance_name in instance_list:
2578
      instance = self.cfg.GetInstanceInfo(instance_name)
2579
      if node.name in instance.all_nodes:
2580
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2581
                                   " please remove first." % instance_name,
2582
                                   errors.ECODE_INVAL)
2583
    self.op.node_name = node.name
2584
    self.node = node
2585

    
2586
  def Exec(self, feedback_fn):
2587
    """Removes the node from the cluster.
2588

2589
    """
2590
    node = self.node
2591
    logging.info("Stopping the node daemon and removing configs from node %s",
2592
                 node.name)
2593

    
2594
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2595

    
2596
    # Promote nodes to master candidate as needed
2597
    _AdjustCandidatePool(self, exceptions=[node.name])
2598
    self.context.RemoveNode(node.name)
2599

    
2600
    # Run post hooks on the node before it's removed
2601
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2602
    try:
2603
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2604
    except:
2605
      # pylint: disable-msg=W0702
2606
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2607

    
2608
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2609
    msg = result.fail_msg
2610
    if msg:
2611
      self.LogWarning("Errors encountered on the remote node while leaving"
2612
                      " the cluster: %s", msg)
2613

    
2614

    
2615
class LUQueryNodes(NoHooksLU):
2616
  """Logical unit for querying nodes.
2617

2618
  """
2619
  # pylint: disable-msg=W0142
2620
  _OP_REQP = ["output_fields", "names", "use_locking"]
2621
  REQ_BGL = False
2622

    
2623
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2624
                    "master_candidate", "offline", "drained"]
2625

    
2626
  _FIELDS_DYNAMIC = utils.FieldSet(
2627
    "dtotal", "dfree",
2628
    "mtotal", "mnode", "mfree",
2629
    "bootid",
2630
    "ctotal", "cnodes", "csockets",
2631
    )
2632

    
2633
  _FIELDS_STATIC = utils.FieldSet(*[
2634
    "pinst_cnt", "sinst_cnt",
2635
    "pinst_list", "sinst_list",
2636
    "pip", "sip", "tags",
2637
    "master",
2638
    "role"] + _SIMPLE_FIELDS
2639
    )
2640

    
2641
  def ExpandNames(self):
2642
    _CheckOutputFields(static=self._FIELDS_STATIC,
2643
                       dynamic=self._FIELDS_DYNAMIC,
2644
                       selected=self.op.output_fields)
2645

    
2646
    self.needed_locks = {}
2647
    self.share_locks[locking.LEVEL_NODE] = 1
2648

    
2649
    if self.op.names:
2650
      self.wanted = _GetWantedNodes(self, self.op.names)
2651
    else:
2652
      self.wanted = locking.ALL_SET
2653

    
2654
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2655
    self.do_locking = self.do_node_query and self.op.use_locking
2656
    if self.do_locking:
2657
      # if we don't request only static fields, we need to lock the nodes
2658
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2659

    
2660
  def CheckPrereq(self):
2661
    """Check prerequisites.
2662

2663
    """
2664
    # The validation of the node list is done in the _GetWantedNodes,
2665
    # if non empty, and if empty, there's no validation to do
2666
    pass
2667

    
2668
  def Exec(self, feedback_fn):
2669
    """Computes the list of nodes and their attributes.
2670

2671
    """
2672
    all_info = self.cfg.GetAllNodesInfo()
2673
    if self.do_locking:
2674
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2675
    elif self.wanted != locking.ALL_SET:
2676
      nodenames = self.wanted
2677
      missing = set(nodenames).difference(all_info.keys())
2678
      if missing:
2679
        raise errors.OpExecError(
2680
          "Some nodes were removed before retrieving their data: %s" % missing)
2681
    else:
2682
      nodenames = all_info.keys()
2683

    
2684
    nodenames = utils.NiceSort(nodenames)
2685
    nodelist = [all_info[name] for name in nodenames]
2686

    
2687
    # begin data gathering
2688

    
2689
    if self.do_node_query:
2690
      live_data = {}
2691
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2692
                                          self.cfg.GetHypervisorType())
2693
      for name in nodenames:
2694
        nodeinfo = node_data[name]
2695
        if not nodeinfo.fail_msg and nodeinfo.payload:
2696
          nodeinfo = nodeinfo.payload
2697
          fn = utils.TryConvert
2698
          live_data[name] = {
2699
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2700
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2701
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2702
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2703
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2704
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2705
            "bootid": nodeinfo.get('bootid', None),
2706
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2707
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2708
            }
2709
        else:
2710
          live_data[name] = {}
2711
    else:
2712
      live_data = dict.fromkeys(nodenames, {})
2713

    
2714
    node_to_primary = dict([(name, set()) for name in nodenames])
2715
    node_to_secondary = dict([(name, set()) for name in nodenames])
2716

    
2717
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2718
                             "sinst_cnt", "sinst_list"))
2719
    if inst_fields & frozenset(self.op.output_fields):
2720
      inst_data = self.cfg.GetAllInstancesInfo()
2721

    
2722
      for inst in inst_data.values():
2723
        if inst.primary_node in node_to_primary:
2724
          node_to_primary[inst.primary_node].add(inst.name)
2725
        for secnode in inst.secondary_nodes:
2726
          if secnode in node_to_secondary:
2727
            node_to_secondary[secnode].add(inst.name)
2728

    
2729
    master_node = self.cfg.GetMasterNode()
2730

    
2731
    # end data gathering
2732

    
2733
    output = []
2734
    for node in nodelist:
2735
      node_output = []
2736
      for field in self.op.output_fields:
2737
        if field in self._SIMPLE_FIELDS:
2738
          val = getattr(node, field)
2739
        elif field == "pinst_list":
2740
          val = list(node_to_primary[node.name])
2741
        elif field == "sinst_list":
2742
          val = list(node_to_secondary[node.name])
2743
        elif field == "pinst_cnt":
2744
          val = len(node_to_primary[node.name])
2745
        elif field == "sinst_cnt":
2746
          val = len(node_to_secondary[node.name])
2747
        elif field == "pip":
2748
          val = node.primary_ip
2749
        elif field == "sip":
2750
          val = node.secondary_ip
2751
        elif field == "tags":
2752
          val = list(node.GetTags())
2753
        elif field == "master":
2754
          val = node.name == master_node
2755
        elif self._FIELDS_DYNAMIC.Matches(field):
2756
          val = live_data[node.name].get(field, None)
2757
        elif field == "role":
2758
          if node.name == master_node:
2759
            val = "M"
2760
          elif node.master_candidate:
2761
            val = "C"
2762
          elif node.drained:
2763
            val = "D"
2764
          elif node.offline:
2765
            val = "O"
2766
          else:
2767
            val = "R"
2768
        else:
2769
          raise errors.ParameterError(field)
2770
        node_output.append(val)
2771
      output.append(node_output)
2772

    
2773
    return output
2774

    
2775

    
2776
class LUQueryNodeVolumes(NoHooksLU):
2777
  """Logical unit for getting volumes on node(s).
2778

2779
  """
2780
  _OP_REQP = ["nodes", "output_fields"]
2781
  REQ_BGL = False
2782
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2783
  _FIELDS_STATIC = utils.FieldSet("node")
2784

    
2785
  def ExpandNames(self):
2786
    _CheckOutputFields(static=self._FIELDS_STATIC,
2787
                       dynamic=self._FIELDS_DYNAMIC,
2788
                       selected=self.op.output_fields)
2789

    
2790
    self.needed_locks = {}
2791
    self.share_locks[locking.LEVEL_NODE] = 1
2792
    if not self.op.nodes:
2793
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2794
    else:
2795
      self.needed_locks[locking.LEVEL_NODE] = \
2796
        _GetWantedNodes(self, self.op.nodes)
2797

    
2798
  def CheckPrereq(self):
2799
    """Check prerequisites.
2800

2801
    This checks that the fields required are valid output fields.
2802

2803
    """
2804
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2805

    
2806
  def Exec(self, feedback_fn):
2807
    """Computes the list of nodes and their attributes.
2808

2809
    """
2810
    nodenames = self.nodes
2811
    volumes = self.rpc.call_node_volumes(nodenames)
2812

    
2813
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2814
             in self.cfg.GetInstanceList()]
2815

    
2816
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2817

    
2818
    output = []
2819
    for node in nodenames:
2820
      nresult = volumes[node]
2821
      if nresult.offline:
2822
        continue
2823
      msg = nresult.fail_msg
2824
      if msg:
2825
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
2826
        continue
2827

    
2828
      node_vols = nresult.payload[:]
2829
      node_vols.sort(key=lambda vol: vol['dev'])
2830

    
2831
      for vol in node_vols:
2832
        node_output = []
2833
        for field in self.op.output_fields:
2834
          if field == "node":
2835
            val = node
2836
          elif field == "phys":
2837
            val = vol['dev']
2838
          elif field == "vg":
2839
            val = vol['vg']
2840
          elif field == "name":
2841
            val = vol['name']
2842
          elif field == "size":
2843
            val = int(float(vol['size']))
2844
          elif field == "instance":
2845
            for inst in ilist:
2846
              if node not in lv_by_node[inst]:
2847
                continue
2848
              if vol['name'] in lv_by_node[inst][node]:
2849
                val = inst.name
2850
                break
2851
            else:
2852
              val = '-'
2853
          else:
2854
            raise errors.ParameterError(field)
2855
          node_output.append(str(val))
2856

    
2857
        output.append(node_output)
2858

    
2859
    return output
2860

    
2861

    
2862
class LUQueryNodeStorage(NoHooksLU):
2863
  """Logical unit for getting information on storage units on node(s).
2864

2865
  """
2866
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
2867
  REQ_BGL = False
2868
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
2869

    
2870
  def ExpandNames(self):
2871
    storage_type = self.op.storage_type
2872

    
2873
    if storage_type not in constants.VALID_STORAGE_TYPES:
2874
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2875
                                 errors.ECODE_INVAL)
2876

    
2877
    _CheckOutputFields(static=self._FIELDS_STATIC,
2878
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
2879
                       selected=self.op.output_fields)
2880

    
2881
    self.needed_locks = {}
2882
    self.share_locks[locking.LEVEL_NODE] = 1
2883

    
2884
    if self.op.nodes:
2885
      self.needed_locks[locking.LEVEL_NODE] = \
2886
        _GetWantedNodes(self, self.op.nodes)
2887
    else:
2888
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2889

    
2890
  def CheckPrereq(self):
2891
    """Check prerequisites.
2892

2893
    This checks that the fields required are valid output fields.
2894

2895
    """
2896
    self.op.name = getattr(self.op, "name", None)
2897

    
2898
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2899

    
2900
  def Exec(self, feedback_fn):
2901
    """Computes the list of nodes and their attributes.
2902

2903
    """
2904
    # Always get name to sort by
2905
    if constants.SF_NAME in self.op.output_fields:
2906
      fields = self.op.output_fields[:]
2907
    else:
2908
      fields = [constants.SF_NAME] + self.op.output_fields
2909

    
2910
    # Never ask for node or type as it's only known to the LU
2911
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
2912
      while extra in fields:
2913
        fields.remove(extra)
2914

    
2915
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
2916
    name_idx = field_idx[constants.SF_NAME]
2917

    
2918
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2919
    data = self.rpc.call_storage_list(self.nodes,
2920
                                      self.op.storage_type, st_args,
2921
                                      self.op.name, fields)
2922

    
2923
    result = []
2924

    
2925
    for node in utils.NiceSort(self.nodes):
2926
      nresult = data[node]
2927
      if nresult.offline:
2928
        continue
2929

    
2930
      msg = nresult.fail_msg
2931
      if msg:
2932
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
2933
        continue
2934

    
2935
      rows = dict([(row[name_idx], row) for row in nresult.payload])
2936

    
2937
      for name in utils.NiceSort(rows.keys()):
2938
        row = rows[name]
2939

    
2940
        out = []
2941

    
2942
        for field in self.op.output_fields:
2943
          if field == constants.SF_NODE:
2944
            val = node
2945
          elif field == constants.SF_TYPE:
2946
            val = self.op.storage_type
2947
          elif field in field_idx:
2948
            val = row[field_idx[field]]
2949
          else:
2950
            raise errors.ParameterError(field)
2951

    
2952
          out.append(val)
2953

    
2954
        result.append(out)
2955

    
2956
    return result
2957

    
2958

    
2959
class LUModifyNodeStorage(NoHooksLU):
2960
  """Logical unit for modifying a storage volume on a node.
2961

2962
  """
2963
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
2964
  REQ_BGL = False
2965

    
2966
  def CheckArguments(self):
2967
    self.opnode_name = _ExpandNodeName(self.cfg, self.op.node_name)
2968

    
2969
    storage_type = self.op.storage_type
2970
    if storage_type not in constants.VALID_STORAGE_TYPES:
2971
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2972
                                 errors.ECODE_INVAL)
2973

    
2974
  def ExpandNames(self):
2975
    self.needed_locks = {
2976
      locking.LEVEL_NODE: self.op.node_name,
2977
      }
2978

    
2979
  def CheckPrereq(self):
2980
    """Check prerequisites.
2981

2982
    """
2983
    storage_type = self.op.storage_type
2984

    
2985
    try:
2986
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
2987
    except KeyError:
2988
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
2989
                                 " modified" % storage_type,
2990
                                 errors.ECODE_INVAL)
2991

    
2992
    diff = set(self.op.changes.keys()) - modifiable
2993
    if diff:
2994
      raise errors.OpPrereqError("The following fields can not be modified for"
2995
                                 " storage units of type '%s': %r" %
2996
                                 (storage_type, list(diff)),
2997
                                 errors.ECODE_INVAL)
2998

    
2999
  def Exec(self, feedback_fn):
3000
    """Computes the list of nodes and their attributes.
3001

3002
    """
3003
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3004
    result = self.rpc.call_storage_modify(self.op.node_name,
3005
                                          self.op.storage_type, st_args,
3006
                                          self.op.name, self.op.changes)
3007
    result.Raise("Failed to modify storage unit '%s' on %s" %
3008
                 (self.op.name, self.op.node_name))
3009

    
3010

    
3011
class LUAddNode(LogicalUnit):
3012
  """Logical unit for adding node to the cluster.
3013

3014
  """
3015
  HPATH = "node-add"
3016
  HTYPE = constants.HTYPE_NODE
3017
  _OP_REQP = ["node_name"]
3018

    
3019
  def CheckArguments(self):
3020
    # validate/normalize the node name
3021
    self.op.node_name = utils.HostInfo.NormalizeName(self.op.node_name)
3022

    
3023
  def BuildHooksEnv(self):
3024
    """Build hooks env.
3025

3026
    This will run on all nodes before, and on all nodes + the new node after.
3027

3028
    """
3029
    env = {
3030
      "OP_TARGET": self.op.node_name,
3031
      "NODE_NAME": self.op.node_name,
3032
      "NODE_PIP": self.op.primary_ip,
3033
      "NODE_SIP": self.op.secondary_ip,
3034
      }
3035
    nodes_0 = self.cfg.GetNodeList()
3036
    nodes_1 = nodes_0 + [self.op.node_name, ]
3037
    return env, nodes_0, nodes_1
3038

    
3039
  def CheckPrereq(self):
3040
    """Check prerequisites.
3041

3042
    This checks:
3043
     - the new node is not already in the config
3044
     - it is resolvable
3045
     - its parameters (single/dual homed) matches the cluster
3046

3047
    Any errors are signaled by raising errors.OpPrereqError.
3048

3049
    """
3050
    node_name = self.op.node_name
3051
    cfg = self.cfg
3052

    
3053
    dns_data = utils.GetHostInfo(node_name)
3054

    
3055
    node = dns_data.name
3056
    primary_ip = self.op.primary_ip = dns_data.ip
3057
    secondary_ip = getattr(self.op, "secondary_ip", None)
3058
    if secondary_ip is None:
3059
      secondary_ip = primary_ip
3060
    if not utils.IsValidIP(secondary_ip):
3061
      raise errors.OpPrereqError("Invalid secondary IP given",
3062
                                 errors.ECODE_INVAL)
3063
    self.op.secondary_ip = secondary_ip
3064

    
3065
    node_list = cfg.GetNodeList()
3066
    if not self.op.readd and node in node_list:
3067
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3068
                                 node, errors.ECODE_EXISTS)
3069
    elif self.op.readd and node not in node_list:
3070
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3071
                                 errors.ECODE_NOENT)
3072

    
3073
    for existing_node_name in node_list:
3074
      existing_node = cfg.GetNodeInfo(existing_node_name)
3075

    
3076
      if self.op.readd and node == existing_node_name:
3077
        if (existing_node.primary_ip != primary_ip or
3078
            existing_node.secondary_ip != secondary_ip):
3079
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3080
                                     " address configuration as before",
3081
                                     errors.ECODE_INVAL)
3082
        continue
3083

    
3084
      if (existing_node.primary_ip == primary_ip or
3085
          existing_node.secondary_ip == primary_ip or
3086
          existing_node.primary_ip == secondary_ip or
3087
          existing_node.secondary_ip == secondary_ip):
3088
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3089
                                   " existing node %s" % existing_node.name,
3090
                                   errors.ECODE_NOTUNIQUE)
3091

    
3092
    # check that the type of the node (single versus dual homed) is the
3093
    # same as for the master
3094
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3095
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3096
    newbie_singlehomed = secondary_ip == primary_ip
3097
    if master_singlehomed != newbie_singlehomed:
3098
      if master_singlehomed:
3099
        raise errors.OpPrereqError("The master has no private ip but the"
3100
                                   " new node has one",
3101
                                   errors.ECODE_INVAL)
3102
      else:
3103
        raise errors.OpPrereqError("The master has a private ip but the"
3104
                                   " new node doesn't have one",
3105
                                   errors.ECODE_INVAL)
3106

    
3107
    # checks reachability
3108
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3109
      raise errors.OpPrereqError("Node not reachable by ping",
3110
                                 errors.ECODE_ENVIRON)
3111

    
3112
    if not newbie_singlehomed:
3113
      # check reachability from my secondary ip to newbie's secondary ip
3114
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3115
                           source=myself.secondary_ip):
3116
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3117
                                   " based ping to noded port",
3118
                                   errors.ECODE_ENVIRON)
3119

    
3120
    if self.op.readd:
3121
      exceptions = [node]
3122
    else:
3123
      exceptions = []
3124

    
3125
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3126

    
3127
    if self.op.readd:
3128
      self.new_node = self.cfg.GetNodeInfo(node)
3129
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3130
    else:
3131
      self.new_node = objects.Node(name=node,
3132
                                   primary_ip=primary_ip,
3133
                                   secondary_ip=secondary_ip,
3134
                                   master_candidate=self.master_candidate,
3135
                                   offline=False, drained=False)
3136

    
3137
  def Exec(self, feedback_fn):
3138
    """Adds the new node to the cluster.
3139

3140
    """
3141
    new_node = self.new_node
3142
    node = new_node.name
3143

    
3144
    # for re-adds, reset the offline/drained/master-candidate flags;
3145
    # we need to reset here, otherwise offline would prevent RPC calls
3146
    # later in the procedure; this also means that if the re-add
3147
    # fails, we are left with a non-offlined, broken node
3148
    if self.op.readd:
3149
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3150
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3151
      # if we demote the node, we do cleanup later in the procedure
3152
      new_node.master_candidate = self.master_candidate
3153

    
3154
    # notify the user about any possible mc promotion
3155
    if new_node.master_candidate:
3156
      self.LogInfo("Node will be a master candidate")
3157

    
3158
    # check connectivity
3159
    result = self.rpc.call_version([node])[node]
3160
    result.Raise("Can't get version information from node %s" % node)
3161
    if constants.PROTOCOL_VERSION == result.payload:
3162
      logging.info("Communication to node %s fine, sw version %s match",
3163
                   node, result.payload)
3164
    else:
3165
      raise errors.OpExecError("Version mismatch master version %s,"
3166
                               " node version %s" %
3167
                               (constants.PROTOCOL_VERSION, result.payload))
3168

    
3169
    # setup ssh on node
3170
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3171
      logging.info("Copy ssh key to node %s", node)
3172
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3173
      keyarray = []
3174
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3175
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3176
                  priv_key, pub_key]
3177

    
3178
      for i in keyfiles:
3179
        keyarray.append(utils.ReadFile(i))
3180

    
3181
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3182
                                      keyarray[2], keyarray[3], keyarray[4],
3183
                                      keyarray[5])
3184
      result.Raise("Cannot transfer ssh keys to the new node")
3185

    
3186
    # Add node to our /etc/hosts, and add key to known_hosts
3187
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3188
      utils.AddHostToEtcHosts(new_node.name)
3189

    
3190
    if new_node.secondary_ip != new_node.primary_ip:
3191
      result = self.rpc.call_node_has_ip_address(new_node.name,
3192
                                                 new_node.secondary_ip)
3193
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3194
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3195
      if not result.payload:
3196
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3197
                                 " you gave (%s). Please fix and re-run this"
3198
                                 " command." % new_node.secondary_ip)
3199

    
3200
    node_verify_list = [self.cfg.GetMasterNode()]
3201
    node_verify_param = {
3202
      constants.NV_NODELIST: [node],
3203
      # TODO: do a node-net-test as well?
3204
    }
3205

    
3206
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3207
                                       self.cfg.GetClusterName())
3208
    for verifier in node_verify_list:
3209
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3210
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3211
      if nl_payload:
3212
        for failed in nl_payload:
3213
          feedback_fn("ssh/hostname verification failed"
3214
                      " (checking from %s): %s" %
3215
                      (verifier, nl_payload[failed]))
3216
        raise errors.OpExecError("ssh/hostname verification failed.")
3217

    
3218
    if self.op.readd:
3219
      _RedistributeAncillaryFiles(self)
3220
      self.context.ReaddNode(new_node)
3221
      # make sure we redistribute the config
3222
      self.cfg.Update(new_node, feedback_fn)
3223
      # and make sure the new node will not have old files around
3224
      if not new_node.master_candidate:
3225
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3226
        msg = result.fail_msg
3227
        if msg:
3228
          self.LogWarning("Node failed to demote itself from master"
3229
                          " candidate status: %s" % msg)
3230
    else:
3231
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3232
      self.context.AddNode(new_node, self.proc.GetECId())
3233

    
3234

    
3235
class LUSetNodeParams(LogicalUnit):
3236
  """Modifies the parameters of a node.
3237

3238
  """
3239
  HPATH = "node-modify"
3240
  HTYPE = constants.HTYPE_NODE
3241
  _OP_REQP = ["node_name"]
3242
  REQ_BGL = False
3243

    
3244
  def CheckArguments(self):
3245
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3246
    _CheckBooleanOpField(self.op, 'master_candidate')
3247
    _CheckBooleanOpField(self.op, 'offline')
3248
    _CheckBooleanOpField(self.op, 'drained')
3249
    _CheckBooleanOpField(self.op, 'auto_promote')
3250
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3251
    if all_mods.count(None) == 3:
3252
      raise errors.OpPrereqError("Please pass at least one modification",
3253
                                 errors.ECODE_INVAL)
3254
    if all_mods.count(True) > 1:
3255
      raise errors.OpPrereqError("Can't set the node into more than one"
3256
                                 " state at the same time",
3257
                                 errors.ECODE_INVAL)
3258

    
3259
    # Boolean value that tells us whether we're offlining or draining the node
3260
    self.offline_or_drain = (self.op.offline == True or
3261
                             self.op.drained == True)
3262
    self.deoffline_or_drain = (self.op.offline == False or
3263
                               self.op.drained == False)
3264
    self.might_demote = (self.op.master_candidate == False or
3265
                         self.offline_or_drain)
3266

    
3267
    self.lock_all = self.op.auto_promote and self.might_demote
3268

    
3269

    
3270
  def ExpandNames(self):
3271
    if self.lock_all:
3272
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3273
    else:
3274
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3275

    
3276
  def BuildHooksEnv(self):
3277
    """Build hooks env.
3278

3279
    This runs on the master node.
3280

3281
    """
3282
    env = {
3283
      "OP_TARGET": self.op.node_name,
3284
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3285
      "OFFLINE": str(self.op.offline),
3286
      "DRAINED": str(self.op.drained),
3287
      }
3288
    nl = [self.cfg.GetMasterNode(),
3289
          self.op.node_name]
3290
    return env, nl, nl
3291

    
3292
  def CheckPrereq(self):
3293
    """Check prerequisites.
3294

3295
    This only checks the instance list against the existing names.
3296

3297
    """
3298
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3299

    
3300
    if (self.op.master_candidate is not None or
3301
        self.op.drained is not None or
3302
        self.op.offline is not None):
3303
      # we can't change the master's node flags
3304
      if self.op.node_name == self.cfg.GetMasterNode():
3305
        raise errors.OpPrereqError("The master role can be changed"
3306
                                   " only via masterfailover",
3307
                                   errors.ECODE_INVAL)
3308

    
3309

    
3310
    if node.master_candidate and self.might_demote and not self.lock_all:
3311
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3312
      # check if after removing the current node, we're missing master
3313
      # candidates
3314
      (mc_remaining, mc_should, _) = \
3315
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3316
      if mc_remaining != mc_should:
3317
        raise errors.OpPrereqError("Not enough master candidates, please"
3318
                                   " pass auto_promote to allow promotion",
3319
                                   errors.ECODE_INVAL)
3320

    
3321
    if (self.op.master_candidate == True and
3322
        ((node.offline and not self.op.offline == False) or
3323
         (node.drained and not self.op.drained == False))):
3324
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3325
                                 " to master_candidate" % node.name,
3326
                                 errors.ECODE_INVAL)
3327

    
3328
    # If we're being deofflined/drained, we'll MC ourself if needed
3329
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3330
        self.op.master_candidate == True and not node.master_candidate):
3331
      self.op.master_candidate = _DecideSelfPromotion(self)
3332
      if self.op.master_candidate:
3333
        self.LogInfo("Autopromoting node to master candidate")
3334

    
3335
    return
3336

    
3337
  def Exec(self, feedback_fn):
3338
    """Modifies a node.
3339

3340
    """
3341
    node = self.node
3342

    
3343
    result = []
3344
    changed_mc = False
3345

    
3346
    if self.op.offline is not None:
3347
      node.offline = self.op.offline
3348
      result.append(("offline", str(self.op.offline)))
3349
      if self.op.offline == True:
3350
        if node.master_candidate:
3351
          node.master_candidate = False
3352
          changed_mc = True
3353
          result.append(("master_candidate", "auto-demotion due to offline"))
3354
        if node.drained:
3355
          node.drained = False
3356
          result.append(("drained", "clear drained status due to offline"))
3357

    
3358
    if self.op.master_candidate is not None:
3359
      node.master_candidate = self.op.master_candidate
3360
      changed_mc = True
3361
      result.append(("master_candidate", str(self.op.master_candidate)))
3362
      if self.op.master_candidate == False:
3363
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3364
        msg = rrc.fail_msg
3365
        if msg:
3366
          self.LogWarning("Node failed to demote itself: %s" % msg)
3367

    
3368
    if self.op.drained is not None:
3369
      node.drained = self.op.drained
3370
      result.append(("drained", str(self.op.drained)))
3371
      if self.op.drained == True:
3372
        if node.master_candidate:
3373
          node.master_candidate = False
3374
          changed_mc = True
3375
          result.append(("master_candidate", "auto-demotion due to drain"))
3376
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3377
          msg = rrc.fail_msg
3378
          if msg:
3379
            self.LogWarning("Node failed to demote itself: %s" % msg)
3380
        if node.offline:
3381
          node.offline = False
3382
          result.append(("offline", "clear offline status due to drain"))
3383

    
3384
    # we locked all nodes, we adjust the CP before updating this node
3385
    if self.lock_all:
3386
      _AdjustCandidatePool(self, [node.name])
3387

    
3388
    # this will trigger configuration file update, if needed
3389
    self.cfg.Update(node, feedback_fn)
3390

    
3391
    # this will trigger job queue propagation or cleanup
3392
    if changed_mc:
3393
      self.context.ReaddNode(node)
3394

    
3395
    return result
3396

    
3397

    
3398
class LUPowercycleNode(NoHooksLU):
3399
  """Powercycles a node.
3400

3401
  """
3402
  _OP_REQP = ["node_name", "force"]
3403
  REQ_BGL = False
3404

    
3405
  def CheckArguments(self):
3406
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3407
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
3408
      raise errors.OpPrereqError("The node is the master and the force"
3409
                                 " parameter was not set",
3410
                                 errors.ECODE_INVAL)
3411

    
3412
  def ExpandNames(self):
3413
    """Locking for PowercycleNode.
3414

3415
    This is a last-resort option and shouldn't block on other
3416
    jobs. Therefore, we grab no locks.
3417

3418
    """
3419
    self.needed_locks = {}
3420

    
3421
  def CheckPrereq(self):
3422
    """Check prerequisites.
3423

3424
    This LU has no prereqs.
3425

3426
    """
3427
    pass
3428

    
3429
  def Exec(self, feedback_fn):
3430
    """Reboots a node.
3431

3432
    """
3433
    result = self.rpc.call_node_powercycle(self.op.node_name,
3434
                                           self.cfg.GetHypervisorType())
3435
    result.Raise("Failed to schedule the reboot")
3436
    return result.payload
3437

    
3438

    
3439
class LUQueryClusterInfo(NoHooksLU):
3440
  """Query cluster configuration.
3441

3442
  """
3443
  _OP_REQP = []
3444
  REQ_BGL = False
3445

    
3446
  def ExpandNames(self):
3447
    self.needed_locks = {}
3448

    
3449
  def CheckPrereq(self):
3450
    """No prerequsites needed for this LU.
3451

3452
    """
3453
    pass
3454

    
3455
  def Exec(self, feedback_fn):
3456
    """Return cluster config.
3457

3458
    """
3459
    cluster = self.cfg.GetClusterInfo()
3460
    os_hvp = {}
3461

    
3462
    # Filter just for enabled hypervisors
3463
    for os_name, hv_dict in cluster.os_hvp.items():
3464
      os_hvp[os_name] = {}
3465
      for hv_name, hv_params in hv_dict.items():
3466
        if hv_name in cluster.enabled_hypervisors:
3467
          os_hvp[os_name][hv_name] = hv_params
3468

    
3469
    result = {
3470
      "software_version": constants.RELEASE_VERSION,
3471
      "protocol_version": constants.PROTOCOL_VERSION,
3472
      "config_version": constants.CONFIG_VERSION,
3473
      "os_api_version": max(constants.OS_API_VERSIONS),
3474
      "export_version": constants.EXPORT_VERSION,
3475
      "architecture": (platform.architecture()[0], platform.machine()),
3476
      "name": cluster.cluster_name,
3477
      "master": cluster.master_node,
3478
      "default_hypervisor": cluster.enabled_hypervisors[0],
3479
      "enabled_hypervisors": cluster.enabled_hypervisors,
3480
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3481
                        for hypervisor_name in cluster.enabled_hypervisors]),
3482
      "os_hvp": os_hvp,
3483
      "beparams": cluster.beparams,
3484
      "nicparams": cluster.nicparams,
3485
      "candidate_pool_size": cluster.candidate_pool_size,
3486
      "master_netdev": cluster.master_netdev,
3487
      "volume_group_name": cluster.volume_group_name,
3488
      "file_storage_dir": cluster.file_storage_dir,
3489
      "ctime": cluster.ctime,
3490
      "mtime": cluster.mtime,
3491
      "uuid": cluster.uuid,
3492
      "tags": list(cluster.GetTags()),
3493
      }
3494

    
3495
    return result
3496

    
3497

    
3498
class LUQueryConfigValues(NoHooksLU):
3499
  """Return configuration values.
3500

3501
  """
3502
  _OP_REQP = []
3503
  REQ_BGL = False
3504
  _FIELDS_DYNAMIC = utils.FieldSet()
3505
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3506
                                  "watcher_pause")
3507

    
3508
  def ExpandNames(self):
3509
    self.needed_locks = {}
3510

    
3511
    _CheckOutputFields(static=self._FIELDS_STATIC,
3512
                       dynamic=self._FIELDS_DYNAMIC,
3513
                       selected=self.op.output_fields)
3514

    
3515
  def CheckPrereq(self):
3516
    """No prerequisites.
3517

3518
    """
3519
    pass
3520

    
3521
  def Exec(self, feedback_fn):
3522
    """Dump a representation of the cluster config to the standard output.
3523

3524
    """
3525
    values = []
3526
    for field in self.op.output_fields:
3527
      if field == "cluster_name":
3528
        entry = self.cfg.GetClusterName()
3529
      elif field == "master_node":
3530
        entry = self.cfg.GetMasterNode()
3531
      elif field == "drain_flag":
3532
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3533
      elif field == "watcher_pause":
3534
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3535
      else:
3536
        raise errors.ParameterError(field)
3537
      values.append(entry)
3538
    return values
3539

    
3540

    
3541
class LUActivateInstanceDisks(NoHooksLU):
3542
  """Bring up an instance's disks.
3543

3544
  """
3545
  _OP_REQP = ["instance_name"]
3546
  REQ_BGL = False
3547

    
3548
  def ExpandNames(self):
3549
    self._ExpandAndLockInstance()
3550
    self.needed_locks[locking.LEVEL_NODE] = []
3551
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3552

    
3553
  def DeclareLocks(self, level):
3554
    if level == locking.LEVEL_NODE:
3555
      self._LockInstancesNodes()
3556

    
3557
  def CheckPrereq(self):
3558
    """Check prerequisites.
3559

3560
    This checks that the instance is in the cluster.
3561

3562
    """
3563
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3564
    assert self.instance is not None, \
3565
      "Cannot retrieve locked instance %s" % self.op.instance_name
3566
    _CheckNodeOnline(self, self.instance.primary_node)
3567
    if not hasattr(self.op, "ignore_size"):
3568
      self.op.ignore_size = False
3569

    
3570
  def Exec(self, feedback_fn):
3571
    """Activate the disks.
3572

3573
    """
3574
    disks_ok, disks_info = \
3575
              _AssembleInstanceDisks(self, self.instance,
3576
                                     ignore_size=self.op.ignore_size)
3577
    if not disks_ok:
3578
      raise errors.OpExecError("Cannot activate block devices")
3579

    
3580
    return disks_info
3581

    
3582

    
3583
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3584
                           ignore_size=False):
3585
  """Prepare the block devices for an instance.
3586

3587
  This sets up the block devices on all nodes.
3588

3589
  @type lu: L{LogicalUnit}
3590
  @param lu: the logical unit on whose behalf we execute
3591
  @type instance: L{objects.Instance}
3592
  @param instance: the instance for whose disks we assemble
3593
  @type ignore_secondaries: boolean
3594
  @param ignore_secondaries: if true, errors on secondary nodes
3595
      won't result in an error return from the function
3596
  @type ignore_size: boolean
3597
  @param ignore_size: if true, the current known size of the disk
3598
      will not be used during the disk activation, useful for cases
3599
      when the size is wrong
3600
  @return: False if the operation failed, otherwise a list of
3601
      (host, instance_visible_name, node_visible_name)
3602
      with the mapping from node devices to instance devices
3603

3604
  """
3605
  device_info = []
3606
  disks_ok = True
3607
  iname = instance.name
3608
  # With the two passes mechanism we try to reduce the window of
3609
  # opportunity for the race condition of switching DRBD to primary
3610
  # before handshaking occured, but we do not eliminate it
3611

    
3612
  # The proper fix would be to wait (with some limits) until the
3613
  # connection has been made and drbd transitions from WFConnection
3614
  # into any other network-connected state (Connected, SyncTarget,
3615
  # SyncSource, etc.)
3616

    
3617
  # 1st pass, assemble on all nodes in secondary mode
3618
  for inst_disk in instance.disks:
3619
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3620
      if ignore_size:
3621
        node_disk = node_disk.Copy()
3622
        node_disk.UnsetSize()
3623
      lu.cfg.SetDiskID(node_disk, node)
3624
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3625
      msg = result.fail_msg
3626
      if msg:
3627
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3628
                           " (is_primary=False, pass=1): %s",
3629
                           inst_disk.iv_name, node, msg)
3630
        if not ignore_secondaries:
3631
          disks_ok = False
3632

    
3633
  # FIXME: race condition on drbd migration to primary
3634

    
3635
  # 2nd pass, do only the primary node
3636
  for inst_disk in instance.disks:
3637
    dev_path = None
3638

    
3639
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3640
      if node != instance.primary_node:
3641
        continue
3642
      if ignore_size:
3643
        node_disk = node_disk.Copy()
3644
        node_disk.UnsetSize()
3645
      lu.cfg.SetDiskID(node_disk, node)
3646
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3647
      msg = result.fail_msg
3648
      if msg:
3649
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3650
                           " (is_primary=True, pass=2): %s",
3651
                           inst_disk.iv_name, node, msg)
3652
        disks_ok = False
3653
      else:
3654
        dev_path = result.payload
3655

    
3656
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3657

    
3658
  # leave the disks configured for the primary node
3659
  # this is a workaround that would be fixed better by
3660
  # improving the logical/physical id handling
3661
  for disk in instance.disks:
3662
    lu.cfg.SetDiskID(disk, instance.primary_node)
3663

    
3664
  return disks_ok, device_info
3665

    
3666

    
3667
def _StartInstanceDisks(lu, instance, force):
3668
  """Start the disks of an instance.
3669

3670
  """
3671
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3672
                                           ignore_secondaries=force)
3673
  if not disks_ok:
3674
    _ShutdownInstanceDisks(lu, instance)
3675
    if force is not None and not force:
3676
      lu.proc.LogWarning("", hint="If the message above refers to a"
3677
                         " secondary node,"
3678
                         " you can retry the operation using '--force'.")
3679
    raise errors.OpExecError("Disk consistency error")
3680

    
3681

    
3682
class LUDeactivateInstanceDisks(NoHooksLU):
3683
  """Shutdown an instance's disks.
3684

3685
  """
3686
  _OP_REQP = ["instance_name"]
3687
  REQ_BGL = False
3688

    
3689
  def ExpandNames(self):
3690
    self._ExpandAndLockInstance()
3691
    self.needed_locks[locking.LEVEL_NODE] = []
3692
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3693

    
3694
  def DeclareLocks(self, level):
3695
    if level == locking.LEVEL_NODE:
3696
      self._LockInstancesNodes()
3697

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

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

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

    
3708
  def Exec(self, feedback_fn):
3709
    """Deactivate the disks
3710

3711
    """
3712
    instance = self.instance
3713
    _SafeShutdownInstanceDisks(self, instance)
3714

    
3715

    
3716
def _SafeShutdownInstanceDisks(lu, instance):
3717
  """Shutdown block devices of an instance.
3718

3719
  This function checks if an instance is running, before calling
3720
  _ShutdownInstanceDisks.
3721

3722
  """
3723
  pnode = instance.primary_node
3724
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
3725
  ins_l.Raise("Can't contact node %s" % pnode)
3726

    
3727
  if instance.name in ins_l.payload:
3728
    raise errors.OpExecError("Instance is running, can't shutdown"
3729
                             " block devices.")
3730

    
3731
  _ShutdownInstanceDisks(lu, instance)
3732

    
3733

    
3734
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3735
  """Shutdown block devices of an instance.
3736

3737
  This does the shutdown on all nodes of the instance.
3738

3739
  If the ignore_primary is false, errors on the primary node are
3740
  ignored.
3741

3742
  """
3743
  all_result = True
3744
  for disk in instance.disks:
3745
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3746
      lu.cfg.SetDiskID(top_disk, node)
3747
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3748
      msg = result.fail_msg
3749
      if msg:
3750
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3751
                      disk.iv_name, node, msg)
3752
        if not ignore_primary or node != instance.primary_node:
3753
          all_result = False
3754
  return all_result
3755

    
3756

    
3757
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3758
  """Checks if a node has enough free memory.
3759

3760
  This function check if a given node has the needed amount of free
3761
  memory. In case the node has less memory or we cannot get the
3762
  information from the node, this function raise an OpPrereqError
3763
  exception.
3764

3765
  @type lu: C{LogicalUnit}
3766
  @param lu: a logical unit from which we get configuration data
3767
  @type node: C{str}
3768
  @param node: the node to check
3769
  @type reason: C{str}
3770
  @param reason: string to use in the error message
3771
  @type requested: C{int}
3772
  @param requested: the amount of memory in MiB to check for
3773
  @type hypervisor_name: C{str}
3774
  @param hypervisor_name: the hypervisor to ask for memory stats
3775
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3776
      we cannot check the node
3777

3778
  """
3779
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3780
  nodeinfo[node].Raise("Can't get data from node %s" % node,
3781
                       prereq=True, ecode=errors.ECODE_ENVIRON)
3782
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3783
  if not isinstance(free_mem, int):
3784
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3785
                               " was '%s'" % (node, free_mem),
3786
                               errors.ECODE_ENVIRON)
3787
  if requested > free_mem:
3788
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3789
                               " needed %s MiB, available %s MiB" %
3790
                               (node, reason, requested, free_mem),
3791
                               errors.ECODE_NORES)
3792

    
3793

    
3794
class LUStartupInstance(LogicalUnit):
3795
  """Starts an instance.
3796

3797
  """
3798
  HPATH = "instance-start"
3799
  HTYPE = constants.HTYPE_INSTANCE
3800
  _OP_REQP = ["instance_name", "force"]
3801
  REQ_BGL = False
3802

    
3803
  def ExpandNames(self):
3804
    self._ExpandAndLockInstance()
3805

    
3806
  def BuildHooksEnv(self):
3807
    """Build hooks env.
3808

3809
    This runs on master, primary and secondary nodes of the instance.
3810

3811
    """
3812
    env = {
3813
      "FORCE": self.op.force,
3814
      }
3815
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3816
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3817
    return env, nl, nl
3818

    
3819
  def CheckPrereq(self):
3820
    """Check prerequisites.
3821

3822
    This checks that the instance is in the cluster.
3823

3824
    """
3825
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3826
    assert self.instance is not None, \
3827
      "Cannot retrieve locked instance %s" % self.op.instance_name
3828

    
3829
    # extra beparams
3830
    self.beparams = getattr(self.op, "beparams", {})
3831
    if self.beparams:
3832
      if not isinstance(self.beparams, dict):
3833
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3834
                                   " dict" % (type(self.beparams), ),
3835
                                   errors.ECODE_INVAL)
3836
      # fill the beparams dict
3837
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3838
      self.op.beparams = self.beparams
3839

    
3840
    # extra hvparams
3841
    self.hvparams = getattr(self.op, "hvparams", {})
3842
    if self.hvparams:
3843
      if not isinstance(self.hvparams, dict):
3844
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3845
                                   " dict" % (type(self.hvparams), ),
3846
                                   errors.ECODE_INVAL)
3847

    
3848
      # check hypervisor parameter syntax (locally)
3849
      cluster = self.cfg.GetClusterInfo()
3850
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3851
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
3852
                                    instance.hvparams)
3853
      filled_hvp.update(self.hvparams)
3854
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3855
      hv_type.CheckParameterSyntax(filled_hvp)
3856
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3857
      self.op.hvparams = self.hvparams
3858

    
3859
    _CheckNodeOnline(self, instance.primary_node)
3860

    
3861
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3862
    # check bridges existence
3863
    _CheckInstanceBridgesExist(self, instance)
3864

    
3865
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3866
                                              instance.name,
3867
                                              instance.hypervisor)
3868
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3869
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3870
    if not remote_info.payload: # not running already
3871
      _CheckNodeFreeMemory(self, instance.primary_node,
3872
                           "starting instance %s" % instance.name,
3873
                           bep[constants.BE_MEMORY], instance.hypervisor)
3874

    
3875
  def Exec(self, feedback_fn):
3876
    """Start the instance.
3877

3878
    """
3879
    instance = self.instance
3880
    force = self.op.force
3881

    
3882
    self.cfg.MarkInstanceUp(instance.name)
3883

    
3884
    node_current = instance.primary_node
3885

    
3886
    _StartInstanceDisks(self, instance, force)
3887

    
3888
    result = self.rpc.call_instance_start(node_current, instance,
3889
                                          self.hvparams, self.beparams)
3890
    msg = result.fail_msg
3891
    if msg:
3892
      _ShutdownInstanceDisks(self, instance)
3893
      raise errors.OpExecError("Could not start instance: %s" % msg)
3894

    
3895

    
3896
class LURebootInstance(LogicalUnit):
3897
  """Reboot an instance.
3898

3899
  """
3900
  HPATH = "instance-reboot"
3901
  HTYPE = constants.HTYPE_INSTANCE
3902
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3903
  REQ_BGL = False
3904

    
3905
  def CheckArguments(self):
3906
    """Check the arguments.
3907

3908
    """
3909
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
3910
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
3911

    
3912
  def ExpandNames(self):
3913
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3914
                                   constants.INSTANCE_REBOOT_HARD,
3915
                                   constants.INSTANCE_REBOOT_FULL]:
3916
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3917
                                  (constants.INSTANCE_REBOOT_SOFT,
3918
                                   constants.INSTANCE_REBOOT_HARD,
3919
                                   constants.INSTANCE_REBOOT_FULL))
3920
    self._ExpandAndLockInstance()
3921

    
3922
  def BuildHooksEnv(self):
3923
    """Build hooks env.
3924

3925
    This runs on master, primary and secondary nodes of the instance.
3926

3927
    """
3928
    env = {
3929
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3930
      "REBOOT_TYPE": self.op.reboot_type,
3931
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
3932
      }
3933
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3934
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3935
    return env, nl, nl
3936

    
3937
  def CheckPrereq(self):
3938
    """Check prerequisites.
3939

3940
    This checks that the instance is in the cluster.
3941

3942
    """
3943
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3944
    assert self.instance is not None, \
3945
      "Cannot retrieve locked instance %s" % self.op.instance_name
3946

    
3947
    _CheckNodeOnline(self, instance.primary_node)
3948

    
3949
    # check bridges existence
3950
    _CheckInstanceBridgesExist(self, instance)
3951

    
3952
  def Exec(self, feedback_fn):
3953
    """Reboot the instance.
3954

3955
    """
3956
    instance = self.instance
3957
    ignore_secondaries = self.op.ignore_secondaries
3958
    reboot_type = self.op.reboot_type
3959

    
3960
    node_current = instance.primary_node
3961

    
3962
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3963
                       constants.INSTANCE_REBOOT_HARD]:
3964
      for disk in instance.disks:
3965
        self.cfg.SetDiskID(disk, node_current)
3966
      result = self.rpc.call_instance_reboot(node_current, instance,
3967
                                             reboot_type,
3968
                                             self.shutdown_timeout)
3969
      result.Raise("Could not reboot instance")
3970
    else:
3971
      result = self.rpc.call_instance_shutdown(node_current, instance,
3972
                                               self.shutdown_timeout)
3973
      result.Raise("Could not shutdown instance for full reboot")
3974
      _ShutdownInstanceDisks(self, instance)
3975
      _StartInstanceDisks(self, instance, ignore_secondaries)
3976
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3977
      msg = result.fail_msg
3978
      if msg:
3979
        _ShutdownInstanceDisks(self, instance)
3980
        raise errors.OpExecError("Could not start instance for"
3981
                                 " full reboot: %s" % msg)
3982

    
3983
    self.cfg.MarkInstanceUp(instance.name)
3984

    
3985

    
3986
class LUShutdownInstance(LogicalUnit):
3987
  """Shutdown an instance.
3988

3989
  """
3990
  HPATH = "instance-stop"
3991
  HTYPE = constants.HTYPE_INSTANCE
3992
  _OP_REQP = ["instance_name"]
3993
  REQ_BGL = False
3994

    
3995
  def CheckArguments(self):
3996
    """Check the arguments.
3997

3998
    """
3999
    self.timeout = getattr(self.op, "timeout",
4000
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
4001

    
4002
  def ExpandNames(self):
4003
    self._ExpandAndLockInstance()
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["TIMEOUT"] = self.timeout
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.
4020

4021
    """
4022
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4023
    assert self.instance is not None, \
4024
      "Cannot retrieve locked instance %s" % self.op.instance_name
4025
    _CheckNodeOnline(self, self.instance.primary_node)
4026

    
4027
  def Exec(self, feedback_fn):
4028
    """Shutdown the instance.
4029

4030
    """
4031
    instance = self.instance
4032
    node_current = instance.primary_node
4033
    timeout = self.timeout
4034
    self.cfg.MarkInstanceDown(instance.name)
4035
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4036
    msg = result.fail_msg
4037
    if msg:
4038
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4039

    
4040
    _ShutdownInstanceDisks(self, instance)
4041

    
4042

    
4043
class LUReinstallInstance(LogicalUnit):
4044
  """Reinstall an instance.
4045

4046
  """
4047
  HPATH = "instance-reinstall"
4048
  HTYPE = constants.HTYPE_INSTANCE
4049
  _OP_REQP = ["instance_name"]
4050
  REQ_BGL = False
4051

    
4052
  def ExpandNames(self):
4053
    self._ExpandAndLockInstance()
4054

    
4055
  def BuildHooksEnv(self):
4056
    """Build hooks env.
4057

4058
    This runs on master, primary and secondary nodes of the instance.
4059

4060
    """
4061
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4062
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4063
    return env, nl, nl
4064

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

4068
    This checks that the instance is in the cluster and is not running.
4069

4070
    """
4071
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4072
    assert instance is not None, \
4073
      "Cannot retrieve locked instance %s" % self.op.instance_name
4074
    _CheckNodeOnline(self, instance.primary_node)
4075

    
4076
    if instance.disk_template == constants.DT_DISKLESS:
4077
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4078
                                 self.op.instance_name,
4079
                                 errors.ECODE_INVAL)
4080
    if instance.admin_up:
4081
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
4082
                                 self.op.instance_name,
4083
                                 errors.ECODE_STATE)
4084
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4085
                                              instance.name,
4086
                                              instance.hypervisor)
4087
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4088
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4089
    if remote_info.payload:
4090
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
4091
                                 (self.op.instance_name,
4092
                                  instance.primary_node),
4093
                                 errors.ECODE_STATE)
4094

    
4095
    self.op.os_type = getattr(self.op, "os_type", None)
4096
    self.op.force_variant = getattr(self.op, "force_variant", False)
4097
    if self.op.os_type is not None:
4098
      # OS verification
4099
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4100
      result = self.rpc.call_os_get(pnode, self.op.os_type)
4101
      result.Raise("OS '%s' not in supported OS list for primary node %s" %
4102
                   (self.op.os_type, pnode),
4103
                   prereq=True, ecode=errors.ECODE_INVAL)
4104
      if not self.op.force_variant:
4105
        _CheckOSVariant(result.payload, self.op.os_type)
4106

    
4107
    self.instance = instance
4108

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

4112
    """
4113
    inst = self.instance
4114

    
4115
    if self.op.os_type is not None:
4116
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4117
      inst.os = self.op.os_type
4118
      self.cfg.Update(inst, feedback_fn)
4119

    
4120
    _StartInstanceDisks(self, inst, None)
4121
    try:
4122
      feedback_fn("Running the instance OS create scripts...")
4123
      # FIXME: pass debug option from opcode to backend
4124
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4125
                                             self.op.debug_level)
4126
      result.Raise("Could not install OS for instance %s on node %s" %
4127
                   (inst.name, inst.primary_node))
4128
    finally:
4129
      _ShutdownInstanceDisks(self, inst)
4130

    
4131

    
4132
class LURecreateInstanceDisks(LogicalUnit):
4133
  """Recreate an instance's missing disks.
4134

4135
  """
4136
  HPATH = "instance-recreate-disks"
4137
  HTYPE = constants.HTYPE_INSTANCE
4138
  _OP_REQP = ["instance_name", "disks"]
4139
  REQ_BGL = False
4140

    
4141
  def CheckArguments(self):
4142
    """Check the arguments.
4143

4144
    """
4145
    if not isinstance(self.op.disks, list):
4146
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
4147
    for item in self.op.disks:
4148
      if (not isinstance(item, int) or
4149
          item < 0):
4150
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
4151
                                   str(item), errors.ECODE_INVAL)
4152

    
4153
  def ExpandNames(self):
4154
    self._ExpandAndLockInstance()
4155

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

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

4161
    """
4162
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4163
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4164
    return env, nl, nl
4165

    
4166
  def CheckPrereq(self):
4167
    """Check prerequisites.
4168

4169
    This checks that the instance is in the cluster and is not running.
4170

4171
    """
4172
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4173
    assert instance is not None, \
4174
      "Cannot retrieve locked instance %s" % self.op.instance_name
4175
    _CheckNodeOnline(self, instance.primary_node)
4176

    
4177
    if instance.disk_template == constants.DT_DISKLESS:
4178
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4179
                                 self.op.instance_name, errors.ECODE_INVAL)
4180
    if instance.admin_up:
4181
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
4182
                                 self.op.instance_name, errors.ECODE_STATE)
4183
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4184
                                              instance.name,
4185
                                              instance.hypervisor)
4186
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4187
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4188
    if remote_info.payload:
4189
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
4190
                                 (self.op.instance_name,
4191
                                  instance.primary_node), errors.ECODE_STATE)
4192

    
4193
    if not self.op.disks:
4194
      self.op.disks = range(len(instance.disks))
4195
    else:
4196
      for idx in self.op.disks:
4197
        if idx >= len(instance.disks):
4198
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4199
                                     errors.ECODE_INVAL)
4200

    
4201
    self.instance = instance
4202

    
4203
  def Exec(self, feedback_fn):
4204
    """Recreate the disks.
4205

4206
    """
4207
    to_skip = []
4208
    for idx, _ in enumerate(self.instance.disks):
4209
      if idx not in self.op.disks: # disk idx has not been passed in
4210
        to_skip.append(idx)
4211
        continue
4212

    
4213
    _CreateDisks(self, self.instance, to_skip=to_skip)
4214

    
4215

    
4216
class LURenameInstance(LogicalUnit):
4217
  """Rename an instance.
4218

4219
  """
4220
  HPATH = "instance-rename"
4221
  HTYPE = constants.HTYPE_INSTANCE
4222
  _OP_REQP = ["instance_name", "new_name"]
4223

    
4224
  def BuildHooksEnv(self):
4225
    """Build hooks env.
4226

4227
    This runs on master, primary and secondary nodes of the instance.
4228

4229
    """
4230
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4231
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4232
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4233
    return env, nl, nl
4234

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

4238
    This checks that the instance is in the cluster and is not running.
4239

4240
    """
4241
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4242
                                                self.op.instance_name)
4243
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4244
    assert instance is not None
4245
    _CheckNodeOnline(self, instance.primary_node)
4246

    
4247
    if instance.admin_up:
4248
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
4249
                                 self.op.instance_name, errors.ECODE_STATE)
4250
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4251
                                              instance.name,
4252
                                              instance.hypervisor)
4253
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4254
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4255
    if remote_info.payload:
4256
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
4257
                                 (self.op.instance_name,
4258
                                  instance.primary_node), errors.ECODE_STATE)
4259
    self.instance = instance
4260

    
4261
    # new name verification
4262
    name_info = utils.GetHostInfo(self.op.new_name)
4263

    
4264
    self.op.new_name = new_name = name_info.name
4265
    instance_list = self.cfg.GetInstanceList()
4266
    if new_name in instance_list:
4267
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4268
                                 new_name, errors.ECODE_EXISTS)
4269

    
4270
    if not getattr(self.op, "ignore_ip", False):
4271
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4272
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4273
                                   (name_info.ip, new_name),
4274
                                   errors.ECODE_NOTUNIQUE)
4275

    
4276

    
4277
  def Exec(self, feedback_fn):
4278
    """Reinstall the instance.
4279

4280
    """
4281
    inst = self.instance
4282
    old_name = inst.name
4283

    
4284
    if inst.disk_template == constants.DT_FILE:
4285
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4286

    
4287
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4288
    # Change the instance lock. This is definitely safe while we hold the BGL
4289
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4290
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4291

    
4292
    # re-read the instance from the configuration after rename
4293
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4294

    
4295
    if inst.disk_template == constants.DT_FILE:
4296
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4297
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4298
                                                     old_file_storage_dir,
4299
                                                     new_file_storage_dir)
4300
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4301
                   " (but the instance has been renamed in Ganeti)" %
4302
                   (inst.primary_node, old_file_storage_dir,
4303
                    new_file_storage_dir))
4304

    
4305
    _StartInstanceDisks(self, inst, None)
4306
    try:
4307
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4308
                                                 old_name, self.op.debug_level)
4309
      msg = result.fail_msg
4310
      if msg:
4311
        msg = ("Could not run OS rename script for instance %s on node %s"
4312
               " (but the instance has been renamed in Ganeti): %s" %
4313
               (inst.name, inst.primary_node, msg))
4314
        self.proc.LogWarning(msg)
4315
    finally:
4316
      _ShutdownInstanceDisks(self, inst)
4317

    
4318

    
4319
class LURemoveInstance(LogicalUnit):
4320
  """Remove an instance.
4321

4322
  """
4323
  HPATH = "instance-remove"
4324
  HTYPE = constants.HTYPE_INSTANCE
4325
  _OP_REQP = ["instance_name", "ignore_failures"]
4326
  REQ_BGL = False
4327

    
4328
  def CheckArguments(self):
4329
    """Check the arguments.
4330

4331
    """
4332
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4333
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4334

    
4335
  def ExpandNames(self):
4336
    self._ExpandAndLockInstance()
4337
    self.needed_locks[locking.LEVEL_NODE] = []
4338
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4339

    
4340
  def DeclareLocks(self, level):
4341
    if level == locking.LEVEL_NODE:
4342
      self._LockInstancesNodes()
4343

    
4344
  def BuildHooksEnv(self):
4345
    """Build hooks env.
4346

4347
    This runs on master, primary and secondary nodes of the instance.
4348

4349
    """
4350
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4351
    env["SHUTDOWN_TIMEOUT"] = self.shutdown_timeout
4352
    nl = [self.cfg.GetMasterNode()]
4353
    nl_post = list(self.instance.all_nodes) + nl
4354
    return env, nl, nl_post
4355

    
4356
  def CheckPrereq(self):
4357
    """Check prerequisites.
4358

4359
    This checks that the instance is in the cluster.
4360

4361
    """
4362
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4363
    assert self.instance is not None, \
4364
      "Cannot retrieve locked instance %s" % self.op.instance_name
4365

    
4366
  def Exec(self, feedback_fn):
4367
    """Remove the instance.
4368

4369
    """
4370
    instance = self.instance
4371
    logging.info("Shutting down instance %s on node %s",
4372
                 instance.name, instance.primary_node)
4373

    
4374
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4375
                                             self.shutdown_timeout)
4376
    msg = result.fail_msg
4377
    if msg:
4378
      if self.op.ignore_failures:
4379
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4380
      else:
4381
        raise errors.OpExecError("Could not shutdown instance %s on"
4382
                                 " node %s: %s" %
4383
                                 (instance.name, instance.primary_node, msg))
4384

    
4385
    logging.info("Removing block devices for instance %s", instance.name)
4386

    
4387
    if not _RemoveDisks(self, instance):
4388
      if self.op.ignore_failures:
4389
        feedback_fn("Warning: can't remove instance's disks")
4390
      else:
4391
        raise errors.OpExecError("Can't remove instance's disks")
4392

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

    
4395
    self.cfg.RemoveInstance(instance.name)
4396
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4397

    
4398

    
4399
class LUQueryInstances(NoHooksLU):
4400
  """Logical unit for querying instances.
4401

4402
  """
4403
  # pylint: disable-msg=W0142
4404
  _OP_REQP = ["output_fields", "names", "use_locking"]
4405
  REQ_BGL = False
4406
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4407
                    "serial_no", "ctime", "mtime", "uuid"]
4408
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4409
                                    "admin_state",
4410
                                    "disk_template", "ip", "mac", "bridge",
4411
                                    "nic_mode", "nic_link",
4412
                                    "sda_size", "sdb_size", "vcpus", "tags",
4413
                                    "network_port", "beparams",
4414
                                    r"(disk)\.(size)/([0-9]+)",
4415
                                    r"(disk)\.(sizes)", "disk_usage",
4416
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4417
                                    r"(nic)\.(bridge)/([0-9]+)",
4418
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4419
                                    r"(disk|nic)\.(count)",
4420
                                    "hvparams",
4421
                                    ] + _SIMPLE_FIELDS +
4422
                                  ["hv/%s" % name
4423
                                   for name in constants.HVS_PARAMETERS
4424
                                   if name not in constants.HVC_GLOBALS] +
4425
                                  ["be/%s" % name
4426
                                   for name in constants.BES_PARAMETERS])
4427
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4428

    
4429

    
4430
  def ExpandNames(self):
4431
    _CheckOutputFields(static=self._FIELDS_STATIC,
4432
                       dynamic=self._FIELDS_DYNAMIC,
4433
                       selected=self.op.output_fields)
4434

    
4435
    self.needed_locks = {}
4436
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4437
    self.share_locks[locking.LEVEL_NODE] = 1
4438

    
4439
    if self.op.names:
4440
      self.wanted = _GetWantedInstances(self, self.op.names)
4441
    else:
4442
      self.wanted = locking.ALL_SET
4443

    
4444
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4445
    self.do_locking = self.do_node_query and self.op.use_locking
4446
    if self.do_locking:
4447
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4448
      self.needed_locks[locking.LEVEL_NODE] = []
4449
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4450

    
4451
  def DeclareLocks(self, level):
4452
    if level == locking.LEVEL_NODE and self.do_locking:
4453
      self._LockInstancesNodes()
4454

    
4455
  def CheckPrereq(self):
4456
    """Check prerequisites.
4457

4458
    """
4459
    pass
4460

    
4461
  def Exec(self, feedback_fn):
4462
    """Computes the list of nodes and their attributes.
4463

4464
    """
4465
    # pylint: disable-msg=R0912
4466
    # way too many branches here
4467
    all_info = self.cfg.GetAllInstancesInfo()
4468
    if self.wanted == locking.ALL_SET:
4469
      # caller didn't specify instance names, so ordering is not important
4470
      if self.do_locking:
4471
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4472
      else:
4473
        instance_names = all_info.keys()
4474
      instance_names = utils.NiceSort(instance_names)
4475
    else:
4476
      # caller did specify names, so we must keep the ordering
4477
      if self.do_locking:
4478
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4479
      else:
4480
        tgt_set = all_info.keys()
4481
      missing = set(self.wanted).difference(tgt_set)
4482
      if missing:
4483
        raise errors.OpExecError("Some instances were removed before"
4484
                                 " retrieving their data: %s" % missing)
4485
      instance_names = self.wanted
4486

    
4487
    instance_list = [all_info[iname] for iname in instance_names]
4488

    
4489
    # begin data gathering
4490

    
4491
    nodes = frozenset([inst.primary_node for inst in instance_list])
4492
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4493

    
4494
    bad_nodes = []
4495
    off_nodes = []
4496
    if self.do_node_query:
4497
      live_data = {}
4498
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4499
      for name in nodes:
4500
        result = node_data[name]
4501
        if result.offline:
4502
          # offline nodes will be in both lists
4503
          off_nodes.append(name)
4504
        if result.fail_msg:
4505
          bad_nodes.append(name)
4506
        else:
4507
          if result.payload:
4508
            live_data.update(result.payload)
4509
          # else no instance is alive
4510
    else:
4511
      live_data = dict([(name, {}) for name in instance_names])
4512

    
4513
    # end data gathering
4514

    
4515
    HVPREFIX = "hv/"
4516
    BEPREFIX = "be/"
4517
    output = []
4518
    cluster = self.cfg.GetClusterInfo()
4519
    for instance in instance_list:
4520
      iout = []
4521
      i_hv = cluster.FillHV(instance, skip_globals=True)
4522
      i_be = cluster.FillBE(instance)
4523
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
4524
                                 nic.nicparams) for nic in instance.nics]
4525
      for field in self.op.output_fields:
4526
        st_match = self._FIELDS_STATIC.Matches(field)
4527
        if field in self._SIMPLE_FIELDS:
4528
          val = getattr(instance, field)
4529
        elif field == "pnode":
4530
          val = instance.primary_node
4531
        elif field == "snodes":
4532
          val = list(instance.secondary_nodes)
4533
        elif field == "admin_state":
4534
          val = instance.admin_up
4535
        elif field == "oper_state":
4536
          if instance.primary_node in bad_nodes:
4537
            val = None
4538
          else:
4539
            val = bool(live_data.get(instance.name))
4540
        elif field == "status":
4541
          if instance.primary_node in off_nodes:
4542
            val = "ERROR_nodeoffline"
4543
          elif instance.primary_node in bad_nodes:
4544
            val = "ERROR_nodedown"
4545
          else:
4546
            running = bool(live_data.get(instance.name))
4547
            if running:
4548
              if instance.admin_up:
4549
                val = "running"
4550
              else:
4551
                val = "ERROR_up"
4552
            else:
4553
              if instance.admin_up:
4554
                val = "ERROR_down"
4555
              else:
4556
                val = "ADMIN_down"
4557
        elif field == "oper_ram":
4558
          if instance.primary_node in bad_nodes:
4559
            val = None
4560
          elif instance.name in live_data:
4561
            val = live_data[instance.name].get("memory", "?")
4562
          else:
4563
            val = "-"
4564
        elif field == "vcpus":
4565
          val = i_be[constants.BE_VCPUS]
4566
        elif field == "disk_template":
4567
          val = instance.disk_template
4568
        elif field == "ip":
4569
          if instance.nics:
4570
            val = instance.nics[0].ip
4571
          else:
4572
            val = None
4573
        elif field == "nic_mode":
4574
          if instance.nics:
4575
            val = i_nicp[0][constants.NIC_MODE]
4576
          else:
4577
            val = None
4578
        elif field == "nic_link":
4579
          if instance.nics:
4580
            val = i_nicp[0][constants.NIC_LINK]
4581
          else:
4582
            val = None
4583
        elif field == "bridge":
4584
          if (instance.nics and
4585
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4586
            val = i_nicp[0][constants.NIC_LINK]
4587
          else:
4588
            val = None
4589
        elif field == "mac":
4590
          if instance.nics:
4591
            val = instance.nics[0].mac
4592
          else:
4593
            val = None
4594
        elif field == "sda_size" or field == "sdb_size":
4595
          idx = ord(field[2]) - ord('a')
4596
          try:
4597
            val = instance.FindDisk(idx).size
4598
          except errors.OpPrereqError:
4599
            val = None
4600
        elif field == "disk_usage": # total disk usage per node
4601
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4602
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4603
        elif field == "tags":
4604
          val = list(instance.GetTags())
4605
        elif field == "hvparams":
4606
          val = i_hv
4607
        elif (field.startswith(HVPREFIX) and
4608
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
4609
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
4610
          val = i_hv.get(field[len(HVPREFIX):], None)
4611
        elif field == "beparams":
4612
          val = i_be
4613
        elif (field.startswith(BEPREFIX) and
4614
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4615
          val = i_be.get(field[len(BEPREFIX):], None)
4616
        elif st_match and st_match.groups():
4617
          # matches a variable list
4618
          st_groups = st_match.groups()
4619
          if st_groups and st_groups[0] == "disk":
4620
            if st_groups[1] == "count":
4621
              val = len(instance.disks)
4622
            elif st_groups[1] == "sizes":
4623
              val = [disk.size for disk in instance.disks]
4624
            elif st_groups[1] == "size":
4625
              try:
4626
                val = instance.FindDisk(st_groups[2]).size
4627
              except errors.OpPrereqError:
4628
                val = None
4629
            else:
4630
              assert False, "Unhandled disk parameter"
4631
          elif st_groups[0] == "nic":
4632
            if st_groups[1] == "count":
4633
              val = len(instance.nics)
4634
            elif st_groups[1] == "macs":
4635
              val = [nic.mac for nic in instance.nics]
4636
            elif st_groups[1] == "ips":
4637
              val = [nic.ip for nic in instance.nics]
4638
            elif st_groups[1] == "modes":
4639
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4640
            elif st_groups[1] == "links":
4641
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4642
            elif st_groups[1] == "bridges":
4643
              val = []
4644
              for nicp in i_nicp:
4645
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4646
                  val.append(nicp[constants.NIC_LINK])
4647
                else:
4648
                  val.append(None)
4649
            else:
4650
              # index-based item
4651
              nic_idx = int(st_groups[2])
4652
              if nic_idx >= len(instance.nics):
4653
                val = None
4654
              else:
4655
                if st_groups[1] == "mac":
4656
                  val = instance.nics[nic_idx].mac
4657
                elif st_groups[1] == "ip":
4658
                  val = instance.nics[nic_idx].ip
4659
                elif st_groups[1] == "mode":
4660
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4661
                elif st_groups[1] == "link":
4662
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4663
                elif st_groups[1] == "bridge":
4664
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4665
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4666
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4667
                  else:
4668
                    val = None
4669
                else:
4670
                  assert False, "Unhandled NIC parameter"
4671
          else:
4672
            assert False, ("Declared but unhandled variable parameter '%s'" %
4673
                           field)
4674
        else:
4675
          assert False, "Declared but unhandled parameter '%s'" % field
4676
        iout.append(val)
4677
      output.append(iout)
4678

    
4679
    return output
4680

    
4681

    
4682
class LUFailoverInstance(LogicalUnit):
4683
  """Failover an instance.
4684

4685
  """
4686
  HPATH = "instance-failover"
4687
  HTYPE = constants.HTYPE_INSTANCE
4688
  _OP_REQP = ["instance_name", "ignore_consistency"]
4689
  REQ_BGL = False
4690

    
4691
  def CheckArguments(self):
4692
    """Check the arguments.
4693

4694
    """
4695
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4696
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4697

    
4698
  def ExpandNames(self):
4699
    self._ExpandAndLockInstance()
4700
    self.needed_locks[locking.LEVEL_NODE] = []
4701
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4702

    
4703
  def DeclareLocks(self, level):
4704
    if level == locking.LEVEL_NODE:
4705
      self._LockInstancesNodes()
4706

    
4707
  def BuildHooksEnv(self):
4708
    """Build hooks env.
4709

4710
    This runs on master, primary and secondary nodes of the instance.
4711

4712
    """
4713
    instance = self.instance
4714
    source_node = instance.primary_node
4715
    target_node = instance.secondary_nodes[0]
4716
    env = {
4717
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4718
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4719
      "OLD_PRIMARY": source_node,
4720
      "OLD_SECONDARY": target_node,
4721
      "NEW_PRIMARY": target_node,
4722
      "NEW_SECONDARY": source_node,
4723
      }
4724
    env.update(_BuildInstanceHookEnvByObject(self, instance))
4725
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4726
    nl_post = list(nl)
4727
    nl_post.append(source_node)
4728
    return env, nl, nl_post
4729

    
4730
  def CheckPrereq(self):
4731
    """Check prerequisites.
4732

4733
    This checks that the instance is in the cluster.
4734

4735
    """
4736
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4737
    assert self.instance is not None, \
4738
      "Cannot retrieve locked instance %s" % self.op.instance_name
4739

    
4740
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4741
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4742
      raise errors.OpPrereqError("Instance's disk layout is not"
4743
                                 " network mirrored, cannot failover.",
4744
                                 errors.ECODE_STATE)
4745

    
4746
    secondary_nodes = instance.secondary_nodes
4747
    if not secondary_nodes:
4748
      raise errors.ProgrammerError("no secondary node but using "
4749
                                   "a mirrored disk template")
4750

    
4751
    target_node = secondary_nodes[0]
4752
    _CheckNodeOnline(self, target_node)
4753
    _CheckNodeNotDrained(self, target_node)
4754
    if instance.admin_up:
4755
      # check memory requirements on the secondary node
4756
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4757
                           instance.name, bep[constants.BE_MEMORY],
4758
                           instance.hypervisor)
4759
    else:
4760
      self.LogInfo("Not checking memory on the secondary node as"
4761
                   " instance will not be started")
4762

    
4763
    # check bridge existance
4764
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4765

    
4766
  def Exec(self, feedback_fn):
4767
    """Failover an instance.
4768

4769
    The failover is done by shutting it down on its present node and
4770
    starting it on the secondary.
4771

4772
    """
4773
    instance = self.instance
4774

    
4775
    source_node = instance.primary_node
4776
    target_node = instance.secondary_nodes[0]
4777

    
4778
    if instance.admin_up:
4779
      feedback_fn("* checking disk consistency between source and target")
4780
      for dev in instance.disks:
4781
        # for drbd, these are drbd over lvm
4782
        if not _CheckDiskConsistency(self, dev, target_node, False):
4783
          if not self.op.ignore_consistency:
4784
            raise errors.OpExecError("Disk %s is degraded on target node,"
4785
                                     " aborting failover." % dev.iv_name)
4786
    else:
4787
      feedback_fn("* not checking disk consistency as instance is not running")
4788

    
4789
    feedback_fn("* shutting down instance on source node")
4790
    logging.info("Shutting down instance %s on node %s",
4791
                 instance.name, source_node)
4792

    
4793
    result = self.rpc.call_instance_shutdown(source_node, instance,
4794
                                             self.shutdown_timeout)
4795
    msg = result.fail_msg
4796
    if msg:
4797
      if self.op.ignore_consistency:
4798
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4799
                             " Proceeding anyway. Please make sure node"
4800
                             " %s is down. Error details: %s",
4801
                             instance.name, source_node, source_node, msg)
4802
      else:
4803
        raise errors.OpExecError("Could not shutdown instance %s on"
4804
                                 " node %s: %s" %
4805
                                 (instance.name, source_node, msg))
4806

    
4807
    feedback_fn("* deactivating the instance's disks on source node")
4808
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
4809
      raise errors.OpExecError("Can't shut down the instance's disks.")
4810

    
4811
    instance.primary_node = target_node
4812
    # distribute new instance config to the other nodes
4813
    self.cfg.Update(instance, feedback_fn)
4814

    
4815
    # Only start the instance if it's marked as up
4816
    if instance.admin_up:
4817
      feedback_fn("* activating the instance's disks on target node")
4818
      logging.info("Starting instance %s on node %s",
4819
                   instance.name, target_node)
4820

    
4821
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4822
                                               ignore_secondaries=True)
4823
      if not disks_ok:
4824
        _ShutdownInstanceDisks(self, instance)
4825
        raise errors.OpExecError("Can't activate the instance's disks")
4826

    
4827
      feedback_fn("* starting the instance on the target node")
4828
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4829
      msg = result.fail_msg
4830
      if msg:
4831
        _ShutdownInstanceDisks(self, instance)
4832
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4833
                                 (instance.name, target_node, msg))
4834

    
4835

    
4836
class LUMigrateInstance(LogicalUnit):
4837
  """Migrate an instance.
4838

4839
  This is migration without shutting down, compared to the failover,
4840
  which is done with shutdown.
4841

4842
  """
4843
  HPATH = "instance-migrate"
4844
  HTYPE = constants.HTYPE_INSTANCE
4845
  _OP_REQP = ["instance_name", "live", "cleanup"]
4846

    
4847
  REQ_BGL = False
4848

    
4849
  def ExpandNames(self):
4850
    self._ExpandAndLockInstance()
4851

    
4852
    self.needed_locks[locking.LEVEL_NODE] = []
4853
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4854

    
4855
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
4856
                                       self.op.live, self.op.cleanup)
4857
    self.tasklets = [self._migrater]
4858

    
4859
  def DeclareLocks(self, level):
4860
    if level == locking.LEVEL_NODE:
4861
      self._LockInstancesNodes()
4862

    
4863
  def BuildHooksEnv(self):
4864
    """Build hooks env.
4865

4866
    This runs on master, primary and secondary nodes of the instance.
4867

4868
    """
4869
    instance = self._migrater.instance
4870
    source_node = instance.primary_node
4871
    target_node = instance.secondary_nodes[0]
4872
    env = _BuildInstanceHookEnvByObject(self, instance)
4873
    env["MIGRATE_LIVE"] = self.op.live
4874
    env["MIGRATE_CLEANUP"] = self.op.cleanup
4875
    env.update({
4876
        "OLD_PRIMARY": source_node,
4877
        "OLD_SECONDARY": target_node,
4878
        "NEW_PRIMARY": target_node,
4879
        "NEW_SECONDARY": source_node,
4880
        })
4881
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4882
    nl_post = list(nl)
4883
    nl_post.append(source_node)
4884
    return env, nl, nl_post
4885

    
4886

    
4887
class LUMoveInstance(LogicalUnit):
4888
  """Move an instance by data-copying.
4889

4890
  """
4891
  HPATH = "instance-move"
4892
  HTYPE = constants.HTYPE_INSTANCE
4893
  _OP_REQP = ["instance_name", "target_node"]
4894
  REQ_BGL = False
4895

    
4896
  def CheckArguments(self):
4897
    """Check the arguments.
4898

4899
    """
4900
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4901
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4902

    
4903
  def ExpandNames(self):
4904
    self._ExpandAndLockInstance()
4905
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
4906
    self.op.target_node = target_node
4907
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
4908
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4909

    
4910
  def DeclareLocks(self, level):
4911
    if level == locking.LEVEL_NODE:
4912
      self._LockInstancesNodes(primary_only=True)
4913

    
4914
  def BuildHooksEnv(self):
4915
    """Build hooks env.
4916

4917
    This runs on master, primary and secondary nodes of the instance.
4918

4919
    """
4920
    env = {
4921
      "TARGET_NODE": self.op.target_node,
4922
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4923
      }
4924
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4925
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
4926
                                       self.op.target_node]
4927
    return env, nl, nl
4928

    
4929
  def CheckPrereq(self):
4930
    """Check prerequisites.
4931

4932
    This checks that the instance is in the cluster.
4933

4934
    """
4935
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4936
    assert self.instance is not None, \
4937
      "Cannot retrieve locked instance %s" % self.op.instance_name
4938

    
4939
    node = self.cfg.GetNodeInfo(self.op.target_node)
4940
    assert node is not None, \
4941
      "Cannot retrieve locked node %s" % self.op.target_node
4942

    
4943
    self.target_node = target_node = node.name
4944

    
4945
    if target_node == instance.primary_node:
4946
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
4947
                                 (instance.name, target_node),
4948
                                 errors.ECODE_STATE)
4949

    
4950
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4951

    
4952
    for idx, dsk in enumerate(instance.disks):
4953
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
4954
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
4955
                                   " cannot copy" % idx, errors.ECODE_STATE)
4956

    
4957
    _CheckNodeOnline(self, target_node)
4958
    _CheckNodeNotDrained(self, target_node)
4959

    
4960
    if instance.admin_up:
4961
      # check memory requirements on the secondary node
4962
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4963
                           instance.name, bep[constants.BE_MEMORY],
4964
                           instance.hypervisor)
4965
    else:
4966
      self.LogInfo("Not checking memory on the secondary node as"
4967
                   " instance will not be started")
4968

    
4969
    # check bridge existance
4970
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4971

    
4972
  def Exec(self, feedback_fn):
4973
    """Move an instance.
4974

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

4978
    """
4979
    instance = self.instance
4980

    
4981
    source_node = instance.primary_node
4982
    target_node = self.target_node
4983

    
4984
    self.LogInfo("Shutting down instance %s on source node %s",
4985
                 instance.name, source_node)
4986

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

    
5001
    # create the target disks
5002
    try:
5003
      _CreateDisks(self, instance, target_node=target_node)
5004
    except errors.OpExecError:
5005
      self.LogWarning("Device creation failed, reverting...")
5006
      try:
5007
        _RemoveDisks(self, instance, target_node=target_node)
5008
      finally:
5009
        self.cfg.ReleaseDRBDMinors(instance.name)
5010
        raise
5011

    
5012
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5013

    
5014
    errs = []
5015
    # activate, get path, copy the data over
5016
    for idx, disk in enumerate(instance.disks):
5017
      self.LogInfo("Copying data for disk %d", idx)
5018
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5019
                                               instance.name, True)
5020
      if result.fail_msg:
5021
        self.LogWarning("Can't assemble newly created disk %d: %s",
5022
                        idx, result.fail_msg)
5023
        errs.append(result.fail_msg)
5024
        break
5025
      dev_path = result.payload
5026
      result = self.rpc.call_blockdev_export(source_node, disk,
5027
                                             target_node, dev_path,
5028
                                             cluster_name)
5029
      if result.fail_msg:
5030
        self.LogWarning("Can't copy data over for disk %d: %s",
5031
                        idx, result.fail_msg)
5032
        errs.append(result.fail_msg)
5033
        break
5034

    
5035
    if errs:
5036
      self.LogWarning("Some disks failed to copy, aborting")
5037
      try:
5038
        _RemoveDisks(self, instance, target_node=target_node)
5039
      finally:
5040
        self.cfg.ReleaseDRBDMinors(instance.name)
5041
        raise errors.OpExecError("Errors during disk copy: %s" %
5042
                                 (",".join(errs),))
5043

    
5044
    instance.primary_node = target_node
5045
    self.cfg.Update(instance, feedback_fn)
5046

    
5047
    self.LogInfo("Removing the disks on the original node")
5048
    _RemoveDisks(self, instance, target_node=source_node)
5049

    
5050
    # Only start the instance if it's marked as up
5051
    if instance.admin_up:
5052
      self.LogInfo("Starting instance %s on node %s",
5053
                   instance.name, target_node)
5054

    
5055
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5056
                                           ignore_secondaries=True)
5057
      if not disks_ok:
5058
        _ShutdownInstanceDisks(self, instance)
5059
        raise errors.OpExecError("Can't activate the instance's disks")
5060

    
5061
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5062
      msg = result.fail_msg
5063
      if msg:
5064
        _ShutdownInstanceDisks(self, instance)
5065
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5066
                                 (instance.name, target_node, msg))
5067

    
5068

    
5069
class LUMigrateNode(LogicalUnit):
5070
  """Migrate all instances from a node.
5071

5072
  """
5073
  HPATH = "node-migrate"
5074
  HTYPE = constants.HTYPE_NODE
5075
  _OP_REQP = ["node_name", "live"]
5076
  REQ_BGL = False
5077

    
5078
  def ExpandNames(self):
5079
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5080

    
5081
    self.needed_locks = {
5082
      locking.LEVEL_NODE: [self.op.node_name],
5083
      }
5084

    
5085
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5086

    
5087
    # Create tasklets for migrating instances for all instances on this node
5088
    names = []
5089
    tasklets = []
5090

    
5091
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5092
      logging.debug("Migrating instance %s", inst.name)
5093
      names.append(inst.name)
5094

    
5095
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
5096

    
5097
    self.tasklets = tasklets
5098

    
5099
    # Declare instance locks
5100
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5101

    
5102
  def DeclareLocks(self, level):
5103
    if level == locking.LEVEL_NODE:
5104
      self._LockInstancesNodes()
5105

    
5106
  def BuildHooksEnv(self):
5107
    """Build hooks env.
5108

5109
    This runs on the master, the primary and all the secondaries.
5110

5111
    """
5112
    env = {
5113
      "NODE_NAME": self.op.node_name,
5114
      }
5115

    
5116
    nl = [self.cfg.GetMasterNode()]
5117

    
5118
    return (env, nl, nl)
5119

    
5120

    
5121
class TLMigrateInstance(Tasklet):
5122
  def __init__(self, lu, instance_name, live, cleanup):
5123
    """Initializes this class.
5124

5125
    """
5126
    Tasklet.__init__(self, lu)
5127

    
5128
    # Parameters
5129
    self.instance_name = instance_name
5130
    self.live = live
5131
    self.cleanup = cleanup
5132

    
5133
  def CheckPrereq(self):
5134
    """Check prerequisites.
5135

5136
    This checks that the instance is in the cluster.
5137

5138
    """
5139
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5140
    instance = self.cfg.GetInstanceInfo(instance_name)
5141
    assert instance is not None
5142

    
5143
    if instance.disk_template != constants.DT_DRBD8:
5144
      raise errors.OpPrereqError("Instance's disk layout is not"
5145
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5146

    
5147
    secondary_nodes = instance.secondary_nodes
5148
    if not secondary_nodes:
5149
      raise errors.ConfigurationError("No secondary node but using"
5150
                                      " drbd8 disk template")
5151

    
5152
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5153

    
5154
    target_node = secondary_nodes[0]
5155
    # check memory requirements on the secondary node
5156
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
5157
                         instance.name, i_be[constants.BE_MEMORY],
5158
                         instance.hypervisor)
5159

    
5160
    # check bridge existance
5161
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5162

    
5163
    if not self.cleanup:
5164
      _CheckNodeNotDrained(self, target_node)
5165
      result = self.rpc.call_instance_migratable(instance.primary_node,
5166
                                                 instance)
5167
      result.Raise("Can't migrate, please use failover",
5168
                   prereq=True, ecode=errors.ECODE_STATE)
5169

    
5170
    self.instance = instance
5171

    
5172
  def _WaitUntilSync(self):
5173
    """Poll with custom rpc for disk sync.
5174

5175
    This uses our own step-based rpc call.
5176

5177
    """
5178
    self.feedback_fn("* wait until resync is done")
5179
    all_done = False
5180
    while not all_done:
5181
      all_done = True
5182
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5183
                                            self.nodes_ip,
5184
                                            self.instance.disks)
5185
      min_percent = 100
5186
      for node, nres in result.items():
5187
        nres.Raise("Cannot resync disks on node %s" % node)
5188
        node_done, node_percent = nres.payload
5189
        all_done = all_done and node_done
5190
        if node_percent is not None:
5191
          min_percent = min(min_percent, node_percent)
5192
      if not all_done:
5193
        if min_percent < 100:
5194
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5195
        time.sleep(2)
5196

    
5197
  def _EnsureSecondary(self, node):
5198
    """Demote a node to secondary.
5199

5200
    """
5201
    self.feedback_fn("* switching node %s to secondary mode" % node)
5202

    
5203
    for dev in self.instance.disks:
5204
      self.cfg.SetDiskID(dev, node)
5205

    
5206
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5207
                                          self.instance.disks)
5208
    result.Raise("Cannot change disk to secondary on node %s" % node)
5209

    
5210
  def _GoStandalone(self):
5211
    """Disconnect from the network.
5212

5213
    """
5214
    self.feedback_fn("* changing into standalone mode")
5215
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5216
                                               self.instance.disks)
5217
    for node, nres in result.items():
5218
      nres.Raise("Cannot disconnect disks node %s" % node)
5219

    
5220
  def _GoReconnect(self, multimaster):
5221
    """Reconnect to the network.
5222

5223
    """
5224
    if multimaster:
5225
      msg = "dual-master"
5226
    else:
5227
      msg = "single-master"
5228
    self.feedback_fn("* changing disks into %s mode" % msg)
5229
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5230
                                           self.instance.disks,
5231
                                           self.instance.name, multimaster)
5232
    for node, nres in result.items():
5233
      nres.Raise("Cannot change disks config on node %s" % node)
5234

    
5235
  def _ExecCleanup(self):
5236
    """Try to cleanup after a failed migration.
5237

5238
    The cleanup is done by:
5239
      - check that the instance is running only on one node
5240
        (and update the config if needed)
5241
      - change disks on its secondary node to secondary
5242
      - wait until disks are fully synchronized
5243
      - disconnect from the network
5244
      - change disks into single-master mode
5245
      - wait again until disks are fully synchronized
5246

5247
    """
5248
    instance = self.instance
5249
    target_node = self.target_node
5250
    source_node = self.source_node
5251

    
5252
    # check running on only one node
5253
    self.feedback_fn("* checking where the instance actually runs"
5254
                     " (if this hangs, the hypervisor might be in"
5255
                     " a bad state)")
5256
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5257
    for node, result in ins_l.items():
5258
      result.Raise("Can't contact node %s" % node)
5259

    
5260
    runningon_source = instance.name in ins_l[source_node].payload
5261
    runningon_target = instance.name in ins_l[target_node].payload
5262

    
5263
    if runningon_source and runningon_target:
5264
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5265
                               " or the hypervisor is confused. You will have"
5266
                               " to ensure manually that it runs only on one"
5267
                               " and restart this operation.")
5268

    
5269
    if not (runningon_source or runningon_target):
5270
      raise errors.OpExecError("Instance does not seem to be running at all."
5271
                               " In this case, it's safer to repair by"
5272
                               " running 'gnt-instance stop' to ensure disk"
5273
                               " shutdown, and then restarting it.")
5274

    
5275
    if runningon_target:
5276
      # the migration has actually succeeded, we need to update the config
5277
      self.feedback_fn("* instance running on secondary node (%s),"
5278
                       " updating config" % target_node)
5279
      instance.primary_node = target_node
5280
      self.cfg.Update(instance, self.feedback_fn)
5281
      demoted_node = source_node
5282
    else:
5283
      self.feedback_fn("* instance confirmed to be running on its"
5284
                       " primary node (%s)" % source_node)
5285
      demoted_node = target_node
5286

    
5287
    self._EnsureSecondary(demoted_node)
5288
    try:
5289
      self._WaitUntilSync()
5290
    except errors.OpExecError:
5291
      # we ignore here errors, since if the device is standalone, it
5292
      # won't be able to sync
5293
      pass
5294
    self._GoStandalone()
5295
    self._GoReconnect(False)
5296
    self._WaitUntilSync()
5297

    
5298
    self.feedback_fn("* done")
5299

    
5300
  def _RevertDiskStatus(self):
5301
    """Try to revert the disk status after a failed migration.
5302

5303
    """
5304
    target_node = self.target_node
5305
    try:
5306
      self._EnsureSecondary(target_node)
5307
      self._GoStandalone()
5308
      self._GoReconnect(False)
5309
      self._WaitUntilSync()
5310
    except errors.OpExecError, err:
5311
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5312
                         " drives: error '%s'\n"
5313
                         "Please look and recover the instance status" %
5314
                         str(err))
5315

    
5316
  def _AbortMigration(self):
5317
    """Call the hypervisor code to abort a started migration.
5318

5319
    """
5320
    instance = self.instance
5321
    target_node = self.target_node
5322
    migration_info = self.migration_info
5323

    
5324
    abort_result = self.rpc.call_finalize_migration(target_node,
5325
                                                    instance,
5326
                                                    migration_info,
5327
                                                    False)
5328
    abort_msg = abort_result.fail_msg
5329
    if abort_msg:
5330
      logging.error("Aborting migration failed on target node %s: %s",
5331
                    target_node, abort_msg)
5332
      # Don't raise an exception here, as we stil have to try to revert the
5333
      # disk status, even if this step failed.
5334

    
5335
  def _ExecMigration(self):
5336
    """Migrate an instance.
5337

5338
    The migrate is done by:
5339
      - change the disks into dual-master mode
5340
      - wait until disks are fully synchronized again
5341
      - migrate the instance
5342
      - change disks on the new secondary node (the old primary) to secondary
5343
      - wait until disks are fully synchronized
5344
      - change disks into single-master mode
5345

5346
    """
5347
    instance = self.instance
5348
    target_node = self.target_node
5349
    source_node = self.source_node
5350

    
5351
    self.feedback_fn("* checking disk consistency between source and target")
5352
    for dev in instance.disks:
5353
      if not _CheckDiskConsistency(self, dev, target_node, False):
5354
        raise errors.OpExecError("Disk %s is degraded or not fully"
5355
                                 " synchronized on target node,"
5356
                                 " aborting migrate." % dev.iv_name)
5357

    
5358
    # First get the migration information from the remote node
5359
    result = self.rpc.call_migration_info(source_node, instance)
5360
    msg = result.fail_msg
5361
    if msg:
5362
      log_err = ("Failed fetching source migration information from %s: %s" %
5363
                 (source_node, msg))
5364
      logging.error(log_err)
5365
      raise errors.OpExecError(log_err)
5366

    
5367
    self.migration_info = migration_info = result.payload
5368

    
5369
    # Then switch the disks to master/master mode
5370
    self._EnsureSecondary(target_node)
5371
    self._GoStandalone()
5372
    self._GoReconnect(True)
5373
    self._WaitUntilSync()
5374

    
5375
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5376
    result = self.rpc.call_accept_instance(target_node,
5377
                                           instance,
5378
                                           migration_info,
5379
                                           self.nodes_ip[target_node])
5380

    
5381
    msg = result.fail_msg
5382
    if msg:
5383
      logging.error("Instance pre-migration failed, trying to revert"
5384
                    " disk status: %s", msg)
5385
      self.feedback_fn("Pre-migration failed, aborting")
5386
      self._AbortMigration()
5387
      self._RevertDiskStatus()
5388
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5389
                               (instance.name, msg))
5390

    
5391
    self.feedback_fn("* migrating instance to %s" % target_node)
5392
    time.sleep(10)
5393
    result = self.rpc.call_instance_migrate(source_node, instance,
5394
                                            self.nodes_ip[target_node],
5395
                                            self.live)
5396
    msg = result.fail_msg
5397
    if msg:
5398
      logging.error("Instance migration failed, trying to revert"
5399
                    " disk status: %s", msg)
5400
      self.feedback_fn("Migration failed, aborting")
5401
      self._AbortMigration()
5402
      self._RevertDiskStatus()
5403
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5404
                               (instance.name, msg))
5405
    time.sleep(10)
5406

    
5407
    instance.primary_node = target_node
5408
    # distribute new instance config to the other nodes
5409
    self.cfg.Update(instance, self.feedback_fn)
5410

    
5411
    result = self.rpc.call_finalize_migration(target_node,
5412
                                              instance,
5413
                                              migration_info,
5414
                                              True)
5415
    msg = result.fail_msg
5416
    if msg:
5417
      logging.error("Instance migration succeeded, but finalization failed:"
5418
                    " %s", msg)
5419
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5420
                               msg)
5421

    
5422
    self._EnsureSecondary(source_node)
5423
    self._WaitUntilSync()
5424
    self._GoStandalone()
5425
    self._GoReconnect(False)
5426
    self._WaitUntilSync()
5427

    
5428
    self.feedback_fn("* done")
5429

    
5430
  def Exec(self, feedback_fn):
5431
    """Perform the migration.
5432

5433
    """
5434
    feedback_fn("Migrating instance %s" % self.instance.name)
5435

    
5436
    self.feedback_fn = feedback_fn
5437

    
5438
    self.source_node = self.instance.primary_node
5439
    self.target_node = self.instance.secondary_nodes[0]
5440
    self.all_nodes = [self.source_node, self.target_node]
5441
    self.nodes_ip = {
5442
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5443
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5444
      }
5445

    
5446
    if self.cleanup:
5447
      return self._ExecCleanup()
5448
    else:
5449
      return self._ExecMigration()
5450

    
5451

    
5452
def _CreateBlockDev(lu, node, instance, device, force_create,
5453
                    info, force_open):
5454
  """Create a tree of block devices on a given node.
5455

5456
  If this device type has to be created on secondaries, create it and
5457
  all its children.
5458

5459
  If not, just recurse to children keeping the same 'force' value.
5460

5461
  @param lu: the lu on whose behalf we execute
5462
  @param node: the node on which to create the device
5463
  @type instance: L{objects.Instance}
5464
  @param instance: the instance which owns the device
5465
  @type device: L{objects.Disk}
5466
  @param device: the device to create
5467
  @type force_create: boolean
5468
  @param force_create: whether to force creation of this device; this
5469
      will be change to True whenever we find a device which has
5470
      CreateOnSecondary() attribute
5471
  @param info: the extra 'metadata' we should attach to the device
5472
      (this will be represented as a LVM tag)
5473
  @type force_open: boolean
5474
  @param force_open: this parameter will be passes to the
5475
      L{backend.BlockdevCreate} function where it specifies
5476
      whether we run on primary or not, and it affects both
5477
      the child assembly and the device own Open() execution
5478

5479
  """
5480
  if device.CreateOnSecondary():
5481
    force_create = True
5482

    
5483
  if device.children:
5484
    for child in device.children:
5485
      _CreateBlockDev(lu, node, instance, child, force_create,
5486
                      info, force_open)
5487

    
5488
  if not force_create:
5489
    return
5490

    
5491
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5492

    
5493

    
5494
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5495
  """Create a single block device on a given node.
5496

5497
  This will not recurse over children of the device, so they must be
5498
  created in advance.
5499

5500
  @param lu: the lu on whose behalf we execute
5501
  @param node: the node on which to create the device
5502
  @type instance: L{objects.Instance}
5503
  @param instance: the instance which owns the device
5504
  @type device: L{objects.Disk}
5505
  @param device: the device to create
5506
  @param info: the extra 'metadata' we should attach to the device
5507
      (this will be represented as a LVM tag)
5508
  @type force_open: boolean
5509
  @param force_open: this parameter will be passes to the
5510
      L{backend.BlockdevCreate} function where it specifies
5511
      whether we run on primary or not, and it affects both
5512
      the child assembly and the device own Open() execution
5513

5514
  """
5515
  lu.cfg.SetDiskID(device, node)
5516
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5517
                                       instance.name, force_open, info)
5518
  result.Raise("Can't create block device %s on"
5519
               " node %s for instance %s" % (device, node, instance.name))
5520
  if device.physical_id is None:
5521
    device.physical_id = result.payload
5522

    
5523

    
5524
def _GenerateUniqueNames(lu, exts):
5525
  """Generate a suitable LV name.
5526

5527
  This will generate a logical volume name for the given instance.
5528

5529
  """
5530
  results = []
5531
  for val in exts:
5532
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
5533
    results.append("%s%s" % (new_id, val))
5534
  return results
5535

    
5536

    
5537
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5538
                         p_minor, s_minor):
5539
  """Generate a drbd8 device complete with its children.
5540

5541
  """
5542
  port = lu.cfg.AllocatePort()
5543
  vgname = lu.cfg.GetVGName()
5544
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
5545
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5546
                          logical_id=(vgname, names[0]))
5547
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5548
                          logical_id=(vgname, names[1]))
5549
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5550
                          logical_id=(primary, secondary, port,
5551
                                      p_minor, s_minor,
5552
                                      shared_secret),
5553
                          children=[dev_data, dev_meta],
5554
                          iv_name=iv_name)
5555
  return drbd_dev
5556

    
5557

    
5558
def _GenerateDiskTemplate(lu, template_name,
5559
                          instance_name, primary_node,
5560
                          secondary_nodes, disk_info,
5561
                          file_storage_dir, file_driver,
5562
                          base_index):
5563
  """Generate the entire disk layout for a given template type.
5564

5565
  """
5566
  #TODO: compute space requirements
5567

    
5568
  vgname = lu.cfg.GetVGName()
5569
  disk_count = len(disk_info)
5570
  disks = []
5571
  if template_name == constants.DT_DISKLESS:
5572
    pass
5573
  elif template_name == constants.DT_PLAIN:
5574
    if len(secondary_nodes) != 0:
5575
      raise errors.ProgrammerError("Wrong template configuration")
5576

    
5577
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5578
                                      for i in range(disk_count)])
5579
    for idx, disk in enumerate(disk_info):
5580
      disk_index = idx + base_index
5581
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5582
                              logical_id=(vgname, names[idx]),
5583
                              iv_name="disk/%d" % disk_index,
5584
                              mode=disk["mode"])
5585
      disks.append(disk_dev)
5586
  elif template_name == constants.DT_DRBD8:
5587
    if len(secondary_nodes) != 1:
5588
      raise errors.ProgrammerError("Wrong template configuration")
5589
    remote_node = secondary_nodes[0]
5590
    minors = lu.cfg.AllocateDRBDMinor(
5591
      [primary_node, remote_node] * len(disk_info), instance_name)
5592

    
5593
    names = []
5594
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5595
                                               for i in range(disk_count)]):
5596
      names.append(lv_prefix + "_data")
5597
      names.append(lv_prefix + "_meta")
5598
    for idx, disk in enumerate(disk_info):
5599
      disk_index = idx + base_index
5600
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5601
                                      disk["size"], names[idx*2:idx*2+2],
5602
                                      "disk/%d" % disk_index,
5603
                                      minors[idx*2], minors[idx*2+1])
5604
      disk_dev.mode = disk["mode"]
5605
      disks.append(disk_dev)
5606
  elif template_name == constants.DT_FILE:
5607
    if len(secondary_nodes) != 0:
5608
      raise errors.ProgrammerError("Wrong template configuration")
5609

    
5610
    for idx, disk in enumerate(disk_info):
5611
      disk_index = idx + base_index
5612
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5613
                              iv_name="disk/%d" % disk_index,
5614
                              logical_id=(file_driver,
5615
                                          "%s/disk%d" % (file_storage_dir,
5616
                                                         disk_index)),
5617
                              mode=disk["mode"])
5618
      disks.append(disk_dev)
5619
  else:
5620
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5621
  return disks
5622

    
5623

    
5624
def _GetInstanceInfoText(instance):
5625
  """Compute that text that should be added to the disk's metadata.
5626

5627
  """
5628
  return "originstname+%s" % instance.name
5629

    
5630

    
5631
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5632
  """Create all disks for an instance.
5633

5634
  This abstracts away some work from AddInstance.
5635

5636
  @type lu: L{LogicalUnit}
5637
  @param lu: the logical unit on whose behalf we execute
5638
  @type instance: L{objects.Instance}
5639
  @param instance: the instance whose disks we should create
5640
  @type to_skip: list
5641
  @param to_skip: list of indices to skip
5642
  @type target_node: string
5643
  @param target_node: if passed, overrides the target node for creation
5644
  @rtype: boolean
5645
  @return: the success of the creation
5646

5647
  """
5648
  info = _GetInstanceInfoText(instance)
5649
  if target_node is None:
5650
    pnode = instance.primary_node
5651
    all_nodes = instance.all_nodes
5652
  else:
5653
    pnode = target_node
5654
    all_nodes = [pnode]
5655

    
5656
  if instance.disk_template == constants.DT_FILE:
5657
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5658
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5659

    
5660
    result.Raise("Failed to create directory '%s' on"
5661
                 " node %s" % (file_storage_dir, pnode))
5662

    
5663
  # Note: this needs to be kept in sync with adding of disks in
5664
  # LUSetInstanceParams
5665
  for idx, device in enumerate(instance.disks):
5666
    if to_skip and idx in to_skip:
5667
      continue
5668
    logging.info("Creating volume %s for instance %s",
5669
                 device.iv_name, instance.name)
5670
    #HARDCODE
5671
    for node in all_nodes:
5672
      f_create = node == pnode
5673
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5674

    
5675

    
5676
def _RemoveDisks(lu, instance, target_node=None):
5677
  """Remove all disks for an instance.
5678

5679
  This abstracts away some work from `AddInstance()` and
5680
  `RemoveInstance()`. Note that in case some of the devices couldn't
5681
  be removed, the removal will continue with the other ones (compare
5682
  with `_CreateDisks()`).
5683

5684
  @type lu: L{LogicalUnit}
5685
  @param lu: the logical unit on whose behalf we execute
5686
  @type instance: L{objects.Instance}
5687
  @param instance: the instance whose disks we should remove
5688
  @type target_node: string
5689
  @param target_node: used to override the node on which to remove the disks
5690
  @rtype: boolean
5691
  @return: the success of the removal
5692

5693
  """
5694
  logging.info("Removing block devices for instance %s", instance.name)
5695

    
5696
  all_result = True
5697
  for device in instance.disks:
5698
    if target_node:
5699
      edata = [(target_node, device)]
5700
    else:
5701
      edata = device.ComputeNodeTree(instance.primary_node)
5702
    for node, disk in edata:
5703
      lu.cfg.SetDiskID(disk, node)
5704
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5705
      if msg:
5706
        lu.LogWarning("Could not remove block device %s on node %s,"
5707
                      " continuing anyway: %s", device.iv_name, node, msg)
5708
        all_result = False
5709

    
5710
  if instance.disk_template == constants.DT_FILE:
5711
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5712
    if target_node:
5713
      tgt = target_node
5714
    else:
5715
      tgt = instance.primary_node
5716
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5717
    if result.fail_msg:
5718
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5719
                    file_storage_dir, instance.primary_node, result.fail_msg)
5720
      all_result = False
5721

    
5722
  return all_result
5723

    
5724

    
5725
def _ComputeDiskSize(disk_template, disks):
5726
  """Compute disk size requirements in the volume group
5727

5728
  """
5729
  # Required free disk space as a function of disk and swap space
5730
  req_size_dict = {
5731
    constants.DT_DISKLESS: None,
5732
    constants.DT_PLAIN: sum(d["size"] for d in disks),
5733
    # 128 MB are added for drbd metadata for each disk
5734
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
5735
    constants.DT_FILE: None,
5736
  }
5737

    
5738
  if disk_template not in req_size_dict:
5739
    raise errors.ProgrammerError("Disk template '%s' size requirement"
5740
                                 " is unknown" %  disk_template)
5741

    
5742
  return req_size_dict[disk_template]
5743

    
5744

    
5745
def _CheckHVParams(lu, nodenames, hvname, hvparams):
5746
  """Hypervisor parameter validation.
5747

5748
  This function abstract the hypervisor parameter validation to be
5749
  used in both instance create and instance modify.
5750

5751
  @type lu: L{LogicalUnit}
5752
  @param lu: the logical unit for which we check
5753
  @type nodenames: list
5754
  @param nodenames: the list of nodes on which we should check
5755
  @type hvname: string
5756
  @param hvname: the name of the hypervisor we should use
5757
  @type hvparams: dict
5758
  @param hvparams: the parameters which we need to check
5759
  @raise errors.OpPrereqError: if the parameters are not valid
5760

5761
  """
5762
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
5763
                                                  hvname,
5764
                                                  hvparams)
5765
  for node in nodenames:
5766
    info = hvinfo[node]
5767
    if info.offline:
5768
      continue
5769
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
5770

    
5771

    
5772
class LUCreateInstance(LogicalUnit):
5773
  """Create an instance.
5774

5775
  """
5776
  HPATH = "instance-add"
5777
  HTYPE = constants.HTYPE_INSTANCE
5778
  _OP_REQP = ["instance_name", "disks", "disk_template",
5779
              "mode", "start",
5780
              "wait_for_sync", "ip_check", "nics",
5781
              "hvparams", "beparams"]
5782
  REQ_BGL = False
5783

    
5784
  def CheckArguments(self):
5785
    """Check arguments.
5786

5787
    """
5788
    # do not require name_check to ease forward/backward compatibility
5789
    # for tools
5790
    if not hasattr(self.op, "name_check"):
5791
      self.op.name_check = True
5792
    # validate/normalize the instance name
5793
    self.op.instance_name = utils.HostInfo.NormalizeName(self.op.instance_name)
5794
    if self.op.ip_check and not self.op.name_check:
5795
      # TODO: make the ip check more flexible and not depend on the name check
5796
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
5797
                                 errors.ECODE_INVAL)
5798
    if (self.op.disk_template == constants.DT_FILE and
5799
        not constants.ENABLE_FILE_STORAGE):
5800
      raise errors.OpPrereqError("File storage disabled at configure time",
5801
                                 errors.ECODE_INVAL)
5802

    
5803
  def ExpandNames(self):
5804
    """ExpandNames for CreateInstance.
5805

5806
    Figure out the right locks for instance creation.
5807

5808
    """
5809
    self.needed_locks = {}
5810

    
5811
    # set optional parameters to none if they don't exist
5812
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
5813
      if not hasattr(self.op, attr):
5814
        setattr(self.op, attr, None)
5815

    
5816
    # cheap checks, mostly valid constants given
5817

    
5818
    # verify creation mode
5819
    if self.op.mode not in (constants.INSTANCE_CREATE,
5820
                            constants.INSTANCE_IMPORT):
5821
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
5822
                                 self.op.mode, errors.ECODE_INVAL)
5823

    
5824
    # disk template and mirror node verification
5825
    if self.op.disk_template not in constants.DISK_TEMPLATES:
5826
      raise errors.OpPrereqError("Invalid disk template name",
5827
                                 errors.ECODE_INVAL)
5828

    
5829
    if self.op.hypervisor is None:
5830
      self.op.hypervisor = self.cfg.GetHypervisorType()
5831

    
5832
    cluster = self.cfg.GetClusterInfo()
5833
    enabled_hvs = cluster.enabled_hypervisors
5834
    if self.op.hypervisor not in enabled_hvs:
5835
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
5836
                                 " cluster (%s)" % (self.op.hypervisor,
5837
                                  ",".join(enabled_hvs)),
5838
                                 errors.ECODE_STATE)
5839

    
5840
    # check hypervisor parameter syntax (locally)
5841
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5842
    filled_hvp = objects.FillDict(cluster.hvparams[self.op.hypervisor],
5843
                                  self.op.hvparams)
5844
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
5845
    hv_type.CheckParameterSyntax(filled_hvp)
5846
    self.hv_full = filled_hvp
5847
    # check that we don't specify global parameters on an instance
5848
    _CheckGlobalHvParams(self.op.hvparams)
5849

    
5850
    # fill and remember the beparams dict
5851
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5852
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
5853
                                    self.op.beparams)
5854

    
5855
    #### instance parameters check
5856

    
5857
    # instance name verification
5858
    if self.op.name_check:
5859
      hostname1 = utils.GetHostInfo(self.op.instance_name)
5860
      self.op.instance_name = instance_name = hostname1.name
5861
      # used in CheckPrereq for ip ping check
5862
      self.check_ip = hostname1.ip
5863
    else:
5864
      instance_name = self.op.instance_name
5865
      self.check_ip = None
5866

    
5867
    # this is just a preventive check, but someone might still add this
5868
    # instance in the meantime, and creation will fail at lock-add time
5869
    if instance_name in self.cfg.GetInstanceList():
5870
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5871
                                 instance_name, errors.ECODE_EXISTS)
5872

    
5873
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
5874

    
5875
    # NIC buildup
5876
    self.nics = []
5877
    for idx, nic in enumerate(self.op.nics):
5878
      nic_mode_req = nic.get("mode", None)
5879
      nic_mode = nic_mode_req
5880
      if nic_mode is None:
5881
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
5882

    
5883
      # in routed mode, for the first nic, the default ip is 'auto'
5884
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
5885
        default_ip_mode = constants.VALUE_AUTO
5886
      else:
5887
        default_ip_mode = constants.VALUE_NONE
5888

    
5889
      # ip validity checks
5890
      ip = nic.get("ip", default_ip_mode)
5891
      if ip is None or ip.lower() == constants.VALUE_NONE:
5892
        nic_ip = None
5893
      elif ip.lower() == constants.VALUE_AUTO:
5894
        if not self.op.name_check:
5895
          raise errors.OpPrereqError("IP address set to auto but name checks"
5896
                                     " have been skipped. Aborting.",
5897
                                     errors.ECODE_INVAL)
5898
        nic_ip = hostname1.ip
5899
      else:
5900
        if not utils.IsValidIP(ip):
5901
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
5902
                                     " like a valid IP" % ip,
5903
                                     errors.ECODE_INVAL)
5904
        nic_ip = ip
5905

    
5906
      # TODO: check the ip address for uniqueness
5907
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
5908
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
5909
                                   errors.ECODE_INVAL)
5910

    
5911
      # MAC address verification
5912
      mac = nic.get("mac", constants.VALUE_AUTO)
5913
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5914
        mac = utils.NormalizeAndValidateMac(mac)
5915

    
5916
        try:
5917
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
5918
        except errors.ReservationError:
5919
          raise errors.OpPrereqError("MAC address %s already in use"
5920
                                     " in cluster" % mac,
5921
                                     errors.ECODE_NOTUNIQUE)
5922

    
5923
      # bridge verification
5924
      bridge = nic.get("bridge", None)
5925
      link = nic.get("link", None)
5926
      if bridge and link:
5927
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
5928
                                   " at the same time", errors.ECODE_INVAL)
5929
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
5930
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
5931
                                   errors.ECODE_INVAL)
5932
      elif bridge:
5933
        link = bridge
5934

    
5935
      nicparams = {}
5936
      if nic_mode_req:
5937
        nicparams[constants.NIC_MODE] = nic_mode_req
5938
      if link:
5939
        nicparams[constants.NIC_LINK] = link
5940

    
5941
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
5942
                                      nicparams)
5943
      objects.NIC.CheckParameterSyntax(check_params)
5944
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
5945

    
5946
    # disk checks/pre-build
5947
    self.disks = []
5948
    for disk in self.op.disks:
5949
      mode = disk.get("mode", constants.DISK_RDWR)
5950
      if mode not in constants.DISK_ACCESS_SET:
5951
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
5952
                                   mode, errors.ECODE_INVAL)
5953
      size = disk.get("size", None)
5954
      if size is None:
5955
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
5956
      try:
5957
        size = int(size)
5958
      except (TypeError, ValueError):
5959
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
5960
                                   errors.ECODE_INVAL)
5961
      self.disks.append({"size": size, "mode": mode})
5962

    
5963
    # file storage checks
5964
    if (self.op.file_driver and
5965
        not self.op.file_driver in constants.FILE_DRIVER):
5966
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
5967
                                 self.op.file_driver, errors.ECODE_INVAL)
5968

    
5969
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
5970
      raise errors.OpPrereqError("File storage directory path not absolute",
5971
                                 errors.ECODE_INVAL)
5972

    
5973
    ### Node/iallocator related checks
5974
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
5975
      raise errors.OpPrereqError("One and only one of iallocator and primary"
5976
                                 " node must be given",
5977
                                 errors.ECODE_INVAL)
5978

    
5979
    if self.op.iallocator:
5980
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5981
    else:
5982
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
5983
      nodelist = [self.op.pnode]
5984
      if self.op.snode is not None:
5985
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
5986
        nodelist.append(self.op.snode)
5987
      self.needed_locks[locking.LEVEL_NODE] = nodelist
5988

    
5989
    # in case of import lock the source node too
5990
    if self.op.mode == constants.INSTANCE_IMPORT:
5991
      src_node = getattr(self.op, "src_node", None)
5992
      src_path = getattr(self.op, "src_path", None)
5993

    
5994
      if src_path is None:
5995
        self.op.src_path = src_path = self.op.instance_name
5996

    
5997
      if src_node is None:
5998
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5999
        self.op.src_node = None
6000
        if os.path.isabs(src_path):
6001
          raise errors.OpPrereqError("Importing an instance from an absolute"
6002
                                     " path requires a source node option.",
6003
                                     errors.ECODE_INVAL)
6004
      else:
6005
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6006
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6007
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6008
        if not os.path.isabs(src_path):
6009
          self.op.src_path = src_path = \
6010
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6011

    
6012
      # On import force_variant must be True, because if we forced it at
6013
      # initial install, our only chance when importing it back is that it
6014
      # works again!
6015
      self.op.force_variant = True
6016

    
6017
    else: # INSTANCE_CREATE
6018
      if getattr(self.op, "os_type", None) is None:
6019
        raise errors.OpPrereqError("No guest OS specified",
6020
                                   errors.ECODE_INVAL)
6021
      self.op.force_variant = getattr(self.op, "force_variant", False)
6022

    
6023
  def _RunAllocator(self):
6024
    """Run the allocator based on input opcode.
6025

6026
    """
6027
    nics = [n.ToDict() for n in self.nics]
6028
    ial = IAllocator(self.cfg, self.rpc,
6029
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6030
                     name=self.op.instance_name,
6031
                     disk_template=self.op.disk_template,
6032
                     tags=[],
6033
                     os=self.op.os_type,
6034
                     vcpus=self.be_full[constants.BE_VCPUS],
6035
                     mem_size=self.be_full[constants.BE_MEMORY],
6036
                     disks=self.disks,
6037
                     nics=nics,
6038
                     hypervisor=self.op.hypervisor,
6039
                     )
6040

    
6041
    ial.Run(self.op.iallocator)
6042

    
6043
    if not ial.success:
6044
      raise errors.OpPrereqError("Can't compute nodes using"
6045
                                 " iallocator '%s': %s" %
6046
                                 (self.op.iallocator, ial.info),
6047
                                 errors.ECODE_NORES)
6048
    if len(ial.result) != ial.required_nodes:
6049
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6050
                                 " of nodes (%s), required %s" %
6051
                                 (self.op.iallocator, len(ial.result),
6052
                                  ial.required_nodes), errors.ECODE_FAULT)
6053
    self.op.pnode = ial.result[0]
6054
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6055
                 self.op.instance_name, self.op.iallocator,
6056
                 utils.CommaJoin(ial.result))
6057
    if ial.required_nodes == 2:
6058
      self.op.snode = ial.result[1]
6059

    
6060
  def BuildHooksEnv(self):
6061
    """Build hooks env.
6062

6063
    This runs on master, primary and secondary nodes of the instance.
6064

6065
    """
6066
    env = {
6067
      "ADD_MODE": self.op.mode,
6068
      }
6069
    if self.op.mode == constants.INSTANCE_IMPORT:
6070
      env["SRC_NODE"] = self.op.src_node
6071
      env["SRC_PATH"] = self.op.src_path
6072
      env["SRC_IMAGES"] = self.src_images
6073

    
6074
    env.update(_BuildInstanceHookEnv(
6075
      name=self.op.instance_name,
6076
      primary_node=self.op.pnode,
6077
      secondary_nodes=self.secondaries,
6078
      status=self.op.start,
6079
      os_type=self.op.os_type,
6080
      memory=self.be_full[constants.BE_MEMORY],
6081
      vcpus=self.be_full[constants.BE_VCPUS],
6082
      nics=_NICListToTuple(self, self.nics),
6083
      disk_template=self.op.disk_template,
6084
      disks=[(d["size"], d["mode"]) for d in self.disks],
6085
      bep=self.be_full,
6086
      hvp=self.hv_full,
6087
      hypervisor_name=self.op.hypervisor,
6088
    ))
6089

    
6090
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6091
          self.secondaries)
6092
    return env, nl, nl
6093

    
6094

    
6095
  def CheckPrereq(self):
6096
    """Check prerequisites.
6097

6098
    """
6099
    if (not self.cfg.GetVGName() and
6100
        self.op.disk_template not in constants.DTS_NOT_LVM):
6101
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6102
                                 " instances", errors.ECODE_STATE)
6103

    
6104
    if self.op.mode == constants.INSTANCE_IMPORT:
6105
      src_node = self.op.src_node
6106
      src_path = self.op.src_path
6107

    
6108
      if src_node is None:
6109
        locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6110
        exp_list = self.rpc.call_export_list(locked_nodes)
6111
        found = False
6112
        for node in exp_list:
6113
          if exp_list[node].fail_msg:
6114
            continue
6115
          if src_path in exp_list[node].payload:
6116
            found = True
6117
            self.op.src_node = src_node = node
6118
            self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6119
                                                         src_path)
6120
            break
6121
        if not found:
6122
          raise errors.OpPrereqError("No export found for relative path %s" %
6123
                                      src_path, errors.ECODE_INVAL)
6124

    
6125
      _CheckNodeOnline(self, src_node)
6126
      result = self.rpc.call_export_info(src_node, src_path)
6127
      result.Raise("No export or invalid export found in dir %s" % src_path)
6128

    
6129
      export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6130
      if not export_info.has_section(constants.INISECT_EXP):
6131
        raise errors.ProgrammerError("Corrupted export config",
6132
                                     errors.ECODE_ENVIRON)
6133

    
6134
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
6135
      if (int(ei_version) != constants.EXPORT_VERSION):
6136
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6137
                                   (ei_version, constants.EXPORT_VERSION),
6138
                                   errors.ECODE_ENVIRON)
6139

    
6140
      # Check that the new instance doesn't have less disks than the export
6141
      instance_disks = len(self.disks)
6142
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6143
      if instance_disks < export_disks:
6144
        raise errors.OpPrereqError("Not enough disks to import."
6145
                                   " (instance: %d, export: %d)" %
6146
                                   (instance_disks, export_disks),
6147
                                   errors.ECODE_INVAL)
6148

    
6149
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
6150
      disk_images = []
6151
      for idx in range(export_disks):
6152
        option = 'disk%d_dump' % idx
6153
        if export_info.has_option(constants.INISECT_INS, option):
6154
          # FIXME: are the old os-es, disk sizes, etc. useful?
6155
          export_name = export_info.get(constants.INISECT_INS, option)
6156
          image = utils.PathJoin(src_path, export_name)
6157
          disk_images.append(image)
6158
        else:
6159
          disk_images.append(False)
6160

    
6161
      self.src_images = disk_images
6162

    
6163
      old_name = export_info.get(constants.INISECT_INS, 'name')
6164
      # FIXME: int() here could throw a ValueError on broken exports
6165
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
6166
      if self.op.instance_name == old_name:
6167
        for idx, nic in enumerate(self.nics):
6168
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
6169
            nic_mac_ini = 'nic%d_mac' % idx
6170
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
6171

    
6172
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
6173

    
6174
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
6175
    if self.op.ip_check:
6176
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
6177
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6178
                                   (self.check_ip, self.op.instance_name),
6179
                                   errors.ECODE_NOTUNIQUE)
6180

    
6181
    #### mac address generation
6182
    # By generating here the mac address both the allocator and the hooks get
6183
    # the real final mac address rather than the 'auto' or 'generate' value.
6184
    # There is a race condition between the generation and the instance object
6185
    # creation, which means that we know the mac is valid now, but we're not
6186
    # sure it will be when we actually add the instance. If things go bad
6187
    # adding the instance will abort because of a duplicate mac, and the
6188
    # creation job will fail.
6189
    for nic in self.nics:
6190
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6191
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
6192

    
6193
    #### allocator run
6194

    
6195
    if self.op.iallocator is not None:
6196
      self._RunAllocator()
6197

    
6198
    #### node related checks
6199

    
6200
    # check primary node
6201
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
6202
    assert self.pnode is not None, \
6203
      "Cannot retrieve locked node %s" % self.op.pnode
6204
    if pnode.offline:
6205
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
6206
                                 pnode.name, errors.ECODE_STATE)
6207
    if pnode.drained:
6208
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
6209
                                 pnode.name, errors.ECODE_STATE)
6210

    
6211
    self.secondaries = []
6212

    
6213
    # mirror node verification
6214
    if self.op.disk_template in constants.DTS_NET_MIRROR:
6215
      if self.op.snode is None:
6216
        raise errors.OpPrereqError("The networked disk templates need"
6217
                                   " a mirror node", errors.ECODE_INVAL)
6218
      if self.op.snode == pnode.name:
6219
        raise errors.OpPrereqError("The secondary node cannot be the"
6220
                                   " primary node.", errors.ECODE_INVAL)
6221
      _CheckNodeOnline(self, self.op.snode)
6222
      _CheckNodeNotDrained(self, self.op.snode)
6223
      self.secondaries.append(self.op.snode)
6224

    
6225
    nodenames = [pnode.name] + self.secondaries
6226

    
6227
    req_size = _ComputeDiskSize(self.op.disk_template,
6228
                                self.disks)
6229

    
6230
    # Check lv size requirements
6231
    if req_size is not None:
6232
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
6233
                                         self.op.hypervisor)
6234
      for node in nodenames:
6235
        info = nodeinfo[node]
6236
        info.Raise("Cannot get current information from node %s" % node)
6237
        info = info.payload
6238
        vg_free = info.get('vg_free', None)
6239
        if not isinstance(vg_free, int):
6240
          raise errors.OpPrereqError("Can't compute free disk space on"
6241
                                     " node %s" % node, errors.ECODE_ENVIRON)
6242
        if req_size > vg_free:
6243
          raise errors.OpPrereqError("Not enough disk space on target node %s."
6244
                                     " %d MB available, %d MB required" %
6245
                                     (node, vg_free, req_size),
6246
                                     errors.ECODE_NORES)
6247

    
6248
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
6249

    
6250
    # os verification
6251
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
6252
    result.Raise("OS '%s' not in supported os list for primary node %s" %
6253
                 (self.op.os_type, pnode.name),
6254
                 prereq=True, ecode=errors.ECODE_INVAL)
6255
    if not self.op.force_variant:
6256
      _CheckOSVariant(result.payload, self.op.os_type)
6257

    
6258
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
6259

    
6260
    # memory check on primary node
6261
    if self.op.start:
6262
      _CheckNodeFreeMemory(self, self.pnode.name,
6263
                           "creating instance %s" % self.op.instance_name,
6264
                           self.be_full[constants.BE_MEMORY],
6265
                           self.op.hypervisor)
6266

    
6267
    self.dry_run_result = list(nodenames)
6268

    
6269
  def Exec(self, feedback_fn):
6270
    """Create and add the instance to the cluster.
6271

6272
    """
6273
    instance = self.op.instance_name
6274
    pnode_name = self.pnode.name
6275

    
6276
    ht_kind = self.op.hypervisor
6277
    if ht_kind in constants.HTS_REQ_PORT:
6278
      network_port = self.cfg.AllocatePort()
6279
    else:
6280
      network_port = None
6281

    
6282
    ##if self.op.vnc_bind_address is None:
6283
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
6284

    
6285
    # this is needed because os.path.join does not accept None arguments
6286
    if self.op.file_storage_dir is None:
6287
      string_file_storage_dir = ""
6288
    else:
6289
      string_file_storage_dir = self.op.file_storage_dir
6290

    
6291
    # build the full file storage dir path
6292
    file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
6293
                                      string_file_storage_dir, instance)
6294

    
6295

    
6296
    disks = _GenerateDiskTemplate(self,
6297
                                  self.op.disk_template,
6298
                                  instance, pnode_name,
6299
                                  self.secondaries,
6300
                                  self.disks,
6301
                                  file_storage_dir,
6302
                                  self.op.file_driver,
6303
                                  0)
6304

    
6305
    iobj = objects.Instance(name=instance, os=self.op.os_type,
6306
                            primary_node=pnode_name,
6307
                            nics=self.nics, disks=disks,
6308
                            disk_template=self.op.disk_template,
6309
                            admin_up=False,
6310
                            network_port=network_port,
6311
                            beparams=self.op.beparams,
6312
                            hvparams=self.op.hvparams,
6313
                            hypervisor=self.op.hypervisor,
6314
                            )
6315

    
6316
    feedback_fn("* creating instance disks...")
6317
    try:
6318
      _CreateDisks(self, iobj)
6319
    except errors.OpExecError:
6320
      self.LogWarning("Device creation failed, reverting...")
6321
      try:
6322
        _RemoveDisks(self, iobj)
6323
      finally:
6324
        self.cfg.ReleaseDRBDMinors(instance)
6325
        raise
6326

    
6327
    feedback_fn("adding instance %s to cluster config" % instance)
6328

    
6329
    self.cfg.AddInstance(iobj, self.proc.GetECId())
6330

    
6331
    # Declare that we don't want to remove the instance lock anymore, as we've
6332
    # added the instance to the config
6333
    del self.remove_locks[locking.LEVEL_INSTANCE]
6334
    # Unlock all the nodes
6335
    if self.op.mode == constants.INSTANCE_IMPORT:
6336
      nodes_keep = [self.op.src_node]
6337
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
6338
                       if node != self.op.src_node]
6339
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
6340
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6341
    else:
6342
      self.context.glm.release(locking.LEVEL_NODE)
6343
      del self.acquired_locks[locking.LEVEL_NODE]
6344

    
6345
    if self.op.wait_for_sync:
6346
      disk_abort = not _WaitForSync(self, iobj)
6347
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
6348
      # make sure the disks are not degraded (still sync-ing is ok)
6349
      time.sleep(15)
6350
      feedback_fn("* checking mirrors status")
6351
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
6352
    else:
6353
      disk_abort = False
6354

    
6355
    if disk_abort:
6356
      _RemoveDisks(self, iobj)
6357
      self.cfg.RemoveInstance(iobj.name)
6358
      # Make sure the instance lock gets removed
6359
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
6360
      raise errors.OpExecError("There are some degraded disks for"
6361
                               " this instance")
6362

    
6363
    feedback_fn("creating os for instance %s on node %s" %
6364
                (instance, pnode_name))
6365

    
6366
    if iobj.disk_template != constants.DT_DISKLESS:
6367
      if self.op.mode == constants.INSTANCE_CREATE:
6368
        feedback_fn("* running the instance OS create scripts...")
6369
        # FIXME: pass debug option from opcode to backend
6370
        result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
6371
                                               self.op.debug_level)
6372
        result.Raise("Could not add os for instance %s"
6373
                     " on node %s" % (instance, pnode_name))
6374

    
6375
      elif self.op.mode == constants.INSTANCE_IMPORT:
6376
        feedback_fn("* running the instance OS import scripts...")
6377
        src_node = self.op.src_node
6378
        src_images = self.src_images
6379
        cluster_name = self.cfg.GetClusterName()
6380
        # FIXME: pass debug option from opcode to backend
6381
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
6382
                                                         src_node, src_images,
6383
                                                         cluster_name,
6384
                                                         self.op.debug_level)
6385
        msg = import_result.fail_msg
6386
        if msg:
6387
          self.LogWarning("Error while importing the disk images for instance"
6388
                          " %s on node %s: %s" % (instance, pnode_name, msg))
6389
      else:
6390
        # also checked in the prereq part
6391
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
6392
                                     % self.op.mode)
6393

    
6394
    if self.op.start:
6395
      iobj.admin_up = True
6396
      self.cfg.Update(iobj, feedback_fn)
6397
      logging.info("Starting instance %s on node %s", instance, pnode_name)
6398
      feedback_fn("* starting instance...")
6399
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
6400
      result.Raise("Could not start instance")
6401

    
6402
    return list(iobj.all_nodes)
6403

    
6404

    
6405
class LUConnectConsole(NoHooksLU):
6406
  """Connect to an instance's console.
6407

6408
  This is somewhat special in that it returns the command line that
6409
  you need to run on the master node in order to connect to the
6410
  console.
6411

6412
  """
6413
  _OP_REQP = ["instance_name"]
6414
  REQ_BGL = False
6415

    
6416
  def ExpandNames(self):
6417
    self._ExpandAndLockInstance()
6418

    
6419
  def CheckPrereq(self):
6420
    """Check prerequisites.
6421

6422
    This checks that the instance is in the cluster.
6423

6424
    """
6425
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6426
    assert self.instance is not None, \
6427
      "Cannot retrieve locked instance %s" % self.op.instance_name
6428
    _CheckNodeOnline(self, self.instance.primary_node)
6429

    
6430
  def Exec(self, feedback_fn):
6431
    """Connect to the console of an instance
6432

6433
    """
6434
    instance = self.instance
6435
    node = instance.primary_node
6436

    
6437
    node_insts = self.rpc.call_instance_list([node],
6438
                                             [instance.hypervisor])[node]
6439
    node_insts.Raise("Can't get node information from %s" % node)
6440

    
6441
    if instance.name not in node_insts.payload:
6442
      raise errors.OpExecError("Instance %s is not running." % instance.name)
6443

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

    
6446
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6447
    cluster = self.cfg.GetClusterInfo()
6448
    # beparams and hvparams are passed separately, to avoid editing the
6449
    # instance and then saving the defaults in the instance itself.
6450
    hvparams = cluster.FillHV(instance)
6451
    beparams = cluster.FillBE(instance)
6452
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6453

    
6454
    # build ssh cmdline
6455
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6456

    
6457

    
6458
class LUReplaceDisks(LogicalUnit):
6459
  """Replace the disks of an instance.
6460

6461
  """
6462
  HPATH = "mirrors-replace"
6463
  HTYPE = constants.HTYPE_INSTANCE
6464
  _OP_REQP = ["instance_name", "mode", "disks"]
6465
  REQ_BGL = False
6466

    
6467
  def CheckArguments(self):
6468
    if not hasattr(self.op, "remote_node"):
6469
      self.op.remote_node = None
6470
    if not hasattr(self.op, "iallocator"):
6471
      self.op.iallocator = None
6472
    if not hasattr(self.op, "early_release"):
6473
      self.op.early_release = False
6474

    
6475
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
6476
                                  self.op.iallocator)
6477

    
6478
  def ExpandNames(self):
6479
    self._ExpandAndLockInstance()
6480

    
6481
    if self.op.iallocator is not None:
6482
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6483

    
6484
    elif self.op.remote_node is not None:
6485
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
6486
      self.op.remote_node = remote_node
6487

    
6488
      # Warning: do not remove the locking of the new secondary here
6489
      # unless DRBD8.AddChildren is changed to work in parallel;
6490
      # currently it doesn't since parallel invocations of
6491
      # FindUnusedMinor will conflict
6492
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6493
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6494

    
6495
    else:
6496
      self.needed_locks[locking.LEVEL_NODE] = []
6497
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6498

    
6499
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
6500
                                   self.op.iallocator, self.op.remote_node,
6501
                                   self.op.disks, False, self.op.early_release)
6502

    
6503
    self.tasklets = [self.replacer]
6504

    
6505
  def DeclareLocks(self, level):
6506
    # If we're not already locking all nodes in the set we have to declare the
6507
    # instance's primary/secondary nodes.
6508
    if (level == locking.LEVEL_NODE and
6509
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6510
      self._LockInstancesNodes()
6511

    
6512
  def BuildHooksEnv(self):
6513
    """Build hooks env.
6514

6515
    This runs on the master, the primary and all the secondaries.
6516

6517
    """
6518
    instance = self.replacer.instance
6519
    env = {
6520
      "MODE": self.op.mode,
6521
      "NEW_SECONDARY": self.op.remote_node,
6522
      "OLD_SECONDARY": instance.secondary_nodes[0],
6523
      }
6524
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6525
    nl = [
6526
      self.cfg.GetMasterNode(),
6527
      instance.primary_node,
6528
      ]
6529
    if self.op.remote_node is not None:
6530
      nl.append(self.op.remote_node)
6531
    return env, nl, nl
6532

    
6533

    
6534
class LUEvacuateNode(LogicalUnit):
6535
  """Relocate the secondary instances from a node.
6536

6537
  """
6538
  HPATH = "node-evacuate"
6539
  HTYPE = constants.HTYPE_NODE
6540
  _OP_REQP = ["node_name"]
6541
  REQ_BGL = False
6542

    
6543
  def CheckArguments(self):
6544
    if not hasattr(self.op, "remote_node"):
6545
      self.op.remote_node = None
6546
    if not hasattr(self.op, "iallocator"):
6547
      self.op.iallocator = None
6548
    if not hasattr(self.op, "early_release"):
6549
      self.op.early_release = False
6550

    
6551
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
6552
                                  self.op.remote_node,
6553
                                  self.op.iallocator)
6554

    
6555
  def ExpandNames(self):
6556
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6557

    
6558
    self.needed_locks = {}
6559

    
6560
    # Declare node locks
6561
    if self.op.iallocator is not None:
6562
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6563

    
6564
    elif self.op.remote_node is not None:
6565
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
6566

    
6567
      # Warning: do not remove the locking of the new secondary here
6568
      # unless DRBD8.AddChildren is changed to work in parallel;
6569
      # currently it doesn't since parallel invocations of
6570
      # FindUnusedMinor will conflict
6571
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
6572
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6573

    
6574
    else:
6575
      raise errors.OpPrereqError("Invalid parameters", errors.ECODE_INVAL)
6576

    
6577
    # Create tasklets for replacing disks for all secondary instances on this
6578
    # node
6579
    names = []
6580
    tasklets = []
6581

    
6582
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
6583
      logging.debug("Replacing disks for instance %s", inst.name)
6584
      names.append(inst.name)
6585

    
6586
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
6587
                                self.op.iallocator, self.op.remote_node, [],
6588
                                True, self.op.early_release)
6589
      tasklets.append(replacer)
6590

    
6591
    self.tasklets = tasklets
6592
    self.instance_names = names
6593

    
6594
    # Declare instance locks
6595
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
6596

    
6597
  def DeclareLocks(self, level):
6598
    # If we're not already locking all nodes in the set we have to declare the
6599
    # instance's primary/secondary nodes.
6600
    if (level == locking.LEVEL_NODE and
6601
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6602
      self._LockInstancesNodes()
6603

    
6604
  def BuildHooksEnv(self):
6605
    """Build hooks env.
6606

6607
    This runs on the master, the primary and all the secondaries.
6608

6609
    """
6610
    env = {
6611
      "NODE_NAME": self.op.node_name,
6612
      }
6613

    
6614
    nl = [self.cfg.GetMasterNode()]
6615

    
6616
    if self.op.remote_node is not None:
6617
      env["NEW_SECONDARY"] = self.op.remote_node
6618
      nl.append(self.op.remote_node)
6619

    
6620
    return (env, nl, nl)
6621

    
6622

    
6623
class TLReplaceDisks(Tasklet):
6624
  """Replaces disks for an instance.
6625

6626
  Note: Locking is not within the scope of this class.
6627

6628
  """
6629
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
6630
               disks, delay_iallocator, early_release):
6631
    """Initializes this class.
6632

6633
    """
6634
    Tasklet.__init__(self, lu)
6635

    
6636
    # Parameters
6637
    self.instance_name = instance_name
6638
    self.mode = mode
6639
    self.iallocator_name = iallocator_name
6640
    self.remote_node = remote_node
6641
    self.disks = disks
6642
    self.delay_iallocator = delay_iallocator
6643
    self.early_release = early_release
6644

    
6645
    # Runtime data
6646
    self.instance = None
6647
    self.new_node = None
6648
    self.target_node = None
6649
    self.other_node = None
6650
    self.remote_node_info = None
6651
    self.node_secondary_ip = None
6652

    
6653
  @staticmethod
6654
  def CheckArguments(mode, remote_node, iallocator):
6655
    """Helper function for users of this class.
6656

6657
    """
6658
    # check for valid parameter combination
6659
    if mode == constants.REPLACE_DISK_CHG:
6660
      if remote_node is None and iallocator is None:
6661
        raise errors.OpPrereqError("When changing the secondary either an"
6662
                                   " iallocator script must be used or the"
6663
                                   " new node given", errors.ECODE_INVAL)
6664

    
6665
      if remote_node is not None and iallocator is not None:
6666
        raise errors.OpPrereqError("Give either the iallocator or the new"
6667
                                   " secondary, not both", errors.ECODE_INVAL)
6668

    
6669
    elif remote_node is not None or iallocator is not None:
6670
      # Not replacing the secondary
6671
      raise errors.OpPrereqError("The iallocator and new node options can"
6672
                                 " only be used when changing the"
6673
                                 " secondary node", errors.ECODE_INVAL)
6674

    
6675
  @staticmethod
6676
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
6677
    """Compute a new secondary node using an IAllocator.
6678

6679
    """
6680
    ial = IAllocator(lu.cfg, lu.rpc,
6681
                     mode=constants.IALLOCATOR_MODE_RELOC,
6682
                     name=instance_name,
6683
                     relocate_from=relocate_from)
6684

    
6685
    ial.Run(iallocator_name)
6686

    
6687
    if not ial.success:
6688
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
6689
                                 " %s" % (iallocator_name, ial.info),
6690
                                 errors.ECODE_NORES)
6691

    
6692
    if len(ial.result) != ial.required_nodes:
6693
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6694
                                 " of nodes (%s), required %s" %
6695
                                 (iallocator_name,
6696
                                  len(ial.result), ial.required_nodes),
6697
                                 errors.ECODE_FAULT)
6698

    
6699
    remote_node_name = ial.result[0]
6700

    
6701
    lu.LogInfo("Selected new secondary for instance '%s': %s",
6702
               instance_name, remote_node_name)
6703

    
6704
    return remote_node_name
6705

    
6706
  def _FindFaultyDisks(self, node_name):
6707
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
6708
                                    node_name, True)
6709

    
6710
  def CheckPrereq(self):
6711
    """Check prerequisites.
6712

6713
    This checks that the instance is in the cluster.
6714

6715
    """
6716
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
6717
    assert instance is not None, \
6718
      "Cannot retrieve locked instance %s" % self.instance_name
6719

    
6720
    if instance.disk_template != constants.DT_DRBD8:
6721
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
6722
                                 " instances", errors.ECODE_INVAL)
6723

    
6724
    if len(instance.secondary_nodes) != 1:
6725
      raise errors.OpPrereqError("The instance has a strange layout,"
6726
                                 " expected one secondary but found %d" %
6727
                                 len(instance.secondary_nodes),
6728
                                 errors.ECODE_FAULT)
6729

    
6730
    if not self.delay_iallocator:
6731
      self._CheckPrereq2()
6732

    
6733
  def _CheckPrereq2(self):
6734
    """Check prerequisites, second part.
6735

6736
    This function should always be part of CheckPrereq. It was separated and is
6737
    now called from Exec because during node evacuation iallocator was only
6738
    called with an unmodified cluster model, not taking planned changes into
6739
    account.
6740

6741
    """
6742
    instance = self.instance
6743
    secondary_node = instance.secondary_nodes[0]
6744

    
6745
    if self.iallocator_name is None:
6746
      remote_node = self.remote_node
6747
    else:
6748
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
6749
                                       instance.name, instance.secondary_nodes)
6750

    
6751
    if remote_node is not None:
6752
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
6753
      assert self.remote_node_info is not None, \
6754
        "Cannot retrieve locked node %s" % remote_node
6755
    else:
6756
      self.remote_node_info = None
6757

    
6758
    if remote_node == self.instance.primary_node:
6759
      raise errors.OpPrereqError("The specified node is the primary node of"
6760
                                 " the instance.", errors.ECODE_INVAL)
6761

    
6762
    if remote_node == secondary_node:
6763
      raise errors.OpPrereqError("The specified node is already the"
6764
                                 " secondary node of the instance.",
6765
                                 errors.ECODE_INVAL)
6766

    
6767
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
6768
                                    constants.REPLACE_DISK_CHG):
6769
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
6770
                                 errors.ECODE_INVAL)
6771

    
6772
    if self.mode == constants.REPLACE_DISK_AUTO:
6773
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
6774
      faulty_secondary = self._FindFaultyDisks(secondary_node)
6775

    
6776
      if faulty_primary and faulty_secondary:
6777
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
6778
                                   " one node and can not be repaired"
6779
                                   " automatically" % self.instance_name,
6780
                                   errors.ECODE_STATE)
6781

    
6782
      if faulty_primary:
6783
        self.disks = faulty_primary
6784
        self.target_node = instance.primary_node
6785
        self.other_node = secondary_node
6786
        check_nodes = [self.target_node, self.other_node]
6787
      elif faulty_secondary:
6788
        self.disks = faulty_secondary
6789
        self.target_node = secondary_node
6790
        self.other_node = instance.primary_node
6791
        check_nodes = [self.target_node, self.other_node]
6792
      else:
6793
        self.disks = []
6794
        check_nodes = []
6795

    
6796
    else:
6797
      # Non-automatic modes
6798
      if self.mode == constants.REPLACE_DISK_PRI:
6799
        self.target_node = instance.primary_node
6800
        self.other_node = secondary_node
6801
        check_nodes = [self.target_node, self.other_node]
6802

    
6803
      elif self.mode == constants.REPLACE_DISK_SEC:
6804
        self.target_node = secondary_node
6805
        self.other_node = instance.primary_node
6806
        check_nodes = [self.target_node, self.other_node]
6807

    
6808
      elif self.mode == constants.REPLACE_DISK_CHG:
6809
        self.new_node = remote_node
6810
        self.other_node = instance.primary_node
6811
        self.target_node = secondary_node
6812
        check_nodes = [self.new_node, self.other_node]
6813

    
6814
        _CheckNodeNotDrained(self.lu, remote_node)
6815

    
6816
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
6817
        assert old_node_info is not None
6818
        if old_node_info.offline and not self.early_release:
6819
          # doesn't make sense to delay the release
6820
          self.early_release = True
6821
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
6822
                          " early-release mode", secondary_node)
6823

    
6824
      else:
6825
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
6826
                                     self.mode)
6827

    
6828
      # If not specified all disks should be replaced
6829
      if not self.disks:
6830
        self.disks = range(len(self.instance.disks))
6831

    
6832
    for node in check_nodes:
6833
      _CheckNodeOnline(self.lu, node)
6834

    
6835
    # Check whether disks are valid
6836
    for disk_idx in self.disks:
6837
      instance.FindDisk(disk_idx)
6838

    
6839
    # Get secondary node IP addresses
6840
    node_2nd_ip = {}
6841

    
6842
    for node_name in [self.target_node, self.other_node, self.new_node]:
6843
      if node_name is not None:
6844
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
6845

    
6846
    self.node_secondary_ip = node_2nd_ip
6847

    
6848
  def Exec(self, feedback_fn):
6849
    """Execute disk replacement.
6850

6851
    This dispatches the disk replacement to the appropriate handler.
6852

6853
    """
6854
    if self.delay_iallocator:
6855
      self._CheckPrereq2()
6856

    
6857
    if not self.disks:
6858
      feedback_fn("No disks need replacement")
6859
      return
6860

    
6861
    feedback_fn("Replacing disk(s) %s for %s" %
6862
                (utils.CommaJoin(self.disks), self.instance.name))
6863

    
6864
    activate_disks = (not self.instance.admin_up)
6865

    
6866
    # Activate the instance disks if we're replacing them on a down instance
6867
    if activate_disks:
6868
      _StartInstanceDisks(self.lu, self.instance, True)
6869

    
6870
    try:
6871
      # Should we replace the secondary node?
6872
      if self.new_node is not None:
6873
        fn = self._ExecDrbd8Secondary
6874
      else:
6875
        fn = self._ExecDrbd8DiskOnly
6876

    
6877
      return fn(feedback_fn)
6878

    
6879
    finally:
6880
      # Deactivate the instance disks if we're replacing them on a
6881
      # down instance
6882
      if activate_disks:
6883
        _SafeShutdownInstanceDisks(self.lu, self.instance)
6884

    
6885
  def _CheckVolumeGroup(self, nodes):
6886
    self.lu.LogInfo("Checking volume groups")
6887

    
6888
    vgname = self.cfg.GetVGName()
6889

    
6890
    # Make sure volume group exists on all involved nodes
6891
    results = self.rpc.call_vg_list(nodes)
6892
    if not results:
6893
      raise errors.OpExecError("Can't list volume groups on the nodes")
6894

    
6895
    for node in nodes:
6896
      res = results[node]
6897
      res.Raise("Error checking node %s" % node)
6898
      if vgname not in res.payload:
6899
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
6900
                                 (vgname, node))
6901

    
6902
  def _CheckDisksExistence(self, nodes):
6903
    # Check disk existence
6904
    for idx, dev in enumerate(self.instance.disks):
6905
      if idx not in self.disks:
6906
        continue
6907

    
6908
      for node in nodes:
6909
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
6910
        self.cfg.SetDiskID(dev, node)
6911

    
6912
        result = self.rpc.call_blockdev_find(node, dev)
6913

    
6914
        msg = result.fail_msg
6915
        if msg or not result.payload:
6916
          if not msg:
6917
            msg = "disk not found"
6918
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
6919
                                   (idx, node, msg))
6920

    
6921
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
6922
    for idx, dev in enumerate(self.instance.disks):
6923
      if idx not in self.disks:
6924
        continue
6925

    
6926
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
6927
                      (idx, node_name))
6928

    
6929
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
6930
                                   ldisk=ldisk):
6931
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
6932
                                 " replace disks for instance %s" %
6933
                                 (node_name, self.instance.name))
6934

    
6935
  def _CreateNewStorage(self, node_name):
6936
    vgname = self.cfg.GetVGName()
6937
    iv_names = {}
6938

    
6939
    for idx, dev in enumerate(self.instance.disks):
6940
      if idx not in self.disks:
6941
        continue
6942

    
6943
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
6944

    
6945
      self.cfg.SetDiskID(dev, node_name)
6946

    
6947
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
6948
      names = _GenerateUniqueNames(self.lu, lv_names)
6949

    
6950
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
6951
                             logical_id=(vgname, names[0]))
6952
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6953
                             logical_id=(vgname, names[1]))
6954

    
6955
      new_lvs = [lv_data, lv_meta]
6956
      old_lvs = dev.children
6957
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
6958

    
6959
      # we pass force_create=True to force the LVM creation
6960
      for new_lv in new_lvs:
6961
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
6962
                        _GetInstanceInfoText(self.instance), False)
6963

    
6964
    return iv_names
6965

    
6966
  def _CheckDevices(self, node_name, iv_names):
6967
    for name, (dev, _, _) in iv_names.iteritems():
6968
      self.cfg.SetDiskID(dev, node_name)
6969

    
6970
      result = self.rpc.call_blockdev_find(node_name, dev)
6971

    
6972
      msg = result.fail_msg
6973
      if msg or not result.payload:
6974
        if not msg:
6975
          msg = "disk not found"
6976
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
6977
                                 (name, msg))
6978

    
6979
      if result.payload.is_degraded:
6980
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
6981

    
6982
  def _RemoveOldStorage(self, node_name, iv_names):
6983
    for name, (_, old_lvs, _) in iv_names.iteritems():
6984
      self.lu.LogInfo("Remove logical volumes for %s" % name)
6985

    
6986
      for lv in old_lvs:
6987
        self.cfg.SetDiskID(lv, node_name)
6988

    
6989
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
6990
        if msg:
6991
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
6992
                             hint="remove unused LVs manually")
6993

    
6994
  def _ReleaseNodeLock(self, node_name):
6995
    """Releases the lock for a given node."""
6996
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
6997

    
6998
  def _ExecDrbd8DiskOnly(self, feedback_fn):
6999
    """Replace a disk on the primary or secondary for DRBD 8.
7000

7001
    The algorithm for replace is quite complicated:
7002

7003
      1. for each disk to be replaced:
7004

7005
        1. create new LVs on the target node with unique names
7006
        1. detach old LVs from the drbd device
7007
        1. rename old LVs to name_replaced.<time_t>
7008
        1. rename new LVs to old LVs
7009
        1. attach the new LVs (with the old names now) to the drbd device
7010

7011
      1. wait for sync across all devices
7012

7013
      1. for each modified disk:
7014

7015
        1. remove old LVs (which have the name name_replaces.<time_t>)
7016

7017
    Failures are not very well handled.
7018

7019
    """
7020
    steps_total = 6
7021

    
7022
    # Step: check device activation
7023
    self.lu.LogStep(1, steps_total, "Check device existence")
7024
    self._CheckDisksExistence([self.other_node, self.target_node])
7025
    self._CheckVolumeGroup([self.target_node, self.other_node])
7026

    
7027
    # Step: check other node consistency
7028
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7029
    self._CheckDisksConsistency(self.other_node,
7030
                                self.other_node == self.instance.primary_node,
7031
                                False)
7032

    
7033
    # Step: create new storage
7034
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7035
    iv_names = self._CreateNewStorage(self.target_node)
7036

    
7037
    # Step: for each lv, detach+rename*2+attach
7038
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7039
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7040
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7041

    
7042
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7043
                                                     old_lvs)
7044
      result.Raise("Can't detach drbd from local storage on node"
7045
                   " %s for device %s" % (self.target_node, dev.iv_name))
7046
      #dev.children = []
7047
      #cfg.Update(instance)
7048

    
7049
      # ok, we created the new LVs, so now we know we have the needed
7050
      # storage; as such, we proceed on the target node to rename
7051
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7052
      # using the assumption that logical_id == physical_id (which in
7053
      # turn is the unique_id on that node)
7054

    
7055
      # FIXME(iustin): use a better name for the replaced LVs
7056
      temp_suffix = int(time.time())
7057
      ren_fn = lambda d, suff: (d.physical_id[0],
7058
                                d.physical_id[1] + "_replaced-%s" % suff)
7059

    
7060
      # Build the rename list based on what LVs exist on the node
7061
      rename_old_to_new = []
7062
      for to_ren in old_lvs:
7063
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7064
        if not result.fail_msg and result.payload:
7065
          # device exists
7066
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7067

    
7068
      self.lu.LogInfo("Renaming the old LVs on the target node")
7069
      result = self.rpc.call_blockdev_rename(self.target_node,
7070
                                             rename_old_to_new)
7071
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7072

    
7073
      # Now we rename the new LVs to the old LVs
7074
      self.lu.LogInfo("Renaming the new LVs on the target node")
7075
      rename_new_to_old = [(new, old.physical_id)
7076
                           for old, new in zip(old_lvs, new_lvs)]
7077
      result = self.rpc.call_blockdev_rename(self.target_node,
7078
                                             rename_new_to_old)
7079
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7080

    
7081
      for old, new in zip(old_lvs, new_lvs):
7082
        new.logical_id = old.logical_id
7083
        self.cfg.SetDiskID(new, self.target_node)
7084

    
7085
      for disk in old_lvs:
7086
        disk.logical_id = ren_fn(disk, temp_suffix)
7087
        self.cfg.SetDiskID(disk, self.target_node)
7088

    
7089
      # Now that the new lvs have the old name, we can add them to the device
7090
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7091
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7092
                                                  new_lvs)
7093
      msg = result.fail_msg
7094
      if msg:
7095
        for new_lv in new_lvs:
7096
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7097
                                               new_lv).fail_msg
7098
          if msg2:
7099
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7100
                               hint=("cleanup manually the unused logical"
7101
                                     "volumes"))
7102
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7103

    
7104
      dev.children = new_lvs
7105

    
7106
      self.cfg.Update(self.instance, feedback_fn)
7107

    
7108
    cstep = 5
7109
    if self.early_release:
7110
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7111
      cstep += 1
7112
      self._RemoveOldStorage(self.target_node, iv_names)
7113
      # WARNING: we release both node locks here, do not do other RPCs
7114
      # than WaitForSync to the primary node
7115
      self._ReleaseNodeLock([self.target_node, self.other_node])
7116

    
7117
    # Wait for sync
7118
    # This can fail as the old devices are degraded and _WaitForSync
7119
    # does a combined result over all disks, so we don't check its return value
7120
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7121
    cstep += 1
7122
    _WaitForSync(self.lu, self.instance)
7123

    
7124
    # Check all devices manually
7125
    self._CheckDevices(self.instance.primary_node, iv_names)
7126

    
7127
    # Step: remove old storage
7128
    if not self.early_release:
7129
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7130
      cstep += 1
7131
      self._RemoveOldStorage(self.target_node, iv_names)
7132

    
7133
  def _ExecDrbd8Secondary(self, feedback_fn):
7134
    """Replace the secondary node for DRBD 8.
7135

7136
    The algorithm for replace is quite complicated:
7137
      - for all disks of the instance:
7138
        - create new LVs on the new node with same names
7139
        - shutdown the drbd device on the old secondary
7140
        - disconnect the drbd network on the primary
7141
        - create the drbd device on the new secondary
7142
        - network attach the drbd on the primary, using an artifice:
7143
          the drbd code for Attach() will connect to the network if it
7144
          finds a device which is connected to the good local disks but
7145
          not network enabled
7146
      - wait for sync across all devices
7147
      - remove all disks from the old secondary
7148

7149
    Failures are not very well handled.
7150

7151
    """
7152
    steps_total = 6
7153

    
7154
    # Step: check device activation
7155
    self.lu.LogStep(1, steps_total, "Check device existence")
7156
    self._CheckDisksExistence([self.instance.primary_node])
7157
    self._CheckVolumeGroup([self.instance.primary_node])
7158

    
7159
    # Step: check other node consistency
7160
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7161
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
7162

    
7163
    # Step: create new storage
7164
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7165
    for idx, dev in enumerate(self.instance.disks):
7166
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
7167
                      (self.new_node, idx))
7168
      # we pass force_create=True to force LVM creation
7169
      for new_lv in dev.children:
7170
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
7171
                        _GetInstanceInfoText(self.instance), False)
7172

    
7173
    # Step 4: dbrd minors and drbd setups changes
7174
    # after this, we must manually remove the drbd minors on both the
7175
    # error and the success paths
7176
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7177
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7178
                                         for dev in self.instance.disks],
7179
                                        self.instance.name)
7180
    logging.debug("Allocated minors %r", minors)
7181

    
7182
    iv_names = {}
7183
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7184
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7185
                      (self.new_node, idx))
7186
      # create new devices on new_node; note that we create two IDs:
7187
      # one without port, so the drbd will be activated without
7188
      # networking information on the new node at this stage, and one
7189
      # with network, for the latter activation in step 4
7190
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7191
      if self.instance.primary_node == o_node1:
7192
        p_minor = o_minor1
7193
      else:
7194
        assert self.instance.primary_node == o_node2, "Three-node instance?"
7195
        p_minor = o_minor2
7196

    
7197
      new_alone_id = (self.instance.primary_node, self.new_node, None,
7198
                      p_minor, new_minor, o_secret)
7199
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
7200
                    p_minor, new_minor, o_secret)
7201

    
7202
      iv_names[idx] = (dev, dev.children, new_net_id)
7203
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
7204
                    new_net_id)
7205
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
7206
                              logical_id=new_alone_id,
7207
                              children=dev.children,
7208
                              size=dev.size)
7209
      try:
7210
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
7211
                              _GetInstanceInfoText(self.instance), False)
7212
      except errors.GenericError:
7213
        self.cfg.ReleaseDRBDMinors(self.instance.name)
7214
        raise
7215

    
7216
    # We have new devices, shutdown the drbd on the old secondary
7217
    for idx, dev in enumerate(self.instance.disks):
7218
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
7219
      self.cfg.SetDiskID(dev, self.target_node)
7220
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
7221
      if msg:
7222
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
7223
                           "node: %s" % (idx, msg),
7224
                           hint=("Please cleanup this device manually as"
7225
                                 " soon as possible"))
7226

    
7227
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
7228
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
7229
                                               self.node_secondary_ip,
7230
                                               self.instance.disks)\
7231
                                              [self.instance.primary_node]
7232

    
7233
    msg = result.fail_msg
7234
    if msg:
7235
      # detaches didn't succeed (unlikely)
7236
      self.cfg.ReleaseDRBDMinors(self.instance.name)
7237
      raise errors.OpExecError("Can't detach the disks from the network on"
7238
                               " old node: %s" % (msg,))
7239

    
7240
    # if we managed to detach at least one, we update all the disks of
7241
    # the instance to point to the new secondary
7242
    self.lu.LogInfo("Updating instance configuration")
7243
    for dev, _, new_logical_id in iv_names.itervalues():
7244
      dev.logical_id = new_logical_id
7245
      self.cfg.SetDiskID(dev, self.instance.primary_node)
7246

    
7247
    self.cfg.Update(self.instance, feedback_fn)
7248

    
7249
    # and now perform the drbd attach
7250
    self.lu.LogInfo("Attaching primary drbds to new secondary"
7251
                    " (standalone => connected)")
7252
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
7253
                                            self.new_node],
7254
                                           self.node_secondary_ip,
7255
                                           self.instance.disks,
7256
                                           self.instance.name,
7257
                                           False)
7258
    for to_node, to_result in result.items():
7259
      msg = to_result.fail_msg
7260
      if msg:
7261
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
7262
                           to_node, msg,
7263
                           hint=("please do a gnt-instance info to see the"
7264
                                 " status of disks"))
7265
    cstep = 5
7266
    if self.early_release:
7267
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7268
      cstep += 1
7269
      self._RemoveOldStorage(self.target_node, iv_names)
7270
      # WARNING: we release all node locks here, do not do other RPCs
7271
      # than WaitForSync to the primary node
7272
      self._ReleaseNodeLock([self.instance.primary_node,
7273
                             self.target_node,
7274
                             self.new_node])
7275

    
7276
    # Wait for sync
7277
    # This can fail as the old devices are degraded and _WaitForSync
7278
    # does a combined result over all disks, so we don't check its return value
7279
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7280
    cstep += 1
7281
    _WaitForSync(self.lu, self.instance)
7282

    
7283
    # Check all devices manually
7284
    self._CheckDevices(self.instance.primary_node, iv_names)
7285

    
7286
    # Step: remove old storage
7287
    if not self.early_release:
7288
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7289
      self._RemoveOldStorage(self.target_node, iv_names)
7290

    
7291

    
7292
class LURepairNodeStorage(NoHooksLU):
7293
  """Repairs the volume group on a node.
7294

7295
  """
7296
  _OP_REQP = ["node_name"]
7297
  REQ_BGL = False
7298

    
7299
  def CheckArguments(self):
7300
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
7301

    
7302
  def ExpandNames(self):
7303
    self.needed_locks = {
7304
      locking.LEVEL_NODE: [self.op.node_name],
7305
      }
7306

    
7307
  def _CheckFaultyDisks(self, instance, node_name):
7308
    """Ensure faulty disks abort the opcode or at least warn."""
7309
    try:
7310
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
7311
                                  node_name, True):
7312
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
7313
                                   " node '%s'" % (instance.name, node_name),
7314
                                   errors.ECODE_STATE)
7315
    except errors.OpPrereqError, err:
7316
      if self.op.ignore_consistency:
7317
        self.proc.LogWarning(str(err.args[0]))
7318
      else:
7319
        raise
7320

    
7321
  def CheckPrereq(self):
7322
    """Check prerequisites.
7323

7324
    """
7325
    storage_type = self.op.storage_type
7326

    
7327
    if (constants.SO_FIX_CONSISTENCY not in
7328
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
7329
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
7330
                                 " repaired" % storage_type,
7331
                                 errors.ECODE_INVAL)
7332

    
7333
    # Check whether any instance on this node has faulty disks
7334
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
7335
      if not inst.admin_up:
7336
        continue
7337
      check_nodes = set(inst.all_nodes)
7338
      check_nodes.discard(self.op.node_name)
7339
      for inst_node_name in check_nodes:
7340
        self._CheckFaultyDisks(inst, inst_node_name)
7341

    
7342
  def Exec(self, feedback_fn):
7343
    feedback_fn("Repairing storage unit '%s' on %s ..." %
7344
                (self.op.name, self.op.node_name))
7345

    
7346
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
7347
    result = self.rpc.call_storage_execute(self.op.node_name,
7348
                                           self.op.storage_type, st_args,
7349
                                           self.op.name,
7350
                                           constants.SO_FIX_CONSISTENCY)
7351
    result.Raise("Failed to repair storage unit '%s' on %s" %
7352
                 (self.op.name, self.op.node_name))
7353

    
7354

    
7355
class LUNodeEvacuationStrategy(NoHooksLU):
7356
  """Computes the node evacuation strategy.
7357

7358
  """
7359
  _OP_REQP = ["nodes"]
7360
  REQ_BGL = False
7361

    
7362
  def CheckArguments(self):
7363
    if not hasattr(self.op, "remote_node"):
7364
      self.op.remote_node = None
7365
    if not hasattr(self.op, "iallocator"):
7366
      self.op.iallocator = None
7367
    if self.op.remote_node is not None and self.op.iallocator is not None:
7368
      raise errors.OpPrereqError("Give either the iallocator or the new"
7369
                                 " secondary, not both", errors.ECODE_INVAL)
7370

    
7371
  def ExpandNames(self):
7372
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
7373
    self.needed_locks = locks = {}
7374
    if self.op.remote_node is None:
7375
      locks[locking.LEVEL_NODE] = locking.ALL_SET
7376
    else:
7377
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7378
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
7379

    
7380
  def CheckPrereq(self):
7381
    pass
7382

    
7383
  def Exec(self, feedback_fn):
7384
    if self.op.remote_node is not None:
7385
      instances = []
7386
      for node in self.op.nodes:
7387
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
7388
      result = []
7389
      for i in instances:
7390
        if i.primary_node == self.op.remote_node:
7391
          raise errors.OpPrereqError("Node %s is the primary node of"
7392
                                     " instance %s, cannot use it as"
7393
                                     " secondary" %
7394
                                     (self.op.remote_node, i.name),
7395
                                     errors.ECODE_INVAL)
7396
        result.append([i.name, self.op.remote_node])
7397
    else:
7398
      ial = IAllocator(self.cfg, self.rpc,
7399
                       mode=constants.IALLOCATOR_MODE_MEVAC,
7400
                       evac_nodes=self.op.nodes)
7401
      ial.Run(self.op.iallocator, validate=True)
7402
      if not ial.success:
7403
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
7404
                                 errors.ECODE_NORES)
7405
      result = ial.result
7406
    return result
7407

    
7408

    
7409
class LUGrowDisk(LogicalUnit):
7410
  """Grow a disk of an instance.
7411

7412
  """
7413
  HPATH = "disk-grow"
7414
  HTYPE = constants.HTYPE_INSTANCE
7415
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
7416
  REQ_BGL = False
7417

    
7418
  def ExpandNames(self):
7419
    self._ExpandAndLockInstance()
7420
    self.needed_locks[locking.LEVEL_NODE] = []
7421
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7422

    
7423
  def DeclareLocks(self, level):
7424
    if level == locking.LEVEL_NODE:
7425
      self._LockInstancesNodes()
7426

    
7427
  def BuildHooksEnv(self):
7428
    """Build hooks env.
7429

7430
    This runs on the master, the primary and all the secondaries.
7431

7432
    """
7433
    env = {
7434
      "DISK": self.op.disk,
7435
      "AMOUNT": self.op.amount,
7436
      }
7437
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7438
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7439
    return env, nl, nl
7440

    
7441
  def CheckPrereq(self):
7442
    """Check prerequisites.
7443

7444
    This checks that the instance is in the cluster.
7445

7446
    """
7447
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7448
    assert instance is not None, \
7449
      "Cannot retrieve locked instance %s" % self.op.instance_name
7450
    nodenames = list(instance.all_nodes)
7451
    for node in nodenames:
7452
      _CheckNodeOnline(self, node)
7453

    
7454

    
7455
    self.instance = instance
7456

    
7457
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
7458
      raise errors.OpPrereqError("Instance's disk layout does not support"
7459
                                 " growing.", errors.ECODE_INVAL)
7460

    
7461
    self.disk = instance.FindDisk(self.op.disk)
7462

    
7463
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
7464
                                       instance.hypervisor)
7465
    for node in nodenames:
7466
      info = nodeinfo[node]
7467
      info.Raise("Cannot get current information from node %s" % node)
7468
      vg_free = info.payload.get('vg_free', None)
7469
      if not isinstance(vg_free, int):
7470
        raise errors.OpPrereqError("Can't compute free disk space on"
7471
                                   " node %s" % node, errors.ECODE_ENVIRON)
7472
      if self.op.amount > vg_free:
7473
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
7474
                                   " %d MiB available, %d MiB required" %
7475
                                   (node, vg_free, self.op.amount),
7476
                                   errors.ECODE_NORES)
7477

    
7478
  def Exec(self, feedback_fn):
7479
    """Execute disk grow.
7480

7481
    """
7482
    instance = self.instance
7483
    disk = self.disk
7484
    for node in instance.all_nodes:
7485
      self.cfg.SetDiskID(disk, node)
7486
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
7487
      result.Raise("Grow request failed to node %s" % node)
7488

    
7489
      # TODO: Rewrite code to work properly
7490
      # DRBD goes into sync mode for a short amount of time after executing the
7491
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
7492
      # calling "resize" in sync mode fails. Sleeping for a short amount of
7493
      # time is a work-around.
7494
      time.sleep(5)
7495

    
7496
    disk.RecordGrow(self.op.amount)
7497
    self.cfg.Update(instance, feedback_fn)
7498
    if self.op.wait_for_sync:
7499
      disk_abort = not _WaitForSync(self, instance)
7500
      if disk_abort:
7501
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
7502
                             " status.\nPlease check the instance.")
7503

    
7504

    
7505
class LUQueryInstanceData(NoHooksLU):
7506
  """Query runtime instance data.
7507

7508
  """
7509
  _OP_REQP = ["instances", "static"]
7510
  REQ_BGL = False
7511

    
7512
  def ExpandNames(self):
7513
    self.needed_locks = {}
7514
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
7515

    
7516
    if not isinstance(self.op.instances, list):
7517
      raise errors.OpPrereqError("Invalid argument type 'instances'",
7518
                                 errors.ECODE_INVAL)
7519

    
7520
    if self.op.instances:
7521
      self.wanted_names = []
7522
      for name in self.op.instances:
7523
        full_name = _ExpandInstanceName(self.cfg, name)
7524
        self.wanted_names.append(full_name)
7525
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
7526
    else:
7527
      self.wanted_names = None
7528
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
7529

    
7530
    self.needed_locks[locking.LEVEL_NODE] = []
7531
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7532

    
7533
  def DeclareLocks(self, level):
7534
    if level == locking.LEVEL_NODE:
7535
      self._LockInstancesNodes()
7536

    
7537
  def CheckPrereq(self):
7538
    """Check prerequisites.
7539

7540
    This only checks the optional instance list against the existing names.
7541

7542
    """
7543
    if self.wanted_names is None:
7544
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
7545

    
7546
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
7547
                             in self.wanted_names]
7548
    return
7549

    
7550
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
7551
    """Returns the status of a block device
7552

7553
    """
7554
    if self.op.static or not node:
7555
      return None
7556

    
7557
    self.cfg.SetDiskID(dev, node)
7558

    
7559
    result = self.rpc.call_blockdev_find(node, dev)
7560
    if result.offline:
7561
      return None
7562

    
7563
    result.Raise("Can't compute disk status for %s" % instance_name)
7564

    
7565
    status = result.payload
7566
    if status is None:
7567
      return None
7568

    
7569
    return (status.dev_path, status.major, status.minor,
7570
            status.sync_percent, status.estimated_time,
7571
            status.is_degraded, status.ldisk_status)
7572

    
7573
  def _ComputeDiskStatus(self, instance, snode, dev):
7574
    """Compute block device status.
7575

7576
    """
7577
    if dev.dev_type in constants.LDS_DRBD:
7578
      # we change the snode then (otherwise we use the one passed in)
7579
      if dev.logical_id[0] == instance.primary_node:
7580
        snode = dev.logical_id[1]
7581
      else:
7582
        snode = dev.logical_id[0]
7583

    
7584
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
7585
                                              instance.name, dev)
7586
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
7587

    
7588
    if dev.children:
7589
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
7590
                      for child in dev.children]
7591
    else:
7592
      dev_children = []
7593

    
7594
    data = {
7595
      "iv_name": dev.iv_name,
7596
      "dev_type": dev.dev_type,
7597
      "logical_id": dev.logical_id,
7598
      "physical_id": dev.physical_id,
7599
      "pstatus": dev_pstatus,
7600
      "sstatus": dev_sstatus,
7601
      "children": dev_children,
7602
      "mode": dev.mode,
7603
      "size": dev.size,
7604
      }
7605

    
7606
    return data
7607

    
7608
  def Exec(self, feedback_fn):
7609
    """Gather and return data"""
7610
    result = {}
7611

    
7612
    cluster = self.cfg.GetClusterInfo()
7613

    
7614
    for instance in self.wanted_instances:
7615
      if not self.op.static:
7616
        remote_info = self.rpc.call_instance_info(instance.primary_node,
7617
                                                  instance.name,
7618
                                                  instance.hypervisor)
7619
        remote_info.Raise("Error checking node %s" % instance.primary_node)
7620
        remote_info = remote_info.payload
7621
        if remote_info and "state" in remote_info:
7622
          remote_state = "up"
7623
        else:
7624
          remote_state = "down"
7625
      else:
7626
        remote_state = None
7627
      if instance.admin_up:
7628
        config_state = "up"
7629
      else:
7630
        config_state = "down"
7631

    
7632
      disks = [self._ComputeDiskStatus(instance, None, device)
7633
               for device in instance.disks]
7634

    
7635
      idict = {
7636
        "name": instance.name,
7637
        "config_state": config_state,
7638
        "run_state": remote_state,
7639
        "pnode": instance.primary_node,
7640
        "snodes": instance.secondary_nodes,
7641
        "os": instance.os,
7642
        # this happens to be the same format used for hooks
7643
        "nics": _NICListToTuple(self, instance.nics),
7644
        "disks": disks,
7645
        "hypervisor": instance.hypervisor,
7646
        "network_port": instance.network_port,
7647
        "hv_instance": instance.hvparams,
7648
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
7649
        "be_instance": instance.beparams,
7650
        "be_actual": cluster.FillBE(instance),
7651
        "serial_no": instance.serial_no,
7652
        "mtime": instance.mtime,
7653
        "ctime": instance.ctime,
7654
        "uuid": instance.uuid,
7655
        }
7656

    
7657
      result[instance.name] = idict
7658

    
7659
    return result
7660

    
7661

    
7662
class LUSetInstanceParams(LogicalUnit):
7663
  """Modifies an instances's parameters.
7664

7665
  """
7666
  HPATH = "instance-modify"
7667
  HTYPE = constants.HTYPE_INSTANCE
7668
  _OP_REQP = ["instance_name"]
7669
  REQ_BGL = False
7670

    
7671
  def CheckArguments(self):
7672
    if not hasattr(self.op, 'nics'):
7673
      self.op.nics = []
7674
    if not hasattr(self.op, 'disks'):
7675
      self.op.disks = []
7676
    if not hasattr(self.op, 'beparams'):
7677
      self.op.beparams = {}
7678
    if not hasattr(self.op, 'hvparams'):
7679
      self.op.hvparams = {}
7680
    self.op.force = getattr(self.op, "force", False)
7681
    if not (self.op.nics or self.op.disks or
7682
            self.op.hvparams or self.op.beparams):
7683
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
7684

    
7685
    if self.op.hvparams:
7686
      _CheckGlobalHvParams(self.op.hvparams)
7687

    
7688
    # Disk validation
7689
    disk_addremove = 0
7690
    for disk_op, disk_dict in self.op.disks:
7691
      if disk_op == constants.DDM_REMOVE:
7692
        disk_addremove += 1
7693
        continue
7694
      elif disk_op == constants.DDM_ADD:
7695
        disk_addremove += 1
7696
      else:
7697
        if not isinstance(disk_op, int):
7698
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
7699
        if not isinstance(disk_dict, dict):
7700
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
7701
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7702

    
7703
      if disk_op == constants.DDM_ADD:
7704
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
7705
        if mode not in constants.DISK_ACCESS_SET:
7706
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
7707
                                     errors.ECODE_INVAL)
7708
        size = disk_dict.get('size', None)
7709
        if size is None:
7710
          raise errors.OpPrereqError("Required disk parameter size missing",
7711
                                     errors.ECODE_INVAL)
7712
        try:
7713
          size = int(size)
7714
        except (TypeError, ValueError), err:
7715
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
7716
                                     str(err), errors.ECODE_INVAL)
7717
        disk_dict['size'] = size
7718
      else:
7719
        # modification of disk
7720
        if 'size' in disk_dict:
7721
          raise errors.OpPrereqError("Disk size change not possible, use"
7722
                                     " grow-disk", errors.ECODE_INVAL)
7723

    
7724
    if disk_addremove > 1:
7725
      raise errors.OpPrereqError("Only one disk add or remove operation"
7726
                                 " supported at a time", errors.ECODE_INVAL)
7727

    
7728
    # NIC validation
7729
    nic_addremove = 0
7730
    for nic_op, nic_dict in self.op.nics:
7731
      if nic_op == constants.DDM_REMOVE:
7732
        nic_addremove += 1
7733
        continue
7734
      elif nic_op == constants.DDM_ADD:
7735
        nic_addremove += 1
7736
      else:
7737
        if not isinstance(nic_op, int):
7738
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
7739
        if not isinstance(nic_dict, dict):
7740
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
7741
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7742

    
7743
      # nic_dict should be a dict
7744
      nic_ip = nic_dict.get('ip', None)
7745
      if nic_ip is not None:
7746
        if nic_ip.lower() == constants.VALUE_NONE:
7747
          nic_dict['ip'] = None
7748
        else:
7749
          if not utils.IsValidIP(nic_ip):
7750
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
7751
                                       errors.ECODE_INVAL)
7752

    
7753
      nic_bridge = nic_dict.get('bridge', None)
7754
      nic_link = nic_dict.get('link', None)
7755
      if nic_bridge and nic_link:
7756
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7757
                                   " at the same time", errors.ECODE_INVAL)
7758
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
7759
        nic_dict['bridge'] = None
7760
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
7761
        nic_dict['link'] = None
7762

    
7763
      if nic_op == constants.DDM_ADD:
7764
        nic_mac = nic_dict.get('mac', None)
7765
        if nic_mac is None:
7766
          nic_dict['mac'] = constants.VALUE_AUTO
7767

    
7768
      if 'mac' in nic_dict:
7769
        nic_mac = nic_dict['mac']
7770
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7771
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
7772

    
7773
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
7774
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
7775
                                     " modifying an existing nic",
7776
                                     errors.ECODE_INVAL)
7777

    
7778
    if nic_addremove > 1:
7779
      raise errors.OpPrereqError("Only one NIC add or remove operation"
7780
                                 " supported at a time", errors.ECODE_INVAL)
7781

    
7782
  def ExpandNames(self):
7783
    self._ExpandAndLockInstance()
7784
    self.needed_locks[locking.LEVEL_NODE] = []
7785
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7786

    
7787
  def DeclareLocks(self, level):
7788
    if level == locking.LEVEL_NODE:
7789
      self._LockInstancesNodes()
7790

    
7791
  def BuildHooksEnv(self):
7792
    """Build hooks env.
7793

7794
    This runs on the master, primary and secondaries.
7795

7796
    """
7797
    args = dict()
7798
    if constants.BE_MEMORY in self.be_new:
7799
      args['memory'] = self.be_new[constants.BE_MEMORY]
7800
    if constants.BE_VCPUS in self.be_new:
7801
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
7802
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
7803
    # information at all.
7804
    if self.op.nics:
7805
      args['nics'] = []
7806
      nic_override = dict(self.op.nics)
7807
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
7808
      for idx, nic in enumerate(self.instance.nics):
7809
        if idx in nic_override:
7810
          this_nic_override = nic_override[idx]
7811
        else:
7812
          this_nic_override = {}
7813
        if 'ip' in this_nic_override:
7814
          ip = this_nic_override['ip']
7815
        else:
7816
          ip = nic.ip
7817
        if 'mac' in this_nic_override:
7818
          mac = this_nic_override['mac']
7819
        else:
7820
          mac = nic.mac
7821
        if idx in self.nic_pnew:
7822
          nicparams = self.nic_pnew[idx]
7823
        else:
7824
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
7825
        mode = nicparams[constants.NIC_MODE]
7826
        link = nicparams[constants.NIC_LINK]
7827
        args['nics'].append((ip, mac, mode, link))
7828
      if constants.DDM_ADD in nic_override:
7829
        ip = nic_override[constants.DDM_ADD].get('ip', None)
7830
        mac = nic_override[constants.DDM_ADD]['mac']
7831
        nicparams = self.nic_pnew[constants.DDM_ADD]
7832
        mode = nicparams[constants.NIC_MODE]
7833
        link = nicparams[constants.NIC_LINK]
7834
        args['nics'].append((ip, mac, mode, link))
7835
      elif constants.DDM_REMOVE in nic_override:
7836
        del args['nics'][-1]
7837

    
7838
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
7839
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7840
    return env, nl, nl
7841

    
7842
  @staticmethod
7843
  def _GetUpdatedParams(old_params, update_dict,
7844
                        default_values, parameter_types):
7845
    """Return the new params dict for the given params.
7846

7847
    @type old_params: dict
7848
    @param old_params: old parameters
7849
    @type update_dict: dict
7850
    @param update_dict: dict containing new parameter values,
7851
                        or constants.VALUE_DEFAULT to reset the
7852
                        parameter to its default value
7853
    @type default_values: dict
7854
    @param default_values: default values for the filled parameters
7855
    @type parameter_types: dict
7856
    @param parameter_types: dict mapping target dict keys to types
7857
                            in constants.ENFORCEABLE_TYPES
7858
    @rtype: (dict, dict)
7859
    @return: (new_parameters, filled_parameters)
7860

7861
    """
7862
    params_copy = copy.deepcopy(old_params)
7863
    for key, val in update_dict.iteritems():
7864
      if val == constants.VALUE_DEFAULT:
7865
        try:
7866
          del params_copy[key]
7867
        except KeyError:
7868
          pass
7869
      else:
7870
        params_copy[key] = val
7871
    utils.ForceDictType(params_copy, parameter_types)
7872
    params_filled = objects.FillDict(default_values, params_copy)
7873
    return (params_copy, params_filled)
7874

    
7875
  def CheckPrereq(self):
7876
    """Check prerequisites.
7877

7878
    This only checks the instance list against the existing names.
7879

7880
    """
7881
    self.force = self.op.force
7882

    
7883
    # checking the new params on the primary/secondary nodes
7884

    
7885
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7886
    cluster = self.cluster = self.cfg.GetClusterInfo()
7887
    assert self.instance is not None, \
7888
      "Cannot retrieve locked instance %s" % self.op.instance_name
7889
    pnode = instance.primary_node
7890
    nodelist = list(instance.all_nodes)
7891

    
7892
    # hvparams processing
7893
    if self.op.hvparams:
7894
      i_hvdict, hv_new = self._GetUpdatedParams(
7895
                             instance.hvparams, self.op.hvparams,
7896
                             cluster.hvparams[instance.hypervisor],
7897
                             constants.HVS_PARAMETER_TYPES)
7898
      # local check
7899
      hypervisor.GetHypervisor(
7900
        instance.hypervisor).CheckParameterSyntax(hv_new)
7901
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
7902
      self.hv_new = hv_new # the new actual values
7903
      self.hv_inst = i_hvdict # the new dict (without defaults)
7904
    else:
7905
      self.hv_new = self.hv_inst = {}
7906

    
7907
    # beparams processing
7908
    if self.op.beparams:
7909
      i_bedict, be_new = self._GetUpdatedParams(
7910
                             instance.beparams, self.op.beparams,
7911
                             cluster.beparams[constants.PP_DEFAULT],
7912
                             constants.BES_PARAMETER_TYPES)
7913
      self.be_new = be_new # the new actual values
7914
      self.be_inst = i_bedict # the new dict (without defaults)
7915
    else:
7916
      self.be_new = self.be_inst = {}
7917

    
7918
    self.warn = []
7919

    
7920
    if constants.BE_MEMORY in self.op.beparams and not self.force:
7921
      mem_check_list = [pnode]
7922
      if be_new[constants.BE_AUTO_BALANCE]:
7923
        # either we changed auto_balance to yes or it was from before
7924
        mem_check_list.extend(instance.secondary_nodes)
7925
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
7926
                                                  instance.hypervisor)
7927
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
7928
                                         instance.hypervisor)
7929
      pninfo = nodeinfo[pnode]
7930
      msg = pninfo.fail_msg
7931
      if msg:
7932
        # Assume the primary node is unreachable and go ahead
7933
        self.warn.append("Can't get info from primary node %s: %s" %
7934
                         (pnode,  msg))
7935
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
7936
        self.warn.append("Node data from primary node %s doesn't contain"
7937
                         " free memory information" % pnode)
7938
      elif instance_info.fail_msg:
7939
        self.warn.append("Can't get instance runtime information: %s" %
7940
                        instance_info.fail_msg)
7941
      else:
7942
        if instance_info.payload:
7943
          current_mem = int(instance_info.payload['memory'])
7944
        else:
7945
          # Assume instance not running
7946
          # (there is a slight race condition here, but it's not very probable,
7947
          # and we have no other way to check)
7948
          current_mem = 0
7949
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
7950
                    pninfo.payload['memory_free'])
7951
        if miss_mem > 0:
7952
          raise errors.OpPrereqError("This change will prevent the instance"
7953
                                     " from starting, due to %d MB of memory"
7954
                                     " missing on its primary node" % miss_mem,
7955
                                     errors.ECODE_NORES)
7956

    
7957
      if be_new[constants.BE_AUTO_BALANCE]:
7958
        for node, nres in nodeinfo.items():
7959
          if node not in instance.secondary_nodes:
7960
            continue
7961
          msg = nres.fail_msg
7962
          if msg:
7963
            self.warn.append("Can't get info from secondary node %s: %s" %
7964
                             (node, msg))
7965
          elif not isinstance(nres.payload.get('memory_free', None), int):
7966
            self.warn.append("Secondary node %s didn't return free"
7967
                             " memory information" % node)
7968
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
7969
            self.warn.append("Not enough memory to failover instance to"
7970
                             " secondary node %s" % node)
7971

    
7972
    # NIC processing
7973
    self.nic_pnew = {}
7974
    self.nic_pinst = {}
7975
    for nic_op, nic_dict in self.op.nics:
7976
      if nic_op == constants.DDM_REMOVE:
7977
        if not instance.nics:
7978
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
7979
                                     errors.ECODE_INVAL)
7980
        continue
7981
      if nic_op != constants.DDM_ADD:
7982
        # an existing nic
7983
        if not instance.nics:
7984
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
7985
                                     " no NICs" % nic_op,
7986
                                     errors.ECODE_INVAL)
7987
        if nic_op < 0 or nic_op >= len(instance.nics):
7988
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
7989
                                     " are 0 to %d" %
7990
                                     (nic_op, len(instance.nics) - 1),
7991
                                     errors.ECODE_INVAL)
7992
        old_nic_params = instance.nics[nic_op].nicparams
7993
        old_nic_ip = instance.nics[nic_op].ip
7994
      else:
7995
        old_nic_params = {}
7996
        old_nic_ip = None
7997

    
7998
      update_params_dict = dict([(key, nic_dict[key])
7999
                                 for key in constants.NICS_PARAMETERS
8000
                                 if key in nic_dict])
8001

    
8002
      if 'bridge' in nic_dict:
8003
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8004

    
8005
      new_nic_params, new_filled_nic_params = \
8006
          self._GetUpdatedParams(old_nic_params, update_params_dict,
8007
                                 cluster.nicparams[constants.PP_DEFAULT],
8008
                                 constants.NICS_PARAMETER_TYPES)
8009
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8010
      self.nic_pinst[nic_op] = new_nic_params
8011
      self.nic_pnew[nic_op] = new_filled_nic_params
8012
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8013

    
8014
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8015
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8016
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8017
        if msg:
8018
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8019
          if self.force:
8020
            self.warn.append(msg)
8021
          else:
8022
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8023
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8024
        if 'ip' in nic_dict:
8025
          nic_ip = nic_dict['ip']
8026
        else:
8027
          nic_ip = old_nic_ip
8028
        if nic_ip is None:
8029
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8030
                                     ' on a routed nic', errors.ECODE_INVAL)
8031
      if 'mac' in nic_dict:
8032
        nic_mac = nic_dict['mac']
8033
        if nic_mac is None:
8034
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8035
                                     errors.ECODE_INVAL)
8036
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8037
          # otherwise generate the mac
8038
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8039
        else:
8040
          # or validate/reserve the current one
8041
          try:
8042
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8043
          except errors.ReservationError:
8044
            raise errors.OpPrereqError("MAC address %s already in use"
8045
                                       " in cluster" % nic_mac,
8046
                                       errors.ECODE_NOTUNIQUE)
8047

    
8048
    # DISK processing
8049
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8050
      raise errors.OpPrereqError("Disk operations not supported for"
8051
                                 " diskless instances",
8052
                                 errors.ECODE_INVAL)
8053
    for disk_op, _ in self.op.disks:
8054
      if disk_op == constants.DDM_REMOVE:
8055
        if len(instance.disks) == 1:
8056
          raise errors.OpPrereqError("Cannot remove the last disk of"
8057
                                     " an instance",
8058
                                     errors.ECODE_INVAL)
8059
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
8060
        ins_l = ins_l[pnode]
8061
        msg = ins_l.fail_msg
8062
        if msg:
8063
          raise errors.OpPrereqError("Can't contact node %s: %s" %
8064
                                     (pnode, msg), errors.ECODE_ENVIRON)
8065
        if instance.name in ins_l.payload:
8066
          raise errors.OpPrereqError("Instance is running, can't remove"
8067
                                     " disks.", errors.ECODE_STATE)
8068

    
8069
      if (disk_op == constants.DDM_ADD and
8070
          len(instance.nics) >= constants.MAX_DISKS):
8071
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8072
                                   " add more" % constants.MAX_DISKS,
8073
                                   errors.ECODE_STATE)
8074
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8075
        # an existing disk
8076
        if disk_op < 0 or disk_op >= len(instance.disks):
8077
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8078
                                     " are 0 to %d" %
8079
                                     (disk_op, len(instance.disks)),
8080
                                     errors.ECODE_INVAL)
8081

    
8082
    return
8083

    
8084
  def Exec(self, feedback_fn):
8085
    """Modifies an instance.
8086

8087
    All parameters take effect only at the next restart of the instance.
8088

8089
    """
8090
    # Process here the warnings from CheckPrereq, as we don't have a
8091
    # feedback_fn there.
8092
    for warn in self.warn:
8093
      feedback_fn("WARNING: %s" % warn)
8094

    
8095
    result = []
8096
    instance = self.instance
8097
    # disk changes
8098
    for disk_op, disk_dict in self.op.disks:
8099
      if disk_op == constants.DDM_REMOVE:
8100
        # remove the last disk
8101
        device = instance.disks.pop()
8102
        device_idx = len(instance.disks)
8103
        for node, disk in device.ComputeNodeTree(instance.primary_node):
8104
          self.cfg.SetDiskID(disk, node)
8105
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
8106
          if msg:
8107
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
8108
                            " continuing anyway", device_idx, node, msg)
8109
        result.append(("disk/%d" % device_idx, "remove"))
8110
      elif disk_op == constants.DDM_ADD:
8111
        # add a new disk
8112
        if instance.disk_template == constants.DT_FILE:
8113
          file_driver, file_path = instance.disks[0].logical_id
8114
          file_path = os.path.dirname(file_path)
8115
        else:
8116
          file_driver = file_path = None
8117
        disk_idx_base = len(instance.disks)
8118
        new_disk = _GenerateDiskTemplate(self,
8119
                                         instance.disk_template,
8120
                                         instance.name, instance.primary_node,
8121
                                         instance.secondary_nodes,
8122
                                         [disk_dict],
8123
                                         file_path,
8124
                                         file_driver,
8125
                                         disk_idx_base)[0]
8126
        instance.disks.append(new_disk)
8127
        info = _GetInstanceInfoText(instance)
8128

    
8129
        logging.info("Creating volume %s for instance %s",
8130
                     new_disk.iv_name, instance.name)
8131
        # Note: this needs to be kept in sync with _CreateDisks
8132
        #HARDCODE
8133
        for node in instance.all_nodes:
8134
          f_create = node == instance.primary_node
8135
          try:
8136
            _CreateBlockDev(self, node, instance, new_disk,
8137
                            f_create, info, f_create)
8138
          except errors.OpExecError, err:
8139
            self.LogWarning("Failed to create volume %s (%s) on"
8140
                            " node %s: %s",
8141
                            new_disk.iv_name, new_disk, node, err)
8142
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
8143
                       (new_disk.size, new_disk.mode)))
8144
      else:
8145
        # change a given disk
8146
        instance.disks[disk_op].mode = disk_dict['mode']
8147
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
8148
    # NIC changes
8149
    for nic_op, nic_dict in self.op.nics:
8150
      if nic_op == constants.DDM_REMOVE:
8151
        # remove the last nic
8152
        del instance.nics[-1]
8153
        result.append(("nic.%d" % len(instance.nics), "remove"))
8154
      elif nic_op == constants.DDM_ADD:
8155
        # mac and bridge should be set, by now
8156
        mac = nic_dict['mac']
8157
        ip = nic_dict.get('ip', None)
8158
        nicparams = self.nic_pinst[constants.DDM_ADD]
8159
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
8160
        instance.nics.append(new_nic)
8161
        result.append(("nic.%d" % (len(instance.nics) - 1),
8162
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
8163
                       (new_nic.mac, new_nic.ip,
8164
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
8165
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
8166
                       )))
8167
      else:
8168
        for key in 'mac', 'ip':
8169
          if key in nic_dict:
8170
            setattr(instance.nics[nic_op], key, nic_dict[key])
8171
        if nic_op in self.nic_pinst:
8172
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
8173
        for key, val in nic_dict.iteritems():
8174
          result.append(("nic.%s/%d" % (key, nic_op), val))
8175

    
8176
    # hvparams changes
8177
    if self.op.hvparams:
8178
      instance.hvparams = self.hv_inst
8179
      for key, val in self.op.hvparams.iteritems():
8180
        result.append(("hv/%s" % key, val))
8181

    
8182
    # beparams changes
8183
    if self.op.beparams:
8184
      instance.beparams = self.be_inst
8185
      for key, val in self.op.beparams.iteritems():
8186
        result.append(("be/%s" % key, val))
8187

    
8188
    self.cfg.Update(instance, feedback_fn)
8189

    
8190
    return result
8191

    
8192

    
8193
class LUQueryExports(NoHooksLU):
8194
  """Query the exports list
8195

8196
  """
8197
  _OP_REQP = ['nodes']
8198
  REQ_BGL = False
8199

    
8200
  def ExpandNames(self):
8201
    self.needed_locks = {}
8202
    self.share_locks[locking.LEVEL_NODE] = 1
8203
    if not self.op.nodes:
8204
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8205
    else:
8206
      self.needed_locks[locking.LEVEL_NODE] = \
8207
        _GetWantedNodes(self, self.op.nodes)
8208

    
8209
  def CheckPrereq(self):
8210
    """Check prerequisites.
8211

8212
    """
8213
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
8214

    
8215
  def Exec(self, feedback_fn):
8216
    """Compute the list of all the exported system images.
8217

8218
    @rtype: dict
8219
    @return: a dictionary with the structure node->(export-list)
8220
        where export-list is a list of the instances exported on
8221
        that node.
8222

8223
    """
8224
    rpcresult = self.rpc.call_export_list(self.nodes)
8225
    result = {}
8226
    for node in rpcresult:
8227
      if rpcresult[node].fail_msg:
8228
        result[node] = False
8229
      else:
8230
        result[node] = rpcresult[node].payload
8231

    
8232
    return result
8233

    
8234

    
8235
class LUExportInstance(LogicalUnit):
8236
  """Export an instance to an image in the cluster.
8237

8238
  """
8239
  HPATH = "instance-export"
8240
  HTYPE = constants.HTYPE_INSTANCE
8241
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
8242
  REQ_BGL = False
8243

    
8244
  def CheckArguments(self):
8245
    """Check the arguments.
8246

8247
    """
8248
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
8249
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
8250

    
8251
  def ExpandNames(self):
8252
    self._ExpandAndLockInstance()
8253
    # FIXME: lock only instance primary and destination node
8254
    #
8255
    # Sad but true, for now we have do lock all nodes, as we don't know where
8256
    # the previous export might be, and and in this LU we search for it and
8257
    # remove it from its current node. In the future we could fix this by:
8258
    #  - making a tasklet to search (share-lock all), then create the new one,
8259
    #    then one to remove, after
8260
    #  - removing the removal operation altogether
8261
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8262

    
8263
  def DeclareLocks(self, level):
8264
    """Last minute lock declaration."""
8265
    # All nodes are locked anyway, so nothing to do here.
8266

    
8267
  def BuildHooksEnv(self):
8268
    """Build hooks env.
8269

8270
    This will run on the master, primary node and target node.
8271

8272
    """
8273
    env = {
8274
      "EXPORT_NODE": self.op.target_node,
8275
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
8276
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
8277
      }
8278
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8279
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
8280
          self.op.target_node]
8281
    return env, nl, nl
8282

    
8283
  def CheckPrereq(self):
8284
    """Check prerequisites.
8285

8286
    This checks that the instance and node names are valid.
8287

8288
    """
8289
    instance_name = self.op.instance_name
8290
    self.instance = self.cfg.GetInstanceInfo(instance_name)
8291
    assert self.instance is not None, \
8292
          "Cannot retrieve locked instance %s" % self.op.instance_name
8293
    _CheckNodeOnline(self, self.instance.primary_node)
8294

    
8295
    self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
8296
    self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
8297
    assert self.dst_node is not None
8298

    
8299
    _CheckNodeOnline(self, self.dst_node.name)
8300
    _CheckNodeNotDrained(self, self.dst_node.name)
8301

    
8302
    # instance disk type verification
8303
    for disk in self.instance.disks:
8304
      if disk.dev_type == constants.LD_FILE:
8305
        raise errors.OpPrereqError("Export not supported for instances with"
8306
                                   " file-based disks", errors.ECODE_INVAL)
8307

    
8308
  def Exec(self, feedback_fn):
8309
    """Export an instance to an image in the cluster.
8310

8311
    """
8312
    instance = self.instance
8313
    dst_node = self.dst_node
8314
    src_node = instance.primary_node
8315

    
8316
    if self.op.shutdown:
8317
      # shutdown the instance, but not the disks
8318
      feedback_fn("Shutting down instance %s" % instance.name)
8319
      result = self.rpc.call_instance_shutdown(src_node, instance,
8320
                                               self.shutdown_timeout)
8321
      result.Raise("Could not shutdown instance %s on"
8322
                   " node %s" % (instance.name, src_node))
8323

    
8324
    vgname = self.cfg.GetVGName()
8325

    
8326
    snap_disks = []
8327

    
8328
    # set the disks ID correctly since call_instance_start needs the
8329
    # correct drbd minor to create the symlinks
8330
    for disk in instance.disks:
8331
      self.cfg.SetDiskID(disk, src_node)
8332

    
8333
    activate_disks = (not instance.admin_up)
8334

    
8335
    if activate_disks:
8336
      # Activate the instance disks if we'exporting a stopped instance
8337
      feedback_fn("Activating disks for %s" % instance.name)
8338
      _StartInstanceDisks(self, instance, None)
8339

    
8340
    try:
8341
      # per-disk results
8342
      dresults = []
8343
      try:
8344
        for idx, disk in enumerate(instance.disks):
8345
          feedback_fn("Creating a snapshot of disk/%s on node %s" %
8346
                      (idx, src_node))
8347

    
8348
          # result.payload will be a snapshot of an lvm leaf of the one we
8349
          # passed
8350
          result = self.rpc.call_blockdev_snapshot(src_node, disk)
8351
          msg = result.fail_msg
8352
          if msg:
8353
            self.LogWarning("Could not snapshot disk/%s on node %s: %s",
8354
                            idx, src_node, msg)
8355
            snap_disks.append(False)
8356
          else:
8357
            disk_id = (vgname, result.payload)
8358
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
8359
                                   logical_id=disk_id, physical_id=disk_id,
8360
                                   iv_name=disk.iv_name)
8361
            snap_disks.append(new_dev)
8362

    
8363
      finally:
8364
        if self.op.shutdown and instance.admin_up:
8365
          feedback_fn("Starting instance %s" % instance.name)
8366
          result = self.rpc.call_instance_start(src_node, instance, None, None)
8367
          msg = result.fail_msg
8368
          if msg:
8369
            _ShutdownInstanceDisks(self, instance)
8370
            raise errors.OpExecError("Could not start instance: %s" % msg)
8371

    
8372
      # TODO: check for size
8373

    
8374
      cluster_name = self.cfg.GetClusterName()
8375
      for idx, dev in enumerate(snap_disks):
8376
        feedback_fn("Exporting snapshot %s from %s to %s" %
8377
                    (idx, src_node, dst_node.name))
8378
        if dev:
8379
          # FIXME: pass debug from opcode to backend
8380
          result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
8381
                                                 instance, cluster_name,
8382
                                                 idx, self.op.debug_level)
8383
          msg = result.fail_msg
8384
          if msg:
8385
            self.LogWarning("Could not export disk/%s from node %s to"
8386
                            " node %s: %s", idx, src_node, dst_node.name, msg)
8387
            dresults.append(False)
8388
          else:
8389
            dresults.append(True)
8390
          msg = self.rpc.call_blockdev_remove(src_node, dev).fail_msg
8391
          if msg:
8392
            self.LogWarning("Could not remove snapshot for disk/%d from node"
8393
                            " %s: %s", idx, src_node, msg)
8394
        else:
8395
          dresults.append(False)
8396

    
8397
      feedback_fn("Finalizing export on %s" % dst_node.name)
8398
      result = self.rpc.call_finalize_export(dst_node.name, instance,
8399
                                             snap_disks)
8400
      fin_resu = True
8401
      msg = result.fail_msg
8402
      if msg:
8403
        self.LogWarning("Could not finalize export for instance %s"
8404
                        " on node %s: %s", instance.name, dst_node.name, msg)
8405
        fin_resu = False
8406

    
8407
    finally:
8408
      if activate_disks:
8409
        feedback_fn("Deactivating disks for %s" % instance.name)
8410
        _ShutdownInstanceDisks(self, instance)
8411

    
8412
    nodelist = self.cfg.GetNodeList()
8413
    nodelist.remove(dst_node.name)
8414

    
8415
    # on one-node clusters nodelist will be empty after the removal
8416
    # if we proceed the backup would be removed because OpQueryExports
8417
    # substitutes an empty list with the full cluster node list.
8418
    iname = instance.name
8419
    if nodelist:
8420
      feedback_fn("Removing old exports for instance %s" % iname)
8421
      exportlist = self.rpc.call_export_list(nodelist)
8422
      for node in exportlist:
8423
        if exportlist[node].fail_msg:
8424
          continue
8425
        if iname in exportlist[node].payload:
8426
          msg = self.rpc.call_export_remove(node, iname).fail_msg
8427
          if msg:
8428
            self.LogWarning("Could not remove older export for instance %s"
8429
                            " on node %s: %s", iname, node, msg)
8430
    return fin_resu, dresults
8431

    
8432

    
8433
class LURemoveExport(NoHooksLU):
8434
  """Remove exports related to the named instance.
8435

8436
  """
8437
  _OP_REQP = ["instance_name"]
8438
  REQ_BGL = False
8439

    
8440
  def ExpandNames(self):
8441
    self.needed_locks = {}
8442
    # We need all nodes to be locked in order for RemoveExport to work, but we
8443
    # don't need to lock the instance itself, as nothing will happen to it (and
8444
    # we can remove exports also for a removed instance)
8445
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8446

    
8447
  def CheckPrereq(self):
8448
    """Check prerequisites.
8449
    """
8450
    pass
8451

    
8452
  def Exec(self, feedback_fn):
8453
    """Remove any export.
8454

8455
    """
8456
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
8457
    # If the instance was not found we'll try with the name that was passed in.
8458
    # This will only work if it was an FQDN, though.
8459
    fqdn_warn = False
8460
    if not instance_name:
8461
      fqdn_warn = True
8462
      instance_name = self.op.instance_name
8463

    
8464
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
8465
    exportlist = self.rpc.call_export_list(locked_nodes)
8466
    found = False
8467
    for node in exportlist:
8468
      msg = exportlist[node].fail_msg
8469
      if msg:
8470
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
8471
        continue
8472
      if instance_name in exportlist[node].payload:
8473
        found = True
8474
        result = self.rpc.call_export_remove(node, instance_name)
8475
        msg = result.fail_msg
8476
        if msg:
8477
          logging.error("Could not remove export for instance %s"
8478
                        " on node %s: %s", instance_name, node, msg)
8479

    
8480
    if fqdn_warn and not found:
8481
      feedback_fn("Export not found. If trying to remove an export belonging"
8482
                  " to a deleted instance please use its Fully Qualified"
8483
                  " Domain Name.")
8484

    
8485

    
8486
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
8487
  """Generic tags LU.
8488

8489
  This is an abstract class which is the parent of all the other tags LUs.
8490

8491
  """
8492

    
8493
  def ExpandNames(self):
8494
    self.needed_locks = {}
8495
    if self.op.kind == constants.TAG_NODE:
8496
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
8497
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
8498
    elif self.op.kind == constants.TAG_INSTANCE:
8499
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
8500
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
8501

    
8502
  def CheckPrereq(self):
8503
    """Check prerequisites.
8504

8505
    """
8506
    if self.op.kind == constants.TAG_CLUSTER:
8507
      self.target = self.cfg.GetClusterInfo()
8508
    elif self.op.kind == constants.TAG_NODE:
8509
      self.target = self.cfg.GetNodeInfo(self.op.name)
8510
    elif self.op.kind == constants.TAG_INSTANCE:
8511
      self.target = self.cfg.GetInstanceInfo(self.op.name)
8512
    else:
8513
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
8514
                                 str(self.op.kind), errors.ECODE_INVAL)
8515

    
8516

    
8517
class LUGetTags(TagsLU):
8518
  """Returns the tags of a given object.
8519

8520
  """
8521
  _OP_REQP = ["kind", "name"]
8522
  REQ_BGL = False
8523

    
8524
  def Exec(self, feedback_fn):
8525
    """Returns the tag list.
8526

8527
    """
8528
    return list(self.target.GetTags())
8529

    
8530

    
8531
class LUSearchTags(NoHooksLU):
8532
  """Searches the tags for a given pattern.
8533

8534
  """
8535
  _OP_REQP = ["pattern"]
8536
  REQ_BGL = False
8537

    
8538
  def ExpandNames(self):
8539
    self.needed_locks = {}
8540

    
8541
  def CheckPrereq(self):
8542
    """Check prerequisites.
8543

8544
    This checks the pattern passed for validity by compiling it.
8545

8546
    """
8547
    try:
8548
      self.re = re.compile(self.op.pattern)
8549
    except re.error, err:
8550
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
8551
                                 (self.op.pattern, err), errors.ECODE_INVAL)
8552

    
8553
  def Exec(self, feedback_fn):
8554
    """Returns the tag list.
8555

8556
    """
8557
    cfg = self.cfg
8558
    tgts = [("/cluster", cfg.GetClusterInfo())]
8559
    ilist = cfg.GetAllInstancesInfo().values()
8560
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
8561
    nlist = cfg.GetAllNodesInfo().values()
8562
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
8563
    results = []
8564
    for path, target in tgts:
8565
      for tag in target.GetTags():
8566
        if self.re.search(tag):
8567
          results.append((path, tag))
8568
    return results
8569

    
8570

    
8571
class LUAddTags(TagsLU):
8572
  """Sets a tag on a given object.
8573

8574
  """
8575
  _OP_REQP = ["kind", "name", "tags"]
8576
  REQ_BGL = False
8577

    
8578
  def CheckPrereq(self):
8579
    """Check prerequisites.
8580

8581
    This checks the type and length of the tag name and value.
8582

8583
    """
8584
    TagsLU.CheckPrereq(self)
8585
    for tag in self.op.tags:
8586
      objects.TaggableObject.ValidateTag(tag)
8587

    
8588
  def Exec(self, feedback_fn):
8589
    """Sets the tag.
8590

8591
    """
8592
    try:
8593
      for tag in self.op.tags:
8594
        self.target.AddTag(tag)
8595
    except errors.TagError, err:
8596
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
8597
    self.cfg.Update(self.target, feedback_fn)
8598

    
8599

    
8600
class LUDelTags(TagsLU):
8601
  """Delete a list of tags from a given object.
8602

8603
  """
8604
  _OP_REQP = ["kind", "name", "tags"]
8605
  REQ_BGL = False
8606

    
8607
  def CheckPrereq(self):
8608
    """Check prerequisites.
8609

8610
    This checks that we have the given tag.
8611

8612
    """
8613
    TagsLU.CheckPrereq(self)
8614
    for tag in self.op.tags:
8615
      objects.TaggableObject.ValidateTag(tag)
8616
    del_tags = frozenset(self.op.tags)
8617
    cur_tags = self.target.GetTags()
8618
    if not del_tags <= cur_tags:
8619
      diff_tags = del_tags - cur_tags
8620
      diff_names = ["'%s'" % tag for tag in diff_tags]
8621
      diff_names.sort()
8622
      raise errors.OpPrereqError("Tag(s) %s not found" %
8623
                                 (",".join(diff_names)), errors.ECODE_NOENT)
8624

    
8625
  def Exec(self, feedback_fn):
8626
    """Remove the tag from the object.
8627

8628
    """
8629
    for tag in self.op.tags:
8630
      self.target.RemoveTag(tag)
8631
    self.cfg.Update(self.target, feedback_fn)
8632

    
8633

    
8634
class LUTestDelay(NoHooksLU):
8635
  """Sleep for a specified amount of time.
8636

8637
  This LU sleeps on the master and/or nodes for a specified amount of
8638
  time.
8639

8640
  """
8641
  _OP_REQP = ["duration", "on_master", "on_nodes"]
8642
  REQ_BGL = False
8643

    
8644
  def ExpandNames(self):
8645
    """Expand names and set required locks.
8646

8647
    This expands the node list, if any.
8648

8649
    """
8650
    self.needed_locks = {}
8651
    if self.op.on_nodes:
8652
      # _GetWantedNodes can be used here, but is not always appropriate to use
8653
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
8654
      # more information.
8655
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
8656
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
8657

    
8658
  def CheckPrereq(self):
8659
    """Check prerequisites.
8660

8661
    """
8662

    
8663
  def Exec(self, feedback_fn):
8664
    """Do the actual sleep.
8665

8666
    """
8667
    if self.op.on_master:
8668
      if not utils.TestDelay(self.op.duration):
8669
        raise errors.OpExecError("Error during master delay test")
8670
    if self.op.on_nodes:
8671
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
8672
      for node, node_result in result.items():
8673
        node_result.Raise("Failure during rpc call to node %s" % node)
8674

    
8675

    
8676
class IAllocator(object):
8677
  """IAllocator framework.
8678

8679
  An IAllocator instance has three sets of attributes:
8680
    - cfg that is needed to query the cluster
8681
    - input data (all members of the _KEYS class attribute are required)
8682
    - four buffer attributes (in|out_data|text), that represent the
8683
      input (to the external script) in text and data structure format,
8684
      and the output from it, again in two formats
8685
    - the result variables from the script (success, info, nodes) for
8686
      easy usage
8687

8688
  """
8689
  # pylint: disable-msg=R0902
8690
  # lots of instance attributes
8691
  _ALLO_KEYS = [
8692
    "name", "mem_size", "disks", "disk_template",
8693
    "os", "tags", "nics", "vcpus", "hypervisor",
8694
    ]
8695
  _RELO_KEYS = [
8696
    "name", "relocate_from",
8697
    ]
8698
  _EVAC_KEYS = [
8699
    "evac_nodes",
8700
    ]
8701

    
8702
  def __init__(self, cfg, rpc, mode, **kwargs):
8703
    self.cfg = cfg
8704
    self.rpc = rpc
8705
    # init buffer variables
8706
    self.in_text = self.out_text = self.in_data = self.out_data = None
8707
    # init all input fields so that pylint is happy
8708
    self.mode = mode
8709
    self.mem_size = self.disks = self.disk_template = None
8710
    self.os = self.tags = self.nics = self.vcpus = None
8711
    self.hypervisor = None
8712
    self.relocate_from = None
8713
    self.name = None
8714
    self.evac_nodes = None
8715
    # computed fields
8716
    self.required_nodes = None
8717
    # init result fields
8718
    self.success = self.info = self.result = None
8719
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8720
      keyset = self._ALLO_KEYS
8721
      fn = self._AddNewInstance
8722
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8723
      keyset = self._RELO_KEYS
8724
      fn = self._AddRelocateInstance
8725
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
8726
      keyset = self._EVAC_KEYS
8727
      fn = self._AddEvacuateNodes
8728
    else:
8729
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
8730
                                   " IAllocator" % self.mode)
8731
    for key in kwargs:
8732
      if key not in keyset:
8733
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
8734
                                     " IAllocator" % key)
8735
      setattr(self, key, kwargs[key])
8736

    
8737
    for key in keyset:
8738
      if key not in kwargs:
8739
        raise errors.ProgrammerError("Missing input parameter '%s' to"
8740
                                     " IAllocator" % key)
8741
    self._BuildInputData(fn)
8742

    
8743
  def _ComputeClusterData(self):
8744
    """Compute the generic allocator input data.
8745

8746
    This is the data that is independent of the actual operation.
8747

8748
    """
8749
    cfg = self.cfg
8750
    cluster_info = cfg.GetClusterInfo()
8751
    # cluster data
8752
    data = {
8753
      "version": constants.IALLOCATOR_VERSION,
8754
      "cluster_name": cfg.GetClusterName(),
8755
      "cluster_tags": list(cluster_info.GetTags()),
8756
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
8757
      # we don't have job IDs
8758
      }
8759
    iinfo = cfg.GetAllInstancesInfo().values()
8760
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
8761

    
8762
    # node data
8763
    node_results = {}
8764
    node_list = cfg.GetNodeList()
8765

    
8766
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8767
      hypervisor_name = self.hypervisor
8768
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8769
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
8770
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
8771
      hypervisor_name = cluster_info.enabled_hypervisors[0]
8772

    
8773
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
8774
                                        hypervisor_name)
8775
    node_iinfo = \
8776
      self.rpc.call_all_instances_info(node_list,
8777
                                       cluster_info.enabled_hypervisors)
8778
    for nname, nresult in node_data.items():
8779
      # first fill in static (config-based) values
8780
      ninfo = cfg.GetNodeInfo(nname)
8781
      pnr = {
8782
        "tags": list(ninfo.GetTags()),
8783
        "primary_ip": ninfo.primary_ip,
8784
        "secondary_ip": ninfo.secondary_ip,
8785
        "offline": ninfo.offline,
8786
        "drained": ninfo.drained,
8787
        "master_candidate": ninfo.master_candidate,
8788
        }
8789

    
8790
      if not (ninfo.offline or ninfo.drained):
8791
        nresult.Raise("Can't get data for node %s" % nname)
8792
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
8793
                                nname)
8794
        remote_info = nresult.payload
8795

    
8796
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
8797
                     'vg_size', 'vg_free', 'cpu_total']:
8798
          if attr not in remote_info:
8799
            raise errors.OpExecError("Node '%s' didn't return attribute"
8800
                                     " '%s'" % (nname, attr))
8801
          if not isinstance(remote_info[attr], int):
8802
            raise errors.OpExecError("Node '%s' returned invalid value"
8803
                                     " for '%s': %s" %
8804
                                     (nname, attr, remote_info[attr]))
8805
        # compute memory used by primary instances
8806
        i_p_mem = i_p_up_mem = 0
8807
        for iinfo, beinfo in i_list:
8808
          if iinfo.primary_node == nname:
8809
            i_p_mem += beinfo[constants.BE_MEMORY]
8810
            if iinfo.name not in node_iinfo[nname].payload:
8811
              i_used_mem = 0
8812
            else:
8813
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
8814
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
8815
            remote_info['memory_free'] -= max(0, i_mem_diff)
8816

    
8817
            if iinfo.admin_up:
8818
              i_p_up_mem += beinfo[constants.BE_MEMORY]
8819

    
8820
        # compute memory used by instances
8821
        pnr_dyn = {
8822
          "total_memory": remote_info['memory_total'],
8823
          "reserved_memory": remote_info['memory_dom0'],
8824
          "free_memory": remote_info['memory_free'],
8825
          "total_disk": remote_info['vg_size'],
8826
          "free_disk": remote_info['vg_free'],
8827
          "total_cpus": remote_info['cpu_total'],
8828
          "i_pri_memory": i_p_mem,
8829
          "i_pri_up_memory": i_p_up_mem,
8830
          }
8831
        pnr.update(pnr_dyn)
8832

    
8833
      node_results[nname] = pnr
8834
    data["nodes"] = node_results
8835

    
8836
    # instance data
8837
    instance_data = {}
8838
    for iinfo, beinfo in i_list:
8839
      nic_data = []
8840
      for nic in iinfo.nics:
8841
        filled_params = objects.FillDict(
8842
            cluster_info.nicparams[constants.PP_DEFAULT],
8843
            nic.nicparams)
8844
        nic_dict = {"mac": nic.mac,
8845
                    "ip": nic.ip,
8846
                    "mode": filled_params[constants.NIC_MODE],
8847
                    "link": filled_params[constants.NIC_LINK],
8848
                   }
8849
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
8850
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
8851
        nic_data.append(nic_dict)
8852
      pir = {
8853
        "tags": list(iinfo.GetTags()),
8854
        "admin_up": iinfo.admin_up,
8855
        "vcpus": beinfo[constants.BE_VCPUS],
8856
        "memory": beinfo[constants.BE_MEMORY],
8857
        "os": iinfo.os,
8858
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
8859
        "nics": nic_data,
8860
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
8861
        "disk_template": iinfo.disk_template,
8862
        "hypervisor": iinfo.hypervisor,
8863
        }
8864
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
8865
                                                 pir["disks"])
8866
      instance_data[iinfo.name] = pir
8867

    
8868
    data["instances"] = instance_data
8869

    
8870
    self.in_data = data
8871

    
8872
  def _AddNewInstance(self):
8873
    """Add new instance data to allocator structure.
8874

8875
    This in combination with _AllocatorGetClusterData will create the
8876
    correct structure needed as input for the allocator.
8877

8878
    The checks for the completeness of the opcode must have already been
8879
    done.
8880

8881
    """
8882
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
8883

    
8884
    if self.disk_template in constants.DTS_NET_MIRROR:
8885
      self.required_nodes = 2
8886
    else:
8887
      self.required_nodes = 1
8888
    request = {
8889
      "name": self.name,
8890
      "disk_template": self.disk_template,
8891
      "tags": self.tags,
8892
      "os": self.os,
8893
      "vcpus": self.vcpus,
8894
      "memory": self.mem_size,
8895
      "disks": self.disks,
8896
      "disk_space_total": disk_space,
8897
      "nics": self.nics,
8898
      "required_nodes": self.required_nodes,
8899
      }
8900
    return request
8901

    
8902
  def _AddRelocateInstance(self):
8903
    """Add relocate instance data to allocator structure.
8904

8905
    This in combination with _IAllocatorGetClusterData will create the
8906
    correct structure needed as input for the allocator.
8907

8908
    The checks for the completeness of the opcode must have already been
8909
    done.
8910

8911
    """
8912
    instance = self.cfg.GetInstanceInfo(self.name)
8913
    if instance is None:
8914
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
8915
                                   " IAllocator" % self.name)
8916

    
8917
    if instance.disk_template not in constants.DTS_NET_MIRROR:
8918
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
8919
                                 errors.ECODE_INVAL)
8920

    
8921
    if len(instance.secondary_nodes) != 1:
8922
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
8923
                                 errors.ECODE_STATE)
8924

    
8925
    self.required_nodes = 1
8926
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
8927
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
8928

    
8929
    request = {
8930
      "name": self.name,
8931
      "disk_space_total": disk_space,
8932
      "required_nodes": self.required_nodes,
8933
      "relocate_from": self.relocate_from,
8934
      }
8935
    return request
8936

    
8937
  def _AddEvacuateNodes(self):
8938
    """Add evacuate nodes data to allocator structure.
8939

8940
    """
8941
    request = {
8942
      "evac_nodes": self.evac_nodes
8943
      }
8944
    return request
8945

    
8946
  def _BuildInputData(self, fn):
8947
    """Build input data structures.
8948

8949
    """
8950
    self._ComputeClusterData()
8951

    
8952
    request = fn()
8953
    request["type"] = self.mode
8954
    self.in_data["request"] = request
8955

    
8956
    self.in_text = serializer.Dump(self.in_data)
8957

    
8958
  def Run(self, name, validate=True, call_fn=None):
8959
    """Run an instance allocator and return the results.
8960

8961
    """
8962
    if call_fn is None:
8963
      call_fn = self.rpc.call_iallocator_runner
8964

    
8965
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
8966
    result.Raise("Failure while running the iallocator script")
8967

    
8968
    self.out_text = result.payload
8969
    if validate:
8970
      self._ValidateResult()
8971

    
8972
  def _ValidateResult(self):
8973
    """Process the allocator results.
8974

8975
    This will process and if successful save the result in
8976
    self.out_data and the other parameters.
8977

8978
    """
8979
    try:
8980
      rdict = serializer.Load(self.out_text)
8981
    except Exception, err:
8982
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
8983

    
8984
    if not isinstance(rdict, dict):
8985
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
8986

    
8987
    # TODO: remove backwards compatiblity in later versions
8988
    if "nodes" in rdict and "result" not in rdict:
8989
      rdict["result"] = rdict["nodes"]
8990
      del rdict["nodes"]
8991

    
8992
    for key in "success", "info", "result":
8993
      if key not in rdict:
8994
        raise errors.OpExecError("Can't parse iallocator results:"
8995
                                 " missing key '%s'" % key)
8996
      setattr(self, key, rdict[key])
8997

    
8998
    if not isinstance(rdict["result"], list):
8999
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
9000
                               " is not a list")
9001
    self.out_data = rdict
9002

    
9003

    
9004
class LUTestAllocator(NoHooksLU):
9005
  """Run allocator tests.
9006

9007
  This LU runs the allocator tests
9008

9009
  """
9010
  _OP_REQP = ["direction", "mode", "name"]
9011

    
9012
  def CheckPrereq(self):
9013
    """Check prerequisites.
9014

9015
    This checks the opcode parameters depending on the director and mode test.
9016

9017
    """
9018
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9019
      for attr in ["name", "mem_size", "disks", "disk_template",
9020
                   "os", "tags", "nics", "vcpus"]:
9021
        if not hasattr(self.op, attr):
9022
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
9023
                                     attr, errors.ECODE_INVAL)
9024
      iname = self.cfg.ExpandInstanceName(self.op.name)
9025
      if iname is not None:
9026
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
9027
                                   iname, errors.ECODE_EXISTS)
9028
      if not isinstance(self.op.nics, list):
9029
        raise errors.OpPrereqError("Invalid parameter 'nics'",
9030
                                   errors.ECODE_INVAL)
9031
      for row in self.op.nics:
9032
        if (not isinstance(row, dict) or
9033
            "mac" not in row or
9034
            "ip" not in row or
9035
            "bridge" not in row):
9036
          raise errors.OpPrereqError("Invalid contents of the 'nics'"
9037
                                     " parameter", errors.ECODE_INVAL)
9038
      if not isinstance(self.op.disks, list):
9039
        raise errors.OpPrereqError("Invalid parameter 'disks'",
9040
                                   errors.ECODE_INVAL)
9041
      for row in self.op.disks:
9042
        if (not isinstance(row, dict) or
9043
            "size" not in row or
9044
            not isinstance(row["size"], int) or
9045
            "mode" not in row or
9046
            row["mode"] not in ['r', 'w']):
9047
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
9048
                                     " parameter", errors.ECODE_INVAL)
9049
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
9050
        self.op.hypervisor = self.cfg.GetHypervisorType()
9051
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9052
      if not hasattr(self.op, "name"):
9053
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input",
9054
                                   errors.ECODE_INVAL)
9055
      fname = _ExpandInstanceName(self.cfg, self.op.name)
9056
      self.op.name = fname
9057
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
9058
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9059
      if not hasattr(self.op, "evac_nodes"):
9060
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
9061
                                   " opcode input", errors.ECODE_INVAL)
9062
    else:
9063
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
9064
                                 self.op.mode, errors.ECODE_INVAL)
9065

    
9066
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
9067
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
9068
        raise errors.OpPrereqError("Missing allocator name",
9069
                                   errors.ECODE_INVAL)
9070
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
9071
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
9072
                                 self.op.direction, errors.ECODE_INVAL)
9073

    
9074
  def Exec(self, feedback_fn):
9075
    """Run the allocator test.
9076

9077
    """
9078
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9079
      ial = IAllocator(self.cfg, self.rpc,
9080
                       mode=self.op.mode,
9081
                       name=self.op.name,
9082
                       mem_size=self.op.mem_size,
9083
                       disks=self.op.disks,
9084
                       disk_template=self.op.disk_template,
9085
                       os=self.op.os,
9086
                       tags=self.op.tags,
9087
                       nics=self.op.nics,
9088
                       vcpus=self.op.vcpus,
9089
                       hypervisor=self.op.hypervisor,
9090
                       )
9091
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9092
      ial = IAllocator(self.cfg, self.rpc,
9093
                       mode=self.op.mode,
9094
                       name=self.op.name,
9095
                       relocate_from=list(self.relocate_from),
9096
                       )
9097
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9098
      ial = IAllocator(self.cfg, self.rpc,
9099
                       mode=self.op.mode,
9100
                       evac_nodes=self.op.evac_nodes)
9101
    else:
9102
      raise errors.ProgrammerError("Uncatched mode %s in"
9103
                                   " LUTestAllocator.Exec", self.op.mode)
9104

    
9105
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
9106
      result = ial.in_text
9107
    else:
9108
      ial.Run(self.op.allocator, validate=False)
9109
      result = ial.out_text
9110
    return result