Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ eb630f50

History | View | Annotate | Download (347.6 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
from ganeti import uidpool
48
from ganeti import compat
49
from ganeti import masterd
50

    
51
import ganeti.masterd.instance # pylint: disable-msg=W0611
52

    
53

    
54
class LogicalUnit(object):
55
  """Logical Unit base class.
56

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

66
  Note that all commands require root permissions.
67

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

71
  """
72
  HPATH = None
73
  HTYPE = None
74
  _OP_REQP = []
75
  REQ_BGL = True
76

    
77
  def __init__(self, processor, op, context, rpc):
78
    """Constructor for LogicalUnit.
79

80
    This needs to be overridden in derived classes in order to check op
81
    validity.
82

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

    
109
    # Tasklets
110
    self.tasklets = None
111

    
112
    for attr_name in self._OP_REQP:
113
      attr_val = getattr(op, attr_name, None)
114
      if attr_val is None:
115
        raise errors.OpPrereqError("Required parameter '%s' missing" %
116
                                   attr_name, errors.ECODE_INVAL)
117

    
118
    self.CheckArguments()
119

    
120
  def __GetSSH(self):
121
    """Returns the SshRunner object
122

123
    """
124
    if not self.__ssh:
125
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
126
    return self.__ssh
127

    
128
  ssh = property(fget=__GetSSH)
129

    
130
  def CheckArguments(self):
131
    """Check syntactic validity for the opcode arguments.
132

133
    This method is for doing a simple syntactic check and ensure
134
    validity of opcode parameters, without any cluster-related
135
    checks. While the same can be accomplished in ExpandNames and/or
136
    CheckPrereq, doing these separate is better because:
137

138
      - ExpandNames is left as as purely a lock-related function
139
      - CheckPrereq is run after we have acquired locks (and possible
140
        waited for them)
141

142
    The function is allowed to change the self.op attribute so that
143
    later methods can no longer worry about missing parameters.
144

145
    """
146
    pass
147

    
148
  def ExpandNames(self):
149
    """Expand names for this LU.
150

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

156
    LUs which implement this method must also populate the self.needed_locks
157
    member, as a dict with lock levels as keys, and a list of needed lock names
158
    as values. Rules:
159

160
      - use an empty dict if you don't need any lock
161
      - if you don't need any lock at a particular level omit that level
162
      - don't put anything for the BGL level
163
      - if you want all locks at a level use locking.ALL_SET as a value
164

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

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

173
    Examples::
174

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

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

    
196
  def DeclareLocks(self, level):
197
    """Declare LU locking needs for a level
198

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

206
    This function is only called if you have something already set in
207
    self.needed_locks for the level.
208

209
    @param level: Locking level which is going to be locked
210
    @type level: member of ganeti.locking.LEVELS
211

212
    """
213

    
214
  def CheckPrereq(self):
215
    """Check prerequisites for this LU.
216

217
    This method should check that the prerequisites for the execution
218
    of this LU are fulfilled. It can do internode communication, but
219
    it should be idempotent - no cluster or system changes are
220
    allowed.
221

222
    The method should raise errors.OpPrereqError in case something is
223
    not fulfilled. Its return value is ignored.
224

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

228
    """
229
    if self.tasklets is not None:
230
      for (idx, tl) in enumerate(self.tasklets):
231
        logging.debug("Checking prerequisites for tasklet %s/%s",
232
                      idx + 1, len(self.tasklets))
233
        tl.CheckPrereq()
234
    else:
235
      raise NotImplementedError
236

    
237
  def Exec(self, feedback_fn):
238
    """Execute the LU.
239

240
    This method should implement the actual work. It should raise
241
    errors.OpExecError for failures that are somewhat dealt with in
242
    code, or expected.
243

244
    """
245
    if self.tasklets is not None:
246
      for (idx, tl) in enumerate(self.tasklets):
247
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
248
        tl.Exec(feedback_fn)
249
    else:
250
      raise NotImplementedError
251

    
252
  def BuildHooksEnv(self):
253
    """Build hooks environment for this LU.
254

255
    This method should return a three-node tuple consisting of: a dict
256
    containing the environment that will be used for running the
257
    specific hook for this LU, a list of node names on which the hook
258
    should run before the execution, and a list of node names on which
259
    the hook should run after the execution.
260

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

266
    No nodes should be returned as an empty list (and not None).
267

268
    Note that if the HPATH for a LU class is None, this function will
269
    not be called.
270

271
    """
272
    raise NotImplementedError
273

    
274
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
275
    """Notify the LU about the results of its hooks.
276

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

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

292
    """
293
    # API must be kept, thus we ignore the unused argument and could
294
    # be a function warnings
295
    # pylint: disable-msg=W0613,R0201
296
    return lu_result
297

    
298
  def _ExpandAndLockInstance(self):
299
    """Helper function to expand and lock an instance.
300

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

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

    
317
  def _LockInstancesNodes(self, primary_only=False):
318
    """Helper function to declare instances' nodes for locking.
319

320
    This function should be called after locking one or more instances to lock
321
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
322
    with all primary or secondary nodes for instances already locked and
323
    present in self.needed_locks[locking.LEVEL_INSTANCE].
324

325
    It should be called from DeclareLocks, and for safety only works if
326
    self.recalculate_locks[locking.LEVEL_NODE] is set.
327

328
    In the future it may grow parameters to just lock some instance's nodes, or
329
    to just lock primaries or secondary nodes, if needed.
330

331
    If should be called in DeclareLocks in a way similar to::
332

333
      if level == locking.LEVEL_NODE:
334
        self._LockInstancesNodes()
335

336
    @type primary_only: boolean
337
    @param primary_only: only lock primary nodes of locked instances
338

339
    """
340
    assert locking.LEVEL_NODE in self.recalculate_locks, \
341
      "_LockInstancesNodes helper function called with no nodes to recalculate"
342

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

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

    
355
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
356
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
357
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
358
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
359

    
360
    del self.recalculate_locks[locking.LEVEL_NODE]
361

    
362

    
363
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
364
  """Simple LU which runs no hooks.
365

366
  This LU is intended as a parent for other LogicalUnits which will
367
  run no hooks, in order to reduce duplicate code.
368

369
  """
370
  HPATH = None
371
  HTYPE = None
372

    
373
  def BuildHooksEnv(self):
374
    """Empty BuildHooksEnv for NoHooksLu.
375

376
    This just raises an error.
377

378
    """
379
    assert False, "BuildHooksEnv called for NoHooksLUs"
380

    
381

    
382
class Tasklet:
383
  """Tasklet base class.
384

385
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
386
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
387
  tasklets know nothing about locks.
388

389
  Subclasses must follow these rules:
390
    - Implement CheckPrereq
391
    - Implement Exec
392

393
  """
394
  def __init__(self, lu):
395
    self.lu = lu
396

    
397
    # Shortcuts
398
    self.cfg = lu.cfg
399
    self.rpc = lu.rpc
400

    
401
  def CheckPrereq(self):
402
    """Check prerequisites for this tasklets.
403

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

408
    The method should raise errors.OpPrereqError in case something is not
409
    fulfilled. Its return value is ignored.
410

411
    This method should also update all parameters to their canonical form if it
412
    hasn't been done before.
413

414
    """
415
    raise NotImplementedError
416

    
417
  def Exec(self, feedback_fn):
418
    """Execute the tasklet.
419

420
    This method should implement the actual work. It should raise
421
    errors.OpExecError for failures that are somewhat dealt with in code, or
422
    expected.
423

424
    """
425
    raise NotImplementedError
426

    
427

    
428
def _GetWantedNodes(lu, nodes):
429
  """Returns list of checked and expanded node names.
430

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

439
  """
440
  if not isinstance(nodes, list):
441
    raise errors.OpPrereqError("Invalid argument type 'nodes'",
442
                               errors.ECODE_INVAL)
443

    
444
  if not nodes:
445
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
446
      " non-empty list of nodes whose name is to be expanded.")
447

    
448
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
449
  return utils.NiceSort(wanted)
450

    
451

    
452
def _GetWantedInstances(lu, instances):
453
  """Returns list of checked and expanded instance names.
454

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

464
  """
465
  if not isinstance(instances, list):
466
    raise errors.OpPrereqError("Invalid argument type 'instances'",
467
                               errors.ECODE_INVAL)
468

    
469
  if instances:
470
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
471
  else:
472
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
473
  return wanted
474

    
475

    
476
def _CheckOutputFields(static, dynamic, selected):
477
  """Checks whether all selected fields are valid.
478

479
  @type static: L{utils.FieldSet}
480
  @param static: static fields set
481
  @type dynamic: L{utils.FieldSet}
482
  @param dynamic: dynamic fields set
483

484
  """
485
  f = utils.FieldSet()
486
  f.Extend(static)
487
  f.Extend(dynamic)
488

    
489
  delta = f.NonMatching(selected)
490
  if delta:
491
    raise errors.OpPrereqError("Unknown output fields selected: %s"
492
                               % ",".join(delta), errors.ECODE_INVAL)
493

    
494

    
495
def _CheckBooleanOpField(op, name):
496
  """Validates boolean opcode parameters.
497

498
  This will ensure that an opcode parameter is either a boolean value,
499
  or None (but that it always exists).
500

501
  """
502
  val = getattr(op, name, None)
503
  if not (val is None or isinstance(val, bool)):
504
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
505
                               (name, str(val)), errors.ECODE_INVAL)
506
  setattr(op, name, val)
507

    
508

    
509
def _CheckGlobalHvParams(params):
510
  """Validates that given hypervisor params are not global ones.
511

512
  This will ensure that instances don't get customised versions of
513
  global params.
514

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

    
523

    
524
def _CheckNodeOnline(lu, node):
525
  """Ensure that a given node is online.
526

527
  @param lu: the LU on behalf of which we make the check
528
  @param node: the node to check
529
  @raise errors.OpPrereqError: if the node is offline
530

531
  """
532
  if lu.cfg.GetNodeInfo(node).offline:
533
    raise errors.OpPrereqError("Can't use offline node %s" % node,
534
                               errors.ECODE_INVAL)
535

    
536

    
537
def _CheckNodeNotDrained(lu, node):
538
  """Ensure that a given node is not drained.
539

540
  @param lu: the LU on behalf of which we make the check
541
  @param node: the node to check
542
  @raise errors.OpPrereqError: if the node is drained
543

544
  """
545
  if lu.cfg.GetNodeInfo(node).drained:
546
    raise errors.OpPrereqError("Can't use drained node %s" % node,
547
                               errors.ECODE_INVAL)
548

    
549

    
550
def _CheckNodeHasOS(lu, node, os_name, force_variant):
551
  """Ensure that a node supports a given OS.
552

553
  @param lu: the LU on behalf of which we make the check
554
  @param node: the node to check
555
  @param os_name: the OS to query about
556
  @param force_variant: whether to ignore variant errors
557
  @raise errors.OpPrereqError: if the node is not supporting the OS
558

559
  """
560
  result = lu.rpc.call_os_get(node, os_name)
561
  result.Raise("OS '%s' not in supported OS list for node %s" %
562
               (os_name, node),
563
               prereq=True, ecode=errors.ECODE_INVAL)
564
  if not force_variant:
565
    _CheckOSVariant(result.payload, os_name)
566

    
567

    
568
def _RequireFileStorage():
569
  """Checks that file storage is enabled.
570

571
  @raise errors.OpPrereqError: when file storage is disabled
572

573
  """
574
  if not constants.ENABLE_FILE_STORAGE:
575
    raise errors.OpPrereqError("File storage disabled at configure time",
576
                               errors.ECODE_INVAL)
577

    
578

    
579
def _CheckDiskTemplate(template):
580
  """Ensure a given disk template is valid.
581

582
  """
583
  if template not in constants.DISK_TEMPLATES:
584
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
585
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
586
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
587
  if template == constants.DT_FILE:
588
    _RequireFileStorage()
589

    
590

    
591
def _CheckStorageType(storage_type):
592
  """Ensure a given storage type is valid.
593

594
  """
595
  if storage_type not in constants.VALID_STORAGE_TYPES:
596
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
597
                               errors.ECODE_INVAL)
598
  if storage_type == constants.ST_FILE:
599
    _RequireFileStorage()
600

    
601

    
602
def _GetClusterDomainSecret():
603
  """Reads the cluster domain secret.
604

605
  """
606
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
607
                               strict=True)
608

    
609

    
610
def _CheckInstanceDown(lu, instance, reason):
611
  """Ensure that an instance is not running."""
612
  if instance.admin_up:
613
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
614
                               (instance.name, reason), errors.ECODE_STATE)
615

    
616
  pnode = instance.primary_node
617
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
618
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
619
              prereq=True, ecode=errors.ECODE_ENVIRON)
620

    
621
  if instance.name in ins_l.payload:
622
    raise errors.OpPrereqError("Instance %s is running, %s" %
623
                               (instance.name, reason), errors.ECODE_STATE)
624

    
625

    
626
def _ExpandItemName(fn, name, kind):
627
  """Expand an item name.
628

629
  @param fn: the function to use for expansion
630
  @param name: requested item name
631
  @param kind: text description ('Node' or 'Instance')
632
  @return: the resolved (full) name
633
  @raise errors.OpPrereqError: if the item is not found
634

635
  """
636
  full_name = fn(name)
637
  if full_name is None:
638
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
639
                               errors.ECODE_NOENT)
640
  return full_name
641

    
642

    
643
def _ExpandNodeName(cfg, name):
644
  """Wrapper over L{_ExpandItemName} for nodes."""
645
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
646

    
647

    
648
def _ExpandInstanceName(cfg, name):
649
  """Wrapper over L{_ExpandItemName} for instance."""
650
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
651

    
652

    
653
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
654
                          memory, vcpus, nics, disk_template, disks,
655
                          bep, hvp, hypervisor_name):
656
  """Builds instance related env variables for hooks
657

658
  This builds the hook environment from individual variables.
659

660
  @type name: string
661
  @param name: the name of the instance
662
  @type primary_node: string
663
  @param primary_node: the name of the instance's primary node
664
  @type secondary_nodes: list
665
  @param secondary_nodes: list of secondary nodes as strings
666
  @type os_type: string
667
  @param os_type: the name of the instance's OS
668
  @type status: boolean
669
  @param status: the should_run status of the instance
670
  @type memory: string
671
  @param memory: the memory size of the instance
672
  @type vcpus: string
673
  @param vcpus: the count of VCPUs the instance has
674
  @type nics: list
675
  @param nics: list of tuples (ip, mac, mode, link) representing
676
      the NICs the instance has
677
  @type disk_template: string
678
  @param disk_template: the disk template of the instance
679
  @type disks: list
680
  @param disks: the list of (size, mode) pairs
681
  @type bep: dict
682
  @param bep: the backend parameters for the instance
683
  @type hvp: dict
684
  @param hvp: the hypervisor parameters for the instance
685
  @type hypervisor_name: string
686
  @param hypervisor_name: the hypervisor for the instance
687
  @rtype: dict
688
  @return: the hook environment for this instance
689

690
  """
691
  if status:
692
    str_status = "up"
693
  else:
694
    str_status = "down"
695
  env = {
696
    "OP_TARGET": name,
697
    "INSTANCE_NAME": name,
698
    "INSTANCE_PRIMARY": primary_node,
699
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
700
    "INSTANCE_OS_TYPE": os_type,
701
    "INSTANCE_STATUS": str_status,
702
    "INSTANCE_MEMORY": memory,
703
    "INSTANCE_VCPUS": vcpus,
704
    "INSTANCE_DISK_TEMPLATE": disk_template,
705
    "INSTANCE_HYPERVISOR": hypervisor_name,
706
  }
707

    
708
  if nics:
709
    nic_count = len(nics)
710
    for idx, (ip, mac, mode, link) in enumerate(nics):
711
      if ip is None:
712
        ip = ""
713
      env["INSTANCE_NIC%d_IP" % idx] = ip
714
      env["INSTANCE_NIC%d_MAC" % idx] = mac
715
      env["INSTANCE_NIC%d_MODE" % idx] = mode
716
      env["INSTANCE_NIC%d_LINK" % idx] = link
717
      if mode == constants.NIC_MODE_BRIDGED:
718
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
719
  else:
720
    nic_count = 0
721

    
722
  env["INSTANCE_NIC_COUNT"] = nic_count
723

    
724
  if disks:
725
    disk_count = len(disks)
726
    for idx, (size, mode) in enumerate(disks):
727
      env["INSTANCE_DISK%d_SIZE" % idx] = size
728
      env["INSTANCE_DISK%d_MODE" % idx] = mode
729
  else:
730
    disk_count = 0
731

    
732
  env["INSTANCE_DISK_COUNT"] = disk_count
733

    
734
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
735
    for key, value in source.items():
736
      env["INSTANCE_%s_%s" % (kind, key)] = value
737

    
738
  return env
739

    
740

    
741
def _NICListToTuple(lu, nics):
742
  """Build a list of nic information tuples.
743

744
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
745
  value in LUQueryInstanceData.
746

747
  @type lu:  L{LogicalUnit}
748
  @param lu: the logical unit on whose behalf we execute
749
  @type nics: list of L{objects.NIC}
750
  @param nics: list of nics to convert to hooks tuples
751

752
  """
753
  hooks_nics = []
754
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
755
  for nic in nics:
756
    ip = nic.ip
757
    mac = nic.mac
758
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
759
    mode = filled_params[constants.NIC_MODE]
760
    link = filled_params[constants.NIC_LINK]
761
    hooks_nics.append((ip, mac, mode, link))
762
  return hooks_nics
763

    
764

    
765
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
766
  """Builds instance related env variables for hooks from an object.
767

768
  @type lu: L{LogicalUnit}
769
  @param lu: the logical unit on whose behalf we execute
770
  @type instance: L{objects.Instance}
771
  @param instance: the instance for which we should build the
772
      environment
773
  @type override: dict
774
  @param override: dictionary with key/values that will override
775
      our values
776
  @rtype: dict
777
  @return: the hook environment dictionary
778

779
  """
780
  cluster = lu.cfg.GetClusterInfo()
781
  bep = cluster.FillBE(instance)
782
  hvp = cluster.FillHV(instance)
783
  args = {
784
    'name': instance.name,
785
    'primary_node': instance.primary_node,
786
    'secondary_nodes': instance.secondary_nodes,
787
    'os_type': instance.os,
788
    'status': instance.admin_up,
789
    'memory': bep[constants.BE_MEMORY],
790
    'vcpus': bep[constants.BE_VCPUS],
791
    'nics': _NICListToTuple(lu, instance.nics),
792
    'disk_template': instance.disk_template,
793
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
794
    'bep': bep,
795
    'hvp': hvp,
796
    'hypervisor_name': instance.hypervisor,
797
  }
798
  if override:
799
    args.update(override)
800
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
801

    
802

    
803
def _AdjustCandidatePool(lu, exceptions):
804
  """Adjust the candidate pool after node operations.
805

806
  """
807
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
808
  if mod_list:
809
    lu.LogInfo("Promoted nodes to master candidate role: %s",
810
               utils.CommaJoin(node.name for node in mod_list))
811
    for name in mod_list:
812
      lu.context.ReaddNode(name)
813
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
814
  if mc_now > mc_max:
815
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
816
               (mc_now, mc_max))
817

    
818

    
819
def _DecideSelfPromotion(lu, exceptions=None):
820
  """Decide whether I should promote myself as a master candidate.
821

822
  """
823
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
824
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
825
  # the new node will increase mc_max with one, so:
826
  mc_should = min(mc_should + 1, cp_size)
827
  return mc_now < mc_should
828

    
829

    
830
def _CheckNicsBridgesExist(lu, target_nics, target_node,
831
                               profile=constants.PP_DEFAULT):
832
  """Check that the brigdes needed by a list of nics exist.
833

834
  """
835
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
836
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
837
                for nic in target_nics]
838
  brlist = [params[constants.NIC_LINK] for params in paramslist
839
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
840
  if brlist:
841
    result = lu.rpc.call_bridges_exist(target_node, brlist)
842
    result.Raise("Error checking bridges on destination node '%s'" %
843
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
844

    
845

    
846
def _CheckInstanceBridgesExist(lu, instance, node=None):
847
  """Check that the brigdes needed by an instance exist.
848

849
  """
850
  if node is None:
851
    node = instance.primary_node
852
  _CheckNicsBridgesExist(lu, instance.nics, node)
853

    
854

    
855
def _CheckOSVariant(os_obj, name):
856
  """Check whether an OS name conforms to the os variants specification.
857

858
  @type os_obj: L{objects.OS}
859
  @param os_obj: OS object to check
860
  @type name: string
861
  @param name: OS name passed by the user, to check for validity
862

863
  """
864
  if not os_obj.supported_variants:
865
    return
866
  try:
867
    variant = name.split("+", 1)[1]
868
  except IndexError:
869
    raise errors.OpPrereqError("OS name must include a variant",
870
                               errors.ECODE_INVAL)
871

    
872
  if variant not in os_obj.supported_variants:
873
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
874

    
875

    
876
def _GetNodeInstancesInner(cfg, fn):
877
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
878

    
879

    
880
def _GetNodeInstances(cfg, node_name):
881
  """Returns a list of all primary and secondary instances on a node.
882

883
  """
884

    
885
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
886

    
887

    
888
def _GetNodePrimaryInstances(cfg, node_name):
889
  """Returns primary instances on a node.
890

891
  """
892
  return _GetNodeInstancesInner(cfg,
893
                                lambda inst: node_name == inst.primary_node)
894

    
895

    
896
def _GetNodeSecondaryInstances(cfg, node_name):
897
  """Returns secondary instances on a node.
898

899
  """
900
  return _GetNodeInstancesInner(cfg,
901
                                lambda inst: node_name in inst.secondary_nodes)
902

    
903

    
904
def _GetStorageTypeArgs(cfg, storage_type):
905
  """Returns the arguments for a storage type.
906

907
  """
908
  # Special case for file storage
909
  if storage_type == constants.ST_FILE:
910
    # storage.FileStorage wants a list of storage directories
911
    return [[cfg.GetFileStorageDir()]]
912

    
913
  return []
914

    
915

    
916
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
917
  faulty = []
918

    
919
  for dev in instance.disks:
920
    cfg.SetDiskID(dev, node_name)
921

    
922
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
923
  result.Raise("Failed to get disk status from node %s" % node_name,
924
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
925

    
926
  for idx, bdev_status in enumerate(result.payload):
927
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
928
      faulty.append(idx)
929

    
930
  return faulty
931

    
932

    
933
class LUPostInitCluster(LogicalUnit):
934
  """Logical unit for running hooks after cluster initialization.
935

936
  """
937
  HPATH = "cluster-init"
938
  HTYPE = constants.HTYPE_CLUSTER
939
  _OP_REQP = []
940

    
941
  def BuildHooksEnv(self):
942
    """Build hooks env.
943

944
    """
945
    env = {"OP_TARGET": self.cfg.GetClusterName()}
946
    mn = self.cfg.GetMasterNode()
947
    return env, [], [mn]
948

    
949
  def CheckPrereq(self):
950
    """No prerequisites to check.
951

952
    """
953
    return True
954

    
955
  def Exec(self, feedback_fn):
956
    """Nothing to do.
957

958
    """
959
    return True
960

    
961

    
962
class LUDestroyCluster(LogicalUnit):
963
  """Logical unit for destroying the cluster.
964

965
  """
966
  HPATH = "cluster-destroy"
967
  HTYPE = constants.HTYPE_CLUSTER
968
  _OP_REQP = []
969

    
970
  def BuildHooksEnv(self):
971
    """Build hooks env.
972

973
    """
974
    env = {"OP_TARGET": self.cfg.GetClusterName()}
975
    return env, [], []
976

    
977
  def CheckPrereq(self):
978
    """Check prerequisites.
979

980
    This checks whether the cluster is empty.
981

982
    Any errors are signaled by raising errors.OpPrereqError.
983

984
    """
985
    master = self.cfg.GetMasterNode()
986

    
987
    nodelist = self.cfg.GetNodeList()
988
    if len(nodelist) != 1 or nodelist[0] != master:
989
      raise errors.OpPrereqError("There are still %d node(s) in"
990
                                 " this cluster." % (len(nodelist) - 1),
991
                                 errors.ECODE_INVAL)
992
    instancelist = self.cfg.GetInstanceList()
993
    if instancelist:
994
      raise errors.OpPrereqError("There are still %d instance(s) in"
995
                                 " this cluster." % len(instancelist),
996
                                 errors.ECODE_INVAL)
997

    
998
  def Exec(self, feedback_fn):
999
    """Destroys the cluster.
1000

1001
    """
1002
    master = self.cfg.GetMasterNode()
1003
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
1004

    
1005
    # Run post hooks on master node before it's removed
1006
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1007
    try:
1008
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1009
    except:
1010
      # pylint: disable-msg=W0702
1011
      self.LogWarning("Errors occurred running hooks on %s" % master)
1012

    
1013
    result = self.rpc.call_node_stop_master(master, False)
1014
    result.Raise("Could not disable the master role")
1015

    
1016
    if modify_ssh_setup:
1017
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1018
      utils.CreateBackup(priv_key)
1019
      utils.CreateBackup(pub_key)
1020

    
1021
    return master
1022

    
1023

    
1024
def _VerifyCertificate(filename):
1025
  """Verifies a certificate for LUVerifyCluster.
1026

1027
  @type filename: string
1028
  @param filename: Path to PEM file
1029

1030
  """
1031
  try:
1032
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1033
                                           utils.ReadFile(filename))
1034
  except Exception, err: # pylint: disable-msg=W0703
1035
    return (LUVerifyCluster.ETYPE_ERROR,
1036
            "Failed to load X509 certificate %s: %s" % (filename, err))
1037

    
1038
  (errcode, msg) = \
1039
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1040
                                constants.SSL_CERT_EXPIRATION_ERROR)
1041

    
1042
  if msg:
1043
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1044
  else:
1045
    fnamemsg = None
1046

    
1047
  if errcode is None:
1048
    return (None, fnamemsg)
1049
  elif errcode == utils.CERT_WARNING:
1050
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1051
  elif errcode == utils.CERT_ERROR:
1052
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1053

    
1054
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1055

    
1056

    
1057
class LUVerifyCluster(LogicalUnit):
1058
  """Verifies the cluster status.
1059

1060
  """
1061
  HPATH = "cluster-verify"
1062
  HTYPE = constants.HTYPE_CLUSTER
1063
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
1064
  REQ_BGL = False
1065

    
1066
  TCLUSTER = "cluster"
1067
  TNODE = "node"
1068
  TINSTANCE = "instance"
1069

    
1070
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1071
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1072
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1073
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1074
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1075
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1076
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1077
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1078
  ENODEDRBD = (TNODE, "ENODEDRBD")
1079
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1080
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1081
  ENODEHV = (TNODE, "ENODEHV")
1082
  ENODELVM = (TNODE, "ENODELVM")
1083
  ENODEN1 = (TNODE, "ENODEN1")
1084
  ENODENET = (TNODE, "ENODENET")
1085
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1086
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1087
  ENODERPC = (TNODE, "ENODERPC")
1088
  ENODESSH = (TNODE, "ENODESSH")
1089
  ENODEVERSION = (TNODE, "ENODEVERSION")
1090
  ENODESETUP = (TNODE, "ENODESETUP")
1091
  ENODETIME = (TNODE, "ENODETIME")
1092

    
1093
  ETYPE_FIELD = "code"
1094
  ETYPE_ERROR = "ERROR"
1095
  ETYPE_WARNING = "WARNING"
1096

    
1097
  class NodeImage(object):
1098
    """A class representing the logical and physical status of a node.
1099

1100
    @ivar volumes: a structure as returned from
1101
        L{ganeti.backend.GetVolumeList} (runtime)
1102
    @ivar instances: a list of running instances (runtime)
1103
    @ivar pinst: list of configured primary instances (config)
1104
    @ivar sinst: list of configured secondary instances (config)
1105
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1106
        of this node (config)
1107
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1108
    @ivar dfree: free disk, as reported by the node (runtime)
1109
    @ivar offline: the offline status (config)
1110
    @type rpc_fail: boolean
1111
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1112
        not whether the individual keys were correct) (runtime)
1113
    @type lvm_fail: boolean
1114
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1115
    @type hyp_fail: boolean
1116
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1117
    @type ghost: boolean
1118
    @ivar ghost: whether this is a known node or not (config)
1119

1120
    """
1121
    def __init__(self, offline=False):
1122
      self.volumes = {}
1123
      self.instances = []
1124
      self.pinst = []
1125
      self.sinst = []
1126
      self.sbp = {}
1127
      self.mfree = 0
1128
      self.dfree = 0
1129
      self.offline = offline
1130
      self.rpc_fail = False
1131
      self.lvm_fail = False
1132
      self.hyp_fail = False
1133
      self.ghost = False
1134

    
1135
  def ExpandNames(self):
1136
    self.needed_locks = {
1137
      locking.LEVEL_NODE: locking.ALL_SET,
1138
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1139
    }
1140
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1141

    
1142
  def _Error(self, ecode, item, msg, *args, **kwargs):
1143
    """Format an error message.
1144

1145
    Based on the opcode's error_codes parameter, either format a
1146
    parseable error code, or a simpler error string.
1147

1148
    This must be called only from Exec and functions called from Exec.
1149

1150
    """
1151
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1152
    itype, etxt = ecode
1153
    # first complete the msg
1154
    if args:
1155
      msg = msg % args
1156
    # then format the whole message
1157
    if self.op.error_codes:
1158
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1159
    else:
1160
      if item:
1161
        item = " " + item
1162
      else:
1163
        item = ""
1164
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1165
    # and finally report it via the feedback_fn
1166
    self._feedback_fn("  - %s" % msg)
1167

    
1168
  def _ErrorIf(self, cond, *args, **kwargs):
1169
    """Log an error message if the passed condition is True.
1170

1171
    """
1172
    cond = bool(cond) or self.op.debug_simulate_errors
1173
    if cond:
1174
      self._Error(*args, **kwargs)
1175
    # do not mark the operation as failed for WARN cases only
1176
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1177
      self.bad = self.bad or cond
1178

    
1179
  def _VerifyNode(self, ninfo, nresult):
1180
    """Run multiple tests against a node.
1181

1182
    Test list:
1183

1184
      - compares ganeti version
1185
      - checks vg existence and size > 20G
1186
      - checks config file checksum
1187
      - checks ssh to other nodes
1188

1189
    @type ninfo: L{objects.Node}
1190
    @param ninfo: the node to check
1191
    @param nresult: the results from the node
1192
    @rtype: boolean
1193
    @return: whether overall this call was successful (and we can expect
1194
         reasonable values in the respose)
1195

1196
    """
1197
    node = ninfo.name
1198
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1199

    
1200
    # main result, nresult should be a non-empty dict
1201
    test = not nresult or not isinstance(nresult, dict)
1202
    _ErrorIf(test, self.ENODERPC, node,
1203
                  "unable to verify node: no data returned")
1204
    if test:
1205
      return False
1206

    
1207
    # compares ganeti version
1208
    local_version = constants.PROTOCOL_VERSION
1209
    remote_version = nresult.get("version", None)
1210
    test = not (remote_version and
1211
                isinstance(remote_version, (list, tuple)) and
1212
                len(remote_version) == 2)
1213
    _ErrorIf(test, self.ENODERPC, node,
1214
             "connection to node returned invalid data")
1215
    if test:
1216
      return False
1217

    
1218
    test = local_version != remote_version[0]
1219
    _ErrorIf(test, self.ENODEVERSION, node,
1220
             "incompatible protocol versions: master %s,"
1221
             " node %s", local_version, remote_version[0])
1222
    if test:
1223
      return False
1224

    
1225
    # node seems compatible, we can actually try to look into its results
1226

    
1227
    # full package version
1228
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1229
                  self.ENODEVERSION, node,
1230
                  "software version mismatch: master %s, node %s",
1231
                  constants.RELEASE_VERSION, remote_version[1],
1232
                  code=self.ETYPE_WARNING)
1233

    
1234
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1235
    if isinstance(hyp_result, dict):
1236
      for hv_name, hv_result in hyp_result.iteritems():
1237
        test = hv_result is not None
1238
        _ErrorIf(test, self.ENODEHV, node,
1239
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1240

    
1241

    
1242
    test = nresult.get(constants.NV_NODESETUP,
1243
                           ["Missing NODESETUP results"])
1244
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1245
             "; ".join(test))
1246

    
1247
    return True
1248

    
1249
  def _VerifyNodeTime(self, ninfo, nresult,
1250
                      nvinfo_starttime, nvinfo_endtime):
1251
    """Check the node time.
1252

1253
    @type ninfo: L{objects.Node}
1254
    @param ninfo: the node to check
1255
    @param nresult: the remote results for the node
1256
    @param nvinfo_starttime: the start time of the RPC call
1257
    @param nvinfo_endtime: the end time of the RPC call
1258

1259
    """
1260
    node = ninfo.name
1261
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1262

    
1263
    ntime = nresult.get(constants.NV_TIME, None)
1264
    try:
1265
      ntime_merged = utils.MergeTime(ntime)
1266
    except (ValueError, TypeError):
1267
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1268
      return
1269

    
1270
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1271
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1272
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1273
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1274
    else:
1275
      ntime_diff = None
1276

    
1277
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1278
             "Node time diverges by at least %s from master node time",
1279
             ntime_diff)
1280

    
1281
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1282
    """Check the node time.
1283

1284
    @type ninfo: L{objects.Node}
1285
    @param ninfo: the node to check
1286
    @param nresult: the remote results for the node
1287
    @param vg_name: the configured VG name
1288

1289
    """
1290
    if vg_name is None:
1291
      return
1292

    
1293
    node = ninfo.name
1294
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1295

    
1296
    # checks vg existence and size > 20G
1297
    vglist = nresult.get(constants.NV_VGLIST, None)
1298
    test = not vglist
1299
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1300
    if not test:
1301
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1302
                                            constants.MIN_VG_SIZE)
1303
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1304

    
1305
    # check pv names
1306
    pvlist = nresult.get(constants.NV_PVLIST, None)
1307
    test = pvlist is None
1308
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1309
    if not test:
1310
      # check that ':' is not present in PV names, since it's a
1311
      # special character for lvcreate (denotes the range of PEs to
1312
      # use on the PV)
1313
      for _, pvname, owner_vg in pvlist:
1314
        test = ":" in pvname
1315
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1316
                 " '%s' of VG '%s'", pvname, owner_vg)
1317

    
1318
  def _VerifyNodeNetwork(self, ninfo, nresult):
1319
    """Check the node time.
1320

1321
    @type ninfo: L{objects.Node}
1322
    @param ninfo: the node to check
1323
    @param nresult: the remote results for the node
1324

1325
    """
1326
    node = ninfo.name
1327
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1328

    
1329
    test = constants.NV_NODELIST not in nresult
1330
    _ErrorIf(test, self.ENODESSH, node,
1331
             "node hasn't returned node ssh connectivity data")
1332
    if not test:
1333
      if nresult[constants.NV_NODELIST]:
1334
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1335
          _ErrorIf(True, self.ENODESSH, node,
1336
                   "ssh communication with node '%s': %s", a_node, a_msg)
1337

    
1338
    test = constants.NV_NODENETTEST not in nresult
1339
    _ErrorIf(test, self.ENODENET, node,
1340
             "node hasn't returned node tcp connectivity data")
1341
    if not test:
1342
      if nresult[constants.NV_NODENETTEST]:
1343
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1344
        for anode in nlist:
1345
          _ErrorIf(True, self.ENODENET, node,
1346
                   "tcp communication with node '%s': %s",
1347
                   anode, nresult[constants.NV_NODENETTEST][anode])
1348

    
1349
    test = constants.NV_MASTERIP not in nresult
1350
    _ErrorIf(test, self.ENODENET, node,
1351
             "node hasn't returned node master IP reachability data")
1352
    if not test:
1353
      if not nresult[constants.NV_MASTERIP]:
1354
        if node == self.master_node:
1355
          msg = "the master node cannot reach the master IP (not configured?)"
1356
        else:
1357
          msg = "cannot reach the master IP"
1358
        _ErrorIf(True, self.ENODENET, node, msg)
1359

    
1360

    
1361
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1362
    """Verify an instance.
1363

1364
    This function checks to see if the required block devices are
1365
    available on the instance's node.
1366

1367
    """
1368
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1369
    node_current = instanceconfig.primary_node
1370

    
1371
    node_vol_should = {}
1372
    instanceconfig.MapLVsByNode(node_vol_should)
1373

    
1374
    for node in node_vol_should:
1375
      n_img = node_image[node]
1376
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1377
        # ignore missing volumes on offline or broken nodes
1378
        continue
1379
      for volume in node_vol_should[node]:
1380
        test = volume not in n_img.volumes
1381
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1382
                 "volume %s missing on node %s", volume, node)
1383

    
1384
    if instanceconfig.admin_up:
1385
      pri_img = node_image[node_current]
1386
      test = instance not in pri_img.instances and not pri_img.offline
1387
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1388
               "instance not running on its primary node %s",
1389
               node_current)
1390

    
1391
    for node, n_img in node_image.items():
1392
      if (not node == node_current):
1393
        test = instance in n_img.instances
1394
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1395
                 "instance should not run on node %s", node)
1396

    
1397
  def _VerifyOrphanVolumes(self, node_vol_should, node_image):
1398
    """Verify if there are any unknown volumes in the cluster.
1399

1400
    The .os, .swap and backup volumes are ignored. All other volumes are
1401
    reported as unknown.
1402

1403
    """
1404
    for node, n_img in node_image.items():
1405
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1406
        # skip non-healthy nodes
1407
        continue
1408
      for volume in n_img.volumes:
1409
        test = (node not in node_vol_should or
1410
                volume not in node_vol_should[node])
1411
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1412
                      "volume %s is unknown", volume)
1413

    
1414
  def _VerifyOrphanInstances(self, instancelist, node_image):
1415
    """Verify the list of running instances.
1416

1417
    This checks what instances are running but unknown to the cluster.
1418

1419
    """
1420
    for node, n_img in node_image.items():
1421
      for o_inst in n_img.instances:
1422
        test = o_inst not in instancelist
1423
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1424
                      "instance %s on node %s should not exist", o_inst, node)
1425

    
1426
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1427
    """Verify N+1 Memory Resilience.
1428

1429
    Check that if one single node dies we can still start all the
1430
    instances it was primary for.
1431

1432
    """
1433
    for node, n_img in node_image.items():
1434
      # This code checks that every node which is now listed as
1435
      # secondary has enough memory to host all instances it is
1436
      # supposed to should a single other node in the cluster fail.
1437
      # FIXME: not ready for failover to an arbitrary node
1438
      # FIXME: does not support file-backed instances
1439
      # WARNING: we currently take into account down instances as well
1440
      # as up ones, considering that even if they're down someone
1441
      # might want to start them even in the event of a node failure.
1442
      for prinode, instances in n_img.sbp.items():
1443
        needed_mem = 0
1444
        for instance in instances:
1445
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1446
          if bep[constants.BE_AUTO_BALANCE]:
1447
            needed_mem += bep[constants.BE_MEMORY]
1448
        test = n_img.mfree < needed_mem
1449
        self._ErrorIf(test, self.ENODEN1, node,
1450
                      "not enough memory on to accommodate"
1451
                      " failovers should peer node %s fail", prinode)
1452

    
1453
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1454
                       master_files):
1455
    """Verifies and computes the node required file checksums.
1456

1457
    @type ninfo: L{objects.Node}
1458
    @param ninfo: the node to check
1459
    @param nresult: the remote results for the node
1460
    @param file_list: required list of files
1461
    @param local_cksum: dictionary of local files and their checksums
1462
    @param master_files: list of files that only masters should have
1463

1464
    """
1465
    node = ninfo.name
1466
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1467

    
1468
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1469
    test = not isinstance(remote_cksum, dict)
1470
    _ErrorIf(test, self.ENODEFILECHECK, node,
1471
             "node hasn't returned file checksum data")
1472
    if test:
1473
      return
1474

    
1475
    for file_name in file_list:
1476
      node_is_mc = ninfo.master_candidate
1477
      must_have = (file_name not in master_files) or node_is_mc
1478
      # missing
1479
      test1 = file_name not in remote_cksum
1480
      # invalid checksum
1481
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1482
      # existing and good
1483
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1484
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1485
               "file '%s' missing", file_name)
1486
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1487
               "file '%s' has wrong checksum", file_name)
1488
      # not candidate and this is not a must-have file
1489
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1490
               "file '%s' should not exist on non master"
1491
               " candidates (and the file is outdated)", file_name)
1492
      # all good, except non-master/non-must have combination
1493
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1494
               "file '%s' should not exist"
1495
               " on non master candidates", file_name)
1496

    
1497
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_map):
1498
    """Verifies and the node DRBD status.
1499

1500
    @type ninfo: L{objects.Node}
1501
    @param ninfo: the node to check
1502
    @param nresult: the remote results for the node
1503
    @param instanceinfo: the dict of instances
1504
    @param drbd_map: the DRBD map as returned by
1505
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1506

1507
    """
1508
    node = ninfo.name
1509
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1510

    
1511
    # compute the DRBD minors
1512
    node_drbd = {}
1513
    for minor, instance in drbd_map[node].items():
1514
      test = instance not in instanceinfo
1515
      _ErrorIf(test, self.ECLUSTERCFG, None,
1516
               "ghost instance '%s' in temporary DRBD map", instance)
1517
        # ghost instance should not be running, but otherwise we
1518
        # don't give double warnings (both ghost instance and
1519
        # unallocated minor in use)
1520
      if test:
1521
        node_drbd[minor] = (instance, False)
1522
      else:
1523
        instance = instanceinfo[instance]
1524
        node_drbd[minor] = (instance.name, instance.admin_up)
1525

    
1526
    # and now check them
1527
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1528
    test = not isinstance(used_minors, (tuple, list))
1529
    _ErrorIf(test, self.ENODEDRBD, node,
1530
             "cannot parse drbd status file: %s", str(used_minors))
1531
    if test:
1532
      # we cannot check drbd status
1533
      return
1534

    
1535
    for minor, (iname, must_exist) in node_drbd.items():
1536
      test = minor not in used_minors and must_exist
1537
      _ErrorIf(test, self.ENODEDRBD, node,
1538
               "drbd minor %d of instance %s is not active", minor, iname)
1539
    for minor in used_minors:
1540
      test = minor not in node_drbd
1541
      _ErrorIf(test, self.ENODEDRBD, node,
1542
               "unallocated drbd minor %d is in use", minor)
1543

    
1544
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1545
    """Verifies and updates the node volume data.
1546

1547
    This function will update a L{NodeImage}'s internal structures
1548
    with data from the remote call.
1549

1550
    @type ninfo: L{objects.Node}
1551
    @param ninfo: the node to check
1552
    @param nresult: the remote results for the node
1553
    @param nimg: the node image object
1554
    @param vg_name: the configured VG name
1555

1556
    """
1557
    node = ninfo.name
1558
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1559

    
1560
    nimg.lvm_fail = True
1561
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1562
    if vg_name is None:
1563
      pass
1564
    elif isinstance(lvdata, basestring):
1565
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1566
               utils.SafeEncode(lvdata))
1567
    elif not isinstance(lvdata, dict):
1568
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1569
    else:
1570
      nimg.volumes = lvdata
1571
      nimg.lvm_fail = False
1572

    
1573
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1574
    """Verifies and updates the node instance list.
1575

1576
    If the listing was successful, then updates this node's instance
1577
    list. Otherwise, it marks the RPC call as failed for the instance
1578
    list key.
1579

1580
    @type ninfo: L{objects.Node}
1581
    @param ninfo: the node to check
1582
    @param nresult: the remote results for the node
1583
    @param nimg: the node image object
1584

1585
    """
1586
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1587
    test = not isinstance(idata, list)
1588
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1589
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1590
    if test:
1591
      nimg.hyp_fail = True
1592
    else:
1593
      nimg.instances = idata
1594

    
1595
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1596
    """Verifies and computes a node information map
1597

1598
    @type ninfo: L{objects.Node}
1599
    @param ninfo: the node to check
1600
    @param nresult: the remote results for the node
1601
    @param nimg: the node image object
1602
    @param vg_name: the configured VG name
1603

1604
    """
1605
    node = ninfo.name
1606
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1607

    
1608
    # try to read free memory (from the hypervisor)
1609
    hv_info = nresult.get(constants.NV_HVINFO, None)
1610
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1611
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1612
    if not test:
1613
      try:
1614
        nimg.mfree = int(hv_info["memory_free"])
1615
      except (ValueError, TypeError):
1616
        _ErrorIf(True, self.ENODERPC, node,
1617
                 "node returned invalid nodeinfo, check hypervisor")
1618

    
1619
    # FIXME: devise a free space model for file based instances as well
1620
    if vg_name is not None:
1621
      test = (constants.NV_VGLIST not in nresult or
1622
              vg_name not in nresult[constants.NV_VGLIST])
1623
      _ErrorIf(test, self.ENODELVM, node,
1624
               "node didn't return data for the volume group '%s'"
1625
               " - it is either missing or broken", vg_name)
1626
      if not test:
1627
        try:
1628
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1629
        except (ValueError, TypeError):
1630
          _ErrorIf(True, self.ENODERPC, node,
1631
                   "node returned invalid LVM info, check LVM status")
1632

    
1633
  def CheckPrereq(self):
1634
    """Check prerequisites.
1635

1636
    Transform the list of checks we're going to skip into a set and check that
1637
    all its members are valid.
1638

1639
    """
1640
    self.skip_set = frozenset(self.op.skip_checks)
1641
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1642
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1643
                                 errors.ECODE_INVAL)
1644

    
1645
  def BuildHooksEnv(self):
1646
    """Build hooks env.
1647

1648
    Cluster-Verify hooks just ran in the post phase and their failure makes
1649
    the output be logged in the verify output and the verification to fail.
1650

1651
    """
1652
    all_nodes = self.cfg.GetNodeList()
1653
    env = {
1654
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1655
      }
1656
    for node in self.cfg.GetAllNodesInfo().values():
1657
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1658

    
1659
    return env, [], all_nodes
1660

    
1661
  def Exec(self, feedback_fn):
1662
    """Verify integrity of cluster, performing various test on nodes.
1663

1664
    """
1665
    self.bad = False
1666
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1667
    verbose = self.op.verbose
1668
    self._feedback_fn = feedback_fn
1669
    feedback_fn("* Verifying global settings")
1670
    for msg in self.cfg.VerifyConfig():
1671
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1672

    
1673
    # Check the cluster certificates
1674
    for cert_filename in constants.ALL_CERT_FILES:
1675
      (errcode, msg) = _VerifyCertificate(cert_filename)
1676
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1677

    
1678
    vg_name = self.cfg.GetVGName()
1679
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1680
    cluster = self.cfg.GetClusterInfo()
1681
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1682
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1683
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1684
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1685
                        for iname in instancelist)
1686
    i_non_redundant = [] # Non redundant instances
1687
    i_non_a_balanced = [] # Non auto-balanced instances
1688
    n_offline = 0 # Count of offline nodes
1689
    n_drained = 0 # Count of nodes being drained
1690
    node_vol_should = {}
1691

    
1692
    # FIXME: verify OS list
1693
    # do local checksums
1694
    master_files = [constants.CLUSTER_CONF_FILE]
1695
    master_node = self.master_node = self.cfg.GetMasterNode()
1696
    master_ip = self.cfg.GetMasterIP()
1697

    
1698
    file_names = ssconf.SimpleStore().GetFileList()
1699
    file_names.extend(constants.ALL_CERT_FILES)
1700
    file_names.extend(master_files)
1701
    if cluster.modify_etc_hosts:
1702
      file_names.append(constants.ETC_HOSTS)
1703

    
1704
    local_checksums = utils.FingerprintFiles(file_names)
1705

    
1706
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1707
    node_verify_param = {
1708
      constants.NV_FILELIST: file_names,
1709
      constants.NV_NODELIST: [node.name for node in nodeinfo
1710
                              if not node.offline],
1711
      constants.NV_HYPERVISOR: hypervisors,
1712
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1713
                                  node.secondary_ip) for node in nodeinfo
1714
                                 if not node.offline],
1715
      constants.NV_INSTANCELIST: hypervisors,
1716
      constants.NV_VERSION: None,
1717
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1718
      constants.NV_NODESETUP: None,
1719
      constants.NV_TIME: None,
1720
      constants.NV_MASTERIP: (master_node, master_ip),
1721
      }
1722

    
1723
    if vg_name is not None:
1724
      node_verify_param[constants.NV_VGLIST] = None
1725
      node_verify_param[constants.NV_LVLIST] = vg_name
1726
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1727
      node_verify_param[constants.NV_DRBDLIST] = None
1728

    
1729
    # Build our expected cluster state
1730
    node_image = dict((node.name, self.NodeImage(offline=node.offline))
1731
                      for node in nodeinfo)
1732

    
1733
    for instance in instancelist:
1734
      inst_config = instanceinfo[instance]
1735

    
1736
      for nname in inst_config.all_nodes:
1737
        if nname not in node_image:
1738
          # ghost node
1739
          gnode = self.NodeImage()
1740
          gnode.ghost = True
1741
          node_image[nname] = gnode
1742

    
1743
      inst_config.MapLVsByNode(node_vol_should)
1744

    
1745
      pnode = inst_config.primary_node
1746
      node_image[pnode].pinst.append(instance)
1747

    
1748
      for snode in inst_config.secondary_nodes:
1749
        nimg = node_image[snode]
1750
        nimg.sinst.append(instance)
1751
        if pnode not in nimg.sbp:
1752
          nimg.sbp[pnode] = []
1753
        nimg.sbp[pnode].append(instance)
1754

    
1755
    # At this point, we have the in-memory data structures complete,
1756
    # except for the runtime information, which we'll gather next
1757

    
1758
    # Due to the way our RPC system works, exact response times cannot be
1759
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
1760
    # time before and after executing the request, we can at least have a time
1761
    # window.
1762
    nvinfo_starttime = time.time()
1763
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1764
                                           self.cfg.GetClusterName())
1765
    nvinfo_endtime = time.time()
1766

    
1767
    all_drbd_map = self.cfg.ComputeDRBDMap()
1768

    
1769
    feedback_fn("* Verifying node status")
1770
    for node_i in nodeinfo:
1771
      node = node_i.name
1772
      nimg = node_image[node]
1773

    
1774
      if node_i.offline:
1775
        if verbose:
1776
          feedback_fn("* Skipping offline node %s" % (node,))
1777
        n_offline += 1
1778
        continue
1779

    
1780
      if node == master_node:
1781
        ntype = "master"
1782
      elif node_i.master_candidate:
1783
        ntype = "master candidate"
1784
      elif node_i.drained:
1785
        ntype = "drained"
1786
        n_drained += 1
1787
      else:
1788
        ntype = "regular"
1789
      if verbose:
1790
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1791

    
1792
      msg = all_nvinfo[node].fail_msg
1793
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1794
      if msg:
1795
        nimg.rpc_fail = True
1796
        continue
1797

    
1798
      nresult = all_nvinfo[node].payload
1799

    
1800
      nimg.call_ok = self._VerifyNode(node_i, nresult)
1801
      self._VerifyNodeNetwork(node_i, nresult)
1802
      self._VerifyNodeLVM(node_i, nresult, vg_name)
1803
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
1804
                            master_files)
1805
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, all_drbd_map)
1806
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
1807

    
1808
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
1809
      self._UpdateNodeInstances(node_i, nresult, nimg)
1810
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
1811

    
1812
    feedback_fn("* Verifying instance status")
1813
    for instance in instancelist:
1814
      if verbose:
1815
        feedback_fn("* Verifying instance %s" % instance)
1816
      inst_config = instanceinfo[instance]
1817
      self._VerifyInstance(instance, inst_config, node_image)
1818
      inst_nodes_offline = []
1819

    
1820
      pnode = inst_config.primary_node
1821
      pnode_img = node_image[pnode]
1822
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
1823
               self.ENODERPC, pnode, "instance %s, connection to"
1824
               " primary node failed", instance)
1825

    
1826
      if pnode_img.offline:
1827
        inst_nodes_offline.append(pnode)
1828

    
1829
      # If the instance is non-redundant we cannot survive losing its primary
1830
      # node, so we are not N+1 compliant. On the other hand we have no disk
1831
      # templates with more than one secondary so that situation is not well
1832
      # supported either.
1833
      # FIXME: does not support file-backed instances
1834
      if not inst_config.secondary_nodes:
1835
        i_non_redundant.append(instance)
1836
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
1837
               instance, "instance has multiple secondary nodes: %s",
1838
               utils.CommaJoin(inst_config.secondary_nodes),
1839
               code=self.ETYPE_WARNING)
1840

    
1841
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1842
        i_non_a_balanced.append(instance)
1843

    
1844
      for snode in inst_config.secondary_nodes:
1845
        s_img = node_image[snode]
1846
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
1847
                 "instance %s, connection to secondary node failed", instance)
1848

    
1849
        if s_img.offline:
1850
          inst_nodes_offline.append(snode)
1851

    
1852
      # warn that the instance lives on offline nodes
1853
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1854
               "instance lives on offline node(s) %s",
1855
               utils.CommaJoin(inst_nodes_offline))
1856
      # ... or ghost nodes
1857
      for node in inst_config.all_nodes:
1858
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
1859
                 "instance lives on ghost node %s", node)
1860

    
1861
    feedback_fn("* Verifying orphan volumes")
1862
    self._VerifyOrphanVolumes(node_vol_should, node_image)
1863

    
1864
    feedback_fn("* Verifying orphan instances")
1865
    self._VerifyOrphanInstances(instancelist, node_image)
1866

    
1867
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1868
      feedback_fn("* Verifying N+1 Memory redundancy")
1869
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
1870

    
1871
    feedback_fn("* Other Notes")
1872
    if i_non_redundant:
1873
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1874
                  % len(i_non_redundant))
1875

    
1876
    if i_non_a_balanced:
1877
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1878
                  % len(i_non_a_balanced))
1879

    
1880
    if n_offline:
1881
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
1882

    
1883
    if n_drained:
1884
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
1885

    
1886
    return not self.bad
1887

    
1888
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1889
    """Analyze the post-hooks' result
1890

1891
    This method analyses the hook result, handles it, and sends some
1892
    nicely-formatted feedback back to the user.
1893

1894
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1895
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1896
    @param hooks_results: the results of the multi-node hooks rpc call
1897
    @param feedback_fn: function used send feedback back to the caller
1898
    @param lu_result: previous Exec result
1899
    @return: the new Exec result, based on the previous result
1900
        and hook results
1901

1902
    """
1903
    # We only really run POST phase hooks, and are only interested in
1904
    # their results
1905
    if phase == constants.HOOKS_PHASE_POST:
1906
      # Used to change hooks' output to proper indentation
1907
      indent_re = re.compile('^', re.M)
1908
      feedback_fn("* Hooks Results")
1909
      assert hooks_results, "invalid result from hooks"
1910

    
1911
      for node_name in hooks_results:
1912
        res = hooks_results[node_name]
1913
        msg = res.fail_msg
1914
        test = msg and not res.offline
1915
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1916
                      "Communication failure in hooks execution: %s", msg)
1917
        if res.offline or msg:
1918
          # No need to investigate payload if node is offline or gave an error.
1919
          # override manually lu_result here as _ErrorIf only
1920
          # overrides self.bad
1921
          lu_result = 1
1922
          continue
1923
        for script, hkr, output in res.payload:
1924
          test = hkr == constants.HKR_FAIL
1925
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1926
                        "Script %s failed, output:", script)
1927
          if test:
1928
            output = indent_re.sub('      ', output)
1929
            feedback_fn("%s" % output)
1930
            lu_result = 0
1931

    
1932
      return lu_result
1933

    
1934

    
1935
class LUVerifyDisks(NoHooksLU):
1936
  """Verifies the cluster disks status.
1937

1938
  """
1939
  _OP_REQP = []
1940
  REQ_BGL = False
1941

    
1942
  def ExpandNames(self):
1943
    self.needed_locks = {
1944
      locking.LEVEL_NODE: locking.ALL_SET,
1945
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1946
    }
1947
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1948

    
1949
  def CheckPrereq(self):
1950
    """Check prerequisites.
1951

1952
    This has no prerequisites.
1953

1954
    """
1955
    pass
1956

    
1957
  def Exec(self, feedback_fn):
1958
    """Verify integrity of cluster disks.
1959

1960
    @rtype: tuple of three items
1961
    @return: a tuple of (dict of node-to-node_error, list of instances
1962
        which need activate-disks, dict of instance: (node, volume) for
1963
        missing volumes
1964

1965
    """
1966
    result = res_nodes, res_instances, res_missing = {}, [], {}
1967

    
1968
    vg_name = self.cfg.GetVGName()
1969
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1970
    instances = [self.cfg.GetInstanceInfo(name)
1971
                 for name in self.cfg.GetInstanceList()]
1972

    
1973
    nv_dict = {}
1974
    for inst in instances:
1975
      inst_lvs = {}
1976
      if (not inst.admin_up or
1977
          inst.disk_template not in constants.DTS_NET_MIRROR):
1978
        continue
1979
      inst.MapLVsByNode(inst_lvs)
1980
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1981
      for node, vol_list in inst_lvs.iteritems():
1982
        for vol in vol_list:
1983
          nv_dict[(node, vol)] = inst
1984

    
1985
    if not nv_dict:
1986
      return result
1987

    
1988
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1989

    
1990
    for node in nodes:
1991
      # node_volume
1992
      node_res = node_lvs[node]
1993
      if node_res.offline:
1994
        continue
1995
      msg = node_res.fail_msg
1996
      if msg:
1997
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1998
        res_nodes[node] = msg
1999
        continue
2000

    
2001
      lvs = node_res.payload
2002
      for lv_name, (_, _, lv_online) in lvs.items():
2003
        inst = nv_dict.pop((node, lv_name), None)
2004
        if (not lv_online and inst is not None
2005
            and inst.name not in res_instances):
2006
          res_instances.append(inst.name)
2007

    
2008
    # any leftover items in nv_dict are missing LVs, let's arrange the
2009
    # data better
2010
    for key, inst in nv_dict.iteritems():
2011
      if inst.name not in res_missing:
2012
        res_missing[inst.name] = []
2013
      res_missing[inst.name].append(key)
2014

    
2015
    return result
2016

    
2017

    
2018
class LURepairDiskSizes(NoHooksLU):
2019
  """Verifies the cluster disks sizes.
2020

2021
  """
2022
  _OP_REQP = ["instances"]
2023
  REQ_BGL = False
2024

    
2025
  def ExpandNames(self):
2026
    if not isinstance(self.op.instances, list):
2027
      raise errors.OpPrereqError("Invalid argument type 'instances'",
2028
                                 errors.ECODE_INVAL)
2029

    
2030
    if self.op.instances:
2031
      self.wanted_names = []
2032
      for name in self.op.instances:
2033
        full_name = _ExpandInstanceName(self.cfg, name)
2034
        self.wanted_names.append(full_name)
2035
      self.needed_locks = {
2036
        locking.LEVEL_NODE: [],
2037
        locking.LEVEL_INSTANCE: self.wanted_names,
2038
        }
2039
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2040
    else:
2041
      self.wanted_names = None
2042
      self.needed_locks = {
2043
        locking.LEVEL_NODE: locking.ALL_SET,
2044
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2045
        }
2046
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2047

    
2048
  def DeclareLocks(self, level):
2049
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2050
      self._LockInstancesNodes(primary_only=True)
2051

    
2052
  def CheckPrereq(self):
2053
    """Check prerequisites.
2054

2055
    This only checks the optional instance list against the existing names.
2056

2057
    """
2058
    if self.wanted_names is None:
2059
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2060

    
2061
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2062
                             in self.wanted_names]
2063

    
2064
  def _EnsureChildSizes(self, disk):
2065
    """Ensure children of the disk have the needed disk size.
2066

2067
    This is valid mainly for DRBD8 and fixes an issue where the
2068
    children have smaller disk size.
2069

2070
    @param disk: an L{ganeti.objects.Disk} object
2071

2072
    """
2073
    if disk.dev_type == constants.LD_DRBD8:
2074
      assert disk.children, "Empty children for DRBD8?"
2075
      fchild = disk.children[0]
2076
      mismatch = fchild.size < disk.size
2077
      if mismatch:
2078
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2079
                     fchild.size, disk.size)
2080
        fchild.size = disk.size
2081

    
2082
      # and we recurse on this child only, not on the metadev
2083
      return self._EnsureChildSizes(fchild) or mismatch
2084
    else:
2085
      return False
2086

    
2087
  def Exec(self, feedback_fn):
2088
    """Verify the size of cluster disks.
2089

2090
    """
2091
    # TODO: check child disks too
2092
    # TODO: check differences in size between primary/secondary nodes
2093
    per_node_disks = {}
2094
    for instance in self.wanted_instances:
2095
      pnode = instance.primary_node
2096
      if pnode not in per_node_disks:
2097
        per_node_disks[pnode] = []
2098
      for idx, disk in enumerate(instance.disks):
2099
        per_node_disks[pnode].append((instance, idx, disk))
2100

    
2101
    changed = []
2102
    for node, dskl in per_node_disks.items():
2103
      newl = [v[2].Copy() for v in dskl]
2104
      for dsk in newl:
2105
        self.cfg.SetDiskID(dsk, node)
2106
      result = self.rpc.call_blockdev_getsizes(node, newl)
2107
      if result.fail_msg:
2108
        self.LogWarning("Failure in blockdev_getsizes call to node"
2109
                        " %s, ignoring", node)
2110
        continue
2111
      if len(result.data) != len(dskl):
2112
        self.LogWarning("Invalid result from node %s, ignoring node results",
2113
                        node)
2114
        continue
2115
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2116
        if size is None:
2117
          self.LogWarning("Disk %d of instance %s did not return size"
2118
                          " information, ignoring", idx, instance.name)
2119
          continue
2120
        if not isinstance(size, (int, long)):
2121
          self.LogWarning("Disk %d of instance %s did not return valid"
2122
                          " size information, ignoring", idx, instance.name)
2123
          continue
2124
        size = size >> 20
2125
        if size != disk.size:
2126
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2127
                       " correcting: recorded %d, actual %d", idx,
2128
                       instance.name, disk.size, size)
2129
          disk.size = size
2130
          self.cfg.Update(instance, feedback_fn)
2131
          changed.append((instance.name, idx, size))
2132
        if self._EnsureChildSizes(disk):
2133
          self.cfg.Update(instance, feedback_fn)
2134
          changed.append((instance.name, idx, disk.size))
2135
    return changed
2136

    
2137

    
2138
class LURenameCluster(LogicalUnit):
2139
  """Rename the cluster.
2140

2141
  """
2142
  HPATH = "cluster-rename"
2143
  HTYPE = constants.HTYPE_CLUSTER
2144
  _OP_REQP = ["name"]
2145

    
2146
  def BuildHooksEnv(self):
2147
    """Build hooks env.
2148

2149
    """
2150
    env = {
2151
      "OP_TARGET": self.cfg.GetClusterName(),
2152
      "NEW_NAME": self.op.name,
2153
      }
2154
    mn = self.cfg.GetMasterNode()
2155
    all_nodes = self.cfg.GetNodeList()
2156
    return env, [mn], all_nodes
2157

    
2158
  def CheckPrereq(self):
2159
    """Verify that the passed name is a valid one.
2160

2161
    """
2162
    hostname = utils.GetHostInfo(self.op.name)
2163

    
2164
    new_name = hostname.name
2165
    self.ip = new_ip = hostname.ip
2166
    old_name = self.cfg.GetClusterName()
2167
    old_ip = self.cfg.GetMasterIP()
2168
    if new_name == old_name and new_ip == old_ip:
2169
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2170
                                 " cluster has changed",
2171
                                 errors.ECODE_INVAL)
2172
    if new_ip != old_ip:
2173
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2174
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2175
                                   " reachable on the network. Aborting." %
2176
                                   new_ip, errors.ECODE_NOTUNIQUE)
2177

    
2178
    self.op.name = new_name
2179

    
2180
  def Exec(self, feedback_fn):
2181
    """Rename the cluster.
2182

2183
    """
2184
    clustername = self.op.name
2185
    ip = self.ip
2186

    
2187
    # shutdown the master IP
2188
    master = self.cfg.GetMasterNode()
2189
    result = self.rpc.call_node_stop_master(master, False)
2190
    result.Raise("Could not disable the master role")
2191

    
2192
    try:
2193
      cluster = self.cfg.GetClusterInfo()
2194
      cluster.cluster_name = clustername
2195
      cluster.master_ip = ip
2196
      self.cfg.Update(cluster, feedback_fn)
2197

    
2198
      # update the known hosts file
2199
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2200
      node_list = self.cfg.GetNodeList()
2201
      try:
2202
        node_list.remove(master)
2203
      except ValueError:
2204
        pass
2205
      result = self.rpc.call_upload_file(node_list,
2206
                                         constants.SSH_KNOWN_HOSTS_FILE)
2207
      for to_node, to_result in result.iteritems():
2208
        msg = to_result.fail_msg
2209
        if msg:
2210
          msg = ("Copy of file %s to node %s failed: %s" %
2211
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2212
          self.proc.LogWarning(msg)
2213

    
2214
    finally:
2215
      result = self.rpc.call_node_start_master(master, False, False)
2216
      msg = result.fail_msg
2217
      if msg:
2218
        self.LogWarning("Could not re-enable the master role on"
2219
                        " the master, please restart manually: %s", msg)
2220

    
2221

    
2222
def _RecursiveCheckIfLVMBased(disk):
2223
  """Check if the given disk or its children are lvm-based.
2224

2225
  @type disk: L{objects.Disk}
2226
  @param disk: the disk to check
2227
  @rtype: boolean
2228
  @return: boolean indicating whether a LD_LV dev_type was found or not
2229

2230
  """
2231
  if disk.children:
2232
    for chdisk in disk.children:
2233
      if _RecursiveCheckIfLVMBased(chdisk):
2234
        return True
2235
  return disk.dev_type == constants.LD_LV
2236

    
2237

    
2238
class LUSetClusterParams(LogicalUnit):
2239
  """Change the parameters of the cluster.
2240

2241
  """
2242
  HPATH = "cluster-modify"
2243
  HTYPE = constants.HTYPE_CLUSTER
2244
  _OP_REQP = []
2245
  REQ_BGL = False
2246

    
2247
  def CheckArguments(self):
2248
    """Check parameters
2249

2250
    """
2251
    for attr in ["candidate_pool_size",
2252
                 "uid_pool", "add_uids", "remove_uids"]:
2253
      if not hasattr(self.op, attr):
2254
        setattr(self.op, attr, None)
2255

    
2256
    if self.op.candidate_pool_size is not None:
2257
      try:
2258
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
2259
      except (ValueError, TypeError), err:
2260
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
2261
                                   str(err), errors.ECODE_INVAL)
2262
      if self.op.candidate_pool_size < 1:
2263
        raise errors.OpPrereqError("At least one master candidate needed",
2264
                                   errors.ECODE_INVAL)
2265

    
2266
    _CheckBooleanOpField(self.op, "maintain_node_health")
2267

    
2268
    if self.op.uid_pool:
2269
      uidpool.CheckUidPool(self.op.uid_pool)
2270

    
2271
    if self.op.add_uids:
2272
      uidpool.CheckUidPool(self.op.add_uids)
2273

    
2274
    if self.op.remove_uids:
2275
      uidpool.CheckUidPool(self.op.remove_uids)
2276

    
2277
  def ExpandNames(self):
2278
    # FIXME: in the future maybe other cluster params won't require checking on
2279
    # all nodes to be modified.
2280
    self.needed_locks = {
2281
      locking.LEVEL_NODE: locking.ALL_SET,
2282
    }
2283
    self.share_locks[locking.LEVEL_NODE] = 1
2284

    
2285
  def BuildHooksEnv(self):
2286
    """Build hooks env.
2287

2288
    """
2289
    env = {
2290
      "OP_TARGET": self.cfg.GetClusterName(),
2291
      "NEW_VG_NAME": self.op.vg_name,
2292
      }
2293
    mn = self.cfg.GetMasterNode()
2294
    return env, [mn], [mn]
2295

    
2296
  def CheckPrereq(self):
2297
    """Check prerequisites.
2298

2299
    This checks whether the given params don't conflict and
2300
    if the given volume group is valid.
2301

2302
    """
2303
    if self.op.vg_name is not None and not self.op.vg_name:
2304
      instances = self.cfg.GetAllInstancesInfo().values()
2305
      for inst in instances:
2306
        for disk in inst.disks:
2307
          if _RecursiveCheckIfLVMBased(disk):
2308
            raise errors.OpPrereqError("Cannot disable lvm storage while"
2309
                                       " lvm-based instances exist",
2310
                                       errors.ECODE_INVAL)
2311

    
2312
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2313

    
2314
    # if vg_name not None, checks given volume group on all nodes
2315
    if self.op.vg_name:
2316
      vglist = self.rpc.call_vg_list(node_list)
2317
      for node in node_list:
2318
        msg = vglist[node].fail_msg
2319
        if msg:
2320
          # ignoring down node
2321
          self.LogWarning("Error while gathering data on node %s"
2322
                          " (ignoring node): %s", node, msg)
2323
          continue
2324
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2325
                                              self.op.vg_name,
2326
                                              constants.MIN_VG_SIZE)
2327
        if vgstatus:
2328
          raise errors.OpPrereqError("Error on node '%s': %s" %
2329
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2330

    
2331
    self.cluster = cluster = self.cfg.GetClusterInfo()
2332
    # validate params changes
2333
    if self.op.beparams:
2334
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2335
      self.new_beparams = objects.FillDict(
2336
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
2337

    
2338
    if self.op.nicparams:
2339
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2340
      self.new_nicparams = objects.FillDict(
2341
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
2342
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2343
      nic_errors = []
2344

    
2345
      # check all instances for consistency
2346
      for instance in self.cfg.GetAllInstancesInfo().values():
2347
        for nic_idx, nic in enumerate(instance.nics):
2348
          params_copy = copy.deepcopy(nic.nicparams)
2349
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2350

    
2351
          # check parameter syntax
2352
          try:
2353
            objects.NIC.CheckParameterSyntax(params_filled)
2354
          except errors.ConfigurationError, err:
2355
            nic_errors.append("Instance %s, nic/%d: %s" %
2356
                              (instance.name, nic_idx, err))
2357

    
2358
          # if we're moving instances to routed, check that they have an ip
2359
          target_mode = params_filled[constants.NIC_MODE]
2360
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2361
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2362
                              (instance.name, nic_idx))
2363
      if nic_errors:
2364
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2365
                                   "\n".join(nic_errors))
2366

    
2367
    # hypervisor list/parameters
2368
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2369
    if self.op.hvparams:
2370
      if not isinstance(self.op.hvparams, dict):
2371
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
2372
                                   errors.ECODE_INVAL)
2373
      for hv_name, hv_dict in self.op.hvparams.items():
2374
        if hv_name not in self.new_hvparams:
2375
          self.new_hvparams[hv_name] = hv_dict
2376
        else:
2377
          self.new_hvparams[hv_name].update(hv_dict)
2378

    
2379
    # os hypervisor parameters
2380
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2381
    if self.op.os_hvp:
2382
      if not isinstance(self.op.os_hvp, dict):
2383
        raise errors.OpPrereqError("Invalid 'os_hvp' parameter on input",
2384
                                   errors.ECODE_INVAL)
2385
      for os_name, hvs in self.op.os_hvp.items():
2386
        if not isinstance(hvs, dict):
2387
          raise errors.OpPrereqError(("Invalid 'os_hvp' parameter on"
2388
                                      " input"), errors.ECODE_INVAL)
2389
        if os_name not in self.new_os_hvp:
2390
          self.new_os_hvp[os_name] = hvs
2391
        else:
2392
          for hv_name, hv_dict in hvs.items():
2393
            if hv_name not in self.new_os_hvp[os_name]:
2394
              self.new_os_hvp[os_name][hv_name] = hv_dict
2395
            else:
2396
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2397

    
2398
    # changes to the hypervisor list
2399
    if self.op.enabled_hypervisors is not None:
2400
      self.hv_list = self.op.enabled_hypervisors
2401
      if not self.hv_list:
2402
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
2403
                                   " least one member",
2404
                                   errors.ECODE_INVAL)
2405
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
2406
      if invalid_hvs:
2407
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
2408
                                   " entries: %s" %
2409
                                   utils.CommaJoin(invalid_hvs),
2410
                                   errors.ECODE_INVAL)
2411
      for hv in self.hv_list:
2412
        # if the hypervisor doesn't already exist in the cluster
2413
        # hvparams, we initialize it to empty, and then (in both
2414
        # cases) we make sure to fill the defaults, as we might not
2415
        # have a complete defaults list if the hypervisor wasn't
2416
        # enabled before
2417
        if hv not in new_hvp:
2418
          new_hvp[hv] = {}
2419
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2420
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2421
    else:
2422
      self.hv_list = cluster.enabled_hypervisors
2423

    
2424
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2425
      # either the enabled list has changed, or the parameters have, validate
2426
      for hv_name, hv_params in self.new_hvparams.items():
2427
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2428
            (self.op.enabled_hypervisors and
2429
             hv_name in self.op.enabled_hypervisors)):
2430
          # either this is a new hypervisor, or its parameters have changed
2431
          hv_class = hypervisor.GetHypervisor(hv_name)
2432
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2433
          hv_class.CheckParameterSyntax(hv_params)
2434
          _CheckHVParams(self, node_list, hv_name, hv_params)
2435

    
2436
    if self.op.os_hvp:
2437
      # no need to check any newly-enabled hypervisors, since the
2438
      # defaults have already been checked in the above code-block
2439
      for os_name, os_hvp in self.new_os_hvp.items():
2440
        for hv_name, hv_params in os_hvp.items():
2441
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2442
          # we need to fill in the new os_hvp on top of the actual hv_p
2443
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2444
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2445
          hv_class = hypervisor.GetHypervisor(hv_name)
2446
          hv_class.CheckParameterSyntax(new_osp)
2447
          _CheckHVParams(self, node_list, hv_name, new_osp)
2448

    
2449

    
2450
  def Exec(self, feedback_fn):
2451
    """Change the parameters of the cluster.
2452

2453
    """
2454
    if self.op.vg_name is not None:
2455
      new_volume = self.op.vg_name
2456
      if not new_volume:
2457
        new_volume = None
2458
      if new_volume != self.cfg.GetVGName():
2459
        self.cfg.SetVGName(new_volume)
2460
      else:
2461
        feedback_fn("Cluster LVM configuration already in desired"
2462
                    " state, not changing")
2463
    if self.op.hvparams:
2464
      self.cluster.hvparams = self.new_hvparams
2465
    if self.op.os_hvp:
2466
      self.cluster.os_hvp = self.new_os_hvp
2467
    if self.op.enabled_hypervisors is not None:
2468
      self.cluster.hvparams = self.new_hvparams
2469
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2470
    if self.op.beparams:
2471
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2472
    if self.op.nicparams:
2473
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2474

    
2475
    if self.op.candidate_pool_size is not None:
2476
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2477
      # we need to update the pool size here, otherwise the save will fail
2478
      _AdjustCandidatePool(self, [])
2479

    
2480
    if self.op.maintain_node_health is not None:
2481
      self.cluster.maintain_node_health = self.op.maintain_node_health
2482

    
2483
    if self.op.add_uids is not None:
2484
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2485

    
2486
    if self.op.remove_uids is not None:
2487
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2488

    
2489
    if self.op.uid_pool is not None:
2490
      self.cluster.uid_pool = self.op.uid_pool
2491

    
2492
    self.cfg.Update(self.cluster, feedback_fn)
2493

    
2494

    
2495
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2496
  """Distribute additional files which are part of the cluster configuration.
2497

2498
  ConfigWriter takes care of distributing the config and ssconf files, but
2499
  there are more files which should be distributed to all nodes. This function
2500
  makes sure those are copied.
2501

2502
  @param lu: calling logical unit
2503
  @param additional_nodes: list of nodes not in the config to distribute to
2504

2505
  """
2506
  # 1. Gather target nodes
2507
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2508
  dist_nodes = lu.cfg.GetOnlineNodeList()
2509
  if additional_nodes is not None:
2510
    dist_nodes.extend(additional_nodes)
2511
  if myself.name in dist_nodes:
2512
    dist_nodes.remove(myself.name)
2513

    
2514
  # 2. Gather files to distribute
2515
  dist_files = set([constants.ETC_HOSTS,
2516
                    constants.SSH_KNOWN_HOSTS_FILE,
2517
                    constants.RAPI_CERT_FILE,
2518
                    constants.RAPI_USERS_FILE,
2519
                    constants.CONFD_HMAC_KEY,
2520
                   ])
2521

    
2522
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2523
  for hv_name in enabled_hypervisors:
2524
    hv_class = hypervisor.GetHypervisor(hv_name)
2525
    dist_files.update(hv_class.GetAncillaryFiles())
2526

    
2527
  # 3. Perform the files upload
2528
  for fname in dist_files:
2529
    if os.path.exists(fname):
2530
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2531
      for to_node, to_result in result.items():
2532
        msg = to_result.fail_msg
2533
        if msg:
2534
          msg = ("Copy of file %s to node %s failed: %s" %
2535
                 (fname, to_node, msg))
2536
          lu.proc.LogWarning(msg)
2537

    
2538

    
2539
class LURedistributeConfig(NoHooksLU):
2540
  """Force the redistribution of cluster configuration.
2541

2542
  This is a very simple LU.
2543

2544
  """
2545
  _OP_REQP = []
2546
  REQ_BGL = False
2547

    
2548
  def ExpandNames(self):
2549
    self.needed_locks = {
2550
      locking.LEVEL_NODE: locking.ALL_SET,
2551
    }
2552
    self.share_locks[locking.LEVEL_NODE] = 1
2553

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

2557
    """
2558

    
2559
  def Exec(self, feedback_fn):
2560
    """Redistribute the configuration.
2561

2562
    """
2563
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2564
    _RedistributeAncillaryFiles(self)
2565

    
2566

    
2567
def _WaitForSync(lu, instance, oneshot=False):
2568
  """Sleep and poll for an instance's disk to sync.
2569

2570
  """
2571
  if not instance.disks:
2572
    return True
2573

    
2574
  if not oneshot:
2575
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2576

    
2577
  node = instance.primary_node
2578

    
2579
  for dev in instance.disks:
2580
    lu.cfg.SetDiskID(dev, node)
2581

    
2582
  # TODO: Convert to utils.Retry
2583

    
2584
  retries = 0
2585
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2586
  while True:
2587
    max_time = 0
2588
    done = True
2589
    cumul_degraded = False
2590
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2591
    msg = rstats.fail_msg
2592
    if msg:
2593
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2594
      retries += 1
2595
      if retries >= 10:
2596
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2597
                                 " aborting." % node)
2598
      time.sleep(6)
2599
      continue
2600
    rstats = rstats.payload
2601
    retries = 0
2602
    for i, mstat in enumerate(rstats):
2603
      if mstat is None:
2604
        lu.LogWarning("Can't compute data for node %s/%s",
2605
                           node, instance.disks[i].iv_name)
2606
        continue
2607

    
2608
      cumul_degraded = (cumul_degraded or
2609
                        (mstat.is_degraded and mstat.sync_percent is None))
2610
      if mstat.sync_percent is not None:
2611
        done = False
2612
        if mstat.estimated_time is not None:
2613
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2614
          max_time = mstat.estimated_time
2615
        else:
2616
          rem_time = "no time estimate"
2617
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2618
                        (instance.disks[i].iv_name, mstat.sync_percent,
2619
                         rem_time))
2620

    
2621
    # if we're done but degraded, let's do a few small retries, to
2622
    # make sure we see a stable and not transient situation; therefore
2623
    # we force restart of the loop
2624
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2625
      logging.info("Degraded disks found, %d retries left", degr_retries)
2626
      degr_retries -= 1
2627
      time.sleep(1)
2628
      continue
2629

    
2630
    if done or oneshot:
2631
      break
2632

    
2633
    time.sleep(min(60, max_time))
2634

    
2635
  if done:
2636
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2637
  return not cumul_degraded
2638

    
2639

    
2640
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2641
  """Check that mirrors are not degraded.
2642

2643
  The ldisk parameter, if True, will change the test from the
2644
  is_degraded attribute (which represents overall non-ok status for
2645
  the device(s)) to the ldisk (representing the local storage status).
2646

2647
  """
2648
  lu.cfg.SetDiskID(dev, node)
2649

    
2650
  result = True
2651

    
2652
  if on_primary or dev.AssembleOnSecondary():
2653
    rstats = lu.rpc.call_blockdev_find(node, dev)
2654
    msg = rstats.fail_msg
2655
    if msg:
2656
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2657
      result = False
2658
    elif not rstats.payload:
2659
      lu.LogWarning("Can't find disk on node %s", node)
2660
      result = False
2661
    else:
2662
      if ldisk:
2663
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2664
      else:
2665
        result = result and not rstats.payload.is_degraded
2666

    
2667
  if dev.children:
2668
    for child in dev.children:
2669
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2670

    
2671
  return result
2672

    
2673

    
2674
class LUDiagnoseOS(NoHooksLU):
2675
  """Logical unit for OS diagnose/query.
2676

2677
  """
2678
  _OP_REQP = ["output_fields", "names"]
2679
  REQ_BGL = False
2680
  _FIELDS_STATIC = utils.FieldSet()
2681
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2682
  # Fields that need calculation of global os validity
2683
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2684

    
2685
  def ExpandNames(self):
2686
    if self.op.names:
2687
      raise errors.OpPrereqError("Selective OS query not supported",
2688
                                 errors.ECODE_INVAL)
2689

    
2690
    _CheckOutputFields(static=self._FIELDS_STATIC,
2691
                       dynamic=self._FIELDS_DYNAMIC,
2692
                       selected=self.op.output_fields)
2693

    
2694
    # Lock all nodes, in shared mode
2695
    # Temporary removal of locks, should be reverted later
2696
    # TODO: reintroduce locks when they are lighter-weight
2697
    self.needed_locks = {}
2698
    #self.share_locks[locking.LEVEL_NODE] = 1
2699
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2700

    
2701
  def CheckPrereq(self):
2702
    """Check prerequisites.
2703

2704
    """
2705

    
2706
  @staticmethod
2707
  def _DiagnoseByOS(rlist):
2708
    """Remaps a per-node return list into an a per-os per-node dictionary
2709

2710
    @param rlist: a map with node names as keys and OS objects as values
2711

2712
    @rtype: dict
2713
    @return: a dictionary with osnames as keys and as value another map, with
2714
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2715

2716
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2717
                                     (/srv/..., False, "invalid api")],
2718
                           "node2": [(/srv/..., True, "")]}
2719
          }
2720

2721
    """
2722
    all_os = {}
2723
    # we build here the list of nodes that didn't fail the RPC (at RPC
2724
    # level), so that nodes with a non-responding node daemon don't
2725
    # make all OSes invalid
2726
    good_nodes = [node_name for node_name in rlist
2727
                  if not rlist[node_name].fail_msg]
2728
    for node_name, nr in rlist.items():
2729
      if nr.fail_msg or not nr.payload:
2730
        continue
2731
      for name, path, status, diagnose, variants in nr.payload:
2732
        if name not in all_os:
2733
          # build a list of nodes for this os containing empty lists
2734
          # for each node in node_list
2735
          all_os[name] = {}
2736
          for nname in good_nodes:
2737
            all_os[name][nname] = []
2738
        all_os[name][node_name].append((path, status, diagnose, variants))
2739
    return all_os
2740

    
2741
  def Exec(self, feedback_fn):
2742
    """Compute the list of OSes.
2743

2744
    """
2745
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2746
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2747
    pol = self._DiagnoseByOS(node_data)
2748
    output = []
2749
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2750
    calc_variants = "variants" in self.op.output_fields
2751

    
2752
    for os_name, os_data in pol.items():
2753
      row = []
2754
      if calc_valid:
2755
        valid = True
2756
        variants = None
2757
        for osl in os_data.values():
2758
          valid = valid and osl and osl[0][1]
2759
          if not valid:
2760
            variants = None
2761
            break
2762
          if calc_variants:
2763
            node_variants = osl[0][3]
2764
            if variants is None:
2765
              variants = node_variants
2766
            else:
2767
              variants = [v for v in variants if v in node_variants]
2768

    
2769
      for field in self.op.output_fields:
2770
        if field == "name":
2771
          val = os_name
2772
        elif field == "valid":
2773
          val = valid
2774
        elif field == "node_status":
2775
          # this is just a copy of the dict
2776
          val = {}
2777
          for node_name, nos_list in os_data.items():
2778
            val[node_name] = nos_list
2779
        elif field == "variants":
2780
          val =  variants
2781
        else:
2782
          raise errors.ParameterError(field)
2783
        row.append(val)
2784
      output.append(row)
2785

    
2786
    return output
2787

    
2788

    
2789
class LURemoveNode(LogicalUnit):
2790
  """Logical unit for removing a node.
2791

2792
  """
2793
  HPATH = "node-remove"
2794
  HTYPE = constants.HTYPE_NODE
2795
  _OP_REQP = ["node_name"]
2796

    
2797
  def BuildHooksEnv(self):
2798
    """Build hooks env.
2799

2800
    This doesn't run on the target node in the pre phase as a failed
2801
    node would then be impossible to remove.
2802

2803
    """
2804
    env = {
2805
      "OP_TARGET": self.op.node_name,
2806
      "NODE_NAME": self.op.node_name,
2807
      }
2808
    all_nodes = self.cfg.GetNodeList()
2809
    try:
2810
      all_nodes.remove(self.op.node_name)
2811
    except ValueError:
2812
      logging.warning("Node %s which is about to be removed not found"
2813
                      " in the all nodes list", self.op.node_name)
2814
    return env, all_nodes, all_nodes
2815

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

2819
    This checks:
2820
     - the node exists in the configuration
2821
     - it does not have primary or secondary instances
2822
     - it's not the master
2823

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

2826
    """
2827
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
2828
    node = self.cfg.GetNodeInfo(self.op.node_name)
2829
    assert node is not None
2830

    
2831
    instance_list = self.cfg.GetInstanceList()
2832

    
2833
    masternode = self.cfg.GetMasterNode()
2834
    if node.name == masternode:
2835
      raise errors.OpPrereqError("Node is the master node,"
2836
                                 " you need to failover first.",
2837
                                 errors.ECODE_INVAL)
2838

    
2839
    for instance_name in instance_list:
2840
      instance = self.cfg.GetInstanceInfo(instance_name)
2841
      if node.name in instance.all_nodes:
2842
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2843
                                   " please remove first." % instance_name,
2844
                                   errors.ECODE_INVAL)
2845
    self.op.node_name = node.name
2846
    self.node = node
2847

    
2848
  def Exec(self, feedback_fn):
2849
    """Removes the node from the cluster.
2850

2851
    """
2852
    node = self.node
2853
    logging.info("Stopping the node daemon and removing configs from node %s",
2854
                 node.name)
2855

    
2856
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2857

    
2858
    # Promote nodes to master candidate as needed
2859
    _AdjustCandidatePool(self, exceptions=[node.name])
2860
    self.context.RemoveNode(node.name)
2861

    
2862
    # Run post hooks on the node before it's removed
2863
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2864
    try:
2865
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2866
    except:
2867
      # pylint: disable-msg=W0702
2868
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2869

    
2870
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2871
    msg = result.fail_msg
2872
    if msg:
2873
      self.LogWarning("Errors encountered on the remote node while leaving"
2874
                      " the cluster: %s", msg)
2875

    
2876
    # Remove node from our /etc/hosts
2877
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2878
      # FIXME: this should be done via an rpc call to node daemon
2879
      utils.RemoveHostFromEtcHosts(node.name)
2880
      _RedistributeAncillaryFiles(self)
2881

    
2882

    
2883
class LUQueryNodes(NoHooksLU):
2884
  """Logical unit for querying nodes.
2885

2886
  """
2887
  # pylint: disable-msg=W0142
2888
  _OP_REQP = ["output_fields", "names", "use_locking"]
2889
  REQ_BGL = False
2890

    
2891
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2892
                    "master_candidate", "offline", "drained"]
2893

    
2894
  _FIELDS_DYNAMIC = utils.FieldSet(
2895
    "dtotal", "dfree",
2896
    "mtotal", "mnode", "mfree",
2897
    "bootid",
2898
    "ctotal", "cnodes", "csockets",
2899
    )
2900

    
2901
  _FIELDS_STATIC = utils.FieldSet(*[
2902
    "pinst_cnt", "sinst_cnt",
2903
    "pinst_list", "sinst_list",
2904
    "pip", "sip", "tags",
2905
    "master",
2906
    "role"] + _SIMPLE_FIELDS
2907
    )
2908

    
2909
  def ExpandNames(self):
2910
    _CheckOutputFields(static=self._FIELDS_STATIC,
2911
                       dynamic=self._FIELDS_DYNAMIC,
2912
                       selected=self.op.output_fields)
2913

    
2914
    self.needed_locks = {}
2915
    self.share_locks[locking.LEVEL_NODE] = 1
2916

    
2917
    if self.op.names:
2918
      self.wanted = _GetWantedNodes(self, self.op.names)
2919
    else:
2920
      self.wanted = locking.ALL_SET
2921

    
2922
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2923
    self.do_locking = self.do_node_query and self.op.use_locking
2924
    if self.do_locking:
2925
      # if we don't request only static fields, we need to lock the nodes
2926
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2927

    
2928
  def CheckPrereq(self):
2929
    """Check prerequisites.
2930

2931
    """
2932
    # The validation of the node list is done in the _GetWantedNodes,
2933
    # if non empty, and if empty, there's no validation to do
2934
    pass
2935

    
2936
  def Exec(self, feedback_fn):
2937
    """Computes the list of nodes and their attributes.
2938

2939
    """
2940
    all_info = self.cfg.GetAllNodesInfo()
2941
    if self.do_locking:
2942
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2943
    elif self.wanted != locking.ALL_SET:
2944
      nodenames = self.wanted
2945
      missing = set(nodenames).difference(all_info.keys())
2946
      if missing:
2947
        raise errors.OpExecError(
2948
          "Some nodes were removed before retrieving their data: %s" % missing)
2949
    else:
2950
      nodenames = all_info.keys()
2951

    
2952
    nodenames = utils.NiceSort(nodenames)
2953
    nodelist = [all_info[name] for name in nodenames]
2954

    
2955
    # begin data gathering
2956

    
2957
    if self.do_node_query:
2958
      live_data = {}
2959
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2960
                                          self.cfg.GetHypervisorType())
2961
      for name in nodenames:
2962
        nodeinfo = node_data[name]
2963
        if not nodeinfo.fail_msg and nodeinfo.payload:
2964
          nodeinfo = nodeinfo.payload
2965
          fn = utils.TryConvert
2966
          live_data[name] = {
2967
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2968
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2969
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2970
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2971
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2972
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2973
            "bootid": nodeinfo.get('bootid', None),
2974
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2975
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2976
            }
2977
        else:
2978
          live_data[name] = {}
2979
    else:
2980
      live_data = dict.fromkeys(nodenames, {})
2981

    
2982
    node_to_primary = dict([(name, set()) for name in nodenames])
2983
    node_to_secondary = dict([(name, set()) for name in nodenames])
2984

    
2985
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2986
                             "sinst_cnt", "sinst_list"))
2987
    if inst_fields & frozenset(self.op.output_fields):
2988
      inst_data = self.cfg.GetAllInstancesInfo()
2989

    
2990
      for inst in inst_data.values():
2991
        if inst.primary_node in node_to_primary:
2992
          node_to_primary[inst.primary_node].add(inst.name)
2993
        for secnode in inst.secondary_nodes:
2994
          if secnode in node_to_secondary:
2995
            node_to_secondary[secnode].add(inst.name)
2996

    
2997
    master_node = self.cfg.GetMasterNode()
2998

    
2999
    # end data gathering
3000

    
3001
    output = []
3002
    for node in nodelist:
3003
      node_output = []
3004
      for field in self.op.output_fields:
3005
        if field in self._SIMPLE_FIELDS:
3006
          val = getattr(node, field)
3007
        elif field == "pinst_list":
3008
          val = list(node_to_primary[node.name])
3009
        elif field == "sinst_list":
3010
          val = list(node_to_secondary[node.name])
3011
        elif field == "pinst_cnt":
3012
          val = len(node_to_primary[node.name])
3013
        elif field == "sinst_cnt":
3014
          val = len(node_to_secondary[node.name])
3015
        elif field == "pip":
3016
          val = node.primary_ip
3017
        elif field == "sip":
3018
          val = node.secondary_ip
3019
        elif field == "tags":
3020
          val = list(node.GetTags())
3021
        elif field == "master":
3022
          val = node.name == master_node
3023
        elif self._FIELDS_DYNAMIC.Matches(field):
3024
          val = live_data[node.name].get(field, None)
3025
        elif field == "role":
3026
          if node.name == master_node:
3027
            val = "M"
3028
          elif node.master_candidate:
3029
            val = "C"
3030
          elif node.drained:
3031
            val = "D"
3032
          elif node.offline:
3033
            val = "O"
3034
          else:
3035
            val = "R"
3036
        else:
3037
          raise errors.ParameterError(field)
3038
        node_output.append(val)
3039
      output.append(node_output)
3040

    
3041
    return output
3042

    
3043

    
3044
class LUQueryNodeVolumes(NoHooksLU):
3045
  """Logical unit for getting volumes on node(s).
3046

3047
  """
3048
  _OP_REQP = ["nodes", "output_fields"]
3049
  REQ_BGL = False
3050
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3051
  _FIELDS_STATIC = utils.FieldSet("node")
3052

    
3053
  def ExpandNames(self):
3054
    _CheckOutputFields(static=self._FIELDS_STATIC,
3055
                       dynamic=self._FIELDS_DYNAMIC,
3056
                       selected=self.op.output_fields)
3057

    
3058
    self.needed_locks = {}
3059
    self.share_locks[locking.LEVEL_NODE] = 1
3060
    if not self.op.nodes:
3061
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3062
    else:
3063
      self.needed_locks[locking.LEVEL_NODE] = \
3064
        _GetWantedNodes(self, self.op.nodes)
3065

    
3066
  def CheckPrereq(self):
3067
    """Check prerequisites.
3068

3069
    This checks that the fields required are valid output fields.
3070

3071
    """
3072
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3073

    
3074
  def Exec(self, feedback_fn):
3075
    """Computes the list of nodes and their attributes.
3076

3077
    """
3078
    nodenames = self.nodes
3079
    volumes = self.rpc.call_node_volumes(nodenames)
3080

    
3081
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3082
             in self.cfg.GetInstanceList()]
3083

    
3084
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3085

    
3086
    output = []
3087
    for node in nodenames:
3088
      nresult = volumes[node]
3089
      if nresult.offline:
3090
        continue
3091
      msg = nresult.fail_msg
3092
      if msg:
3093
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3094
        continue
3095

    
3096
      node_vols = nresult.payload[:]
3097
      node_vols.sort(key=lambda vol: vol['dev'])
3098

    
3099
      for vol in node_vols:
3100
        node_output = []
3101
        for field in self.op.output_fields:
3102
          if field == "node":
3103
            val = node
3104
          elif field == "phys":
3105
            val = vol['dev']
3106
          elif field == "vg":
3107
            val = vol['vg']
3108
          elif field == "name":
3109
            val = vol['name']
3110
          elif field == "size":
3111
            val = int(float(vol['size']))
3112
          elif field == "instance":
3113
            for inst in ilist:
3114
              if node not in lv_by_node[inst]:
3115
                continue
3116
              if vol['name'] in lv_by_node[inst][node]:
3117
                val = inst.name
3118
                break
3119
            else:
3120
              val = '-'
3121
          else:
3122
            raise errors.ParameterError(field)
3123
          node_output.append(str(val))
3124

    
3125
        output.append(node_output)
3126

    
3127
    return output
3128

    
3129

    
3130
class LUQueryNodeStorage(NoHooksLU):
3131
  """Logical unit for getting information on storage units on node(s).
3132

3133
  """
3134
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
3135
  REQ_BGL = False
3136
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3137

    
3138
  def CheckArguments(self):
3139
    _CheckStorageType(self.op.storage_type)
3140

    
3141
    _CheckOutputFields(static=self._FIELDS_STATIC,
3142
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3143
                       selected=self.op.output_fields)
3144

    
3145
  def ExpandNames(self):
3146
    self.needed_locks = {}
3147
    self.share_locks[locking.LEVEL_NODE] = 1
3148

    
3149
    if self.op.nodes:
3150
      self.needed_locks[locking.LEVEL_NODE] = \
3151
        _GetWantedNodes(self, self.op.nodes)
3152
    else:
3153
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3154

    
3155
  def CheckPrereq(self):
3156
    """Check prerequisites.
3157

3158
    This checks that the fields required are valid output fields.
3159

3160
    """
3161
    self.op.name = getattr(self.op, "name", None)
3162

    
3163
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3164

    
3165
  def Exec(self, feedback_fn):
3166
    """Computes the list of nodes and their attributes.
3167

3168
    """
3169
    # Always get name to sort by
3170
    if constants.SF_NAME in self.op.output_fields:
3171
      fields = self.op.output_fields[:]
3172
    else:
3173
      fields = [constants.SF_NAME] + self.op.output_fields
3174

    
3175
    # Never ask for node or type as it's only known to the LU
3176
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3177
      while extra in fields:
3178
        fields.remove(extra)
3179

    
3180
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3181
    name_idx = field_idx[constants.SF_NAME]
3182

    
3183
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3184
    data = self.rpc.call_storage_list(self.nodes,
3185
                                      self.op.storage_type, st_args,
3186
                                      self.op.name, fields)
3187

    
3188
    result = []
3189

    
3190
    for node in utils.NiceSort(self.nodes):
3191
      nresult = data[node]
3192
      if nresult.offline:
3193
        continue
3194

    
3195
      msg = nresult.fail_msg
3196
      if msg:
3197
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3198
        continue
3199

    
3200
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3201

    
3202
      for name in utils.NiceSort(rows.keys()):
3203
        row = rows[name]
3204

    
3205
        out = []
3206

    
3207
        for field in self.op.output_fields:
3208
          if field == constants.SF_NODE:
3209
            val = node
3210
          elif field == constants.SF_TYPE:
3211
            val = self.op.storage_type
3212
          elif field in field_idx:
3213
            val = row[field_idx[field]]
3214
          else:
3215
            raise errors.ParameterError(field)
3216

    
3217
          out.append(val)
3218

    
3219
        result.append(out)
3220

    
3221
    return result
3222

    
3223

    
3224
class LUModifyNodeStorage(NoHooksLU):
3225
  """Logical unit for modifying a storage volume on a node.
3226

3227
  """
3228
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
3229
  REQ_BGL = False
3230

    
3231
  def CheckArguments(self):
3232
    self.opnode_name = _ExpandNodeName(self.cfg, self.op.node_name)
3233

    
3234
    _CheckStorageType(self.op.storage_type)
3235

    
3236
  def ExpandNames(self):
3237
    self.needed_locks = {
3238
      locking.LEVEL_NODE: self.op.node_name,
3239
      }
3240

    
3241
  def CheckPrereq(self):
3242
    """Check prerequisites.
3243

3244
    """
3245
    storage_type = self.op.storage_type
3246

    
3247
    try:
3248
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3249
    except KeyError:
3250
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3251
                                 " modified" % storage_type,
3252
                                 errors.ECODE_INVAL)
3253

    
3254
    diff = set(self.op.changes.keys()) - modifiable
3255
    if diff:
3256
      raise errors.OpPrereqError("The following fields can not be modified for"
3257
                                 " storage units of type '%s': %r" %
3258
                                 (storage_type, list(diff)),
3259
                                 errors.ECODE_INVAL)
3260

    
3261
  def Exec(self, feedback_fn):
3262
    """Computes the list of nodes and their attributes.
3263

3264
    """
3265
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3266
    result = self.rpc.call_storage_modify(self.op.node_name,
3267
                                          self.op.storage_type, st_args,
3268
                                          self.op.name, self.op.changes)
3269
    result.Raise("Failed to modify storage unit '%s' on %s" %
3270
                 (self.op.name, self.op.node_name))
3271

    
3272

    
3273
class LUAddNode(LogicalUnit):
3274
  """Logical unit for adding node to the cluster.
3275

3276
  """
3277
  HPATH = "node-add"
3278
  HTYPE = constants.HTYPE_NODE
3279
  _OP_REQP = ["node_name"]
3280

    
3281
  def CheckArguments(self):
3282
    # validate/normalize the node name
3283
    self.op.node_name = utils.HostInfo.NormalizeName(self.op.node_name)
3284

    
3285
  def BuildHooksEnv(self):
3286
    """Build hooks env.
3287

3288
    This will run on all nodes before, and on all nodes + the new node after.
3289

3290
    """
3291
    env = {
3292
      "OP_TARGET": self.op.node_name,
3293
      "NODE_NAME": self.op.node_name,
3294
      "NODE_PIP": self.op.primary_ip,
3295
      "NODE_SIP": self.op.secondary_ip,
3296
      }
3297
    nodes_0 = self.cfg.GetNodeList()
3298
    nodes_1 = nodes_0 + [self.op.node_name, ]
3299
    return env, nodes_0, nodes_1
3300

    
3301
  def CheckPrereq(self):
3302
    """Check prerequisites.
3303

3304
    This checks:
3305
     - the new node is not already in the config
3306
     - it is resolvable
3307
     - its parameters (single/dual homed) matches the cluster
3308

3309
    Any errors are signaled by raising errors.OpPrereqError.
3310

3311
    """
3312
    node_name = self.op.node_name
3313
    cfg = self.cfg
3314

    
3315
    dns_data = utils.GetHostInfo(node_name)
3316

    
3317
    node = dns_data.name
3318
    primary_ip = self.op.primary_ip = dns_data.ip
3319
    secondary_ip = getattr(self.op, "secondary_ip", None)
3320
    if secondary_ip is None:
3321
      secondary_ip = primary_ip
3322
    if not utils.IsValidIP(secondary_ip):
3323
      raise errors.OpPrereqError("Invalid secondary IP given",
3324
                                 errors.ECODE_INVAL)
3325
    self.op.secondary_ip = secondary_ip
3326

    
3327
    node_list = cfg.GetNodeList()
3328
    if not self.op.readd and node in node_list:
3329
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3330
                                 node, errors.ECODE_EXISTS)
3331
    elif self.op.readd and node not in node_list:
3332
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3333
                                 errors.ECODE_NOENT)
3334

    
3335
    self.changed_primary_ip = False
3336

    
3337
    for existing_node_name in node_list:
3338
      existing_node = cfg.GetNodeInfo(existing_node_name)
3339

    
3340
      if self.op.readd and node == existing_node_name:
3341
        if existing_node.secondary_ip != secondary_ip:
3342
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3343
                                     " address configuration as before",
3344
                                     errors.ECODE_INVAL)
3345
        if existing_node.primary_ip != primary_ip:
3346
          self.changed_primary_ip = True
3347

    
3348
        continue
3349

    
3350
      if (existing_node.primary_ip == primary_ip or
3351
          existing_node.secondary_ip == primary_ip or
3352
          existing_node.primary_ip == secondary_ip or
3353
          existing_node.secondary_ip == secondary_ip):
3354
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3355
                                   " existing node %s" % existing_node.name,
3356
                                   errors.ECODE_NOTUNIQUE)
3357

    
3358
    # check that the type of the node (single versus dual homed) is the
3359
    # same as for the master
3360
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3361
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3362
    newbie_singlehomed = secondary_ip == primary_ip
3363
    if master_singlehomed != newbie_singlehomed:
3364
      if master_singlehomed:
3365
        raise errors.OpPrereqError("The master has no private ip but the"
3366
                                   " new node has one",
3367
                                   errors.ECODE_INVAL)
3368
      else:
3369
        raise errors.OpPrereqError("The master has a private ip but the"
3370
                                   " new node doesn't have one",
3371
                                   errors.ECODE_INVAL)
3372

    
3373
    # checks reachability
3374
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3375
      raise errors.OpPrereqError("Node not reachable by ping",
3376
                                 errors.ECODE_ENVIRON)
3377

    
3378
    if not newbie_singlehomed:
3379
      # check reachability from my secondary ip to newbie's secondary ip
3380
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3381
                           source=myself.secondary_ip):
3382
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3383
                                   " based ping to noded port",
3384
                                   errors.ECODE_ENVIRON)
3385

    
3386
    if self.op.readd:
3387
      exceptions = [node]
3388
    else:
3389
      exceptions = []
3390

    
3391
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3392

    
3393
    if self.op.readd:
3394
      self.new_node = self.cfg.GetNodeInfo(node)
3395
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3396
    else:
3397
      self.new_node = objects.Node(name=node,
3398
                                   primary_ip=primary_ip,
3399
                                   secondary_ip=secondary_ip,
3400
                                   master_candidate=self.master_candidate,
3401
                                   offline=False, drained=False)
3402

    
3403
  def Exec(self, feedback_fn):
3404
    """Adds the new node to the cluster.
3405

3406
    """
3407
    new_node = self.new_node
3408
    node = new_node.name
3409

    
3410
    # for re-adds, reset the offline/drained/master-candidate flags;
3411
    # we need to reset here, otherwise offline would prevent RPC calls
3412
    # later in the procedure; this also means that if the re-add
3413
    # fails, we are left with a non-offlined, broken node
3414
    if self.op.readd:
3415
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3416
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3417
      # if we demote the node, we do cleanup later in the procedure
3418
      new_node.master_candidate = self.master_candidate
3419
      if self.changed_primary_ip:
3420
        new_node.primary_ip = self.op.primary_ip
3421

    
3422
    # notify the user about any possible mc promotion
3423
    if new_node.master_candidate:
3424
      self.LogInfo("Node will be a master candidate")
3425

    
3426
    # check connectivity
3427
    result = self.rpc.call_version([node])[node]
3428
    result.Raise("Can't get version information from node %s" % node)
3429
    if constants.PROTOCOL_VERSION == result.payload:
3430
      logging.info("Communication to node %s fine, sw version %s match",
3431
                   node, result.payload)
3432
    else:
3433
      raise errors.OpExecError("Version mismatch master version %s,"
3434
                               " node version %s" %
3435
                               (constants.PROTOCOL_VERSION, result.payload))
3436

    
3437
    # setup ssh on node
3438
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3439
      logging.info("Copy ssh key to node %s", node)
3440
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3441
      keyarray = []
3442
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3443
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3444
                  priv_key, pub_key]
3445

    
3446
      for i in keyfiles:
3447
        keyarray.append(utils.ReadFile(i))
3448

    
3449
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3450
                                      keyarray[2], keyarray[3], keyarray[4],
3451
                                      keyarray[5])
3452
      result.Raise("Cannot transfer ssh keys to the new node")
3453

    
3454
    # Add node to our /etc/hosts, and add key to known_hosts
3455
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3456
      # FIXME: this should be done via an rpc call to node daemon
3457
      utils.AddHostToEtcHosts(new_node.name)
3458

    
3459
    if new_node.secondary_ip != new_node.primary_ip:
3460
      result = self.rpc.call_node_has_ip_address(new_node.name,
3461
                                                 new_node.secondary_ip)
3462
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3463
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3464
      if not result.payload:
3465
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3466
                                 " you gave (%s). Please fix and re-run this"
3467
                                 " command." % new_node.secondary_ip)
3468

    
3469
    node_verify_list = [self.cfg.GetMasterNode()]
3470
    node_verify_param = {
3471
      constants.NV_NODELIST: [node],
3472
      # TODO: do a node-net-test as well?
3473
    }
3474

    
3475
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3476
                                       self.cfg.GetClusterName())
3477
    for verifier in node_verify_list:
3478
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3479
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3480
      if nl_payload:
3481
        for failed in nl_payload:
3482
          feedback_fn("ssh/hostname verification failed"
3483
                      " (checking from %s): %s" %
3484
                      (verifier, nl_payload[failed]))
3485
        raise errors.OpExecError("ssh/hostname verification failed.")
3486

    
3487
    if self.op.readd:
3488
      _RedistributeAncillaryFiles(self)
3489
      self.context.ReaddNode(new_node)
3490
      # make sure we redistribute the config
3491
      self.cfg.Update(new_node, feedback_fn)
3492
      # and make sure the new node will not have old files around
3493
      if not new_node.master_candidate:
3494
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3495
        msg = result.fail_msg
3496
        if msg:
3497
          self.LogWarning("Node failed to demote itself from master"
3498
                          " candidate status: %s" % msg)
3499
    else:
3500
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3501
      self.context.AddNode(new_node, self.proc.GetECId())
3502

    
3503

    
3504
class LUSetNodeParams(LogicalUnit):
3505
  """Modifies the parameters of a node.
3506

3507
  """
3508
  HPATH = "node-modify"
3509
  HTYPE = constants.HTYPE_NODE
3510
  _OP_REQP = ["node_name"]
3511
  REQ_BGL = False
3512

    
3513
  def CheckArguments(self):
3514
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3515
    _CheckBooleanOpField(self.op, 'master_candidate')
3516
    _CheckBooleanOpField(self.op, 'offline')
3517
    _CheckBooleanOpField(self.op, 'drained')
3518
    _CheckBooleanOpField(self.op, 'auto_promote')
3519
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3520
    if all_mods.count(None) == 3:
3521
      raise errors.OpPrereqError("Please pass at least one modification",
3522
                                 errors.ECODE_INVAL)
3523
    if all_mods.count(True) > 1:
3524
      raise errors.OpPrereqError("Can't set the node into more than one"
3525
                                 " state at the same time",
3526
                                 errors.ECODE_INVAL)
3527

    
3528
    # Boolean value that tells us whether we're offlining or draining the node
3529
    self.offline_or_drain = (self.op.offline == True or
3530
                             self.op.drained == True)
3531
    self.deoffline_or_drain = (self.op.offline == False or
3532
                               self.op.drained == False)
3533
    self.might_demote = (self.op.master_candidate == False or
3534
                         self.offline_or_drain)
3535

    
3536
    self.lock_all = self.op.auto_promote and self.might_demote
3537

    
3538

    
3539
  def ExpandNames(self):
3540
    if self.lock_all:
3541
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3542
    else:
3543
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3544

    
3545
  def BuildHooksEnv(self):
3546
    """Build hooks env.
3547

3548
    This runs on the master node.
3549

3550
    """
3551
    env = {
3552
      "OP_TARGET": self.op.node_name,
3553
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3554
      "OFFLINE": str(self.op.offline),
3555
      "DRAINED": str(self.op.drained),
3556
      }
3557
    nl = [self.cfg.GetMasterNode(),
3558
          self.op.node_name]
3559
    return env, nl, nl
3560

    
3561
  def CheckPrereq(self):
3562
    """Check prerequisites.
3563

3564
    This only checks the instance list against the existing names.
3565

3566
    """
3567
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3568

    
3569
    if (self.op.master_candidate is not None or
3570
        self.op.drained is not None or
3571
        self.op.offline is not None):
3572
      # we can't change the master's node flags
3573
      if self.op.node_name == self.cfg.GetMasterNode():
3574
        raise errors.OpPrereqError("The master role can be changed"
3575
                                   " only via masterfailover",
3576
                                   errors.ECODE_INVAL)
3577

    
3578

    
3579
    if node.master_candidate and self.might_demote and not self.lock_all:
3580
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3581
      # check if after removing the current node, we're missing master
3582
      # candidates
3583
      (mc_remaining, mc_should, _) = \
3584
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3585
      if mc_remaining < mc_should:
3586
        raise errors.OpPrereqError("Not enough master candidates, please"
3587
                                   " pass auto_promote to allow promotion",
3588
                                   errors.ECODE_INVAL)
3589

    
3590
    if (self.op.master_candidate == True and
3591
        ((node.offline and not self.op.offline == False) or
3592
         (node.drained and not self.op.drained == False))):
3593
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3594
                                 " to master_candidate" % node.name,
3595
                                 errors.ECODE_INVAL)
3596

    
3597
    # If we're being deofflined/drained, we'll MC ourself if needed
3598
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3599
        self.op.master_candidate == True and not node.master_candidate):
3600
      self.op.master_candidate = _DecideSelfPromotion(self)
3601
      if self.op.master_candidate:
3602
        self.LogInfo("Autopromoting node to master candidate")
3603

    
3604
    return
3605

    
3606
  def Exec(self, feedback_fn):
3607
    """Modifies a node.
3608

3609
    """
3610
    node = self.node
3611

    
3612
    result = []
3613
    changed_mc = False
3614

    
3615
    if self.op.offline is not None:
3616
      node.offline = self.op.offline
3617
      result.append(("offline", str(self.op.offline)))
3618
      if self.op.offline == True:
3619
        if node.master_candidate:
3620
          node.master_candidate = False
3621
          changed_mc = True
3622
          result.append(("master_candidate", "auto-demotion due to offline"))
3623
        if node.drained:
3624
          node.drained = False
3625
          result.append(("drained", "clear drained status due to offline"))
3626

    
3627
    if self.op.master_candidate is not None:
3628
      node.master_candidate = self.op.master_candidate
3629
      changed_mc = True
3630
      result.append(("master_candidate", str(self.op.master_candidate)))
3631
      if self.op.master_candidate == False:
3632
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3633
        msg = rrc.fail_msg
3634
        if msg:
3635
          self.LogWarning("Node failed to demote itself: %s" % msg)
3636

    
3637
    if self.op.drained is not None:
3638
      node.drained = self.op.drained
3639
      result.append(("drained", str(self.op.drained)))
3640
      if self.op.drained == True:
3641
        if node.master_candidate:
3642
          node.master_candidate = False
3643
          changed_mc = True
3644
          result.append(("master_candidate", "auto-demotion due to drain"))
3645
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3646
          msg = rrc.fail_msg
3647
          if msg:
3648
            self.LogWarning("Node failed to demote itself: %s" % msg)
3649
        if node.offline:
3650
          node.offline = False
3651
          result.append(("offline", "clear offline status due to drain"))
3652

    
3653
    # we locked all nodes, we adjust the CP before updating this node
3654
    if self.lock_all:
3655
      _AdjustCandidatePool(self, [node.name])
3656

    
3657
    # this will trigger configuration file update, if needed
3658
    self.cfg.Update(node, feedback_fn)
3659

    
3660
    # this will trigger job queue propagation or cleanup
3661
    if changed_mc:
3662
      self.context.ReaddNode(node)
3663

    
3664
    return result
3665

    
3666

    
3667
class LUPowercycleNode(NoHooksLU):
3668
  """Powercycles a node.
3669

3670
  """
3671
  _OP_REQP = ["node_name", "force"]
3672
  REQ_BGL = False
3673

    
3674
  def CheckArguments(self):
3675
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3676
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
3677
      raise errors.OpPrereqError("The node is the master and the force"
3678
                                 " parameter was not set",
3679
                                 errors.ECODE_INVAL)
3680

    
3681
  def ExpandNames(self):
3682
    """Locking for PowercycleNode.
3683

3684
    This is a last-resort option and shouldn't block on other
3685
    jobs. Therefore, we grab no locks.
3686

3687
    """
3688
    self.needed_locks = {}
3689

    
3690
  def CheckPrereq(self):
3691
    """Check prerequisites.
3692

3693
    This LU has no prereqs.
3694

3695
    """
3696
    pass
3697

    
3698
  def Exec(self, feedback_fn):
3699
    """Reboots a node.
3700

3701
    """
3702
    result = self.rpc.call_node_powercycle(self.op.node_name,
3703
                                           self.cfg.GetHypervisorType())
3704
    result.Raise("Failed to schedule the reboot")
3705
    return result.payload
3706

    
3707

    
3708
class LUQueryClusterInfo(NoHooksLU):
3709
  """Query cluster configuration.
3710

3711
  """
3712
  _OP_REQP = []
3713
  REQ_BGL = False
3714

    
3715
  def ExpandNames(self):
3716
    self.needed_locks = {}
3717

    
3718
  def CheckPrereq(self):
3719
    """No prerequsites needed for this LU.
3720

3721
    """
3722
    pass
3723

    
3724
  def Exec(self, feedback_fn):
3725
    """Return cluster config.
3726

3727
    """
3728
    cluster = self.cfg.GetClusterInfo()
3729
    os_hvp = {}
3730

    
3731
    # Filter just for enabled hypervisors
3732
    for os_name, hv_dict in cluster.os_hvp.items():
3733
      os_hvp[os_name] = {}
3734
      for hv_name, hv_params in hv_dict.items():
3735
        if hv_name in cluster.enabled_hypervisors:
3736
          os_hvp[os_name][hv_name] = hv_params
3737

    
3738
    result = {
3739
      "software_version": constants.RELEASE_VERSION,
3740
      "protocol_version": constants.PROTOCOL_VERSION,
3741
      "config_version": constants.CONFIG_VERSION,
3742
      "os_api_version": max(constants.OS_API_VERSIONS),
3743
      "export_version": constants.EXPORT_VERSION,
3744
      "architecture": (platform.architecture()[0], platform.machine()),
3745
      "name": cluster.cluster_name,
3746
      "master": cluster.master_node,
3747
      "default_hypervisor": cluster.enabled_hypervisors[0],
3748
      "enabled_hypervisors": cluster.enabled_hypervisors,
3749
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3750
                        for hypervisor_name in cluster.enabled_hypervisors]),
3751
      "os_hvp": os_hvp,
3752
      "beparams": cluster.beparams,
3753
      "nicparams": cluster.nicparams,
3754
      "candidate_pool_size": cluster.candidate_pool_size,
3755
      "master_netdev": cluster.master_netdev,
3756
      "volume_group_name": cluster.volume_group_name,
3757
      "file_storage_dir": cluster.file_storage_dir,
3758
      "maintain_node_health": cluster.maintain_node_health,
3759
      "ctime": cluster.ctime,
3760
      "mtime": cluster.mtime,
3761
      "uuid": cluster.uuid,
3762
      "tags": list(cluster.GetTags()),
3763
      "uid_pool": cluster.uid_pool,
3764
      }
3765

    
3766
    return result
3767

    
3768

    
3769
class LUQueryConfigValues(NoHooksLU):
3770
  """Return configuration values.
3771

3772
  """
3773
  _OP_REQP = []
3774
  REQ_BGL = False
3775
  _FIELDS_DYNAMIC = utils.FieldSet()
3776
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3777
                                  "watcher_pause")
3778

    
3779
  def ExpandNames(self):
3780
    self.needed_locks = {}
3781

    
3782
    _CheckOutputFields(static=self._FIELDS_STATIC,
3783
                       dynamic=self._FIELDS_DYNAMIC,
3784
                       selected=self.op.output_fields)
3785

    
3786
  def CheckPrereq(self):
3787
    """No prerequisites.
3788

3789
    """
3790
    pass
3791

    
3792
  def Exec(self, feedback_fn):
3793
    """Dump a representation of the cluster config to the standard output.
3794

3795
    """
3796
    values = []
3797
    for field in self.op.output_fields:
3798
      if field == "cluster_name":
3799
        entry = self.cfg.GetClusterName()
3800
      elif field == "master_node":
3801
        entry = self.cfg.GetMasterNode()
3802
      elif field == "drain_flag":
3803
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3804
      elif field == "watcher_pause":
3805
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3806
      else:
3807
        raise errors.ParameterError(field)
3808
      values.append(entry)
3809
    return values
3810

    
3811

    
3812
class LUActivateInstanceDisks(NoHooksLU):
3813
  """Bring up an instance's disks.
3814

3815
  """
3816
  _OP_REQP = ["instance_name"]
3817
  REQ_BGL = False
3818

    
3819
  def ExpandNames(self):
3820
    self._ExpandAndLockInstance()
3821
    self.needed_locks[locking.LEVEL_NODE] = []
3822
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3823

    
3824
  def DeclareLocks(self, level):
3825
    if level == locking.LEVEL_NODE:
3826
      self._LockInstancesNodes()
3827

    
3828
  def CheckPrereq(self):
3829
    """Check prerequisites.
3830

3831
    This checks that the instance is in the cluster.
3832

3833
    """
3834
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3835
    assert self.instance is not None, \
3836
      "Cannot retrieve locked instance %s" % self.op.instance_name
3837
    _CheckNodeOnline(self, self.instance.primary_node)
3838
    if not hasattr(self.op, "ignore_size"):
3839
      self.op.ignore_size = False
3840

    
3841
  def Exec(self, feedback_fn):
3842
    """Activate the disks.
3843

3844
    """
3845
    disks_ok, disks_info = \
3846
              _AssembleInstanceDisks(self, self.instance,
3847
                                     ignore_size=self.op.ignore_size)
3848
    if not disks_ok:
3849
      raise errors.OpExecError("Cannot activate block devices")
3850

    
3851
    return disks_info
3852

    
3853

    
3854
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3855
                           ignore_size=False):
3856
  """Prepare the block devices for an instance.
3857

3858
  This sets up the block devices on all nodes.
3859

3860
  @type lu: L{LogicalUnit}
3861
  @param lu: the logical unit on whose behalf we execute
3862
  @type instance: L{objects.Instance}
3863
  @param instance: the instance for whose disks we assemble
3864
  @type ignore_secondaries: boolean
3865
  @param ignore_secondaries: if true, errors on secondary nodes
3866
      won't result in an error return from the function
3867
  @type ignore_size: boolean
3868
  @param ignore_size: if true, the current known size of the disk
3869
      will not be used during the disk activation, useful for cases
3870
      when the size is wrong
3871
  @return: False if the operation failed, otherwise a list of
3872
      (host, instance_visible_name, node_visible_name)
3873
      with the mapping from node devices to instance devices
3874

3875
  """
3876
  device_info = []
3877
  disks_ok = True
3878
  iname = instance.name
3879
  # With the two passes mechanism we try to reduce the window of
3880
  # opportunity for the race condition of switching DRBD to primary
3881
  # before handshaking occured, but we do not eliminate it
3882

    
3883
  # The proper fix would be to wait (with some limits) until the
3884
  # connection has been made and drbd transitions from WFConnection
3885
  # into any other network-connected state (Connected, SyncTarget,
3886
  # SyncSource, etc.)
3887

    
3888
  # 1st pass, assemble on all nodes in secondary mode
3889
  for inst_disk in instance.disks:
3890
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3891
      if ignore_size:
3892
        node_disk = node_disk.Copy()
3893
        node_disk.UnsetSize()
3894
      lu.cfg.SetDiskID(node_disk, node)
3895
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3896
      msg = result.fail_msg
3897
      if msg:
3898
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3899
                           " (is_primary=False, pass=1): %s",
3900
                           inst_disk.iv_name, node, msg)
3901
        if not ignore_secondaries:
3902
          disks_ok = False
3903

    
3904
  # FIXME: race condition on drbd migration to primary
3905

    
3906
  # 2nd pass, do only the primary node
3907
  for inst_disk in instance.disks:
3908
    dev_path = None
3909

    
3910
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3911
      if node != instance.primary_node:
3912
        continue
3913
      if ignore_size:
3914
        node_disk = node_disk.Copy()
3915
        node_disk.UnsetSize()
3916
      lu.cfg.SetDiskID(node_disk, node)
3917
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3918
      msg = result.fail_msg
3919
      if msg:
3920
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3921
                           " (is_primary=True, pass=2): %s",
3922
                           inst_disk.iv_name, node, msg)
3923
        disks_ok = False
3924
      else:
3925
        dev_path = result.payload
3926

    
3927
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3928

    
3929
  # leave the disks configured for the primary node
3930
  # this is a workaround that would be fixed better by
3931
  # improving the logical/physical id handling
3932
  for disk in instance.disks:
3933
    lu.cfg.SetDiskID(disk, instance.primary_node)
3934

    
3935
  return disks_ok, device_info
3936

    
3937

    
3938
def _StartInstanceDisks(lu, instance, force):
3939
  """Start the disks of an instance.
3940

3941
  """
3942
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3943
                                           ignore_secondaries=force)
3944
  if not disks_ok:
3945
    _ShutdownInstanceDisks(lu, instance)
3946
    if force is not None and not force:
3947
      lu.proc.LogWarning("", hint="If the message above refers to a"
3948
                         " secondary node,"
3949
                         " you can retry the operation using '--force'.")
3950
    raise errors.OpExecError("Disk consistency error")
3951

    
3952

    
3953
class LUDeactivateInstanceDisks(NoHooksLU):
3954
  """Shutdown an instance's disks.
3955

3956
  """
3957
  _OP_REQP = ["instance_name"]
3958
  REQ_BGL = False
3959

    
3960
  def ExpandNames(self):
3961
    self._ExpandAndLockInstance()
3962
    self.needed_locks[locking.LEVEL_NODE] = []
3963
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3964

    
3965
  def DeclareLocks(self, level):
3966
    if level == locking.LEVEL_NODE:
3967
      self._LockInstancesNodes()
3968

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

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

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

    
3979
  def Exec(self, feedback_fn):
3980
    """Deactivate the disks
3981

3982
    """
3983
    instance = self.instance
3984
    _SafeShutdownInstanceDisks(self, instance)
3985

    
3986

    
3987
def _SafeShutdownInstanceDisks(lu, instance):
3988
  """Shutdown block devices of an instance.
3989

3990
  This function checks if an instance is running, before calling
3991
  _ShutdownInstanceDisks.
3992

3993
  """
3994
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
3995
  _ShutdownInstanceDisks(lu, instance)
3996

    
3997

    
3998
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3999
  """Shutdown block devices of an instance.
4000

4001
  This does the shutdown on all nodes of the instance.
4002

4003
  If the ignore_primary is false, errors on the primary node are
4004
  ignored.
4005

4006
  """
4007
  all_result = True
4008
  for disk in instance.disks:
4009
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4010
      lu.cfg.SetDiskID(top_disk, node)
4011
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4012
      msg = result.fail_msg
4013
      if msg:
4014
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4015
                      disk.iv_name, node, msg)
4016
        if not ignore_primary or node != instance.primary_node:
4017
          all_result = False
4018
  return all_result
4019

    
4020

    
4021
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4022
  """Checks if a node has enough free memory.
4023

4024
  This function check if a given node has the needed amount of free
4025
  memory. In case the node has less memory or we cannot get the
4026
  information from the node, this function raise an OpPrereqError
4027
  exception.
4028

4029
  @type lu: C{LogicalUnit}
4030
  @param lu: a logical unit from which we get configuration data
4031
  @type node: C{str}
4032
  @param node: the node to check
4033
  @type reason: C{str}
4034
  @param reason: string to use in the error message
4035
  @type requested: C{int}
4036
  @param requested: the amount of memory in MiB to check for
4037
  @type hypervisor_name: C{str}
4038
  @param hypervisor_name: the hypervisor to ask for memory stats
4039
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4040
      we cannot check the node
4041

4042
  """
4043
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4044
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4045
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4046
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4047
  if not isinstance(free_mem, int):
4048
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4049
                               " was '%s'" % (node, free_mem),
4050
                               errors.ECODE_ENVIRON)
4051
  if requested > free_mem:
4052
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4053
                               " needed %s MiB, available %s MiB" %
4054
                               (node, reason, requested, free_mem),
4055
                               errors.ECODE_NORES)
4056

    
4057

    
4058
def _CheckNodesFreeDisk(lu, nodenames, requested):
4059
  """Checks if nodes have enough free disk space in the default VG.
4060

4061
  This function check if all given nodes have the needed amount of
4062
  free disk. In case any node has less disk or we cannot get the
4063
  information from the node, this function raise an OpPrereqError
4064
  exception.
4065

4066
  @type lu: C{LogicalUnit}
4067
  @param lu: a logical unit from which we get configuration data
4068
  @type nodenames: C{list}
4069
  @param nodenames: the list of node names to check
4070
  @type requested: C{int}
4071
  @param requested: the amount of disk in MiB to check for
4072
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4073
      we cannot check the node
4074

4075
  """
4076
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4077
                                   lu.cfg.GetHypervisorType())
4078
  for node in nodenames:
4079
    info = nodeinfo[node]
4080
    info.Raise("Cannot get current information from node %s" % node,
4081
               prereq=True, ecode=errors.ECODE_ENVIRON)
4082
    vg_free = info.payload.get("vg_free", None)
4083
    if not isinstance(vg_free, int):
4084
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4085
                                 " result was '%s'" % (node, vg_free),
4086
                                 errors.ECODE_ENVIRON)
4087
    if requested > vg_free:
4088
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4089
                                 " required %d MiB, available %d MiB" %
4090
                                 (node, requested, vg_free),
4091
                                 errors.ECODE_NORES)
4092

    
4093

    
4094
class LUStartupInstance(LogicalUnit):
4095
  """Starts an instance.
4096

4097
  """
4098
  HPATH = "instance-start"
4099
  HTYPE = constants.HTYPE_INSTANCE
4100
  _OP_REQP = ["instance_name", "force"]
4101
  REQ_BGL = False
4102

    
4103
  def ExpandNames(self):
4104
    self._ExpandAndLockInstance()
4105

    
4106
  def BuildHooksEnv(self):
4107
    """Build hooks env.
4108

4109
    This runs on master, primary and secondary nodes of the instance.
4110

4111
    """
4112
    env = {
4113
      "FORCE": self.op.force,
4114
      }
4115
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4116
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4117
    return env, nl, nl
4118

    
4119
  def CheckPrereq(self):
4120
    """Check prerequisites.
4121

4122
    This checks that the instance is in the cluster.
4123

4124
    """
4125
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4126
    assert self.instance is not None, \
4127
      "Cannot retrieve locked instance %s" % self.op.instance_name
4128

    
4129
    # extra beparams
4130
    self.beparams = getattr(self.op, "beparams", {})
4131
    if self.beparams:
4132
      if not isinstance(self.beparams, dict):
4133
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
4134
                                   " dict" % (type(self.beparams), ),
4135
                                   errors.ECODE_INVAL)
4136
      # fill the beparams dict
4137
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
4138
      self.op.beparams = self.beparams
4139

    
4140
    # extra hvparams
4141
    self.hvparams = getattr(self.op, "hvparams", {})
4142
    if self.hvparams:
4143
      if not isinstance(self.hvparams, dict):
4144
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
4145
                                   " dict" % (type(self.hvparams), ),
4146
                                   errors.ECODE_INVAL)
4147

    
4148
      # check hypervisor parameter syntax (locally)
4149
      cluster = self.cfg.GetClusterInfo()
4150
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
4151
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
4152
                                    instance.hvparams)
4153
      filled_hvp.update(self.hvparams)
4154
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4155
      hv_type.CheckParameterSyntax(filled_hvp)
4156
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4157
      self.op.hvparams = self.hvparams
4158

    
4159
    _CheckNodeOnline(self, instance.primary_node)
4160

    
4161
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4162
    # check bridges existence
4163
    _CheckInstanceBridgesExist(self, instance)
4164

    
4165
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4166
                                              instance.name,
4167
                                              instance.hypervisor)
4168
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4169
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4170
    if not remote_info.payload: # not running already
4171
      _CheckNodeFreeMemory(self, instance.primary_node,
4172
                           "starting instance %s" % instance.name,
4173
                           bep[constants.BE_MEMORY], instance.hypervisor)
4174

    
4175
  def Exec(self, feedback_fn):
4176
    """Start the instance.
4177

4178
    """
4179
    instance = self.instance
4180
    force = self.op.force
4181

    
4182
    self.cfg.MarkInstanceUp(instance.name)
4183

    
4184
    node_current = instance.primary_node
4185

    
4186
    _StartInstanceDisks(self, instance, force)
4187

    
4188
    result = self.rpc.call_instance_start(node_current, instance,
4189
                                          self.hvparams, self.beparams)
4190
    msg = result.fail_msg
4191
    if msg:
4192
      _ShutdownInstanceDisks(self, instance)
4193
      raise errors.OpExecError("Could not start instance: %s" % msg)
4194

    
4195

    
4196
class LURebootInstance(LogicalUnit):
4197
  """Reboot an instance.
4198

4199
  """
4200
  HPATH = "instance-reboot"
4201
  HTYPE = constants.HTYPE_INSTANCE
4202
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
4203
  REQ_BGL = False
4204

    
4205
  def CheckArguments(self):
4206
    """Check the arguments.
4207

4208
    """
4209
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4210
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4211

    
4212
  def ExpandNames(self):
4213
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
4214
                                   constants.INSTANCE_REBOOT_HARD,
4215
                                   constants.INSTANCE_REBOOT_FULL]:
4216
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
4217
                                  (constants.INSTANCE_REBOOT_SOFT,
4218
                                   constants.INSTANCE_REBOOT_HARD,
4219
                                   constants.INSTANCE_REBOOT_FULL))
4220
    self._ExpandAndLockInstance()
4221

    
4222
  def BuildHooksEnv(self):
4223
    """Build hooks env.
4224

4225
    This runs on master, primary and secondary nodes of the instance.
4226

4227
    """
4228
    env = {
4229
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4230
      "REBOOT_TYPE": self.op.reboot_type,
4231
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4232
      }
4233
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4234
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4235
    return env, nl, nl
4236

    
4237
  def CheckPrereq(self):
4238
    """Check prerequisites.
4239

4240
    This checks that the instance is in the cluster.
4241

4242
    """
4243
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4244
    assert self.instance is not None, \
4245
      "Cannot retrieve locked instance %s" % self.op.instance_name
4246

    
4247
    _CheckNodeOnline(self, instance.primary_node)
4248

    
4249
    # check bridges existence
4250
    _CheckInstanceBridgesExist(self, instance)
4251

    
4252
  def Exec(self, feedback_fn):
4253
    """Reboot the instance.
4254

4255
    """
4256
    instance = self.instance
4257
    ignore_secondaries = self.op.ignore_secondaries
4258
    reboot_type = self.op.reboot_type
4259

    
4260
    node_current = instance.primary_node
4261

    
4262
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4263
                       constants.INSTANCE_REBOOT_HARD]:
4264
      for disk in instance.disks:
4265
        self.cfg.SetDiskID(disk, node_current)
4266
      result = self.rpc.call_instance_reboot(node_current, instance,
4267
                                             reboot_type,
4268
                                             self.shutdown_timeout)
4269
      result.Raise("Could not reboot instance")
4270
    else:
4271
      result = self.rpc.call_instance_shutdown(node_current, instance,
4272
                                               self.shutdown_timeout)
4273
      result.Raise("Could not shutdown instance for full reboot")
4274
      _ShutdownInstanceDisks(self, instance)
4275
      _StartInstanceDisks(self, instance, ignore_secondaries)
4276
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4277
      msg = result.fail_msg
4278
      if msg:
4279
        _ShutdownInstanceDisks(self, instance)
4280
        raise errors.OpExecError("Could not start instance for"
4281
                                 " full reboot: %s" % msg)
4282

    
4283
    self.cfg.MarkInstanceUp(instance.name)
4284

    
4285

    
4286
class LUShutdownInstance(LogicalUnit):
4287
  """Shutdown an instance.
4288

4289
  """
4290
  HPATH = "instance-stop"
4291
  HTYPE = constants.HTYPE_INSTANCE
4292
  _OP_REQP = ["instance_name"]
4293
  REQ_BGL = False
4294

    
4295
  def CheckArguments(self):
4296
    """Check the arguments.
4297

4298
    """
4299
    self.timeout = getattr(self.op, "timeout",
4300
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
4301

    
4302
  def ExpandNames(self):
4303
    self._ExpandAndLockInstance()
4304

    
4305
  def BuildHooksEnv(self):
4306
    """Build hooks env.
4307

4308
    This runs on master, primary and secondary nodes of the instance.
4309

4310
    """
4311
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4312
    env["TIMEOUT"] = self.timeout
4313
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4314
    return env, nl, nl
4315

    
4316
  def CheckPrereq(self):
4317
    """Check prerequisites.
4318

4319
    This checks that the instance is in the cluster.
4320

4321
    """
4322
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4323
    assert self.instance is not None, \
4324
      "Cannot retrieve locked instance %s" % self.op.instance_name
4325
    _CheckNodeOnline(self, self.instance.primary_node)
4326

    
4327
  def Exec(self, feedback_fn):
4328
    """Shutdown the instance.
4329

4330
    """
4331
    instance = self.instance
4332
    node_current = instance.primary_node
4333
    timeout = self.timeout
4334
    self.cfg.MarkInstanceDown(instance.name)
4335
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4336
    msg = result.fail_msg
4337
    if msg:
4338
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4339

    
4340
    _ShutdownInstanceDisks(self, instance)
4341

    
4342

    
4343
class LUReinstallInstance(LogicalUnit):
4344
  """Reinstall an instance.
4345

4346
  """
4347
  HPATH = "instance-reinstall"
4348
  HTYPE = constants.HTYPE_INSTANCE
4349
  _OP_REQP = ["instance_name"]
4350
  REQ_BGL = False
4351

    
4352
  def ExpandNames(self):
4353
    self._ExpandAndLockInstance()
4354

    
4355
  def BuildHooksEnv(self):
4356
    """Build hooks env.
4357

4358
    This runs on master, primary and secondary nodes of the instance.
4359

4360
    """
4361
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4362
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4363
    return env, nl, nl
4364

    
4365
  def CheckPrereq(self):
4366
    """Check prerequisites.
4367

4368
    This checks that the instance is in the cluster and is not running.
4369

4370
    """
4371
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4372
    assert instance is not None, \
4373
      "Cannot retrieve locked instance %s" % self.op.instance_name
4374
    _CheckNodeOnline(self, instance.primary_node)
4375

    
4376
    if instance.disk_template == constants.DT_DISKLESS:
4377
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4378
                                 self.op.instance_name,
4379
                                 errors.ECODE_INVAL)
4380
    _CheckInstanceDown(self, instance, "cannot reinstall")
4381

    
4382
    self.op.os_type = getattr(self.op, "os_type", None)
4383
    self.op.force_variant = getattr(self.op, "force_variant", False)
4384
    if self.op.os_type is not None:
4385
      # OS verification
4386
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4387
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4388

    
4389
    self.instance = instance
4390

    
4391
  def Exec(self, feedback_fn):
4392
    """Reinstall the instance.
4393

4394
    """
4395
    inst = self.instance
4396

    
4397
    if self.op.os_type is not None:
4398
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4399
      inst.os = self.op.os_type
4400
      self.cfg.Update(inst, feedback_fn)
4401

    
4402
    _StartInstanceDisks(self, inst, None)
4403
    try:
4404
      feedback_fn("Running the instance OS create scripts...")
4405
      # FIXME: pass debug option from opcode to backend
4406
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4407
                                             self.op.debug_level)
4408
      result.Raise("Could not install OS for instance %s on node %s" %
4409
                   (inst.name, inst.primary_node))
4410
    finally:
4411
      _ShutdownInstanceDisks(self, inst)
4412

    
4413

    
4414
class LURecreateInstanceDisks(LogicalUnit):
4415
  """Recreate an instance's missing disks.
4416

4417
  """
4418
  HPATH = "instance-recreate-disks"
4419
  HTYPE = constants.HTYPE_INSTANCE
4420
  _OP_REQP = ["instance_name", "disks"]
4421
  REQ_BGL = False
4422

    
4423
  def CheckArguments(self):
4424
    """Check the arguments.
4425

4426
    """
4427
    if not isinstance(self.op.disks, list):
4428
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
4429
    for item in self.op.disks:
4430
      if (not isinstance(item, int) or
4431
          item < 0):
4432
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
4433
                                   str(item), errors.ECODE_INVAL)
4434

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

    
4438
  def BuildHooksEnv(self):
4439
    """Build hooks env.
4440

4441
    This runs on master, primary and secondary nodes of the instance.
4442

4443
    """
4444
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4445
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4446
    return env, nl, nl
4447

    
4448
  def CheckPrereq(self):
4449
    """Check prerequisites.
4450

4451
    This checks that the instance is in the cluster and is not running.
4452

4453
    """
4454
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4455
    assert instance is not None, \
4456
      "Cannot retrieve locked instance %s" % self.op.instance_name
4457
    _CheckNodeOnline(self, instance.primary_node)
4458

    
4459
    if instance.disk_template == constants.DT_DISKLESS:
4460
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4461
                                 self.op.instance_name, errors.ECODE_INVAL)
4462
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4463

    
4464
    if not self.op.disks:
4465
      self.op.disks = range(len(instance.disks))
4466
    else:
4467
      for idx in self.op.disks:
4468
        if idx >= len(instance.disks):
4469
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4470
                                     errors.ECODE_INVAL)
4471

    
4472
    self.instance = instance
4473

    
4474
  def Exec(self, feedback_fn):
4475
    """Recreate the disks.
4476

4477
    """
4478
    to_skip = []
4479
    for idx, _ in enumerate(self.instance.disks):
4480
      if idx not in self.op.disks: # disk idx has not been passed in
4481
        to_skip.append(idx)
4482
        continue
4483

    
4484
    _CreateDisks(self, self.instance, to_skip=to_skip)
4485

    
4486

    
4487
class LURenameInstance(LogicalUnit):
4488
  """Rename an instance.
4489

4490
  """
4491
  HPATH = "instance-rename"
4492
  HTYPE = constants.HTYPE_INSTANCE
4493
  _OP_REQP = ["instance_name", "new_name"]
4494

    
4495
  def BuildHooksEnv(self):
4496
    """Build hooks env.
4497

4498
    This runs on master, primary and secondary nodes of the instance.
4499

4500
    """
4501
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4502
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4503
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4504
    return env, nl, nl
4505

    
4506
  def CheckPrereq(self):
4507
    """Check prerequisites.
4508

4509
    This checks that the instance is in the cluster and is not running.
4510

4511
    """
4512
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4513
                                                self.op.instance_name)
4514
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4515
    assert instance is not None
4516
    _CheckNodeOnline(self, instance.primary_node)
4517
    _CheckInstanceDown(self, instance, "cannot rename")
4518
    self.instance = instance
4519

    
4520
    # new name verification
4521
    name_info = utils.GetHostInfo(self.op.new_name)
4522

    
4523
    self.op.new_name = new_name = name_info.name
4524
    instance_list = self.cfg.GetInstanceList()
4525
    if new_name in instance_list:
4526
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4527
                                 new_name, errors.ECODE_EXISTS)
4528

    
4529
    if not getattr(self.op, "ignore_ip", False):
4530
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4531
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4532
                                   (name_info.ip, new_name),
4533
                                   errors.ECODE_NOTUNIQUE)
4534

    
4535

    
4536
  def Exec(self, feedback_fn):
4537
    """Reinstall the instance.
4538

4539
    """
4540
    inst = self.instance
4541
    old_name = inst.name
4542

    
4543
    if inst.disk_template == constants.DT_FILE:
4544
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4545

    
4546
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4547
    # Change the instance lock. This is definitely safe while we hold the BGL
4548
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4549
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4550

    
4551
    # re-read the instance from the configuration after rename
4552
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4553

    
4554
    if inst.disk_template == constants.DT_FILE:
4555
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4556
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4557
                                                     old_file_storage_dir,
4558
                                                     new_file_storage_dir)
4559
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4560
                   " (but the instance has been renamed in Ganeti)" %
4561
                   (inst.primary_node, old_file_storage_dir,
4562
                    new_file_storage_dir))
4563

    
4564
    _StartInstanceDisks(self, inst, None)
4565
    try:
4566
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4567
                                                 old_name, self.op.debug_level)
4568
      msg = result.fail_msg
4569
      if msg:
4570
        msg = ("Could not run OS rename script for instance %s on node %s"
4571
               " (but the instance has been renamed in Ganeti): %s" %
4572
               (inst.name, inst.primary_node, msg))
4573
        self.proc.LogWarning(msg)
4574
    finally:
4575
      _ShutdownInstanceDisks(self, inst)
4576

    
4577

    
4578
class LURemoveInstance(LogicalUnit):
4579
  """Remove an instance.
4580

4581
  """
4582
  HPATH = "instance-remove"
4583
  HTYPE = constants.HTYPE_INSTANCE
4584
  _OP_REQP = ["instance_name", "ignore_failures"]
4585
  REQ_BGL = False
4586

    
4587
  def CheckArguments(self):
4588
    """Check the arguments.
4589

4590
    """
4591
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4592
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4593

    
4594
  def ExpandNames(self):
4595
    self._ExpandAndLockInstance()
4596
    self.needed_locks[locking.LEVEL_NODE] = []
4597
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4598

    
4599
  def DeclareLocks(self, level):
4600
    if level == locking.LEVEL_NODE:
4601
      self._LockInstancesNodes()
4602

    
4603
  def BuildHooksEnv(self):
4604
    """Build hooks env.
4605

4606
    This runs on master, primary and secondary nodes of the instance.
4607

4608
    """
4609
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4610
    env["SHUTDOWN_TIMEOUT"] = self.shutdown_timeout
4611
    nl = [self.cfg.GetMasterNode()]
4612
    nl_post = list(self.instance.all_nodes) + nl
4613
    return env, nl, nl_post
4614

    
4615
  def CheckPrereq(self):
4616
    """Check prerequisites.
4617

4618
    This checks that the instance is in the cluster.
4619

4620
    """
4621
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4622
    assert self.instance is not None, \
4623
      "Cannot retrieve locked instance %s" % self.op.instance_name
4624

    
4625
  def Exec(self, feedback_fn):
4626
    """Remove the instance.
4627

4628
    """
4629
    instance = self.instance
4630
    logging.info("Shutting down instance %s on node %s",
4631
                 instance.name, instance.primary_node)
4632

    
4633
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4634
                                             self.shutdown_timeout)
4635
    msg = result.fail_msg
4636
    if msg:
4637
      if self.op.ignore_failures:
4638
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4639
      else:
4640
        raise errors.OpExecError("Could not shutdown instance %s on"
4641
                                 " node %s: %s" %
4642
                                 (instance.name, instance.primary_node, msg))
4643

    
4644
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
4645

    
4646

    
4647
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
4648
  """Utility function to remove an instance.
4649

4650
  """
4651
  logging.info("Removing block devices for instance %s", instance.name)
4652

    
4653
  if not _RemoveDisks(lu, instance):
4654
    if not ignore_failures:
4655
      raise errors.OpExecError("Can't remove instance's disks")
4656
    feedback_fn("Warning: can't remove instance's disks")
4657

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

    
4660
  lu.cfg.RemoveInstance(instance.name)
4661

    
4662
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
4663
    "Instance lock removal conflict"
4664

    
4665
  # Remove lock for the instance
4666
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4667

    
4668

    
4669
class LUQueryInstances(NoHooksLU):
4670
  """Logical unit for querying instances.
4671

4672
  """
4673
  # pylint: disable-msg=W0142
4674
  _OP_REQP = ["output_fields", "names", "use_locking"]
4675
  REQ_BGL = False
4676
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4677
                    "serial_no", "ctime", "mtime", "uuid"]
4678
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4679
                                    "admin_state",
4680
                                    "disk_template", "ip", "mac", "bridge",
4681
                                    "nic_mode", "nic_link",
4682
                                    "sda_size", "sdb_size", "vcpus", "tags",
4683
                                    "network_port", "beparams",
4684
                                    r"(disk)\.(size)/([0-9]+)",
4685
                                    r"(disk)\.(sizes)", "disk_usage",
4686
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4687
                                    r"(nic)\.(bridge)/([0-9]+)",
4688
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4689
                                    r"(disk|nic)\.(count)",
4690
                                    "hvparams",
4691
                                    ] + _SIMPLE_FIELDS +
4692
                                  ["hv/%s" % name
4693
                                   for name in constants.HVS_PARAMETERS
4694
                                   if name not in constants.HVC_GLOBALS] +
4695
                                  ["be/%s" % name
4696
                                   for name in constants.BES_PARAMETERS])
4697
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4698

    
4699

    
4700
  def ExpandNames(self):
4701
    _CheckOutputFields(static=self._FIELDS_STATIC,
4702
                       dynamic=self._FIELDS_DYNAMIC,
4703
                       selected=self.op.output_fields)
4704

    
4705
    self.needed_locks = {}
4706
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4707
    self.share_locks[locking.LEVEL_NODE] = 1
4708

    
4709
    if self.op.names:
4710
      self.wanted = _GetWantedInstances(self, self.op.names)
4711
    else:
4712
      self.wanted = locking.ALL_SET
4713

    
4714
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4715
    self.do_locking = self.do_node_query and self.op.use_locking
4716
    if self.do_locking:
4717
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4718
      self.needed_locks[locking.LEVEL_NODE] = []
4719
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4720

    
4721
  def DeclareLocks(self, level):
4722
    if level == locking.LEVEL_NODE and self.do_locking:
4723
      self._LockInstancesNodes()
4724

    
4725
  def CheckPrereq(self):
4726
    """Check prerequisites.
4727

4728
    """
4729
    pass
4730

    
4731
  def Exec(self, feedback_fn):
4732
    """Computes the list of nodes and their attributes.
4733

4734
    """
4735
    # pylint: disable-msg=R0912
4736
    # way too many branches here
4737
    all_info = self.cfg.GetAllInstancesInfo()
4738
    if self.wanted == locking.ALL_SET:
4739
      # caller didn't specify instance names, so ordering is not important
4740
      if self.do_locking:
4741
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4742
      else:
4743
        instance_names = all_info.keys()
4744
      instance_names = utils.NiceSort(instance_names)
4745
    else:
4746
      # caller did specify names, so we must keep the ordering
4747
      if self.do_locking:
4748
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4749
      else:
4750
        tgt_set = all_info.keys()
4751
      missing = set(self.wanted).difference(tgt_set)
4752
      if missing:
4753
        raise errors.OpExecError("Some instances were removed before"
4754
                                 " retrieving their data: %s" % missing)
4755
      instance_names = self.wanted
4756

    
4757
    instance_list = [all_info[iname] for iname in instance_names]
4758

    
4759
    # begin data gathering
4760

    
4761
    nodes = frozenset([inst.primary_node for inst in instance_list])
4762
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4763

    
4764
    bad_nodes = []
4765
    off_nodes = []
4766
    if self.do_node_query:
4767
      live_data = {}
4768
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4769
      for name in nodes:
4770
        result = node_data[name]
4771
        if result.offline:
4772
          # offline nodes will be in both lists
4773
          off_nodes.append(name)
4774
        if result.fail_msg:
4775
          bad_nodes.append(name)
4776
        else:
4777
          if result.payload:
4778
            live_data.update(result.payload)
4779
          # else no instance is alive
4780
    else:
4781
      live_data = dict([(name, {}) for name in instance_names])
4782

    
4783
    # end data gathering
4784

    
4785
    HVPREFIX = "hv/"
4786
    BEPREFIX = "be/"
4787
    output = []
4788
    cluster = self.cfg.GetClusterInfo()
4789
    for instance in instance_list:
4790
      iout = []
4791
      i_hv = cluster.FillHV(instance, skip_globals=True)
4792
      i_be = cluster.FillBE(instance)
4793
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
4794
                                 nic.nicparams) for nic in instance.nics]
4795
      for field in self.op.output_fields:
4796
        st_match = self._FIELDS_STATIC.Matches(field)
4797
        if field in self._SIMPLE_FIELDS:
4798
          val = getattr(instance, field)
4799
        elif field == "pnode":
4800
          val = instance.primary_node
4801
        elif field == "snodes":
4802
          val = list(instance.secondary_nodes)
4803
        elif field == "admin_state":
4804
          val = instance.admin_up
4805
        elif field == "oper_state":
4806
          if instance.primary_node in bad_nodes:
4807
            val = None
4808
          else:
4809
            val = bool(live_data.get(instance.name))
4810
        elif field == "status":
4811
          if instance.primary_node in off_nodes:
4812
            val = "ERROR_nodeoffline"
4813
          elif instance.primary_node in bad_nodes:
4814
            val = "ERROR_nodedown"
4815
          else:
4816
            running = bool(live_data.get(instance.name))
4817
            if running:
4818
              if instance.admin_up:
4819
                val = "running"
4820
              else:
4821
                val = "ERROR_up"
4822
            else:
4823
              if instance.admin_up:
4824
                val = "ERROR_down"
4825
              else:
4826
                val = "ADMIN_down"
4827
        elif field == "oper_ram":
4828
          if instance.primary_node in bad_nodes:
4829
            val = None
4830
          elif instance.name in live_data:
4831
            val = live_data[instance.name].get("memory", "?")
4832
          else:
4833
            val = "-"
4834
        elif field == "vcpus":
4835
          val = i_be[constants.BE_VCPUS]
4836
        elif field == "disk_template":
4837
          val = instance.disk_template
4838
        elif field == "ip":
4839
          if instance.nics:
4840
            val = instance.nics[0].ip
4841
          else:
4842
            val = None
4843
        elif field == "nic_mode":
4844
          if instance.nics:
4845
            val = i_nicp[0][constants.NIC_MODE]
4846
          else:
4847
            val = None
4848
        elif field == "nic_link":
4849
          if instance.nics:
4850
            val = i_nicp[0][constants.NIC_LINK]
4851
          else:
4852
            val = None
4853
        elif field == "bridge":
4854
          if (instance.nics and
4855
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4856
            val = i_nicp[0][constants.NIC_LINK]
4857
          else:
4858
            val = None
4859
        elif field == "mac":
4860
          if instance.nics:
4861
            val = instance.nics[0].mac
4862
          else:
4863
            val = None
4864
        elif field == "sda_size" or field == "sdb_size":
4865
          idx = ord(field[2]) - ord('a')
4866
          try:
4867
            val = instance.FindDisk(idx).size
4868
          except errors.OpPrereqError:
4869
            val = None
4870
        elif field == "disk_usage": # total disk usage per node
4871
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4872
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4873
        elif field == "tags":
4874
          val = list(instance.GetTags())
4875
        elif field == "hvparams":
4876
          val = i_hv
4877
        elif (field.startswith(HVPREFIX) and
4878
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
4879
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
4880
          val = i_hv.get(field[len(HVPREFIX):], None)
4881
        elif field == "beparams":
4882
          val = i_be
4883
        elif (field.startswith(BEPREFIX) and
4884
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4885
          val = i_be.get(field[len(BEPREFIX):], None)
4886
        elif st_match and st_match.groups():
4887
          # matches a variable list
4888
          st_groups = st_match.groups()
4889
          if st_groups and st_groups[0] == "disk":
4890
            if st_groups[1] == "count":
4891
              val = len(instance.disks)
4892
            elif st_groups[1] == "sizes":
4893
              val = [disk.size for disk in instance.disks]
4894
            elif st_groups[1] == "size":
4895
              try:
4896
                val = instance.FindDisk(st_groups[2]).size
4897
              except errors.OpPrereqError:
4898
                val = None
4899
            else:
4900
              assert False, "Unhandled disk parameter"
4901
          elif st_groups[0] == "nic":
4902
            if st_groups[1] == "count":
4903
              val = len(instance.nics)
4904
            elif st_groups[1] == "macs":
4905
              val = [nic.mac for nic in instance.nics]
4906
            elif st_groups[1] == "ips":
4907
              val = [nic.ip for nic in instance.nics]
4908
            elif st_groups[1] == "modes":
4909
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4910
            elif st_groups[1] == "links":
4911
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4912
            elif st_groups[1] == "bridges":
4913
              val = []
4914
              for nicp in i_nicp:
4915
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4916
                  val.append(nicp[constants.NIC_LINK])
4917
                else:
4918
                  val.append(None)
4919
            else:
4920
              # index-based item
4921
              nic_idx = int(st_groups[2])
4922
              if nic_idx >= len(instance.nics):
4923
                val = None
4924
              else:
4925
                if st_groups[1] == "mac":
4926
                  val = instance.nics[nic_idx].mac
4927
                elif st_groups[1] == "ip":
4928
                  val = instance.nics[nic_idx].ip
4929
                elif st_groups[1] == "mode":
4930
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4931
                elif st_groups[1] == "link":
4932
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4933
                elif st_groups[1] == "bridge":
4934
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4935
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4936
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4937
                  else:
4938
                    val = None
4939
                else:
4940
                  assert False, "Unhandled NIC parameter"
4941
          else:
4942
            assert False, ("Declared but unhandled variable parameter '%s'" %
4943
                           field)
4944
        else:
4945
          assert False, "Declared but unhandled parameter '%s'" % field
4946
        iout.append(val)
4947
      output.append(iout)
4948

    
4949
    return output
4950

    
4951

    
4952
class LUFailoverInstance(LogicalUnit):
4953
  """Failover an instance.
4954

4955
  """
4956
  HPATH = "instance-failover"
4957
  HTYPE = constants.HTYPE_INSTANCE
4958
  _OP_REQP = ["instance_name", "ignore_consistency"]
4959
  REQ_BGL = False
4960

    
4961
  def CheckArguments(self):
4962
    """Check the arguments.
4963

4964
    """
4965
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4966
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4967

    
4968
  def ExpandNames(self):
4969
    self._ExpandAndLockInstance()
4970
    self.needed_locks[locking.LEVEL_NODE] = []
4971
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4972

    
4973
  def DeclareLocks(self, level):
4974
    if level == locking.LEVEL_NODE:
4975
      self._LockInstancesNodes()
4976

    
4977
  def BuildHooksEnv(self):
4978
    """Build hooks env.
4979

4980
    This runs on master, primary and secondary nodes of the instance.
4981

4982
    """
4983
    instance = self.instance
4984
    source_node = instance.primary_node
4985
    target_node = instance.secondary_nodes[0]
4986
    env = {
4987
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4988
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4989
      "OLD_PRIMARY": source_node,
4990
      "OLD_SECONDARY": target_node,
4991
      "NEW_PRIMARY": target_node,
4992
      "NEW_SECONDARY": source_node,
4993
      }
4994
    env.update(_BuildInstanceHookEnvByObject(self, instance))
4995
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4996
    nl_post = list(nl)
4997
    nl_post.append(source_node)
4998
    return env, nl, nl_post
4999

    
5000
  def CheckPrereq(self):
5001
    """Check prerequisites.
5002

5003
    This checks that the instance is in the cluster.
5004

5005
    """
5006
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5007
    assert self.instance is not None, \
5008
      "Cannot retrieve locked instance %s" % self.op.instance_name
5009

    
5010
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5011
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5012
      raise errors.OpPrereqError("Instance's disk layout is not"
5013
                                 " network mirrored, cannot failover.",
5014
                                 errors.ECODE_STATE)
5015

    
5016
    secondary_nodes = instance.secondary_nodes
5017
    if not secondary_nodes:
5018
      raise errors.ProgrammerError("no secondary node but using "
5019
                                   "a mirrored disk template")
5020

    
5021
    target_node = secondary_nodes[0]
5022
    _CheckNodeOnline(self, target_node)
5023
    _CheckNodeNotDrained(self, target_node)
5024
    if instance.admin_up:
5025
      # check memory requirements on the secondary node
5026
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5027
                           instance.name, bep[constants.BE_MEMORY],
5028
                           instance.hypervisor)
5029
    else:
5030
      self.LogInfo("Not checking memory on the secondary node as"
5031
                   " instance will not be started")
5032

    
5033
    # check bridge existance
5034
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5035

    
5036
  def Exec(self, feedback_fn):
5037
    """Failover an instance.
5038

5039
    The failover is done by shutting it down on its present node and
5040
    starting it on the secondary.
5041

5042
    """
5043
    instance = self.instance
5044

    
5045
    source_node = instance.primary_node
5046
    target_node = instance.secondary_nodes[0]
5047

    
5048
    if instance.admin_up:
5049
      feedback_fn("* checking disk consistency between source and target")
5050
      for dev in instance.disks:
5051
        # for drbd, these are drbd over lvm
5052
        if not _CheckDiskConsistency(self, dev, target_node, False):
5053
          if not self.op.ignore_consistency:
5054
            raise errors.OpExecError("Disk %s is degraded on target node,"
5055
                                     " aborting failover." % dev.iv_name)
5056
    else:
5057
      feedback_fn("* not checking disk consistency as instance is not running")
5058

    
5059
    feedback_fn("* shutting down instance on source node")
5060
    logging.info("Shutting down instance %s on node %s",
5061
                 instance.name, source_node)
5062

    
5063
    result = self.rpc.call_instance_shutdown(source_node, instance,
5064
                                             self.shutdown_timeout)
5065
    msg = result.fail_msg
5066
    if msg:
5067
      if self.op.ignore_consistency:
5068
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5069
                             " Proceeding anyway. Please make sure node"
5070
                             " %s is down. Error details: %s",
5071
                             instance.name, source_node, source_node, msg)
5072
      else:
5073
        raise errors.OpExecError("Could not shutdown instance %s on"
5074
                                 " node %s: %s" %
5075
                                 (instance.name, source_node, msg))
5076

    
5077
    feedback_fn("* deactivating the instance's disks on source node")
5078
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5079
      raise errors.OpExecError("Can't shut down the instance's disks.")
5080

    
5081
    instance.primary_node = target_node
5082
    # distribute new instance config to the other nodes
5083
    self.cfg.Update(instance, feedback_fn)
5084

    
5085
    # Only start the instance if it's marked as up
5086
    if instance.admin_up:
5087
      feedback_fn("* activating the instance's disks on target node")
5088
      logging.info("Starting instance %s on node %s",
5089
                   instance.name, target_node)
5090

    
5091
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5092
                                               ignore_secondaries=True)
5093
      if not disks_ok:
5094
        _ShutdownInstanceDisks(self, instance)
5095
        raise errors.OpExecError("Can't activate the instance's disks")
5096

    
5097
      feedback_fn("* starting the instance on the target node")
5098
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5099
      msg = result.fail_msg
5100
      if msg:
5101
        _ShutdownInstanceDisks(self, instance)
5102
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5103
                                 (instance.name, target_node, msg))
5104

    
5105

    
5106
class LUMigrateInstance(LogicalUnit):
5107
  """Migrate an instance.
5108

5109
  This is migration without shutting down, compared to the failover,
5110
  which is done with shutdown.
5111

5112
  """
5113
  HPATH = "instance-migrate"
5114
  HTYPE = constants.HTYPE_INSTANCE
5115
  _OP_REQP = ["instance_name", "live", "cleanup"]
5116

    
5117
  REQ_BGL = False
5118

    
5119
  def ExpandNames(self):
5120
    self._ExpandAndLockInstance()
5121

    
5122
    self.needed_locks[locking.LEVEL_NODE] = []
5123
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5124

    
5125
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5126
                                       self.op.live, self.op.cleanup)
5127
    self.tasklets = [self._migrater]
5128

    
5129
  def DeclareLocks(self, level):
5130
    if level == locking.LEVEL_NODE:
5131
      self._LockInstancesNodes()
5132

    
5133
  def BuildHooksEnv(self):
5134
    """Build hooks env.
5135

5136
    This runs on master, primary and secondary nodes of the instance.
5137

5138
    """
5139
    instance = self._migrater.instance
5140
    source_node = instance.primary_node
5141
    target_node = instance.secondary_nodes[0]
5142
    env = _BuildInstanceHookEnvByObject(self, instance)
5143
    env["MIGRATE_LIVE"] = self.op.live
5144
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5145
    env.update({
5146
        "OLD_PRIMARY": source_node,
5147
        "OLD_SECONDARY": target_node,
5148
        "NEW_PRIMARY": target_node,
5149
        "NEW_SECONDARY": source_node,
5150
        })
5151
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5152
    nl_post = list(nl)
5153
    nl_post.append(source_node)
5154
    return env, nl, nl_post
5155

    
5156

    
5157
class LUMoveInstance(LogicalUnit):
5158
  """Move an instance by data-copying.
5159

5160
  """
5161
  HPATH = "instance-move"
5162
  HTYPE = constants.HTYPE_INSTANCE
5163
  _OP_REQP = ["instance_name", "target_node"]
5164
  REQ_BGL = False
5165

    
5166
  def CheckArguments(self):
5167
    """Check the arguments.
5168

5169
    """
5170
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
5171
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
5172

    
5173
  def ExpandNames(self):
5174
    self._ExpandAndLockInstance()
5175
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5176
    self.op.target_node = target_node
5177
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5178
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5179

    
5180
  def DeclareLocks(self, level):
5181
    if level == locking.LEVEL_NODE:
5182
      self._LockInstancesNodes(primary_only=True)
5183

    
5184
  def BuildHooksEnv(self):
5185
    """Build hooks env.
5186

5187
    This runs on master, primary and secondary nodes of the instance.
5188

5189
    """
5190
    env = {
5191
      "TARGET_NODE": self.op.target_node,
5192
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
5193
      }
5194
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5195
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5196
                                       self.op.target_node]
5197
    return env, nl, nl
5198

    
5199
  def CheckPrereq(self):
5200
    """Check prerequisites.
5201

5202
    This checks that the instance is in the cluster.
5203

5204
    """
5205
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5206
    assert self.instance is not None, \
5207
      "Cannot retrieve locked instance %s" % self.op.instance_name
5208

    
5209
    node = self.cfg.GetNodeInfo(self.op.target_node)
5210
    assert node is not None, \
5211
      "Cannot retrieve locked node %s" % self.op.target_node
5212

    
5213
    self.target_node = target_node = node.name
5214

    
5215
    if target_node == instance.primary_node:
5216
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5217
                                 (instance.name, target_node),
5218
                                 errors.ECODE_STATE)
5219

    
5220
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5221

    
5222
    for idx, dsk in enumerate(instance.disks):
5223
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5224
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5225
                                   " cannot copy" % idx, errors.ECODE_STATE)
5226

    
5227
    _CheckNodeOnline(self, target_node)
5228
    _CheckNodeNotDrained(self, target_node)
5229

    
5230
    if instance.admin_up:
5231
      # check memory requirements on the secondary node
5232
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5233
                           instance.name, bep[constants.BE_MEMORY],
5234
                           instance.hypervisor)
5235
    else:
5236
      self.LogInfo("Not checking memory on the secondary node as"
5237
                   " instance will not be started")
5238

    
5239
    # check bridge existance
5240
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5241

    
5242
  def Exec(self, feedback_fn):
5243
    """Move an instance.
5244

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

5248
    """
5249
    instance = self.instance
5250

    
5251
    source_node = instance.primary_node
5252
    target_node = self.target_node
5253

    
5254
    self.LogInfo("Shutting down instance %s on source node %s",
5255
                 instance.name, source_node)
5256

    
5257
    result = self.rpc.call_instance_shutdown(source_node, instance,
5258
                                             self.shutdown_timeout)
5259
    msg = result.fail_msg
5260
    if msg:
5261
      if self.op.ignore_consistency:
5262
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5263
                             " Proceeding anyway. Please make sure node"
5264
                             " %s is down. Error details: %s",
5265
                             instance.name, source_node, source_node, msg)
5266
      else:
5267
        raise errors.OpExecError("Could not shutdown instance %s on"
5268
                                 " node %s: %s" %
5269
                                 (instance.name, source_node, msg))
5270

    
5271
    # create the target disks
5272
    try:
5273
      _CreateDisks(self, instance, target_node=target_node)
5274
    except errors.OpExecError:
5275
      self.LogWarning("Device creation failed, reverting...")
5276
      try:
5277
        _RemoveDisks(self, instance, target_node=target_node)
5278
      finally:
5279
        self.cfg.ReleaseDRBDMinors(instance.name)
5280
        raise
5281

    
5282
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5283

    
5284
    errs = []
5285
    # activate, get path, copy the data over
5286
    for idx, disk in enumerate(instance.disks):
5287
      self.LogInfo("Copying data for disk %d", idx)
5288
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5289
                                               instance.name, True)
5290
      if result.fail_msg:
5291
        self.LogWarning("Can't assemble newly created disk %d: %s",
5292
                        idx, result.fail_msg)
5293
        errs.append(result.fail_msg)
5294
        break
5295
      dev_path = result.payload
5296
      result = self.rpc.call_blockdev_export(source_node, disk,
5297
                                             target_node, dev_path,
5298
                                             cluster_name)
5299
      if result.fail_msg:
5300
        self.LogWarning("Can't copy data over for disk %d: %s",
5301
                        idx, result.fail_msg)
5302
        errs.append(result.fail_msg)
5303
        break
5304

    
5305
    if errs:
5306
      self.LogWarning("Some disks failed to copy, aborting")
5307
      try:
5308
        _RemoveDisks(self, instance, target_node=target_node)
5309
      finally:
5310
        self.cfg.ReleaseDRBDMinors(instance.name)
5311
        raise errors.OpExecError("Errors during disk copy: %s" %
5312
                                 (",".join(errs),))
5313

    
5314
    instance.primary_node = target_node
5315
    self.cfg.Update(instance, feedback_fn)
5316

    
5317
    self.LogInfo("Removing the disks on the original node")
5318
    _RemoveDisks(self, instance, target_node=source_node)
5319

    
5320
    # Only start the instance if it's marked as up
5321
    if instance.admin_up:
5322
      self.LogInfo("Starting instance %s on node %s",
5323
                   instance.name, target_node)
5324

    
5325
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5326
                                           ignore_secondaries=True)
5327
      if not disks_ok:
5328
        _ShutdownInstanceDisks(self, instance)
5329
        raise errors.OpExecError("Can't activate the instance's disks")
5330

    
5331
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5332
      msg = result.fail_msg
5333
      if msg:
5334
        _ShutdownInstanceDisks(self, instance)
5335
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5336
                                 (instance.name, target_node, msg))
5337

    
5338

    
5339
class LUMigrateNode(LogicalUnit):
5340
  """Migrate all instances from a node.
5341

5342
  """
5343
  HPATH = "node-migrate"
5344
  HTYPE = constants.HTYPE_NODE
5345
  _OP_REQP = ["node_name", "live"]
5346
  REQ_BGL = False
5347

    
5348
  def ExpandNames(self):
5349
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5350

    
5351
    self.needed_locks = {
5352
      locking.LEVEL_NODE: [self.op.node_name],
5353
      }
5354

    
5355
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5356

    
5357
    # Create tasklets for migrating instances for all instances on this node
5358
    names = []
5359
    tasklets = []
5360

    
5361
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5362
      logging.debug("Migrating instance %s", inst.name)
5363
      names.append(inst.name)
5364

    
5365
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
5366

    
5367
    self.tasklets = tasklets
5368

    
5369
    # Declare instance locks
5370
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5371

    
5372
  def DeclareLocks(self, level):
5373
    if level == locking.LEVEL_NODE:
5374
      self._LockInstancesNodes()
5375

    
5376
  def BuildHooksEnv(self):
5377
    """Build hooks env.
5378

5379
    This runs on the master, the primary and all the secondaries.
5380

5381
    """
5382
    env = {
5383
      "NODE_NAME": self.op.node_name,
5384
      }
5385

    
5386
    nl = [self.cfg.GetMasterNode()]
5387

    
5388
    return (env, nl, nl)
5389

    
5390

    
5391
class TLMigrateInstance(Tasklet):
5392
  def __init__(self, lu, instance_name, live, cleanup):
5393
    """Initializes this class.
5394

5395
    """
5396
    Tasklet.__init__(self, lu)
5397

    
5398
    # Parameters
5399
    self.instance_name = instance_name
5400
    self.live = live
5401
    self.cleanup = cleanup
5402

    
5403
  def CheckPrereq(self):
5404
    """Check prerequisites.
5405

5406
    This checks that the instance is in the cluster.
5407

5408
    """
5409
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5410
    instance = self.cfg.GetInstanceInfo(instance_name)
5411
    assert instance is not None
5412

    
5413
    if instance.disk_template != constants.DT_DRBD8:
5414
      raise errors.OpPrereqError("Instance's disk layout is not"
5415
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5416

    
5417
    secondary_nodes = instance.secondary_nodes
5418
    if not secondary_nodes:
5419
      raise errors.ConfigurationError("No secondary node but using"
5420
                                      " drbd8 disk template")
5421

    
5422
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5423

    
5424
    target_node = secondary_nodes[0]
5425
    # check memory requirements on the secondary node
5426
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
5427
                         instance.name, i_be[constants.BE_MEMORY],
5428
                         instance.hypervisor)
5429

    
5430
    # check bridge existance
5431
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5432

    
5433
    if not self.cleanup:
5434
      _CheckNodeNotDrained(self, target_node)
5435
      result = self.rpc.call_instance_migratable(instance.primary_node,
5436
                                                 instance)
5437
      result.Raise("Can't migrate, please use failover",
5438
                   prereq=True, ecode=errors.ECODE_STATE)
5439

    
5440
    self.instance = instance
5441

    
5442
  def _WaitUntilSync(self):
5443
    """Poll with custom rpc for disk sync.
5444

5445
    This uses our own step-based rpc call.
5446

5447
    """
5448
    self.feedback_fn("* wait until resync is done")
5449
    all_done = False
5450
    while not all_done:
5451
      all_done = True
5452
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5453
                                            self.nodes_ip,
5454
                                            self.instance.disks)
5455
      min_percent = 100
5456
      for node, nres in result.items():
5457
        nres.Raise("Cannot resync disks on node %s" % node)
5458
        node_done, node_percent = nres.payload
5459
        all_done = all_done and node_done
5460
        if node_percent is not None:
5461
          min_percent = min(min_percent, node_percent)
5462
      if not all_done:
5463
        if min_percent < 100:
5464
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5465
        time.sleep(2)
5466

    
5467
  def _EnsureSecondary(self, node):
5468
    """Demote a node to secondary.
5469

5470
    """
5471
    self.feedback_fn("* switching node %s to secondary mode" % node)
5472

    
5473
    for dev in self.instance.disks:
5474
      self.cfg.SetDiskID(dev, node)
5475

    
5476
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5477
                                          self.instance.disks)
5478
    result.Raise("Cannot change disk to secondary on node %s" % node)
5479

    
5480
  def _GoStandalone(self):
5481
    """Disconnect from the network.
5482

5483
    """
5484
    self.feedback_fn("* changing into standalone mode")
5485
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5486
                                               self.instance.disks)
5487
    for node, nres in result.items():
5488
      nres.Raise("Cannot disconnect disks node %s" % node)
5489

    
5490
  def _GoReconnect(self, multimaster):
5491
    """Reconnect to the network.
5492

5493
    """
5494
    if multimaster:
5495
      msg = "dual-master"
5496
    else:
5497
      msg = "single-master"
5498
    self.feedback_fn("* changing disks into %s mode" % msg)
5499
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5500
                                           self.instance.disks,
5501
                                           self.instance.name, multimaster)
5502
    for node, nres in result.items():
5503
      nres.Raise("Cannot change disks config on node %s" % node)
5504

    
5505
  def _ExecCleanup(self):
5506
    """Try to cleanup after a failed migration.
5507

5508
    The cleanup is done by:
5509
      - check that the instance is running only on one node
5510
        (and update the config if needed)
5511
      - change disks on its secondary node to secondary
5512
      - wait until disks are fully synchronized
5513
      - disconnect from the network
5514
      - change disks into single-master mode
5515
      - wait again until disks are fully synchronized
5516

5517
    """
5518
    instance = self.instance
5519
    target_node = self.target_node
5520
    source_node = self.source_node
5521

    
5522
    # check running on only one node
5523
    self.feedback_fn("* checking where the instance actually runs"
5524
                     " (if this hangs, the hypervisor might be in"
5525
                     " a bad state)")
5526
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5527
    for node, result in ins_l.items():
5528
      result.Raise("Can't contact node %s" % node)
5529

    
5530
    runningon_source = instance.name in ins_l[source_node].payload
5531
    runningon_target = instance.name in ins_l[target_node].payload
5532

    
5533
    if runningon_source and runningon_target:
5534
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5535
                               " or the hypervisor is confused. You will have"
5536
                               " to ensure manually that it runs only on one"
5537
                               " and restart this operation.")
5538

    
5539
    if not (runningon_source or runningon_target):
5540
      raise errors.OpExecError("Instance does not seem to be running at all."
5541
                               " In this case, it's safer to repair by"
5542
                               " running 'gnt-instance stop' to ensure disk"
5543
                               " shutdown, and then restarting it.")
5544

    
5545
    if runningon_target:
5546
      # the migration has actually succeeded, we need to update the config
5547
      self.feedback_fn("* instance running on secondary node (%s),"
5548
                       " updating config" % target_node)
5549
      instance.primary_node = target_node
5550
      self.cfg.Update(instance, self.feedback_fn)
5551
      demoted_node = source_node
5552
    else:
5553
      self.feedback_fn("* instance confirmed to be running on its"
5554
                       " primary node (%s)" % source_node)
5555
      demoted_node = target_node
5556

    
5557
    self._EnsureSecondary(demoted_node)
5558
    try:
5559
      self._WaitUntilSync()
5560
    except errors.OpExecError:
5561
      # we ignore here errors, since if the device is standalone, it
5562
      # won't be able to sync
5563
      pass
5564
    self._GoStandalone()
5565
    self._GoReconnect(False)
5566
    self._WaitUntilSync()
5567

    
5568
    self.feedback_fn("* done")
5569

    
5570
  def _RevertDiskStatus(self):
5571
    """Try to revert the disk status after a failed migration.
5572

5573
    """
5574
    target_node = self.target_node
5575
    try:
5576
      self._EnsureSecondary(target_node)
5577
      self._GoStandalone()
5578
      self._GoReconnect(False)
5579
      self._WaitUntilSync()
5580
    except errors.OpExecError, err:
5581
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5582
                         " drives: error '%s'\n"
5583
                         "Please look and recover the instance status" %
5584
                         str(err))
5585

    
5586
  def _AbortMigration(self):
5587
    """Call the hypervisor code to abort a started migration.
5588

5589
    """
5590
    instance = self.instance
5591
    target_node = self.target_node
5592
    migration_info = self.migration_info
5593

    
5594
    abort_result = self.rpc.call_finalize_migration(target_node,
5595
                                                    instance,
5596
                                                    migration_info,
5597
                                                    False)
5598
    abort_msg = abort_result.fail_msg
5599
    if abort_msg:
5600
      logging.error("Aborting migration failed on target node %s: %s",
5601
                    target_node, abort_msg)
5602
      # Don't raise an exception here, as we stil have to try to revert the
5603
      # disk status, even if this step failed.
5604

    
5605
  def _ExecMigration(self):
5606
    """Migrate an instance.
5607

5608
    The migrate is done by:
5609
      - change the disks into dual-master mode
5610
      - wait until disks are fully synchronized again
5611
      - migrate the instance
5612
      - change disks on the new secondary node (the old primary) to secondary
5613
      - wait until disks are fully synchronized
5614
      - change disks into single-master mode
5615

5616
    """
5617
    instance = self.instance
5618
    target_node = self.target_node
5619
    source_node = self.source_node
5620

    
5621
    self.feedback_fn("* checking disk consistency between source and target")
5622
    for dev in instance.disks:
5623
      if not _CheckDiskConsistency(self, dev, target_node, False):
5624
        raise errors.OpExecError("Disk %s is degraded or not fully"
5625
                                 " synchronized on target node,"
5626
                                 " aborting migrate." % dev.iv_name)
5627

    
5628
    # First get the migration information from the remote node
5629
    result = self.rpc.call_migration_info(source_node, instance)
5630
    msg = result.fail_msg
5631
    if msg:
5632
      log_err = ("Failed fetching source migration information from %s: %s" %
5633
                 (source_node, msg))
5634
      logging.error(log_err)
5635
      raise errors.OpExecError(log_err)
5636

    
5637
    self.migration_info = migration_info = result.payload
5638

    
5639
    # Then switch the disks to master/master mode
5640
    self._EnsureSecondary(target_node)
5641
    self._GoStandalone()
5642
    self._GoReconnect(True)
5643
    self._WaitUntilSync()
5644

    
5645
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5646
    result = self.rpc.call_accept_instance(target_node,
5647
                                           instance,
5648
                                           migration_info,
5649
                                           self.nodes_ip[target_node])
5650

    
5651
    msg = result.fail_msg
5652
    if msg:
5653
      logging.error("Instance pre-migration failed, trying to revert"
5654
                    " disk status: %s", msg)
5655
      self.feedback_fn("Pre-migration failed, aborting")
5656
      self._AbortMigration()
5657
      self._RevertDiskStatus()
5658
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5659
                               (instance.name, msg))
5660

    
5661
    self.feedback_fn("* migrating instance to %s" % target_node)
5662
    time.sleep(10)
5663
    result = self.rpc.call_instance_migrate(source_node, instance,
5664
                                            self.nodes_ip[target_node],
5665
                                            self.live)
5666
    msg = result.fail_msg
5667
    if msg:
5668
      logging.error("Instance migration failed, trying to revert"
5669
                    " disk status: %s", msg)
5670
      self.feedback_fn("Migration failed, aborting")
5671
      self._AbortMigration()
5672
      self._RevertDiskStatus()
5673
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5674
                               (instance.name, msg))
5675
    time.sleep(10)
5676

    
5677
    instance.primary_node = target_node
5678
    # distribute new instance config to the other nodes
5679
    self.cfg.Update(instance, self.feedback_fn)
5680

    
5681
    result = self.rpc.call_finalize_migration(target_node,
5682
                                              instance,
5683
                                              migration_info,
5684
                                              True)
5685
    msg = result.fail_msg
5686
    if msg:
5687
      logging.error("Instance migration succeeded, but finalization failed:"
5688
                    " %s", msg)
5689
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5690
                               msg)
5691

    
5692
    self._EnsureSecondary(source_node)
5693
    self._WaitUntilSync()
5694
    self._GoStandalone()
5695
    self._GoReconnect(False)
5696
    self._WaitUntilSync()
5697

    
5698
    self.feedback_fn("* done")
5699

    
5700
  def Exec(self, feedback_fn):
5701
    """Perform the migration.
5702

5703
    """
5704
    feedback_fn("Migrating instance %s" % self.instance.name)
5705

    
5706
    self.feedback_fn = feedback_fn
5707

    
5708
    self.source_node = self.instance.primary_node
5709
    self.target_node = self.instance.secondary_nodes[0]
5710
    self.all_nodes = [self.source_node, self.target_node]
5711
    self.nodes_ip = {
5712
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5713
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5714
      }
5715

    
5716
    if self.cleanup:
5717
      return self._ExecCleanup()
5718
    else:
5719
      return self._ExecMigration()
5720

    
5721

    
5722
def _CreateBlockDev(lu, node, instance, device, force_create,
5723
                    info, force_open):
5724
  """Create a tree of block devices on a given node.
5725

5726
  If this device type has to be created on secondaries, create it and
5727
  all its children.
5728

5729
  If not, just recurse to children keeping the same 'force' value.
5730

5731
  @param lu: the lu on whose behalf we execute
5732
  @param node: the node on which to create the device
5733
  @type instance: L{objects.Instance}
5734
  @param instance: the instance which owns the device
5735
  @type device: L{objects.Disk}
5736
  @param device: the device to create
5737
  @type force_create: boolean
5738
  @param force_create: whether to force creation of this device; this
5739
      will be change to True whenever we find a device which has
5740
      CreateOnSecondary() attribute
5741
  @param info: the extra 'metadata' we should attach to the device
5742
      (this will be represented as a LVM tag)
5743
  @type force_open: boolean
5744
  @param force_open: this parameter will be passes to the
5745
      L{backend.BlockdevCreate} function where it specifies
5746
      whether we run on primary or not, and it affects both
5747
      the child assembly and the device own Open() execution
5748

5749
  """
5750
  if device.CreateOnSecondary():
5751
    force_create = True
5752

    
5753
  if device.children:
5754
    for child in device.children:
5755
      _CreateBlockDev(lu, node, instance, child, force_create,
5756
                      info, force_open)
5757

    
5758
  if not force_create:
5759
    return
5760

    
5761
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5762

    
5763

    
5764
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5765
  """Create a single block device on a given node.
5766

5767
  This will not recurse over children of the device, so they must be
5768
  created in advance.
5769

5770
  @param lu: the lu on whose behalf we execute
5771
  @param node: the node on which to create the device
5772
  @type instance: L{objects.Instance}
5773
  @param instance: the instance which owns the device
5774
  @type device: L{objects.Disk}
5775
  @param device: the device to create
5776
  @param info: the extra 'metadata' we should attach to the device
5777
      (this will be represented as a LVM tag)
5778
  @type force_open: boolean
5779
  @param force_open: this parameter will be passes to the
5780
      L{backend.BlockdevCreate} function where it specifies
5781
      whether we run on primary or not, and it affects both
5782
      the child assembly and the device own Open() execution
5783

5784
  """
5785
  lu.cfg.SetDiskID(device, node)
5786
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5787
                                       instance.name, force_open, info)
5788
  result.Raise("Can't create block device %s on"
5789
               " node %s for instance %s" % (device, node, instance.name))
5790
  if device.physical_id is None:
5791
    device.physical_id = result.payload
5792

    
5793

    
5794
def _GenerateUniqueNames(lu, exts):
5795
  """Generate a suitable LV name.
5796

5797
  This will generate a logical volume name for the given instance.
5798

5799
  """
5800
  results = []
5801
  for val in exts:
5802
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
5803
    results.append("%s%s" % (new_id, val))
5804
  return results
5805

    
5806

    
5807
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5808
                         p_minor, s_minor):
5809
  """Generate a drbd8 device complete with its children.
5810

5811
  """
5812
  port = lu.cfg.AllocatePort()
5813
  vgname = lu.cfg.GetVGName()
5814
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
5815
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5816
                          logical_id=(vgname, names[0]))
5817
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5818
                          logical_id=(vgname, names[1]))
5819
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5820
                          logical_id=(primary, secondary, port,
5821
                                      p_minor, s_minor,
5822
                                      shared_secret),
5823
                          children=[dev_data, dev_meta],
5824
                          iv_name=iv_name)
5825
  return drbd_dev
5826

    
5827

    
5828
def _GenerateDiskTemplate(lu, template_name,
5829
                          instance_name, primary_node,
5830
                          secondary_nodes, disk_info,
5831
                          file_storage_dir, file_driver,
5832
                          base_index):
5833
  """Generate the entire disk layout for a given template type.
5834

5835
  """
5836
  #TODO: compute space requirements
5837

    
5838
  vgname = lu.cfg.GetVGName()
5839
  disk_count = len(disk_info)
5840
  disks = []
5841
  if template_name == constants.DT_DISKLESS:
5842
    pass
5843
  elif template_name == constants.DT_PLAIN:
5844
    if len(secondary_nodes) != 0:
5845
      raise errors.ProgrammerError("Wrong template configuration")
5846

    
5847
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5848
                                      for i in range(disk_count)])
5849
    for idx, disk in enumerate(disk_info):
5850
      disk_index = idx + base_index
5851
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5852
                              logical_id=(vgname, names[idx]),
5853
                              iv_name="disk/%d" % disk_index,
5854
                              mode=disk["mode"])
5855
      disks.append(disk_dev)
5856
  elif template_name == constants.DT_DRBD8:
5857
    if len(secondary_nodes) != 1:
5858
      raise errors.ProgrammerError("Wrong template configuration")
5859
    remote_node = secondary_nodes[0]
5860
    minors = lu.cfg.AllocateDRBDMinor(
5861
      [primary_node, remote_node] * len(disk_info), instance_name)
5862

    
5863
    names = []
5864
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5865
                                               for i in range(disk_count)]):
5866
      names.append(lv_prefix + "_data")
5867
      names.append(lv_prefix + "_meta")
5868
    for idx, disk in enumerate(disk_info):
5869
      disk_index = idx + base_index
5870
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5871
                                      disk["size"], names[idx*2:idx*2+2],
5872
                                      "disk/%d" % disk_index,
5873
                                      minors[idx*2], minors[idx*2+1])
5874
      disk_dev.mode = disk["mode"]
5875
      disks.append(disk_dev)
5876
  elif template_name == constants.DT_FILE:
5877
    if len(secondary_nodes) != 0:
5878
      raise errors.ProgrammerError("Wrong template configuration")
5879

    
5880
    _RequireFileStorage()
5881

    
5882
    for idx, disk in enumerate(disk_info):
5883
      disk_index = idx + base_index
5884
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5885
                              iv_name="disk/%d" % disk_index,
5886
                              logical_id=(file_driver,
5887
                                          "%s/disk%d" % (file_storage_dir,
5888
                                                         disk_index)),
5889
                              mode=disk["mode"])
5890
      disks.append(disk_dev)
5891
  else:
5892
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5893
  return disks
5894

    
5895

    
5896
def _GetInstanceInfoText(instance):
5897
  """Compute that text that should be added to the disk's metadata.
5898

5899
  """
5900
  return "originstname+%s" % instance.name
5901

    
5902

    
5903
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5904
  """Create all disks for an instance.
5905

5906
  This abstracts away some work from AddInstance.
5907

5908
  @type lu: L{LogicalUnit}
5909
  @param lu: the logical unit on whose behalf we execute
5910
  @type instance: L{objects.Instance}
5911
  @param instance: the instance whose disks we should create
5912
  @type to_skip: list
5913
  @param to_skip: list of indices to skip
5914
  @type target_node: string
5915
  @param target_node: if passed, overrides the target node for creation
5916
  @rtype: boolean
5917
  @return: the success of the creation
5918

5919
  """
5920
  info = _GetInstanceInfoText(instance)
5921
  if target_node is None:
5922
    pnode = instance.primary_node
5923
    all_nodes = instance.all_nodes
5924
  else:
5925
    pnode = target_node
5926
    all_nodes = [pnode]
5927

    
5928
  if instance.disk_template == constants.DT_FILE:
5929
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5930
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5931

    
5932
    result.Raise("Failed to create directory '%s' on"
5933
                 " node %s" % (file_storage_dir, pnode))
5934

    
5935
  # Note: this needs to be kept in sync with adding of disks in
5936
  # LUSetInstanceParams
5937
  for idx, device in enumerate(instance.disks):
5938
    if to_skip and idx in to_skip:
5939
      continue
5940
    logging.info("Creating volume %s for instance %s",
5941
                 device.iv_name, instance.name)
5942
    #HARDCODE
5943
    for node in all_nodes:
5944
      f_create = node == pnode
5945
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5946

    
5947

    
5948
def _RemoveDisks(lu, instance, target_node=None):
5949
  """Remove all disks for an instance.
5950

5951
  This abstracts away some work from `AddInstance()` and
5952
  `RemoveInstance()`. Note that in case some of the devices couldn't
5953
  be removed, the removal will continue with the other ones (compare
5954
  with `_CreateDisks()`).
5955

5956
  @type lu: L{LogicalUnit}
5957
  @param lu: the logical unit on whose behalf we execute
5958
  @type instance: L{objects.Instance}
5959
  @param instance: the instance whose disks we should remove
5960
  @type target_node: string
5961
  @param target_node: used to override the node on which to remove the disks
5962
  @rtype: boolean
5963
  @return: the success of the removal
5964

5965
  """
5966
  logging.info("Removing block devices for instance %s", instance.name)
5967

    
5968
  all_result = True
5969
  for device in instance.disks:
5970
    if target_node:
5971
      edata = [(target_node, device)]
5972
    else:
5973
      edata = device.ComputeNodeTree(instance.primary_node)
5974
    for node, disk in edata:
5975
      lu.cfg.SetDiskID(disk, node)
5976
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5977
      if msg:
5978
        lu.LogWarning("Could not remove block device %s on node %s,"
5979
                      " continuing anyway: %s", device.iv_name, node, msg)
5980
        all_result = False
5981

    
5982
  if instance.disk_template == constants.DT_FILE:
5983
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5984
    if target_node:
5985
      tgt = target_node
5986
    else:
5987
      tgt = instance.primary_node
5988
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5989
    if result.fail_msg:
5990
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5991
                    file_storage_dir, instance.primary_node, result.fail_msg)
5992
      all_result = False
5993

    
5994
  return all_result
5995

    
5996

    
5997
def _ComputeDiskSize(disk_template, disks):
5998
  """Compute disk size requirements in the volume group
5999

6000
  """
6001
  # Required free disk space as a function of disk and swap space
6002
  req_size_dict = {
6003
    constants.DT_DISKLESS: None,
6004
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6005
    # 128 MB are added for drbd metadata for each disk
6006
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6007
    constants.DT_FILE: None,
6008
  }
6009

    
6010
  if disk_template not in req_size_dict:
6011
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6012
                                 " is unknown" %  disk_template)
6013

    
6014
  return req_size_dict[disk_template]
6015

    
6016

    
6017
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6018
  """Hypervisor parameter validation.
6019

6020
  This function abstract the hypervisor parameter validation to be
6021
  used in both instance create and instance modify.
6022

6023
  @type lu: L{LogicalUnit}
6024
  @param lu: the logical unit for which we check
6025
  @type nodenames: list
6026
  @param nodenames: the list of nodes on which we should check
6027
  @type hvname: string
6028
  @param hvname: the name of the hypervisor we should use
6029
  @type hvparams: dict
6030
  @param hvparams: the parameters which we need to check
6031
  @raise errors.OpPrereqError: if the parameters are not valid
6032

6033
  """
6034
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6035
                                                  hvname,
6036
                                                  hvparams)
6037
  for node in nodenames:
6038
    info = hvinfo[node]
6039
    if info.offline:
6040
      continue
6041
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6042

    
6043

    
6044
class LUCreateInstance(LogicalUnit):
6045
  """Create an instance.
6046

6047
  """
6048
  HPATH = "instance-add"
6049
  HTYPE = constants.HTYPE_INSTANCE
6050
  _OP_REQP = ["instance_name", "disks",
6051
              "mode", "start",
6052
              "wait_for_sync", "ip_check", "nics",
6053
              "hvparams", "beparams"]
6054
  REQ_BGL = False
6055

    
6056
  def CheckArguments(self):
6057
    """Check arguments.
6058

6059
    """
6060
    # set optional parameters to none if they don't exist
6061
    for attr in ["pnode", "snode", "iallocator", "hypervisor",
6062
                 "disk_template", "identify_defaults"]:
6063
      if not hasattr(self.op, attr):
6064
        setattr(self.op, attr, None)
6065

    
6066
    # do not require name_check to ease forward/backward compatibility
6067
    # for tools
6068
    if not hasattr(self.op, "name_check"):
6069
      self.op.name_check = True
6070
    if not hasattr(self.op, "no_install"):
6071
      self.op.no_install = False
6072
    if self.op.no_install and self.op.start:
6073
      self.LogInfo("No-installation mode selected, disabling startup")
6074
      self.op.start = False
6075
    # validate/normalize the instance name
6076
    self.op.instance_name = utils.HostInfo.NormalizeName(self.op.instance_name)
6077
    if self.op.ip_check and not self.op.name_check:
6078
      # TODO: make the ip check more flexible and not depend on the name check
6079
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
6080
                                 errors.ECODE_INVAL)
6081
    # check disk information: either all adopt, or no adopt
6082
    has_adopt = has_no_adopt = False
6083
    for disk in self.op.disks:
6084
      if "adopt" in disk:
6085
        has_adopt = True
6086
      else:
6087
        has_no_adopt = True
6088
    if has_adopt and has_no_adopt:
6089
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6090
                                 errors.ECODE_INVAL)
6091
    if has_adopt:
6092
      if self.op.disk_template != constants.DT_PLAIN:
6093
        raise errors.OpPrereqError("Disk adoption is only supported for the"
6094
                                   " 'plain' disk template",
6095
                                   errors.ECODE_INVAL)
6096
      if self.op.iallocator is not None:
6097
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6098
                                   " iallocator script", errors.ECODE_INVAL)
6099
      if self.op.mode == constants.INSTANCE_IMPORT:
6100
        raise errors.OpPrereqError("Disk adoption not allowed for"
6101
                                   " instance import", errors.ECODE_INVAL)
6102

    
6103
    self.adopt_disks = has_adopt
6104

    
6105
    # verify creation mode
6106
    if self.op.mode not in constants.INSTANCE_CREATE_MODES:
6107
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
6108
                                 self.op.mode, errors.ECODE_INVAL)
6109

    
6110
    # instance name verification
6111
    if self.op.name_check:
6112
      self.hostname1 = utils.GetHostInfo(self.op.instance_name)
6113
      self.op.instance_name = self.hostname1.name
6114
      # used in CheckPrereq for ip ping check
6115
      self.check_ip = self.hostname1.ip
6116
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6117
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6118
                                 errors.ECODE_INVAL)
6119
    else:
6120
      self.check_ip = None
6121

    
6122
    # file storage checks
6123
    if (self.op.file_driver and
6124
        not self.op.file_driver in constants.FILE_DRIVER):
6125
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6126
                                 self.op.file_driver, errors.ECODE_INVAL)
6127

    
6128
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6129
      raise errors.OpPrereqError("File storage directory path not absolute",
6130
                                 errors.ECODE_INVAL)
6131

    
6132
    ### Node/iallocator related checks
6133
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
6134
      raise errors.OpPrereqError("One and only one of iallocator and primary"
6135
                                 " node must be given",
6136
                                 errors.ECODE_INVAL)
6137

    
6138
    self._cds = _GetClusterDomainSecret()
6139

    
6140
    if self.op.mode == constants.INSTANCE_IMPORT:
6141
      # On import force_variant must be True, because if we forced it at
6142
      # initial install, our only chance when importing it back is that it
6143
      # works again!
6144
      self.op.force_variant = True
6145

    
6146
      if self.op.no_install:
6147
        self.LogInfo("No-installation mode has no effect during import")
6148

    
6149
    elif self.op.mode == constants.INSTANCE_CREATE:
6150
      if getattr(self.op, "os_type", None) is None:
6151
        raise errors.OpPrereqError("No guest OS specified",
6152
                                   errors.ECODE_INVAL)
6153
      self.op.force_variant = getattr(self.op, "force_variant", False)
6154
      if self.op.disk_template is None:
6155
        raise errors.OpPrereqError("No disk template specified",
6156
                                   errors.ECODE_INVAL)
6157

    
6158
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6159
      # Check handshake to ensure both clusters have the same domain secret
6160
      src_handshake = getattr(self.op, "source_handshake", None)
6161
      if not src_handshake:
6162
        raise errors.OpPrereqError("Missing source handshake",
6163
                                   errors.ECODE_INVAL)
6164

    
6165
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6166
                                                           src_handshake)
6167
      if errmsg:
6168
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6169
                                   errors.ECODE_INVAL)
6170

    
6171
      # Load and check source CA
6172
      self.source_x509_ca_pem = getattr(self.op, "source_x509_ca", None)
6173
      if not self.source_x509_ca_pem:
6174
        raise errors.OpPrereqError("Missing source X509 CA",
6175
                                   errors.ECODE_INVAL)
6176

    
6177
      try:
6178
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6179
                                                    self._cds)
6180
      except OpenSSL.crypto.Error, err:
6181
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6182
                                   (err, ), errors.ECODE_INVAL)
6183

    
6184
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6185
      if errcode is not None:
6186
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6187
                                   errors.ECODE_INVAL)
6188

    
6189
      self.source_x509_ca = cert
6190

    
6191
      src_instance_name = getattr(self.op, "source_instance_name", None)
6192
      if not src_instance_name:
6193
        raise errors.OpPrereqError("Missing source instance name",
6194
                                   errors.ECODE_INVAL)
6195

    
6196
      self.source_instance_name = \
6197
        utils.GetHostInfo(utils.HostInfo.NormalizeName(src_instance_name)).name
6198

    
6199
    else:
6200
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6201
                                 self.op.mode, errors.ECODE_INVAL)
6202

    
6203
  def ExpandNames(self):
6204
    """ExpandNames for CreateInstance.
6205

6206
    Figure out the right locks for instance creation.
6207

6208
    """
6209
    self.needed_locks = {}
6210

    
6211
    instance_name = self.op.instance_name
6212
    # this is just a preventive check, but someone might still add this
6213
    # instance in the meantime, and creation will fail at lock-add time
6214
    if instance_name in self.cfg.GetInstanceList():
6215
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6216
                                 instance_name, errors.ECODE_EXISTS)
6217

    
6218
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6219

    
6220
    if self.op.iallocator:
6221
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6222
    else:
6223
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6224
      nodelist = [self.op.pnode]
6225
      if self.op.snode is not None:
6226
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6227
        nodelist.append(self.op.snode)
6228
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6229

    
6230
    # in case of import lock the source node too
6231
    if self.op.mode == constants.INSTANCE_IMPORT:
6232
      src_node = getattr(self.op, "src_node", None)
6233
      src_path = getattr(self.op, "src_path", None)
6234

    
6235
      if src_path is None:
6236
        self.op.src_path = src_path = self.op.instance_name
6237

    
6238
      if src_node is None:
6239
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6240
        self.op.src_node = None
6241
        if os.path.isabs(src_path):
6242
          raise errors.OpPrereqError("Importing an instance from an absolute"
6243
                                     " path requires a source node option.",
6244
                                     errors.ECODE_INVAL)
6245
      else:
6246
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6247
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6248
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6249
        if not os.path.isabs(src_path):
6250
          self.op.src_path = src_path = \
6251
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6252

    
6253
  def _RunAllocator(self):
6254
    """Run the allocator based on input opcode.
6255

6256
    """
6257
    nics = [n.ToDict() for n in self.nics]
6258
    ial = IAllocator(self.cfg, self.rpc,
6259
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6260
                     name=self.op.instance_name,
6261
                     disk_template=self.op.disk_template,
6262
                     tags=[],
6263
                     os=self.op.os_type,
6264
                     vcpus=self.be_full[constants.BE_VCPUS],
6265
                     mem_size=self.be_full[constants.BE_MEMORY],
6266
                     disks=self.disks,
6267
                     nics=nics,
6268
                     hypervisor=self.op.hypervisor,
6269
                     )
6270

    
6271
    ial.Run(self.op.iallocator)
6272

    
6273
    if not ial.success:
6274
      raise errors.OpPrereqError("Can't compute nodes using"
6275
                                 " iallocator '%s': %s" %
6276
                                 (self.op.iallocator, ial.info),
6277
                                 errors.ECODE_NORES)
6278
    if len(ial.result) != ial.required_nodes:
6279
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6280
                                 " of nodes (%s), required %s" %
6281
                                 (self.op.iallocator, len(ial.result),
6282
                                  ial.required_nodes), errors.ECODE_FAULT)
6283
    self.op.pnode = ial.result[0]
6284
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6285
                 self.op.instance_name, self.op.iallocator,
6286
                 utils.CommaJoin(ial.result))
6287
    if ial.required_nodes == 2:
6288
      self.op.snode = ial.result[1]
6289

    
6290
  def BuildHooksEnv(self):
6291
    """Build hooks env.
6292

6293
    This runs on master, primary and secondary nodes of the instance.
6294

6295
    """
6296
    env = {
6297
      "ADD_MODE": self.op.mode,
6298
      }
6299
    if self.op.mode == constants.INSTANCE_IMPORT:
6300
      env["SRC_NODE"] = self.op.src_node
6301
      env["SRC_PATH"] = self.op.src_path
6302
      env["SRC_IMAGES"] = self.src_images
6303

    
6304
    env.update(_BuildInstanceHookEnv(
6305
      name=self.op.instance_name,
6306
      primary_node=self.op.pnode,
6307
      secondary_nodes=self.secondaries,
6308
      status=self.op.start,
6309
      os_type=self.op.os_type,
6310
      memory=self.be_full[constants.BE_MEMORY],
6311
      vcpus=self.be_full[constants.BE_VCPUS],
6312
      nics=_NICListToTuple(self, self.nics),
6313
      disk_template=self.op.disk_template,
6314
      disks=[(d["size"], d["mode"]) for d in self.disks],
6315
      bep=self.be_full,
6316
      hvp=self.hv_full,
6317
      hypervisor_name=self.op.hypervisor,
6318
    ))
6319

    
6320
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6321
          self.secondaries)
6322
    return env, nl, nl
6323

    
6324
  def _ReadExportInfo(self):
6325
    """Reads the export information from disk.
6326

6327
    It will override the opcode source node and path with the actual
6328
    information, if these two were not specified before.
6329

6330
    @return: the export information
6331

6332
    """
6333
    assert self.op.mode == constants.INSTANCE_IMPORT
6334

    
6335
    src_node = self.op.src_node
6336
    src_path = self.op.src_path
6337

    
6338
    if src_node is None:
6339
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6340
      exp_list = self.rpc.call_export_list(locked_nodes)
6341
      found = False
6342
      for node in exp_list:
6343
        if exp_list[node].fail_msg:
6344
          continue
6345
        if src_path in exp_list[node].payload:
6346
          found = True
6347
          self.op.src_node = src_node = node
6348
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6349
                                                       src_path)
6350
          break
6351
      if not found:
6352
        raise errors.OpPrereqError("No export found for relative path %s" %
6353
                                    src_path, errors.ECODE_INVAL)
6354

    
6355
    _CheckNodeOnline(self, src_node)
6356
    result = self.rpc.call_export_info(src_node, src_path)
6357
    result.Raise("No export or invalid export found in dir %s" % src_path)
6358

    
6359
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6360
    if not export_info.has_section(constants.INISECT_EXP):
6361
      raise errors.ProgrammerError("Corrupted export config",
6362
                                   errors.ECODE_ENVIRON)
6363

    
6364
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6365
    if (int(ei_version) != constants.EXPORT_VERSION):
6366
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6367
                                 (ei_version, constants.EXPORT_VERSION),
6368
                                 errors.ECODE_ENVIRON)
6369
    return export_info
6370

    
6371
  def _ReadExportParams(self, einfo):
6372
    """Use export parameters as defaults.
6373

6374
    In case the opcode doesn't specify (as in override) some instance
6375
    parameters, then try to use them from the export information, if
6376
    that declares them.
6377

6378
    """
6379
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6380

    
6381
    if self.op.disk_template is None:
6382
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6383
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6384
                                          "disk_template")
6385
      else:
6386
        raise errors.OpPrereqError("No disk template specified and the export"
6387
                                   " is missing the disk_template information",
6388
                                   errors.ECODE_INVAL)
6389

    
6390
    if not self.op.disks:
6391
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6392
        disks = []
6393
        # TODO: import the disk iv_name too
6394
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6395
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6396
          disks.append({"size": disk_sz})
6397
        self.op.disks = disks
6398
      else:
6399
        raise errors.OpPrereqError("No disk info specified and the export"
6400
                                   " is missing the disk information",
6401
                                   errors.ECODE_INVAL)
6402

    
6403
    if (not self.op.nics and
6404
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6405
      nics = []
6406
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6407
        ndict = {}
6408
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6409
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6410
          ndict[name] = v
6411
        nics.append(ndict)
6412
      self.op.nics = nics
6413

    
6414
    if (self.op.hypervisor is None and
6415
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6416
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6417
    if einfo.has_section(constants.INISECT_HYP):
6418
      # use the export parameters but do not override the ones
6419
      # specified by the user
6420
      for name, value in einfo.items(constants.INISECT_HYP):
6421
        if name not in self.op.hvparams:
6422
          self.op.hvparams[name] = value
6423

    
6424
    if einfo.has_section(constants.INISECT_BEP):
6425
      # use the parameters, without overriding
6426
      for name, value in einfo.items(constants.INISECT_BEP):
6427
        if name not in self.op.beparams:
6428
          self.op.beparams[name] = value
6429
    else:
6430
      # try to read the parameters old style, from the main section
6431
      for name in constants.BES_PARAMETERS:
6432
        if (name not in self.op.beparams and
6433
            einfo.has_option(constants.INISECT_INS, name)):
6434
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6435

    
6436
  def _RevertToDefaults(self, cluster):
6437
    """Revert the instance parameters to the default values.
6438

6439
    """
6440
    # hvparams
6441
    hv_defs = cluster.GetHVDefaults(self.op.hypervisor, self.op.os_type)
6442
    for name in self.op.hvparams.keys():
6443
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6444
        del self.op.hvparams[name]
6445
    # beparams
6446
    be_defs = cluster.beparams.get(constants.PP_DEFAULT, {})
6447
    for name in self.op.beparams.keys():
6448
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6449
        del self.op.beparams[name]
6450
    # nic params
6451
    nic_defs = cluster.nicparams.get(constants.PP_DEFAULT, {})
6452
    for nic in self.op.nics:
6453
      for name in constants.NICS_PARAMETERS:
6454
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6455
          del nic[name]
6456

    
6457
  def CheckPrereq(self):
6458
    """Check prerequisites.
6459

6460
    """
6461
    if self.op.mode == constants.INSTANCE_IMPORT:
6462
      export_info = self._ReadExportInfo()
6463
      self._ReadExportParams(export_info)
6464

    
6465
    _CheckDiskTemplate(self.op.disk_template)
6466

    
6467
    if (not self.cfg.GetVGName() and
6468
        self.op.disk_template not in constants.DTS_NOT_LVM):
6469
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6470
                                 " instances", errors.ECODE_STATE)
6471

    
6472
    if self.op.hypervisor is None:
6473
      self.op.hypervisor = self.cfg.GetHypervisorType()
6474

    
6475
    cluster = self.cfg.GetClusterInfo()
6476
    enabled_hvs = cluster.enabled_hypervisors
6477
    if self.op.hypervisor not in enabled_hvs:
6478
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6479
                                 " cluster (%s)" % (self.op.hypervisor,
6480
                                  ",".join(enabled_hvs)),
6481
                                 errors.ECODE_STATE)
6482

    
6483
    # check hypervisor parameter syntax (locally)
6484
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6485
    filled_hvp = objects.FillDict(cluster.GetHVDefaults(self.op.hypervisor,
6486
                                                        self.op.os_type),
6487
                                  self.op.hvparams)
6488
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6489
    hv_type.CheckParameterSyntax(filled_hvp)
6490
    self.hv_full = filled_hvp
6491
    # check that we don't specify global parameters on an instance
6492
    _CheckGlobalHvParams(self.op.hvparams)
6493

    
6494
    # fill and remember the beparams dict
6495
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6496
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
6497
                                    self.op.beparams)
6498

    
6499
    # now that hvp/bep are in final format, let's reset to defaults,
6500
    # if told to do so
6501
    if self.op.identify_defaults:
6502
      self._RevertToDefaults(cluster)
6503

    
6504
    # NIC buildup
6505
    self.nics = []
6506
    for idx, nic in enumerate(self.op.nics):
6507
      nic_mode_req = nic.get("mode", None)
6508
      nic_mode = nic_mode_req
6509
      if nic_mode is None:
6510
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6511

    
6512
      # in routed mode, for the first nic, the default ip is 'auto'
6513
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6514
        default_ip_mode = constants.VALUE_AUTO
6515
      else:
6516
        default_ip_mode = constants.VALUE_NONE
6517

    
6518
      # ip validity checks
6519
      ip = nic.get("ip", default_ip_mode)
6520
      if ip is None or ip.lower() == constants.VALUE_NONE:
6521
        nic_ip = None
6522
      elif ip.lower() == constants.VALUE_AUTO:
6523
        if not self.op.name_check:
6524
          raise errors.OpPrereqError("IP address set to auto but name checks"
6525
                                     " have been skipped. Aborting.",
6526
                                     errors.ECODE_INVAL)
6527
        nic_ip = self.hostname1.ip
6528
      else:
6529
        if not utils.IsValidIP(ip):
6530
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6531
                                     " like a valid IP" % ip,
6532
                                     errors.ECODE_INVAL)
6533
        nic_ip = ip
6534

    
6535
      # TODO: check the ip address for uniqueness
6536
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6537
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6538
                                   errors.ECODE_INVAL)
6539

    
6540
      # MAC address verification
6541
      mac = nic.get("mac", constants.VALUE_AUTO)
6542
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6543
        mac = utils.NormalizeAndValidateMac(mac)
6544

    
6545
        try:
6546
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
6547
        except errors.ReservationError:
6548
          raise errors.OpPrereqError("MAC address %s already in use"
6549
                                     " in cluster" % mac,
6550
                                     errors.ECODE_NOTUNIQUE)
6551

    
6552
      # bridge verification
6553
      bridge = nic.get("bridge", None)
6554
      link = nic.get("link", None)
6555
      if bridge and link:
6556
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
6557
                                   " at the same time", errors.ECODE_INVAL)
6558
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
6559
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
6560
                                   errors.ECODE_INVAL)
6561
      elif bridge:
6562
        link = bridge
6563

    
6564
      nicparams = {}
6565
      if nic_mode_req:
6566
        nicparams[constants.NIC_MODE] = nic_mode_req
6567
      if link:
6568
        nicparams[constants.NIC_LINK] = link
6569

    
6570
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
6571
                                      nicparams)
6572
      objects.NIC.CheckParameterSyntax(check_params)
6573
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
6574

    
6575
    # disk checks/pre-build
6576
    self.disks = []
6577
    for disk in self.op.disks:
6578
      mode = disk.get("mode", constants.DISK_RDWR)
6579
      if mode not in constants.DISK_ACCESS_SET:
6580
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
6581
                                   mode, errors.ECODE_INVAL)
6582
      size = disk.get("size", None)
6583
      if size is None:
6584
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
6585
      try:
6586
        size = int(size)
6587
      except (TypeError, ValueError):
6588
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
6589
                                   errors.ECODE_INVAL)
6590
      new_disk = {"size": size, "mode": mode}
6591
      if "adopt" in disk:
6592
        new_disk["adopt"] = disk["adopt"]
6593
      self.disks.append(new_disk)
6594

    
6595
    if self.op.mode == constants.INSTANCE_IMPORT:
6596

    
6597
      # Check that the new instance doesn't have less disks than the export
6598
      instance_disks = len(self.disks)
6599
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6600
      if instance_disks < export_disks:
6601
        raise errors.OpPrereqError("Not enough disks to import."
6602
                                   " (instance: %d, export: %d)" %
6603
                                   (instance_disks, export_disks),
6604
                                   errors.ECODE_INVAL)
6605

    
6606
      disk_images = []
6607
      for idx in range(export_disks):
6608
        option = 'disk%d_dump' % idx
6609
        if export_info.has_option(constants.INISECT_INS, option):
6610
          # FIXME: are the old os-es, disk sizes, etc. useful?
6611
          export_name = export_info.get(constants.INISECT_INS, option)
6612
          image = utils.PathJoin(self.op.src_path, export_name)
6613
          disk_images.append(image)
6614
        else:
6615
          disk_images.append(False)
6616

    
6617
      self.src_images = disk_images
6618

    
6619
      old_name = export_info.get(constants.INISECT_INS, 'name')
6620
      try:
6621
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
6622
      except (TypeError, ValueError), err:
6623
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
6624
                                   " an integer: %s" % str(err),
6625
                                   errors.ECODE_STATE)
6626
      if self.op.instance_name == old_name:
6627
        for idx, nic in enumerate(self.nics):
6628
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
6629
            nic_mac_ini = 'nic%d_mac' % idx
6630
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
6631

    
6632
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
6633

    
6634
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
6635
    if self.op.ip_check:
6636
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
6637
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6638
                                   (self.check_ip, self.op.instance_name),
6639
                                   errors.ECODE_NOTUNIQUE)
6640

    
6641
    #### mac address generation
6642
    # By generating here the mac address both the allocator and the hooks get
6643
    # the real final mac address rather than the 'auto' or 'generate' value.
6644
    # There is a race condition between the generation and the instance object
6645
    # creation, which means that we know the mac is valid now, but we're not
6646
    # sure it will be when we actually add the instance. If things go bad
6647
    # adding the instance will abort because of a duplicate mac, and the
6648
    # creation job will fail.
6649
    for nic in self.nics:
6650
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6651
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
6652

    
6653
    #### allocator run
6654

    
6655
    if self.op.iallocator is not None:
6656
      self._RunAllocator()
6657

    
6658
    #### node related checks
6659

    
6660
    # check primary node
6661
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
6662
    assert self.pnode is not None, \
6663
      "Cannot retrieve locked node %s" % self.op.pnode
6664
    if pnode.offline:
6665
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
6666
                                 pnode.name, errors.ECODE_STATE)
6667
    if pnode.drained:
6668
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
6669
                                 pnode.name, errors.ECODE_STATE)
6670

    
6671
    self.secondaries = []
6672

    
6673
    # mirror node verification
6674
    if self.op.disk_template in constants.DTS_NET_MIRROR:
6675
      if self.op.snode is None:
6676
        raise errors.OpPrereqError("The networked disk templates need"
6677
                                   " a mirror node", errors.ECODE_INVAL)
6678
      if self.op.snode == pnode.name:
6679
        raise errors.OpPrereqError("The secondary node cannot be the"
6680
                                   " primary node.", errors.ECODE_INVAL)
6681
      _CheckNodeOnline(self, self.op.snode)
6682
      _CheckNodeNotDrained(self, self.op.snode)
6683
      self.secondaries.append(self.op.snode)
6684

    
6685
    nodenames = [pnode.name] + self.secondaries
6686

    
6687
    req_size = _ComputeDiskSize(self.op.disk_template,
6688
                                self.disks)
6689

    
6690
    # Check lv size requirements, if not adopting
6691
    if req_size is not None and not self.adopt_disks:
6692
      _CheckNodesFreeDisk(self, nodenames, req_size)
6693

    
6694
    if self.adopt_disks: # instead, we must check the adoption data
6695
      all_lvs = set([i["adopt"] for i in self.disks])
6696
      if len(all_lvs) != len(self.disks):
6697
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
6698
                                   errors.ECODE_INVAL)
6699
      for lv_name in all_lvs:
6700
        try:
6701
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
6702
        except errors.ReservationError:
6703
          raise errors.OpPrereqError("LV named %s used by another instance" %
6704
                                     lv_name, errors.ECODE_NOTUNIQUE)
6705

    
6706
      node_lvs = self.rpc.call_lv_list([pnode.name],
6707
                                       self.cfg.GetVGName())[pnode.name]
6708
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
6709
      node_lvs = node_lvs.payload
6710
      delta = all_lvs.difference(node_lvs.keys())
6711
      if delta:
6712
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
6713
                                   utils.CommaJoin(delta),
6714
                                   errors.ECODE_INVAL)
6715
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
6716
      if online_lvs:
6717
        raise errors.OpPrereqError("Online logical volumes found, cannot"
6718
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
6719
                                   errors.ECODE_STATE)
6720
      # update the size of disk based on what is found
6721
      for dsk in self.disks:
6722
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
6723

    
6724
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
6725

    
6726
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
6727

    
6728
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
6729

    
6730
    # memory check on primary node
6731
    if self.op.start:
6732
      _CheckNodeFreeMemory(self, self.pnode.name,
6733
                           "creating instance %s" % self.op.instance_name,
6734
                           self.be_full[constants.BE_MEMORY],
6735
                           self.op.hypervisor)
6736

    
6737
    self.dry_run_result = list(nodenames)
6738

    
6739
  def Exec(self, feedback_fn):
6740
    """Create and add the instance to the cluster.
6741

6742
    """
6743
    instance = self.op.instance_name
6744
    pnode_name = self.pnode.name
6745

    
6746
    ht_kind = self.op.hypervisor
6747
    if ht_kind in constants.HTS_REQ_PORT:
6748
      network_port = self.cfg.AllocatePort()
6749
    else:
6750
      network_port = None
6751

    
6752
    if constants.ENABLE_FILE_STORAGE:
6753
      # this is needed because os.path.join does not accept None arguments
6754
      if self.op.file_storage_dir is None:
6755
        string_file_storage_dir = ""
6756
      else:
6757
        string_file_storage_dir = self.op.file_storage_dir
6758

    
6759
      # build the full file storage dir path
6760
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
6761
                                        string_file_storage_dir, instance)
6762
    else:
6763
      file_storage_dir = ""
6764

    
6765
    disks = _GenerateDiskTemplate(self,
6766
                                  self.op.disk_template,
6767
                                  instance, pnode_name,
6768
                                  self.secondaries,
6769
                                  self.disks,
6770
                                  file_storage_dir,
6771
                                  self.op.file_driver,
6772
                                  0)
6773

    
6774
    iobj = objects.Instance(name=instance, os=self.op.os_type,
6775
                            primary_node=pnode_name,
6776
                            nics=self.nics, disks=disks,
6777
                            disk_template=self.op.disk_template,
6778
                            admin_up=False,
6779
                            network_port=network_port,
6780
                            beparams=self.op.beparams,
6781
                            hvparams=self.op.hvparams,
6782
                            hypervisor=self.op.hypervisor,
6783
                            )
6784

    
6785
    if self.adopt_disks:
6786
      # rename LVs to the newly-generated names; we need to construct
6787
      # 'fake' LV disks with the old data, plus the new unique_id
6788
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
6789
      rename_to = []
6790
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
6791
        rename_to.append(t_dsk.logical_id)
6792
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
6793
        self.cfg.SetDiskID(t_dsk, pnode_name)
6794
      result = self.rpc.call_blockdev_rename(pnode_name,
6795
                                             zip(tmp_disks, rename_to))
6796
      result.Raise("Failed to rename adoped LVs")
6797
    else:
6798
      feedback_fn("* creating instance disks...")
6799
      try:
6800
        _CreateDisks(self, iobj)
6801
      except errors.OpExecError:
6802
        self.LogWarning("Device creation failed, reverting...")
6803
        try:
6804
          _RemoveDisks(self, iobj)
6805
        finally:
6806
          self.cfg.ReleaseDRBDMinors(instance)
6807
          raise
6808

    
6809
    feedback_fn("adding instance %s to cluster config" % instance)
6810

    
6811
    self.cfg.AddInstance(iobj, self.proc.GetECId())
6812

    
6813
    # Declare that we don't want to remove the instance lock anymore, as we've
6814
    # added the instance to the config
6815
    del self.remove_locks[locking.LEVEL_INSTANCE]
6816
    # Unlock all the nodes
6817
    if self.op.mode == constants.INSTANCE_IMPORT:
6818
      nodes_keep = [self.op.src_node]
6819
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
6820
                       if node != self.op.src_node]
6821
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
6822
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6823
    else:
6824
      self.context.glm.release(locking.LEVEL_NODE)
6825
      del self.acquired_locks[locking.LEVEL_NODE]
6826

    
6827
    if self.op.wait_for_sync:
6828
      disk_abort = not _WaitForSync(self, iobj)
6829
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
6830
      # make sure the disks are not degraded (still sync-ing is ok)
6831
      time.sleep(15)
6832
      feedback_fn("* checking mirrors status")
6833
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
6834
    else:
6835
      disk_abort = False
6836

    
6837
    if disk_abort:
6838
      _RemoveDisks(self, iobj)
6839
      self.cfg.RemoveInstance(iobj.name)
6840
      # Make sure the instance lock gets removed
6841
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
6842
      raise errors.OpExecError("There are some degraded disks for"
6843
                               " this instance")
6844

    
6845
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
6846
      if self.op.mode == constants.INSTANCE_CREATE:
6847
        if not self.op.no_install:
6848
          feedback_fn("* running the instance OS create scripts...")
6849
          # FIXME: pass debug option from opcode to backend
6850
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
6851
                                                 self.op.debug_level)
6852
          result.Raise("Could not add os for instance %s"
6853
                       " on node %s" % (instance, pnode_name))
6854

    
6855
      elif self.op.mode == constants.INSTANCE_IMPORT:
6856
        feedback_fn("* running the instance OS import scripts...")
6857

    
6858
        transfers = []
6859

    
6860
        for idx, image in enumerate(self.src_images):
6861
          if not image:
6862
            continue
6863

    
6864
          # FIXME: pass debug option from opcode to backend
6865
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
6866
                                             constants.IEIO_FILE, (image, ),
6867
                                             constants.IEIO_SCRIPT,
6868
                                             (iobj.disks[idx], idx),
6869
                                             None)
6870
          transfers.append(dt)
6871

    
6872
        import_result = \
6873
          masterd.instance.TransferInstanceData(self, feedback_fn,
6874
                                                self.op.src_node, pnode_name,
6875
                                                self.pnode.secondary_ip,
6876
                                                iobj, transfers)
6877
        if not compat.all(import_result):
6878
          self.LogWarning("Some disks for instance %s on node %s were not"
6879
                          " imported successfully" % (instance, pnode_name))
6880

    
6881
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6882
        feedback_fn("* preparing remote import...")
6883
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
6884
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
6885

    
6886
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
6887
                                                     self.source_x509_ca,
6888
                                                     self._cds, timeouts)
6889
        if not compat.all(disk_results):
6890
          # TODO: Should the instance still be started, even if some disks
6891
          # failed to import (valid for local imports, too)?
6892
          self.LogWarning("Some disks for instance %s on node %s were not"
6893
                          " imported successfully" % (instance, pnode_name))
6894

    
6895
        # Run rename script on newly imported instance
6896
        assert iobj.name == instance
6897
        feedback_fn("Running rename script for %s" % instance)
6898
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
6899
                                                   self.source_instance_name,
6900
                                                   self.op.debug_level)
6901
        if result.fail_msg:
6902
          self.LogWarning("Failed to run rename script for %s on node"
6903
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
6904

    
6905
      else:
6906
        # also checked in the prereq part
6907
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
6908
                                     % self.op.mode)
6909

    
6910
    if self.op.start:
6911
      iobj.admin_up = True
6912
      self.cfg.Update(iobj, feedback_fn)
6913
      logging.info("Starting instance %s on node %s", instance, pnode_name)
6914
      feedback_fn("* starting instance...")
6915
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
6916
      result.Raise("Could not start instance")
6917

    
6918
    return list(iobj.all_nodes)
6919

    
6920

    
6921
class LUConnectConsole(NoHooksLU):
6922
  """Connect to an instance's console.
6923

6924
  This is somewhat special in that it returns the command line that
6925
  you need to run on the master node in order to connect to the
6926
  console.
6927

6928
  """
6929
  _OP_REQP = ["instance_name"]
6930
  REQ_BGL = False
6931

    
6932
  def ExpandNames(self):
6933
    self._ExpandAndLockInstance()
6934

    
6935
  def CheckPrereq(self):
6936
    """Check prerequisites.
6937

6938
    This checks that the instance is in the cluster.
6939

6940
    """
6941
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6942
    assert self.instance is not None, \
6943
      "Cannot retrieve locked instance %s" % self.op.instance_name
6944
    _CheckNodeOnline(self, self.instance.primary_node)
6945

    
6946
  def Exec(self, feedback_fn):
6947
    """Connect to the console of an instance
6948

6949
    """
6950
    instance = self.instance
6951
    node = instance.primary_node
6952

    
6953
    node_insts = self.rpc.call_instance_list([node],
6954
                                             [instance.hypervisor])[node]
6955
    node_insts.Raise("Can't get node information from %s" % node)
6956

    
6957
    if instance.name not in node_insts.payload:
6958
      raise errors.OpExecError("Instance %s is not running." % instance.name)
6959

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

    
6962
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6963
    cluster = self.cfg.GetClusterInfo()
6964
    # beparams and hvparams are passed separately, to avoid editing the
6965
    # instance and then saving the defaults in the instance itself.
6966
    hvparams = cluster.FillHV(instance)
6967
    beparams = cluster.FillBE(instance)
6968
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6969

    
6970
    # build ssh cmdline
6971
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6972

    
6973

    
6974
class LUReplaceDisks(LogicalUnit):
6975
  """Replace the disks of an instance.
6976

6977
  """
6978
  HPATH = "mirrors-replace"
6979
  HTYPE = constants.HTYPE_INSTANCE
6980
  _OP_REQP = ["instance_name", "mode", "disks"]
6981
  REQ_BGL = False
6982

    
6983
  def CheckArguments(self):
6984
    if not hasattr(self.op, "remote_node"):
6985
      self.op.remote_node = None
6986
    if not hasattr(self.op, "iallocator"):
6987
      self.op.iallocator = None
6988
    if not hasattr(self.op, "early_release"):
6989
      self.op.early_release = False
6990

    
6991
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
6992
                                  self.op.iallocator)
6993

    
6994
  def ExpandNames(self):
6995
    self._ExpandAndLockInstance()
6996

    
6997
    if self.op.iallocator is not None:
6998
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6999

    
7000
    elif self.op.remote_node is not None:
7001
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7002
      self.op.remote_node = remote_node
7003

    
7004
      # Warning: do not remove the locking of the new secondary here
7005
      # unless DRBD8.AddChildren is changed to work in parallel;
7006
      # currently it doesn't since parallel invocations of
7007
      # FindUnusedMinor will conflict
7008
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7009
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7010

    
7011
    else:
7012
      self.needed_locks[locking.LEVEL_NODE] = []
7013
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7014

    
7015
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7016
                                   self.op.iallocator, self.op.remote_node,
7017
                                   self.op.disks, False, self.op.early_release)
7018

    
7019
    self.tasklets = [self.replacer]
7020

    
7021
  def DeclareLocks(self, level):
7022
    # If we're not already locking all nodes in the set we have to declare the
7023
    # instance's primary/secondary nodes.
7024
    if (level == locking.LEVEL_NODE and
7025
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7026
      self._LockInstancesNodes()
7027

    
7028
  def BuildHooksEnv(self):
7029
    """Build hooks env.
7030

7031
    This runs on the master, the primary and all the secondaries.
7032

7033
    """
7034
    instance = self.replacer.instance
7035
    env = {
7036
      "MODE": self.op.mode,
7037
      "NEW_SECONDARY": self.op.remote_node,
7038
      "OLD_SECONDARY": instance.secondary_nodes[0],
7039
      }
7040
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7041
    nl = [
7042
      self.cfg.GetMasterNode(),
7043
      instance.primary_node,
7044
      ]
7045
    if self.op.remote_node is not None:
7046
      nl.append(self.op.remote_node)
7047
    return env, nl, nl
7048

    
7049

    
7050
class LUEvacuateNode(LogicalUnit):
7051
  """Relocate the secondary instances from a node.
7052

7053
  """
7054
  HPATH = "node-evacuate"
7055
  HTYPE = constants.HTYPE_NODE
7056
  _OP_REQP = ["node_name"]
7057
  REQ_BGL = False
7058

    
7059
  def CheckArguments(self):
7060
    if not hasattr(self.op, "remote_node"):
7061
      self.op.remote_node = None
7062
    if not hasattr(self.op, "iallocator"):
7063
      self.op.iallocator = None
7064
    if not hasattr(self.op, "early_release"):
7065
      self.op.early_release = False
7066

    
7067
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
7068
                                  self.op.remote_node,
7069
                                  self.op.iallocator)
7070

    
7071
  def ExpandNames(self):
7072
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
7073

    
7074
    self.needed_locks = {}
7075

    
7076
    # Declare node locks
7077
    if self.op.iallocator is not None:
7078
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7079

    
7080
    elif self.op.remote_node is not None:
7081
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7082

    
7083
      # Warning: do not remove the locking of the new secondary here
7084
      # unless DRBD8.AddChildren is changed to work in parallel;
7085
      # currently it doesn't since parallel invocations of
7086
      # FindUnusedMinor will conflict
7087
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
7088
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7089

    
7090
    else:
7091
      raise errors.OpPrereqError("Invalid parameters", errors.ECODE_INVAL)
7092

    
7093
    # Create tasklets for replacing disks for all secondary instances on this
7094
    # node
7095
    names = []
7096
    tasklets = []
7097

    
7098
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
7099
      logging.debug("Replacing disks for instance %s", inst.name)
7100
      names.append(inst.name)
7101

    
7102
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
7103
                                self.op.iallocator, self.op.remote_node, [],
7104
                                True, self.op.early_release)
7105
      tasklets.append(replacer)
7106

    
7107
    self.tasklets = tasklets
7108
    self.instance_names = names
7109

    
7110
    # Declare instance locks
7111
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
7112

    
7113
  def DeclareLocks(self, level):
7114
    # If we're not already locking all nodes in the set we have to declare the
7115
    # instance's primary/secondary nodes.
7116
    if (level == locking.LEVEL_NODE and
7117
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7118
      self._LockInstancesNodes()
7119

    
7120
  def BuildHooksEnv(self):
7121
    """Build hooks env.
7122

7123
    This runs on the master, the primary and all the secondaries.
7124

7125
    """
7126
    env = {
7127
      "NODE_NAME": self.op.node_name,
7128
      }
7129

    
7130
    nl = [self.cfg.GetMasterNode()]
7131

    
7132
    if self.op.remote_node is not None:
7133
      env["NEW_SECONDARY"] = self.op.remote_node
7134
      nl.append(self.op.remote_node)
7135

    
7136
    return (env, nl, nl)
7137

    
7138

    
7139
class TLReplaceDisks(Tasklet):
7140
  """Replaces disks for an instance.
7141

7142
  Note: Locking is not within the scope of this class.
7143

7144
  """
7145
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7146
               disks, delay_iallocator, early_release):
7147
    """Initializes this class.
7148

7149
    """
7150
    Tasklet.__init__(self, lu)
7151

    
7152
    # Parameters
7153
    self.instance_name = instance_name
7154
    self.mode = mode
7155
    self.iallocator_name = iallocator_name
7156
    self.remote_node = remote_node
7157
    self.disks = disks
7158
    self.delay_iallocator = delay_iallocator
7159
    self.early_release = early_release
7160

    
7161
    # Runtime data
7162
    self.instance = None
7163
    self.new_node = None
7164
    self.target_node = None
7165
    self.other_node = None
7166
    self.remote_node_info = None
7167
    self.node_secondary_ip = None
7168

    
7169
  @staticmethod
7170
  def CheckArguments(mode, remote_node, iallocator):
7171
    """Helper function for users of this class.
7172

7173
    """
7174
    # check for valid parameter combination
7175
    if mode == constants.REPLACE_DISK_CHG:
7176
      if remote_node is None and iallocator is None:
7177
        raise errors.OpPrereqError("When changing the secondary either an"
7178
                                   " iallocator script must be used or the"
7179
                                   " new node given", errors.ECODE_INVAL)
7180

    
7181
      if remote_node is not None and iallocator is not None:
7182
        raise errors.OpPrereqError("Give either the iallocator or the new"
7183
                                   " secondary, not both", errors.ECODE_INVAL)
7184

    
7185
    elif remote_node is not None or iallocator is not None:
7186
      # Not replacing the secondary
7187
      raise errors.OpPrereqError("The iallocator and new node options can"
7188
                                 " only be used when changing the"
7189
                                 " secondary node", errors.ECODE_INVAL)
7190

    
7191
  @staticmethod
7192
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7193
    """Compute a new secondary node using an IAllocator.
7194

7195
    """
7196
    ial = IAllocator(lu.cfg, lu.rpc,
7197
                     mode=constants.IALLOCATOR_MODE_RELOC,
7198
                     name=instance_name,
7199
                     relocate_from=relocate_from)
7200

    
7201
    ial.Run(iallocator_name)
7202

    
7203
    if not ial.success:
7204
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7205
                                 " %s" % (iallocator_name, ial.info),
7206
                                 errors.ECODE_NORES)
7207

    
7208
    if len(ial.result) != ial.required_nodes:
7209
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7210
                                 " of nodes (%s), required %s" %
7211
                                 (iallocator_name,
7212
                                  len(ial.result), ial.required_nodes),
7213
                                 errors.ECODE_FAULT)
7214

    
7215
    remote_node_name = ial.result[0]
7216

    
7217
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7218
               instance_name, remote_node_name)
7219

    
7220
    return remote_node_name
7221

    
7222
  def _FindFaultyDisks(self, node_name):
7223
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7224
                                    node_name, True)
7225

    
7226
  def CheckPrereq(self):
7227
    """Check prerequisites.
7228

7229
    This checks that the instance is in the cluster.
7230

7231
    """
7232
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7233
    assert instance is not None, \
7234
      "Cannot retrieve locked instance %s" % self.instance_name
7235

    
7236
    if instance.disk_template != constants.DT_DRBD8:
7237
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7238
                                 " instances", errors.ECODE_INVAL)
7239

    
7240
    if len(instance.secondary_nodes) != 1:
7241
      raise errors.OpPrereqError("The instance has a strange layout,"
7242
                                 " expected one secondary but found %d" %
7243
                                 len(instance.secondary_nodes),
7244
                                 errors.ECODE_FAULT)
7245

    
7246
    if not self.delay_iallocator:
7247
      self._CheckPrereq2()
7248

    
7249
  def _CheckPrereq2(self):
7250
    """Check prerequisites, second part.
7251

7252
    This function should always be part of CheckPrereq. It was separated and is
7253
    now called from Exec because during node evacuation iallocator was only
7254
    called with an unmodified cluster model, not taking planned changes into
7255
    account.
7256

7257
    """
7258
    instance = self.instance
7259
    secondary_node = instance.secondary_nodes[0]
7260

    
7261
    if self.iallocator_name is None:
7262
      remote_node = self.remote_node
7263
    else:
7264
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7265
                                       instance.name, instance.secondary_nodes)
7266

    
7267
    if remote_node is not None:
7268
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7269
      assert self.remote_node_info is not None, \
7270
        "Cannot retrieve locked node %s" % remote_node
7271
    else:
7272
      self.remote_node_info = None
7273

    
7274
    if remote_node == self.instance.primary_node:
7275
      raise errors.OpPrereqError("The specified node is the primary node of"
7276
                                 " the instance.", errors.ECODE_INVAL)
7277

    
7278
    if remote_node == secondary_node:
7279
      raise errors.OpPrereqError("The specified node is already the"
7280
                                 " secondary node of the instance.",
7281
                                 errors.ECODE_INVAL)
7282

    
7283
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7284
                                    constants.REPLACE_DISK_CHG):
7285
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7286
                                 errors.ECODE_INVAL)
7287

    
7288
    if self.mode == constants.REPLACE_DISK_AUTO:
7289
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7290
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7291

    
7292
      if faulty_primary and faulty_secondary:
7293
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7294
                                   " one node and can not be repaired"
7295
                                   " automatically" % self.instance_name,
7296
                                   errors.ECODE_STATE)
7297

    
7298
      if faulty_primary:
7299
        self.disks = faulty_primary
7300
        self.target_node = instance.primary_node
7301
        self.other_node = secondary_node
7302
        check_nodes = [self.target_node, self.other_node]
7303
      elif faulty_secondary:
7304
        self.disks = faulty_secondary
7305
        self.target_node = secondary_node
7306
        self.other_node = instance.primary_node
7307
        check_nodes = [self.target_node, self.other_node]
7308
      else:
7309
        self.disks = []
7310
        check_nodes = []
7311

    
7312
    else:
7313
      # Non-automatic modes
7314
      if self.mode == constants.REPLACE_DISK_PRI:
7315
        self.target_node = instance.primary_node
7316
        self.other_node = secondary_node
7317
        check_nodes = [self.target_node, self.other_node]
7318

    
7319
      elif self.mode == constants.REPLACE_DISK_SEC:
7320
        self.target_node = secondary_node
7321
        self.other_node = instance.primary_node
7322
        check_nodes = [self.target_node, self.other_node]
7323

    
7324
      elif self.mode == constants.REPLACE_DISK_CHG:
7325
        self.new_node = remote_node
7326
        self.other_node = instance.primary_node
7327
        self.target_node = secondary_node
7328
        check_nodes = [self.new_node, self.other_node]
7329

    
7330
        _CheckNodeNotDrained(self.lu, remote_node)
7331

    
7332
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7333
        assert old_node_info is not None
7334
        if old_node_info.offline and not self.early_release:
7335
          # doesn't make sense to delay the release
7336
          self.early_release = True
7337
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7338
                          " early-release mode", secondary_node)
7339

    
7340
      else:
7341
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7342
                                     self.mode)
7343

    
7344
      # If not specified all disks should be replaced
7345
      if not self.disks:
7346
        self.disks = range(len(self.instance.disks))
7347

    
7348
    for node in check_nodes:
7349
      _CheckNodeOnline(self.lu, node)
7350

    
7351
    # Check whether disks are valid
7352
    for disk_idx in self.disks:
7353
      instance.FindDisk(disk_idx)
7354

    
7355
    # Get secondary node IP addresses
7356
    node_2nd_ip = {}
7357

    
7358
    for node_name in [self.target_node, self.other_node, self.new_node]:
7359
      if node_name is not None:
7360
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7361

    
7362
    self.node_secondary_ip = node_2nd_ip
7363

    
7364
  def Exec(self, feedback_fn):
7365
    """Execute disk replacement.
7366

7367
    This dispatches the disk replacement to the appropriate handler.
7368

7369
    """
7370
    if self.delay_iallocator:
7371
      self._CheckPrereq2()
7372

    
7373
    if not self.disks:
7374
      feedback_fn("No disks need replacement")
7375
      return
7376

    
7377
    feedback_fn("Replacing disk(s) %s for %s" %
7378
                (utils.CommaJoin(self.disks), self.instance.name))
7379

    
7380
    activate_disks = (not self.instance.admin_up)
7381

    
7382
    # Activate the instance disks if we're replacing them on a down instance
7383
    if activate_disks:
7384
      _StartInstanceDisks(self.lu, self.instance, True)
7385

    
7386
    try:
7387
      # Should we replace the secondary node?
7388
      if self.new_node is not None:
7389
        fn = self._ExecDrbd8Secondary
7390
      else:
7391
        fn = self._ExecDrbd8DiskOnly
7392

    
7393
      return fn(feedback_fn)
7394

    
7395
    finally:
7396
      # Deactivate the instance disks if we're replacing them on a
7397
      # down instance
7398
      if activate_disks:
7399
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7400

    
7401
  def _CheckVolumeGroup(self, nodes):
7402
    self.lu.LogInfo("Checking volume groups")
7403

    
7404
    vgname = self.cfg.GetVGName()
7405

    
7406
    # Make sure volume group exists on all involved nodes
7407
    results = self.rpc.call_vg_list(nodes)
7408
    if not results:
7409
      raise errors.OpExecError("Can't list volume groups on the nodes")
7410

    
7411
    for node in nodes:
7412
      res = results[node]
7413
      res.Raise("Error checking node %s" % node)
7414
      if vgname not in res.payload:
7415
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7416
                                 (vgname, node))
7417

    
7418
  def _CheckDisksExistence(self, nodes):
7419
    # Check disk existence
7420
    for idx, dev in enumerate(self.instance.disks):
7421
      if idx not in self.disks:
7422
        continue
7423

    
7424
      for node in nodes:
7425
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7426
        self.cfg.SetDiskID(dev, node)
7427

    
7428
        result = self.rpc.call_blockdev_find(node, dev)
7429

    
7430
        msg = result.fail_msg
7431
        if msg or not result.payload:
7432
          if not msg:
7433
            msg = "disk not found"
7434
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7435
                                   (idx, node, msg))
7436

    
7437
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7438
    for idx, dev in enumerate(self.instance.disks):
7439
      if idx not in self.disks:
7440
        continue
7441

    
7442
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7443
                      (idx, node_name))
7444

    
7445
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7446
                                   ldisk=ldisk):
7447
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7448
                                 " replace disks for instance %s" %
7449
                                 (node_name, self.instance.name))
7450

    
7451
  def _CreateNewStorage(self, node_name):
7452
    vgname = self.cfg.GetVGName()
7453
    iv_names = {}
7454

    
7455
    for idx, dev in enumerate(self.instance.disks):
7456
      if idx not in self.disks:
7457
        continue
7458

    
7459
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7460

    
7461
      self.cfg.SetDiskID(dev, node_name)
7462

    
7463
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7464
      names = _GenerateUniqueNames(self.lu, lv_names)
7465

    
7466
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7467
                             logical_id=(vgname, names[0]))
7468
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7469
                             logical_id=(vgname, names[1]))
7470

    
7471
      new_lvs = [lv_data, lv_meta]
7472
      old_lvs = dev.children
7473
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7474

    
7475
      # we pass force_create=True to force the LVM creation
7476
      for new_lv in new_lvs:
7477
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7478
                        _GetInstanceInfoText(self.instance), False)
7479

    
7480
    return iv_names
7481

    
7482
  def _CheckDevices(self, node_name, iv_names):
7483
    for name, (dev, _, _) in iv_names.iteritems():
7484
      self.cfg.SetDiskID(dev, node_name)
7485

    
7486
      result = self.rpc.call_blockdev_find(node_name, dev)
7487

    
7488
      msg = result.fail_msg
7489
      if msg or not result.payload:
7490
        if not msg:
7491
          msg = "disk not found"
7492
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7493
                                 (name, msg))
7494

    
7495
      if result.payload.is_degraded:
7496
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7497

    
7498
  def _RemoveOldStorage(self, node_name, iv_names):
7499
    for name, (_, old_lvs, _) in iv_names.iteritems():
7500
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7501

    
7502
      for lv in old_lvs:
7503
        self.cfg.SetDiskID(lv, node_name)
7504

    
7505
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7506
        if msg:
7507
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7508
                             hint="remove unused LVs manually")
7509

    
7510
  def _ReleaseNodeLock(self, node_name):
7511
    """Releases the lock for a given node."""
7512
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7513

    
7514
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7515
    """Replace a disk on the primary or secondary for DRBD 8.
7516

7517
    The algorithm for replace is quite complicated:
7518

7519
      1. for each disk to be replaced:
7520

7521
        1. create new LVs on the target node with unique names
7522
        1. detach old LVs from the drbd device
7523
        1. rename old LVs to name_replaced.<time_t>
7524
        1. rename new LVs to old LVs
7525
        1. attach the new LVs (with the old names now) to the drbd device
7526

7527
      1. wait for sync across all devices
7528

7529
      1. for each modified disk:
7530

7531
        1. remove old LVs (which have the name name_replaces.<time_t>)
7532

7533
    Failures are not very well handled.
7534

7535
    """
7536
    steps_total = 6
7537

    
7538
    # Step: check device activation
7539
    self.lu.LogStep(1, steps_total, "Check device existence")
7540
    self._CheckDisksExistence([self.other_node, self.target_node])
7541
    self._CheckVolumeGroup([self.target_node, self.other_node])
7542

    
7543
    # Step: check other node consistency
7544
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7545
    self._CheckDisksConsistency(self.other_node,
7546
                                self.other_node == self.instance.primary_node,
7547
                                False)
7548

    
7549
    # Step: create new storage
7550
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7551
    iv_names = self._CreateNewStorage(self.target_node)
7552

    
7553
    # Step: for each lv, detach+rename*2+attach
7554
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7555
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7556
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7557

    
7558
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7559
                                                     old_lvs)
7560
      result.Raise("Can't detach drbd from local storage on node"
7561
                   " %s for device %s" % (self.target_node, dev.iv_name))
7562
      #dev.children = []
7563
      #cfg.Update(instance)
7564

    
7565
      # ok, we created the new LVs, so now we know we have the needed
7566
      # storage; as such, we proceed on the target node to rename
7567
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7568
      # using the assumption that logical_id == physical_id (which in
7569
      # turn is the unique_id on that node)
7570

    
7571
      # FIXME(iustin): use a better name for the replaced LVs
7572
      temp_suffix = int(time.time())
7573
      ren_fn = lambda d, suff: (d.physical_id[0],
7574
                                d.physical_id[1] + "_replaced-%s" % suff)
7575

    
7576
      # Build the rename list based on what LVs exist on the node
7577
      rename_old_to_new = []
7578
      for to_ren in old_lvs:
7579
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7580
        if not result.fail_msg and result.payload:
7581
          # device exists
7582
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7583

    
7584
      self.lu.LogInfo("Renaming the old LVs on the target node")
7585
      result = self.rpc.call_blockdev_rename(self.target_node,
7586
                                             rename_old_to_new)
7587
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7588

    
7589
      # Now we rename the new LVs to the old LVs
7590
      self.lu.LogInfo("Renaming the new LVs on the target node")
7591
      rename_new_to_old = [(new, old.physical_id)
7592
                           for old, new in zip(old_lvs, new_lvs)]
7593
      result = self.rpc.call_blockdev_rename(self.target_node,
7594
                                             rename_new_to_old)
7595
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7596

    
7597
      for old, new in zip(old_lvs, new_lvs):
7598
        new.logical_id = old.logical_id
7599
        self.cfg.SetDiskID(new, self.target_node)
7600

    
7601
      for disk in old_lvs:
7602
        disk.logical_id = ren_fn(disk, temp_suffix)
7603
        self.cfg.SetDiskID(disk, self.target_node)
7604

    
7605
      # Now that the new lvs have the old name, we can add them to the device
7606
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7607
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7608
                                                  new_lvs)
7609
      msg = result.fail_msg
7610
      if msg:
7611
        for new_lv in new_lvs:
7612
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7613
                                               new_lv).fail_msg
7614
          if msg2:
7615
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7616
                               hint=("cleanup manually the unused logical"
7617
                                     "volumes"))
7618
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7619

    
7620
      dev.children = new_lvs
7621

    
7622
      self.cfg.Update(self.instance, feedback_fn)
7623

    
7624
    cstep = 5
7625
    if self.early_release:
7626
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7627
      cstep += 1
7628
      self._RemoveOldStorage(self.target_node, iv_names)
7629
      # WARNING: we release both node locks here, do not do other RPCs
7630
      # than WaitForSync to the primary node
7631
      self._ReleaseNodeLock([self.target_node, self.other_node])
7632

    
7633
    # Wait for sync
7634
    # This can fail as the old devices are degraded and _WaitForSync
7635
    # does a combined result over all disks, so we don't check its return value
7636
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7637
    cstep += 1
7638
    _WaitForSync(self.lu, self.instance)
7639

    
7640
    # Check all devices manually
7641
    self._CheckDevices(self.instance.primary_node, iv_names)
7642

    
7643
    # Step: remove old storage
7644
    if not self.early_release:
7645
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7646
      cstep += 1
7647
      self._RemoveOldStorage(self.target_node, iv_names)
7648

    
7649
  def _ExecDrbd8Secondary(self, feedback_fn):
7650
    """Replace the secondary node for DRBD 8.
7651

7652
    The algorithm for replace is quite complicated:
7653
      - for all disks of the instance:
7654
        - create new LVs on the new node with same names
7655
        - shutdown the drbd device on the old secondary
7656
        - disconnect the drbd network on the primary
7657
        - create the drbd device on the new secondary
7658
        - network attach the drbd on the primary, using an artifice:
7659
          the drbd code for Attach() will connect to the network if it
7660
          finds a device which is connected to the good local disks but
7661
          not network enabled
7662
      - wait for sync across all devices
7663
      - remove all disks from the old secondary
7664

7665
    Failures are not very well handled.
7666

7667
    """
7668
    steps_total = 6
7669

    
7670
    # Step: check device activation
7671
    self.lu.LogStep(1, steps_total, "Check device existence")
7672
    self._CheckDisksExistence([self.instance.primary_node])
7673
    self._CheckVolumeGroup([self.instance.primary_node])
7674

    
7675
    # Step: check other node consistency
7676
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7677
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
7678

    
7679
    # Step: create new storage
7680
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7681
    for idx, dev in enumerate(self.instance.disks):
7682
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
7683
                      (self.new_node, idx))
7684
      # we pass force_create=True to force LVM creation
7685
      for new_lv in dev.children:
7686
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
7687
                        _GetInstanceInfoText(self.instance), False)
7688

    
7689
    # Step 4: dbrd minors and drbd setups changes
7690
    # after this, we must manually remove the drbd minors on both the
7691
    # error and the success paths
7692
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7693
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7694
                                         for dev in self.instance.disks],
7695
                                        self.instance.name)
7696
    logging.debug("Allocated minors %r", minors)
7697

    
7698
    iv_names = {}
7699
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7700
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7701
                      (self.new_node, idx))
7702
      # create new devices on new_node; note that we create two IDs:
7703
      # one without port, so the drbd will be activated without
7704
      # networking information on the new node at this stage, and one
7705
      # with network, for the latter activation in step 4
7706
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7707
      if self.instance.primary_node == o_node1:
7708
        p_minor = o_minor1
7709
      else:
7710
        assert self.instance.primary_node == o_node2, "Three-node instance?"
7711
        p_minor = o_minor2
7712

    
7713
      new_alone_id = (self.instance.primary_node, self.new_node, None,
7714
                      p_minor, new_minor, o_secret)
7715
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
7716
                    p_minor, new_minor, o_secret)
7717

    
7718
      iv_names[idx] = (dev, dev.children, new_net_id)
7719
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
7720
                    new_net_id)
7721
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
7722
                              logical_id=new_alone_id,
7723
                              children=dev.children,
7724
                              size=dev.size)
7725
      try:
7726
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
7727
                              _GetInstanceInfoText(self.instance), False)
7728
      except errors.GenericError:
7729
        self.cfg.ReleaseDRBDMinors(self.instance.name)
7730
        raise
7731

    
7732
    # We have new devices, shutdown the drbd on the old secondary
7733
    for idx, dev in enumerate(self.instance.disks):
7734
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
7735
      self.cfg.SetDiskID(dev, self.target_node)
7736
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
7737
      if msg:
7738
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
7739
                           "node: %s" % (idx, msg),
7740
                           hint=("Please cleanup this device manually as"
7741
                                 " soon as possible"))
7742

    
7743
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
7744
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
7745
                                               self.node_secondary_ip,
7746
                                               self.instance.disks)\
7747
                                              [self.instance.primary_node]
7748

    
7749
    msg = result.fail_msg
7750
    if msg:
7751
      # detaches didn't succeed (unlikely)
7752
      self.cfg.ReleaseDRBDMinors(self.instance.name)
7753
      raise errors.OpExecError("Can't detach the disks from the network on"
7754
                               " old node: %s" % (msg,))
7755

    
7756
    # if we managed to detach at least one, we update all the disks of
7757
    # the instance to point to the new secondary
7758
    self.lu.LogInfo("Updating instance configuration")
7759
    for dev, _, new_logical_id in iv_names.itervalues():
7760
      dev.logical_id = new_logical_id
7761
      self.cfg.SetDiskID(dev, self.instance.primary_node)
7762

    
7763
    self.cfg.Update(self.instance, feedback_fn)
7764

    
7765
    # and now perform the drbd attach
7766
    self.lu.LogInfo("Attaching primary drbds to new secondary"
7767
                    " (standalone => connected)")
7768
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
7769
                                            self.new_node],
7770
                                           self.node_secondary_ip,
7771
                                           self.instance.disks,
7772
                                           self.instance.name,
7773
                                           False)
7774
    for to_node, to_result in result.items():
7775
      msg = to_result.fail_msg
7776
      if msg:
7777
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
7778
                           to_node, msg,
7779
                           hint=("please do a gnt-instance info to see the"
7780
                                 " status of disks"))
7781
    cstep = 5
7782
    if self.early_release:
7783
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7784
      cstep += 1
7785
      self._RemoveOldStorage(self.target_node, iv_names)
7786
      # WARNING: we release all node locks here, do not do other RPCs
7787
      # than WaitForSync to the primary node
7788
      self._ReleaseNodeLock([self.instance.primary_node,
7789
                             self.target_node,
7790
                             self.new_node])
7791

    
7792
    # Wait for sync
7793
    # This can fail as the old devices are degraded and _WaitForSync
7794
    # does a combined result over all disks, so we don't check its return value
7795
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7796
    cstep += 1
7797
    _WaitForSync(self.lu, self.instance)
7798

    
7799
    # Check all devices manually
7800
    self._CheckDevices(self.instance.primary_node, iv_names)
7801

    
7802
    # Step: remove old storage
7803
    if not self.early_release:
7804
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7805
      self._RemoveOldStorage(self.target_node, iv_names)
7806

    
7807

    
7808
class LURepairNodeStorage(NoHooksLU):
7809
  """Repairs the volume group on a node.
7810

7811
  """
7812
  _OP_REQP = ["node_name"]
7813
  REQ_BGL = False
7814

    
7815
  def CheckArguments(self):
7816
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
7817

    
7818
    _CheckStorageType(self.op.storage_type)
7819

    
7820
  def ExpandNames(self):
7821
    self.needed_locks = {
7822
      locking.LEVEL_NODE: [self.op.node_name],
7823
      }
7824

    
7825
  def _CheckFaultyDisks(self, instance, node_name):
7826
    """Ensure faulty disks abort the opcode or at least warn."""
7827
    try:
7828
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
7829
                                  node_name, True):
7830
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
7831
                                   " node '%s'" % (instance.name, node_name),
7832
                                   errors.ECODE_STATE)
7833
    except errors.OpPrereqError, err:
7834
      if self.op.ignore_consistency:
7835
        self.proc.LogWarning(str(err.args[0]))
7836
      else:
7837
        raise
7838

    
7839
  def CheckPrereq(self):
7840
    """Check prerequisites.
7841

7842
    """
7843
    storage_type = self.op.storage_type
7844

    
7845
    if (constants.SO_FIX_CONSISTENCY not in
7846
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
7847
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
7848
                                 " repaired" % storage_type,
7849
                                 errors.ECODE_INVAL)
7850

    
7851
    # Check whether any instance on this node has faulty disks
7852
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
7853
      if not inst.admin_up:
7854
        continue
7855
      check_nodes = set(inst.all_nodes)
7856
      check_nodes.discard(self.op.node_name)
7857
      for inst_node_name in check_nodes:
7858
        self._CheckFaultyDisks(inst, inst_node_name)
7859

    
7860
  def Exec(self, feedback_fn):
7861
    feedback_fn("Repairing storage unit '%s' on %s ..." %
7862
                (self.op.name, self.op.node_name))
7863

    
7864
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
7865
    result = self.rpc.call_storage_execute(self.op.node_name,
7866
                                           self.op.storage_type, st_args,
7867
                                           self.op.name,
7868
                                           constants.SO_FIX_CONSISTENCY)
7869
    result.Raise("Failed to repair storage unit '%s' on %s" %
7870
                 (self.op.name, self.op.node_name))
7871

    
7872

    
7873
class LUNodeEvacuationStrategy(NoHooksLU):
7874
  """Computes the node evacuation strategy.
7875

7876
  """
7877
  _OP_REQP = ["nodes"]
7878
  REQ_BGL = False
7879

    
7880
  def CheckArguments(self):
7881
    if not hasattr(self.op, "remote_node"):
7882
      self.op.remote_node = None
7883
    if not hasattr(self.op, "iallocator"):
7884
      self.op.iallocator = None
7885
    if self.op.remote_node is not None and self.op.iallocator is not None:
7886
      raise errors.OpPrereqError("Give either the iallocator or the new"
7887
                                 " secondary, not both", errors.ECODE_INVAL)
7888

    
7889
  def ExpandNames(self):
7890
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
7891
    self.needed_locks = locks = {}
7892
    if self.op.remote_node is None:
7893
      locks[locking.LEVEL_NODE] = locking.ALL_SET
7894
    else:
7895
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7896
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
7897

    
7898
  def CheckPrereq(self):
7899
    pass
7900

    
7901
  def Exec(self, feedback_fn):
7902
    if self.op.remote_node is not None:
7903
      instances = []
7904
      for node in self.op.nodes:
7905
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
7906
      result = []
7907
      for i in instances:
7908
        if i.primary_node == self.op.remote_node:
7909
          raise errors.OpPrereqError("Node %s is the primary node of"
7910
                                     " instance %s, cannot use it as"
7911
                                     " secondary" %
7912
                                     (self.op.remote_node, i.name),
7913
                                     errors.ECODE_INVAL)
7914
        result.append([i.name, self.op.remote_node])
7915
    else:
7916
      ial = IAllocator(self.cfg, self.rpc,
7917
                       mode=constants.IALLOCATOR_MODE_MEVAC,
7918
                       evac_nodes=self.op.nodes)
7919
      ial.Run(self.op.iallocator, validate=True)
7920
      if not ial.success:
7921
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
7922
                                 errors.ECODE_NORES)
7923
      result = ial.result
7924
    return result
7925

    
7926

    
7927
class LUGrowDisk(LogicalUnit):
7928
  """Grow a disk of an instance.
7929

7930
  """
7931
  HPATH = "disk-grow"
7932
  HTYPE = constants.HTYPE_INSTANCE
7933
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
7934
  REQ_BGL = False
7935

    
7936
  def ExpandNames(self):
7937
    self._ExpandAndLockInstance()
7938
    self.needed_locks[locking.LEVEL_NODE] = []
7939
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7940

    
7941
  def DeclareLocks(self, level):
7942
    if level == locking.LEVEL_NODE:
7943
      self._LockInstancesNodes()
7944

    
7945
  def BuildHooksEnv(self):
7946
    """Build hooks env.
7947

7948
    This runs on the master, the primary and all the secondaries.
7949

7950
    """
7951
    env = {
7952
      "DISK": self.op.disk,
7953
      "AMOUNT": self.op.amount,
7954
      }
7955
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7956
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7957
    return env, nl, nl
7958

    
7959
  def CheckPrereq(self):
7960
    """Check prerequisites.
7961

7962
    This checks that the instance is in the cluster.
7963

7964
    """
7965
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7966
    assert instance is not None, \
7967
      "Cannot retrieve locked instance %s" % self.op.instance_name
7968
    nodenames = list(instance.all_nodes)
7969
    for node in nodenames:
7970
      _CheckNodeOnline(self, node)
7971

    
7972

    
7973
    self.instance = instance
7974

    
7975
    if instance.disk_template not in constants.DTS_GROWABLE:
7976
      raise errors.OpPrereqError("Instance's disk layout does not support"
7977
                                 " growing.", errors.ECODE_INVAL)
7978

    
7979
    self.disk = instance.FindDisk(self.op.disk)
7980

    
7981
    if instance.disk_template != constants.DT_FILE:
7982
      # TODO: check the free disk space for file, when that feature will be
7983
      # supported
7984
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
7985

    
7986
  def Exec(self, feedback_fn):
7987
    """Execute disk grow.
7988

7989
    """
7990
    instance = self.instance
7991
    disk = self.disk
7992
    for node in instance.all_nodes:
7993
      self.cfg.SetDiskID(disk, node)
7994
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
7995
      result.Raise("Grow request failed to node %s" % node)
7996

    
7997
      # TODO: Rewrite code to work properly
7998
      # DRBD goes into sync mode for a short amount of time after executing the
7999
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8000
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8001
      # time is a work-around.
8002
      time.sleep(5)
8003

    
8004
    disk.RecordGrow(self.op.amount)
8005
    self.cfg.Update(instance, feedback_fn)
8006
    if self.op.wait_for_sync:
8007
      disk_abort = not _WaitForSync(self, instance)
8008
      if disk_abort:
8009
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8010
                             " status.\nPlease check the instance.")
8011

    
8012

    
8013
class LUQueryInstanceData(NoHooksLU):
8014
  """Query runtime instance data.
8015

8016
  """
8017
  _OP_REQP = ["instances", "static"]
8018
  REQ_BGL = False
8019

    
8020
  def ExpandNames(self):
8021
    self.needed_locks = {}
8022
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8023

    
8024
    if not isinstance(self.op.instances, list):
8025
      raise errors.OpPrereqError("Invalid argument type 'instances'",
8026
                                 errors.ECODE_INVAL)
8027

    
8028
    if self.op.instances:
8029
      self.wanted_names = []
8030
      for name in self.op.instances:
8031
        full_name = _ExpandInstanceName(self.cfg, name)
8032
        self.wanted_names.append(full_name)
8033
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8034
    else:
8035
      self.wanted_names = None
8036
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8037

    
8038
    self.needed_locks[locking.LEVEL_NODE] = []
8039
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8040

    
8041
  def DeclareLocks(self, level):
8042
    if level == locking.LEVEL_NODE:
8043
      self._LockInstancesNodes()
8044

    
8045
  def CheckPrereq(self):
8046
    """Check prerequisites.
8047

8048
    This only checks the optional instance list against the existing names.
8049

8050
    """
8051
    if self.wanted_names is None:
8052
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8053

    
8054
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8055
                             in self.wanted_names]
8056
    return
8057

    
8058
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8059
    """Returns the status of a block device
8060

8061
    """
8062
    if self.op.static or not node:
8063
      return None
8064

    
8065
    self.cfg.SetDiskID(dev, node)
8066

    
8067
    result = self.rpc.call_blockdev_find(node, dev)
8068
    if result.offline:
8069
      return None
8070

    
8071
    result.Raise("Can't compute disk status for %s" % instance_name)
8072

    
8073
    status = result.payload
8074
    if status is None:
8075
      return None
8076

    
8077
    return (status.dev_path, status.major, status.minor,
8078
            status.sync_percent, status.estimated_time,
8079
            status.is_degraded, status.ldisk_status)
8080

    
8081
  def _ComputeDiskStatus(self, instance, snode, dev):
8082
    """Compute block device status.
8083

8084
    """
8085
    if dev.dev_type in constants.LDS_DRBD:
8086
      # we change the snode then (otherwise we use the one passed in)
8087
      if dev.logical_id[0] == instance.primary_node:
8088
        snode = dev.logical_id[1]
8089
      else:
8090
        snode = dev.logical_id[0]
8091

    
8092
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8093
                                              instance.name, dev)
8094
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8095

    
8096
    if dev.children:
8097
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8098
                      for child in dev.children]
8099
    else:
8100
      dev_children = []
8101

    
8102
    data = {
8103
      "iv_name": dev.iv_name,
8104
      "dev_type": dev.dev_type,
8105
      "logical_id": dev.logical_id,
8106
      "physical_id": dev.physical_id,
8107
      "pstatus": dev_pstatus,
8108
      "sstatus": dev_sstatus,
8109
      "children": dev_children,
8110
      "mode": dev.mode,
8111
      "size": dev.size,
8112
      }
8113

    
8114
    return data
8115

    
8116
  def Exec(self, feedback_fn):
8117
    """Gather and return data"""
8118
    result = {}
8119

    
8120
    cluster = self.cfg.GetClusterInfo()
8121

    
8122
    for instance in self.wanted_instances:
8123
      if not self.op.static:
8124
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8125
                                                  instance.name,
8126
                                                  instance.hypervisor)
8127
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8128
        remote_info = remote_info.payload
8129
        if remote_info and "state" in remote_info:
8130
          remote_state = "up"
8131
        else:
8132
          remote_state = "down"
8133
      else:
8134
        remote_state = None
8135
      if instance.admin_up:
8136
        config_state = "up"
8137
      else:
8138
        config_state = "down"
8139

    
8140
      disks = [self._ComputeDiskStatus(instance, None, device)
8141
               for device in instance.disks]
8142

    
8143
      idict = {
8144
        "name": instance.name,
8145
        "config_state": config_state,
8146
        "run_state": remote_state,
8147
        "pnode": instance.primary_node,
8148
        "snodes": instance.secondary_nodes,
8149
        "os": instance.os,
8150
        # this happens to be the same format used for hooks
8151
        "nics": _NICListToTuple(self, instance.nics),
8152
        "disk_template": instance.disk_template,
8153
        "disks": disks,
8154
        "hypervisor": instance.hypervisor,
8155
        "network_port": instance.network_port,
8156
        "hv_instance": instance.hvparams,
8157
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8158
        "be_instance": instance.beparams,
8159
        "be_actual": cluster.FillBE(instance),
8160
        "serial_no": instance.serial_no,
8161
        "mtime": instance.mtime,
8162
        "ctime": instance.ctime,
8163
        "uuid": instance.uuid,
8164
        }
8165

    
8166
      result[instance.name] = idict
8167

    
8168
    return result
8169

    
8170

    
8171
class LUSetInstanceParams(LogicalUnit):
8172
  """Modifies an instances's parameters.
8173

8174
  """
8175
  HPATH = "instance-modify"
8176
  HTYPE = constants.HTYPE_INSTANCE
8177
  _OP_REQP = ["instance_name"]
8178
  REQ_BGL = False
8179

    
8180
  def CheckArguments(self):
8181
    if not hasattr(self.op, 'nics'):
8182
      self.op.nics = []
8183
    if not hasattr(self.op, 'disks'):
8184
      self.op.disks = []
8185
    if not hasattr(self.op, 'beparams'):
8186
      self.op.beparams = {}
8187
    if not hasattr(self.op, 'hvparams'):
8188
      self.op.hvparams = {}
8189
    if not hasattr(self.op, "disk_template"):
8190
      self.op.disk_template = None
8191
    if not hasattr(self.op, "remote_node"):
8192
      self.op.remote_node = None
8193
    if not hasattr(self.op, "os_name"):
8194
      self.op.os_name = None
8195
    if not hasattr(self.op, "force_variant"):
8196
      self.op.force_variant = False
8197
    self.op.force = getattr(self.op, "force", False)
8198
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8199
            self.op.hvparams or self.op.beparams or self.op.os_name):
8200
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8201

    
8202
    if self.op.hvparams:
8203
      _CheckGlobalHvParams(self.op.hvparams)
8204

    
8205
    # Disk validation
8206
    disk_addremove = 0
8207
    for disk_op, disk_dict in self.op.disks:
8208
      if disk_op == constants.DDM_REMOVE:
8209
        disk_addremove += 1
8210
        continue
8211
      elif disk_op == constants.DDM_ADD:
8212
        disk_addremove += 1
8213
      else:
8214
        if not isinstance(disk_op, int):
8215
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8216
        if not isinstance(disk_dict, dict):
8217
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8218
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8219

    
8220
      if disk_op == constants.DDM_ADD:
8221
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8222
        if mode not in constants.DISK_ACCESS_SET:
8223
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8224
                                     errors.ECODE_INVAL)
8225
        size = disk_dict.get('size', None)
8226
        if size is None:
8227
          raise errors.OpPrereqError("Required disk parameter size missing",
8228
                                     errors.ECODE_INVAL)
8229
        try:
8230
          size = int(size)
8231
        except (TypeError, ValueError), err:
8232
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8233
                                     str(err), errors.ECODE_INVAL)
8234
        disk_dict['size'] = size
8235
      else:
8236
        # modification of disk
8237
        if 'size' in disk_dict:
8238
          raise errors.OpPrereqError("Disk size change not possible, use"
8239
                                     " grow-disk", errors.ECODE_INVAL)
8240

    
8241
    if disk_addremove > 1:
8242
      raise errors.OpPrereqError("Only one disk add or remove operation"
8243
                                 " supported at a time", errors.ECODE_INVAL)
8244

    
8245
    if self.op.disks and self.op.disk_template is not None:
8246
      raise errors.OpPrereqError("Disk template conversion and other disk"
8247
                                 " changes not supported at the same time",
8248
                                 errors.ECODE_INVAL)
8249

    
8250
    if self.op.disk_template:
8251
      _CheckDiskTemplate(self.op.disk_template)
8252
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8253
          self.op.remote_node is None):
8254
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8255
                                   " one requires specifying a secondary node",
8256
                                   errors.ECODE_INVAL)
8257

    
8258
    # NIC validation
8259
    nic_addremove = 0
8260
    for nic_op, nic_dict in self.op.nics:
8261
      if nic_op == constants.DDM_REMOVE:
8262
        nic_addremove += 1
8263
        continue
8264
      elif nic_op == constants.DDM_ADD:
8265
        nic_addremove += 1
8266
      else:
8267
        if not isinstance(nic_op, int):
8268
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8269
        if not isinstance(nic_dict, dict):
8270
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8271
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8272

    
8273
      # nic_dict should be a dict
8274
      nic_ip = nic_dict.get('ip', None)
8275
      if nic_ip is not None:
8276
        if nic_ip.lower() == constants.VALUE_NONE:
8277
          nic_dict['ip'] = None
8278
        else:
8279
          if not utils.IsValidIP(nic_ip):
8280
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8281
                                       errors.ECODE_INVAL)
8282

    
8283
      nic_bridge = nic_dict.get('bridge', None)
8284
      nic_link = nic_dict.get('link', None)
8285
      if nic_bridge and nic_link:
8286
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8287
                                   " at the same time", errors.ECODE_INVAL)
8288
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8289
        nic_dict['bridge'] = None
8290
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8291
        nic_dict['link'] = None
8292

    
8293
      if nic_op == constants.DDM_ADD:
8294
        nic_mac = nic_dict.get('mac', None)
8295
        if nic_mac is None:
8296
          nic_dict['mac'] = constants.VALUE_AUTO
8297

    
8298
      if 'mac' in nic_dict:
8299
        nic_mac = nic_dict['mac']
8300
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8301
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8302

    
8303
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8304
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8305
                                     " modifying an existing nic",
8306
                                     errors.ECODE_INVAL)
8307

    
8308
    if nic_addremove > 1:
8309
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8310
                                 " supported at a time", errors.ECODE_INVAL)
8311

    
8312
  def ExpandNames(self):
8313
    self._ExpandAndLockInstance()
8314
    self.needed_locks[locking.LEVEL_NODE] = []
8315
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8316

    
8317
  def DeclareLocks(self, level):
8318
    if level == locking.LEVEL_NODE:
8319
      self._LockInstancesNodes()
8320
      if self.op.disk_template and self.op.remote_node:
8321
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8322
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8323

    
8324
  def BuildHooksEnv(self):
8325
    """Build hooks env.
8326

8327
    This runs on the master, primary and secondaries.
8328

8329
    """
8330
    args = dict()
8331
    if constants.BE_MEMORY in self.be_new:
8332
      args['memory'] = self.be_new[constants.BE_MEMORY]
8333
    if constants.BE_VCPUS in self.be_new:
8334
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8335
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8336
    # information at all.
8337
    if self.op.nics:
8338
      args['nics'] = []
8339
      nic_override = dict(self.op.nics)
8340
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
8341
      for idx, nic in enumerate(self.instance.nics):
8342
        if idx in nic_override:
8343
          this_nic_override = nic_override[idx]
8344
        else:
8345
          this_nic_override = {}
8346
        if 'ip' in this_nic_override:
8347
          ip = this_nic_override['ip']
8348
        else:
8349
          ip = nic.ip
8350
        if 'mac' in this_nic_override:
8351
          mac = this_nic_override['mac']
8352
        else:
8353
          mac = nic.mac
8354
        if idx in self.nic_pnew:
8355
          nicparams = self.nic_pnew[idx]
8356
        else:
8357
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
8358
        mode = nicparams[constants.NIC_MODE]
8359
        link = nicparams[constants.NIC_LINK]
8360
        args['nics'].append((ip, mac, mode, link))
8361
      if constants.DDM_ADD in nic_override:
8362
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8363
        mac = nic_override[constants.DDM_ADD]['mac']
8364
        nicparams = self.nic_pnew[constants.DDM_ADD]
8365
        mode = nicparams[constants.NIC_MODE]
8366
        link = nicparams[constants.NIC_LINK]
8367
        args['nics'].append((ip, mac, mode, link))
8368
      elif constants.DDM_REMOVE in nic_override:
8369
        del args['nics'][-1]
8370

    
8371
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8372
    if self.op.disk_template:
8373
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8374
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8375
    return env, nl, nl
8376

    
8377
  @staticmethod
8378
  def _GetUpdatedParams(old_params, update_dict,
8379
                        default_values, parameter_types):
8380
    """Return the new params dict for the given params.
8381

8382
    @type old_params: dict
8383
    @param old_params: old parameters
8384
    @type update_dict: dict
8385
    @param update_dict: dict containing new parameter values,
8386
                        or constants.VALUE_DEFAULT to reset the
8387
                        parameter to its default value
8388
    @type default_values: dict
8389
    @param default_values: default values for the filled parameters
8390
    @type parameter_types: dict
8391
    @param parameter_types: dict mapping target dict keys to types
8392
                            in constants.ENFORCEABLE_TYPES
8393
    @rtype: (dict, dict)
8394
    @return: (new_parameters, filled_parameters)
8395

8396
    """
8397
    params_copy = copy.deepcopy(old_params)
8398
    for key, val in update_dict.iteritems():
8399
      if val == constants.VALUE_DEFAULT:
8400
        try:
8401
          del params_copy[key]
8402
        except KeyError:
8403
          pass
8404
      else:
8405
        params_copy[key] = val
8406
    utils.ForceDictType(params_copy, parameter_types)
8407
    params_filled = objects.FillDict(default_values, params_copy)
8408
    return (params_copy, params_filled)
8409

    
8410
  def CheckPrereq(self):
8411
    """Check prerequisites.
8412

8413
    This only checks the instance list against the existing names.
8414

8415
    """
8416
    self.force = self.op.force
8417

    
8418
    # checking the new params on the primary/secondary nodes
8419

    
8420
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8421
    cluster = self.cluster = self.cfg.GetClusterInfo()
8422
    assert self.instance is not None, \
8423
      "Cannot retrieve locked instance %s" % self.op.instance_name
8424
    pnode = instance.primary_node
8425
    nodelist = list(instance.all_nodes)
8426

    
8427
    if self.op.disk_template:
8428
      if instance.disk_template == self.op.disk_template:
8429
        raise errors.OpPrereqError("Instance already has disk template %s" %
8430
                                   instance.disk_template, errors.ECODE_INVAL)
8431

    
8432
      if (instance.disk_template,
8433
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8434
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8435
                                   " %s to %s" % (instance.disk_template,
8436
                                                  self.op.disk_template),
8437
                                   errors.ECODE_INVAL)
8438
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8439
        _CheckNodeOnline(self, self.op.remote_node)
8440
        _CheckNodeNotDrained(self, self.op.remote_node)
8441
        disks = [{"size": d.size} for d in instance.disks]
8442
        required = _ComputeDiskSize(self.op.disk_template, disks)
8443
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8444
        _CheckInstanceDown(self, instance, "cannot change disk template")
8445

    
8446
    # hvparams processing
8447
    if self.op.hvparams:
8448
      i_hvdict, hv_new = self._GetUpdatedParams(
8449
                             instance.hvparams, self.op.hvparams,
8450
                             cluster.hvparams[instance.hypervisor],
8451
                             constants.HVS_PARAMETER_TYPES)
8452
      # local check
8453
      hypervisor.GetHypervisor(
8454
        instance.hypervisor).CheckParameterSyntax(hv_new)
8455
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8456
      self.hv_new = hv_new # the new actual values
8457
      self.hv_inst = i_hvdict # the new dict (without defaults)
8458
    else:
8459
      self.hv_new = self.hv_inst = {}
8460

    
8461
    # beparams processing
8462
    if self.op.beparams:
8463
      i_bedict, be_new = self._GetUpdatedParams(
8464
                             instance.beparams, self.op.beparams,
8465
                             cluster.beparams[constants.PP_DEFAULT],
8466
                             constants.BES_PARAMETER_TYPES)
8467
      self.be_new = be_new # the new actual values
8468
      self.be_inst = i_bedict # the new dict (without defaults)
8469
    else:
8470
      self.be_new = self.be_inst = {}
8471

    
8472
    self.warn = []
8473

    
8474
    if constants.BE_MEMORY in self.op.beparams and not self.force:
8475
      mem_check_list = [pnode]
8476
      if be_new[constants.BE_AUTO_BALANCE]:
8477
        # either we changed auto_balance to yes or it was from before
8478
        mem_check_list.extend(instance.secondary_nodes)
8479
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8480
                                                  instance.hypervisor)
8481
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8482
                                         instance.hypervisor)
8483
      pninfo = nodeinfo[pnode]
8484
      msg = pninfo.fail_msg
8485
      if msg:
8486
        # Assume the primary node is unreachable and go ahead
8487
        self.warn.append("Can't get info from primary node %s: %s" %
8488
                         (pnode,  msg))
8489
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8490
        self.warn.append("Node data from primary node %s doesn't contain"
8491
                         " free memory information" % pnode)
8492
      elif instance_info.fail_msg:
8493
        self.warn.append("Can't get instance runtime information: %s" %
8494
                        instance_info.fail_msg)
8495
      else:
8496
        if instance_info.payload:
8497
          current_mem = int(instance_info.payload['memory'])
8498
        else:
8499
          # Assume instance not running
8500
          # (there is a slight race condition here, but it's not very probable,
8501
          # and we have no other way to check)
8502
          current_mem = 0
8503
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8504
                    pninfo.payload['memory_free'])
8505
        if miss_mem > 0:
8506
          raise errors.OpPrereqError("This change will prevent the instance"
8507
                                     " from starting, due to %d MB of memory"
8508
                                     " missing on its primary node" % miss_mem,
8509
                                     errors.ECODE_NORES)
8510

    
8511
      if be_new[constants.BE_AUTO_BALANCE]:
8512
        for node, nres in nodeinfo.items():
8513
          if node not in instance.secondary_nodes:
8514
            continue
8515
          msg = nres.fail_msg
8516
          if msg:
8517
            self.warn.append("Can't get info from secondary node %s: %s" %
8518
                             (node, msg))
8519
          elif not isinstance(nres.payload.get('memory_free', None), int):
8520
            self.warn.append("Secondary node %s didn't return free"
8521
                             " memory information" % node)
8522
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8523
            self.warn.append("Not enough memory to failover instance to"
8524
                             " secondary node %s" % node)
8525

    
8526
    # NIC processing
8527
    self.nic_pnew = {}
8528
    self.nic_pinst = {}
8529
    for nic_op, nic_dict in self.op.nics:
8530
      if nic_op == constants.DDM_REMOVE:
8531
        if not instance.nics:
8532
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8533
                                     errors.ECODE_INVAL)
8534
        continue
8535
      if nic_op != constants.DDM_ADD:
8536
        # an existing nic
8537
        if not instance.nics:
8538
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8539
                                     " no NICs" % nic_op,
8540
                                     errors.ECODE_INVAL)
8541
        if nic_op < 0 or nic_op >= len(instance.nics):
8542
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8543
                                     " are 0 to %d" %
8544
                                     (nic_op, len(instance.nics) - 1),
8545
                                     errors.ECODE_INVAL)
8546
        old_nic_params = instance.nics[nic_op].nicparams
8547
        old_nic_ip = instance.nics[nic_op].ip
8548
      else:
8549
        old_nic_params = {}
8550
        old_nic_ip = None
8551

    
8552
      update_params_dict = dict([(key, nic_dict[key])
8553
                                 for key in constants.NICS_PARAMETERS
8554
                                 if key in nic_dict])
8555

    
8556
      if 'bridge' in nic_dict:
8557
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8558

    
8559
      new_nic_params, new_filled_nic_params = \
8560
          self._GetUpdatedParams(old_nic_params, update_params_dict,
8561
                                 cluster.nicparams[constants.PP_DEFAULT],
8562
                                 constants.NICS_PARAMETER_TYPES)
8563
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8564
      self.nic_pinst[nic_op] = new_nic_params
8565
      self.nic_pnew[nic_op] = new_filled_nic_params
8566
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8567

    
8568
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8569
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8570
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8571
        if msg:
8572
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8573
          if self.force:
8574
            self.warn.append(msg)
8575
          else:
8576
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8577
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8578
        if 'ip' in nic_dict:
8579
          nic_ip = nic_dict['ip']
8580
        else:
8581
          nic_ip = old_nic_ip
8582
        if nic_ip is None:
8583
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8584
                                     ' on a routed nic', errors.ECODE_INVAL)
8585
      if 'mac' in nic_dict:
8586
        nic_mac = nic_dict['mac']
8587
        if nic_mac is None:
8588
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8589
                                     errors.ECODE_INVAL)
8590
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8591
          # otherwise generate the mac
8592
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8593
        else:
8594
          # or validate/reserve the current one
8595
          try:
8596
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8597
          except errors.ReservationError:
8598
            raise errors.OpPrereqError("MAC address %s already in use"
8599
                                       " in cluster" % nic_mac,
8600
                                       errors.ECODE_NOTUNIQUE)
8601

    
8602
    # DISK processing
8603
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8604
      raise errors.OpPrereqError("Disk operations not supported for"
8605
                                 " diskless instances",
8606
                                 errors.ECODE_INVAL)
8607
    for disk_op, _ in self.op.disks:
8608
      if disk_op == constants.DDM_REMOVE:
8609
        if len(instance.disks) == 1:
8610
          raise errors.OpPrereqError("Cannot remove the last disk of"
8611
                                     " an instance", errors.ECODE_INVAL)
8612
        _CheckInstanceDown(self, instance, "cannot remove disks")
8613

    
8614
      if (disk_op == constants.DDM_ADD and
8615
          len(instance.nics) >= constants.MAX_DISKS):
8616
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8617
                                   " add more" % constants.MAX_DISKS,
8618
                                   errors.ECODE_STATE)
8619
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8620
        # an existing disk
8621
        if disk_op < 0 or disk_op >= len(instance.disks):
8622
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8623
                                     " are 0 to %d" %
8624
                                     (disk_op, len(instance.disks)),
8625
                                     errors.ECODE_INVAL)
8626

    
8627
    # OS change
8628
    if self.op.os_name and not self.op.force:
8629
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8630
                      self.op.force_variant)
8631

    
8632
    return
8633

    
8634
  def _ConvertPlainToDrbd(self, feedback_fn):
8635
    """Converts an instance from plain to drbd.
8636

8637
    """
8638
    feedback_fn("Converting template to drbd")
8639
    instance = self.instance
8640
    pnode = instance.primary_node
8641
    snode = self.op.remote_node
8642

    
8643
    # create a fake disk info for _GenerateDiskTemplate
8644
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
8645
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
8646
                                      instance.name, pnode, [snode],
8647
                                      disk_info, None, None, 0)
8648
    info = _GetInstanceInfoText(instance)
8649
    feedback_fn("Creating aditional volumes...")
8650
    # first, create the missing data and meta devices
8651
    for disk in new_disks:
8652
      # unfortunately this is... not too nice
8653
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
8654
                            info, True)
8655
      for child in disk.children:
8656
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
8657
    # at this stage, all new LVs have been created, we can rename the
8658
    # old ones
8659
    feedback_fn("Renaming original volumes...")
8660
    rename_list = [(o, n.children[0].logical_id)
8661
                   for (o, n) in zip(instance.disks, new_disks)]
8662
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
8663
    result.Raise("Failed to rename original LVs")
8664

    
8665
    feedback_fn("Initializing DRBD devices...")
8666
    # all child devices are in place, we can now create the DRBD devices
8667
    for disk in new_disks:
8668
      for node in [pnode, snode]:
8669
        f_create = node == pnode
8670
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
8671

    
8672
    # at this point, the instance has been modified
8673
    instance.disk_template = constants.DT_DRBD8
8674
    instance.disks = new_disks
8675
    self.cfg.Update(instance, feedback_fn)
8676

    
8677
    # disks are created, waiting for sync
8678
    disk_abort = not _WaitForSync(self, instance)
8679
    if disk_abort:
8680
      raise errors.OpExecError("There are some degraded disks for"
8681
                               " this instance, please cleanup manually")
8682

    
8683
  def _ConvertDrbdToPlain(self, feedback_fn):
8684
    """Converts an instance from drbd to plain.
8685

8686
    """
8687
    instance = self.instance
8688
    assert len(instance.secondary_nodes) == 1
8689
    pnode = instance.primary_node
8690
    snode = instance.secondary_nodes[0]
8691
    feedback_fn("Converting template to plain")
8692

    
8693
    old_disks = instance.disks
8694
    new_disks = [d.children[0] for d in old_disks]
8695

    
8696
    # copy over size and mode
8697
    for parent, child in zip(old_disks, new_disks):
8698
      child.size = parent.size
8699
      child.mode = parent.mode
8700

    
8701
    # update instance structure
8702
    instance.disks = new_disks
8703
    instance.disk_template = constants.DT_PLAIN
8704
    self.cfg.Update(instance, feedback_fn)
8705

    
8706
    feedback_fn("Removing volumes on the secondary node...")
8707
    for disk in old_disks:
8708
      self.cfg.SetDiskID(disk, snode)
8709
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
8710
      if msg:
8711
        self.LogWarning("Could not remove block device %s on node %s,"
8712
                        " continuing anyway: %s", disk.iv_name, snode, msg)
8713

    
8714
    feedback_fn("Removing unneeded volumes on the primary node...")
8715
    for idx, disk in enumerate(old_disks):
8716
      meta = disk.children[1]
8717
      self.cfg.SetDiskID(meta, pnode)
8718
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
8719
      if msg:
8720
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
8721
                        " continuing anyway: %s", idx, pnode, msg)
8722

    
8723

    
8724
  def Exec(self, feedback_fn):
8725
    """Modifies an instance.
8726

8727
    All parameters take effect only at the next restart of the instance.
8728

8729
    """
8730
    # Process here the warnings from CheckPrereq, as we don't have a
8731
    # feedback_fn there.
8732
    for warn in self.warn:
8733
      feedback_fn("WARNING: %s" % warn)
8734

    
8735
    result = []
8736
    instance = self.instance
8737
    # disk changes
8738
    for disk_op, disk_dict in self.op.disks:
8739
      if disk_op == constants.DDM_REMOVE:
8740
        # remove the last disk
8741
        device = instance.disks.pop()
8742
        device_idx = len(instance.disks)
8743
        for node, disk in device.ComputeNodeTree(instance.primary_node):
8744
          self.cfg.SetDiskID(disk, node)
8745
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
8746
          if msg:
8747
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
8748
                            " continuing anyway", device_idx, node, msg)
8749
        result.append(("disk/%d" % device_idx, "remove"))
8750
      elif disk_op == constants.DDM_ADD:
8751
        # add a new disk
8752
        if instance.disk_template == constants.DT_FILE:
8753
          file_driver, file_path = instance.disks[0].logical_id
8754
          file_path = os.path.dirname(file_path)
8755
        else:
8756
          file_driver = file_path = None
8757
        disk_idx_base = len(instance.disks)
8758
        new_disk = _GenerateDiskTemplate(self,
8759
                                         instance.disk_template,
8760
                                         instance.name, instance.primary_node,
8761
                                         instance.secondary_nodes,
8762
                                         [disk_dict],
8763
                                         file_path,
8764
                                         file_driver,
8765
                                         disk_idx_base)[0]
8766
        instance.disks.append(new_disk)
8767
        info = _GetInstanceInfoText(instance)
8768

    
8769
        logging.info("Creating volume %s for instance %s",
8770
                     new_disk.iv_name, instance.name)
8771
        # Note: this needs to be kept in sync with _CreateDisks
8772
        #HARDCODE
8773
        for node in instance.all_nodes:
8774
          f_create = node == instance.primary_node
8775
          try:
8776
            _CreateBlockDev(self, node, instance, new_disk,
8777
                            f_create, info, f_create)
8778
          except errors.OpExecError, err:
8779
            self.LogWarning("Failed to create volume %s (%s) on"
8780
                            " node %s: %s",
8781
                            new_disk.iv_name, new_disk, node, err)
8782
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
8783
                       (new_disk.size, new_disk.mode)))
8784
      else:
8785
        # change a given disk
8786
        instance.disks[disk_op].mode = disk_dict['mode']
8787
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
8788

    
8789
    if self.op.disk_template:
8790
      r_shut = _ShutdownInstanceDisks(self, instance)
8791
      if not r_shut:
8792
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
8793
                                 " proceed with disk template conversion")
8794
      mode = (instance.disk_template, self.op.disk_template)
8795
      try:
8796
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
8797
      except:
8798
        self.cfg.ReleaseDRBDMinors(instance.name)
8799
        raise
8800
      result.append(("disk_template", self.op.disk_template))
8801

    
8802
    # NIC changes
8803
    for nic_op, nic_dict in self.op.nics:
8804
      if nic_op == constants.DDM_REMOVE:
8805
        # remove the last nic
8806
        del instance.nics[-1]
8807
        result.append(("nic.%d" % len(instance.nics), "remove"))
8808
      elif nic_op == constants.DDM_ADD:
8809
        # mac and bridge should be set, by now
8810
        mac = nic_dict['mac']
8811
        ip = nic_dict.get('ip', None)
8812
        nicparams = self.nic_pinst[constants.DDM_ADD]
8813
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
8814
        instance.nics.append(new_nic)
8815
        result.append(("nic.%d" % (len(instance.nics) - 1),
8816
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
8817
                       (new_nic.mac, new_nic.ip,
8818
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
8819
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
8820
                       )))
8821
      else:
8822
        for key in 'mac', 'ip':
8823
          if key in nic_dict:
8824
            setattr(instance.nics[nic_op], key, nic_dict[key])
8825
        if nic_op in self.nic_pinst:
8826
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
8827
        for key, val in nic_dict.iteritems():
8828
          result.append(("nic.%s/%d" % (key, nic_op), val))
8829

    
8830
    # hvparams changes
8831
    if self.op.hvparams:
8832
      instance.hvparams = self.hv_inst
8833
      for key, val in self.op.hvparams.iteritems():
8834
        result.append(("hv/%s" % key, val))
8835

    
8836
    # beparams changes
8837
    if self.op.beparams:
8838
      instance.beparams = self.be_inst
8839
      for key, val in self.op.beparams.iteritems():
8840
        result.append(("be/%s" % key, val))
8841

    
8842
    # OS change
8843
    if self.op.os_name:
8844
      instance.os = self.op.os_name
8845

    
8846
    self.cfg.Update(instance, feedback_fn)
8847

    
8848
    return result
8849

    
8850
  _DISK_CONVERSIONS = {
8851
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
8852
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
8853
    }
8854

    
8855

    
8856
class LUQueryExports(NoHooksLU):
8857
  """Query the exports list
8858

8859
  """
8860
  _OP_REQP = ['nodes']
8861
  REQ_BGL = False
8862

    
8863
  def ExpandNames(self):
8864
    self.needed_locks = {}
8865
    self.share_locks[locking.LEVEL_NODE] = 1
8866
    if not self.op.nodes:
8867
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8868
    else:
8869
      self.needed_locks[locking.LEVEL_NODE] = \
8870
        _GetWantedNodes(self, self.op.nodes)
8871

    
8872
  def CheckPrereq(self):
8873
    """Check prerequisites.
8874

8875
    """
8876
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
8877

    
8878
  def Exec(self, feedback_fn):
8879
    """Compute the list of all the exported system images.
8880

8881
    @rtype: dict
8882
    @return: a dictionary with the structure node->(export-list)
8883
        where export-list is a list of the instances exported on
8884
        that node.
8885

8886
    """
8887
    rpcresult = self.rpc.call_export_list(self.nodes)
8888
    result = {}
8889
    for node in rpcresult:
8890
      if rpcresult[node].fail_msg:
8891
        result[node] = False
8892
      else:
8893
        result[node] = rpcresult[node].payload
8894

    
8895
    return result
8896

    
8897

    
8898
class LUPrepareExport(NoHooksLU):
8899
  """Prepares an instance for an export and returns useful information.
8900

8901
  """
8902
  _OP_REQP = ["instance_name", "mode"]
8903
  REQ_BGL = False
8904

    
8905
  def CheckArguments(self):
8906
    """Check the arguments.
8907

8908
    """
8909
    if self.op.mode not in constants.EXPORT_MODES:
8910
      raise errors.OpPrereqError("Invalid export mode %r" % self.op.mode,
8911
                                 errors.ECODE_INVAL)
8912

    
8913
  def ExpandNames(self):
8914
    self._ExpandAndLockInstance()
8915

    
8916
  def CheckPrereq(self):
8917
    """Check prerequisites.
8918

8919
    """
8920
    instance_name = self.op.instance_name
8921

    
8922
    self.instance = self.cfg.GetInstanceInfo(instance_name)
8923
    assert self.instance is not None, \
8924
          "Cannot retrieve locked instance %s" % self.op.instance_name
8925
    _CheckNodeOnline(self, self.instance.primary_node)
8926

    
8927
    self._cds = _GetClusterDomainSecret()
8928

    
8929
  def Exec(self, feedback_fn):
8930
    """Prepares an instance for an export.
8931

8932
    """
8933
    instance = self.instance
8934

    
8935
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
8936
      salt = utils.GenerateSecret(8)
8937

    
8938
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
8939
      result = self.rpc.call_x509_cert_create(instance.primary_node,
8940
                                              constants.RIE_CERT_VALIDITY)
8941
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
8942

    
8943
      (name, cert_pem) = result.payload
8944

    
8945
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
8946
                                             cert_pem)
8947

    
8948
      return {
8949
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
8950
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
8951
                          salt),
8952
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
8953
        }
8954

    
8955
    return None
8956

    
8957

    
8958
class LUExportInstance(LogicalUnit):
8959
  """Export an instance to an image in the cluster.
8960

8961
  """
8962
  HPATH = "instance-export"
8963
  HTYPE = constants.HTYPE_INSTANCE
8964
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
8965
  REQ_BGL = False
8966

    
8967
  def CheckArguments(self):
8968
    """Check the arguments.
8969

8970
    """
8971
    _CheckBooleanOpField(self.op, "remove_instance")
8972
    _CheckBooleanOpField(self.op, "ignore_remove_failures")
8973

    
8974
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
8975
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
8976
    self.remove_instance = getattr(self.op, "remove_instance", False)
8977
    self.ignore_remove_failures = getattr(self.op, "ignore_remove_failures",
8978
                                          False)
8979
    self.export_mode = getattr(self.op, "mode", constants.EXPORT_MODE_LOCAL)
8980
    self.x509_key_name = getattr(self.op, "x509_key_name", None)
8981
    self.dest_x509_ca_pem = getattr(self.op, "destination_x509_ca", None)
8982

    
8983
    if self.remove_instance and not self.op.shutdown:
8984
      raise errors.OpPrereqError("Can not remove instance without shutting it"
8985
                                 " down before")
8986

    
8987
    if self.export_mode not in constants.EXPORT_MODES:
8988
      raise errors.OpPrereqError("Invalid export mode %r" % self.export_mode,
8989
                                 errors.ECODE_INVAL)
8990

    
8991
    if self.export_mode == constants.EXPORT_MODE_REMOTE:
8992
      if not self.x509_key_name:
8993
        raise errors.OpPrereqError("Missing X509 key name for encryption",
8994
                                   errors.ECODE_INVAL)
8995

    
8996
      if not self.dest_x509_ca_pem:
8997
        raise errors.OpPrereqError("Missing destination X509 CA",
8998
                                   errors.ECODE_INVAL)
8999

    
9000
  def ExpandNames(self):
9001
    self._ExpandAndLockInstance()
9002

    
9003
    # Lock all nodes for local exports
9004
    if self.export_mode == constants.EXPORT_MODE_LOCAL:
9005
      # FIXME: lock only instance primary and destination node
9006
      #
9007
      # Sad but true, for now we have do lock all nodes, as we don't know where
9008
      # the previous export might be, and in this LU we search for it and
9009
      # remove it from its current node. In the future we could fix this by:
9010
      #  - making a tasklet to search (share-lock all), then create the new one,
9011
      #    then one to remove, after
9012
      #  - removing the removal operation altogether
9013
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9014

    
9015
  def DeclareLocks(self, level):
9016
    """Last minute lock declaration."""
9017
    # All nodes are locked anyway, so nothing to do here.
9018

    
9019
  def BuildHooksEnv(self):
9020
    """Build hooks env.
9021

9022
    This will run on the master, primary node and target node.
9023

9024
    """
9025
    env = {
9026
      "EXPORT_MODE": self.export_mode,
9027
      "EXPORT_NODE": self.op.target_node,
9028
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9029
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
9030
      # TODO: Generic function for boolean env variables
9031
      "REMOVE_INSTANCE": str(bool(self.remove_instance)),
9032
      }
9033

    
9034
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9035

    
9036
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9037

    
9038
    if self.export_mode == constants.EXPORT_MODE_LOCAL:
9039
      nl.append(self.op.target_node)
9040

    
9041
    return env, nl, nl
9042

    
9043
  def CheckPrereq(self):
9044
    """Check prerequisites.
9045

9046
    This checks that the instance and node names are valid.
9047

9048
    """
9049
    instance_name = self.op.instance_name
9050

    
9051
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9052
    assert self.instance is not None, \
9053
          "Cannot retrieve locked instance %s" % self.op.instance_name
9054
    _CheckNodeOnline(self, self.instance.primary_node)
9055

    
9056
    if self.export_mode == constants.EXPORT_MODE_LOCAL:
9057
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9058
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9059
      assert self.dst_node is not None
9060

    
9061
      _CheckNodeOnline(self, self.dst_node.name)
9062
      _CheckNodeNotDrained(self, self.dst_node.name)
9063

    
9064
      self._cds = None
9065
      self.dest_x509_ca = None
9066

    
9067
    elif self.export_mode == constants.EXPORT_MODE_REMOTE:
9068
      self.dst_node = None
9069

    
9070
      if len(self.op.target_node) != len(self.instance.disks):
9071
        raise errors.OpPrereqError(("Received destination information for %s"
9072
                                    " disks, but instance %s has %s disks") %
9073
                                   (len(self.op.target_node), instance_name,
9074
                                    len(self.instance.disks)),
9075
                                   errors.ECODE_INVAL)
9076

    
9077
      cds = _GetClusterDomainSecret()
9078

    
9079
      # Check X509 key name
9080
      try:
9081
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9082
      except (TypeError, ValueError), err:
9083
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9084

    
9085
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9086
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9087
                                   errors.ECODE_INVAL)
9088

    
9089
      # Load and verify CA
9090
      try:
9091
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9092
      except OpenSSL.crypto.Error, err:
9093
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9094
                                   (err, ), errors.ECODE_INVAL)
9095

    
9096
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9097
      if errcode is not None:
9098
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" % (msg, ),
9099
                                   errors.ECODE_INVAL)
9100

    
9101
      self.dest_x509_ca = cert
9102

    
9103
      # Verify target information
9104
      for idx, disk_data in enumerate(self.op.target_node):
9105
        try:
9106
          masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9107
        except errors.GenericError, err:
9108
          raise errors.OpPrereqError("Target info for disk %s: %s" % (idx, err),
9109
                                     errors.ECODE_INVAL)
9110

    
9111
    else:
9112
      raise errors.ProgrammerError("Unhandled export mode %r" %
9113
                                   self.export_mode)
9114

    
9115
    # instance disk type verification
9116
    # TODO: Implement export support for file-based disks
9117
    for disk in self.instance.disks:
9118
      if disk.dev_type == constants.LD_FILE:
9119
        raise errors.OpPrereqError("Export not supported for instances with"
9120
                                   " file-based disks", errors.ECODE_INVAL)
9121

    
9122
  def _CleanupExports(self, feedback_fn):
9123
    """Removes exports of current instance from all other nodes.
9124

9125
    If an instance in a cluster with nodes A..D was exported to node C, its
9126
    exports will be removed from the nodes A, B and D.
9127

9128
    """
9129
    assert self.export_mode != constants.EXPORT_MODE_REMOTE
9130

    
9131
    nodelist = self.cfg.GetNodeList()
9132
    nodelist.remove(self.dst_node.name)
9133

    
9134
    # on one-node clusters nodelist will be empty after the removal
9135
    # if we proceed the backup would be removed because OpQueryExports
9136
    # substitutes an empty list with the full cluster node list.
9137
    iname = self.instance.name
9138
    if nodelist:
9139
      feedback_fn("Removing old exports for instance %s" % iname)
9140
      exportlist = self.rpc.call_export_list(nodelist)
9141
      for node in exportlist:
9142
        if exportlist[node].fail_msg:
9143
          continue
9144
        if iname in exportlist[node].payload:
9145
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9146
          if msg:
9147
            self.LogWarning("Could not remove older export for instance %s"
9148
                            " on node %s: %s", iname, node, msg)
9149

    
9150
  def Exec(self, feedback_fn):
9151
    """Export an instance to an image in the cluster.
9152

9153
    """
9154
    assert self.export_mode in constants.EXPORT_MODES
9155

    
9156
    instance = self.instance
9157
    src_node = instance.primary_node
9158

    
9159
    if self.op.shutdown:
9160
      # shutdown the instance, but not the disks
9161
      feedback_fn("Shutting down instance %s" % instance.name)
9162
      result = self.rpc.call_instance_shutdown(src_node, instance,
9163
                                               self.shutdown_timeout)
9164
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9165
      result.Raise("Could not shutdown instance %s on"
9166
                   " node %s" % (instance.name, src_node))
9167

    
9168
    # set the disks ID correctly since call_instance_start needs the
9169
    # correct drbd minor to create the symlinks
9170
    for disk in instance.disks:
9171
      self.cfg.SetDiskID(disk, src_node)
9172

    
9173
    activate_disks = (not instance.admin_up)
9174

    
9175
    if activate_disks:
9176
      # Activate the instance disks if we'exporting a stopped instance
9177
      feedback_fn("Activating disks for %s" % instance.name)
9178
      _StartInstanceDisks(self, instance, None)
9179

    
9180
    try:
9181
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9182
                                                     instance)
9183

    
9184
      helper.CreateSnapshots()
9185
      try:
9186
        if self.export_mode == constants.EXPORT_MODE_LOCAL:
9187
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9188
        elif self.export_mode == constants.EXPORT_MODE_REMOTE:
9189
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9190
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9191

    
9192
          (key_name, _, _) = self.x509_key_name
9193

    
9194
          dest_ca_pem = \
9195
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9196
                                            self.dest_x509_ca)
9197

    
9198
          opts = objects.ImportExportOptions(key_name=key_name,
9199
                                             ca_pem=dest_ca_pem)
9200

    
9201
          (fin_resu, dresults) = helper.RemoteExport(opts, self.op.target_node,
9202
                                                     timeouts)
9203
      finally:
9204
        helper.Cleanup()
9205

    
9206
      # Check for backwards compatibility
9207
      assert len(dresults) == len(instance.disks)
9208
      assert compat.all(isinstance(i, bool) for i in dresults), \
9209
             "Not all results are boolean: %r" % dresults
9210

    
9211
    finally:
9212
      if activate_disks:
9213
        feedback_fn("Deactivating disks for %s" % instance.name)
9214
        _ShutdownInstanceDisks(self, instance)
9215

    
9216
    # Remove instance if requested
9217
    if self.remove_instance:
9218
      if not (compat.all(dresults) and fin_resu):
9219
        feedback_fn("Not removing instance %s as parts of the export failed" %
9220
                    instance.name)
9221
      else:
9222
        feedback_fn("Removing instance %s" % instance.name)
9223
        _RemoveInstance(self, feedback_fn, instance,
9224
                        self.ignore_remove_failures)
9225

    
9226
    if self.export_mode == constants.EXPORT_MODE_LOCAL:
9227
      self._CleanupExports(feedback_fn)
9228

    
9229
    return fin_resu, dresults
9230

    
9231

    
9232
class LURemoveExport(NoHooksLU):
9233
  """Remove exports related to the named instance.
9234

9235
  """
9236
  _OP_REQP = ["instance_name"]
9237
  REQ_BGL = False
9238

    
9239
  def ExpandNames(self):
9240
    self.needed_locks = {}
9241
    # We need all nodes to be locked in order for RemoveExport to work, but we
9242
    # don't need to lock the instance itself, as nothing will happen to it (and
9243
    # we can remove exports also for a removed instance)
9244
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9245

    
9246
  def CheckPrereq(self):
9247
    """Check prerequisites.
9248
    """
9249
    pass
9250

    
9251
  def Exec(self, feedback_fn):
9252
    """Remove any export.
9253

9254
    """
9255
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9256
    # If the instance was not found we'll try with the name that was passed in.
9257
    # This will only work if it was an FQDN, though.
9258
    fqdn_warn = False
9259
    if not instance_name:
9260
      fqdn_warn = True
9261
      instance_name = self.op.instance_name
9262

    
9263
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9264
    exportlist = self.rpc.call_export_list(locked_nodes)
9265
    found = False
9266
    for node in exportlist:
9267
      msg = exportlist[node].fail_msg
9268
      if msg:
9269
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9270
        continue
9271
      if instance_name in exportlist[node].payload:
9272
        found = True
9273
        result = self.rpc.call_export_remove(node, instance_name)
9274
        msg = result.fail_msg
9275
        if msg:
9276
          logging.error("Could not remove export for instance %s"
9277
                        " on node %s: %s", instance_name, node, msg)
9278

    
9279
    if fqdn_warn and not found:
9280
      feedback_fn("Export not found. If trying to remove an export belonging"
9281
                  " to a deleted instance please use its Fully Qualified"
9282
                  " Domain Name.")
9283

    
9284

    
9285
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9286
  """Generic tags LU.
9287

9288
  This is an abstract class which is the parent of all the other tags LUs.
9289

9290
  """
9291

    
9292
  def ExpandNames(self):
9293
    self.needed_locks = {}
9294
    if self.op.kind == constants.TAG_NODE:
9295
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9296
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9297
    elif self.op.kind == constants.TAG_INSTANCE:
9298
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9299
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9300

    
9301
  def CheckPrereq(self):
9302
    """Check prerequisites.
9303

9304
    """
9305
    if self.op.kind == constants.TAG_CLUSTER:
9306
      self.target = self.cfg.GetClusterInfo()
9307
    elif self.op.kind == constants.TAG_NODE:
9308
      self.target = self.cfg.GetNodeInfo(self.op.name)
9309
    elif self.op.kind == constants.TAG_INSTANCE:
9310
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9311
    else:
9312
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9313
                                 str(self.op.kind), errors.ECODE_INVAL)
9314

    
9315

    
9316
class LUGetTags(TagsLU):
9317
  """Returns the tags of a given object.
9318

9319
  """
9320
  _OP_REQP = ["kind", "name"]
9321
  REQ_BGL = False
9322

    
9323
  def Exec(self, feedback_fn):
9324
    """Returns the tag list.
9325

9326
    """
9327
    return list(self.target.GetTags())
9328

    
9329

    
9330
class LUSearchTags(NoHooksLU):
9331
  """Searches the tags for a given pattern.
9332

9333
  """
9334
  _OP_REQP = ["pattern"]
9335
  REQ_BGL = False
9336

    
9337
  def ExpandNames(self):
9338
    self.needed_locks = {}
9339

    
9340
  def CheckPrereq(self):
9341
    """Check prerequisites.
9342

9343
    This checks the pattern passed for validity by compiling it.
9344

9345
    """
9346
    try:
9347
      self.re = re.compile(self.op.pattern)
9348
    except re.error, err:
9349
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9350
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9351

    
9352
  def Exec(self, feedback_fn):
9353
    """Returns the tag list.
9354

9355
    """
9356
    cfg = self.cfg
9357
    tgts = [("/cluster", cfg.GetClusterInfo())]
9358
    ilist = cfg.GetAllInstancesInfo().values()
9359
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9360
    nlist = cfg.GetAllNodesInfo().values()
9361
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9362
    results = []
9363
    for path, target in tgts:
9364
      for tag in target.GetTags():
9365
        if self.re.search(tag):
9366
          results.append((path, tag))
9367
    return results
9368

    
9369

    
9370
class LUAddTags(TagsLU):
9371
  """Sets a tag on a given object.
9372

9373
  """
9374
  _OP_REQP = ["kind", "name", "tags"]
9375
  REQ_BGL = False
9376

    
9377
  def CheckPrereq(self):
9378
    """Check prerequisites.
9379

9380
    This checks the type and length of the tag name and value.
9381

9382
    """
9383
    TagsLU.CheckPrereq(self)
9384
    for tag in self.op.tags:
9385
      objects.TaggableObject.ValidateTag(tag)
9386

    
9387
  def Exec(self, feedback_fn):
9388
    """Sets the tag.
9389

9390
    """
9391
    try:
9392
      for tag in self.op.tags:
9393
        self.target.AddTag(tag)
9394
    except errors.TagError, err:
9395
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9396
    self.cfg.Update(self.target, feedback_fn)
9397

    
9398

    
9399
class LUDelTags(TagsLU):
9400
  """Delete a list of tags from a given object.
9401

9402
  """
9403
  _OP_REQP = ["kind", "name", "tags"]
9404
  REQ_BGL = False
9405

    
9406
  def CheckPrereq(self):
9407
    """Check prerequisites.
9408

9409
    This checks that we have the given tag.
9410

9411
    """
9412
    TagsLU.CheckPrereq(self)
9413
    for tag in self.op.tags:
9414
      objects.TaggableObject.ValidateTag(tag)
9415
    del_tags = frozenset(self.op.tags)
9416
    cur_tags = self.target.GetTags()
9417
    if not del_tags <= cur_tags:
9418
      diff_tags = del_tags - cur_tags
9419
      diff_names = ["'%s'" % tag for tag in diff_tags]
9420
      diff_names.sort()
9421
      raise errors.OpPrereqError("Tag(s) %s not found" %
9422
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9423

    
9424
  def Exec(self, feedback_fn):
9425
    """Remove the tag from the object.
9426

9427
    """
9428
    for tag in self.op.tags:
9429
      self.target.RemoveTag(tag)
9430
    self.cfg.Update(self.target, feedback_fn)
9431

    
9432

    
9433
class LUTestDelay(NoHooksLU):
9434
  """Sleep for a specified amount of time.
9435

9436
  This LU sleeps on the master and/or nodes for a specified amount of
9437
  time.
9438

9439
  """
9440
  _OP_REQP = ["duration", "on_master", "on_nodes"]
9441
  REQ_BGL = False
9442

    
9443
  def ExpandNames(self):
9444
    """Expand names and set required locks.
9445

9446
    This expands the node list, if any.
9447

9448
    """
9449
    self.needed_locks = {}
9450
    if self.op.on_nodes:
9451
      # _GetWantedNodes can be used here, but is not always appropriate to use
9452
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9453
      # more information.
9454
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9455
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9456

    
9457
  def CheckPrereq(self):
9458
    """Check prerequisites.
9459

9460
    """
9461

    
9462
  def Exec(self, feedback_fn):
9463
    """Do the actual sleep.
9464

9465
    """
9466
    if self.op.on_master:
9467
      if not utils.TestDelay(self.op.duration):
9468
        raise errors.OpExecError("Error during master delay test")
9469
    if self.op.on_nodes:
9470
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9471
      for node, node_result in result.items():
9472
        node_result.Raise("Failure during rpc call to node %s" % node)
9473

    
9474

    
9475
class IAllocator(object):
9476
  """IAllocator framework.
9477

9478
  An IAllocator instance has three sets of attributes:
9479
    - cfg that is needed to query the cluster
9480
    - input data (all members of the _KEYS class attribute are required)
9481
    - four buffer attributes (in|out_data|text), that represent the
9482
      input (to the external script) in text and data structure format,
9483
      and the output from it, again in two formats
9484
    - the result variables from the script (success, info, nodes) for
9485
      easy usage
9486

9487
  """
9488
  # pylint: disable-msg=R0902
9489
  # lots of instance attributes
9490
  _ALLO_KEYS = [
9491
    "name", "mem_size", "disks", "disk_template",
9492
    "os", "tags", "nics", "vcpus", "hypervisor",
9493
    ]
9494
  _RELO_KEYS = [
9495
    "name", "relocate_from",
9496
    ]
9497
  _EVAC_KEYS = [
9498
    "evac_nodes",
9499
    ]
9500

    
9501
  def __init__(self, cfg, rpc, mode, **kwargs):
9502
    self.cfg = cfg
9503
    self.rpc = rpc
9504
    # init buffer variables
9505
    self.in_text = self.out_text = self.in_data = self.out_data = None
9506
    # init all input fields so that pylint is happy
9507
    self.mode = mode
9508
    self.mem_size = self.disks = self.disk_template = None
9509
    self.os = self.tags = self.nics = self.vcpus = None
9510
    self.hypervisor = None
9511
    self.relocate_from = None
9512
    self.name = None
9513
    self.evac_nodes = None
9514
    # computed fields
9515
    self.required_nodes = None
9516
    # init result fields
9517
    self.success = self.info = self.result = None
9518
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9519
      keyset = self._ALLO_KEYS
9520
      fn = self._AddNewInstance
9521
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9522
      keyset = self._RELO_KEYS
9523
      fn = self._AddRelocateInstance
9524
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9525
      keyset = self._EVAC_KEYS
9526
      fn = self._AddEvacuateNodes
9527
    else:
9528
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
9529
                                   " IAllocator" % self.mode)
9530
    for key in kwargs:
9531
      if key not in keyset:
9532
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
9533
                                     " IAllocator" % key)
9534
      setattr(self, key, kwargs[key])
9535

    
9536
    for key in keyset:
9537
      if key not in kwargs:
9538
        raise errors.ProgrammerError("Missing input parameter '%s' to"
9539
                                     " IAllocator" % key)
9540
    self._BuildInputData(fn)
9541

    
9542
  def _ComputeClusterData(self):
9543
    """Compute the generic allocator input data.
9544

9545
    This is the data that is independent of the actual operation.
9546

9547
    """
9548
    cfg = self.cfg
9549
    cluster_info = cfg.GetClusterInfo()
9550
    # cluster data
9551
    data = {
9552
      "version": constants.IALLOCATOR_VERSION,
9553
      "cluster_name": cfg.GetClusterName(),
9554
      "cluster_tags": list(cluster_info.GetTags()),
9555
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
9556
      # we don't have job IDs
9557
      }
9558
    iinfo = cfg.GetAllInstancesInfo().values()
9559
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
9560

    
9561
    # node data
9562
    node_results = {}
9563
    node_list = cfg.GetNodeList()
9564

    
9565
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9566
      hypervisor_name = self.hypervisor
9567
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9568
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
9569
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9570
      hypervisor_name = cluster_info.enabled_hypervisors[0]
9571

    
9572
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
9573
                                        hypervisor_name)
9574
    node_iinfo = \
9575
      self.rpc.call_all_instances_info(node_list,
9576
                                       cluster_info.enabled_hypervisors)
9577
    for nname, nresult in node_data.items():
9578
      # first fill in static (config-based) values
9579
      ninfo = cfg.GetNodeInfo(nname)
9580
      pnr = {
9581
        "tags": list(ninfo.GetTags()),
9582
        "primary_ip": ninfo.primary_ip,
9583
        "secondary_ip": ninfo.secondary_ip,
9584
        "offline": ninfo.offline,
9585
        "drained": ninfo.drained,
9586
        "master_candidate": ninfo.master_candidate,
9587
        }
9588

    
9589
      if not (ninfo.offline or ninfo.drained):
9590
        nresult.Raise("Can't get data for node %s" % nname)
9591
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
9592
                                nname)
9593
        remote_info = nresult.payload
9594

    
9595
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
9596
                     'vg_size', 'vg_free', 'cpu_total']:
9597
          if attr not in remote_info:
9598
            raise errors.OpExecError("Node '%s' didn't return attribute"
9599
                                     " '%s'" % (nname, attr))
9600
          if not isinstance(remote_info[attr], int):
9601
            raise errors.OpExecError("Node '%s' returned invalid value"
9602
                                     " for '%s': %s" %
9603
                                     (nname, attr, remote_info[attr]))
9604
        # compute memory used by primary instances
9605
        i_p_mem = i_p_up_mem = 0
9606
        for iinfo, beinfo in i_list:
9607
          if iinfo.primary_node == nname:
9608
            i_p_mem += beinfo[constants.BE_MEMORY]
9609
            if iinfo.name not in node_iinfo[nname].payload:
9610
              i_used_mem = 0
9611
            else:
9612
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
9613
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
9614
            remote_info['memory_free'] -= max(0, i_mem_diff)
9615

    
9616
            if iinfo.admin_up:
9617
              i_p_up_mem += beinfo[constants.BE_MEMORY]
9618

    
9619
        # compute memory used by instances
9620
        pnr_dyn = {
9621
          "total_memory": remote_info['memory_total'],
9622
          "reserved_memory": remote_info['memory_dom0'],
9623
          "free_memory": remote_info['memory_free'],
9624
          "total_disk": remote_info['vg_size'],
9625
          "free_disk": remote_info['vg_free'],
9626
          "total_cpus": remote_info['cpu_total'],
9627
          "i_pri_memory": i_p_mem,
9628
          "i_pri_up_memory": i_p_up_mem,
9629
          }
9630
        pnr.update(pnr_dyn)
9631

    
9632
      node_results[nname] = pnr
9633
    data["nodes"] = node_results
9634

    
9635
    # instance data
9636
    instance_data = {}
9637
    for iinfo, beinfo in i_list:
9638
      nic_data = []
9639
      for nic in iinfo.nics:
9640
        filled_params = objects.FillDict(
9641
            cluster_info.nicparams[constants.PP_DEFAULT],
9642
            nic.nicparams)
9643
        nic_dict = {"mac": nic.mac,
9644
                    "ip": nic.ip,
9645
                    "mode": filled_params[constants.NIC_MODE],
9646
                    "link": filled_params[constants.NIC_LINK],
9647
                   }
9648
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
9649
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
9650
        nic_data.append(nic_dict)
9651
      pir = {
9652
        "tags": list(iinfo.GetTags()),
9653
        "admin_up": iinfo.admin_up,
9654
        "vcpus": beinfo[constants.BE_VCPUS],
9655
        "memory": beinfo[constants.BE_MEMORY],
9656
        "os": iinfo.os,
9657
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
9658
        "nics": nic_data,
9659
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
9660
        "disk_template": iinfo.disk_template,
9661
        "hypervisor": iinfo.hypervisor,
9662
        }
9663
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
9664
                                                 pir["disks"])
9665
      instance_data[iinfo.name] = pir
9666

    
9667
    data["instances"] = instance_data
9668

    
9669
    self.in_data = data
9670

    
9671
  def _AddNewInstance(self):
9672
    """Add new instance data to allocator structure.
9673

9674
    This in combination with _AllocatorGetClusterData will create the
9675
    correct structure needed as input for the allocator.
9676

9677
    The checks for the completeness of the opcode must have already been
9678
    done.
9679

9680
    """
9681
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
9682

    
9683
    if self.disk_template in constants.DTS_NET_MIRROR:
9684
      self.required_nodes = 2
9685
    else:
9686
      self.required_nodes = 1
9687
    request = {
9688
      "name": self.name,
9689
      "disk_template": self.disk_template,
9690
      "tags": self.tags,
9691
      "os": self.os,
9692
      "vcpus": self.vcpus,
9693
      "memory": self.mem_size,
9694
      "disks": self.disks,
9695
      "disk_space_total": disk_space,
9696
      "nics": self.nics,
9697
      "required_nodes": self.required_nodes,
9698
      }
9699
    return request
9700

    
9701
  def _AddRelocateInstance(self):
9702
    """Add relocate instance data to allocator structure.
9703

9704
    This in combination with _IAllocatorGetClusterData will create the
9705
    correct structure needed as input for the allocator.
9706

9707
    The checks for the completeness of the opcode must have already been
9708
    done.
9709

9710
    """
9711
    instance = self.cfg.GetInstanceInfo(self.name)
9712
    if instance is None:
9713
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
9714
                                   " IAllocator" % self.name)
9715

    
9716
    if instance.disk_template not in constants.DTS_NET_MIRROR:
9717
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
9718
                                 errors.ECODE_INVAL)
9719

    
9720
    if len(instance.secondary_nodes) != 1:
9721
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
9722
                                 errors.ECODE_STATE)
9723

    
9724
    self.required_nodes = 1
9725
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
9726
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
9727

    
9728
    request = {
9729
      "name": self.name,
9730
      "disk_space_total": disk_space,
9731
      "required_nodes": self.required_nodes,
9732
      "relocate_from": self.relocate_from,
9733
      }
9734
    return request
9735

    
9736
  def _AddEvacuateNodes(self):
9737
    """Add evacuate nodes data to allocator structure.
9738

9739
    """
9740
    request = {
9741
      "evac_nodes": self.evac_nodes
9742
      }
9743
    return request
9744

    
9745
  def _BuildInputData(self, fn):
9746
    """Build input data structures.
9747

9748
    """
9749
    self._ComputeClusterData()
9750

    
9751
    request = fn()
9752
    request["type"] = self.mode
9753
    self.in_data["request"] = request
9754

    
9755
    self.in_text = serializer.Dump(self.in_data)
9756

    
9757
  def Run(self, name, validate=True, call_fn=None):
9758
    """Run an instance allocator and return the results.
9759

9760
    """
9761
    if call_fn is None:
9762
      call_fn = self.rpc.call_iallocator_runner
9763

    
9764
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
9765
    result.Raise("Failure while running the iallocator script")
9766

    
9767
    self.out_text = result.payload
9768
    if validate:
9769
      self._ValidateResult()
9770

    
9771
  def _ValidateResult(self):
9772
    """Process the allocator results.
9773

9774
    This will process and if successful save the result in
9775
    self.out_data and the other parameters.
9776

9777
    """
9778
    try:
9779
      rdict = serializer.Load(self.out_text)
9780
    except Exception, err:
9781
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
9782

    
9783
    if not isinstance(rdict, dict):
9784
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
9785

    
9786
    # TODO: remove backwards compatiblity in later versions
9787
    if "nodes" in rdict and "result" not in rdict:
9788
      rdict["result"] = rdict["nodes"]
9789
      del rdict["nodes"]
9790

    
9791
    for key in "success", "info", "result":
9792
      if key not in rdict:
9793
        raise errors.OpExecError("Can't parse iallocator results:"
9794
                                 " missing key '%s'" % key)
9795
      setattr(self, key, rdict[key])
9796

    
9797
    if not isinstance(rdict["result"], list):
9798
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
9799
                               " is not a list")
9800
    self.out_data = rdict
9801

    
9802

    
9803
class LUTestAllocator(NoHooksLU):
9804
  """Run allocator tests.
9805

9806
  This LU runs the allocator tests
9807

9808
  """
9809
  _OP_REQP = ["direction", "mode", "name"]
9810

    
9811
  def CheckPrereq(self):
9812
    """Check prerequisites.
9813

9814
    This checks the opcode parameters depending on the director and mode test.
9815

9816
    """
9817
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9818
      for attr in ["name", "mem_size", "disks", "disk_template",
9819
                   "os", "tags", "nics", "vcpus"]:
9820
        if not hasattr(self.op, attr):
9821
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
9822
                                     attr, errors.ECODE_INVAL)
9823
      iname = self.cfg.ExpandInstanceName(self.op.name)
9824
      if iname is not None:
9825
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
9826
                                   iname, errors.ECODE_EXISTS)
9827
      if not isinstance(self.op.nics, list):
9828
        raise errors.OpPrereqError("Invalid parameter 'nics'",
9829
                                   errors.ECODE_INVAL)
9830
      for row in self.op.nics:
9831
        if (not isinstance(row, dict) or
9832
            "mac" not in row or
9833
            "ip" not in row or
9834
            "bridge" not in row):
9835
          raise errors.OpPrereqError("Invalid contents of the 'nics'"
9836
                                     " parameter", errors.ECODE_INVAL)
9837
      if not isinstance(self.op.disks, list):
9838
        raise errors.OpPrereqError("Invalid parameter 'disks'",
9839
                                   errors.ECODE_INVAL)
9840
      for row in self.op.disks:
9841
        if (not isinstance(row, dict) or
9842
            "size" not in row or
9843
            not isinstance(row["size"], int) or
9844
            "mode" not in row or
9845
            row["mode"] not in ['r', 'w']):
9846
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
9847
                                     " parameter", errors.ECODE_INVAL)
9848
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
9849
        self.op.hypervisor = self.cfg.GetHypervisorType()
9850
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9851
      if not hasattr(self.op, "name"):
9852
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input",
9853
                                   errors.ECODE_INVAL)
9854
      fname = _ExpandInstanceName(self.cfg, self.op.name)
9855
      self.op.name = fname
9856
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
9857
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9858
      if not hasattr(self.op, "evac_nodes"):
9859
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
9860
                                   " opcode input", errors.ECODE_INVAL)
9861
    else:
9862
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
9863
                                 self.op.mode, errors.ECODE_INVAL)
9864

    
9865
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
9866
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
9867
        raise errors.OpPrereqError("Missing allocator name",
9868
                                   errors.ECODE_INVAL)
9869
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
9870
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
9871
                                 self.op.direction, errors.ECODE_INVAL)
9872

    
9873
  def Exec(self, feedback_fn):
9874
    """Run the allocator test.
9875

9876
    """
9877
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9878
      ial = IAllocator(self.cfg, self.rpc,
9879
                       mode=self.op.mode,
9880
                       name=self.op.name,
9881
                       mem_size=self.op.mem_size,
9882
                       disks=self.op.disks,
9883
                       disk_template=self.op.disk_template,
9884
                       os=self.op.os,
9885
                       tags=self.op.tags,
9886
                       nics=self.op.nics,
9887
                       vcpus=self.op.vcpus,
9888
                       hypervisor=self.op.hypervisor,
9889
                       )
9890
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9891
      ial = IAllocator(self.cfg, self.rpc,
9892
                       mode=self.op.mode,
9893
                       name=self.op.name,
9894
                       relocate_from=list(self.relocate_from),
9895
                       )
9896
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9897
      ial = IAllocator(self.cfg, self.rpc,
9898
                       mode=self.op.mode,
9899
                       evac_nodes=self.op.evac_nodes)
9900
    else:
9901
      raise errors.ProgrammerError("Uncatched mode %s in"
9902
                                   " LUTestAllocator.Exec", self.op.mode)
9903

    
9904
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
9905
      result = ial.in_text
9906
    else:
9907
      ial.Run(self.op.allocator, validate=False)
9908
      result = ial.out_text
9909
    return result