Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 0debfb35

History | View | Annotate | Download (305.5 kB)

1
#
2
#
3

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

    
21

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

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

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

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

    
44

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

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

57
  Note that all commands require root permissions.
58

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

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

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

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

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

    
96
    # Tasklets
97
    self.tasklets = None
98

    
99
    for attr_name in self._OP_REQP:
100
      attr_val = getattr(op, attr_name, None)
101
      if attr_val is None:
102
        raise errors.OpPrereqError("Required parameter '%s' missing" %
103
                                   attr_name, errors.ECODE_INVAL)
104

    
105
    self.CheckArguments()
106

    
107
  def __GetSSH(self):
108
    """Returns the SshRunner object
109

110
    """
111
    if not self.__ssh:
112
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
113
    return self.__ssh
114

    
115
  ssh = property(fget=__GetSSH)
116

    
117
  def CheckArguments(self):
118
    """Check syntactic validity for the opcode arguments.
119

120
    This method is for doing a simple syntactic check and ensure
121
    validity of opcode parameters, without any cluster-related
122
    checks. While the same can be accomplished in ExpandNames and/or
123
    CheckPrereq, doing these separate is better because:
124

125
      - ExpandNames is left as as purely a lock-related function
126
      - CheckPrereq is run after we have acquired locks (and possible
127
        waited for them)
128

129
    The function is allowed to change the self.op attribute so that
130
    later methods can no longer worry about missing parameters.
131

132
    """
133
    pass
134

    
135
  def ExpandNames(self):
136
    """Expand names for this LU.
137

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

143
    LUs which implement this method must also populate the self.needed_locks
144
    member, as a dict with lock levels as keys, and a list of needed lock names
145
    as values. Rules:
146

147
      - use an empty dict if you don't need any lock
148
      - if you don't need any lock at a particular level omit that level
149
      - don't put anything for the BGL level
150
      - if you want all locks at a level use locking.ALL_SET as a value
151

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

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

160
    Examples::
161

162
      # Acquire all nodes and one instance
163
      self.needed_locks = {
164
        locking.LEVEL_NODE: locking.ALL_SET,
165
        locking.LEVEL_INSTANCE: ['instance1.example.tld'],
166
      }
167
      # Acquire just two nodes
168
      self.needed_locks = {
169
        locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
170
      }
171
      # Acquire no locks
172
      self.needed_locks = {} # No, you can't leave it to the default value None
173

174
    """
175
    # The implementation of this method is mandatory only if the new LU is
176
    # concurrent, so that old LUs don't need to be changed all at the same
177
    # time.
178
    if self.REQ_BGL:
179
      self.needed_locks = {} # Exclusive LUs don't need locks.
180
    else:
181
      raise NotImplementedError
182

    
183
  def DeclareLocks(self, level):
184
    """Declare LU locking needs for a level
185

186
    While most LUs can just declare their locking needs at ExpandNames time,
187
    sometimes there's the need to calculate some locks after having acquired
188
    the ones before. This function is called just before acquiring locks at a
189
    particular level, but after acquiring the ones at lower levels, and permits
190
    such calculations. It can be used to modify self.needed_locks, and by
191
    default it does nothing.
192

193
    This function is only called if you have something already set in
194
    self.needed_locks for the level.
195

196
    @param level: Locking level which is going to be locked
197
    @type level: member of ganeti.locking.LEVELS
198

199
    """
200

    
201
  def CheckPrereq(self):
202
    """Check prerequisites for this LU.
203

204
    This method should check that the prerequisites for the execution
205
    of this LU are fulfilled. It can do internode communication, but
206
    it should be idempotent - no cluster or system changes are
207
    allowed.
208

209
    The method should raise errors.OpPrereqError in case something is
210
    not fulfilled. Its return value is ignored.
211

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

215
    """
216
    if self.tasklets is not None:
217
      for (idx, tl) in enumerate(self.tasklets):
218
        logging.debug("Checking prerequisites for tasklet %s/%s",
219
                      idx + 1, len(self.tasklets))
220
        tl.CheckPrereq()
221
    else:
222
      raise NotImplementedError
223

    
224
  def Exec(self, feedback_fn):
225
    """Execute the LU.
226

227
    This method should implement the actual work. It should raise
228
    errors.OpExecError for failures that are somewhat dealt with in
229
    code, or expected.
230

231
    """
232
    if self.tasklets is not None:
233
      for (idx, tl) in enumerate(self.tasklets):
234
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
235
        tl.Exec(feedback_fn)
236
    else:
237
      raise NotImplementedError
238

    
239
  def BuildHooksEnv(self):
240
    """Build hooks environment for this LU.
241

242
    This method should return a three-node tuple consisting of: a dict
243
    containing the environment that will be used for running the
244
    specific hook for this LU, a list of node names on which the hook
245
    should run before the execution, and a list of node names on which
246
    the hook should run after the execution.
247

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

253
    No nodes should be returned as an empty list (and not None).
254

255
    Note that if the HPATH for a LU class is None, this function will
256
    not be called.
257

258
    """
259
    raise NotImplementedError
260

    
261
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
262
    """Notify the LU about the results of its hooks.
263

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

270
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
271
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
272
    @param hook_results: the results of the multi-node hooks rpc call
273
    @param feedback_fn: function used send feedback back to the caller
274
    @param lu_result: the previous Exec result this LU had, or None
275
        in the PRE phase
276
    @return: the new Exec result, based on the previous result
277
        and hook results
278

279
    """
280
    return lu_result
281

    
282
  def _ExpandAndLockInstance(self):
283
    """Helper function to expand and lock an instance.
284

285
    Many LUs that work on an instance take its name in self.op.instance_name
286
    and need to expand it and then declare the expanded name for locking. This
287
    function does it, and then updates self.op.instance_name to the expanded
288
    name. It also initializes needed_locks as a dict, if this hasn't been done
289
    before.
290

291
    """
292
    if self.needed_locks is None:
293
      self.needed_locks = {}
294
    else:
295
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
296
        "_ExpandAndLockInstance called with instance-level locks set"
297
    expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name)
298
    if expanded_name is None:
299
      raise errors.OpPrereqError("Instance '%s' not known" %
300
                                 self.op.instance_name, errors.ECODE_NOENT)
301
    self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
302
    self.op.instance_name = expanded_name
303

    
304
  def _LockInstancesNodes(self, primary_only=False):
305
    """Helper function to declare instances' nodes for locking.
306

307
    This function should be called after locking one or more instances to lock
308
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
309
    with all primary or secondary nodes for instances already locked and
310
    present in self.needed_locks[locking.LEVEL_INSTANCE].
311

312
    It should be called from DeclareLocks, and for safety only works if
313
    self.recalculate_locks[locking.LEVEL_NODE] is set.
314

315
    In the future it may grow parameters to just lock some instance's nodes, or
316
    to just lock primaries or secondary nodes, if needed.
317

318
    If should be called in DeclareLocks in a way similar to::
319

320
      if level == locking.LEVEL_NODE:
321
        self._LockInstancesNodes()
322

323
    @type primary_only: boolean
324
    @param primary_only: only lock primary nodes of locked instances
325

326
    """
327
    assert locking.LEVEL_NODE in self.recalculate_locks, \
328
      "_LockInstancesNodes helper function called with no nodes to recalculate"
329

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

    
332
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
333
    # future we might want to have different behaviors depending on the value
334
    # of self.recalculate_locks[locking.LEVEL_NODE]
335
    wanted_nodes = []
336
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
337
      instance = self.context.cfg.GetInstanceInfo(instance_name)
338
      wanted_nodes.append(instance.primary_node)
339
      if not primary_only:
340
        wanted_nodes.extend(instance.secondary_nodes)
341

    
342
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
343
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
344
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
345
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
346

    
347
    del self.recalculate_locks[locking.LEVEL_NODE]
348

    
349

    
350
class NoHooksLU(LogicalUnit):
351
  """Simple LU which runs no hooks.
352

353
  This LU is intended as a parent for other LogicalUnits which will
354
  run no hooks, in order to reduce duplicate code.
355

356
  """
357
  HPATH = None
358
  HTYPE = None
359

    
360

    
361
class Tasklet:
362
  """Tasklet base class.
363

364
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
365
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
366
  tasklets know nothing about locks.
367

368
  Subclasses must follow these rules:
369
    - Implement CheckPrereq
370
    - Implement Exec
371

372
  """
373
  def __init__(self, lu):
374
    self.lu = lu
375

    
376
    # Shortcuts
377
    self.cfg = lu.cfg
378
    self.rpc = lu.rpc
379

    
380
  def CheckPrereq(self):
381
    """Check prerequisites for this tasklets.
382

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

387
    The method should raise errors.OpPrereqError in case something is not
388
    fulfilled. Its return value is ignored.
389

390
    This method should also update all parameters to their canonical form if it
391
    hasn't been done before.
392

393
    """
394
    raise NotImplementedError
395

    
396
  def Exec(self, feedback_fn):
397
    """Execute the tasklet.
398

399
    This method should implement the actual work. It should raise
400
    errors.OpExecError for failures that are somewhat dealt with in code, or
401
    expected.
402

403
    """
404
    raise NotImplementedError
405

    
406

    
407
def _GetWantedNodes(lu, nodes):
408
  """Returns list of checked and expanded node names.
409

410
  @type lu: L{LogicalUnit}
411
  @param lu: the logical unit on whose behalf we execute
412
  @type nodes: list
413
  @param nodes: list of node names or None for all nodes
414
  @rtype: list
415
  @return: the list of nodes, sorted
416
  @raise errors.OpProgrammerError: if the nodes parameter is wrong type
417

418
  """
419
  if not isinstance(nodes, list):
420
    raise errors.OpPrereqError("Invalid argument type 'nodes'",
421
                               errors.ECODE_INVAL)
422

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

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

    
435
  return utils.NiceSort(wanted)
436

    
437

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

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

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

    
455
  if instances:
456
    wanted = []
457

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

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

    
469

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

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

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

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

    
488

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

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

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

    
502

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

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

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

    
517

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

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

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

    
530

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

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

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

    
543

    
544
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
545
                          memory, vcpus, nics, disk_template, disks,
546
                          bep, hvp, hypervisor_name):
547
  """Builds instance related env variables for hooks
548

549
  This builds the hook environment from individual variables.
550

551
  @type name: string
552
  @param name: the name of the instance
553
  @type primary_node: string
554
  @param primary_node: the name of the instance's primary node
555
  @type secondary_nodes: list
556
  @param secondary_nodes: list of secondary nodes as strings
557
  @type os_type: string
558
  @param os_type: the name of the instance's OS
559
  @type status: boolean
560
  @param status: the should_run status of the instance
561
  @type memory: string
562
  @param memory: the memory size of the instance
563
  @type vcpus: string
564
  @param vcpus: the count of VCPUs the instance has
565
  @type nics: list
566
  @param nics: list of tuples (ip, mac, mode, link) representing
567
      the NICs the instance has
568
  @type disk_template: string
569
  @param disk_template: the disk template of the instance
570
  @type disks: list
571
  @param disks: the list of (size, mode) pairs
572
  @type bep: dict
573
  @param bep: the backend parameters for the instance
574
  @type hvp: dict
575
  @param hvp: the hypervisor parameters for the instance
576
  @type hypervisor_name: string
577
  @param hypervisor_name: the hypervisor for the instance
578
  @rtype: dict
579
  @return: the hook environment for this instance
580

581
  """
582
  if status:
583
    str_status = "up"
584
  else:
585
    str_status = "down"
586
  env = {
587
    "OP_TARGET": name,
588
    "INSTANCE_NAME": name,
589
    "INSTANCE_PRIMARY": primary_node,
590
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
591
    "INSTANCE_OS_TYPE": os_type,
592
    "INSTANCE_STATUS": str_status,
593
    "INSTANCE_MEMORY": memory,
594
    "INSTANCE_VCPUS": vcpus,
595
    "INSTANCE_DISK_TEMPLATE": disk_template,
596
    "INSTANCE_HYPERVISOR": hypervisor_name,
597
  }
598

    
599
  if nics:
600
    nic_count = len(nics)
601
    for idx, (ip, mac, mode, link) in enumerate(nics):
602
      if ip is None:
603
        ip = ""
604
      env["INSTANCE_NIC%d_IP" % idx] = ip
605
      env["INSTANCE_NIC%d_MAC" % idx] = mac
606
      env["INSTANCE_NIC%d_MODE" % idx] = mode
607
      env["INSTANCE_NIC%d_LINK" % idx] = link
608
      if mode == constants.NIC_MODE_BRIDGED:
609
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
610
  else:
611
    nic_count = 0
612

    
613
  env["INSTANCE_NIC_COUNT"] = nic_count
614

    
615
  if disks:
616
    disk_count = len(disks)
617
    for idx, (size, mode) in enumerate(disks):
618
      env["INSTANCE_DISK%d_SIZE" % idx] = size
619
      env["INSTANCE_DISK%d_MODE" % idx] = mode
620
  else:
621
    disk_count = 0
622

    
623
  env["INSTANCE_DISK_COUNT"] = disk_count
624

    
625
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
626
    for key, value in source.items():
627
      env["INSTANCE_%s_%s" % (kind, key)] = value
628

    
629
  return env
630

    
631

    
632
def _NICListToTuple(lu, nics):
633
  """Build a list of nic information tuples.
634

635
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
636
  value in LUQueryInstanceData.
637

638
  @type lu:  L{LogicalUnit}
639
  @param lu: the logical unit on whose behalf we execute
640
  @type nics: list of L{objects.NIC}
641
  @param nics: list of nics to convert to hooks tuples
642

643
  """
644
  hooks_nics = []
645
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
646
  for nic in nics:
647
    ip = nic.ip
648
    mac = nic.mac
649
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
650
    mode = filled_params[constants.NIC_MODE]
651
    link = filled_params[constants.NIC_LINK]
652
    hooks_nics.append((ip, mac, mode, link))
653
  return hooks_nics
654

    
655

    
656
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
657
  """Builds instance related env variables for hooks from an object.
658

659
  @type lu: L{LogicalUnit}
660
  @param lu: the logical unit on whose behalf we execute
661
  @type instance: L{objects.Instance}
662
  @param instance: the instance for which we should build the
663
      environment
664
  @type override: dict
665
  @param override: dictionary with key/values that will override
666
      our values
667
  @rtype: dict
668
  @return: the hook environment dictionary
669

670
  """
671
  cluster = lu.cfg.GetClusterInfo()
672
  bep = cluster.FillBE(instance)
673
  hvp = cluster.FillHV(instance)
674
  args = {
675
    'name': instance.name,
676
    'primary_node': instance.primary_node,
677
    'secondary_nodes': instance.secondary_nodes,
678
    'os_type': instance.os,
679
    'status': instance.admin_up,
680
    'memory': bep[constants.BE_MEMORY],
681
    'vcpus': bep[constants.BE_VCPUS],
682
    'nics': _NICListToTuple(lu, instance.nics),
683
    'disk_template': instance.disk_template,
684
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
685
    'bep': bep,
686
    'hvp': hvp,
687
    'hypervisor_name': instance.hypervisor,
688
  }
689
  if override:
690
    args.update(override)
691
  return _BuildInstanceHookEnv(**args)
692

    
693

    
694
def _AdjustCandidatePool(lu, exceptions):
695
  """Adjust the candidate pool after node operations.
696

697
  """
698
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
699
  if mod_list:
700
    lu.LogInfo("Promoted nodes to master candidate role: %s",
701
               ", ".join(node.name for node in mod_list))
702
    for name in mod_list:
703
      lu.context.ReaddNode(name)
704
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
705
  if mc_now > mc_max:
706
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
707
               (mc_now, mc_max))
708

    
709

    
710
def _DecideSelfPromotion(lu, exceptions=None):
711
  """Decide whether I should promote myself as a master candidate.
712

713
  """
714
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
715
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
716
  # the new node will increase mc_max with one, so:
717
  mc_should = min(mc_should + 1, cp_size)
718
  return mc_now < mc_should
719

    
720

    
721
def _CheckNicsBridgesExist(lu, target_nics, target_node,
722
                               profile=constants.PP_DEFAULT):
723
  """Check that the brigdes needed by a list of nics exist.
724

725
  """
726
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
727
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
728
                for nic in target_nics]
729
  brlist = [params[constants.NIC_LINK] for params in paramslist
730
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
731
  if brlist:
732
    result = lu.rpc.call_bridges_exist(target_node, brlist)
733
    result.Raise("Error checking bridges on destination node '%s'" %
734
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
735

    
736

    
737
def _CheckInstanceBridgesExist(lu, instance, node=None):
738
  """Check that the brigdes needed by an instance exist.
739

740
  """
741
  if node is None:
742
    node = instance.primary_node
743
  _CheckNicsBridgesExist(lu, instance.nics, node)
744

    
745

    
746
def _CheckOSVariant(os_obj, name):
747
  """Check whether an OS name conforms to the os variants specification.
748

749
  @type os_obj: L{objects.OS}
750
  @param os_obj: OS object to check
751
  @type name: string
752
  @param name: OS name passed by the user, to check for validity
753

754
  """
755
  if not os_obj.supported_variants:
756
    return
757
  try:
758
    variant = name.split("+", 1)[1]
759
  except IndexError:
760
    raise errors.OpPrereqError("OS name must include a variant",
761
                               errors.ECODE_INVAL)
762

    
763
  if variant not in os_obj.supported_variants:
764
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
765

    
766

    
767
def _GetNodeInstancesInner(cfg, fn):
768
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
769

    
770

    
771
def _GetNodeInstances(cfg, node_name):
772
  """Returns a list of all primary and secondary instances on a node.
773

774
  """
775

    
776
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
777

    
778

    
779
def _GetNodePrimaryInstances(cfg, node_name):
780
  """Returns primary instances on a node.
781

782
  """
783
  return _GetNodeInstancesInner(cfg,
784
                                lambda inst: node_name == inst.primary_node)
785

    
786

    
787
def _GetNodeSecondaryInstances(cfg, node_name):
788
  """Returns secondary instances on a node.
789

790
  """
791
  return _GetNodeInstancesInner(cfg,
792
                                lambda inst: node_name in inst.secondary_nodes)
793

    
794

    
795
def _GetStorageTypeArgs(cfg, storage_type):
796
  """Returns the arguments for a storage type.
797

798
  """
799
  # Special case for file storage
800
  if storage_type == constants.ST_FILE:
801
    # storage.FileStorage wants a list of storage directories
802
    return [[cfg.GetFileStorageDir()]]
803

    
804
  return []
805

    
806

    
807
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
808
  faulty = []
809

    
810
  for dev in instance.disks:
811
    cfg.SetDiskID(dev, node_name)
812

    
813
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
814
  result.Raise("Failed to get disk status from node %s" % node_name,
815
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
816

    
817
  for idx, bdev_status in enumerate(result.payload):
818
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
819
      faulty.append(idx)
820

    
821
  return faulty
822

    
823

    
824
class LUPostInitCluster(LogicalUnit):
825
  """Logical unit for running hooks after cluster initialization.
826

827
  """
828
  HPATH = "cluster-init"
829
  HTYPE = constants.HTYPE_CLUSTER
830
  _OP_REQP = []
831

    
832
  def BuildHooksEnv(self):
833
    """Build hooks env.
834

835
    """
836
    env = {"OP_TARGET": self.cfg.GetClusterName()}
837
    mn = self.cfg.GetMasterNode()
838
    return env, [], [mn]
839

    
840
  def CheckPrereq(self):
841
    """No prerequisites to check.
842

843
    """
844
    return True
845

    
846
  def Exec(self, feedback_fn):
847
    """Nothing to do.
848

849
    """
850
    return True
851

    
852

    
853
class LUDestroyCluster(LogicalUnit):
854
  """Logical unit for destroying the cluster.
855

856
  """
857
  HPATH = "cluster-destroy"
858
  HTYPE = constants.HTYPE_CLUSTER
859
  _OP_REQP = []
860

    
861
  def BuildHooksEnv(self):
862
    """Build hooks env.
863

864
    """
865
    env = {"OP_TARGET": self.cfg.GetClusterName()}
866
    return env, [], []
867

    
868
  def CheckPrereq(self):
869
    """Check prerequisites.
870

871
    This checks whether the cluster is empty.
872

873
    Any errors are signaled by raising errors.OpPrereqError.
874

875
    """
876
    master = self.cfg.GetMasterNode()
877

    
878
    nodelist = self.cfg.GetNodeList()
879
    if len(nodelist) != 1 or nodelist[0] != master:
880
      raise errors.OpPrereqError("There are still %d node(s) in"
881
                                 " this cluster." % (len(nodelist) - 1),
882
                                 errors.ECODE_INVAL)
883
    instancelist = self.cfg.GetInstanceList()
884
    if instancelist:
885
      raise errors.OpPrereqError("There are still %d instance(s) in"
886
                                 " this cluster." % len(instancelist),
887
                                 errors.ECODE_INVAL)
888

    
889
  def Exec(self, feedback_fn):
890
    """Destroys the cluster.
891

892
    """
893
    master = self.cfg.GetMasterNode()
894
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
895

    
896
    # Run post hooks on master node before it's removed
897
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
898
    try:
899
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
900
    except:
901
      self.LogWarning("Errors occurred running hooks on %s" % master)
902

    
903
    result = self.rpc.call_node_stop_master(master, False)
904
    result.Raise("Could not disable the master role")
905

    
906
    if modify_ssh_setup:
907
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
908
      utils.CreateBackup(priv_key)
909
      utils.CreateBackup(pub_key)
910

    
911
    return master
912

    
913

    
914
class LUVerifyCluster(LogicalUnit):
915
  """Verifies the cluster status.
916

917
  """
918
  HPATH = "cluster-verify"
919
  HTYPE = constants.HTYPE_CLUSTER
920
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
921
  REQ_BGL = False
922

    
923
  TCLUSTER = "cluster"
924
  TNODE = "node"
925
  TINSTANCE = "instance"
926

    
927
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
928
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
929
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
930
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
931
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
932
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
933
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
934
  ENODEDRBD = (TNODE, "ENODEDRBD")
935
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
936
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
937
  ENODEHV = (TNODE, "ENODEHV")
938
  ENODELVM = (TNODE, "ENODELVM")
939
  ENODEN1 = (TNODE, "ENODEN1")
940
  ENODENET = (TNODE, "ENODENET")
941
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
942
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
943
  ENODERPC = (TNODE, "ENODERPC")
944
  ENODESSH = (TNODE, "ENODESSH")
945
  ENODEVERSION = (TNODE, "ENODEVERSION")
946
  ENODESETUP = (TNODE, "ENODESETUP")
947

    
948
  ETYPE_FIELD = "code"
949
  ETYPE_ERROR = "ERROR"
950
  ETYPE_WARNING = "WARNING"
951

    
952
  def ExpandNames(self):
953
    self.needed_locks = {
954
      locking.LEVEL_NODE: locking.ALL_SET,
955
      locking.LEVEL_INSTANCE: locking.ALL_SET,
956
    }
957
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
958

    
959
  def _Error(self, ecode, item, msg, *args, **kwargs):
960
    """Format an error message.
961

962
    Based on the opcode's error_codes parameter, either format a
963
    parseable error code, or a simpler error string.
964

965
    This must be called only from Exec and functions called from Exec.
966

967
    """
968
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
969
    itype, etxt = ecode
970
    # first complete the msg
971
    if args:
972
      msg = msg % args
973
    # then format the whole message
974
    if self.op.error_codes:
975
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
976
    else:
977
      if item:
978
        item = " " + item
979
      else:
980
        item = ""
981
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
982
    # and finally report it via the feedback_fn
983
    self._feedback_fn("  - %s" % msg)
984

    
985
  def _ErrorIf(self, cond, *args, **kwargs):
986
    """Log an error message if the passed condition is True.
987

988
    """
989
    cond = bool(cond) or self.op.debug_simulate_errors
990
    if cond:
991
      self._Error(*args, **kwargs)
992
    # do not mark the operation as failed for WARN cases only
993
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
994
      self.bad = self.bad or cond
995

    
996
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
997
                  node_result, master_files, drbd_map, vg_name):
998
    """Run multiple tests against a node.
999

1000
    Test list:
1001

1002
      - compares ganeti version
1003
      - checks vg existence and size > 20G
1004
      - checks config file checksum
1005
      - checks ssh to other nodes
1006

1007
    @type nodeinfo: L{objects.Node}
1008
    @param nodeinfo: the node to check
1009
    @param file_list: required list of files
1010
    @param local_cksum: dictionary of local files and their checksums
1011
    @param node_result: the results from the node
1012
    @param master_files: list of files that only masters should have
1013
    @param drbd_map: the useddrbd minors for this node, in
1014
        form of minor: (instance, must_exist) which correspond to instances
1015
        and their running status
1016
    @param vg_name: Ganeti Volume Group (result of self.cfg.GetVGName())
1017

1018
    """
1019
    node = nodeinfo.name
1020
    _ErrorIf = self._ErrorIf
1021

    
1022
    # main result, node_result should be a non-empty dict
1023
    test = not node_result or not isinstance(node_result, dict)
1024
    _ErrorIf(test, self.ENODERPC, node,
1025
                  "unable to verify node: no data returned")
1026
    if test:
1027
      return
1028

    
1029
    # compares ganeti version
1030
    local_version = constants.PROTOCOL_VERSION
1031
    remote_version = node_result.get('version', None)
1032
    test = not (remote_version and
1033
                isinstance(remote_version, (list, tuple)) and
1034
                len(remote_version) == 2)
1035
    _ErrorIf(test, self.ENODERPC, node,
1036
             "connection to node returned invalid data")
1037
    if test:
1038
      return
1039

    
1040
    test = local_version != remote_version[0]
1041
    _ErrorIf(test, self.ENODEVERSION, node,
1042
             "incompatible protocol versions: master %s,"
1043
             " node %s", local_version, remote_version[0])
1044
    if test:
1045
      return
1046

    
1047
    # node seems compatible, we can actually try to look into its results
1048

    
1049
    # full package version
1050
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1051
                  self.ENODEVERSION, node,
1052
                  "software version mismatch: master %s, node %s",
1053
                  constants.RELEASE_VERSION, remote_version[1],
1054
                  code=self.ETYPE_WARNING)
1055

    
1056
    # checks vg existence and size > 20G
1057
    if vg_name is not None:
1058
      vglist = node_result.get(constants.NV_VGLIST, None)
1059
      test = not vglist
1060
      _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1061
      if not test:
1062
        vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1063
                                              constants.MIN_VG_SIZE)
1064
        _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1065

    
1066
    # checks config file checksum
1067

    
1068
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
1069
    test = not isinstance(remote_cksum, dict)
1070
    _ErrorIf(test, self.ENODEFILECHECK, node,
1071
             "node hasn't returned file checksum data")
1072
    if not test:
1073
      for file_name in file_list:
1074
        node_is_mc = nodeinfo.master_candidate
1075
        must_have = (file_name not in master_files) or node_is_mc
1076
        # missing
1077
        test1 = file_name not in remote_cksum
1078
        # invalid checksum
1079
        test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1080
        # existing and good
1081
        test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1082
        _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1083
                 "file '%s' missing", file_name)
1084
        _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1085
                 "file '%s' has wrong checksum", file_name)
1086
        # not candidate and this is not a must-have file
1087
        _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1088
                 "file '%s' should not exist on non master"
1089
                 " candidates (and the file is outdated)", file_name)
1090
        # all good, except non-master/non-must have combination
1091
        _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1092
                 "file '%s' should not exist"
1093
                 " on non master candidates", file_name)
1094

    
1095
    # checks ssh to any
1096

    
1097
    test = constants.NV_NODELIST not in node_result
1098
    _ErrorIf(test, self.ENODESSH, node,
1099
             "node hasn't returned node ssh connectivity data")
1100
    if not test:
1101
      if node_result[constants.NV_NODELIST]:
1102
        for a_node, a_msg in node_result[constants.NV_NODELIST].items():
1103
          _ErrorIf(True, self.ENODESSH, node,
1104
                   "ssh communication with node '%s': %s", a_node, a_msg)
1105

    
1106
    test = constants.NV_NODENETTEST not in node_result
1107
    _ErrorIf(test, self.ENODENET, node,
1108
             "node hasn't returned node tcp connectivity data")
1109
    if not test:
1110
      if node_result[constants.NV_NODENETTEST]:
1111
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
1112
        for anode in nlist:
1113
          _ErrorIf(True, self.ENODENET, node,
1114
                   "tcp communication with node '%s': %s",
1115
                   anode, node_result[constants.NV_NODENETTEST][anode])
1116

    
1117
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
1118
    if isinstance(hyp_result, dict):
1119
      for hv_name, hv_result in hyp_result.iteritems():
1120
        test = hv_result is not None
1121
        _ErrorIf(test, self.ENODEHV, node,
1122
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1123

    
1124
    # check used drbd list
1125
    if vg_name is not None:
1126
      used_minors = node_result.get(constants.NV_DRBDLIST, [])
1127
      test = not isinstance(used_minors, (tuple, list))
1128
      _ErrorIf(test, self.ENODEDRBD, node,
1129
               "cannot parse drbd status file: %s", str(used_minors))
1130
      if not test:
1131
        for minor, (iname, must_exist) in drbd_map.items():
1132
          test = minor not in used_minors and must_exist
1133
          _ErrorIf(test, self.ENODEDRBD, node,
1134
                   "drbd minor %d of instance %s is not active",
1135
                   minor, iname)
1136
        for minor in used_minors:
1137
          test = minor not in drbd_map
1138
          _ErrorIf(test, self.ENODEDRBD, node,
1139
                   "unallocated drbd minor %d is in use", minor)
1140
    test = node_result.get(constants.NV_NODESETUP,
1141
                           ["Missing NODESETUP results"])
1142
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1143
             "; ".join(test))
1144

    
1145
    # check pv names
1146
    if vg_name is not None:
1147
      pvlist = node_result.get(constants.NV_PVLIST, None)
1148
      test = pvlist is None
1149
      _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1150
      if not test:
1151
        # check that ':' is not present in PV names, since it's a
1152
        # special character for lvcreate (denotes the range of PEs to
1153
        # use on the PV)
1154
        for size, pvname, owner_vg in pvlist:
1155
          test = ":" in pvname
1156
          _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1157
                   " '%s' of VG '%s'", pvname, owner_vg)
1158

    
1159
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
1160
                      node_instance, n_offline):
1161
    """Verify an instance.
1162

1163
    This function checks to see if the required block devices are
1164
    available on the instance's node.
1165

1166
    """
1167
    _ErrorIf = self._ErrorIf
1168
    node_current = instanceconfig.primary_node
1169

    
1170
    node_vol_should = {}
1171
    instanceconfig.MapLVsByNode(node_vol_should)
1172

    
1173
    for node in node_vol_should:
1174
      if node in n_offline:
1175
        # ignore missing volumes on offline nodes
1176
        continue
1177
      for volume in node_vol_should[node]:
1178
        test = node not in node_vol_is or volume not in node_vol_is[node]
1179
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1180
                 "volume %s missing on node %s", volume, node)
1181

    
1182
    if instanceconfig.admin_up:
1183
      test = ((node_current not in node_instance or
1184
               not instance in node_instance[node_current]) and
1185
              node_current not in n_offline)
1186
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1187
               "instance not running on its primary node %s",
1188
               node_current)
1189

    
1190
    for node in node_instance:
1191
      if (not node == node_current):
1192
        test = instance in node_instance[node]
1193
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1194
                 "instance should not run on node %s", node)
1195

    
1196
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is):
1197
    """Verify if there are any unknown volumes in the cluster.
1198

1199
    The .os, .swap and backup volumes are ignored. All other volumes are
1200
    reported as unknown.
1201

1202
    """
1203
    for node in node_vol_is:
1204
      for volume in node_vol_is[node]:
1205
        test = (node not in node_vol_should or
1206
                volume not in node_vol_should[node])
1207
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1208
                      "volume %s is unknown", volume)
1209

    
1210
  def _VerifyOrphanInstances(self, instancelist, node_instance):
1211
    """Verify the list of running instances.
1212

1213
    This checks what instances are running but unknown to the cluster.
1214

1215
    """
1216
    for node in node_instance:
1217
      for o_inst in node_instance[node]:
1218
        test = o_inst not in instancelist
1219
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1220
                      "instance %s on node %s should not exist", o_inst, node)
1221

    
1222
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg):
1223
    """Verify N+1 Memory Resilience.
1224

1225
    Check that if one single node dies we can still start all the instances it
1226
    was primary for.
1227

1228
    """
1229
    for node, nodeinfo in node_info.iteritems():
1230
      # This code checks that every node which is now listed as secondary has
1231
      # enough memory to host all instances it is supposed to should a single
1232
      # other node in the cluster fail.
1233
      # FIXME: not ready for failover to an arbitrary node
1234
      # FIXME: does not support file-backed instances
1235
      # WARNING: we currently take into account down instances as well as up
1236
      # ones, considering that even if they're down someone might want to start
1237
      # them even in the event of a node failure.
1238
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
1239
        needed_mem = 0
1240
        for instance in instances:
1241
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1242
          if bep[constants.BE_AUTO_BALANCE]:
1243
            needed_mem += bep[constants.BE_MEMORY]
1244
        test = nodeinfo['mfree'] < needed_mem
1245
        self._ErrorIf(test, self.ENODEN1, node,
1246
                      "not enough memory on to accommodate"
1247
                      " failovers should peer node %s fail", prinode)
1248

    
1249
  def CheckPrereq(self):
1250
    """Check prerequisites.
1251

1252
    Transform the list of checks we're going to skip into a set and check that
1253
    all its members are valid.
1254

1255
    """
1256
    self.skip_set = frozenset(self.op.skip_checks)
1257
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1258
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1259
                                 errors.ECODE_INVAL)
1260

    
1261
  def BuildHooksEnv(self):
1262
    """Build hooks env.
1263

1264
    Cluster-Verify hooks just ran in the post phase and their failure makes
1265
    the output be logged in the verify output and the verification to fail.
1266

1267
    """
1268
    all_nodes = self.cfg.GetNodeList()
1269
    env = {
1270
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1271
      }
1272
    for node in self.cfg.GetAllNodesInfo().values():
1273
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1274

    
1275
    return env, [], all_nodes
1276

    
1277
  def Exec(self, feedback_fn):
1278
    """Verify integrity of cluster, performing various test on nodes.
1279

1280
    """
1281
    self.bad = False
1282
    _ErrorIf = self._ErrorIf
1283
    verbose = self.op.verbose
1284
    self._feedback_fn = feedback_fn
1285
    feedback_fn("* Verifying global settings")
1286
    for msg in self.cfg.VerifyConfig():
1287
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1288

    
1289
    vg_name = self.cfg.GetVGName()
1290
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1291
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1292
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1293
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1294
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1295
                        for iname in instancelist)
1296
    i_non_redundant = [] # Non redundant instances
1297
    i_non_a_balanced = [] # Non auto-balanced instances
1298
    n_offline = [] # List of offline nodes
1299
    n_drained = [] # List of nodes being drained
1300
    node_volume = {}
1301
    node_instance = {}
1302
    node_info = {}
1303
    instance_cfg = {}
1304

    
1305
    # FIXME: verify OS list
1306
    # do local checksums
1307
    master_files = [constants.CLUSTER_CONF_FILE]
1308

    
1309
    file_names = ssconf.SimpleStore().GetFileList()
1310
    file_names.append(constants.SSL_CERT_FILE)
1311
    file_names.append(constants.RAPI_CERT_FILE)
1312
    file_names.extend(master_files)
1313

    
1314
    local_checksums = utils.FingerprintFiles(file_names)
1315

    
1316
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1317
    node_verify_param = {
1318
      constants.NV_FILELIST: file_names,
1319
      constants.NV_NODELIST: [node.name for node in nodeinfo
1320
                              if not node.offline],
1321
      constants.NV_HYPERVISOR: hypervisors,
1322
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1323
                                  node.secondary_ip) for node in nodeinfo
1324
                                 if not node.offline],
1325
      constants.NV_INSTANCELIST: hypervisors,
1326
      constants.NV_VERSION: None,
1327
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1328
      constants.NV_NODESETUP: None,
1329
      }
1330
    if vg_name is not None:
1331
      node_verify_param[constants.NV_VGLIST] = None
1332
      node_verify_param[constants.NV_LVLIST] = vg_name
1333
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1334
      node_verify_param[constants.NV_DRBDLIST] = None
1335
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1336
                                           self.cfg.GetClusterName())
1337

    
1338
    cluster = self.cfg.GetClusterInfo()
1339
    master_node = self.cfg.GetMasterNode()
1340
    all_drbd_map = self.cfg.ComputeDRBDMap()
1341

    
1342
    feedback_fn("* Verifying node status")
1343
    for node_i in nodeinfo:
1344
      node = node_i.name
1345

    
1346
      if node_i.offline:
1347
        if verbose:
1348
          feedback_fn("* Skipping offline node %s" % (node,))
1349
        n_offline.append(node)
1350
        continue
1351

    
1352
      if node == master_node:
1353
        ntype = "master"
1354
      elif node_i.master_candidate:
1355
        ntype = "master candidate"
1356
      elif node_i.drained:
1357
        ntype = "drained"
1358
        n_drained.append(node)
1359
      else:
1360
        ntype = "regular"
1361
      if verbose:
1362
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1363

    
1364
      msg = all_nvinfo[node].fail_msg
1365
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1366
      if msg:
1367
        continue
1368

    
1369
      nresult = all_nvinfo[node].payload
1370
      node_drbd = {}
1371
      for minor, instance in all_drbd_map[node].items():
1372
        test = instance not in instanceinfo
1373
        _ErrorIf(test, self.ECLUSTERCFG, None,
1374
                 "ghost instance '%s' in temporary DRBD map", instance)
1375
          # ghost instance should not be running, but otherwise we
1376
          # don't give double warnings (both ghost instance and
1377
          # unallocated minor in use)
1378
        if test:
1379
          node_drbd[minor] = (instance, False)
1380
        else:
1381
          instance = instanceinfo[instance]
1382
          node_drbd[minor] = (instance.name, instance.admin_up)
1383
      self._VerifyNode(node_i, file_names, local_checksums,
1384
                       nresult, master_files, node_drbd, vg_name)
1385

    
1386
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1387
      if vg_name is None:
1388
        node_volume[node] = {}
1389
      elif isinstance(lvdata, basestring):
1390
        _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1391
                 utils.SafeEncode(lvdata))
1392
        node_volume[node] = {}
1393
      elif not isinstance(lvdata, dict):
1394
        _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1395
        continue
1396
      else:
1397
        node_volume[node] = lvdata
1398

    
1399
      # node_instance
1400
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1401
      test = not isinstance(idata, list)
1402
      _ErrorIf(test, self.ENODEHV, node,
1403
               "rpc call to node failed (instancelist)")
1404
      if test:
1405
        continue
1406

    
1407
      node_instance[node] = idata
1408

    
1409
      # node_info
1410
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1411
      test = not isinstance(nodeinfo, dict)
1412
      _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1413
      if test:
1414
        continue
1415

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

    
1444
    node_vol_should = {}
1445

    
1446
    feedback_fn("* Verifying instance status")
1447
    for instance in instancelist:
1448
      if verbose:
1449
        feedback_fn("* Verifying instance %s" % instance)
1450
      inst_config = instanceinfo[instance]
1451
      self._VerifyInstance(instance, inst_config, node_volume,
1452
                           node_instance, n_offline)
1453
      inst_nodes_offline = []
1454

    
1455
      inst_config.MapLVsByNode(node_vol_should)
1456

    
1457
      instance_cfg[instance] = inst_config
1458

    
1459
      pnode = inst_config.primary_node
1460
      _ErrorIf(pnode not in node_info and pnode not in n_offline,
1461
               self.ENODERPC, pnode, "instance %s, connection to"
1462
               " primary node failed", instance)
1463
      if pnode in node_info:
1464
        node_info[pnode]['pinst'].append(instance)
1465

    
1466
      if pnode in n_offline:
1467
        inst_nodes_offline.append(pnode)
1468

    
1469
      # If the instance is non-redundant we cannot survive losing its primary
1470
      # node, so we are not N+1 compliant. On the other hand we have no disk
1471
      # templates with more than one secondary so that situation is not well
1472
      # supported either.
1473
      # FIXME: does not support file-backed instances
1474
      if len(inst_config.secondary_nodes) == 0:
1475
        i_non_redundant.append(instance)
1476
      _ErrorIf(len(inst_config.secondary_nodes) > 1,
1477
               self.EINSTANCELAYOUT, instance,
1478
               "instance has multiple secondary nodes", code="WARNING")
1479

    
1480
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1481
        i_non_a_balanced.append(instance)
1482

    
1483
      for snode in inst_config.secondary_nodes:
1484
        _ErrorIf(snode not in node_info and snode not in n_offline,
1485
                 self.ENODERPC, snode,
1486
                 "instance %s, connection to secondary node"
1487
                 "failed", instance)
1488

    
1489
        if snode in node_info:
1490
          node_info[snode]['sinst'].append(instance)
1491
          if pnode not in node_info[snode]['sinst-by-pnode']:
1492
            node_info[snode]['sinst-by-pnode'][pnode] = []
1493
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1494

    
1495
        if snode in n_offline:
1496
          inst_nodes_offline.append(snode)
1497

    
1498
      # warn that the instance lives on offline nodes
1499
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1500
               "instance lives on offline node(s) %s",
1501
               ", ".join(inst_nodes_offline))
1502

    
1503
    feedback_fn("* Verifying orphan volumes")
1504
    self._VerifyOrphanVolumes(node_vol_should, node_volume)
1505

    
1506
    feedback_fn("* Verifying remaining instances")
1507
    self._VerifyOrphanInstances(instancelist, node_instance)
1508

    
1509
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1510
      feedback_fn("* Verifying N+1 Memory redundancy")
1511
      self._VerifyNPlusOneMemory(node_info, instance_cfg)
1512

    
1513
    feedback_fn("* Other Notes")
1514
    if i_non_redundant:
1515
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1516
                  % len(i_non_redundant))
1517

    
1518
    if i_non_a_balanced:
1519
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1520
                  % len(i_non_a_balanced))
1521

    
1522
    if n_offline:
1523
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1524

    
1525
    if n_drained:
1526
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1527

    
1528
    return not self.bad
1529

    
1530
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1531
    """Analyze the post-hooks' result
1532

1533
    This method analyses the hook result, handles it, and sends some
1534
    nicely-formatted feedback back to the user.
1535

1536
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1537
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1538
    @param hooks_results: the results of the multi-node hooks rpc call
1539
    @param feedback_fn: function used send feedback back to the caller
1540
    @param lu_result: previous Exec result
1541
    @return: the new Exec result, based on the previous result
1542
        and hook results
1543

1544
    """
1545
    # We only really run POST phase hooks, and are only interested in
1546
    # their results
1547
    if phase == constants.HOOKS_PHASE_POST:
1548
      # Used to change hooks' output to proper indentation
1549
      indent_re = re.compile('^', re.M)
1550
      feedback_fn("* Hooks Results")
1551
      assert hooks_results, "invalid result from hooks"
1552

    
1553
      for node_name in hooks_results:
1554
        show_node_header = True
1555
        res = hooks_results[node_name]
1556
        msg = res.fail_msg
1557
        test = msg and not res.offline
1558
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1559
                      "Communication failure in hooks execution: %s", msg)
1560
        if test:
1561
          # override manually lu_result here as _ErrorIf only
1562
          # overrides self.bad
1563
          lu_result = 1
1564
          continue
1565
        for script, hkr, output in res.payload:
1566
          test = hkr == constants.HKR_FAIL
1567
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1568
                        "Script %s failed, output:", script)
1569
          if test:
1570
            output = indent_re.sub('      ', output)
1571
            feedback_fn("%s" % output)
1572
            lu_result = 1
1573

    
1574
      return lu_result
1575

    
1576

    
1577
class LUVerifyDisks(NoHooksLU):
1578
  """Verifies the cluster disks status.
1579

1580
  """
1581
  _OP_REQP = []
1582
  REQ_BGL = False
1583

    
1584
  def ExpandNames(self):
1585
    self.needed_locks = {
1586
      locking.LEVEL_NODE: locking.ALL_SET,
1587
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1588
    }
1589
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1590

    
1591
  def CheckPrereq(self):
1592
    """Check prerequisites.
1593

1594
    This has no prerequisites.
1595

1596
    """
1597
    pass
1598

    
1599
  def Exec(self, feedback_fn):
1600
    """Verify integrity of cluster disks.
1601

1602
    @rtype: tuple of three items
1603
    @return: a tuple of (dict of node-to-node_error, list of instances
1604
        which need activate-disks, dict of instance: (node, volume) for
1605
        missing volumes
1606

1607
    """
1608
    result = res_nodes, res_instances, res_missing = {}, [], {}
1609

    
1610
    vg_name = self.cfg.GetVGName()
1611
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1612
    instances = [self.cfg.GetInstanceInfo(name)
1613
                 for name in self.cfg.GetInstanceList()]
1614

    
1615
    nv_dict = {}
1616
    for inst in instances:
1617
      inst_lvs = {}
1618
      if (not inst.admin_up or
1619
          inst.disk_template not in constants.DTS_NET_MIRROR):
1620
        continue
1621
      inst.MapLVsByNode(inst_lvs)
1622
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1623
      for node, vol_list in inst_lvs.iteritems():
1624
        for vol in vol_list:
1625
          nv_dict[(node, vol)] = inst
1626

    
1627
    if not nv_dict:
1628
      return result
1629

    
1630
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1631

    
1632
    for node in nodes:
1633
      # node_volume
1634
      node_res = node_lvs[node]
1635
      if node_res.offline:
1636
        continue
1637
      msg = node_res.fail_msg
1638
      if msg:
1639
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1640
        res_nodes[node] = msg
1641
        continue
1642

    
1643
      lvs = node_res.payload
1644
      for lv_name, (_, lv_inactive, lv_online) in lvs.items():
1645
        inst = nv_dict.pop((node, lv_name), None)
1646
        if (not lv_online and inst is not None
1647
            and inst.name not in res_instances):
1648
          res_instances.append(inst.name)
1649

    
1650
    # any leftover items in nv_dict are missing LVs, let's arrange the
1651
    # data better
1652
    for key, inst in nv_dict.iteritems():
1653
      if inst.name not in res_missing:
1654
        res_missing[inst.name] = []
1655
      res_missing[inst.name].append(key)
1656

    
1657
    return result
1658

    
1659

    
1660
class LURepairDiskSizes(NoHooksLU):
1661
  """Verifies the cluster disks sizes.
1662

1663
  """
1664
  _OP_REQP = ["instances"]
1665
  REQ_BGL = False
1666

    
1667
  def ExpandNames(self):
1668
    if not isinstance(self.op.instances, list):
1669
      raise errors.OpPrereqError("Invalid argument type 'instances'",
1670
                                 errors.ECODE_INVAL)
1671

    
1672
    if self.op.instances:
1673
      self.wanted_names = []
1674
      for name in self.op.instances:
1675
        full_name = self.cfg.ExpandInstanceName(name)
1676
        if full_name is None:
1677
          raise errors.OpPrereqError("Instance '%s' not known" % name,
1678
                                     errors.ECODE_NOENT)
1679
        self.wanted_names.append(full_name)
1680
      self.needed_locks = {
1681
        locking.LEVEL_NODE: [],
1682
        locking.LEVEL_INSTANCE: self.wanted_names,
1683
        }
1684
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1685
    else:
1686
      self.wanted_names = None
1687
      self.needed_locks = {
1688
        locking.LEVEL_NODE: locking.ALL_SET,
1689
        locking.LEVEL_INSTANCE: locking.ALL_SET,
1690
        }
1691
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1692

    
1693
  def DeclareLocks(self, level):
1694
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
1695
      self._LockInstancesNodes(primary_only=True)
1696

    
1697
  def CheckPrereq(self):
1698
    """Check prerequisites.
1699

1700
    This only checks the optional instance list against the existing names.
1701

1702
    """
1703
    if self.wanted_names is None:
1704
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
1705

    
1706
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
1707
                             in self.wanted_names]
1708

    
1709
  def _EnsureChildSizes(self, disk):
1710
    """Ensure children of the disk have the needed disk size.
1711

1712
    This is valid mainly for DRBD8 and fixes an issue where the
1713
    children have smaller disk size.
1714

1715
    @param disk: an L{ganeti.objects.Disk} object
1716

1717
    """
1718
    if disk.dev_type == constants.LD_DRBD8:
1719
      assert disk.children, "Empty children for DRBD8?"
1720
      fchild = disk.children[0]
1721
      mismatch = fchild.size < disk.size
1722
      if mismatch:
1723
        self.LogInfo("Child disk has size %d, parent %d, fixing",
1724
                     fchild.size, disk.size)
1725
        fchild.size = disk.size
1726

    
1727
      # and we recurse on this child only, not on the metadev
1728
      return self._EnsureChildSizes(fchild) or mismatch
1729
    else:
1730
      return False
1731

    
1732
  def Exec(self, feedback_fn):
1733
    """Verify the size of cluster disks.
1734

1735
    """
1736
    # TODO: check child disks too
1737
    # TODO: check differences in size between primary/secondary nodes
1738
    per_node_disks = {}
1739
    for instance in self.wanted_instances:
1740
      pnode = instance.primary_node
1741
      if pnode not in per_node_disks:
1742
        per_node_disks[pnode] = []
1743
      for idx, disk in enumerate(instance.disks):
1744
        per_node_disks[pnode].append((instance, idx, disk))
1745

    
1746
    changed = []
1747
    for node, dskl in per_node_disks.items():
1748
      newl = [v[2].Copy() for v in dskl]
1749
      for dsk in newl:
1750
        self.cfg.SetDiskID(dsk, node)
1751
      result = self.rpc.call_blockdev_getsizes(node, newl)
1752
      if result.fail_msg:
1753
        self.LogWarning("Failure in blockdev_getsizes call to node"
1754
                        " %s, ignoring", node)
1755
        continue
1756
      if len(result.data) != len(dskl):
1757
        self.LogWarning("Invalid result from node %s, ignoring node results",
1758
                        node)
1759
        continue
1760
      for ((instance, idx, disk), size) in zip(dskl, result.data):
1761
        if size is None:
1762
          self.LogWarning("Disk %d of instance %s did not return size"
1763
                          " information, ignoring", idx, instance.name)
1764
          continue
1765
        if not isinstance(size, (int, long)):
1766
          self.LogWarning("Disk %d of instance %s did not return valid"
1767
                          " size information, ignoring", idx, instance.name)
1768
          continue
1769
        size = size >> 20
1770
        if size != disk.size:
1771
          self.LogInfo("Disk %d of instance %s has mismatched size,"
1772
                       " correcting: recorded %d, actual %d", idx,
1773
                       instance.name, disk.size, size)
1774
          disk.size = size
1775
          self.cfg.Update(instance, feedback_fn)
1776
          changed.append((instance.name, idx, size))
1777
        if self._EnsureChildSizes(disk):
1778
          self.cfg.Update(instance, feedback_fn)
1779
          changed.append((instance.name, idx, disk.size))
1780
    return changed
1781

    
1782

    
1783
class LURenameCluster(LogicalUnit):
1784
  """Rename the cluster.
1785

1786
  """
1787
  HPATH = "cluster-rename"
1788
  HTYPE = constants.HTYPE_CLUSTER
1789
  _OP_REQP = ["name"]
1790

    
1791
  def BuildHooksEnv(self):
1792
    """Build hooks env.
1793

1794
    """
1795
    env = {
1796
      "OP_TARGET": self.cfg.GetClusterName(),
1797
      "NEW_NAME": self.op.name,
1798
      }
1799
    mn = self.cfg.GetMasterNode()
1800
    return env, [mn], [mn]
1801

    
1802
  def CheckPrereq(self):
1803
    """Verify that the passed name is a valid one.
1804

1805
    """
1806
    hostname = utils.GetHostInfo(self.op.name)
1807

    
1808
    new_name = hostname.name
1809
    self.ip = new_ip = hostname.ip
1810
    old_name = self.cfg.GetClusterName()
1811
    old_ip = self.cfg.GetMasterIP()
1812
    if new_name == old_name and new_ip == old_ip:
1813
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1814
                                 " cluster has changed",
1815
                                 errors.ECODE_INVAL)
1816
    if new_ip != old_ip:
1817
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1818
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1819
                                   " reachable on the network. Aborting." %
1820
                                   new_ip, errors.ECODE_NOTUNIQUE)
1821

    
1822
    self.op.name = new_name
1823

    
1824
  def Exec(self, feedback_fn):
1825
    """Rename the cluster.
1826

1827
    """
1828
    clustername = self.op.name
1829
    ip = self.ip
1830

    
1831
    # shutdown the master IP
1832
    master = self.cfg.GetMasterNode()
1833
    result = self.rpc.call_node_stop_master(master, False)
1834
    result.Raise("Could not disable the master role")
1835

    
1836
    try:
1837
      cluster = self.cfg.GetClusterInfo()
1838
      cluster.cluster_name = clustername
1839
      cluster.master_ip = ip
1840
      self.cfg.Update(cluster, feedback_fn)
1841

    
1842
      # update the known hosts file
1843
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1844
      node_list = self.cfg.GetNodeList()
1845
      try:
1846
        node_list.remove(master)
1847
      except ValueError:
1848
        pass
1849
      result = self.rpc.call_upload_file(node_list,
1850
                                         constants.SSH_KNOWN_HOSTS_FILE)
1851
      for to_node, to_result in result.iteritems():
1852
        msg = to_result.fail_msg
1853
        if msg:
1854
          msg = ("Copy of file %s to node %s failed: %s" %
1855
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
1856
          self.proc.LogWarning(msg)
1857

    
1858
    finally:
1859
      result = self.rpc.call_node_start_master(master, False, False)
1860
      msg = result.fail_msg
1861
      if msg:
1862
        self.LogWarning("Could not re-enable the master role on"
1863
                        " the master, please restart manually: %s", msg)
1864

    
1865

    
1866
def _RecursiveCheckIfLVMBased(disk):
1867
  """Check if the given disk or its children are lvm-based.
1868

1869
  @type disk: L{objects.Disk}
1870
  @param disk: the disk to check
1871
  @rtype: boolean
1872
  @return: boolean indicating whether a LD_LV dev_type was found or not
1873

1874
  """
1875
  if disk.children:
1876
    for chdisk in disk.children:
1877
      if _RecursiveCheckIfLVMBased(chdisk):
1878
        return True
1879
  return disk.dev_type == constants.LD_LV
1880

    
1881

    
1882
class LUSetClusterParams(LogicalUnit):
1883
  """Change the parameters of the cluster.
1884

1885
  """
1886
  HPATH = "cluster-modify"
1887
  HTYPE = constants.HTYPE_CLUSTER
1888
  _OP_REQP = []
1889
  REQ_BGL = False
1890

    
1891
  def CheckArguments(self):
1892
    """Check parameters
1893

1894
    """
1895
    if not hasattr(self.op, "candidate_pool_size"):
1896
      self.op.candidate_pool_size = None
1897
    if self.op.candidate_pool_size is not None:
1898
      try:
1899
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1900
      except (ValueError, TypeError), err:
1901
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1902
                                   str(err), errors.ECODE_INVAL)
1903
      if self.op.candidate_pool_size < 1:
1904
        raise errors.OpPrereqError("At least one master candidate needed",
1905
                                   errors.ECODE_INVAL)
1906

    
1907
  def ExpandNames(self):
1908
    # FIXME: in the future maybe other cluster params won't require checking on
1909
    # all nodes to be modified.
1910
    self.needed_locks = {
1911
      locking.LEVEL_NODE: locking.ALL_SET,
1912
    }
1913
    self.share_locks[locking.LEVEL_NODE] = 1
1914

    
1915
  def BuildHooksEnv(self):
1916
    """Build hooks env.
1917

1918
    """
1919
    env = {
1920
      "OP_TARGET": self.cfg.GetClusterName(),
1921
      "NEW_VG_NAME": self.op.vg_name,
1922
      }
1923
    mn = self.cfg.GetMasterNode()
1924
    return env, [mn], [mn]
1925

    
1926
  def CheckPrereq(self):
1927
    """Check prerequisites.
1928

1929
    This checks whether the given params don't conflict and
1930
    if the given volume group is valid.
1931

1932
    """
1933
    if self.op.vg_name is not None and not self.op.vg_name:
1934
      instances = self.cfg.GetAllInstancesInfo().values()
1935
      for inst in instances:
1936
        for disk in inst.disks:
1937
          if _RecursiveCheckIfLVMBased(disk):
1938
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1939
                                       " lvm-based instances exist",
1940
                                       errors.ECODE_INVAL)
1941

    
1942
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1943

    
1944
    # if vg_name not None, checks given volume group on all nodes
1945
    if self.op.vg_name:
1946
      vglist = self.rpc.call_vg_list(node_list)
1947
      for node in node_list:
1948
        msg = vglist[node].fail_msg
1949
        if msg:
1950
          # ignoring down node
1951
          self.LogWarning("Error while gathering data on node %s"
1952
                          " (ignoring node): %s", node, msg)
1953
          continue
1954
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
1955
                                              self.op.vg_name,
1956
                                              constants.MIN_VG_SIZE)
1957
        if vgstatus:
1958
          raise errors.OpPrereqError("Error on node '%s': %s" %
1959
                                     (node, vgstatus), errors.ECODE_ENVIRON)
1960

    
1961
    self.cluster = cluster = self.cfg.GetClusterInfo()
1962
    # validate params changes
1963
    if self.op.beparams:
1964
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
1965
      self.new_beparams = objects.FillDict(
1966
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
1967

    
1968
    if self.op.nicparams:
1969
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
1970
      self.new_nicparams = objects.FillDict(
1971
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
1972
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
1973

    
1974
    # hypervisor list/parameters
1975
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
1976
    if self.op.hvparams:
1977
      if not isinstance(self.op.hvparams, dict):
1978
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
1979
                                   errors.ECODE_INVAL)
1980
      for hv_name, hv_dict in self.op.hvparams.items():
1981
        if hv_name not in self.new_hvparams:
1982
          self.new_hvparams[hv_name] = hv_dict
1983
        else:
1984
          self.new_hvparams[hv_name].update(hv_dict)
1985

    
1986
    if self.op.enabled_hypervisors is not None:
1987
      self.hv_list = self.op.enabled_hypervisors
1988
      if not self.hv_list:
1989
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
1990
                                   " least one member",
1991
                                   errors.ECODE_INVAL)
1992
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
1993
      if invalid_hvs:
1994
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
1995
                                   " entries: %s" % " ,".join(invalid_hvs),
1996
                                   errors.ECODE_INVAL)
1997
    else:
1998
      self.hv_list = cluster.enabled_hypervisors
1999

    
2000
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2001
      # either the enabled list has changed, or the parameters have, validate
2002
      for hv_name, hv_params in self.new_hvparams.items():
2003
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2004
            (self.op.enabled_hypervisors and
2005
             hv_name in self.op.enabled_hypervisors)):
2006
          # either this is a new hypervisor, or its parameters have changed
2007
          hv_class = hypervisor.GetHypervisor(hv_name)
2008
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2009
          hv_class.CheckParameterSyntax(hv_params)
2010
          _CheckHVParams(self, node_list, hv_name, hv_params)
2011

    
2012
  def Exec(self, feedback_fn):
2013
    """Change the parameters of the cluster.
2014

2015
    """
2016
    if self.op.vg_name is not None:
2017
      new_volume = self.op.vg_name
2018
      if not new_volume:
2019
        new_volume = None
2020
      if new_volume != self.cfg.GetVGName():
2021
        self.cfg.SetVGName(new_volume)
2022
      else:
2023
        feedback_fn("Cluster LVM configuration already in desired"
2024
                    " state, not changing")
2025
    if self.op.hvparams:
2026
      self.cluster.hvparams = self.new_hvparams
2027
    if self.op.enabled_hypervisors is not None:
2028
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2029
    if self.op.beparams:
2030
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2031
    if self.op.nicparams:
2032
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2033

    
2034
    if self.op.candidate_pool_size is not None:
2035
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2036
      # we need to update the pool size here, otherwise the save will fail
2037
      _AdjustCandidatePool(self, [])
2038

    
2039
    self.cfg.Update(self.cluster, feedback_fn)
2040

    
2041

    
2042
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2043
  """Distribute additional files which are part of the cluster configuration.
2044

2045
  ConfigWriter takes care of distributing the config and ssconf files, but
2046
  there are more files which should be distributed to all nodes. This function
2047
  makes sure those are copied.
2048

2049
  @param lu: calling logical unit
2050
  @param additional_nodes: list of nodes not in the config to distribute to
2051

2052
  """
2053
  # 1. Gather target nodes
2054
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2055
  dist_nodes = lu.cfg.GetNodeList()
2056
  if additional_nodes is not None:
2057
    dist_nodes.extend(additional_nodes)
2058
  if myself.name in dist_nodes:
2059
    dist_nodes.remove(myself.name)
2060

    
2061
  # 2. Gather files to distribute
2062
  dist_files = set([constants.ETC_HOSTS,
2063
                    constants.SSH_KNOWN_HOSTS_FILE,
2064
                    constants.RAPI_CERT_FILE,
2065
                    constants.RAPI_USERS_FILE,
2066
                    constants.HMAC_CLUSTER_KEY,
2067
                   ])
2068

    
2069
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2070
  for hv_name in enabled_hypervisors:
2071
    hv_class = hypervisor.GetHypervisor(hv_name)
2072
    dist_files.update(hv_class.GetAncillaryFiles())
2073

    
2074
  # 3. Perform the files upload
2075
  for fname in dist_files:
2076
    if os.path.exists(fname):
2077
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2078
      for to_node, to_result in result.items():
2079
        msg = to_result.fail_msg
2080
        if msg:
2081
          msg = ("Copy of file %s to node %s failed: %s" %
2082
                 (fname, to_node, msg))
2083
          lu.proc.LogWarning(msg)
2084

    
2085

    
2086
class LURedistributeConfig(NoHooksLU):
2087
  """Force the redistribution of cluster configuration.
2088

2089
  This is a very simple LU.
2090

2091
  """
2092
  _OP_REQP = []
2093
  REQ_BGL = False
2094

    
2095
  def ExpandNames(self):
2096
    self.needed_locks = {
2097
      locking.LEVEL_NODE: locking.ALL_SET,
2098
    }
2099
    self.share_locks[locking.LEVEL_NODE] = 1
2100

    
2101
  def CheckPrereq(self):
2102
    """Check prerequisites.
2103

2104
    """
2105

    
2106
  def Exec(self, feedback_fn):
2107
    """Redistribute the configuration.
2108

2109
    """
2110
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2111
    _RedistributeAncillaryFiles(self)
2112

    
2113

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

2117
  """
2118
  if not instance.disks:
2119
    return True
2120

    
2121
  if not oneshot:
2122
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2123

    
2124
  node = instance.primary_node
2125

    
2126
  for dev in instance.disks:
2127
    lu.cfg.SetDiskID(dev, node)
2128

    
2129
  # TODO: Convert to utils.Retry
2130

    
2131
  retries = 0
2132
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2133
  while True:
2134
    max_time = 0
2135
    done = True
2136
    cumul_degraded = False
2137
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2138
    msg = rstats.fail_msg
2139
    if msg:
2140
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2141
      retries += 1
2142
      if retries >= 10:
2143
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2144
                                 " aborting." % node)
2145
      time.sleep(6)
2146
      continue
2147
    rstats = rstats.payload
2148
    retries = 0
2149
    for i, mstat in enumerate(rstats):
2150
      if mstat is None:
2151
        lu.LogWarning("Can't compute data for node %s/%s",
2152
                           node, instance.disks[i].iv_name)
2153
        continue
2154

    
2155
      cumul_degraded = (cumul_degraded or
2156
                        (mstat.is_degraded and mstat.sync_percent is None))
2157
      if mstat.sync_percent is not None:
2158
        done = False
2159
        if mstat.estimated_time is not None:
2160
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2161
          max_time = mstat.estimated_time
2162
        else:
2163
          rem_time = "no time estimate"
2164
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2165
                        (instance.disks[i].iv_name, mstat.sync_percent,
2166
                         rem_time))
2167

    
2168
    # if we're done but degraded, let's do a few small retries, to
2169
    # make sure we see a stable and not transient situation; therefore
2170
    # we force restart of the loop
2171
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2172
      logging.info("Degraded disks found, %d retries left", degr_retries)
2173
      degr_retries -= 1
2174
      time.sleep(1)
2175
      continue
2176

    
2177
    if done or oneshot:
2178
      break
2179

    
2180
    time.sleep(min(60, max_time))
2181

    
2182
  if done:
2183
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2184
  return not cumul_degraded
2185

    
2186

    
2187
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2188
  """Check that mirrors are not degraded.
2189

2190
  The ldisk parameter, if True, will change the test from the
2191
  is_degraded attribute (which represents overall non-ok status for
2192
  the device(s)) to the ldisk (representing the local storage status).
2193

2194
  """
2195
  lu.cfg.SetDiskID(dev, node)
2196

    
2197
  result = True
2198

    
2199
  if on_primary or dev.AssembleOnSecondary():
2200
    rstats = lu.rpc.call_blockdev_find(node, dev)
2201
    msg = rstats.fail_msg
2202
    if msg:
2203
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2204
      result = False
2205
    elif not rstats.payload:
2206
      lu.LogWarning("Can't find disk on node %s", node)
2207
      result = False
2208
    else:
2209
      if ldisk:
2210
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2211
      else:
2212
        result = result and not rstats.payload.is_degraded
2213

    
2214
  if dev.children:
2215
    for child in dev.children:
2216
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2217

    
2218
  return result
2219

    
2220

    
2221
class LUDiagnoseOS(NoHooksLU):
2222
  """Logical unit for OS diagnose/query.
2223

2224
  """
2225
  _OP_REQP = ["output_fields", "names"]
2226
  REQ_BGL = False
2227
  _FIELDS_STATIC = utils.FieldSet()
2228
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2229
  # Fields that need calculation of global os validity
2230
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2231

    
2232
  def ExpandNames(self):
2233
    if self.op.names:
2234
      raise errors.OpPrereqError("Selective OS query not supported",
2235
                                 errors.ECODE_INVAL)
2236

    
2237
    _CheckOutputFields(static=self._FIELDS_STATIC,
2238
                       dynamic=self._FIELDS_DYNAMIC,
2239
                       selected=self.op.output_fields)
2240

    
2241
    # Lock all nodes, in shared mode
2242
    # Temporary removal of locks, should be reverted later
2243
    # TODO: reintroduce locks when they are lighter-weight
2244
    self.needed_locks = {}
2245
    #self.share_locks[locking.LEVEL_NODE] = 1
2246
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2247

    
2248
  def CheckPrereq(self):
2249
    """Check prerequisites.
2250

2251
    """
2252

    
2253
  @staticmethod
2254
  def _DiagnoseByOS(node_list, rlist):
2255
    """Remaps a per-node return list into an a per-os per-node dictionary
2256

2257
    @param node_list: a list with the names of all nodes
2258
    @param rlist: a map with node names as keys and OS objects as values
2259

2260
    @rtype: dict
2261
    @return: a dictionary with osnames as keys and as value another map, with
2262
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2263

2264
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2265
                                     (/srv/..., False, "invalid api")],
2266
                           "node2": [(/srv/..., True, "")]}
2267
          }
2268

2269
    """
2270
    all_os = {}
2271
    # we build here the list of nodes that didn't fail the RPC (at RPC
2272
    # level), so that nodes with a non-responding node daemon don't
2273
    # make all OSes invalid
2274
    good_nodes = [node_name for node_name in rlist
2275
                  if not rlist[node_name].fail_msg]
2276
    for node_name, nr in rlist.items():
2277
      if nr.fail_msg or not nr.payload:
2278
        continue
2279
      for name, path, status, diagnose, variants in nr.payload:
2280
        if name not in all_os:
2281
          # build a list of nodes for this os containing empty lists
2282
          # for each node in node_list
2283
          all_os[name] = {}
2284
          for nname in good_nodes:
2285
            all_os[name][nname] = []
2286
        all_os[name][node_name].append((path, status, diagnose, variants))
2287
    return all_os
2288

    
2289
  def Exec(self, feedback_fn):
2290
    """Compute the list of OSes.
2291

2292
    """
2293
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2294
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2295
    pol = self._DiagnoseByOS(valid_nodes, node_data)
2296
    output = []
2297
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2298
    calc_variants = "variants" in self.op.output_fields
2299

    
2300
    for os_name, os_data in pol.items():
2301
      row = []
2302
      if calc_valid:
2303
        valid = True
2304
        variants = None
2305
        for osl in os_data.values():
2306
          valid = valid and osl and osl[0][1]
2307
          if not valid:
2308
            variants = None
2309
            break
2310
          if calc_variants:
2311
            node_variants = osl[0][3]
2312
            if variants is None:
2313
              variants = node_variants
2314
            else:
2315
              variants = [v for v in variants if v in node_variants]
2316

    
2317
      for field in self.op.output_fields:
2318
        if field == "name":
2319
          val = os_name
2320
        elif field == "valid":
2321
          val = valid
2322
        elif field == "node_status":
2323
          # this is just a copy of the dict
2324
          val = {}
2325
          for node_name, nos_list in os_data.items():
2326
            val[node_name] = nos_list
2327
        elif field == "variants":
2328
          val =  variants
2329
        else:
2330
          raise errors.ParameterError(field)
2331
        row.append(val)
2332
      output.append(row)
2333

    
2334
    return output
2335

    
2336

    
2337
class LURemoveNode(LogicalUnit):
2338
  """Logical unit for removing a node.
2339

2340
  """
2341
  HPATH = "node-remove"
2342
  HTYPE = constants.HTYPE_NODE
2343
  _OP_REQP = ["node_name"]
2344

    
2345
  def BuildHooksEnv(self):
2346
    """Build hooks env.
2347

2348
    This doesn't run on the target node in the pre phase as a failed
2349
    node would then be impossible to remove.
2350

2351
    """
2352
    env = {
2353
      "OP_TARGET": self.op.node_name,
2354
      "NODE_NAME": self.op.node_name,
2355
      }
2356
    all_nodes = self.cfg.GetNodeList()
2357
    if self.op.node_name in all_nodes:
2358
      all_nodes.remove(self.op.node_name)
2359
    return env, all_nodes, all_nodes
2360

    
2361
  def CheckPrereq(self):
2362
    """Check prerequisites.
2363

2364
    This checks:
2365
     - the node exists in the configuration
2366
     - it does not have primary or secondary instances
2367
     - it's not the master
2368

2369
    Any errors are signaled by raising errors.OpPrereqError.
2370

2371
    """
2372
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
2373
    if node is None:
2374
      raise errors.OpPrereqError("Node '%s' is unknown." % self.op.node_name,
2375
                                 errors.ECODE_NOENT)
2376

    
2377
    instance_list = self.cfg.GetInstanceList()
2378

    
2379
    masternode = self.cfg.GetMasterNode()
2380
    if node.name == masternode:
2381
      raise errors.OpPrereqError("Node is the master node,"
2382
                                 " you need to failover first.",
2383
                                 errors.ECODE_INVAL)
2384

    
2385
    for instance_name in instance_list:
2386
      instance = self.cfg.GetInstanceInfo(instance_name)
2387
      if node.name in instance.all_nodes:
2388
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2389
                                   " please remove first." % instance_name,
2390
                                   errors.ECODE_INVAL)
2391
    self.op.node_name = node.name
2392
    self.node = node
2393

    
2394
  def Exec(self, feedback_fn):
2395
    """Removes the node from the cluster.
2396

2397
    """
2398
    node = self.node
2399
    logging.info("Stopping the node daemon and removing configs from node %s",
2400
                 node.name)
2401

    
2402
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2403

    
2404
    # Promote nodes to master candidate as needed
2405
    _AdjustCandidatePool(self, exceptions=[node.name])
2406
    self.context.RemoveNode(node.name)
2407

    
2408
    # Run post hooks on the node before it's removed
2409
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2410
    try:
2411
      h_results = hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2412
    except:
2413
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2414

    
2415
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2416
    msg = result.fail_msg
2417
    if msg:
2418
      self.LogWarning("Errors encountered on the remote node while leaving"
2419
                      " the cluster: %s", msg)
2420

    
2421

    
2422
class LUQueryNodes(NoHooksLU):
2423
  """Logical unit for querying nodes.
2424

2425
  """
2426
  _OP_REQP = ["output_fields", "names", "use_locking"]
2427
  REQ_BGL = False
2428

    
2429
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2430
                    "master_candidate", "offline", "drained"]
2431

    
2432
  _FIELDS_DYNAMIC = utils.FieldSet(
2433
    "dtotal", "dfree",
2434
    "mtotal", "mnode", "mfree",
2435
    "bootid",
2436
    "ctotal", "cnodes", "csockets",
2437
    )
2438

    
2439
  _FIELDS_STATIC = utils.FieldSet(*[
2440
    "pinst_cnt", "sinst_cnt",
2441
    "pinst_list", "sinst_list",
2442
    "pip", "sip", "tags",
2443
    "master",
2444
    "role"] + _SIMPLE_FIELDS
2445
    )
2446

    
2447
  def ExpandNames(self):
2448
    _CheckOutputFields(static=self._FIELDS_STATIC,
2449
                       dynamic=self._FIELDS_DYNAMIC,
2450
                       selected=self.op.output_fields)
2451

    
2452
    self.needed_locks = {}
2453
    self.share_locks[locking.LEVEL_NODE] = 1
2454

    
2455
    if self.op.names:
2456
      self.wanted = _GetWantedNodes(self, self.op.names)
2457
    else:
2458
      self.wanted = locking.ALL_SET
2459

    
2460
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2461
    self.do_locking = self.do_node_query and self.op.use_locking
2462
    if self.do_locking:
2463
      # if we don't request only static fields, we need to lock the nodes
2464
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2465

    
2466
  def CheckPrereq(self):
2467
    """Check prerequisites.
2468

2469
    """
2470
    # The validation of the node list is done in the _GetWantedNodes,
2471
    # if non empty, and if empty, there's no validation to do
2472
    pass
2473

    
2474
  def Exec(self, feedback_fn):
2475
    """Computes the list of nodes and their attributes.
2476

2477
    """
2478
    all_info = self.cfg.GetAllNodesInfo()
2479
    if self.do_locking:
2480
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2481
    elif self.wanted != locking.ALL_SET:
2482
      nodenames = self.wanted
2483
      missing = set(nodenames).difference(all_info.keys())
2484
      if missing:
2485
        raise errors.OpExecError(
2486
          "Some nodes were removed before retrieving their data: %s" % missing)
2487
    else:
2488
      nodenames = all_info.keys()
2489

    
2490
    nodenames = utils.NiceSort(nodenames)
2491
    nodelist = [all_info[name] for name in nodenames]
2492

    
2493
    # begin data gathering
2494

    
2495
    if self.do_node_query:
2496
      live_data = {}
2497
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2498
                                          self.cfg.GetHypervisorType())
2499
      for name in nodenames:
2500
        nodeinfo = node_data[name]
2501
        if not nodeinfo.fail_msg and nodeinfo.payload:
2502
          nodeinfo = nodeinfo.payload
2503
          fn = utils.TryConvert
2504
          live_data[name] = {
2505
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2506
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2507
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2508
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2509
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2510
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2511
            "bootid": nodeinfo.get('bootid', None),
2512
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2513
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2514
            }
2515
        else:
2516
          live_data[name] = {}
2517
    else:
2518
      live_data = dict.fromkeys(nodenames, {})
2519

    
2520
    node_to_primary = dict([(name, set()) for name in nodenames])
2521
    node_to_secondary = dict([(name, set()) for name in nodenames])
2522

    
2523
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2524
                             "sinst_cnt", "sinst_list"))
2525
    if inst_fields & frozenset(self.op.output_fields):
2526
      instancelist = self.cfg.GetInstanceList()
2527

    
2528
      for instance_name in instancelist:
2529
        inst = self.cfg.GetInstanceInfo(instance_name)
2530
        if inst.primary_node in node_to_primary:
2531
          node_to_primary[inst.primary_node].add(inst.name)
2532
        for secnode in inst.secondary_nodes:
2533
          if secnode in node_to_secondary:
2534
            node_to_secondary[secnode].add(inst.name)
2535

    
2536
    master_node = self.cfg.GetMasterNode()
2537

    
2538
    # end data gathering
2539

    
2540
    output = []
2541
    for node in nodelist:
2542
      node_output = []
2543
      for field in self.op.output_fields:
2544
        if field in self._SIMPLE_FIELDS:
2545
          val = getattr(node, field)
2546
        elif field == "pinst_list":
2547
          val = list(node_to_primary[node.name])
2548
        elif field == "sinst_list":
2549
          val = list(node_to_secondary[node.name])
2550
        elif field == "pinst_cnt":
2551
          val = len(node_to_primary[node.name])
2552
        elif field == "sinst_cnt":
2553
          val = len(node_to_secondary[node.name])
2554
        elif field == "pip":
2555
          val = node.primary_ip
2556
        elif field == "sip":
2557
          val = node.secondary_ip
2558
        elif field == "tags":
2559
          val = list(node.GetTags())
2560
        elif field == "master":
2561
          val = node.name == master_node
2562
        elif self._FIELDS_DYNAMIC.Matches(field):
2563
          val = live_data[node.name].get(field, None)
2564
        elif field == "role":
2565
          if node.name == master_node:
2566
            val = "M"
2567
          elif node.master_candidate:
2568
            val = "C"
2569
          elif node.drained:
2570
            val = "D"
2571
          elif node.offline:
2572
            val = "O"
2573
          else:
2574
            val = "R"
2575
        else:
2576
          raise errors.ParameterError(field)
2577
        node_output.append(val)
2578
      output.append(node_output)
2579

    
2580
    return output
2581

    
2582

    
2583
class LUQueryNodeVolumes(NoHooksLU):
2584
  """Logical unit for getting volumes on node(s).
2585

2586
  """
2587
  _OP_REQP = ["nodes", "output_fields"]
2588
  REQ_BGL = False
2589
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2590
  _FIELDS_STATIC = utils.FieldSet("node")
2591

    
2592
  def ExpandNames(self):
2593
    _CheckOutputFields(static=self._FIELDS_STATIC,
2594
                       dynamic=self._FIELDS_DYNAMIC,
2595
                       selected=self.op.output_fields)
2596

    
2597
    self.needed_locks = {}
2598
    self.share_locks[locking.LEVEL_NODE] = 1
2599
    if not self.op.nodes:
2600
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2601
    else:
2602
      self.needed_locks[locking.LEVEL_NODE] = \
2603
        _GetWantedNodes(self, self.op.nodes)
2604

    
2605
  def CheckPrereq(self):
2606
    """Check prerequisites.
2607

2608
    This checks that the fields required are valid output fields.
2609

2610
    """
2611
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2612

    
2613
  def Exec(self, feedback_fn):
2614
    """Computes the list of nodes and their attributes.
2615

2616
    """
2617
    nodenames = self.nodes
2618
    volumes = self.rpc.call_node_volumes(nodenames)
2619

    
2620
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2621
             in self.cfg.GetInstanceList()]
2622

    
2623
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2624

    
2625
    output = []
2626
    for node in nodenames:
2627
      nresult = volumes[node]
2628
      if nresult.offline:
2629
        continue
2630
      msg = nresult.fail_msg
2631
      if msg:
2632
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
2633
        continue
2634

    
2635
      node_vols = nresult.payload[:]
2636
      node_vols.sort(key=lambda vol: vol['dev'])
2637

    
2638
      for vol in node_vols:
2639
        node_output = []
2640
        for field in self.op.output_fields:
2641
          if field == "node":
2642
            val = node
2643
          elif field == "phys":
2644
            val = vol['dev']
2645
          elif field == "vg":
2646
            val = vol['vg']
2647
          elif field == "name":
2648
            val = vol['name']
2649
          elif field == "size":
2650
            val = int(float(vol['size']))
2651
          elif field == "instance":
2652
            for inst in ilist:
2653
              if node not in lv_by_node[inst]:
2654
                continue
2655
              if vol['name'] in lv_by_node[inst][node]:
2656
                val = inst.name
2657
                break
2658
            else:
2659
              val = '-'
2660
          else:
2661
            raise errors.ParameterError(field)
2662
          node_output.append(str(val))
2663

    
2664
        output.append(node_output)
2665

    
2666
    return output
2667

    
2668

    
2669
class LUQueryNodeStorage(NoHooksLU):
2670
  """Logical unit for getting information on storage units on node(s).
2671

2672
  """
2673
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
2674
  REQ_BGL = False
2675
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
2676

    
2677
  def ExpandNames(self):
2678
    storage_type = self.op.storage_type
2679

    
2680
    if storage_type not in constants.VALID_STORAGE_TYPES:
2681
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2682
                                 errors.ECODE_INVAL)
2683

    
2684
    _CheckOutputFields(static=self._FIELDS_STATIC,
2685
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
2686
                       selected=self.op.output_fields)
2687

    
2688
    self.needed_locks = {}
2689
    self.share_locks[locking.LEVEL_NODE] = 1
2690

    
2691
    if self.op.nodes:
2692
      self.needed_locks[locking.LEVEL_NODE] = \
2693
        _GetWantedNodes(self, self.op.nodes)
2694
    else:
2695
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2696

    
2697
  def CheckPrereq(self):
2698
    """Check prerequisites.
2699

2700
    This checks that the fields required are valid output fields.
2701

2702
    """
2703
    self.op.name = getattr(self.op, "name", None)
2704

    
2705
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2706

    
2707
  def Exec(self, feedback_fn):
2708
    """Computes the list of nodes and their attributes.
2709

2710
    """
2711
    # Always get name to sort by
2712
    if constants.SF_NAME in self.op.output_fields:
2713
      fields = self.op.output_fields[:]
2714
    else:
2715
      fields = [constants.SF_NAME] + self.op.output_fields
2716

    
2717
    # Never ask for node or type as it's only known to the LU
2718
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
2719
      while extra in fields:
2720
        fields.remove(extra)
2721

    
2722
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
2723
    name_idx = field_idx[constants.SF_NAME]
2724

    
2725
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2726
    data = self.rpc.call_storage_list(self.nodes,
2727
                                      self.op.storage_type, st_args,
2728
                                      self.op.name, fields)
2729

    
2730
    result = []
2731

    
2732
    for node in utils.NiceSort(self.nodes):
2733
      nresult = data[node]
2734
      if nresult.offline:
2735
        continue
2736

    
2737
      msg = nresult.fail_msg
2738
      if msg:
2739
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
2740
        continue
2741

    
2742
      rows = dict([(row[name_idx], row) for row in nresult.payload])
2743

    
2744
      for name in utils.NiceSort(rows.keys()):
2745
        row = rows[name]
2746

    
2747
        out = []
2748

    
2749
        for field in self.op.output_fields:
2750
          if field == constants.SF_NODE:
2751
            val = node
2752
          elif field == constants.SF_TYPE:
2753
            val = self.op.storage_type
2754
          elif field in field_idx:
2755
            val = row[field_idx[field]]
2756
          else:
2757
            raise errors.ParameterError(field)
2758

    
2759
          out.append(val)
2760

    
2761
        result.append(out)
2762

    
2763
    return result
2764

    
2765

    
2766
class LUModifyNodeStorage(NoHooksLU):
2767
  """Logical unit for modifying a storage volume on a node.
2768

2769
  """
2770
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
2771
  REQ_BGL = False
2772

    
2773
  def CheckArguments(self):
2774
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2775
    if node_name is None:
2776
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
2777
                                 errors.ECODE_NOENT)
2778

    
2779
    self.op.node_name = node_name
2780

    
2781
    storage_type = self.op.storage_type
2782
    if storage_type not in constants.VALID_STORAGE_TYPES:
2783
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2784
                                 errors.ECODE_INVAL)
2785

    
2786
  def ExpandNames(self):
2787
    self.needed_locks = {
2788
      locking.LEVEL_NODE: self.op.node_name,
2789
      }
2790

    
2791
  def CheckPrereq(self):
2792
    """Check prerequisites.
2793

2794
    """
2795
    storage_type = self.op.storage_type
2796

    
2797
    try:
2798
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
2799
    except KeyError:
2800
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
2801
                                 " modified" % storage_type,
2802
                                 errors.ECODE_INVAL)
2803

    
2804
    diff = set(self.op.changes.keys()) - modifiable
2805
    if diff:
2806
      raise errors.OpPrereqError("The following fields can not be modified for"
2807
                                 " storage units of type '%s': %r" %
2808
                                 (storage_type, list(diff)),
2809
                                 errors.ECODE_INVAL)
2810

    
2811
  def Exec(self, feedback_fn):
2812
    """Computes the list of nodes and their attributes.
2813

2814
    """
2815
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2816
    result = self.rpc.call_storage_modify(self.op.node_name,
2817
                                          self.op.storage_type, st_args,
2818
                                          self.op.name, self.op.changes)
2819
    result.Raise("Failed to modify storage unit '%s' on %s" %
2820
                 (self.op.name, self.op.node_name))
2821

    
2822

    
2823
class LUAddNode(LogicalUnit):
2824
  """Logical unit for adding node to the cluster.
2825

2826
  """
2827
  HPATH = "node-add"
2828
  HTYPE = constants.HTYPE_NODE
2829
  _OP_REQP = ["node_name"]
2830

    
2831
  def BuildHooksEnv(self):
2832
    """Build hooks env.
2833

2834
    This will run on all nodes before, and on all nodes + the new node after.
2835

2836
    """
2837
    env = {
2838
      "OP_TARGET": self.op.node_name,
2839
      "NODE_NAME": self.op.node_name,
2840
      "NODE_PIP": self.op.primary_ip,
2841
      "NODE_SIP": self.op.secondary_ip,
2842
      }
2843
    nodes_0 = self.cfg.GetNodeList()
2844
    nodes_1 = nodes_0 + [self.op.node_name, ]
2845
    return env, nodes_0, nodes_1
2846

    
2847
  def CheckPrereq(self):
2848
    """Check prerequisites.
2849

2850
    This checks:
2851
     - the new node is not already in the config
2852
     - it is resolvable
2853
     - its parameters (single/dual homed) matches the cluster
2854

2855
    Any errors are signaled by raising errors.OpPrereqError.
2856

2857
    """
2858
    node_name = self.op.node_name
2859
    cfg = self.cfg
2860

    
2861
    dns_data = utils.GetHostInfo(node_name)
2862

    
2863
    node = dns_data.name
2864
    primary_ip = self.op.primary_ip = dns_data.ip
2865
    secondary_ip = getattr(self.op, "secondary_ip", None)
2866
    if secondary_ip is None:
2867
      secondary_ip = primary_ip
2868
    if not utils.IsValidIP(secondary_ip):
2869
      raise errors.OpPrereqError("Invalid secondary IP given",
2870
                                 errors.ECODE_INVAL)
2871
    self.op.secondary_ip = secondary_ip
2872

    
2873
    node_list = cfg.GetNodeList()
2874
    if not self.op.readd and node in node_list:
2875
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2876
                                 node, errors.ECODE_EXISTS)
2877
    elif self.op.readd and node not in node_list:
2878
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
2879
                                 errors.ECODE_NOENT)
2880

    
2881
    for existing_node_name in node_list:
2882
      existing_node = cfg.GetNodeInfo(existing_node_name)
2883

    
2884
      if self.op.readd and node == existing_node_name:
2885
        if (existing_node.primary_ip != primary_ip or
2886
            existing_node.secondary_ip != secondary_ip):
2887
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2888
                                     " address configuration as before",
2889
                                     errors.ECODE_INVAL)
2890
        continue
2891

    
2892
      if (existing_node.primary_ip == primary_ip or
2893
          existing_node.secondary_ip == primary_ip or
2894
          existing_node.primary_ip == secondary_ip or
2895
          existing_node.secondary_ip == secondary_ip):
2896
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2897
                                   " existing node %s" % existing_node.name,
2898
                                   errors.ECODE_NOTUNIQUE)
2899

    
2900
    # check that the type of the node (single versus dual homed) is the
2901
    # same as for the master
2902
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2903
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2904
    newbie_singlehomed = secondary_ip == primary_ip
2905
    if master_singlehomed != newbie_singlehomed:
2906
      if master_singlehomed:
2907
        raise errors.OpPrereqError("The master has no private ip but the"
2908
                                   " new node has one",
2909
                                   errors.ECODE_INVAL)
2910
      else:
2911
        raise errors.OpPrereqError("The master has a private ip but the"
2912
                                   " new node doesn't have one",
2913
                                   errors.ECODE_INVAL)
2914

    
2915
    # checks reachability
2916
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2917
      raise errors.OpPrereqError("Node not reachable by ping",
2918
                                 errors.ECODE_ENVIRON)
2919

    
2920
    if not newbie_singlehomed:
2921
      # check reachability from my secondary ip to newbie's secondary ip
2922
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2923
                           source=myself.secondary_ip):
2924
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2925
                                   " based ping to noded port",
2926
                                   errors.ECODE_ENVIRON)
2927

    
2928
    if self.op.readd:
2929
      exceptions = [node]
2930
    else:
2931
      exceptions = []
2932

    
2933
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
2934

    
2935
    if self.op.readd:
2936
      self.new_node = self.cfg.GetNodeInfo(node)
2937
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
2938
    else:
2939
      self.new_node = objects.Node(name=node,
2940
                                   primary_ip=primary_ip,
2941
                                   secondary_ip=secondary_ip,
2942
                                   master_candidate=self.master_candidate,
2943
                                   offline=False, drained=False)
2944

    
2945
  def Exec(self, feedback_fn):
2946
    """Adds the new node to the cluster.
2947

2948
    """
2949
    new_node = self.new_node
2950
    node = new_node.name
2951

    
2952
    # for re-adds, reset the offline/drained/master-candidate flags;
2953
    # we need to reset here, otherwise offline would prevent RPC calls
2954
    # later in the procedure; this also means that if the re-add
2955
    # fails, we are left with a non-offlined, broken node
2956
    if self.op.readd:
2957
      new_node.drained = new_node.offline = False
2958
      self.LogInfo("Readding a node, the offline/drained flags were reset")
2959
      # if we demote the node, we do cleanup later in the procedure
2960
      new_node.master_candidate = self.master_candidate
2961

    
2962
    # notify the user about any possible mc promotion
2963
    if new_node.master_candidate:
2964
      self.LogInfo("Node will be a master candidate")
2965

    
2966
    # check connectivity
2967
    result = self.rpc.call_version([node])[node]
2968
    result.Raise("Can't get version information from node %s" % node)
2969
    if constants.PROTOCOL_VERSION == result.payload:
2970
      logging.info("Communication to node %s fine, sw version %s match",
2971
                   node, result.payload)
2972
    else:
2973
      raise errors.OpExecError("Version mismatch master version %s,"
2974
                               " node version %s" %
2975
                               (constants.PROTOCOL_VERSION, result.payload))
2976

    
2977
    # setup ssh on node
2978
    if self.cfg.GetClusterInfo().modify_ssh_setup:
2979
      logging.info("Copy ssh key to node %s", node)
2980
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2981
      keyarray = []
2982
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2983
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2984
                  priv_key, pub_key]
2985

    
2986
      for i in keyfiles:
2987
        keyarray.append(utils.ReadFile(i))
2988

    
2989
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2990
                                      keyarray[2], keyarray[3], keyarray[4],
2991
                                      keyarray[5])
2992
      result.Raise("Cannot transfer ssh keys to the new node")
2993

    
2994
    # Add node to our /etc/hosts, and add key to known_hosts
2995
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2996
      utils.AddHostToEtcHosts(new_node.name)
2997

    
2998
    if new_node.secondary_ip != new_node.primary_ip:
2999
      result = self.rpc.call_node_has_ip_address(new_node.name,
3000
                                                 new_node.secondary_ip)
3001
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3002
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3003
      if not result.payload:
3004
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3005
                                 " you gave (%s). Please fix and re-run this"
3006
                                 " command." % new_node.secondary_ip)
3007

    
3008
    node_verify_list = [self.cfg.GetMasterNode()]
3009
    node_verify_param = {
3010
      constants.NV_NODELIST: [node],
3011
      # TODO: do a node-net-test as well?
3012
    }
3013

    
3014
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3015
                                       self.cfg.GetClusterName())
3016
    for verifier in node_verify_list:
3017
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3018
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3019
      if nl_payload:
3020
        for failed in nl_payload:
3021
          feedback_fn("ssh/hostname verification failed"
3022
                      " (checking from %s): %s" %
3023
                      (verifier, nl_payload[failed]))
3024
        raise errors.OpExecError("ssh/hostname verification failed.")
3025

    
3026
    if self.op.readd:
3027
      _RedistributeAncillaryFiles(self)
3028
      self.context.ReaddNode(new_node)
3029
      # make sure we redistribute the config
3030
      self.cfg.Update(new_node, feedback_fn)
3031
      # and make sure the new node will not have old files around
3032
      if not new_node.master_candidate:
3033
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3034
        msg = result.fail_msg
3035
        if msg:
3036
          self.LogWarning("Node failed to demote itself from master"
3037
                          " candidate status: %s" % msg)
3038
    else:
3039
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3040
      self.context.AddNode(new_node, self.proc.GetECId())
3041

    
3042

    
3043
class LUSetNodeParams(LogicalUnit):
3044
  """Modifies the parameters of a node.
3045

3046
  """
3047
  HPATH = "node-modify"
3048
  HTYPE = constants.HTYPE_NODE
3049
  _OP_REQP = ["node_name"]
3050
  REQ_BGL = False
3051

    
3052
  def CheckArguments(self):
3053
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3054
    if node_name is None:
3055
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3056
                                 errors.ECODE_INVAL)
3057
    self.op.node_name = node_name
3058
    _CheckBooleanOpField(self.op, 'master_candidate')
3059
    _CheckBooleanOpField(self.op, 'offline')
3060
    _CheckBooleanOpField(self.op, 'drained')
3061
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3062
    if all_mods.count(None) == 3:
3063
      raise errors.OpPrereqError("Please pass at least one modification",
3064
                                 errors.ECODE_INVAL)
3065
    if all_mods.count(True) > 1:
3066
      raise errors.OpPrereqError("Can't set the node into more than one"
3067
                                 " state at the same time",
3068
                                 errors.ECODE_INVAL)
3069

    
3070
  def ExpandNames(self):
3071
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3072

    
3073
  def BuildHooksEnv(self):
3074
    """Build hooks env.
3075

3076
    This runs on the master node.
3077

3078
    """
3079
    env = {
3080
      "OP_TARGET": self.op.node_name,
3081
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3082
      "OFFLINE": str(self.op.offline),
3083
      "DRAINED": str(self.op.drained),
3084
      }
3085
    nl = [self.cfg.GetMasterNode(),
3086
          self.op.node_name]
3087
    return env, nl, nl
3088

    
3089
  def CheckPrereq(self):
3090
    """Check prerequisites.
3091

3092
    This only checks the instance list against the existing names.
3093

3094
    """
3095
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3096

    
3097
    if (self.op.master_candidate is not None or
3098
        self.op.drained is not None or
3099
        self.op.offline is not None):
3100
      # we can't change the master's node flags
3101
      if self.op.node_name == self.cfg.GetMasterNode():
3102
        raise errors.OpPrereqError("The master role can be changed"
3103
                                   " only via masterfailover",
3104
                                   errors.ECODE_INVAL)
3105

    
3106
    # Boolean value that tells us whether we're offlining or draining the node
3107
    offline_or_drain = self.op.offline == True or self.op.drained == True
3108
    deoffline_or_drain = self.op.offline == False or self.op.drained == False
3109

    
3110
    if (node.master_candidate and
3111
        (self.op.master_candidate == False or offline_or_drain)):
3112
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
3113
      mc_now, mc_should, mc_max = self.cfg.GetMasterCandidateStats()
3114
      if mc_now <= cp_size:
3115
        msg = ("Not enough master candidates (desired"
3116
               " %d, new value will be %d)" % (cp_size, mc_now-1))
3117
        # Only allow forcing the operation if it's an offline/drain operation,
3118
        # and we could not possibly promote more nodes.
3119
        # FIXME: this can still lead to issues if in any way another node which
3120
        # could be promoted appears in the meantime.
3121
        if self.op.force and offline_or_drain and mc_should == mc_max:
3122
          self.LogWarning(msg)
3123
        else:
3124
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
3125

    
3126
    if (self.op.master_candidate == True and
3127
        ((node.offline and not self.op.offline == False) or
3128
         (node.drained and not self.op.drained == False))):
3129
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3130
                                 " to master_candidate" % node.name,
3131
                                 errors.ECODE_INVAL)
3132

    
3133
    # If we're being deofflined/drained, we'll MC ourself if needed
3134
    if (deoffline_or_drain and not offline_or_drain and not
3135
        self.op.master_candidate == True):
3136
      self.op.master_candidate = _DecideSelfPromotion(self)
3137
      if self.op.master_candidate:
3138
        self.LogInfo("Autopromoting node to master candidate")
3139

    
3140
    return
3141

    
3142
  def Exec(self, feedback_fn):
3143
    """Modifies a node.
3144

3145
    """
3146
    node = self.node
3147

    
3148
    result = []
3149
    changed_mc = False
3150

    
3151
    if self.op.offline is not None:
3152
      node.offline = self.op.offline
3153
      result.append(("offline", str(self.op.offline)))
3154
      if self.op.offline == True:
3155
        if node.master_candidate:
3156
          node.master_candidate = False
3157
          changed_mc = True
3158
          result.append(("master_candidate", "auto-demotion due to offline"))
3159
        if node.drained:
3160
          node.drained = False
3161
          result.append(("drained", "clear drained status due to offline"))
3162

    
3163
    if self.op.master_candidate is not None:
3164
      node.master_candidate = self.op.master_candidate
3165
      changed_mc = True
3166
      result.append(("master_candidate", str(self.op.master_candidate)))
3167
      if self.op.master_candidate == False:
3168
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3169
        msg = rrc.fail_msg
3170
        if msg:
3171
          self.LogWarning("Node failed to demote itself: %s" % msg)
3172

    
3173
    if self.op.drained is not None:
3174
      node.drained = self.op.drained
3175
      result.append(("drained", str(self.op.drained)))
3176
      if self.op.drained == True:
3177
        if node.master_candidate:
3178
          node.master_candidate = False
3179
          changed_mc = True
3180
          result.append(("master_candidate", "auto-demotion due to drain"))
3181
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3182
          msg = rrc.fail_msg
3183
          if msg:
3184
            self.LogWarning("Node failed to demote itself: %s" % msg)
3185
        if node.offline:
3186
          node.offline = False
3187
          result.append(("offline", "clear offline status due to drain"))
3188

    
3189
    # this will trigger configuration file update, if needed
3190
    self.cfg.Update(node, feedback_fn)
3191
    # this will trigger job queue propagation or cleanup
3192
    if changed_mc:
3193
      self.context.ReaddNode(node)
3194

    
3195
    return result
3196

    
3197

    
3198
class LUPowercycleNode(NoHooksLU):
3199
  """Powercycles a node.
3200

3201
  """
3202
  _OP_REQP = ["node_name", "force"]
3203
  REQ_BGL = False
3204

    
3205
  def CheckArguments(self):
3206
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3207
    if node_name is None:
3208
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3209
                                 errors.ECODE_NOENT)
3210
    self.op.node_name = node_name
3211
    if node_name == self.cfg.GetMasterNode() and not self.op.force:
3212
      raise errors.OpPrereqError("The node is the master and the force"
3213
                                 " parameter was not set",
3214
                                 errors.ECODE_INVAL)
3215

    
3216
  def ExpandNames(self):
3217
    """Locking for PowercycleNode.
3218

3219
    This is a last-resort option and shouldn't block on other
3220
    jobs. Therefore, we grab no locks.
3221

3222
    """
3223
    self.needed_locks = {}
3224

    
3225
  def CheckPrereq(self):
3226
    """Check prerequisites.
3227

3228
    This LU has no prereqs.
3229

3230
    """
3231
    pass
3232

    
3233
  def Exec(self, feedback_fn):
3234
    """Reboots a node.
3235

3236
    """
3237
    result = self.rpc.call_node_powercycle(self.op.node_name,
3238
                                           self.cfg.GetHypervisorType())
3239
    result.Raise("Failed to schedule the reboot")
3240
    return result.payload
3241

    
3242

    
3243
class LUQueryClusterInfo(NoHooksLU):
3244
  """Query cluster configuration.
3245

3246
  """
3247
  _OP_REQP = []
3248
  REQ_BGL = False
3249

    
3250
  def ExpandNames(self):
3251
    self.needed_locks = {}
3252

    
3253
  def CheckPrereq(self):
3254
    """No prerequsites needed for this LU.
3255

3256
    """
3257
    pass
3258

    
3259
  def Exec(self, feedback_fn):
3260
    """Return cluster config.
3261

3262
    """
3263
    cluster = self.cfg.GetClusterInfo()
3264
    result = {
3265
      "software_version": constants.RELEASE_VERSION,
3266
      "protocol_version": constants.PROTOCOL_VERSION,
3267
      "config_version": constants.CONFIG_VERSION,
3268
      "os_api_version": max(constants.OS_API_VERSIONS),
3269
      "export_version": constants.EXPORT_VERSION,
3270
      "architecture": (platform.architecture()[0], platform.machine()),
3271
      "name": cluster.cluster_name,
3272
      "master": cluster.master_node,
3273
      "default_hypervisor": cluster.enabled_hypervisors[0],
3274
      "enabled_hypervisors": cluster.enabled_hypervisors,
3275
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3276
                        for hypervisor_name in cluster.enabled_hypervisors]),
3277
      "beparams": cluster.beparams,
3278
      "nicparams": cluster.nicparams,
3279
      "candidate_pool_size": cluster.candidate_pool_size,
3280
      "master_netdev": cluster.master_netdev,
3281
      "volume_group_name": cluster.volume_group_name,
3282
      "file_storage_dir": cluster.file_storage_dir,
3283
      "ctime": cluster.ctime,
3284
      "mtime": cluster.mtime,
3285
      "uuid": cluster.uuid,
3286
      "tags": list(cluster.GetTags()),
3287
      }
3288

    
3289
    return result
3290

    
3291

    
3292
class LUQueryConfigValues(NoHooksLU):
3293
  """Return configuration values.
3294

3295
  """
3296
  _OP_REQP = []
3297
  REQ_BGL = False
3298
  _FIELDS_DYNAMIC = utils.FieldSet()
3299
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3300
                                  "watcher_pause")
3301

    
3302
  def ExpandNames(self):
3303
    self.needed_locks = {}
3304

    
3305
    _CheckOutputFields(static=self._FIELDS_STATIC,
3306
                       dynamic=self._FIELDS_DYNAMIC,
3307
                       selected=self.op.output_fields)
3308

    
3309
  def CheckPrereq(self):
3310
    """No prerequisites.
3311

3312
    """
3313
    pass
3314

    
3315
  def Exec(self, feedback_fn):
3316
    """Dump a representation of the cluster config to the standard output.
3317

3318
    """
3319
    values = []
3320
    for field in self.op.output_fields:
3321
      if field == "cluster_name":
3322
        entry = self.cfg.GetClusterName()
3323
      elif field == "master_node":
3324
        entry = self.cfg.GetMasterNode()
3325
      elif field == "drain_flag":
3326
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3327
      elif field == "watcher_pause":
3328
        return utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3329
      else:
3330
        raise errors.ParameterError(field)
3331
      values.append(entry)
3332
    return values
3333

    
3334

    
3335
class LUActivateInstanceDisks(NoHooksLU):
3336
  """Bring up an instance's disks.
3337

3338
  """
3339
  _OP_REQP = ["instance_name"]
3340
  REQ_BGL = False
3341

    
3342
  def ExpandNames(self):
3343
    self._ExpandAndLockInstance()
3344
    self.needed_locks[locking.LEVEL_NODE] = []
3345
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3346

    
3347
  def DeclareLocks(self, level):
3348
    if level == locking.LEVEL_NODE:
3349
      self._LockInstancesNodes()
3350

    
3351
  def CheckPrereq(self):
3352
    """Check prerequisites.
3353

3354
    This checks that the instance is in the cluster.
3355

3356
    """
3357
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3358
    assert self.instance is not None, \
3359
      "Cannot retrieve locked instance %s" % self.op.instance_name
3360
    _CheckNodeOnline(self, self.instance.primary_node)
3361
    if not hasattr(self.op, "ignore_size"):
3362
      self.op.ignore_size = False
3363

    
3364
  def Exec(self, feedback_fn):
3365
    """Activate the disks.
3366

3367
    """
3368
    disks_ok, disks_info = \
3369
              _AssembleInstanceDisks(self, self.instance,
3370
                                     ignore_size=self.op.ignore_size)
3371
    if not disks_ok:
3372
      raise errors.OpExecError("Cannot activate block devices")
3373

    
3374
    return disks_info
3375

    
3376

    
3377
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3378
                           ignore_size=False):
3379
  """Prepare the block devices for an instance.
3380

3381
  This sets up the block devices on all nodes.
3382

3383
  @type lu: L{LogicalUnit}
3384
  @param lu: the logical unit on whose behalf we execute
3385
  @type instance: L{objects.Instance}
3386
  @param instance: the instance for whose disks we assemble
3387
  @type ignore_secondaries: boolean
3388
  @param ignore_secondaries: if true, errors on secondary nodes
3389
      won't result in an error return from the function
3390
  @type ignore_size: boolean
3391
  @param ignore_size: if true, the current known size of the disk
3392
      will not be used during the disk activation, useful for cases
3393
      when the size is wrong
3394
  @return: False if the operation failed, otherwise a list of
3395
      (host, instance_visible_name, node_visible_name)
3396
      with the mapping from node devices to instance devices
3397

3398
  """
3399
  device_info = []
3400
  disks_ok = True
3401
  iname = instance.name
3402
  # With the two passes mechanism we try to reduce the window of
3403
  # opportunity for the race condition of switching DRBD to primary
3404
  # before handshaking occured, but we do not eliminate it
3405

    
3406
  # The proper fix would be to wait (with some limits) until the
3407
  # connection has been made and drbd transitions from WFConnection
3408
  # into any other network-connected state (Connected, SyncTarget,
3409
  # SyncSource, etc.)
3410

    
3411
  # 1st pass, assemble on all nodes in secondary mode
3412
  for inst_disk in instance.disks:
3413
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3414
      if ignore_size:
3415
        node_disk = node_disk.Copy()
3416
        node_disk.UnsetSize()
3417
      lu.cfg.SetDiskID(node_disk, node)
3418
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3419
      msg = result.fail_msg
3420
      if msg:
3421
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3422
                           " (is_primary=False, pass=1): %s",
3423
                           inst_disk.iv_name, node, msg)
3424
        if not ignore_secondaries:
3425
          disks_ok = False
3426

    
3427
  # FIXME: race condition on drbd migration to primary
3428

    
3429
  # 2nd pass, do only the primary node
3430
  for inst_disk in instance.disks:
3431
    dev_path = None
3432

    
3433
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3434
      if node != instance.primary_node:
3435
        continue
3436
      if ignore_size:
3437
        node_disk = node_disk.Copy()
3438
        node_disk.UnsetSize()
3439
      lu.cfg.SetDiskID(node_disk, node)
3440
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3441
      msg = result.fail_msg
3442
      if msg:
3443
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3444
                           " (is_primary=True, pass=2): %s",
3445
                           inst_disk.iv_name, node, msg)
3446
        disks_ok = False
3447
      else:
3448
        dev_path = result.payload
3449

    
3450
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3451

    
3452
  # leave the disks configured for the primary node
3453
  # this is a workaround that would be fixed better by
3454
  # improving the logical/physical id handling
3455
  for disk in instance.disks:
3456
    lu.cfg.SetDiskID(disk, instance.primary_node)
3457

    
3458
  return disks_ok, device_info
3459

    
3460

    
3461
def _StartInstanceDisks(lu, instance, force):
3462
  """Start the disks of an instance.
3463

3464
  """
3465
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3466
                                           ignore_secondaries=force)
3467
  if not disks_ok:
3468
    _ShutdownInstanceDisks(lu, instance)
3469
    if force is not None and not force:
3470
      lu.proc.LogWarning("", hint="If the message above refers to a"
3471
                         " secondary node,"
3472
                         " you can retry the operation using '--force'.")
3473
    raise errors.OpExecError("Disk consistency error")
3474

    
3475

    
3476
class LUDeactivateInstanceDisks(NoHooksLU):
3477
  """Shutdown an instance's disks.
3478

3479
  """
3480
  _OP_REQP = ["instance_name"]
3481
  REQ_BGL = False
3482

    
3483
  def ExpandNames(self):
3484
    self._ExpandAndLockInstance()
3485
    self.needed_locks[locking.LEVEL_NODE] = []
3486
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3487

    
3488
  def DeclareLocks(self, level):
3489
    if level == locking.LEVEL_NODE:
3490
      self._LockInstancesNodes()
3491

    
3492
  def CheckPrereq(self):
3493
    """Check prerequisites.
3494

3495
    This checks that the instance is in the cluster.
3496

3497
    """
3498
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3499
    assert self.instance is not None, \
3500
      "Cannot retrieve locked instance %s" % self.op.instance_name
3501

    
3502
  def Exec(self, feedback_fn):
3503
    """Deactivate the disks
3504

3505
    """
3506
    instance = self.instance
3507
    _SafeShutdownInstanceDisks(self, instance)
3508

    
3509

    
3510
def _SafeShutdownInstanceDisks(lu, instance):
3511
  """Shutdown block devices of an instance.
3512

3513
  This function checks if an instance is running, before calling
3514
  _ShutdownInstanceDisks.
3515

3516
  """
3517
  pnode = instance.primary_node
3518
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
3519
  ins_l.Raise("Can't contact node %s" % pnode)
3520

    
3521
  if instance.name in ins_l.payload:
3522
    raise errors.OpExecError("Instance is running, can't shutdown"
3523
                             " block devices.")
3524

    
3525
  _ShutdownInstanceDisks(lu, instance)
3526

    
3527

    
3528
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3529
  """Shutdown block devices of an instance.
3530

3531
  This does the shutdown on all nodes of the instance.
3532

3533
  If the ignore_primary is false, errors on the primary node are
3534
  ignored.
3535

3536
  """
3537
  all_result = True
3538
  for disk in instance.disks:
3539
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3540
      lu.cfg.SetDiskID(top_disk, node)
3541
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3542
      msg = result.fail_msg
3543
      if msg:
3544
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3545
                      disk.iv_name, node, msg)
3546
        if not ignore_primary or node != instance.primary_node:
3547
          all_result = False
3548
  return all_result
3549

    
3550

    
3551
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3552
  """Checks if a node has enough free memory.
3553

3554
  This function check if a given node has the needed amount of free
3555
  memory. In case the node has less memory or we cannot get the
3556
  information from the node, this function raise an OpPrereqError
3557
  exception.
3558

3559
  @type lu: C{LogicalUnit}
3560
  @param lu: a logical unit from which we get configuration data
3561
  @type node: C{str}
3562
  @param node: the node to check
3563
  @type reason: C{str}
3564
  @param reason: string to use in the error message
3565
  @type requested: C{int}
3566
  @param requested: the amount of memory in MiB to check for
3567
  @type hypervisor_name: C{str}
3568
  @param hypervisor_name: the hypervisor to ask for memory stats
3569
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3570
      we cannot check the node
3571

3572
  """
3573
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3574
  nodeinfo[node].Raise("Can't get data from node %s" % node,
3575
                       prereq=True, ecode=errors.ECODE_ENVIRON)
3576
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3577
  if not isinstance(free_mem, int):
3578
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3579
                               " was '%s'" % (node, free_mem),
3580
                               errors.ECODE_ENVIRON)
3581
  if requested > free_mem:
3582
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3583
                               " needed %s MiB, available %s MiB" %
3584
                               (node, reason, requested, free_mem),
3585
                               errors.ECODE_NORES)
3586

    
3587

    
3588
class LUStartupInstance(LogicalUnit):
3589
  """Starts an instance.
3590

3591
  """
3592
  HPATH = "instance-start"
3593
  HTYPE = constants.HTYPE_INSTANCE
3594
  _OP_REQP = ["instance_name", "force"]
3595
  REQ_BGL = False
3596

    
3597
  def ExpandNames(self):
3598
    self._ExpandAndLockInstance()
3599

    
3600
  def BuildHooksEnv(self):
3601
    """Build hooks env.
3602

3603
    This runs on master, primary and secondary nodes of the instance.
3604

3605
    """
3606
    env = {
3607
      "FORCE": self.op.force,
3608
      }
3609
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3610
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3611
    return env, nl, nl
3612

    
3613
  def CheckPrereq(self):
3614
    """Check prerequisites.
3615

3616
    This checks that the instance is in the cluster.
3617

3618
    """
3619
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3620
    assert self.instance is not None, \
3621
      "Cannot retrieve locked instance %s" % self.op.instance_name
3622

    
3623
    # extra beparams
3624
    self.beparams = getattr(self.op, "beparams", {})
3625
    if self.beparams:
3626
      if not isinstance(self.beparams, dict):
3627
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3628
                                   " dict" % (type(self.beparams), ),
3629
                                   errors.ECODE_INVAL)
3630
      # fill the beparams dict
3631
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3632
      self.op.beparams = self.beparams
3633

    
3634
    # extra hvparams
3635
    self.hvparams = getattr(self.op, "hvparams", {})
3636
    if self.hvparams:
3637
      if not isinstance(self.hvparams, dict):
3638
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3639
                                   " dict" % (type(self.hvparams), ),
3640
                                   errors.ECODE_INVAL)
3641

    
3642
      # check hypervisor parameter syntax (locally)
3643
      cluster = self.cfg.GetClusterInfo()
3644
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3645
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
3646
                                    instance.hvparams)
3647
      filled_hvp.update(self.hvparams)
3648
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3649
      hv_type.CheckParameterSyntax(filled_hvp)
3650
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3651
      self.op.hvparams = self.hvparams
3652

    
3653
    _CheckNodeOnline(self, instance.primary_node)
3654

    
3655
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3656
    # check bridges existence
3657
    _CheckInstanceBridgesExist(self, instance)
3658

    
3659
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3660
                                              instance.name,
3661
                                              instance.hypervisor)
3662
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3663
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3664
    if not remote_info.payload: # not running already
3665
      _CheckNodeFreeMemory(self, instance.primary_node,
3666
                           "starting instance %s" % instance.name,
3667
                           bep[constants.BE_MEMORY], instance.hypervisor)
3668

    
3669
  def Exec(self, feedback_fn):
3670
    """Start the instance.
3671

3672
    """
3673
    instance = self.instance
3674
    force = self.op.force
3675

    
3676
    self.cfg.MarkInstanceUp(instance.name)
3677

    
3678
    node_current = instance.primary_node
3679

    
3680
    _StartInstanceDisks(self, instance, force)
3681

    
3682
    result = self.rpc.call_instance_start(node_current, instance,
3683
                                          self.hvparams, self.beparams)
3684
    msg = result.fail_msg
3685
    if msg:
3686
      _ShutdownInstanceDisks(self, instance)
3687
      raise errors.OpExecError("Could not start instance: %s" % msg)
3688

    
3689

    
3690
class LURebootInstance(LogicalUnit):
3691
  """Reboot an instance.
3692

3693
  """
3694
  HPATH = "instance-reboot"
3695
  HTYPE = constants.HTYPE_INSTANCE
3696
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3697
  REQ_BGL = False
3698

    
3699
  def CheckArguments(self):
3700
    """Check the arguments.
3701

3702
    """
3703
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
3704
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
3705

    
3706
  def ExpandNames(self):
3707
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3708
                                   constants.INSTANCE_REBOOT_HARD,
3709
                                   constants.INSTANCE_REBOOT_FULL]:
3710
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3711
                                  (constants.INSTANCE_REBOOT_SOFT,
3712
                                   constants.INSTANCE_REBOOT_HARD,
3713
                                   constants.INSTANCE_REBOOT_FULL))
3714
    self._ExpandAndLockInstance()
3715

    
3716
  def BuildHooksEnv(self):
3717
    """Build hooks env.
3718

3719
    This runs on master, primary and secondary nodes of the instance.
3720

3721
    """
3722
    env = {
3723
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3724
      "REBOOT_TYPE": self.op.reboot_type,
3725
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
3726
      }
3727
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3728
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3729
    return env, nl, nl
3730

    
3731
  def CheckPrereq(self):
3732
    """Check prerequisites.
3733

3734
    This checks that the instance is in the cluster.
3735

3736
    """
3737
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3738
    assert self.instance is not None, \
3739
      "Cannot retrieve locked instance %s" % self.op.instance_name
3740

    
3741
    _CheckNodeOnline(self, instance.primary_node)
3742

    
3743
    # check bridges existence
3744
    _CheckInstanceBridgesExist(self, instance)
3745

    
3746
  def Exec(self, feedback_fn):
3747
    """Reboot the instance.
3748

3749
    """
3750
    instance = self.instance
3751
    ignore_secondaries = self.op.ignore_secondaries
3752
    reboot_type = self.op.reboot_type
3753

    
3754
    node_current = instance.primary_node
3755

    
3756
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3757
                       constants.INSTANCE_REBOOT_HARD]:
3758
      for disk in instance.disks:
3759
        self.cfg.SetDiskID(disk, node_current)
3760
      result = self.rpc.call_instance_reboot(node_current, instance,
3761
                                             reboot_type,
3762
                                             self.shutdown_timeout)
3763
      result.Raise("Could not reboot instance")
3764
    else:
3765
      result = self.rpc.call_instance_shutdown(node_current, instance,
3766
                                               self.shutdown_timeout)
3767
      result.Raise("Could not shutdown instance for full reboot")
3768
      _ShutdownInstanceDisks(self, instance)
3769
      _StartInstanceDisks(self, instance, ignore_secondaries)
3770
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3771
      msg = result.fail_msg
3772
      if msg:
3773
        _ShutdownInstanceDisks(self, instance)
3774
        raise errors.OpExecError("Could not start instance for"
3775
                                 " full reboot: %s" % msg)
3776

    
3777
    self.cfg.MarkInstanceUp(instance.name)
3778

    
3779

    
3780
class LUShutdownInstance(LogicalUnit):
3781
  """Shutdown an instance.
3782

3783
  """
3784
  HPATH = "instance-stop"
3785
  HTYPE = constants.HTYPE_INSTANCE
3786
  _OP_REQP = ["instance_name"]
3787
  REQ_BGL = False
3788

    
3789
  def CheckArguments(self):
3790
    """Check the arguments.
3791

3792
    """
3793
    self.timeout = getattr(self.op, "timeout",
3794
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
3795

    
3796
  def ExpandNames(self):
3797
    self._ExpandAndLockInstance()
3798

    
3799
  def BuildHooksEnv(self):
3800
    """Build hooks env.
3801

3802
    This runs on master, primary and secondary nodes of the instance.
3803

3804
    """
3805
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3806
    env["TIMEOUT"] = self.timeout
3807
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3808
    return env, nl, nl
3809

    
3810
  def CheckPrereq(self):
3811
    """Check prerequisites.
3812

3813
    This checks that the instance is in the cluster.
3814

3815
    """
3816
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3817
    assert self.instance is not None, \
3818
      "Cannot retrieve locked instance %s" % self.op.instance_name
3819
    _CheckNodeOnline(self, self.instance.primary_node)
3820

    
3821
  def Exec(self, feedback_fn):
3822
    """Shutdown the instance.
3823

3824
    """
3825
    instance = self.instance
3826
    node_current = instance.primary_node
3827
    timeout = self.timeout
3828
    self.cfg.MarkInstanceDown(instance.name)
3829
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
3830
    msg = result.fail_msg
3831
    if msg:
3832
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
3833

    
3834
    _ShutdownInstanceDisks(self, instance)
3835

    
3836

    
3837
class LUReinstallInstance(LogicalUnit):
3838
  """Reinstall an instance.
3839

3840
  """
3841
  HPATH = "instance-reinstall"
3842
  HTYPE = constants.HTYPE_INSTANCE
3843
  _OP_REQP = ["instance_name"]
3844
  REQ_BGL = False
3845

    
3846
  def ExpandNames(self):
3847
    self._ExpandAndLockInstance()
3848

    
3849
  def BuildHooksEnv(self):
3850
    """Build hooks env.
3851

3852
    This runs on master, primary and secondary nodes of the instance.
3853

3854
    """
3855
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3856
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3857
    return env, nl, nl
3858

    
3859
  def CheckPrereq(self):
3860
    """Check prerequisites.
3861

3862
    This checks that the instance is in the cluster and is not running.
3863

3864
    """
3865
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3866
    assert instance is not None, \
3867
      "Cannot retrieve locked instance %s" % self.op.instance_name
3868
    _CheckNodeOnline(self, instance.primary_node)
3869

    
3870
    if instance.disk_template == constants.DT_DISKLESS:
3871
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3872
                                 self.op.instance_name,
3873
                                 errors.ECODE_INVAL)
3874
    if instance.admin_up:
3875
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3876
                                 self.op.instance_name,
3877
                                 errors.ECODE_STATE)
3878
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3879
                                              instance.name,
3880
                                              instance.hypervisor)
3881
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3882
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3883
    if remote_info.payload:
3884
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3885
                                 (self.op.instance_name,
3886
                                  instance.primary_node),
3887
                                 errors.ECODE_STATE)
3888

    
3889
    self.op.os_type = getattr(self.op, "os_type", None)
3890
    self.op.force_variant = getattr(self.op, "force_variant", False)
3891
    if self.op.os_type is not None:
3892
      # OS verification
3893
      pnode = self.cfg.GetNodeInfo(
3894
        self.cfg.ExpandNodeName(instance.primary_node))
3895
      if pnode is None:
3896
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
3897
                                   self.op.pnode, errors.ECODE_NOENT)
3898
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
3899
      result.Raise("OS '%s' not in supported OS list for primary node %s" %
3900
                   (self.op.os_type, pnode.name),
3901
                   prereq=True, ecode=errors.ECODE_INVAL)
3902
      if not self.op.force_variant:
3903
        _CheckOSVariant(result.payload, self.op.os_type)
3904

    
3905
    self.instance = instance
3906

    
3907
  def Exec(self, feedback_fn):
3908
    """Reinstall the instance.
3909

3910
    """
3911
    inst = self.instance
3912

    
3913
    if self.op.os_type is not None:
3914
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
3915
      inst.os = self.op.os_type
3916
      self.cfg.Update(inst, feedback_fn)
3917

    
3918
    _StartInstanceDisks(self, inst, None)
3919
    try:
3920
      feedback_fn("Running the instance OS create scripts...")
3921
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True)
3922
      result.Raise("Could not install OS for instance %s on node %s" %
3923
                   (inst.name, inst.primary_node))
3924
    finally:
3925
      _ShutdownInstanceDisks(self, inst)
3926

    
3927

    
3928
class LURecreateInstanceDisks(LogicalUnit):
3929
  """Recreate an instance's missing disks.
3930

3931
  """
3932
  HPATH = "instance-recreate-disks"
3933
  HTYPE = constants.HTYPE_INSTANCE
3934
  _OP_REQP = ["instance_name", "disks"]
3935
  REQ_BGL = False
3936

    
3937
  def CheckArguments(self):
3938
    """Check the arguments.
3939

3940
    """
3941
    if not isinstance(self.op.disks, list):
3942
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
3943
    for item in self.op.disks:
3944
      if (not isinstance(item, int) or
3945
          item < 0):
3946
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
3947
                                   str(item), errors.ECODE_INVAL)
3948

    
3949
  def ExpandNames(self):
3950
    self._ExpandAndLockInstance()
3951

    
3952
  def BuildHooksEnv(self):
3953
    """Build hooks env.
3954

3955
    This runs on master, primary and secondary nodes of the instance.
3956

3957
    """
3958
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3959
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3960
    return env, nl, nl
3961

    
3962
  def CheckPrereq(self):
3963
    """Check prerequisites.
3964

3965
    This checks that the instance is in the cluster and is not running.
3966

3967
    """
3968
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3969
    assert instance is not None, \
3970
      "Cannot retrieve locked instance %s" % self.op.instance_name
3971
    _CheckNodeOnline(self, instance.primary_node)
3972

    
3973
    if instance.disk_template == constants.DT_DISKLESS:
3974
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3975
                                 self.op.instance_name, errors.ECODE_INVAL)
3976
    if instance.admin_up:
3977
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3978
                                 self.op.instance_name, errors.ECODE_STATE)
3979
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3980
                                              instance.name,
3981
                                              instance.hypervisor)
3982
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3983
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3984
    if remote_info.payload:
3985
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3986
                                 (self.op.instance_name,
3987
                                  instance.primary_node), errors.ECODE_STATE)
3988

    
3989
    if not self.op.disks:
3990
      self.op.disks = range(len(instance.disks))
3991
    else:
3992
      for idx in self.op.disks:
3993
        if idx >= len(instance.disks):
3994
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
3995
                                     errors.ECODE_INVAL)
3996

    
3997
    self.instance = instance
3998

    
3999
  def Exec(self, feedback_fn):
4000
    """Recreate the disks.
4001

4002
    """
4003
    to_skip = []
4004
    for idx, disk in enumerate(self.instance.disks):
4005
      if idx not in self.op.disks: # disk idx has not been passed in
4006
        to_skip.append(idx)
4007
        continue
4008

    
4009
    _CreateDisks(self, self.instance, to_skip=to_skip)
4010

    
4011

    
4012
class LURenameInstance(LogicalUnit):
4013
  """Rename an instance.
4014

4015
  """
4016
  HPATH = "instance-rename"
4017
  HTYPE = constants.HTYPE_INSTANCE
4018
  _OP_REQP = ["instance_name", "new_name"]
4019

    
4020
  def BuildHooksEnv(self):
4021
    """Build hooks env.
4022

4023
    This runs on master, primary and secondary nodes of the instance.
4024

4025
    """
4026
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4027
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4028
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4029
    return env, nl, nl
4030

    
4031
  def CheckPrereq(self):
4032
    """Check prerequisites.
4033

4034
    This checks that the instance is in the cluster and is not running.
4035

4036
    """
4037
    instance = self.cfg.GetInstanceInfo(
4038
      self.cfg.ExpandInstanceName(self.op.instance_name))
4039
    if instance is None:
4040
      raise errors.OpPrereqError("Instance '%s' not known" %
4041
                                 self.op.instance_name, errors.ECODE_NOENT)
4042
    _CheckNodeOnline(self, instance.primary_node)
4043

    
4044
    if instance.admin_up:
4045
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
4046
                                 self.op.instance_name, errors.ECODE_STATE)
4047
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4048
                                              instance.name,
4049
                                              instance.hypervisor)
4050
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4051
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4052
    if remote_info.payload:
4053
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
4054
                                 (self.op.instance_name,
4055
                                  instance.primary_node), errors.ECODE_STATE)
4056
    self.instance = instance
4057

    
4058
    # new name verification
4059
    name_info = utils.GetHostInfo(self.op.new_name)
4060

    
4061
    self.op.new_name = new_name = name_info.name
4062
    instance_list = self.cfg.GetInstanceList()
4063
    if new_name in instance_list:
4064
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4065
                                 new_name, errors.ECODE_EXISTS)
4066

    
4067
    if not getattr(self.op, "ignore_ip", False):
4068
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4069
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4070
                                   (name_info.ip, new_name),
4071
                                   errors.ECODE_NOTUNIQUE)
4072

    
4073

    
4074
  def Exec(self, feedback_fn):
4075
    """Reinstall the instance.
4076

4077
    """
4078
    inst = self.instance
4079
    old_name = inst.name
4080

    
4081
    if inst.disk_template == constants.DT_FILE:
4082
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4083

    
4084
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4085
    # Change the instance lock. This is definitely safe while we hold the BGL
4086
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4087
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4088

    
4089
    # re-read the instance from the configuration after rename
4090
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4091

    
4092
    if inst.disk_template == constants.DT_FILE:
4093
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4094
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4095
                                                     old_file_storage_dir,
4096
                                                     new_file_storage_dir)
4097
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4098
                   " (but the instance has been renamed in Ganeti)" %
4099
                   (inst.primary_node, old_file_storage_dir,
4100
                    new_file_storage_dir))
4101

    
4102
    _StartInstanceDisks(self, inst, None)
4103
    try:
4104
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4105
                                                 old_name)
4106
      msg = result.fail_msg
4107
      if msg:
4108
        msg = ("Could not run OS rename script for instance %s on node %s"
4109
               " (but the instance has been renamed in Ganeti): %s" %
4110
               (inst.name, inst.primary_node, msg))
4111
        self.proc.LogWarning(msg)
4112
    finally:
4113
      _ShutdownInstanceDisks(self, inst)
4114

    
4115

    
4116
class LURemoveInstance(LogicalUnit):
4117
  """Remove an instance.
4118

4119
  """
4120
  HPATH = "instance-remove"
4121
  HTYPE = constants.HTYPE_INSTANCE
4122
  _OP_REQP = ["instance_name", "ignore_failures"]
4123
  REQ_BGL = False
4124

    
4125
  def CheckArguments(self):
4126
    """Check the arguments.
4127

4128
    """
4129
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4130
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4131

    
4132
  def ExpandNames(self):
4133
    self._ExpandAndLockInstance()
4134
    self.needed_locks[locking.LEVEL_NODE] = []
4135
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4136

    
4137
  def DeclareLocks(self, level):
4138
    if level == locking.LEVEL_NODE:
4139
      self._LockInstancesNodes()
4140

    
4141
  def BuildHooksEnv(self):
4142
    """Build hooks env.
4143

4144
    This runs on master, primary and secondary nodes of the instance.
4145

4146
    """
4147
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4148
    env["SHUTDOWN_TIMEOUT"] = self.shutdown_timeout
4149
    nl = [self.cfg.GetMasterNode()]
4150
    return env, nl, nl
4151

    
4152
  def CheckPrereq(self):
4153
    """Check prerequisites.
4154

4155
    This checks that the instance is in the cluster.
4156

4157
    """
4158
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4159
    assert self.instance is not None, \
4160
      "Cannot retrieve locked instance %s" % self.op.instance_name
4161

    
4162
  def Exec(self, feedback_fn):
4163
    """Remove the instance.
4164

4165
    """
4166
    instance = self.instance
4167
    logging.info("Shutting down instance %s on node %s",
4168
                 instance.name, instance.primary_node)
4169

    
4170
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4171
                                             self.shutdown_timeout)
4172
    msg = result.fail_msg
4173
    if msg:
4174
      if self.op.ignore_failures:
4175
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4176
      else:
4177
        raise errors.OpExecError("Could not shutdown instance %s on"
4178
                                 " node %s: %s" %
4179
                                 (instance.name, instance.primary_node, msg))
4180

    
4181
    logging.info("Removing block devices for instance %s", instance.name)
4182

    
4183
    if not _RemoveDisks(self, instance):
4184
      if self.op.ignore_failures:
4185
        feedback_fn("Warning: can't remove instance's disks")
4186
      else:
4187
        raise errors.OpExecError("Can't remove instance's disks")
4188

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

    
4191
    self.cfg.RemoveInstance(instance.name)
4192
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4193

    
4194

    
4195
class LUQueryInstances(NoHooksLU):
4196
  """Logical unit for querying instances.
4197

4198
  """
4199
  _OP_REQP = ["output_fields", "names", "use_locking"]
4200
  REQ_BGL = False
4201
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4202
                    "serial_no", "ctime", "mtime", "uuid"]
4203
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4204
                                    "admin_state",
4205
                                    "disk_template", "ip", "mac", "bridge",
4206
                                    "nic_mode", "nic_link",
4207
                                    "sda_size", "sdb_size", "vcpus", "tags",
4208
                                    "network_port", "beparams",
4209
                                    r"(disk)\.(size)/([0-9]+)",
4210
                                    r"(disk)\.(sizes)", "disk_usage",
4211
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4212
                                    r"(nic)\.(bridge)/([0-9]+)",
4213
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4214
                                    r"(disk|nic)\.(count)",
4215
                                    "hvparams",
4216
                                    ] + _SIMPLE_FIELDS +
4217
                                  ["hv/%s" % name
4218
                                   for name in constants.HVS_PARAMETERS
4219
                                   if name not in constants.HVC_GLOBALS] +
4220
                                  ["be/%s" % name
4221
                                   for name in constants.BES_PARAMETERS])
4222
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4223

    
4224

    
4225
  def ExpandNames(self):
4226
    _CheckOutputFields(static=self._FIELDS_STATIC,
4227
                       dynamic=self._FIELDS_DYNAMIC,
4228
                       selected=self.op.output_fields)
4229

    
4230
    self.needed_locks = {}
4231
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4232
    self.share_locks[locking.LEVEL_NODE] = 1
4233

    
4234
    if self.op.names:
4235
      self.wanted = _GetWantedInstances(self, self.op.names)
4236
    else:
4237
      self.wanted = locking.ALL_SET
4238

    
4239
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4240
    self.do_locking = self.do_node_query and self.op.use_locking
4241
    if self.do_locking:
4242
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4243
      self.needed_locks[locking.LEVEL_NODE] = []
4244
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4245

    
4246
  def DeclareLocks(self, level):
4247
    if level == locking.LEVEL_NODE and self.do_locking:
4248
      self._LockInstancesNodes()
4249

    
4250
  def CheckPrereq(self):
4251
    """Check prerequisites.
4252

4253
    """
4254
    pass
4255

    
4256
  def Exec(self, feedback_fn):
4257
    """Computes the list of nodes and their attributes.
4258

4259
    """
4260
    all_info = self.cfg.GetAllInstancesInfo()
4261
    if self.wanted == locking.ALL_SET:
4262
      # caller didn't specify instance names, so ordering is not important
4263
      if self.do_locking:
4264
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4265
      else:
4266
        instance_names = all_info.keys()
4267
      instance_names = utils.NiceSort(instance_names)
4268
    else:
4269
      # caller did specify names, so we must keep the ordering
4270
      if self.do_locking:
4271
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4272
      else:
4273
        tgt_set = all_info.keys()
4274
      missing = set(self.wanted).difference(tgt_set)
4275
      if missing:
4276
        raise errors.OpExecError("Some instances were removed before"
4277
                                 " retrieving their data: %s" % missing)
4278
      instance_names = self.wanted
4279

    
4280
    instance_list = [all_info[iname] for iname in instance_names]
4281

    
4282
    # begin data gathering
4283

    
4284
    nodes = frozenset([inst.primary_node for inst in instance_list])
4285
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4286

    
4287
    bad_nodes = []
4288
    off_nodes = []
4289
    if self.do_node_query:
4290
      live_data = {}
4291
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4292
      for name in nodes:
4293
        result = node_data[name]
4294
        if result.offline:
4295
          # offline nodes will be in both lists
4296
          off_nodes.append(name)
4297
        if result.fail_msg:
4298
          bad_nodes.append(name)
4299
        else:
4300
          if result.payload:
4301
            live_data.update(result.payload)
4302
          # else no instance is alive
4303
    else:
4304
      live_data = dict([(name, {}) for name in instance_names])
4305

    
4306
    # end data gathering
4307

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

    
4472
    return output
4473

    
4474

    
4475
class LUFailoverInstance(LogicalUnit):
4476
  """Failover an instance.
4477

4478
  """
4479
  HPATH = "instance-failover"
4480
  HTYPE = constants.HTYPE_INSTANCE
4481
  _OP_REQP = ["instance_name", "ignore_consistency"]
4482
  REQ_BGL = False
4483

    
4484
  def CheckArguments(self):
4485
    """Check the arguments.
4486

4487
    """
4488
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4489
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4490

    
4491
  def ExpandNames(self):
4492
    self._ExpandAndLockInstance()
4493
    self.needed_locks[locking.LEVEL_NODE] = []
4494
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4495

    
4496
  def DeclareLocks(self, level):
4497
    if level == locking.LEVEL_NODE:
4498
      self._LockInstancesNodes()
4499

    
4500
  def BuildHooksEnv(self):
4501
    """Build hooks env.
4502

4503
    This runs on master, primary and secondary nodes of the instance.
4504

4505
    """
4506
    env = {
4507
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4508
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4509
      }
4510
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4511
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
4512
    return env, nl, nl
4513

    
4514
  def CheckPrereq(self):
4515
    """Check prerequisites.
4516

4517
    This checks that the instance is in the cluster.
4518

4519
    """
4520
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4521
    assert self.instance is not None, \
4522
      "Cannot retrieve locked instance %s" % self.op.instance_name
4523

    
4524
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4525
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4526
      raise errors.OpPrereqError("Instance's disk layout is not"
4527
                                 " network mirrored, cannot failover.",
4528
                                 errors.ECODE_STATE)
4529

    
4530
    secondary_nodes = instance.secondary_nodes
4531
    if not secondary_nodes:
4532
      raise errors.ProgrammerError("no secondary node but using "
4533
                                   "a mirrored disk template")
4534

    
4535
    target_node = secondary_nodes[0]
4536
    _CheckNodeOnline(self, target_node)
4537
    _CheckNodeNotDrained(self, target_node)
4538
    if instance.admin_up:
4539
      # check memory requirements on the secondary node
4540
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4541
                           instance.name, bep[constants.BE_MEMORY],
4542
                           instance.hypervisor)
4543
    else:
4544
      self.LogInfo("Not checking memory on the secondary node as"
4545
                   " instance will not be started")
4546

    
4547
    # check bridge existance
4548
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4549

    
4550
  def Exec(self, feedback_fn):
4551
    """Failover an instance.
4552

4553
    The failover is done by shutting it down on its present node and
4554
    starting it on the secondary.
4555

4556
    """
4557
    instance = self.instance
4558

    
4559
    source_node = instance.primary_node
4560
    target_node = instance.secondary_nodes[0]
4561

    
4562
    if instance.admin_up:
4563
      feedback_fn("* checking disk consistency between source and target")
4564
      for dev in instance.disks:
4565
        # for drbd, these are drbd over lvm
4566
        if not _CheckDiskConsistency(self, dev, target_node, False):
4567
          if not self.op.ignore_consistency:
4568
            raise errors.OpExecError("Disk %s is degraded on target node,"
4569
                                     " aborting failover." % dev.iv_name)
4570
    else:
4571
      feedback_fn("* not checking disk consistency as instance is not running")
4572

    
4573
    feedback_fn("* shutting down instance on source node")
4574
    logging.info("Shutting down instance %s on node %s",
4575
                 instance.name, source_node)
4576

    
4577
    result = self.rpc.call_instance_shutdown(source_node, instance,
4578
                                             self.shutdown_timeout)
4579
    msg = result.fail_msg
4580
    if msg:
4581
      if self.op.ignore_consistency:
4582
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4583
                             " Proceeding anyway. Please make sure node"
4584
                             " %s is down. Error details: %s",
4585
                             instance.name, source_node, source_node, msg)
4586
      else:
4587
        raise errors.OpExecError("Could not shutdown instance %s on"
4588
                                 " node %s: %s" %
4589
                                 (instance.name, source_node, msg))
4590

    
4591
    feedback_fn("* deactivating the instance's disks on source node")
4592
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
4593
      raise errors.OpExecError("Can't shut down the instance's disks.")
4594

    
4595
    instance.primary_node = target_node
4596
    # distribute new instance config to the other nodes
4597
    self.cfg.Update(instance, feedback_fn)
4598

    
4599
    # Only start the instance if it's marked as up
4600
    if instance.admin_up:
4601
      feedback_fn("* activating the instance's disks on target node")
4602
      logging.info("Starting instance %s on node %s",
4603
                   instance.name, target_node)
4604

    
4605
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4606
                                               ignore_secondaries=True)
4607
      if not disks_ok:
4608
        _ShutdownInstanceDisks(self, instance)
4609
        raise errors.OpExecError("Can't activate the instance's disks")
4610

    
4611
      feedback_fn("* starting the instance on the target node")
4612
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4613
      msg = result.fail_msg
4614
      if msg:
4615
        _ShutdownInstanceDisks(self, instance)
4616
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4617
                                 (instance.name, target_node, msg))
4618

    
4619

    
4620
class LUMigrateInstance(LogicalUnit):
4621
  """Migrate an instance.
4622

4623
  This is migration without shutting down, compared to the failover,
4624
  which is done with shutdown.
4625

4626
  """
4627
  HPATH = "instance-migrate"
4628
  HTYPE = constants.HTYPE_INSTANCE
4629
  _OP_REQP = ["instance_name", "live", "cleanup"]
4630

    
4631
  REQ_BGL = False
4632

    
4633
  def ExpandNames(self):
4634
    self._ExpandAndLockInstance()
4635

    
4636
    self.needed_locks[locking.LEVEL_NODE] = []
4637
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4638

    
4639
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
4640
                                       self.op.live, self.op.cleanup)
4641
    self.tasklets = [self._migrater]
4642

    
4643
  def DeclareLocks(self, level):
4644
    if level == locking.LEVEL_NODE:
4645
      self._LockInstancesNodes()
4646

    
4647
  def BuildHooksEnv(self):
4648
    """Build hooks env.
4649

4650
    This runs on master, primary and secondary nodes of the instance.
4651

4652
    """
4653
    instance = self._migrater.instance
4654
    env = _BuildInstanceHookEnvByObject(self, instance)
4655
    env["MIGRATE_LIVE"] = self.op.live
4656
    env["MIGRATE_CLEANUP"] = self.op.cleanup
4657
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4658
    return env, nl, nl
4659

    
4660

    
4661
class LUMoveInstance(LogicalUnit):
4662
  """Move an instance by data-copying.
4663

4664
  """
4665
  HPATH = "instance-move"
4666
  HTYPE = constants.HTYPE_INSTANCE
4667
  _OP_REQP = ["instance_name", "target_node"]
4668
  REQ_BGL = False
4669

    
4670
  def CheckArguments(self):
4671
    """Check the arguments.
4672

4673
    """
4674
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4675
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4676

    
4677
  def ExpandNames(self):
4678
    self._ExpandAndLockInstance()
4679
    target_node = self.cfg.ExpandNodeName(self.op.target_node)
4680
    if target_node is None:
4681
      raise errors.OpPrereqError("Node '%s' not known" %
4682
                                  self.op.target_node, errors.ECODE_NOENT)
4683
    self.op.target_node = target_node
4684
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
4685
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4686

    
4687
  def DeclareLocks(self, level):
4688
    if level == locking.LEVEL_NODE:
4689
      self._LockInstancesNodes(primary_only=True)
4690

    
4691
  def BuildHooksEnv(self):
4692
    """Build hooks env.
4693

4694
    This runs on master, primary and secondary nodes of the instance.
4695

4696
    """
4697
    env = {
4698
      "TARGET_NODE": self.op.target_node,
4699
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4700
      }
4701
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4702
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
4703
                                       self.op.target_node]
4704
    return env, nl, nl
4705

    
4706
  def CheckPrereq(self):
4707
    """Check prerequisites.
4708

4709
    This checks that the instance is in the cluster.
4710

4711
    """
4712
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4713
    assert self.instance is not None, \
4714
      "Cannot retrieve locked instance %s" % self.op.instance_name
4715

    
4716
    node = self.cfg.GetNodeInfo(self.op.target_node)
4717
    assert node is not None, \
4718
      "Cannot retrieve locked node %s" % self.op.target_node
4719

    
4720
    self.target_node = target_node = node.name
4721

    
4722
    if target_node == instance.primary_node:
4723
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
4724
                                 (instance.name, target_node),
4725
                                 errors.ECODE_STATE)
4726

    
4727
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4728

    
4729
    for idx, dsk in enumerate(instance.disks):
4730
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
4731
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
4732
                                   " cannot copy", errors.ECODE_STATE)
4733

    
4734
    _CheckNodeOnline(self, target_node)
4735
    _CheckNodeNotDrained(self, target_node)
4736

    
4737
    if instance.admin_up:
4738
      # check memory requirements on the secondary node
4739
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4740
                           instance.name, bep[constants.BE_MEMORY],
4741
                           instance.hypervisor)
4742
    else:
4743
      self.LogInfo("Not checking memory on the secondary node as"
4744
                   " instance will not be started")
4745

    
4746
    # check bridge existance
4747
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4748

    
4749
  def Exec(self, feedback_fn):
4750
    """Move an instance.
4751

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

4755
    """
4756
    instance = self.instance
4757

    
4758
    source_node = instance.primary_node
4759
    target_node = self.target_node
4760

    
4761
    self.LogInfo("Shutting down instance %s on source node %s",
4762
                 instance.name, source_node)
4763

    
4764
    result = self.rpc.call_instance_shutdown(source_node, instance,
4765
                                             self.shutdown_timeout)
4766
    msg = result.fail_msg
4767
    if msg:
4768
      if self.op.ignore_consistency:
4769
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4770
                             " Proceeding anyway. Please make sure node"
4771
                             " %s is down. Error details: %s",
4772
                             instance.name, source_node, source_node, msg)
4773
      else:
4774
        raise errors.OpExecError("Could not shutdown instance %s on"
4775
                                 " node %s: %s" %
4776
                                 (instance.name, source_node, msg))
4777

    
4778
    # create the target disks
4779
    try:
4780
      _CreateDisks(self, instance, target_node=target_node)
4781
    except errors.OpExecError:
4782
      self.LogWarning("Device creation failed, reverting...")
4783
      try:
4784
        _RemoveDisks(self, instance, target_node=target_node)
4785
      finally:
4786
        self.cfg.ReleaseDRBDMinors(instance.name)
4787
        raise
4788

    
4789
    cluster_name = self.cfg.GetClusterInfo().cluster_name
4790

    
4791
    errs = []
4792
    # activate, get path, copy the data over
4793
    for idx, disk in enumerate(instance.disks):
4794
      self.LogInfo("Copying data for disk %d", idx)
4795
      result = self.rpc.call_blockdev_assemble(target_node, disk,
4796
                                               instance.name, True)
4797
      if result.fail_msg:
4798
        self.LogWarning("Can't assemble newly created disk %d: %s",
4799
                        idx, result.fail_msg)
4800
        errs.append(result.fail_msg)
4801
        break
4802
      dev_path = result.payload
4803
      result = self.rpc.call_blockdev_export(source_node, disk,
4804
                                             target_node, dev_path,
4805
                                             cluster_name)
4806
      if result.fail_msg:
4807
        self.LogWarning("Can't copy data over for disk %d: %s",
4808
                        idx, result.fail_msg)
4809
        errs.append(result.fail_msg)
4810
        break
4811

    
4812
    if errs:
4813
      self.LogWarning("Some disks failed to copy, aborting")
4814
      try:
4815
        _RemoveDisks(self, instance, target_node=target_node)
4816
      finally:
4817
        self.cfg.ReleaseDRBDMinors(instance.name)
4818
        raise errors.OpExecError("Errors during disk copy: %s" %
4819
                                 (",".join(errs),))
4820

    
4821
    instance.primary_node = target_node
4822
    self.cfg.Update(instance, feedback_fn)
4823

    
4824
    self.LogInfo("Removing the disks on the original node")
4825
    _RemoveDisks(self, instance, target_node=source_node)
4826

    
4827
    # Only start the instance if it's marked as up
4828
    if instance.admin_up:
4829
      self.LogInfo("Starting instance %s on node %s",
4830
                   instance.name, target_node)
4831

    
4832
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4833
                                           ignore_secondaries=True)
4834
      if not disks_ok:
4835
        _ShutdownInstanceDisks(self, instance)
4836
        raise errors.OpExecError("Can't activate the instance's disks")
4837

    
4838
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4839
      msg = result.fail_msg
4840
      if msg:
4841
        _ShutdownInstanceDisks(self, instance)
4842
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4843
                                 (instance.name, target_node, msg))
4844

    
4845

    
4846
class LUMigrateNode(LogicalUnit):
4847
  """Migrate all instances from a node.
4848

4849
  """
4850
  HPATH = "node-migrate"
4851
  HTYPE = constants.HTYPE_NODE
4852
  _OP_REQP = ["node_name", "live"]
4853
  REQ_BGL = False
4854

    
4855
  def ExpandNames(self):
4856
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
4857
    if self.op.node_name is None:
4858
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name,
4859
                                 errors.ECODE_NOENT)
4860

    
4861
    self.needed_locks = {
4862
      locking.LEVEL_NODE: [self.op.node_name],
4863
      }
4864

    
4865
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4866

    
4867
    # Create tasklets for migrating instances for all instances on this node
4868
    names = []
4869
    tasklets = []
4870

    
4871
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
4872
      logging.debug("Migrating instance %s", inst.name)
4873
      names.append(inst.name)
4874

    
4875
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
4876

    
4877
    self.tasklets = tasklets
4878

    
4879
    # Declare instance locks
4880
    self.needed_locks[locking.LEVEL_INSTANCE] = names
4881

    
4882
  def DeclareLocks(self, level):
4883
    if level == locking.LEVEL_NODE:
4884
      self._LockInstancesNodes()
4885

    
4886
  def BuildHooksEnv(self):
4887
    """Build hooks env.
4888

4889
    This runs on the master, the primary and all the secondaries.
4890

4891
    """
4892
    env = {
4893
      "NODE_NAME": self.op.node_name,
4894
      }
4895

    
4896
    nl = [self.cfg.GetMasterNode()]
4897

    
4898
    return (env, nl, nl)
4899

    
4900

    
4901
class TLMigrateInstance(Tasklet):
4902
  def __init__(self, lu, instance_name, live, cleanup):
4903
    """Initializes this class.
4904

4905
    """
4906
    Tasklet.__init__(self, lu)
4907

    
4908
    # Parameters
4909
    self.instance_name = instance_name
4910
    self.live = live
4911
    self.cleanup = cleanup
4912

    
4913
  def CheckPrereq(self):
4914
    """Check prerequisites.
4915

4916
    This checks that the instance is in the cluster.
4917

4918
    """
4919
    instance = self.cfg.GetInstanceInfo(
4920
      self.cfg.ExpandInstanceName(self.instance_name))
4921
    if instance is None:
4922
      raise errors.OpPrereqError("Instance '%s' not known" %
4923
                                 self.instance_name, errors.ECODE_NOENT)
4924

    
4925
    if instance.disk_template != constants.DT_DRBD8:
4926
      raise errors.OpPrereqError("Instance's disk layout is not"
4927
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
4928

    
4929
    secondary_nodes = instance.secondary_nodes
4930
    if not secondary_nodes:
4931
      raise errors.ConfigurationError("No secondary node but using"
4932
                                      " drbd8 disk template")
4933

    
4934
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
4935

    
4936
    target_node = secondary_nodes[0]
4937
    # check memory requirements on the secondary node
4938
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
4939
                         instance.name, i_be[constants.BE_MEMORY],
4940
                         instance.hypervisor)
4941

    
4942
    # check bridge existance
4943
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4944

    
4945
    if not self.cleanup:
4946
      _CheckNodeNotDrained(self, target_node)
4947
      result = self.rpc.call_instance_migratable(instance.primary_node,
4948
                                                 instance)
4949
      result.Raise("Can't migrate, please use failover",
4950
                   prereq=True, ecode=errors.ECODE_STATE)
4951

    
4952
    self.instance = instance
4953

    
4954
  def _WaitUntilSync(self):
4955
    """Poll with custom rpc for disk sync.
4956

4957
    This uses our own step-based rpc call.
4958

4959
    """
4960
    self.feedback_fn("* wait until resync is done")
4961
    all_done = False
4962
    while not all_done:
4963
      all_done = True
4964
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
4965
                                            self.nodes_ip,
4966
                                            self.instance.disks)
4967
      min_percent = 100
4968
      for node, nres in result.items():
4969
        nres.Raise("Cannot resync disks on node %s" % node)
4970
        node_done, node_percent = nres.payload
4971
        all_done = all_done and node_done
4972
        if node_percent is not None:
4973
          min_percent = min(min_percent, node_percent)
4974
      if not all_done:
4975
        if min_percent < 100:
4976
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
4977
        time.sleep(2)
4978

    
4979
  def _EnsureSecondary(self, node):
4980
    """Demote a node to secondary.
4981

4982
    """
4983
    self.feedback_fn("* switching node %s to secondary mode" % node)
4984

    
4985
    for dev in self.instance.disks:
4986
      self.cfg.SetDiskID(dev, node)
4987

    
4988
    result = self.rpc.call_blockdev_close(node, self.instance.name,
4989
                                          self.instance.disks)
4990
    result.Raise("Cannot change disk to secondary on node %s" % node)
4991

    
4992
  def _GoStandalone(self):
4993
    """Disconnect from the network.
4994

4995
    """
4996
    self.feedback_fn("* changing into standalone mode")
4997
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
4998
                                               self.instance.disks)
4999
    for node, nres in result.items():
5000
      nres.Raise("Cannot disconnect disks node %s" % node)
5001

    
5002
  def _GoReconnect(self, multimaster):
5003
    """Reconnect to the network.
5004

5005
    """
5006
    if multimaster:
5007
      msg = "dual-master"
5008
    else:
5009
      msg = "single-master"
5010
    self.feedback_fn("* changing disks into %s mode" % msg)
5011
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5012
                                           self.instance.disks,
5013
                                           self.instance.name, multimaster)
5014
    for node, nres in result.items():
5015
      nres.Raise("Cannot change disks config on node %s" % node)
5016

    
5017
  def _ExecCleanup(self):
5018
    """Try to cleanup after a failed migration.
5019

5020
    The cleanup is done by:
5021
      - check that the instance is running only on one node
5022
        (and update the config if needed)
5023
      - change disks on its secondary node to secondary
5024
      - wait until disks are fully synchronized
5025
      - disconnect from the network
5026
      - change disks into single-master mode
5027
      - wait again until disks are fully synchronized
5028

5029
    """
5030
    instance = self.instance
5031
    target_node = self.target_node
5032
    source_node = self.source_node
5033

    
5034
    # check running on only one node
5035
    self.feedback_fn("* checking where the instance actually runs"
5036
                     " (if this hangs, the hypervisor might be in"
5037
                     " a bad state)")
5038
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5039
    for node, result in ins_l.items():
5040
      result.Raise("Can't contact node %s" % node)
5041

    
5042
    runningon_source = instance.name in ins_l[source_node].payload
5043
    runningon_target = instance.name in ins_l[target_node].payload
5044

    
5045
    if runningon_source and runningon_target:
5046
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5047
                               " or the hypervisor is confused. You will have"
5048
                               " to ensure manually that it runs only on one"
5049
                               " and restart this operation.")
5050

    
5051
    if not (runningon_source or runningon_target):
5052
      raise errors.OpExecError("Instance does not seem to be running at all."
5053
                               " In this case, it's safer to repair by"
5054
                               " running 'gnt-instance stop' to ensure disk"
5055
                               " shutdown, and then restarting it.")
5056

    
5057
    if runningon_target:
5058
      # the migration has actually succeeded, we need to update the config
5059
      self.feedback_fn("* instance running on secondary node (%s),"
5060
                       " updating config" % target_node)
5061
      instance.primary_node = target_node
5062
      self.cfg.Update(instance, self.feedback_fn)
5063
      demoted_node = source_node
5064
    else:
5065
      self.feedback_fn("* instance confirmed to be running on its"
5066
                       " primary node (%s)" % source_node)
5067
      demoted_node = target_node
5068

    
5069
    self._EnsureSecondary(demoted_node)
5070
    try:
5071
      self._WaitUntilSync()
5072
    except errors.OpExecError:
5073
      # we ignore here errors, since if the device is standalone, it
5074
      # won't be able to sync
5075
      pass
5076
    self._GoStandalone()
5077
    self._GoReconnect(False)
5078
    self._WaitUntilSync()
5079

    
5080
    self.feedback_fn("* done")
5081

    
5082
  def _RevertDiskStatus(self):
5083
    """Try to revert the disk status after a failed migration.
5084

5085
    """
5086
    target_node = self.target_node
5087
    try:
5088
      self._EnsureSecondary(target_node)
5089
      self._GoStandalone()
5090
      self._GoReconnect(False)
5091
      self._WaitUntilSync()
5092
    except errors.OpExecError, err:
5093
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5094
                         " drives: error '%s'\n"
5095
                         "Please look and recover the instance status" %
5096
                         str(err))
5097

    
5098
  def _AbortMigration(self):
5099
    """Call the hypervisor code to abort a started migration.
5100

5101
    """
5102
    instance = self.instance
5103
    target_node = self.target_node
5104
    migration_info = self.migration_info
5105

    
5106
    abort_result = self.rpc.call_finalize_migration(target_node,
5107
                                                    instance,
5108
                                                    migration_info,
5109
                                                    False)
5110
    abort_msg = abort_result.fail_msg
5111
    if abort_msg:
5112
      logging.error("Aborting migration failed on target node %s: %s",
5113
                    target_node, abort_msg)
5114
      # Don't raise an exception here, as we stil have to try to revert the
5115
      # disk status, even if this step failed.
5116

    
5117
  def _ExecMigration(self):
5118
    """Migrate an instance.
5119

5120
    The migrate is done by:
5121
      - change the disks into dual-master mode
5122
      - wait until disks are fully synchronized again
5123
      - migrate the instance
5124
      - change disks on the new secondary node (the old primary) to secondary
5125
      - wait until disks are fully synchronized
5126
      - change disks into single-master mode
5127

5128
    """
5129
    instance = self.instance
5130
    target_node = self.target_node
5131
    source_node = self.source_node
5132

    
5133
    self.feedback_fn("* checking disk consistency between source and target")
5134
    for dev in instance.disks:
5135
      if not _CheckDiskConsistency(self, dev, target_node, False):
5136
        raise errors.OpExecError("Disk %s is degraded or not fully"
5137
                                 " synchronized on target node,"
5138
                                 " aborting migrate." % dev.iv_name)
5139

    
5140
    # First get the migration information from the remote node
5141
    result = self.rpc.call_migration_info(source_node, instance)
5142
    msg = result.fail_msg
5143
    if msg:
5144
      log_err = ("Failed fetching source migration information from %s: %s" %
5145
                 (source_node, msg))
5146
      logging.error(log_err)
5147
      raise errors.OpExecError(log_err)
5148

    
5149
    self.migration_info = migration_info = result.payload
5150

    
5151
    # Then switch the disks to master/master mode
5152
    self._EnsureSecondary(target_node)
5153
    self._GoStandalone()
5154
    self._GoReconnect(True)
5155
    self._WaitUntilSync()
5156

    
5157
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5158
    result = self.rpc.call_accept_instance(target_node,
5159
                                           instance,
5160
                                           migration_info,
5161
                                           self.nodes_ip[target_node])
5162

    
5163
    msg = result.fail_msg
5164
    if msg:
5165
      logging.error("Instance pre-migration failed, trying to revert"
5166
                    " disk status: %s", msg)
5167
      self.feedback_fn("Pre-migration failed, aborting")
5168
      self._AbortMigration()
5169
      self._RevertDiskStatus()
5170
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5171
                               (instance.name, msg))
5172

    
5173
    self.feedback_fn("* migrating instance to %s" % target_node)
5174
    time.sleep(10)
5175
    result = self.rpc.call_instance_migrate(source_node, instance,
5176
                                            self.nodes_ip[target_node],
5177
                                            self.live)
5178
    msg = result.fail_msg
5179
    if msg:
5180
      logging.error("Instance migration failed, trying to revert"
5181
                    " disk status: %s", msg)
5182
      self.feedback_fn("Migration failed, aborting")
5183
      self._AbortMigration()
5184
      self._RevertDiskStatus()
5185
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5186
                               (instance.name, msg))
5187
    time.sleep(10)
5188

    
5189
    instance.primary_node = target_node
5190
    # distribute new instance config to the other nodes
5191
    self.cfg.Update(instance, self.feedback_fn)
5192

    
5193
    result = self.rpc.call_finalize_migration(target_node,
5194
                                              instance,
5195
                                              migration_info,
5196
                                              True)
5197
    msg = result.fail_msg
5198
    if msg:
5199
      logging.error("Instance migration succeeded, but finalization failed:"
5200
                    " %s", msg)
5201
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5202
                               msg)
5203

    
5204
    self._EnsureSecondary(source_node)
5205
    self._WaitUntilSync()
5206
    self._GoStandalone()
5207
    self._GoReconnect(False)
5208
    self._WaitUntilSync()
5209

    
5210
    self.feedback_fn("* done")
5211

    
5212
  def Exec(self, feedback_fn):
5213
    """Perform the migration.
5214

5215
    """
5216
    feedback_fn("Migrating instance %s" % self.instance.name)
5217

    
5218
    self.feedback_fn = feedback_fn
5219

    
5220
    self.source_node = self.instance.primary_node
5221
    self.target_node = self.instance.secondary_nodes[0]
5222
    self.all_nodes = [self.source_node, self.target_node]
5223
    self.nodes_ip = {
5224
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5225
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5226
      }
5227

    
5228
    if self.cleanup:
5229
      return self._ExecCleanup()
5230
    else:
5231
      return self._ExecMigration()
5232

    
5233

    
5234
def _CreateBlockDev(lu, node, instance, device, force_create,
5235
                    info, force_open):
5236
  """Create a tree of block devices on a given node.
5237

5238
  If this device type has to be created on secondaries, create it and
5239
  all its children.
5240

5241
  If not, just recurse to children keeping the same 'force' value.
5242

5243
  @param lu: the lu on whose behalf we execute
5244
  @param node: the node on which to create the device
5245
  @type instance: L{objects.Instance}
5246
  @param instance: the instance which owns the device
5247
  @type device: L{objects.Disk}
5248
  @param device: the device to create
5249
  @type force_create: boolean
5250
  @param force_create: whether to force creation of this device; this
5251
      will be change to True whenever we find a device which has
5252
      CreateOnSecondary() attribute
5253
  @param info: the extra 'metadata' we should attach to the device
5254
      (this will be represented as a LVM tag)
5255
  @type force_open: boolean
5256
  @param force_open: this parameter will be passes to the
5257
      L{backend.BlockdevCreate} function where it specifies
5258
      whether we run on primary or not, and it affects both
5259
      the child assembly and the device own Open() execution
5260

5261
  """
5262
  if device.CreateOnSecondary():
5263
    force_create = True
5264

    
5265
  if device.children:
5266
    for child in device.children:
5267
      _CreateBlockDev(lu, node, instance, child, force_create,
5268
                      info, force_open)
5269

    
5270
  if not force_create:
5271
    return
5272

    
5273
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5274

    
5275

    
5276
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5277
  """Create a single block device on a given node.
5278

5279
  This will not recurse over children of the device, so they must be
5280
  created in advance.
5281

5282
  @param lu: the lu on whose behalf we execute
5283
  @param node: the node on which to create the device
5284
  @type instance: L{objects.Instance}
5285
  @param instance: the instance which owns the device
5286
  @type device: L{objects.Disk}
5287
  @param device: the device to create
5288
  @param info: the extra 'metadata' we should attach to the device
5289
      (this will be represented as a LVM tag)
5290
  @type force_open: boolean
5291
  @param force_open: this parameter will be passes to the
5292
      L{backend.BlockdevCreate} function where it specifies
5293
      whether we run on primary or not, and it affects both
5294
      the child assembly and the device own Open() execution
5295

5296
  """
5297
  lu.cfg.SetDiskID(device, node)
5298
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5299
                                       instance.name, force_open, info)
5300
  result.Raise("Can't create block device %s on"
5301
               " node %s for instance %s" % (device, node, instance.name))
5302
  if device.physical_id is None:
5303
    device.physical_id = result.payload
5304

    
5305

    
5306
def _GenerateUniqueNames(lu, exts):
5307
  """Generate a suitable LV name.
5308

5309
  This will generate a logical volume name for the given instance.
5310

5311
  """
5312
  results = []
5313
  for val in exts:
5314
    new_id = lu.cfg.GenerateUniqueID()
5315
    results.append("%s%s" % (new_id, val))
5316
  return results
5317

    
5318

    
5319
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5320
                         p_minor, s_minor):
5321
  """Generate a drbd8 device complete with its children.
5322

5323
  """
5324
  port = lu.cfg.AllocatePort()
5325
  vgname = lu.cfg.GetVGName()
5326
  shared_secret = lu.cfg.GenerateDRBDSecret()
5327
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5328
                          logical_id=(vgname, names[0]))
5329
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5330
                          logical_id=(vgname, names[1]))
5331
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5332
                          logical_id=(primary, secondary, port,
5333
                                      p_minor, s_minor,
5334
                                      shared_secret),
5335
                          children=[dev_data, dev_meta],
5336
                          iv_name=iv_name)
5337
  return drbd_dev
5338

    
5339

    
5340
def _GenerateDiskTemplate(lu, template_name,
5341
                          instance_name, primary_node,
5342
                          secondary_nodes, disk_info,
5343
                          file_storage_dir, file_driver,
5344
                          base_index):
5345
  """Generate the entire disk layout for a given template type.
5346

5347
  """
5348
  #TODO: compute space requirements
5349

    
5350
  vgname = lu.cfg.GetVGName()
5351
  disk_count = len(disk_info)
5352
  disks = []
5353
  if template_name == constants.DT_DISKLESS:
5354
    pass
5355
  elif template_name == constants.DT_PLAIN:
5356
    if len(secondary_nodes) != 0:
5357
      raise errors.ProgrammerError("Wrong template configuration")
5358

    
5359
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5360
                                      for i in range(disk_count)])
5361
    for idx, disk in enumerate(disk_info):
5362
      disk_index = idx + base_index
5363
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5364
                              logical_id=(vgname, names[idx]),
5365
                              iv_name="disk/%d" % disk_index,
5366
                              mode=disk["mode"])
5367
      disks.append(disk_dev)
5368
  elif template_name == constants.DT_DRBD8:
5369
    if len(secondary_nodes) != 1:
5370
      raise errors.ProgrammerError("Wrong template configuration")
5371
    remote_node = secondary_nodes[0]
5372
    minors = lu.cfg.AllocateDRBDMinor(
5373
      [primary_node, remote_node] * len(disk_info), instance_name)
5374

    
5375
    names = []
5376
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5377
                                               for i in range(disk_count)]):
5378
      names.append(lv_prefix + "_data")
5379
      names.append(lv_prefix + "_meta")
5380
    for idx, disk in enumerate(disk_info):
5381
      disk_index = idx + base_index
5382
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5383
                                      disk["size"], names[idx*2:idx*2+2],
5384
                                      "disk/%d" % disk_index,
5385
                                      minors[idx*2], minors[idx*2+1])
5386
      disk_dev.mode = disk["mode"]
5387
      disks.append(disk_dev)
5388
  elif template_name == constants.DT_FILE:
5389
    if len(secondary_nodes) != 0:
5390
      raise errors.ProgrammerError("Wrong template configuration")
5391

    
5392
    for idx, disk in enumerate(disk_info):
5393
      disk_index = idx + base_index
5394
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5395
                              iv_name="disk/%d" % disk_index,
5396
                              logical_id=(file_driver,
5397
                                          "%s/disk%d" % (file_storage_dir,
5398
                                                         disk_index)),
5399
                              mode=disk["mode"])
5400
      disks.append(disk_dev)
5401
  else:
5402
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5403
  return disks
5404

    
5405

    
5406
def _GetInstanceInfoText(instance):
5407
  """Compute that text that should be added to the disk's metadata.
5408

5409
  """
5410
  return "originstname+%s" % instance.name
5411

    
5412

    
5413
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5414
  """Create all disks for an instance.
5415

5416
  This abstracts away some work from AddInstance.
5417

5418
  @type lu: L{LogicalUnit}
5419
  @param lu: the logical unit on whose behalf we execute
5420
  @type instance: L{objects.Instance}
5421
  @param instance: the instance whose disks we should create
5422
  @type to_skip: list
5423
  @param to_skip: list of indices to skip
5424
  @type target_node: string
5425
  @param target_node: if passed, overrides the target node for creation
5426
  @rtype: boolean
5427
  @return: the success of the creation
5428

5429
  """
5430
  info = _GetInstanceInfoText(instance)
5431
  if target_node is None:
5432
    pnode = instance.primary_node
5433
    all_nodes = instance.all_nodes
5434
  else:
5435
    pnode = target_node
5436
    all_nodes = [pnode]
5437

    
5438
  if instance.disk_template == constants.DT_FILE:
5439
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5440
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5441

    
5442
    result.Raise("Failed to create directory '%s' on"
5443
                 " node %s" % (file_storage_dir, pnode))
5444

    
5445
  # Note: this needs to be kept in sync with adding of disks in
5446
  # LUSetInstanceParams
5447
  for idx, device in enumerate(instance.disks):
5448
    if to_skip and idx in to_skip:
5449
      continue
5450
    logging.info("Creating volume %s for instance %s",
5451
                 device.iv_name, instance.name)
5452
    #HARDCODE
5453
    for node in all_nodes:
5454
      f_create = node == pnode
5455
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5456

    
5457

    
5458
def _RemoveDisks(lu, instance, target_node=None):
5459
  """Remove all disks for an instance.
5460

5461
  This abstracts away some work from `AddInstance()` and
5462
  `RemoveInstance()`. Note that in case some of the devices couldn't
5463
  be removed, the removal will continue with the other ones (compare
5464
  with `_CreateDisks()`).
5465

5466
  @type lu: L{LogicalUnit}
5467
  @param lu: the logical unit on whose behalf we execute
5468
  @type instance: L{objects.Instance}
5469
  @param instance: the instance whose disks we should remove
5470
  @type target_node: string
5471
  @param target_node: used to override the node on which to remove the disks
5472
  @rtype: boolean
5473
  @return: the success of the removal
5474

5475
  """
5476
  logging.info("Removing block devices for instance %s", instance.name)
5477

    
5478
  all_result = True
5479
  for device in instance.disks:
5480
    if target_node:
5481
      edata = [(target_node, device)]
5482
    else:
5483
      edata = device.ComputeNodeTree(instance.primary_node)
5484
    for node, disk in edata:
5485
      lu.cfg.SetDiskID(disk, node)
5486
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5487
      if msg:
5488
        lu.LogWarning("Could not remove block device %s on node %s,"
5489
                      " continuing anyway: %s", device.iv_name, node, msg)
5490
        all_result = False
5491

    
5492
  if instance.disk_template == constants.DT_FILE:
5493
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5494
    if target_node:
5495
      tgt = target_node
5496
    else:
5497
      tgt = instance.primary_node
5498
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5499
    if result.fail_msg:
5500
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5501
                    file_storage_dir, instance.primary_node, result.fail_msg)
5502
      all_result = False
5503

    
5504
  return all_result
5505

    
5506

    
5507
def _ComputeDiskSize(disk_template, disks):
5508
  """Compute disk size requirements in the volume group
5509

5510
  """
5511
  # Required free disk space as a function of disk and swap space
5512
  req_size_dict = {
5513
    constants.DT_DISKLESS: None,
5514
    constants.DT_PLAIN: sum(d["size"] for d in disks),
5515
    # 128 MB are added for drbd metadata for each disk
5516
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
5517
    constants.DT_FILE: None,
5518
  }
5519

    
5520
  if disk_template not in req_size_dict:
5521
    raise errors.ProgrammerError("Disk template '%s' size requirement"
5522
                                 " is unknown" %  disk_template)
5523

    
5524
  return req_size_dict[disk_template]
5525

    
5526

    
5527
def _CheckHVParams(lu, nodenames, hvname, hvparams):
5528
  """Hypervisor parameter validation.
5529

5530
  This function abstract the hypervisor parameter validation to be
5531
  used in both instance create and instance modify.
5532

5533
  @type lu: L{LogicalUnit}
5534
  @param lu: the logical unit for which we check
5535
  @type nodenames: list
5536
  @param nodenames: the list of nodes on which we should check
5537
  @type hvname: string
5538
  @param hvname: the name of the hypervisor we should use
5539
  @type hvparams: dict
5540
  @param hvparams: the parameters which we need to check
5541
  @raise errors.OpPrereqError: if the parameters are not valid
5542

5543
  """
5544
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
5545
                                                  hvname,
5546
                                                  hvparams)
5547
  for node in nodenames:
5548
    info = hvinfo[node]
5549
    if info.offline:
5550
      continue
5551
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
5552

    
5553

    
5554
class LUCreateInstance(LogicalUnit):
5555
  """Create an instance.
5556

5557
  """
5558
  HPATH = "instance-add"
5559
  HTYPE = constants.HTYPE_INSTANCE
5560
  _OP_REQP = ["instance_name", "disks", "disk_template",
5561
              "mode", "start",
5562
              "wait_for_sync", "ip_check", "nics",
5563
              "hvparams", "beparams"]
5564
  REQ_BGL = False
5565

    
5566
  def _ExpandNode(self, node):
5567
    """Expands and checks one node name.
5568

5569
    """
5570
    node_full = self.cfg.ExpandNodeName(node)
5571
    if node_full is None:
5572
      raise errors.OpPrereqError("Unknown node %s" % node, errors.ECODE_NOENT)
5573
    return node_full
5574

    
5575
  def ExpandNames(self):
5576
    """ExpandNames for CreateInstance.
5577

5578
    Figure out the right locks for instance creation.
5579

5580
    """
5581
    self.needed_locks = {}
5582

    
5583
    # set optional parameters to none if they don't exist
5584
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
5585
      if not hasattr(self.op, attr):
5586
        setattr(self.op, attr, None)
5587

    
5588
    # cheap checks, mostly valid constants given
5589

    
5590
    # verify creation mode
5591
    if self.op.mode not in (constants.INSTANCE_CREATE,
5592
                            constants.INSTANCE_IMPORT):
5593
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
5594
                                 self.op.mode, errors.ECODE_INVAL)
5595

    
5596
    # disk template and mirror node verification
5597
    if self.op.disk_template not in constants.DISK_TEMPLATES:
5598
      raise errors.OpPrereqError("Invalid disk template name",
5599
                                 errors.ECODE_INVAL)
5600

    
5601
    if self.op.hypervisor is None:
5602
      self.op.hypervisor = self.cfg.GetHypervisorType()
5603

    
5604
    cluster = self.cfg.GetClusterInfo()
5605
    enabled_hvs = cluster.enabled_hypervisors
5606
    if self.op.hypervisor not in enabled_hvs:
5607
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
5608
                                 " cluster (%s)" % (self.op.hypervisor,
5609
                                  ",".join(enabled_hvs)),
5610
                                 errors.ECODE_STATE)
5611

    
5612
    # check hypervisor parameter syntax (locally)
5613
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5614
    filled_hvp = objects.FillDict(cluster.hvparams[self.op.hypervisor],
5615
                                  self.op.hvparams)
5616
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
5617
    hv_type.CheckParameterSyntax(filled_hvp)
5618
    self.hv_full = filled_hvp
5619
    # check that we don't specify global parameters on an instance
5620
    _CheckGlobalHvParams(self.op.hvparams)
5621

    
5622
    # fill and remember the beparams dict
5623
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5624
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
5625
                                    self.op.beparams)
5626

    
5627
    #### instance parameters check
5628

    
5629
    # instance name verification
5630
    hostname1 = utils.GetHostInfo(self.op.instance_name)
5631
    self.op.instance_name = instance_name = hostname1.name
5632

    
5633
    # this is just a preventive check, but someone might still add this
5634
    # instance in the meantime, and creation will fail at lock-add time
5635
    if instance_name in self.cfg.GetInstanceList():
5636
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5637
                                 instance_name, errors.ECODE_EXISTS)
5638

    
5639
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
5640

    
5641
    # NIC buildup
5642
    self.nics = []
5643
    for idx, nic in enumerate(self.op.nics):
5644
      nic_mode_req = nic.get("mode", None)
5645
      nic_mode = nic_mode_req
5646
      if nic_mode is None:
5647
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
5648

    
5649
      # in routed mode, for the first nic, the default ip is 'auto'
5650
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
5651
        default_ip_mode = constants.VALUE_AUTO
5652
      else:
5653
        default_ip_mode = constants.VALUE_NONE
5654

    
5655
      # ip validity checks
5656
      ip = nic.get("ip", default_ip_mode)
5657
      if ip is None or ip.lower() == constants.VALUE_NONE:
5658
        nic_ip = None
5659
      elif ip.lower() == constants.VALUE_AUTO:
5660
        nic_ip = hostname1.ip
5661
      else:
5662
        if not utils.IsValidIP(ip):
5663
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
5664
                                     " like a valid IP" % ip,
5665
                                     errors.ECODE_INVAL)
5666
        nic_ip = ip
5667

    
5668
      # TODO: check the ip for uniqueness !!
5669
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
5670
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
5671
                                   errors.ECODE_INVAL)
5672

    
5673
      # MAC address verification
5674
      mac = nic.get("mac", constants.VALUE_AUTO)
5675
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5676
        if not utils.IsValidMac(mac.lower()):
5677
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
5678
                                     mac, errors.ECODE_INVAL)
5679
        else:
5680
          # or validate/reserve the current one
5681
          if self.cfg.IsMacInUse(mac):
5682
            raise errors.OpPrereqError("MAC address %s already in use"
5683
                                       " in cluster" % mac,
5684
                                       errors.ECODE_NOTUNIQUE)
5685

    
5686
      # bridge verification
5687
      bridge = nic.get("bridge", None)
5688
      link = nic.get("link", None)
5689
      if bridge and link:
5690
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
5691
                                   " at the same time", errors.ECODE_INVAL)
5692
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
5693
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
5694
                                   errors.ECODE_INVAL)
5695
      elif bridge:
5696
        link = bridge
5697

    
5698
      nicparams = {}
5699
      if nic_mode_req:
5700
        nicparams[constants.NIC_MODE] = nic_mode_req
5701
      if link:
5702
        nicparams[constants.NIC_LINK] = link
5703

    
5704
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
5705
                                      nicparams)
5706
      objects.NIC.CheckParameterSyntax(check_params)
5707
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
5708

    
5709
    # disk checks/pre-build
5710
    self.disks = []
5711
    for disk in self.op.disks:
5712
      mode = disk.get("mode", constants.DISK_RDWR)
5713
      if mode not in constants.DISK_ACCESS_SET:
5714
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
5715
                                   mode, errors.ECODE_INVAL)
5716
      size = disk.get("size", None)
5717
      if size is None:
5718
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
5719
      try:
5720
        size = int(size)
5721
      except ValueError:
5722
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
5723
                                   errors.ECODE_INVAL)
5724
      self.disks.append({"size": size, "mode": mode})
5725

    
5726
    # used in CheckPrereq for ip ping check
5727
    self.check_ip = hostname1.ip
5728

    
5729
    # file storage checks
5730
    if (self.op.file_driver and
5731
        not self.op.file_driver in constants.FILE_DRIVER):
5732
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
5733
                                 self.op.file_driver, errors.ECODE_INVAL)
5734

    
5735
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
5736
      raise errors.OpPrereqError("File storage directory path not absolute",
5737
                                 errors.ECODE_INVAL)
5738

    
5739
    ### Node/iallocator related checks
5740
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
5741
      raise errors.OpPrereqError("One and only one of iallocator and primary"
5742
                                 " node must be given",
5743
                                 errors.ECODE_INVAL)
5744

    
5745
    if self.op.iallocator:
5746
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5747
    else:
5748
      self.op.pnode = self._ExpandNode(self.op.pnode)
5749
      nodelist = [self.op.pnode]
5750
      if self.op.snode is not None:
5751
        self.op.snode = self._ExpandNode(self.op.snode)
5752
        nodelist.append(self.op.snode)
5753
      self.needed_locks[locking.LEVEL_NODE] = nodelist
5754

    
5755
    # in case of import lock the source node too
5756
    if self.op.mode == constants.INSTANCE_IMPORT:
5757
      src_node = getattr(self.op, "src_node", None)
5758
      src_path = getattr(self.op, "src_path", None)
5759

    
5760
      if src_path is None:
5761
        self.op.src_path = src_path = self.op.instance_name
5762

    
5763
      if src_node is None:
5764
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5765
        self.op.src_node = None
5766
        if os.path.isabs(src_path):
5767
          raise errors.OpPrereqError("Importing an instance from an absolute"
5768
                                     " path requires a source node option.",
5769
                                     errors.ECODE_INVAL)
5770
      else:
5771
        self.op.src_node = src_node = self._ExpandNode(src_node)
5772
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
5773
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
5774
        if not os.path.isabs(src_path):
5775
          self.op.src_path = src_path = \
5776
            os.path.join(constants.EXPORT_DIR, src_path)
5777

    
5778
      # On import force_variant must be True, because if we forced it at
5779
      # initial install, our only chance when importing it back is that it
5780
      # works again!
5781
      self.op.force_variant = True
5782

    
5783
    else: # INSTANCE_CREATE
5784
      if getattr(self.op, "os_type", None) is None:
5785
        raise errors.OpPrereqError("No guest OS specified",
5786
                                   errors.ECODE_INVAL)
5787
      self.op.force_variant = getattr(self.op, "force_variant", False)
5788

    
5789
  def _RunAllocator(self):
5790
    """Run the allocator based on input opcode.
5791

5792
    """
5793
    nics = [n.ToDict() for n in self.nics]
5794
    ial = IAllocator(self.cfg, self.rpc,
5795
                     mode=constants.IALLOCATOR_MODE_ALLOC,
5796
                     name=self.op.instance_name,
5797
                     disk_template=self.op.disk_template,
5798
                     tags=[],
5799
                     os=self.op.os_type,
5800
                     vcpus=self.be_full[constants.BE_VCPUS],
5801
                     mem_size=self.be_full[constants.BE_MEMORY],
5802
                     disks=self.disks,
5803
                     nics=nics,
5804
                     hypervisor=self.op.hypervisor,
5805
                     )
5806

    
5807
    ial.Run(self.op.iallocator)
5808

    
5809
    if not ial.success:
5810
      raise errors.OpPrereqError("Can't compute nodes using"
5811
                                 " iallocator '%s': %s" %
5812
                                 (self.op.iallocator, ial.info),
5813
                                 errors.ECODE_NORES)
5814
    if len(ial.nodes) != ial.required_nodes:
5815
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5816
                                 " of nodes (%s), required %s" %
5817
                                 (self.op.iallocator, len(ial.nodes),
5818
                                  ial.required_nodes), errors.ECODE_FAULT)
5819
    self.op.pnode = ial.nodes[0]
5820
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5821
                 self.op.instance_name, self.op.iallocator,
5822
                 ", ".join(ial.nodes))
5823
    if ial.required_nodes == 2:
5824
      self.op.snode = ial.nodes[1]
5825

    
5826
  def BuildHooksEnv(self):
5827
    """Build hooks env.
5828

5829
    This runs on master, primary and secondary nodes of the instance.
5830

5831
    """
5832
    env = {
5833
      "ADD_MODE": self.op.mode,
5834
      }
5835
    if self.op.mode == constants.INSTANCE_IMPORT:
5836
      env["SRC_NODE"] = self.op.src_node
5837
      env["SRC_PATH"] = self.op.src_path
5838
      env["SRC_IMAGES"] = self.src_images
5839

    
5840
    env.update(_BuildInstanceHookEnv(
5841
      name=self.op.instance_name,
5842
      primary_node=self.op.pnode,
5843
      secondary_nodes=self.secondaries,
5844
      status=self.op.start,
5845
      os_type=self.op.os_type,
5846
      memory=self.be_full[constants.BE_MEMORY],
5847
      vcpus=self.be_full[constants.BE_VCPUS],
5848
      nics=_NICListToTuple(self, self.nics),
5849
      disk_template=self.op.disk_template,
5850
      disks=[(d["size"], d["mode"]) for d in self.disks],
5851
      bep=self.be_full,
5852
      hvp=self.hv_full,
5853
      hypervisor_name=self.op.hypervisor,
5854
    ))
5855

    
5856
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
5857
          self.secondaries)
5858
    return env, nl, nl
5859

    
5860

    
5861
  def CheckPrereq(self):
5862
    """Check prerequisites.
5863

5864
    """
5865
    if (not self.cfg.GetVGName() and
5866
        self.op.disk_template not in constants.DTS_NOT_LVM):
5867
      raise errors.OpPrereqError("Cluster does not support lvm-based"
5868
                                 " instances", errors.ECODE_STATE)
5869

    
5870
    if self.op.mode == constants.INSTANCE_IMPORT:
5871
      src_node = self.op.src_node
5872
      src_path = self.op.src_path
5873

    
5874
      if src_node is None:
5875
        locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
5876
        exp_list = self.rpc.call_export_list(locked_nodes)
5877
        found = False
5878
        for node in exp_list:
5879
          if exp_list[node].fail_msg:
5880
            continue
5881
          if src_path in exp_list[node].payload:
5882
            found = True
5883
            self.op.src_node = src_node = node
5884
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
5885
                                                       src_path)
5886
            break
5887
        if not found:
5888
          raise errors.OpPrereqError("No export found for relative path %s" %
5889
                                      src_path, errors.ECODE_INVAL)
5890

    
5891
      _CheckNodeOnline(self, src_node)
5892
      result = self.rpc.call_export_info(src_node, src_path)
5893
      result.Raise("No export or invalid export found in dir %s" % src_path)
5894

    
5895
      export_info = objects.SerializableConfigParser.Loads(str(result.payload))
5896
      if not export_info.has_section(constants.INISECT_EXP):
5897
        raise errors.ProgrammerError("Corrupted export config",
5898
                                     errors.ECODE_ENVIRON)
5899

    
5900
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
5901
      if (int(ei_version) != constants.EXPORT_VERSION):
5902
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
5903
                                   (ei_version, constants.EXPORT_VERSION),
5904
                                   errors.ECODE_ENVIRON)
5905

    
5906
      # Check that the new instance doesn't have less disks than the export
5907
      instance_disks = len(self.disks)
5908
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
5909
      if instance_disks < export_disks:
5910
        raise errors.OpPrereqError("Not enough disks to import."
5911
                                   " (instance: %d, export: %d)" %
5912
                                   (instance_disks, export_disks),
5913
                                   errors.ECODE_INVAL)
5914

    
5915
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
5916
      disk_images = []
5917
      for idx in range(export_disks):
5918
        option = 'disk%d_dump' % idx
5919
        if export_info.has_option(constants.INISECT_INS, option):
5920
          # FIXME: are the old os-es, disk sizes, etc. useful?
5921
          export_name = export_info.get(constants.INISECT_INS, option)
5922
          image = os.path.join(src_path, export_name)
5923
          disk_images.append(image)
5924
        else:
5925
          disk_images.append(False)
5926

    
5927
      self.src_images = disk_images
5928

    
5929
      old_name = export_info.get(constants.INISECT_INS, 'name')
5930
      # FIXME: int() here could throw a ValueError on broken exports
5931
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
5932
      if self.op.instance_name == old_name:
5933
        for idx, nic in enumerate(self.nics):
5934
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
5935
            nic_mac_ini = 'nic%d_mac' % idx
5936
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
5937

    
5938
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
5939
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
5940
    if self.op.start and not self.op.ip_check:
5941
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
5942
                                 " adding an instance in start mode",
5943
                                 errors.ECODE_INVAL)
5944

    
5945
    if self.op.ip_check:
5946
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
5947
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5948
                                   (self.check_ip, self.op.instance_name),
5949
                                   errors.ECODE_NOTUNIQUE)
5950

    
5951
    #### mac address generation
5952
    # By generating here the mac address both the allocator and the hooks get
5953
    # the real final mac address rather than the 'auto' or 'generate' value.
5954
    # There is a race condition between the generation and the instance object
5955
    # creation, which means that we know the mac is valid now, but we're not
5956
    # sure it will be when we actually add the instance. If things go bad
5957
    # adding the instance will abort because of a duplicate mac, and the
5958
    # creation job will fail.
5959
    for nic in self.nics:
5960
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5961
        nic.mac = self.cfg.GenerateMAC()
5962

    
5963
    #### allocator run
5964

    
5965
    if self.op.iallocator is not None:
5966
      self._RunAllocator()
5967

    
5968
    #### node related checks
5969

    
5970
    # check primary node
5971
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
5972
    assert self.pnode is not None, \
5973
      "Cannot retrieve locked node %s" % self.op.pnode
5974
    if pnode.offline:
5975
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
5976
                                 pnode.name, errors.ECODE_STATE)
5977
    if pnode.drained:
5978
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
5979
                                 pnode.name, errors.ECODE_STATE)
5980

    
5981
    self.secondaries = []
5982

    
5983
    # mirror node verification
5984
    if self.op.disk_template in constants.DTS_NET_MIRROR:
5985
      if self.op.snode is None:
5986
        raise errors.OpPrereqError("The networked disk templates need"
5987
                                   " a mirror node", errors.ECODE_INVAL)
5988
      if self.op.snode == pnode.name:
5989
        raise errors.OpPrereqError("The secondary node cannot be the"
5990
                                   " primary node.", errors.ECODE_INVAL)
5991
      _CheckNodeOnline(self, self.op.snode)
5992
      _CheckNodeNotDrained(self, self.op.snode)
5993
      self.secondaries.append(self.op.snode)
5994

    
5995
    nodenames = [pnode.name] + self.secondaries
5996

    
5997
    req_size = _ComputeDiskSize(self.op.disk_template,
5998
                                self.disks)
5999

    
6000
    # Check lv size requirements
6001
    if req_size is not None:
6002
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
6003
                                         self.op.hypervisor)
6004
      for node in nodenames:
6005
        info = nodeinfo[node]
6006
        info.Raise("Cannot get current information from node %s" % node)
6007
        info = info.payload
6008
        vg_free = info.get('vg_free', None)
6009
        if not isinstance(vg_free, int):
6010
          raise errors.OpPrereqError("Can't compute free disk space on"
6011
                                     " node %s" % node, errors.ECODE_ENVIRON)
6012
        if req_size > vg_free:
6013
          raise errors.OpPrereqError("Not enough disk space on target node %s."
6014
                                     " %d MB available, %d MB required" %
6015
                                     (node, vg_free, req_size),
6016
                                     errors.ECODE_NORES)
6017

    
6018
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
6019

    
6020
    # os verification
6021
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
6022
    result.Raise("OS '%s' not in supported os list for primary node %s" %
6023
                 (self.op.os_type, pnode.name),
6024
                 prereq=True, ecode=errors.ECODE_INVAL)
6025
    if not self.op.force_variant:
6026
      _CheckOSVariant(result.payload, self.op.os_type)
6027

    
6028
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
6029

    
6030
    # memory check on primary node
6031
    if self.op.start:
6032
      _CheckNodeFreeMemory(self, self.pnode.name,
6033
                           "creating instance %s" % self.op.instance_name,
6034
                           self.be_full[constants.BE_MEMORY],
6035
                           self.op.hypervisor)
6036

    
6037
    self.dry_run_result = list(nodenames)
6038

    
6039
  def Exec(self, feedback_fn):
6040
    """Create and add the instance to the cluster.
6041

6042
    """
6043
    instance = self.op.instance_name
6044
    pnode_name = self.pnode.name
6045

    
6046
    ht_kind = self.op.hypervisor
6047
    if ht_kind in constants.HTS_REQ_PORT:
6048
      network_port = self.cfg.AllocatePort()
6049
    else:
6050
      network_port = None
6051

    
6052
    ##if self.op.vnc_bind_address is None:
6053
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
6054

    
6055
    # this is needed because os.path.join does not accept None arguments
6056
    if self.op.file_storage_dir is None:
6057
      string_file_storage_dir = ""
6058
    else:
6059
      string_file_storage_dir = self.op.file_storage_dir
6060

    
6061
    # build the full file storage dir path
6062
    file_storage_dir = os.path.normpath(os.path.join(
6063
                                        self.cfg.GetFileStorageDir(),
6064
                                        string_file_storage_dir, instance))
6065

    
6066

    
6067
    disks = _GenerateDiskTemplate(self,
6068
                                  self.op.disk_template,
6069
                                  instance, pnode_name,
6070
                                  self.secondaries,
6071
                                  self.disks,
6072
                                  file_storage_dir,
6073
                                  self.op.file_driver,
6074
                                  0)
6075

    
6076
    iobj = objects.Instance(name=instance, os=self.op.os_type,
6077
                            primary_node=pnode_name,
6078
                            nics=self.nics, disks=disks,
6079
                            disk_template=self.op.disk_template,
6080
                            admin_up=False,
6081
                            network_port=network_port,
6082
                            beparams=self.op.beparams,
6083
                            hvparams=self.op.hvparams,
6084
                            hypervisor=self.op.hypervisor,
6085
                            )
6086

    
6087
    feedback_fn("* creating instance disks...")
6088
    try:
6089
      _CreateDisks(self, iobj)
6090
    except errors.OpExecError:
6091
      self.LogWarning("Device creation failed, reverting...")
6092
      try:
6093
        _RemoveDisks(self, iobj)
6094
      finally:
6095
        self.cfg.ReleaseDRBDMinors(instance)
6096
        raise
6097

    
6098
    feedback_fn("adding instance %s to cluster config" % instance)
6099

    
6100
    self.cfg.AddInstance(iobj, self.proc.GetECId())
6101

    
6102
    # Declare that we don't want to remove the instance lock anymore, as we've
6103
    # added the instance to the config
6104
    del self.remove_locks[locking.LEVEL_INSTANCE]
6105
    # Unlock all the nodes
6106
    if self.op.mode == constants.INSTANCE_IMPORT:
6107
      nodes_keep = [self.op.src_node]
6108
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
6109
                       if node != self.op.src_node]
6110
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
6111
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6112
    else:
6113
      self.context.glm.release(locking.LEVEL_NODE)
6114
      del self.acquired_locks[locking.LEVEL_NODE]
6115

    
6116
    if self.op.wait_for_sync:
6117
      disk_abort = not _WaitForSync(self, iobj)
6118
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
6119
      # make sure the disks are not degraded (still sync-ing is ok)
6120
      time.sleep(15)
6121
      feedback_fn("* checking mirrors status")
6122
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
6123
    else:
6124
      disk_abort = False
6125

    
6126
    if disk_abort:
6127
      _RemoveDisks(self, iobj)
6128
      self.cfg.RemoveInstance(iobj.name)
6129
      # Make sure the instance lock gets removed
6130
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
6131
      raise errors.OpExecError("There are some degraded disks for"
6132
                               " this instance")
6133

    
6134
    feedback_fn("creating os for instance %s on node %s" %
6135
                (instance, pnode_name))
6136

    
6137
    if iobj.disk_template != constants.DT_DISKLESS:
6138
      if self.op.mode == constants.INSTANCE_CREATE:
6139
        feedback_fn("* running the instance OS create scripts...")
6140
        result = self.rpc.call_instance_os_add(pnode_name, iobj, False)
6141
        result.Raise("Could not add os for instance %s"
6142
                     " on node %s" % (instance, pnode_name))
6143

    
6144
      elif self.op.mode == constants.INSTANCE_IMPORT:
6145
        feedback_fn("* running the instance OS import scripts...")
6146
        src_node = self.op.src_node
6147
        src_images = self.src_images
6148
        cluster_name = self.cfg.GetClusterName()
6149
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
6150
                                                         src_node, src_images,
6151
                                                         cluster_name)
6152
        msg = import_result.fail_msg
6153
        if msg:
6154
          self.LogWarning("Error while importing the disk images for instance"
6155
                          " %s on node %s: %s" % (instance, pnode_name, msg))
6156
      else:
6157
        # also checked in the prereq part
6158
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
6159
                                     % self.op.mode)
6160

    
6161
    if self.op.start:
6162
      iobj.admin_up = True
6163
      self.cfg.Update(iobj, feedback_fn)
6164
      logging.info("Starting instance %s on node %s", instance, pnode_name)
6165
      feedback_fn("* starting instance...")
6166
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
6167
      result.Raise("Could not start instance")
6168

    
6169
    return list(iobj.all_nodes)
6170

    
6171

    
6172
class LUConnectConsole(NoHooksLU):
6173
  """Connect to an instance's console.
6174

6175
  This is somewhat special in that it returns the command line that
6176
  you need to run on the master node in order to connect to the
6177
  console.
6178

6179
  """
6180
  _OP_REQP = ["instance_name"]
6181
  REQ_BGL = False
6182

    
6183
  def ExpandNames(self):
6184
    self._ExpandAndLockInstance()
6185

    
6186
  def CheckPrereq(self):
6187
    """Check prerequisites.
6188

6189
    This checks that the instance is in the cluster.
6190

6191
    """
6192
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6193
    assert self.instance is not None, \
6194
      "Cannot retrieve locked instance %s" % self.op.instance_name
6195
    _CheckNodeOnline(self, self.instance.primary_node)
6196

    
6197
  def Exec(self, feedback_fn):
6198
    """Connect to the console of an instance
6199

6200
    """
6201
    instance = self.instance
6202
    node = instance.primary_node
6203

    
6204
    node_insts = self.rpc.call_instance_list([node],
6205
                                             [instance.hypervisor])[node]
6206
    node_insts.Raise("Can't get node information from %s" % node)
6207

    
6208
    if instance.name not in node_insts.payload:
6209
      raise errors.OpExecError("Instance %s is not running." % instance.name)
6210

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

    
6213
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6214
    cluster = self.cfg.GetClusterInfo()
6215
    # beparams and hvparams are passed separately, to avoid editing the
6216
    # instance and then saving the defaults in the instance itself.
6217
    hvparams = cluster.FillHV(instance)
6218
    beparams = cluster.FillBE(instance)
6219
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6220

    
6221
    # build ssh cmdline
6222
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6223

    
6224

    
6225
class LUReplaceDisks(LogicalUnit):
6226
  """Replace the disks of an instance.
6227

6228
  """
6229
  HPATH = "mirrors-replace"
6230
  HTYPE = constants.HTYPE_INSTANCE
6231
  _OP_REQP = ["instance_name", "mode", "disks"]
6232
  REQ_BGL = False
6233

    
6234
  def CheckArguments(self):
6235
    if not hasattr(self.op, "remote_node"):
6236
      self.op.remote_node = None
6237
    if not hasattr(self.op, "iallocator"):
6238
      self.op.iallocator = None
6239

    
6240
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
6241
                                  self.op.iallocator)
6242

    
6243
  def ExpandNames(self):
6244
    self._ExpandAndLockInstance()
6245

    
6246
    if self.op.iallocator is not None:
6247
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6248

    
6249
    elif self.op.remote_node is not None:
6250
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6251
      if remote_node is None:
6252
        raise errors.OpPrereqError("Node '%s' not known" %
6253
                                   self.op.remote_node, errors.ECODE_NOENT)
6254

    
6255
      self.op.remote_node = remote_node
6256

    
6257
      # Warning: do not remove the locking of the new secondary here
6258
      # unless DRBD8.AddChildren is changed to work in parallel;
6259
      # currently it doesn't since parallel invocations of
6260
      # FindUnusedMinor will conflict
6261
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6262
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6263

    
6264
    else:
6265
      self.needed_locks[locking.LEVEL_NODE] = []
6266
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6267

    
6268
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
6269
                                   self.op.iallocator, self.op.remote_node,
6270
                                   self.op.disks)
6271

    
6272
    self.tasklets = [self.replacer]
6273

    
6274
  def DeclareLocks(self, level):
6275
    # If we're not already locking all nodes in the set we have to declare the
6276
    # instance's primary/secondary nodes.
6277
    if (level == locking.LEVEL_NODE and
6278
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6279
      self._LockInstancesNodes()
6280

    
6281
  def BuildHooksEnv(self):
6282
    """Build hooks env.
6283

6284
    This runs on the master, the primary and all the secondaries.
6285

6286
    """
6287
    instance = self.replacer.instance
6288
    env = {
6289
      "MODE": self.op.mode,
6290
      "NEW_SECONDARY": self.op.remote_node,
6291
      "OLD_SECONDARY": instance.secondary_nodes[0],
6292
      }
6293
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6294
    nl = [
6295
      self.cfg.GetMasterNode(),
6296
      instance.primary_node,
6297
      ]
6298
    if self.op.remote_node is not None:
6299
      nl.append(self.op.remote_node)
6300
    return env, nl, nl
6301

    
6302

    
6303
class LUEvacuateNode(LogicalUnit):
6304
  """Relocate the secondary instances from a node.
6305

6306
  """
6307
  HPATH = "node-evacuate"
6308
  HTYPE = constants.HTYPE_NODE
6309
  _OP_REQP = ["node_name"]
6310
  REQ_BGL = False
6311

    
6312
  def CheckArguments(self):
6313
    if not hasattr(self.op, "remote_node"):
6314
      self.op.remote_node = None
6315
    if not hasattr(self.op, "iallocator"):
6316
      self.op.iallocator = None
6317

    
6318
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
6319
                                  self.op.remote_node,
6320
                                  self.op.iallocator)
6321

    
6322
  def ExpandNames(self):
6323
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
6324
    if self.op.node_name is None:
6325
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name,
6326
                                 errors.ECODE_NOENT)
6327

    
6328
    self.needed_locks = {}
6329

    
6330
    # Declare node locks
6331
    if self.op.iallocator is not None:
6332
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6333

    
6334
    elif self.op.remote_node is not None:
6335
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6336
      if remote_node is None:
6337
        raise errors.OpPrereqError("Node '%s' not known" %
6338
                                   self.op.remote_node, errors.ECODE_NOENT)
6339

    
6340
      self.op.remote_node = remote_node
6341

    
6342
      # Warning: do not remove the locking of the new secondary here
6343
      # unless DRBD8.AddChildren is changed to work in parallel;
6344
      # currently it doesn't since parallel invocations of
6345
      # FindUnusedMinor will conflict
6346
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6347
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6348

    
6349
    else:
6350
      raise errors.OpPrereqError("Invalid parameters", errors.ECODE_INVAL)
6351

    
6352
    # Create tasklets for replacing disks for all secondary instances on this
6353
    # node
6354
    names = []
6355
    tasklets = []
6356

    
6357
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
6358
      logging.debug("Replacing disks for instance %s", inst.name)
6359
      names.append(inst.name)
6360

    
6361
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
6362
                                self.op.iallocator, self.op.remote_node, [])
6363
      tasklets.append(replacer)
6364

    
6365
    self.tasklets = tasklets
6366
    self.instance_names = names
6367

    
6368
    # Declare instance locks
6369
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
6370

    
6371
  def DeclareLocks(self, level):
6372
    # If we're not already locking all nodes in the set we have to declare the
6373
    # instance's primary/secondary nodes.
6374
    if (level == locking.LEVEL_NODE and
6375
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6376
      self._LockInstancesNodes()
6377

    
6378
  def BuildHooksEnv(self):
6379
    """Build hooks env.
6380

6381
    This runs on the master, the primary and all the secondaries.
6382

6383
    """
6384
    env = {
6385
      "NODE_NAME": self.op.node_name,
6386
      }
6387

    
6388
    nl = [self.cfg.GetMasterNode()]
6389

    
6390
    if self.op.remote_node is not None:
6391
      env["NEW_SECONDARY"] = self.op.remote_node
6392
      nl.append(self.op.remote_node)
6393

    
6394
    return (env, nl, nl)
6395

    
6396

    
6397
class TLReplaceDisks(Tasklet):
6398
  """Replaces disks for an instance.
6399

6400
  Note: Locking is not within the scope of this class.
6401

6402
  """
6403
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
6404
               disks):
6405
    """Initializes this class.
6406

6407
    """
6408
    Tasklet.__init__(self, lu)
6409

    
6410
    # Parameters
6411
    self.instance_name = instance_name
6412
    self.mode = mode
6413
    self.iallocator_name = iallocator_name
6414
    self.remote_node = remote_node
6415
    self.disks = disks
6416

    
6417
    # Runtime data
6418
    self.instance = None
6419
    self.new_node = None
6420
    self.target_node = None
6421
    self.other_node = None
6422
    self.remote_node_info = None
6423
    self.node_secondary_ip = None
6424

    
6425
  @staticmethod
6426
  def CheckArguments(mode, remote_node, iallocator):
6427
    """Helper function for users of this class.
6428

6429
    """
6430
    # check for valid parameter combination
6431
    if mode == constants.REPLACE_DISK_CHG:
6432
      if remote_node is None and iallocator is None:
6433
        raise errors.OpPrereqError("When changing the secondary either an"
6434
                                   " iallocator script must be used or the"
6435
                                   " new node given", errors.ECODE_INVAL)
6436

    
6437
      if remote_node is not None and iallocator is not None:
6438
        raise errors.OpPrereqError("Give either the iallocator or the new"
6439
                                   " secondary, not both", errors.ECODE_INVAL)
6440

    
6441
    elif remote_node is not None or iallocator is not None:
6442
      # Not replacing the secondary
6443
      raise errors.OpPrereqError("The iallocator and new node options can"
6444
                                 " only be used when changing the"
6445
                                 " secondary node", errors.ECODE_INVAL)
6446

    
6447
  @staticmethod
6448
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
6449
    """Compute a new secondary node using an IAllocator.
6450

6451
    """
6452
    ial = IAllocator(lu.cfg, lu.rpc,
6453
                     mode=constants.IALLOCATOR_MODE_RELOC,
6454
                     name=instance_name,
6455
                     relocate_from=relocate_from)
6456

    
6457
    ial.Run(iallocator_name)
6458

    
6459
    if not ial.success:
6460
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
6461
                                 " %s" % (iallocator_name, ial.info),
6462
                                 errors.ECODE_NORES)
6463

    
6464
    if len(ial.nodes) != ial.required_nodes:
6465
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6466
                                 " of nodes (%s), required %s" %
6467
                                 (len(ial.nodes), ial.required_nodes),
6468
                                 errors.ECODE_FAULT)
6469

    
6470
    remote_node_name = ial.nodes[0]
6471

    
6472
    lu.LogInfo("Selected new secondary for instance '%s': %s",
6473
               instance_name, remote_node_name)
6474

    
6475
    return remote_node_name
6476

    
6477
  def _FindFaultyDisks(self, node_name):
6478
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
6479
                                    node_name, True)
6480

    
6481
  def CheckPrereq(self):
6482
    """Check prerequisites.
6483

6484
    This checks that the instance is in the cluster.
6485

6486
    """
6487
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
6488
    assert instance is not None, \
6489
      "Cannot retrieve locked instance %s" % self.instance_name
6490

    
6491
    if instance.disk_template != constants.DT_DRBD8:
6492
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
6493
                                 " instances", errors.ECODE_INVAL)
6494

    
6495
    if len(instance.secondary_nodes) != 1:
6496
      raise errors.OpPrereqError("The instance has a strange layout,"
6497
                                 " expected one secondary but found %d" %
6498
                                 len(instance.secondary_nodes),
6499
                                 errors.ECODE_FAULT)
6500

    
6501
    secondary_node = instance.secondary_nodes[0]
6502

    
6503
    if self.iallocator_name is None:
6504
      remote_node = self.remote_node
6505
    else:
6506
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
6507
                                       instance.name, instance.secondary_nodes)
6508

    
6509
    if remote_node is not None:
6510
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
6511
      assert self.remote_node_info is not None, \
6512
        "Cannot retrieve locked node %s" % remote_node
6513
    else:
6514
      self.remote_node_info = None
6515

    
6516
    if remote_node == self.instance.primary_node:
6517
      raise errors.OpPrereqError("The specified node is the primary node of"
6518
                                 " the instance.", errors.ECODE_INVAL)
6519

    
6520
    if remote_node == secondary_node:
6521
      raise errors.OpPrereqError("The specified node is already the"
6522
                                 " secondary node of the instance.",
6523
                                 errors.ECODE_INVAL)
6524

    
6525
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
6526
                                    constants.REPLACE_DISK_CHG):
6527
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
6528
                                 errors.ECODE_INVAL)
6529

    
6530
    if self.mode == constants.REPLACE_DISK_AUTO:
6531
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
6532
      faulty_secondary = self._FindFaultyDisks(secondary_node)
6533

    
6534
      if faulty_primary and faulty_secondary:
6535
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
6536
                                   " one node and can not be repaired"
6537
                                   " automatically" % self.instance_name,
6538
                                   errors.ECODE_STATE)
6539

    
6540
      if faulty_primary:
6541
        self.disks = faulty_primary
6542
        self.target_node = instance.primary_node
6543
        self.other_node = secondary_node
6544
        check_nodes = [self.target_node, self.other_node]
6545
      elif faulty_secondary:
6546
        self.disks = faulty_secondary
6547
        self.target_node = secondary_node
6548
        self.other_node = instance.primary_node
6549
        check_nodes = [self.target_node, self.other_node]
6550
      else:
6551
        self.disks = []
6552
        check_nodes = []
6553

    
6554
    else:
6555
      # Non-automatic modes
6556
      if self.mode == constants.REPLACE_DISK_PRI:
6557
        self.target_node = instance.primary_node
6558
        self.other_node = secondary_node
6559
        check_nodes = [self.target_node, self.other_node]
6560

    
6561
      elif self.mode == constants.REPLACE_DISK_SEC:
6562
        self.target_node = secondary_node
6563
        self.other_node = instance.primary_node
6564
        check_nodes = [self.target_node, self.other_node]
6565

    
6566
      elif self.mode == constants.REPLACE_DISK_CHG:
6567
        self.new_node = remote_node
6568
        self.other_node = instance.primary_node
6569
        self.target_node = secondary_node
6570
        check_nodes = [self.new_node, self.other_node]
6571

    
6572
        _CheckNodeNotDrained(self.lu, remote_node)
6573

    
6574
      else:
6575
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
6576
                                     self.mode)
6577

    
6578
      # If not specified all disks should be replaced
6579
      if not self.disks:
6580
        self.disks = range(len(self.instance.disks))
6581

    
6582
    for node in check_nodes:
6583
      _CheckNodeOnline(self.lu, node)
6584

    
6585
    # Check whether disks are valid
6586
    for disk_idx in self.disks:
6587
      instance.FindDisk(disk_idx)
6588

    
6589
    # Get secondary node IP addresses
6590
    node_2nd_ip = {}
6591

    
6592
    for node_name in [self.target_node, self.other_node, self.new_node]:
6593
      if node_name is not None:
6594
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
6595

    
6596
    self.node_secondary_ip = node_2nd_ip
6597

    
6598
  def Exec(self, feedback_fn):
6599
    """Execute disk replacement.
6600

6601
    This dispatches the disk replacement to the appropriate handler.
6602

6603
    """
6604
    if not self.disks:
6605
      feedback_fn("No disks need replacement")
6606
      return
6607

    
6608
    feedback_fn("Replacing disk(s) %s for %s" %
6609
                (", ".join([str(i) for i in self.disks]), self.instance.name))
6610

    
6611
    activate_disks = (not self.instance.admin_up)
6612

    
6613
    # Activate the instance disks if we're replacing them on a down instance
6614
    if activate_disks:
6615
      _StartInstanceDisks(self.lu, self.instance, True)
6616

    
6617
    try:
6618
      # Should we replace the secondary node?
6619
      if self.new_node is not None:
6620
        fn = self._ExecDrbd8Secondary
6621
      else:
6622
        fn = self._ExecDrbd8DiskOnly
6623

    
6624
      return fn(feedback_fn)
6625

    
6626
    finally:
6627
      # Deactivate the instance disks if we're replacing them on a
6628
      # down instance
6629
      if activate_disks:
6630
        _SafeShutdownInstanceDisks(self.lu, self.instance)
6631

    
6632
  def _CheckVolumeGroup(self, nodes):
6633
    self.lu.LogInfo("Checking volume groups")
6634

    
6635
    vgname = self.cfg.GetVGName()
6636

    
6637
    # Make sure volume group exists on all involved nodes
6638
    results = self.rpc.call_vg_list(nodes)
6639
    if not results:
6640
      raise errors.OpExecError("Can't list volume groups on the nodes")
6641

    
6642
    for node in nodes:
6643
      res = results[node]
6644
      res.Raise("Error checking node %s" % node)
6645
      if vgname not in res.payload:
6646
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
6647
                                 (vgname, node))
6648

    
6649
  def _CheckDisksExistence(self, nodes):
6650
    # Check disk existence
6651
    for idx, dev in enumerate(self.instance.disks):
6652
      if idx not in self.disks:
6653
        continue
6654

    
6655
      for node in nodes:
6656
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
6657
        self.cfg.SetDiskID(dev, node)
6658

    
6659
        result = self.rpc.call_blockdev_find(node, dev)
6660

    
6661
        msg = result.fail_msg
6662
        if msg or not result.payload:
6663
          if not msg:
6664
            msg = "disk not found"
6665
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
6666
                                   (idx, node, msg))
6667

    
6668
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
6669
    for idx, dev in enumerate(self.instance.disks):
6670
      if idx not in self.disks:
6671
        continue
6672

    
6673
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
6674
                      (idx, node_name))
6675

    
6676
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
6677
                                   ldisk=ldisk):
6678
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
6679
                                 " replace disks for instance %s" %
6680
                                 (node_name, self.instance.name))
6681

    
6682
  def _CreateNewStorage(self, node_name):
6683
    vgname = self.cfg.GetVGName()
6684
    iv_names = {}
6685

    
6686
    for idx, dev in enumerate(self.instance.disks):
6687
      if idx not in self.disks:
6688
        continue
6689

    
6690
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
6691

    
6692
      self.cfg.SetDiskID(dev, node_name)
6693

    
6694
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
6695
      names = _GenerateUniqueNames(self.lu, lv_names)
6696

    
6697
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
6698
                             logical_id=(vgname, names[0]))
6699
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6700
                             logical_id=(vgname, names[1]))
6701

    
6702
      new_lvs = [lv_data, lv_meta]
6703
      old_lvs = dev.children
6704
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
6705

    
6706
      # we pass force_create=True to force the LVM creation
6707
      for new_lv in new_lvs:
6708
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
6709
                        _GetInstanceInfoText(self.instance), False)
6710

    
6711
    return iv_names
6712

    
6713
  def _CheckDevices(self, node_name, iv_names):
6714
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
6715
      self.cfg.SetDiskID(dev, node_name)
6716

    
6717
      result = self.rpc.call_blockdev_find(node_name, dev)
6718

    
6719
      msg = result.fail_msg
6720
      if msg or not result.payload:
6721
        if not msg:
6722
          msg = "disk not found"
6723
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
6724
                                 (name, msg))
6725

    
6726
      if result.payload.is_degraded:
6727
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
6728

    
6729
  def _RemoveOldStorage(self, node_name, iv_names):
6730
    for name, (dev, old_lvs, _) in iv_names.iteritems():
6731
      self.lu.LogInfo("Remove logical volumes for %s" % name)
6732

    
6733
      for lv in old_lvs:
6734
        self.cfg.SetDiskID(lv, node_name)
6735

    
6736
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
6737
        if msg:
6738
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
6739
                             hint="remove unused LVs manually")
6740

    
6741
  def _ExecDrbd8DiskOnly(self, feedback_fn):
6742
    """Replace a disk on the primary or secondary for DRBD 8.
6743

6744
    The algorithm for replace is quite complicated:
6745

6746
      1. for each disk to be replaced:
6747

6748
        1. create new LVs on the target node with unique names
6749
        1. detach old LVs from the drbd device
6750
        1. rename old LVs to name_replaced.<time_t>
6751
        1. rename new LVs to old LVs
6752
        1. attach the new LVs (with the old names now) to the drbd device
6753

6754
      1. wait for sync across all devices
6755

6756
      1. for each modified disk:
6757

6758
        1. remove old LVs (which have the name name_replaces.<time_t>)
6759

6760
    Failures are not very well handled.
6761

6762
    """
6763
    steps_total = 6
6764

    
6765
    # Step: check device activation
6766
    self.lu.LogStep(1, steps_total, "Check device existence")
6767
    self._CheckDisksExistence([self.other_node, self.target_node])
6768
    self._CheckVolumeGroup([self.target_node, self.other_node])
6769

    
6770
    # Step: check other node consistency
6771
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6772
    self._CheckDisksConsistency(self.other_node,
6773
                                self.other_node == self.instance.primary_node,
6774
                                False)
6775

    
6776
    # Step: create new storage
6777
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6778
    iv_names = self._CreateNewStorage(self.target_node)
6779

    
6780
    # Step: for each lv, detach+rename*2+attach
6781
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6782
    for dev, old_lvs, new_lvs in iv_names.itervalues():
6783
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
6784

    
6785
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
6786
                                                     old_lvs)
6787
      result.Raise("Can't detach drbd from local storage on node"
6788
                   " %s for device %s" % (self.target_node, dev.iv_name))
6789
      #dev.children = []
6790
      #cfg.Update(instance)
6791

    
6792
      # ok, we created the new LVs, so now we know we have the needed
6793
      # storage; as such, we proceed on the target node to rename
6794
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
6795
      # using the assumption that logical_id == physical_id (which in
6796
      # turn is the unique_id on that node)
6797

    
6798
      # FIXME(iustin): use a better name for the replaced LVs
6799
      temp_suffix = int(time.time())
6800
      ren_fn = lambda d, suff: (d.physical_id[0],
6801
                                d.physical_id[1] + "_replaced-%s" % suff)
6802

    
6803
      # Build the rename list based on what LVs exist on the node
6804
      rename_old_to_new = []
6805
      for to_ren in old_lvs:
6806
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
6807
        if not result.fail_msg and result.payload:
6808
          # device exists
6809
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
6810

    
6811
      self.lu.LogInfo("Renaming the old LVs on the target node")
6812
      result = self.rpc.call_blockdev_rename(self.target_node,
6813
                                             rename_old_to_new)
6814
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
6815

    
6816
      # Now we rename the new LVs to the old LVs
6817
      self.lu.LogInfo("Renaming the new LVs on the target node")
6818
      rename_new_to_old = [(new, old.physical_id)
6819
                           for old, new in zip(old_lvs, new_lvs)]
6820
      result = self.rpc.call_blockdev_rename(self.target_node,
6821
                                             rename_new_to_old)
6822
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
6823

    
6824
      for old, new in zip(old_lvs, new_lvs):
6825
        new.logical_id = old.logical_id
6826
        self.cfg.SetDiskID(new, self.target_node)
6827

    
6828
      for disk in old_lvs:
6829
        disk.logical_id = ren_fn(disk, temp_suffix)
6830
        self.cfg.SetDiskID(disk, self.target_node)
6831

    
6832
      # Now that the new lvs have the old name, we can add them to the device
6833
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
6834
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
6835
                                                  new_lvs)
6836
      msg = result.fail_msg
6837
      if msg:
6838
        for new_lv in new_lvs:
6839
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
6840
                                               new_lv).fail_msg
6841
          if msg2:
6842
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
6843
                               hint=("cleanup manually the unused logical"
6844
                                     "volumes"))
6845
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
6846

    
6847
      dev.children = new_lvs
6848

    
6849
      self.cfg.Update(self.instance, feedback_fn)
6850

    
6851
    # Wait for sync
6852
    # This can fail as the old devices are degraded and _WaitForSync
6853
    # does a combined result over all disks, so we don't check its return value
6854
    self.lu.LogStep(5, steps_total, "Sync devices")
6855
    _WaitForSync(self.lu, self.instance, unlock=True)
6856

    
6857
    # Check all devices manually
6858
    self._CheckDevices(self.instance.primary_node, iv_names)
6859

    
6860
    # Step: remove old storage
6861
    self.lu.LogStep(6, steps_total, "Removing old storage")
6862
    self._RemoveOldStorage(self.target_node, iv_names)
6863

    
6864
  def _ExecDrbd8Secondary(self, feedback_fn):
6865
    """Replace the secondary node for DRBD 8.
6866

6867
    The algorithm for replace is quite complicated:
6868
      - for all disks of the instance:
6869
        - create new LVs on the new node with same names
6870
        - shutdown the drbd device on the old secondary
6871
        - disconnect the drbd network on the primary
6872
        - create the drbd device on the new secondary
6873
        - network attach the drbd on the primary, using an artifice:
6874
          the drbd code for Attach() will connect to the network if it
6875
          finds a device which is connected to the good local disks but
6876
          not network enabled
6877
      - wait for sync across all devices
6878
      - remove all disks from the old secondary
6879

6880
    Failures are not very well handled.
6881

6882
    """
6883
    steps_total = 6
6884

    
6885
    # Step: check device activation
6886
    self.lu.LogStep(1, steps_total, "Check device existence")
6887
    self._CheckDisksExistence([self.instance.primary_node])
6888
    self._CheckVolumeGroup([self.instance.primary_node])
6889

    
6890
    # Step: check other node consistency
6891
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6892
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
6893

    
6894
    # Step: create new storage
6895
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6896
    for idx, dev in enumerate(self.instance.disks):
6897
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
6898
                      (self.new_node, idx))
6899
      # we pass force_create=True to force LVM creation
6900
      for new_lv in dev.children:
6901
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
6902
                        _GetInstanceInfoText(self.instance), False)
6903

    
6904
    # Step 4: dbrd minors and drbd setups changes
6905
    # after this, we must manually remove the drbd minors on both the
6906
    # error and the success paths
6907
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6908
    minors = self.cfg.AllocateDRBDMinor([self.new_node
6909
                                         for dev in self.instance.disks],
6910
                                        self.instance.name)
6911
    logging.debug("Allocated minors %r", minors)
6912

    
6913
    iv_names = {}
6914
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
6915
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
6916
                      (self.new_node, idx))
6917
      # create new devices on new_node; note that we create two IDs:
6918
      # one without port, so the drbd will be activated without
6919
      # networking information on the new node at this stage, and one
6920
      # with network, for the latter activation in step 4
6921
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
6922
      if self.instance.primary_node == o_node1:
6923
        p_minor = o_minor1
6924
      else:
6925
        p_minor = o_minor2
6926

    
6927
      new_alone_id = (self.instance.primary_node, self.new_node, None,
6928
                      p_minor, new_minor, o_secret)
6929
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
6930
                    p_minor, new_minor, o_secret)
6931

    
6932
      iv_names[idx] = (dev, dev.children, new_net_id)
6933
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
6934
                    new_net_id)
6935
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
6936
                              logical_id=new_alone_id,
6937
                              children=dev.children,
6938
                              size=dev.size)
6939
      try:
6940
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
6941
                              _GetInstanceInfoText(self.instance), False)
6942
      except errors.GenericError:
6943
        self.cfg.ReleaseDRBDMinors(self.instance.name)
6944
        raise
6945

    
6946
    # We have new devices, shutdown the drbd on the old secondary
6947
    for idx, dev in enumerate(self.instance.disks):
6948
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
6949
      self.cfg.SetDiskID(dev, self.target_node)
6950
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
6951
      if msg:
6952
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
6953
                           "node: %s" % (idx, msg),
6954
                           hint=("Please cleanup this device manually as"
6955
                                 " soon as possible"))
6956

    
6957
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
6958
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
6959
                                               self.node_secondary_ip,
6960
                                               self.instance.disks)\
6961
                                              [self.instance.primary_node]
6962

    
6963
    msg = result.fail_msg
6964
    if msg:
6965
      # detaches didn't succeed (unlikely)
6966
      self.cfg.ReleaseDRBDMinors(self.instance.name)
6967
      raise errors.OpExecError("Can't detach the disks from the network on"
6968
                               " old node: %s" % (msg,))
6969

    
6970
    # if we managed to detach at least one, we update all the disks of
6971
    # the instance to point to the new secondary
6972
    self.lu.LogInfo("Updating instance configuration")
6973
    for dev, _, new_logical_id in iv_names.itervalues():
6974
      dev.logical_id = new_logical_id
6975
      self.cfg.SetDiskID(dev, self.instance.primary_node)
6976

    
6977
    self.cfg.Update(self.instance, feedback_fn)
6978

    
6979
    # and now perform the drbd attach
6980
    self.lu.LogInfo("Attaching primary drbds to new secondary"
6981
                    " (standalone => connected)")
6982
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
6983
                                            self.new_node],
6984
                                           self.node_secondary_ip,
6985
                                           self.instance.disks,
6986
                                           self.instance.name,
6987
                                           False)
6988
    for to_node, to_result in result.items():
6989
      msg = to_result.fail_msg
6990
      if msg:
6991
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
6992
                           to_node, msg,
6993
                           hint=("please do a gnt-instance info to see the"
6994
                                 " status of disks"))
6995

    
6996
    # Wait for sync
6997
    # This can fail as the old devices are degraded and _WaitForSync
6998
    # does a combined result over all disks, so we don't check its return value
6999
    self.lu.LogStep(5, steps_total, "Sync devices")
7000
    _WaitForSync(self.lu, self.instance, unlock=True)
7001

    
7002
    # Check all devices manually
7003
    self._CheckDevices(self.instance.primary_node, iv_names)
7004

    
7005
    # Step: remove old storage
7006
    self.lu.LogStep(6, steps_total, "Removing old storage")
7007
    self._RemoveOldStorage(self.target_node, iv_names)
7008

    
7009

    
7010
class LURepairNodeStorage(NoHooksLU):
7011
  """Repairs the volume group on a node.
7012

7013
  """
7014
  _OP_REQP = ["node_name"]
7015
  REQ_BGL = False
7016

    
7017
  def CheckArguments(self):
7018
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
7019
    if node_name is None:
7020
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
7021
                                 errors.ECODE_NOENT)
7022

    
7023
    self.op.node_name = node_name
7024

    
7025
  def ExpandNames(self):
7026
    self.needed_locks = {
7027
      locking.LEVEL_NODE: [self.op.node_name],
7028
      }
7029

    
7030
  def _CheckFaultyDisks(self, instance, node_name):
7031
    """Ensure faulty disks abort the opcode or at least warn."""
7032
    try:
7033
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
7034
                                  node_name, True):
7035
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
7036
                                   " node '%s'" % (instance.name, node_name),
7037
                                   errors.ECODE_STATE)
7038
    except errors.OpPrereqError, err:
7039
      if self.op.ignore_consistency:
7040
        self.proc.LogWarning(str(err.args[0]))
7041
      else:
7042
        raise
7043

    
7044
  def CheckPrereq(self):
7045
    """Check prerequisites.
7046

7047
    """
7048
    storage_type = self.op.storage_type
7049

    
7050
    if (constants.SO_FIX_CONSISTENCY not in
7051
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
7052
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
7053
                                 " repaired" % storage_type,
7054
                                 errors.ECODE_INVAL)
7055

    
7056
    # Check whether any instance on this node has faulty disks
7057
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
7058
      if not inst.admin_up:
7059
        continue
7060
      check_nodes = set(inst.all_nodes)
7061
      check_nodes.discard(self.op.node_name)
7062
      for inst_node_name in check_nodes:
7063
        self._CheckFaultyDisks(inst, inst_node_name)
7064

    
7065
  def Exec(self, feedback_fn):
7066
    feedback_fn("Repairing storage unit '%s' on %s ..." %
7067
                (self.op.name, self.op.node_name))
7068

    
7069
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
7070
    result = self.rpc.call_storage_execute(self.op.node_name,
7071
                                           self.op.storage_type, st_args,
7072
                                           self.op.name,
7073
                                           constants.SO_FIX_CONSISTENCY)
7074
    result.Raise("Failed to repair storage unit '%s' on %s" %
7075
                 (self.op.name, self.op.node_name))
7076

    
7077

    
7078
class LUGrowDisk(LogicalUnit):
7079
  """Grow a disk of an instance.
7080

7081
  """
7082
  HPATH = "disk-grow"
7083
  HTYPE = constants.HTYPE_INSTANCE
7084
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
7085
  REQ_BGL = False
7086

    
7087
  def ExpandNames(self):
7088
    self._ExpandAndLockInstance()
7089
    self.needed_locks[locking.LEVEL_NODE] = []
7090
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7091

    
7092
  def DeclareLocks(self, level):
7093
    if level == locking.LEVEL_NODE:
7094
      self._LockInstancesNodes()
7095

    
7096
  def BuildHooksEnv(self):
7097
    """Build hooks env.
7098

7099
    This runs on the master, the primary and all the secondaries.
7100

7101
    """
7102
    env = {
7103
      "DISK": self.op.disk,
7104
      "AMOUNT": self.op.amount,
7105
      }
7106
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7107
    nl = [
7108
      self.cfg.GetMasterNode(),
7109
      self.instance.primary_node,
7110
      ]
7111
    return env, nl, nl
7112

    
7113
  def CheckPrereq(self):
7114
    """Check prerequisites.
7115

7116
    This checks that the instance is in the cluster.
7117

7118
    """
7119
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7120
    assert instance is not None, \
7121
      "Cannot retrieve locked instance %s" % self.op.instance_name
7122
    nodenames = list(instance.all_nodes)
7123
    for node in nodenames:
7124
      _CheckNodeOnline(self, node)
7125

    
7126

    
7127
    self.instance = instance
7128

    
7129
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
7130
      raise errors.OpPrereqError("Instance's disk layout does not support"
7131
                                 " growing.", errors.ECODE_INVAL)
7132

    
7133
    self.disk = instance.FindDisk(self.op.disk)
7134

    
7135
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
7136
                                       instance.hypervisor)
7137
    for node in nodenames:
7138
      info = nodeinfo[node]
7139
      info.Raise("Cannot get current information from node %s" % node)
7140
      vg_free = info.payload.get('vg_free', None)
7141
      if not isinstance(vg_free, int):
7142
        raise errors.OpPrereqError("Can't compute free disk space on"
7143
                                   " node %s" % node, errors.ECODE_ENVIRON)
7144
      if self.op.amount > vg_free:
7145
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
7146
                                   " %d MiB available, %d MiB required" %
7147
                                   (node, vg_free, self.op.amount),
7148
                                   errors.ECODE_NORES)
7149

    
7150
  def Exec(self, feedback_fn):
7151
    """Execute disk grow.
7152

7153
    """
7154
    instance = self.instance
7155
    disk = self.disk
7156
    for node in instance.all_nodes:
7157
      self.cfg.SetDiskID(disk, node)
7158
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
7159
      result.Raise("Grow request failed to node %s" % node)
7160
    disk.RecordGrow(self.op.amount)
7161
    self.cfg.Update(instance, feedback_fn)
7162
    if self.op.wait_for_sync:
7163
      disk_abort = not _WaitForSync(self, instance)
7164
      if disk_abort:
7165
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
7166
                             " status.\nPlease check the instance.")
7167

    
7168

    
7169
class LUQueryInstanceData(NoHooksLU):
7170
  """Query runtime instance data.
7171

7172
  """
7173
  _OP_REQP = ["instances", "static"]
7174
  REQ_BGL = False
7175

    
7176
  def ExpandNames(self):
7177
    self.needed_locks = {}
7178
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
7179

    
7180
    if not isinstance(self.op.instances, list):
7181
      raise errors.OpPrereqError("Invalid argument type 'instances'",
7182
                                 errors.ECODE_INVAL)
7183

    
7184
    if self.op.instances:
7185
      self.wanted_names = []
7186
      for name in self.op.instances:
7187
        full_name = self.cfg.ExpandInstanceName(name)
7188
        if full_name is None:
7189
          raise errors.OpPrereqError("Instance '%s' not known" % name,
7190
                                     errors.ECODE_NOENT)
7191
        self.wanted_names.append(full_name)
7192
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
7193
    else:
7194
      self.wanted_names = None
7195
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
7196

    
7197
    self.needed_locks[locking.LEVEL_NODE] = []
7198
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7199

    
7200
  def DeclareLocks(self, level):
7201
    if level == locking.LEVEL_NODE:
7202
      self._LockInstancesNodes()
7203

    
7204
  def CheckPrereq(self):
7205
    """Check prerequisites.
7206

7207
    This only checks the optional instance list against the existing names.
7208

7209
    """
7210
    if self.wanted_names is None:
7211
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
7212

    
7213
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
7214
                             in self.wanted_names]
7215
    return
7216

    
7217
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
7218
    """Returns the status of a block device
7219

7220
    """
7221
    if self.op.static or not node:
7222
      return None
7223

    
7224
    self.cfg.SetDiskID(dev, node)
7225

    
7226
    result = self.rpc.call_blockdev_find(node, dev)
7227
    if result.offline:
7228
      return None
7229

    
7230
    result.Raise("Can't compute disk status for %s" % instance_name)
7231

    
7232
    status = result.payload
7233
    if status is None:
7234
      return None
7235

    
7236
    return (status.dev_path, status.major, status.minor,
7237
            status.sync_percent, status.estimated_time,
7238
            status.is_degraded, status.ldisk_status)
7239

    
7240
  def _ComputeDiskStatus(self, instance, snode, dev):
7241
    """Compute block device status.
7242

7243
    """
7244
    if dev.dev_type in constants.LDS_DRBD:
7245
      # we change the snode then (otherwise we use the one passed in)
7246
      if dev.logical_id[0] == instance.primary_node:
7247
        snode = dev.logical_id[1]
7248
      else:
7249
        snode = dev.logical_id[0]
7250

    
7251
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
7252
                                              instance.name, dev)
7253
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
7254

    
7255
    if dev.children:
7256
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
7257
                      for child in dev.children]
7258
    else:
7259
      dev_children = []
7260

    
7261
    data = {
7262
      "iv_name": dev.iv_name,
7263
      "dev_type": dev.dev_type,
7264
      "logical_id": dev.logical_id,
7265
      "physical_id": dev.physical_id,
7266
      "pstatus": dev_pstatus,
7267
      "sstatus": dev_sstatus,
7268
      "children": dev_children,
7269
      "mode": dev.mode,
7270
      "size": dev.size,
7271
      }
7272

    
7273
    return data
7274

    
7275
  def Exec(self, feedback_fn):
7276
    """Gather and return data"""
7277
    result = {}
7278

    
7279
    cluster = self.cfg.GetClusterInfo()
7280

    
7281
    for instance in self.wanted_instances:
7282
      if not self.op.static:
7283
        remote_info = self.rpc.call_instance_info(instance.primary_node,
7284
                                                  instance.name,
7285
                                                  instance.hypervisor)
7286
        remote_info.Raise("Error checking node %s" % instance.primary_node)
7287
        remote_info = remote_info.payload
7288
        if remote_info and "state" in remote_info:
7289
          remote_state = "up"
7290
        else:
7291
          remote_state = "down"
7292
      else:
7293
        remote_state = None
7294
      if instance.admin_up:
7295
        config_state = "up"
7296
      else:
7297
        config_state = "down"
7298

    
7299
      disks = [self._ComputeDiskStatus(instance, None, device)
7300
               for device in instance.disks]
7301

    
7302
      idict = {
7303
        "name": instance.name,
7304
        "config_state": config_state,
7305
        "run_state": remote_state,
7306
        "pnode": instance.primary_node,
7307
        "snodes": instance.secondary_nodes,
7308
        "os": instance.os,
7309
        # this happens to be the same format used for hooks
7310
        "nics": _NICListToTuple(self, instance.nics),
7311
        "disks": disks,
7312
        "hypervisor": instance.hypervisor,
7313
        "network_port": instance.network_port,
7314
        "hv_instance": instance.hvparams,
7315
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
7316
        "be_instance": instance.beparams,
7317
        "be_actual": cluster.FillBE(instance),
7318
        "serial_no": instance.serial_no,
7319
        "mtime": instance.mtime,
7320
        "ctime": instance.ctime,
7321
        "uuid": instance.uuid,
7322
        }
7323

    
7324
      result[instance.name] = idict
7325

    
7326
    return result
7327

    
7328

    
7329
class LUSetInstanceParams(LogicalUnit):
7330
  """Modifies an instances's parameters.
7331

7332
  """
7333
  HPATH = "instance-modify"
7334
  HTYPE = constants.HTYPE_INSTANCE
7335
  _OP_REQP = ["instance_name"]
7336
  REQ_BGL = False
7337

    
7338
  def CheckArguments(self):
7339
    if not hasattr(self.op, 'nics'):
7340
      self.op.nics = []
7341
    if not hasattr(self.op, 'disks'):
7342
      self.op.disks = []
7343
    if not hasattr(self.op, 'beparams'):
7344
      self.op.beparams = {}
7345
    if not hasattr(self.op, 'hvparams'):
7346
      self.op.hvparams = {}
7347
    self.op.force = getattr(self.op, "force", False)
7348
    if not (self.op.nics or self.op.disks or
7349
            self.op.hvparams or self.op.beparams):
7350
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
7351

    
7352
    if self.op.hvparams:
7353
      _CheckGlobalHvParams(self.op.hvparams)
7354

    
7355
    # Disk validation
7356
    disk_addremove = 0
7357
    for disk_op, disk_dict in self.op.disks:
7358
      if disk_op == constants.DDM_REMOVE:
7359
        disk_addremove += 1
7360
        continue
7361
      elif disk_op == constants.DDM_ADD:
7362
        disk_addremove += 1
7363
      else:
7364
        if not isinstance(disk_op, int):
7365
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
7366
        if not isinstance(disk_dict, dict):
7367
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
7368
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7369

    
7370
      if disk_op == constants.DDM_ADD:
7371
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
7372
        if mode not in constants.DISK_ACCESS_SET:
7373
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
7374
                                     errors.ECODE_INVAL)
7375
        size = disk_dict.get('size', None)
7376
        if size is None:
7377
          raise errors.OpPrereqError("Required disk parameter size missing",
7378
                                     errors.ECODE_INVAL)
7379
        try:
7380
          size = int(size)
7381
        except ValueError, err:
7382
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
7383
                                     str(err), errors.ECODE_INVAL)
7384
        disk_dict['size'] = size
7385
      else:
7386
        # modification of disk
7387
        if 'size' in disk_dict:
7388
          raise errors.OpPrereqError("Disk size change not possible, use"
7389
                                     " grow-disk", errors.ECODE_INVAL)
7390

    
7391
    if disk_addremove > 1:
7392
      raise errors.OpPrereqError("Only one disk add or remove operation"
7393
                                 " supported at a time", errors.ECODE_INVAL)
7394

    
7395
    # NIC validation
7396
    nic_addremove = 0
7397
    for nic_op, nic_dict in self.op.nics:
7398
      if nic_op == constants.DDM_REMOVE:
7399
        nic_addremove += 1
7400
        continue
7401
      elif nic_op == constants.DDM_ADD:
7402
        nic_addremove += 1
7403
      else:
7404
        if not isinstance(nic_op, int):
7405
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
7406
        if not isinstance(nic_dict, dict):
7407
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
7408
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7409

    
7410
      # nic_dict should be a dict
7411
      nic_ip = nic_dict.get('ip', None)
7412
      if nic_ip is not None:
7413
        if nic_ip.lower() == constants.VALUE_NONE:
7414
          nic_dict['ip'] = None
7415
        else:
7416
          if not utils.IsValidIP(nic_ip):
7417
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
7418
                                       errors.ECODE_INVAL)
7419

    
7420
      nic_bridge = nic_dict.get('bridge', None)
7421
      nic_link = nic_dict.get('link', None)
7422
      if nic_bridge and nic_link:
7423
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7424
                                   " at the same time", errors.ECODE_INVAL)
7425
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
7426
        nic_dict['bridge'] = None
7427
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
7428
        nic_dict['link'] = None
7429

    
7430
      if nic_op == constants.DDM_ADD:
7431
        nic_mac = nic_dict.get('mac', None)
7432
        if nic_mac is None:
7433
          nic_dict['mac'] = constants.VALUE_AUTO
7434

    
7435
      if 'mac' in nic_dict:
7436
        nic_mac = nic_dict['mac']
7437
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7438
          if not utils.IsValidMac(nic_mac):
7439
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac,
7440
                                       errors.ECODE_INVAL)
7441
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
7442
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
7443
                                     " modifying an existing nic",
7444
                                     errors.ECODE_INVAL)
7445

    
7446
    if nic_addremove > 1:
7447
      raise errors.OpPrereqError("Only one NIC add or remove operation"
7448
                                 " supported at a time", errors.ECODE_INVAL)
7449

    
7450
  def ExpandNames(self):
7451
    self._ExpandAndLockInstance()
7452
    self.needed_locks[locking.LEVEL_NODE] = []
7453
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7454

    
7455
  def DeclareLocks(self, level):
7456
    if level == locking.LEVEL_NODE:
7457
      self._LockInstancesNodes()
7458

    
7459
  def BuildHooksEnv(self):
7460
    """Build hooks env.
7461

7462
    This runs on the master, primary and secondaries.
7463

7464
    """
7465
    args = dict()
7466
    if constants.BE_MEMORY in self.be_new:
7467
      args['memory'] = self.be_new[constants.BE_MEMORY]
7468
    if constants.BE_VCPUS in self.be_new:
7469
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
7470
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
7471
    # information at all.
7472
    if self.op.nics:
7473
      args['nics'] = []
7474
      nic_override = dict(self.op.nics)
7475
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
7476
      for idx, nic in enumerate(self.instance.nics):
7477
        if idx in nic_override:
7478
          this_nic_override = nic_override[idx]
7479
        else:
7480
          this_nic_override = {}
7481
        if 'ip' in this_nic_override:
7482
          ip = this_nic_override['ip']
7483
        else:
7484
          ip = nic.ip
7485
        if 'mac' in this_nic_override:
7486
          mac = this_nic_override['mac']
7487
        else:
7488
          mac = nic.mac
7489
        if idx in self.nic_pnew:
7490
          nicparams = self.nic_pnew[idx]
7491
        else:
7492
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
7493
        mode = nicparams[constants.NIC_MODE]
7494
        link = nicparams[constants.NIC_LINK]
7495
        args['nics'].append((ip, mac, mode, link))
7496
      if constants.DDM_ADD in nic_override:
7497
        ip = nic_override[constants.DDM_ADD].get('ip', None)
7498
        mac = nic_override[constants.DDM_ADD]['mac']
7499
        nicparams = self.nic_pnew[constants.DDM_ADD]
7500
        mode = nicparams[constants.NIC_MODE]
7501
        link = nicparams[constants.NIC_LINK]
7502
        args['nics'].append((ip, mac, mode, link))
7503
      elif constants.DDM_REMOVE in nic_override:
7504
        del args['nics'][-1]
7505

    
7506
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
7507
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7508
    return env, nl, nl
7509

    
7510
  def _GetUpdatedParams(self, old_params, update_dict,
7511
                        default_values, parameter_types):
7512
    """Return the new params dict for the given params.
7513

7514
    @type old_params: dict
7515
    @param old_params: old parameters
7516
    @type update_dict: dict
7517
    @param update_dict: dict containing new parameter values,
7518
                        or constants.VALUE_DEFAULT to reset the
7519
                        parameter to its default value
7520
    @type default_values: dict
7521
    @param default_values: default values for the filled parameters
7522
    @type parameter_types: dict
7523
    @param parameter_types: dict mapping target dict keys to types
7524
                            in constants.ENFORCEABLE_TYPES
7525
    @rtype: (dict, dict)
7526
    @return: (new_parameters, filled_parameters)
7527

7528
    """
7529
    params_copy = copy.deepcopy(old_params)
7530
    for key, val in update_dict.iteritems():
7531
      if val == constants.VALUE_DEFAULT:
7532
        try:
7533
          del params_copy[key]
7534
        except KeyError:
7535
          pass
7536
      else:
7537
        params_copy[key] = val
7538
    utils.ForceDictType(params_copy, parameter_types)
7539
    params_filled = objects.FillDict(default_values, params_copy)
7540
    return (params_copy, params_filled)
7541

    
7542
  def CheckPrereq(self):
7543
    """Check prerequisites.
7544

7545
    This only checks the instance list against the existing names.
7546

7547
    """
7548
    self.force = self.op.force
7549

    
7550
    # checking the new params on the primary/secondary nodes
7551

    
7552
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7553
    cluster = self.cluster = self.cfg.GetClusterInfo()
7554
    assert self.instance is not None, \
7555
      "Cannot retrieve locked instance %s" % self.op.instance_name
7556
    pnode = instance.primary_node
7557
    nodelist = list(instance.all_nodes)
7558

    
7559
    # hvparams processing
7560
    if self.op.hvparams:
7561
      i_hvdict, hv_new = self._GetUpdatedParams(
7562
                             instance.hvparams, self.op.hvparams,
7563
                             cluster.hvparams[instance.hypervisor],
7564
                             constants.HVS_PARAMETER_TYPES)
7565
      # local check
7566
      hypervisor.GetHypervisor(
7567
        instance.hypervisor).CheckParameterSyntax(hv_new)
7568
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
7569
      self.hv_new = hv_new # the new actual values
7570
      self.hv_inst = i_hvdict # the new dict (without defaults)
7571
    else:
7572
      self.hv_new = self.hv_inst = {}
7573

    
7574
    # beparams processing
7575
    if self.op.beparams:
7576
      i_bedict, be_new = self._GetUpdatedParams(
7577
                             instance.beparams, self.op.beparams,
7578
                             cluster.beparams[constants.PP_DEFAULT],
7579
                             constants.BES_PARAMETER_TYPES)
7580
      self.be_new = be_new # the new actual values
7581
      self.be_inst = i_bedict # the new dict (without defaults)
7582
    else:
7583
      self.be_new = self.be_inst = {}
7584

    
7585
    self.warn = []
7586

    
7587
    if constants.BE_MEMORY in self.op.beparams and not self.force:
7588
      mem_check_list = [pnode]
7589
      if be_new[constants.BE_AUTO_BALANCE]:
7590
        # either we changed auto_balance to yes or it was from before
7591
        mem_check_list.extend(instance.secondary_nodes)
7592
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
7593
                                                  instance.hypervisor)
7594
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
7595
                                         instance.hypervisor)
7596
      pninfo = nodeinfo[pnode]
7597
      msg = pninfo.fail_msg
7598
      if msg:
7599
        # Assume the primary node is unreachable and go ahead
7600
        self.warn.append("Can't get info from primary node %s: %s" %
7601
                         (pnode,  msg))
7602
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
7603
        self.warn.append("Node data from primary node %s doesn't contain"
7604
                         " free memory information" % pnode)
7605
      elif instance_info.fail_msg:
7606
        self.warn.append("Can't get instance runtime information: %s" %
7607
                        instance_info.fail_msg)
7608
      else:
7609
        if instance_info.payload:
7610
          current_mem = int(instance_info.payload['memory'])
7611
        else:
7612
          # Assume instance not running
7613
          # (there is a slight race condition here, but it's not very probable,
7614
          # and we have no other way to check)
7615
          current_mem = 0
7616
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
7617
                    pninfo.payload['memory_free'])
7618
        if miss_mem > 0:
7619
          raise errors.OpPrereqError("This change will prevent the instance"
7620
                                     " from starting, due to %d MB of memory"
7621
                                     " missing on its primary node" % miss_mem,
7622
                                     errors.ECODE_NORES)
7623

    
7624
      if be_new[constants.BE_AUTO_BALANCE]:
7625
        for node, nres in nodeinfo.items():
7626
          if node not in instance.secondary_nodes:
7627
            continue
7628
          msg = nres.fail_msg
7629
          if msg:
7630
            self.warn.append("Can't get info from secondary node %s: %s" %
7631
                             (node, msg))
7632
          elif not isinstance(nres.payload.get('memory_free', None), int):
7633
            self.warn.append("Secondary node %s didn't return free"
7634
                             " memory information" % node)
7635
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
7636
            self.warn.append("Not enough memory to failover instance to"
7637
                             " secondary node %s" % node)
7638

    
7639
    # NIC processing
7640
    self.nic_pnew = {}
7641
    self.nic_pinst = {}
7642
    for nic_op, nic_dict in self.op.nics:
7643
      if nic_op == constants.DDM_REMOVE:
7644
        if not instance.nics:
7645
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
7646
                                     errors.ECODE_INVAL)
7647
        continue
7648
      if nic_op != constants.DDM_ADD:
7649
        # an existing nic
7650
        if nic_op < 0 or nic_op >= len(instance.nics):
7651
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
7652
                                     " are 0 to %d" %
7653
                                     (nic_op, len(instance.nics)),
7654
                                     errors.ECODE_INVAL)
7655
        old_nic_params = instance.nics[nic_op].nicparams
7656
        old_nic_ip = instance.nics[nic_op].ip
7657
      else:
7658
        old_nic_params = {}
7659
        old_nic_ip = None
7660

    
7661
      update_params_dict = dict([(key, nic_dict[key])
7662
                                 for key in constants.NICS_PARAMETERS
7663
                                 if key in nic_dict])
7664

    
7665
      if 'bridge' in nic_dict:
7666
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
7667

    
7668
      new_nic_params, new_filled_nic_params = \
7669
          self._GetUpdatedParams(old_nic_params, update_params_dict,
7670
                                 cluster.nicparams[constants.PP_DEFAULT],
7671
                                 constants.NICS_PARAMETER_TYPES)
7672
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
7673
      self.nic_pinst[nic_op] = new_nic_params
7674
      self.nic_pnew[nic_op] = new_filled_nic_params
7675
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
7676

    
7677
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
7678
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
7679
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
7680
        if msg:
7681
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
7682
          if self.force:
7683
            self.warn.append(msg)
7684
          else:
7685
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
7686
      if new_nic_mode == constants.NIC_MODE_ROUTED:
7687
        if 'ip' in nic_dict:
7688
          nic_ip = nic_dict['ip']
7689
        else:
7690
          nic_ip = old_nic_ip
7691
        if nic_ip is None:
7692
          raise errors.OpPrereqError('Cannot set the nic ip to None'
7693
                                     ' on a routed nic', errors.ECODE_INVAL)
7694
      if 'mac' in nic_dict:
7695
        nic_mac = nic_dict['mac']
7696
        if nic_mac is None:
7697
          raise errors.OpPrereqError('Cannot set the nic mac to None',
7698
                                     errors.ECODE_INVAL)
7699
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7700
          # otherwise generate the mac
7701
          nic_dict['mac'] = self.cfg.GenerateMAC()
7702
        else:
7703
          # or validate/reserve the current one
7704
          if self.cfg.IsMacInUse(nic_mac):
7705
            raise errors.OpPrereqError("MAC address %s already in use"
7706
                                       " in cluster" % nic_mac,
7707
                                       errors.ECODE_NOTUNIQUE)
7708

    
7709
    # DISK processing
7710
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
7711
      raise errors.OpPrereqError("Disk operations not supported for"
7712
                                 " diskless instances",
7713
                                 errors.ECODE_INVAL)
7714
    for disk_op, disk_dict in self.op.disks:
7715
      if disk_op == constants.DDM_REMOVE:
7716
        if len(instance.disks) == 1:
7717
          raise errors.OpPrereqError("Cannot remove the last disk of"
7718
                                     " an instance",
7719
                                     errors.ECODE_INVAL)
7720
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
7721
        ins_l = ins_l[pnode]
7722
        msg = ins_l.fail_msg
7723
        if msg:
7724
          raise errors.OpPrereqError("Can't contact node %s: %s" %
7725
                                     (pnode, msg), errors.ECODE_ENVIRON)
7726
        if instance.name in ins_l.payload:
7727
          raise errors.OpPrereqError("Instance is running, can't remove"
7728
                                     " disks.", errors.ECODE_STATE)
7729

    
7730
      if (disk_op == constants.DDM_ADD and
7731
          len(instance.nics) >= constants.MAX_DISKS):
7732
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
7733
                                   " add more" % constants.MAX_DISKS,
7734
                                   errors.ECODE_STATE)
7735
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
7736
        # an existing disk
7737
        if disk_op < 0 or disk_op >= len(instance.disks):
7738
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
7739
                                     " are 0 to %d" %
7740
                                     (disk_op, len(instance.disks)),
7741
                                     errors.ECODE_INVAL)
7742

    
7743
    return
7744

    
7745
  def Exec(self, feedback_fn):
7746
    """Modifies an instance.
7747

7748
    All parameters take effect only at the next restart of the instance.
7749

7750
    """
7751
    # Process here the warnings from CheckPrereq, as we don't have a
7752
    # feedback_fn there.
7753
    for warn in self.warn:
7754
      feedback_fn("WARNING: %s" % warn)
7755

    
7756
    result = []
7757
    instance = self.instance
7758
    cluster = self.cluster
7759
    # disk changes
7760
    for disk_op, disk_dict in self.op.disks:
7761
      if disk_op == constants.DDM_REMOVE:
7762
        # remove the last disk
7763
        device = instance.disks.pop()
7764
        device_idx = len(instance.disks)
7765
        for node, disk in device.ComputeNodeTree(instance.primary_node):
7766
          self.cfg.SetDiskID(disk, node)
7767
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
7768
          if msg:
7769
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
7770
                            " continuing anyway", device_idx, node, msg)
7771
        result.append(("disk/%d" % device_idx, "remove"))
7772
      elif disk_op == constants.DDM_ADD:
7773
        # add a new disk
7774
        if instance.disk_template == constants.DT_FILE:
7775
          file_driver, file_path = instance.disks[0].logical_id
7776
          file_path = os.path.dirname(file_path)
7777
        else:
7778
          file_driver = file_path = None
7779
        disk_idx_base = len(instance.disks)
7780
        new_disk = _GenerateDiskTemplate(self,
7781
                                         instance.disk_template,
7782
                                         instance.name, instance.primary_node,
7783
                                         instance.secondary_nodes,
7784
                                         [disk_dict],
7785
                                         file_path,
7786
                                         file_driver,
7787
                                         disk_idx_base)[0]
7788
        instance.disks.append(new_disk)
7789
        info = _GetInstanceInfoText(instance)
7790

    
7791
        logging.info("Creating volume %s for instance %s",
7792
                     new_disk.iv_name, instance.name)
7793
        # Note: this needs to be kept in sync with _CreateDisks
7794
        #HARDCODE
7795
        for node in instance.all_nodes:
7796
          f_create = node == instance.primary_node
7797
          try:
7798
            _CreateBlockDev(self, node, instance, new_disk,
7799
                            f_create, info, f_create)
7800
          except errors.OpExecError, err:
7801
            self.LogWarning("Failed to create volume %s (%s) on"
7802
                            " node %s: %s",
7803
                            new_disk.iv_name, new_disk, node, err)
7804
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
7805
                       (new_disk.size, new_disk.mode)))
7806
      else:
7807
        # change a given disk
7808
        instance.disks[disk_op].mode = disk_dict['mode']
7809
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
7810
    # NIC changes
7811
    for nic_op, nic_dict in self.op.nics:
7812
      if nic_op == constants.DDM_REMOVE:
7813
        # remove the last nic
7814
        del instance.nics[-1]
7815
        result.append(("nic.%d" % len(instance.nics), "remove"))
7816
      elif nic_op == constants.DDM_ADD:
7817
        # mac and bridge should be set, by now
7818
        mac = nic_dict['mac']
7819
        ip = nic_dict.get('ip', None)
7820
        nicparams = self.nic_pinst[constants.DDM_ADD]
7821
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
7822
        instance.nics.append(new_nic)
7823
        result.append(("nic.%d" % (len(instance.nics) - 1),
7824
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
7825
                       (new_nic.mac, new_nic.ip,
7826
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
7827
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
7828
                       )))
7829
      else:
7830
        for key in 'mac', 'ip':
7831
          if key in nic_dict:
7832
            setattr(instance.nics[nic_op], key, nic_dict[key])
7833
        if nic_op in self.nic_pnew:
7834
          instance.nics[nic_op].nicparams = self.nic_pnew[nic_op]
7835
        for key, val in nic_dict.iteritems():
7836
          result.append(("nic.%s/%d" % (key, nic_op), val))
7837

    
7838
    # hvparams changes
7839
    if self.op.hvparams:
7840
      instance.hvparams = self.hv_inst
7841
      for key, val in self.op.hvparams.iteritems():
7842
        result.append(("hv/%s" % key, val))
7843

    
7844
    # beparams changes
7845
    if self.op.beparams:
7846
      instance.beparams = self.be_inst
7847
      for key, val in self.op.beparams.iteritems():
7848
        result.append(("be/%s" % key, val))
7849

    
7850
    self.cfg.Update(instance, feedback_fn)
7851

    
7852
    return result
7853

    
7854

    
7855
class LUQueryExports(NoHooksLU):
7856
  """Query the exports list
7857

7858
  """
7859
  _OP_REQP = ['nodes']
7860
  REQ_BGL = False
7861

    
7862
  def ExpandNames(self):
7863
    self.needed_locks = {}
7864
    self.share_locks[locking.LEVEL_NODE] = 1
7865
    if not self.op.nodes:
7866
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7867
    else:
7868
      self.needed_locks[locking.LEVEL_NODE] = \
7869
        _GetWantedNodes(self, self.op.nodes)
7870

    
7871
  def CheckPrereq(self):
7872
    """Check prerequisites.
7873

7874
    """
7875
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
7876

    
7877
  def Exec(self, feedback_fn):
7878
    """Compute the list of all the exported system images.
7879

7880
    @rtype: dict
7881
    @return: a dictionary with the structure node->(export-list)
7882
        where export-list is a list of the instances exported on
7883
        that node.
7884

7885
    """
7886
    rpcresult = self.rpc.call_export_list(self.nodes)
7887
    result = {}
7888
    for node in rpcresult:
7889
      if rpcresult[node].fail_msg:
7890
        result[node] = False
7891
      else:
7892
        result[node] = rpcresult[node].payload
7893

    
7894
    return result
7895

    
7896

    
7897
class LUExportInstance(LogicalUnit):
7898
  """Export an instance to an image in the cluster.
7899

7900
  """
7901
  HPATH = "instance-export"
7902
  HTYPE = constants.HTYPE_INSTANCE
7903
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
7904
  REQ_BGL = False
7905

    
7906
  def CheckArguments(self):
7907
    """Check the arguments.
7908

7909
    """
7910
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
7911
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
7912

    
7913
  def ExpandNames(self):
7914
    self._ExpandAndLockInstance()
7915
    # FIXME: lock only instance primary and destination node
7916
    #
7917
    # Sad but true, for now we have do lock all nodes, as we don't know where
7918
    # the previous export might be, and and in this LU we search for it and
7919
    # remove it from its current node. In the future we could fix this by:
7920
    #  - making a tasklet to search (share-lock all), then create the new one,
7921
    #    then one to remove, after
7922
    #  - removing the removal operation altogether
7923
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7924

    
7925
  def DeclareLocks(self, level):
7926
    """Last minute lock declaration."""
7927
    # All nodes are locked anyway, so nothing to do here.
7928

    
7929
  def BuildHooksEnv(self):
7930
    """Build hooks env.
7931

7932
    This will run on the master, primary node and target node.
7933

7934
    """
7935
    env = {
7936
      "EXPORT_NODE": self.op.target_node,
7937
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
7938
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
7939
      }
7940
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7941
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
7942
          self.op.target_node]
7943
    return env, nl, nl
7944

    
7945
  def CheckPrereq(self):
7946
    """Check prerequisites.
7947

7948
    This checks that the instance and node names are valid.
7949

7950
    """
7951
    instance_name = self.op.instance_name
7952
    self.instance = self.cfg.GetInstanceInfo(instance_name)
7953
    assert self.instance is not None, \
7954
          "Cannot retrieve locked instance %s" % self.op.instance_name
7955
    _CheckNodeOnline(self, self.instance.primary_node)
7956

    
7957
    self.dst_node = self.cfg.GetNodeInfo(
7958
      self.cfg.ExpandNodeName(self.op.target_node))
7959

    
7960
    if self.dst_node is None:
7961
      # This is wrong node name, not a non-locked node
7962
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node,
7963
                                 errors.ECODE_NOENT)
7964
    _CheckNodeOnline(self, self.dst_node.name)
7965
    _CheckNodeNotDrained(self, self.dst_node.name)
7966

    
7967
    # instance disk type verification
7968
    for disk in self.instance.disks:
7969
      if disk.dev_type == constants.LD_FILE:
7970
        raise errors.OpPrereqError("Export not supported for instances with"
7971
                                   " file-based disks", errors.ECODE_INVAL)
7972

    
7973
  def Exec(self, feedback_fn):
7974
    """Export an instance to an image in the cluster.
7975

7976
    """
7977
    instance = self.instance
7978
    dst_node = self.dst_node
7979
    src_node = instance.primary_node
7980

    
7981
    if self.op.shutdown:
7982
      # shutdown the instance, but not the disks
7983
      feedback_fn("Shutting down instance %s" % instance.name)
7984
      result = self.rpc.call_instance_shutdown(src_node, instance,
7985
                                               self.shutdown_timeout)
7986
      result.Raise("Could not shutdown instance %s on"
7987
                   " node %s" % (instance.name, src_node))
7988

    
7989
    vgname = self.cfg.GetVGName()
7990

    
7991
    snap_disks = []
7992

    
7993
    # set the disks ID correctly since call_instance_start needs the
7994
    # correct drbd minor to create the symlinks
7995
    for disk in instance.disks:
7996
      self.cfg.SetDiskID(disk, src_node)
7997

    
7998
    activate_disks = (not instance.admin_up)
7999

    
8000
    if activate_disks:
8001
      # Activate the instance disks if we'exporting a stopped instance
8002
      feedback_fn("Activating disks for %s" % instance.name)
8003
      _StartInstanceDisks(self, instance, None)
8004

    
8005
    try:
8006
      # per-disk results
8007
      dresults = []
8008
      try:
8009
        for idx, disk in enumerate(instance.disks):
8010
          feedback_fn("Creating a snapshot of disk/%s on node %s" %
8011
                      (idx, src_node))
8012

    
8013
          # result.payload will be a snapshot of an lvm leaf of the one we
8014
          # passed
8015
          result = self.rpc.call_blockdev_snapshot(src_node, disk)
8016
          msg = result.fail_msg
8017
          if msg:
8018
            self.LogWarning("Could not snapshot disk/%s on node %s: %s",
8019
                            idx, src_node, msg)
8020
            snap_disks.append(False)
8021
          else:
8022
            disk_id = (vgname, result.payload)
8023
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
8024
                                   logical_id=disk_id, physical_id=disk_id,
8025
                                   iv_name=disk.iv_name)
8026
            snap_disks.append(new_dev)
8027

    
8028
      finally:
8029
        if self.op.shutdown and instance.admin_up:
8030
          feedback_fn("Starting instance %s" % instance.name)
8031
          result = self.rpc.call_instance_start(src_node, instance, None, None)
8032
          msg = result.fail_msg
8033
          if msg:
8034
            _ShutdownInstanceDisks(self, instance)
8035
            raise errors.OpExecError("Could not start instance: %s" % msg)
8036

    
8037
      # TODO: check for size
8038

    
8039
      cluster_name = self.cfg.GetClusterName()
8040
      for idx, dev in enumerate(snap_disks):
8041
        feedback_fn("Exporting snapshot %s from %s to %s" %
8042
                    (idx, src_node, dst_node.name))
8043
        if dev:
8044
          result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
8045
                                                 instance, cluster_name, idx)
8046
          msg = result.fail_msg
8047
          if msg:
8048
            self.LogWarning("Could not export disk/%s from node %s to"
8049
                            " node %s: %s", idx, src_node, dst_node.name, msg)
8050
            dresults.append(False)
8051
          else:
8052
            dresults.append(True)
8053
          msg = self.rpc.call_blockdev_remove(src_node, dev).fail_msg
8054
          if msg:
8055
            self.LogWarning("Could not remove snapshot for disk/%d from node"
8056
                            " %s: %s", idx, src_node, msg)
8057
        else:
8058
          dresults.append(False)
8059

    
8060
      feedback_fn("Finalizing export on %s" % dst_node.name)
8061
      result = self.rpc.call_finalize_export(dst_node.name, instance,
8062
                                             snap_disks)
8063
      fin_resu = True
8064
      msg = result.fail_msg
8065
      if msg:
8066
        self.LogWarning("Could not finalize export for instance %s"
8067
                        " on node %s: %s", instance.name, dst_node.name, msg)
8068
        fin_resu = False
8069

    
8070
    finally:
8071
      if activate_disks:
8072
        feedback_fn("Deactivating disks for %s" % instance.name)
8073
        _ShutdownInstanceDisks(self, instance)
8074

    
8075
    nodelist = self.cfg.GetNodeList()
8076
    nodelist.remove(dst_node.name)
8077

    
8078
    # on one-node clusters nodelist will be empty after the removal
8079
    # if we proceed the backup would be removed because OpQueryExports
8080
    # substitutes an empty list with the full cluster node list.
8081
    iname = instance.name
8082
    if nodelist:
8083
      feedback_fn("Removing old exports for instance %s" % iname)
8084
      exportlist = self.rpc.call_export_list(nodelist)
8085
      for node in exportlist:
8086
        if exportlist[node].fail_msg:
8087
          continue
8088
        if iname in exportlist[node].payload:
8089
          msg = self.rpc.call_export_remove(node, iname).fail_msg
8090
          if msg:
8091
            self.LogWarning("Could not remove older export for instance %s"
8092
                            " on node %s: %s", iname, node, msg)
8093
    return fin_resu, dresults
8094

    
8095

    
8096
class LURemoveExport(NoHooksLU):
8097
  """Remove exports related to the named instance.
8098

8099
  """
8100
  _OP_REQP = ["instance_name"]
8101
  REQ_BGL = False
8102

    
8103
  def ExpandNames(self):
8104
    self.needed_locks = {}
8105
    # We need all nodes to be locked in order for RemoveExport to work, but we
8106
    # don't need to lock the instance itself, as nothing will happen to it (and
8107
    # we can remove exports also for a removed instance)
8108
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8109

    
8110
  def CheckPrereq(self):
8111
    """Check prerequisites.
8112
    """
8113
    pass
8114

    
8115
  def Exec(self, feedback_fn):
8116
    """Remove any export.
8117

8118
    """
8119
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
8120
    # If the instance was not found we'll try with the name that was passed in.
8121
    # This will only work if it was an FQDN, though.
8122
    fqdn_warn = False
8123
    if not instance_name:
8124
      fqdn_warn = True
8125
      instance_name = self.op.instance_name
8126

    
8127
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
8128
    exportlist = self.rpc.call_export_list(locked_nodes)
8129
    found = False
8130
    for node in exportlist:
8131
      msg = exportlist[node].fail_msg
8132
      if msg:
8133
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
8134
        continue
8135
      if instance_name in exportlist[node].payload:
8136
        found = True
8137
        result = self.rpc.call_export_remove(node, instance_name)
8138
        msg = result.fail_msg
8139
        if msg:
8140
          logging.error("Could not remove export for instance %s"
8141
                        " on node %s: %s", instance_name, node, msg)
8142

    
8143
    if fqdn_warn and not found:
8144
      feedback_fn("Export not found. If trying to remove an export belonging"
8145
                  " to a deleted instance please use its Fully Qualified"
8146
                  " Domain Name.")
8147

    
8148

    
8149
class TagsLU(NoHooksLU):
8150
  """Generic tags LU.
8151

8152
  This is an abstract class which is the parent of all the other tags LUs.
8153

8154
  """
8155

    
8156
  def ExpandNames(self):
8157
    self.needed_locks = {}
8158
    if self.op.kind == constants.TAG_NODE:
8159
      name = self.cfg.ExpandNodeName(self.op.name)
8160
      if name is None:
8161
        raise errors.OpPrereqError("Invalid node name (%s)" %
8162
                                   (self.op.name,), errors.ECODE_NOENT)
8163
      self.op.name = name
8164
      self.needed_locks[locking.LEVEL_NODE] = name
8165
    elif self.op.kind == constants.TAG_INSTANCE:
8166
      name = self.cfg.ExpandInstanceName(self.op.name)
8167
      if name is None:
8168
        raise errors.OpPrereqError("Invalid instance name (%s)" %
8169
                                   (self.op.name,), errors.ECODE_NOENT)
8170
      self.op.name = name
8171
      self.needed_locks[locking.LEVEL_INSTANCE] = name
8172

    
8173
  def CheckPrereq(self):
8174
    """Check prerequisites.
8175

8176
    """
8177
    if self.op.kind == constants.TAG_CLUSTER:
8178
      self.target = self.cfg.GetClusterInfo()
8179
    elif self.op.kind == constants.TAG_NODE:
8180
      self.target = self.cfg.GetNodeInfo(self.op.name)
8181
    elif self.op.kind == constants.TAG_INSTANCE:
8182
      self.target = self.cfg.GetInstanceInfo(self.op.name)
8183
    else:
8184
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
8185
                                 str(self.op.kind), errors.ECODE_INVAL)
8186

    
8187

    
8188
class LUGetTags(TagsLU):
8189
  """Returns the tags of a given object.
8190

8191
  """
8192
  _OP_REQP = ["kind", "name"]
8193
  REQ_BGL = False
8194

    
8195
  def Exec(self, feedback_fn):
8196
    """Returns the tag list.
8197

8198
    """
8199
    return list(self.target.GetTags())
8200

    
8201

    
8202
class LUSearchTags(NoHooksLU):
8203
  """Searches the tags for a given pattern.
8204

8205
  """
8206
  _OP_REQP = ["pattern"]
8207
  REQ_BGL = False
8208

    
8209
  def ExpandNames(self):
8210
    self.needed_locks = {}
8211

    
8212
  def CheckPrereq(self):
8213
    """Check prerequisites.
8214

8215
    This checks the pattern passed for validity by compiling it.
8216

8217
    """
8218
    try:
8219
      self.re = re.compile(self.op.pattern)
8220
    except re.error, err:
8221
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
8222
                                 (self.op.pattern, err), errors.ECODE_INVAL)
8223

    
8224
  def Exec(self, feedback_fn):
8225
    """Returns the tag list.
8226

8227
    """
8228
    cfg = self.cfg
8229
    tgts = [("/cluster", cfg.GetClusterInfo())]
8230
    ilist = cfg.GetAllInstancesInfo().values()
8231
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
8232
    nlist = cfg.GetAllNodesInfo().values()
8233
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
8234
    results = []
8235
    for path, target in tgts:
8236
      for tag in target.GetTags():
8237
        if self.re.search(tag):
8238
          results.append((path, tag))
8239
    return results
8240

    
8241

    
8242
class LUAddTags(TagsLU):
8243
  """Sets a tag on a given object.
8244

8245
  """
8246
  _OP_REQP = ["kind", "name", "tags"]
8247
  REQ_BGL = False
8248

    
8249
  def CheckPrereq(self):
8250
    """Check prerequisites.
8251

8252
    This checks the type and length of the tag name and value.
8253

8254
    """
8255
    TagsLU.CheckPrereq(self)
8256
    for tag in self.op.tags:
8257
      objects.TaggableObject.ValidateTag(tag)
8258

    
8259
  def Exec(self, feedback_fn):
8260
    """Sets the tag.
8261

8262
    """
8263
    try:
8264
      for tag in self.op.tags:
8265
        self.target.AddTag(tag)
8266
    except errors.TagError, err:
8267
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
8268
    self.cfg.Update(self.target, feedback_fn)
8269

    
8270

    
8271
class LUDelTags(TagsLU):
8272
  """Delete a list of tags from a given object.
8273

8274
  """
8275
  _OP_REQP = ["kind", "name", "tags"]
8276
  REQ_BGL = False
8277

    
8278
  def CheckPrereq(self):
8279
    """Check prerequisites.
8280

8281
    This checks that we have the given tag.
8282

8283
    """
8284
    TagsLU.CheckPrereq(self)
8285
    for tag in self.op.tags:
8286
      objects.TaggableObject.ValidateTag(tag)
8287
    del_tags = frozenset(self.op.tags)
8288
    cur_tags = self.target.GetTags()
8289
    if not del_tags <= cur_tags:
8290
      diff_tags = del_tags - cur_tags
8291
      diff_names = ["'%s'" % tag for tag in diff_tags]
8292
      diff_names.sort()
8293
      raise errors.OpPrereqError("Tag(s) %s not found" %
8294
                                 (",".join(diff_names)), errors.ECODE_NOENT)
8295

    
8296
  def Exec(self, feedback_fn):
8297
    """Remove the tag from the object.
8298

8299
    """
8300
    for tag in self.op.tags:
8301
      self.target.RemoveTag(tag)
8302
    self.cfg.Update(self.target, feedback_fn)
8303

    
8304

    
8305
class LUTestDelay(NoHooksLU):
8306
  """Sleep for a specified amount of time.
8307

8308
  This LU sleeps on the master and/or nodes for a specified amount of
8309
  time.
8310

8311
  """
8312
  _OP_REQP = ["duration", "on_master", "on_nodes"]
8313
  REQ_BGL = False
8314

    
8315
  def ExpandNames(self):
8316
    """Expand names and set required locks.
8317

8318
    This expands the node list, if any.
8319

8320
    """
8321
    self.needed_locks = {}
8322
    if self.op.on_nodes:
8323
      # _GetWantedNodes can be used here, but is not always appropriate to use
8324
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
8325
      # more information.
8326
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
8327
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
8328

    
8329
  def CheckPrereq(self):
8330
    """Check prerequisites.
8331

8332
    """
8333

    
8334
  def Exec(self, feedback_fn):
8335
    """Do the actual sleep.
8336

8337
    """
8338
    if self.op.on_master:
8339
      if not utils.TestDelay(self.op.duration):
8340
        raise errors.OpExecError("Error during master delay test")
8341
    if self.op.on_nodes:
8342
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
8343
      for node, node_result in result.items():
8344
        node_result.Raise("Failure during rpc call to node %s" % node)
8345

    
8346

    
8347
class IAllocator(object):
8348
  """IAllocator framework.
8349

8350
  An IAllocator instance has three sets of attributes:
8351
    - cfg that is needed to query the cluster
8352
    - input data (all members of the _KEYS class attribute are required)
8353
    - four buffer attributes (in|out_data|text), that represent the
8354
      input (to the external script) in text and data structure format,
8355
      and the output from it, again in two formats
8356
    - the result variables from the script (success, info, nodes) for
8357
      easy usage
8358

8359
  """
8360
  _ALLO_KEYS = [
8361
    "mem_size", "disks", "disk_template",
8362
    "os", "tags", "nics", "vcpus", "hypervisor",
8363
    ]
8364
  _RELO_KEYS = [
8365
    "relocate_from",
8366
    ]
8367

    
8368
  def __init__(self, cfg, rpc, mode, name, **kwargs):
8369
    self.cfg = cfg
8370
    self.rpc = rpc
8371
    # init buffer variables
8372
    self.in_text = self.out_text = self.in_data = self.out_data = None
8373
    # init all input fields so that pylint is happy
8374
    self.mode = mode
8375
    self.name = name
8376
    self.mem_size = self.disks = self.disk_template = None
8377
    self.os = self.tags = self.nics = self.vcpus = None
8378
    self.hypervisor = None
8379
    self.relocate_from = None
8380
    # computed fields
8381
    self.required_nodes = None
8382
    # init result fields
8383
    self.success = self.info = self.nodes = None
8384
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8385
      keyset = self._ALLO_KEYS
8386
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8387
      keyset = self._RELO_KEYS
8388
    else:
8389
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
8390
                                   " IAllocator" % self.mode)
8391
    for key in kwargs:
8392
      if key not in keyset:
8393
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
8394
                                     " IAllocator" % key)
8395
      setattr(self, key, kwargs[key])
8396
    for key in keyset:
8397
      if key not in kwargs:
8398
        raise errors.ProgrammerError("Missing input parameter '%s' to"
8399
                                     " IAllocator" % key)
8400
    self._BuildInputData()
8401

    
8402
  def _ComputeClusterData(self):
8403
    """Compute the generic allocator input data.
8404

8405
    This is the data that is independent of the actual operation.
8406

8407
    """
8408
    cfg = self.cfg
8409
    cluster_info = cfg.GetClusterInfo()
8410
    # cluster data
8411
    data = {
8412
      "version": constants.IALLOCATOR_VERSION,
8413
      "cluster_name": cfg.GetClusterName(),
8414
      "cluster_tags": list(cluster_info.GetTags()),
8415
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
8416
      # we don't have job IDs
8417
      }
8418
    iinfo = cfg.GetAllInstancesInfo().values()
8419
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
8420

    
8421
    # node data
8422
    node_results = {}
8423
    node_list = cfg.GetNodeList()
8424

    
8425
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8426
      hypervisor_name = self.hypervisor
8427
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8428
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
8429

    
8430
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
8431
                                        hypervisor_name)
8432
    node_iinfo = \
8433
      self.rpc.call_all_instances_info(node_list,
8434
                                       cluster_info.enabled_hypervisors)
8435
    for nname, nresult in node_data.items():
8436
      # first fill in static (config-based) values
8437
      ninfo = cfg.GetNodeInfo(nname)
8438
      pnr = {
8439
        "tags": list(ninfo.GetTags()),
8440
        "primary_ip": ninfo.primary_ip,
8441
        "secondary_ip": ninfo.secondary_ip,
8442
        "offline": ninfo.offline,
8443
        "drained": ninfo.drained,
8444
        "master_candidate": ninfo.master_candidate,
8445
        }
8446

    
8447
      if not (ninfo.offline or ninfo.drained):
8448
        nresult.Raise("Can't get data for node %s" % nname)
8449
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
8450
                                nname)
8451
        remote_info = nresult.payload
8452

    
8453
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
8454
                     'vg_size', 'vg_free', 'cpu_total']:
8455
          if attr not in remote_info:
8456
            raise errors.OpExecError("Node '%s' didn't return attribute"
8457
                                     " '%s'" % (nname, attr))
8458
          if not isinstance(remote_info[attr], int):
8459
            raise errors.OpExecError("Node '%s' returned invalid value"
8460
                                     " for '%s': %s" %
8461
                                     (nname, attr, remote_info[attr]))
8462
        # compute memory used by primary instances
8463
        i_p_mem = i_p_up_mem = 0
8464
        for iinfo, beinfo in i_list:
8465
          if iinfo.primary_node == nname:
8466
            i_p_mem += beinfo[constants.BE_MEMORY]
8467
            if iinfo.name not in node_iinfo[nname].payload:
8468
              i_used_mem = 0
8469
            else:
8470
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
8471
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
8472
            remote_info['memory_free'] -= max(0, i_mem_diff)
8473

    
8474
            if iinfo.admin_up:
8475
              i_p_up_mem += beinfo[constants.BE_MEMORY]
8476

    
8477
        # compute memory used by instances
8478
        pnr_dyn = {
8479
          "total_memory": remote_info['memory_total'],
8480
          "reserved_memory": remote_info['memory_dom0'],
8481
          "free_memory": remote_info['memory_free'],
8482
          "total_disk": remote_info['vg_size'],
8483
          "free_disk": remote_info['vg_free'],
8484
          "total_cpus": remote_info['cpu_total'],
8485
          "i_pri_memory": i_p_mem,
8486
          "i_pri_up_memory": i_p_up_mem,
8487
          }
8488
        pnr.update(pnr_dyn)
8489

    
8490
      node_results[nname] = pnr
8491
    data["nodes"] = node_results
8492

    
8493
    # instance data
8494
    instance_data = {}
8495
    for iinfo, beinfo in i_list:
8496
      nic_data = []
8497
      for nic in iinfo.nics:
8498
        filled_params = objects.FillDict(
8499
            cluster_info.nicparams[constants.PP_DEFAULT],
8500
            nic.nicparams)
8501
        nic_dict = {"mac": nic.mac,
8502
                    "ip": nic.ip,
8503
                    "mode": filled_params[constants.NIC_MODE],
8504
                    "link": filled_params[constants.NIC_LINK],
8505
                   }
8506
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
8507
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
8508
        nic_data.append(nic_dict)
8509
      pir = {
8510
        "tags": list(iinfo.GetTags()),
8511
        "admin_up": iinfo.admin_up,
8512
        "vcpus": beinfo[constants.BE_VCPUS],
8513
        "memory": beinfo[constants.BE_MEMORY],
8514
        "os": iinfo.os,
8515
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
8516
        "nics": nic_data,
8517
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
8518
        "disk_template": iinfo.disk_template,
8519
        "hypervisor": iinfo.hypervisor,
8520
        }
8521
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
8522
                                                 pir["disks"])
8523
      instance_data[iinfo.name] = pir
8524

    
8525
    data["instances"] = instance_data
8526

    
8527
    self.in_data = data
8528

    
8529
  def _AddNewInstance(self):
8530
    """Add new instance data to allocator structure.
8531

8532
    This in combination with _AllocatorGetClusterData will create the
8533
    correct structure needed as input for the allocator.
8534

8535
    The checks for the completeness of the opcode must have already been
8536
    done.
8537

8538
    """
8539
    data = self.in_data
8540

    
8541
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
8542

    
8543
    if self.disk_template in constants.DTS_NET_MIRROR:
8544
      self.required_nodes = 2
8545
    else:
8546
      self.required_nodes = 1
8547
    request = {
8548
      "type": "allocate",
8549
      "name": self.name,
8550
      "disk_template": self.disk_template,
8551
      "tags": self.tags,
8552
      "os": self.os,
8553
      "vcpus": self.vcpus,
8554
      "memory": self.mem_size,
8555
      "disks": self.disks,
8556
      "disk_space_total": disk_space,
8557
      "nics": self.nics,
8558
      "required_nodes": self.required_nodes,
8559
      }
8560
    data["request"] = request
8561

    
8562
  def _AddRelocateInstance(self):
8563
    """Add relocate instance data to allocator structure.
8564

8565
    This in combination with _IAllocatorGetClusterData will create the
8566
    correct structure needed as input for the allocator.
8567

8568
    The checks for the completeness of the opcode must have already been
8569
    done.
8570

8571
    """
8572
    instance = self.cfg.GetInstanceInfo(self.name)
8573
    if instance is None:
8574
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
8575
                                   " IAllocator" % self.name)
8576

    
8577
    if instance.disk_template not in constants.DTS_NET_MIRROR:
8578
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
8579
                                 errors.ECODE_INVAL)
8580

    
8581
    if len(instance.secondary_nodes) != 1:
8582
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
8583
                                 errors.ECODE_STATE)
8584

    
8585
    self.required_nodes = 1
8586
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
8587
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
8588

    
8589
    request = {
8590
      "type": "relocate",
8591
      "name": self.name,
8592
      "disk_space_total": disk_space,
8593
      "required_nodes": self.required_nodes,
8594
      "relocate_from": self.relocate_from,
8595
      }
8596
    self.in_data["request"] = request
8597

    
8598
  def _BuildInputData(self):
8599
    """Build input data structures.
8600

8601
    """
8602
    self._ComputeClusterData()
8603

    
8604
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8605
      self._AddNewInstance()
8606
    else:
8607
      self._AddRelocateInstance()
8608

    
8609
    self.in_text = serializer.Dump(self.in_data)
8610

    
8611
  def Run(self, name, validate=True, call_fn=None):
8612
    """Run an instance allocator and return the results.
8613

8614
    """
8615
    if call_fn is None:
8616
      call_fn = self.rpc.call_iallocator_runner
8617

    
8618
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
8619
    result.Raise("Failure while running the iallocator script")
8620

    
8621
    self.out_text = result.payload
8622
    if validate:
8623
      self._ValidateResult()
8624

    
8625
  def _ValidateResult(self):
8626
    """Process the allocator results.
8627

8628
    This will process and if successful save the result in
8629
    self.out_data and the other parameters.
8630

8631
    """
8632
    try:
8633
      rdict = serializer.Load(self.out_text)
8634
    except Exception, err:
8635
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
8636

    
8637
    if not isinstance(rdict, dict):
8638
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
8639

    
8640
    for key in "success", "info", "nodes":
8641
      if key not in rdict:
8642
        raise errors.OpExecError("Can't parse iallocator results:"
8643
                                 " missing key '%s'" % key)
8644
      setattr(self, key, rdict[key])
8645

    
8646
    if not isinstance(rdict["nodes"], list):
8647
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
8648
                               " is not a list")
8649
    self.out_data = rdict
8650

    
8651

    
8652
class LUTestAllocator(NoHooksLU):
8653
  """Run allocator tests.
8654

8655
  This LU runs the allocator tests
8656

8657
  """
8658
  _OP_REQP = ["direction", "mode", "name"]
8659

    
8660
  def CheckPrereq(self):
8661
    """Check prerequisites.
8662

8663
    This checks the opcode parameters depending on the director and mode test.
8664

8665
    """
8666
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8667
      for attr in ["name", "mem_size", "disks", "disk_template",
8668
                   "os", "tags", "nics", "vcpus"]:
8669
        if not hasattr(self.op, attr):
8670
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
8671
                                     attr, errors.ECODE_INVAL)
8672
      iname = self.cfg.ExpandInstanceName(self.op.name)
8673
      if iname is not None:
8674
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
8675
                                   iname, errors.ECODE_EXISTS)
8676
      if not isinstance(self.op.nics, list):
8677
        raise errors.OpPrereqError("Invalid parameter 'nics'",
8678
                                   errors.ECODE_INVAL)
8679
      for row in self.op.nics:
8680
        if (not isinstance(row, dict) or
8681
            "mac" not in row or
8682
            "ip" not in row or
8683
            "bridge" not in row):
8684
          raise errors.OpPrereqError("Invalid contents of the 'nics'"
8685
                                     " parameter", errors.ECODE_INVAL)
8686
      if not isinstance(self.op.disks, list):
8687
        raise errors.OpPrereqError("Invalid parameter 'disks'",
8688
                                   errors.ECODE_INVAL)
8689
      for row in self.op.disks:
8690
        if (not isinstance(row, dict) or
8691
            "size" not in row or
8692
            not isinstance(row["size"], int) or
8693
            "mode" not in row or
8694
            row["mode"] not in ['r', 'w']):
8695
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
8696
                                     " parameter", errors.ECODE_INVAL)
8697
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
8698
        self.op.hypervisor = self.cfg.GetHypervisorType()
8699
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
8700
      if not hasattr(self.op, "name"):
8701
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input",
8702
                                   errors.ECODE_INVAL)
8703
      fname = self.cfg.ExpandInstanceName(self.op.name)
8704
      if fname is None:
8705
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
8706
                                   self.op.name, errors.ECODE_NOENT)
8707
      self.op.name = fname
8708
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
8709
    else:
8710
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
8711
                                 self.op.mode, errors.ECODE_INVAL)
8712

    
8713
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
8714
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
8715
        raise errors.OpPrereqError("Missing allocator name",
8716
                                   errors.ECODE_INVAL)
8717
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
8718
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
8719
                                 self.op.direction, errors.ECODE_INVAL)
8720

    
8721
  def Exec(self, feedback_fn):
8722
    """Run the allocator test.
8723

8724
    """
8725
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8726
      ial = IAllocator(self.cfg, self.rpc,
8727
                       mode=self.op.mode,
8728
                       name=self.op.name,
8729
                       mem_size=self.op.mem_size,
8730
                       disks=self.op.disks,
8731
                       disk_template=self.op.disk_template,
8732
                       os=self.op.os,
8733
                       tags=self.op.tags,
8734
                       nics=self.op.nics,
8735
                       vcpus=self.op.vcpus,
8736
                       hypervisor=self.op.hypervisor,
8737
                       )
8738
    else:
8739
      ial = IAllocator(self.cfg, self.rpc,
8740
                       mode=self.op.mode,
8741
                       name=self.op.name,
8742
                       relocate_from=list(self.relocate_from),
8743
                       )
8744

    
8745
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
8746
      result = ial.in_text
8747
    else:
8748
      ial.Run(self.op.allocator, validate=False)
8749
      result = ial.out_text
8750
    return result