Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ a872dae6

History | View | Annotate | Download (149.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007 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 sha
29
import time
30
import tempfile
31
import re
32
import platform
33

    
34
from ganeti import rpc
35
from ganeti import ssh
36
from ganeti import logger
37
from ganeti import utils
38
from ganeti import errors
39
from ganeti import hypervisor
40
from ganeti import config
41
from ganeti import constants
42
from ganeti import objects
43
from ganeti import opcodes
44
from ganeti import ssconf
45

    
46

    
47
class LogicalUnit(object):
48
  """Logical Unit base class.
49

50
  Subclasses must follow these rules:
51
    - implement CheckPrereq which also fills in the opcode instance
52
      with all the fields (even if as None)
53
    - implement Exec
54
    - implement BuildHooksEnv
55
    - redefine HPATH and HTYPE
56
    - optionally redefine their run requirements (REQ_CLUSTER,
57
      REQ_MASTER); note that all commands require root permissions
58

59
  """
60
  HPATH = None
61
  HTYPE = None
62
  _OP_REQP = []
63
  REQ_CLUSTER = True
64
  REQ_MASTER = True
65

    
66
  def __init__(self, processor, op, cfg, sstore):
67
    """Constructor for LogicalUnit.
68

69
    This needs to be overriden in derived classes in order to check op
70
    validity.
71

72
    """
73
    self.proc = processor
74
    self.op = op
75
    self.cfg = cfg
76
    self.sstore = sstore
77
    self.__ssh = None
78

    
79
    for attr_name in self._OP_REQP:
80
      attr_val = getattr(op, attr_name, None)
81
      if attr_val is None:
82
        raise errors.OpPrereqError("Required parameter '%s' missing" %
83
                                   attr_name)
84
    if self.REQ_CLUSTER:
85
      if not cfg.IsCluster():
86
        raise errors.OpPrereqError("Cluster not initialized yet,"
87
                                   " use 'gnt-cluster init' first.")
88
      if self.REQ_MASTER:
89
        master = sstore.GetMasterNode()
90
        if master != utils.HostInfo().name:
91
          raise errors.OpPrereqError("Commands must be run on the master"
92
                                     " node %s" % master)
93

    
94
  def __GetSSH(self):
95
    """Returns the SshRunner object
96

97
    """
98
    if not self.__ssh:
99
      self.__ssh = ssh.SshRunner(self.sstore)
100
    return self.__ssh
101

    
102
  ssh = property(fget=__GetSSH)
103

    
104
  def CheckPrereq(self):
105
    """Check prerequisites for this LU.
106

107
    This method should check that the prerequisites for the execution
108
    of this LU are fulfilled. It can do internode communication, but
109
    it should be idempotent - no cluster or system changes are
110
    allowed.
111

112
    The method should raise errors.OpPrereqError in case something is
113
    not fulfilled. Its return value is ignored.
114

115
    This method should also update all the parameters of the opcode to
116
    their canonical form; e.g. a short node name must be fully
117
    expanded after this method has successfully completed (so that
118
    hooks, logging, etc. work correctly).
119

120
    """
121
    raise NotImplementedError
122

    
123
  def Exec(self, feedback_fn):
124
    """Execute the LU.
125

126
    This method should implement the actual work. It should raise
127
    errors.OpExecError for failures that are somewhat dealt with in
128
    code, or expected.
129

130
    """
131
    raise NotImplementedError
132

    
133
  def BuildHooksEnv(self):
134
    """Build hooks environment for this LU.
135

136
    This method should return a three-node tuple consisting of: a dict
137
    containing the environment that will be used for running the
138
    specific hook for this LU, a list of node names on which the hook
139
    should run before the execution, and a list of node names on which
140
    the hook should run after the execution.
141

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

147
    As for the node lists, the master should not be included in the
148
    them, as it will be added by the hooks runner in case this LU
149
    requires a cluster to run on (otherwise we don't have a node
150
    list). No nodes should be returned as an empty list (and not
151
    None).
152

153
    Note that if the HPATH for a LU class is None, this function will
154
    not be called.
155

156
    """
157
    raise NotImplementedError
158

    
159

    
160
class NoHooksLU(LogicalUnit):
161
  """Simple LU which runs no hooks.
162

163
  This LU is intended as a parent for other LogicalUnits which will
164
  run no hooks, in order to reduce duplicate code.
165

166
  """
167
  HPATH = None
168
  HTYPE = None
169

    
170
  def BuildHooksEnv(self):
171
    """Build hooks env.
172

173
    This is a no-op, since we don't run hooks.
174

175
    """
176
    return {}, [], []
177

    
178

    
179
def _AddHostToEtcHosts(hostname):
180
  """Wrapper around utils.SetEtcHostsEntry.
181

182
  """
183
  hi = utils.HostInfo(name=hostname)
184
  utils.SetEtcHostsEntry(constants.ETC_HOSTS, hi.ip, hi.name, [hi.ShortName()])
185

    
186

    
187
def _RemoveHostFromEtcHosts(hostname):
188
  """Wrapper around utils.RemoveEtcHostsEntry.
189

190
  """
191
  hi = utils.HostInfo(name=hostname)
192
  utils.RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.name)
193
  utils.RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.ShortName())
194

    
195

    
196
def _GetWantedNodes(lu, nodes):
197
  """Returns list of checked and expanded node names.
198

199
  Args:
200
    nodes: List of nodes (strings) or None for all
201

202
  """
203
  if not isinstance(nodes, list):
204
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
205

    
206
  if nodes:
207
    wanted = []
208

    
209
    for name in nodes:
210
      node = lu.cfg.ExpandNodeName(name)
211
      if node is None:
212
        raise errors.OpPrereqError("No such node name '%s'" % name)
213
      wanted.append(node)
214

    
215
  else:
216
    wanted = lu.cfg.GetNodeList()
217
  return utils.NiceSort(wanted)
218

    
219

    
220
def _GetWantedInstances(lu, instances):
221
  """Returns list of checked and expanded instance names.
222

223
  Args:
224
    instances: List of instances (strings) or None for all
225

226
  """
227
  if not isinstance(instances, list):
228
    raise errors.OpPrereqError("Invalid argument type 'instances'")
229

    
230
  if instances:
231
    wanted = []
232

    
233
    for name in instances:
234
      instance = lu.cfg.ExpandInstanceName(name)
235
      if instance is None:
236
        raise errors.OpPrereqError("No such instance name '%s'" % name)
237
      wanted.append(instance)
238

    
239
  else:
240
    wanted = lu.cfg.GetInstanceList()
241
  return utils.NiceSort(wanted)
242

    
243

    
244
def _CheckOutputFields(static, dynamic, selected):
245
  """Checks whether all selected fields are valid.
246

247
  Args:
248
    static: Static fields
249
    dynamic: Dynamic fields
250

251
  """
252
  static_fields = frozenset(static)
253
  dynamic_fields = frozenset(dynamic)
254

    
255
  all_fields = static_fields | dynamic_fields
256

    
257
  if not all_fields.issuperset(selected):
258
    raise errors.OpPrereqError("Unknown output fields selected: %s"
259
                               % ",".join(frozenset(selected).
260
                                          difference(all_fields)))
261

    
262

    
263
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
264
                          memory, vcpus, nics):
265
  """Builds instance related env variables for hooks from single variables.
266

267
  Args:
268
    secondary_nodes: List of secondary nodes as strings
269
  """
270
  env = {
271
    "OP_TARGET": name,
272
    "INSTANCE_NAME": name,
273
    "INSTANCE_PRIMARY": primary_node,
274
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
275
    "INSTANCE_OS_TYPE": os_type,
276
    "INSTANCE_STATUS": status,
277
    "INSTANCE_MEMORY": memory,
278
    "INSTANCE_VCPUS": vcpus,
279
  }
280

    
281
  if nics:
282
    nic_count = len(nics)
283
    for idx, (ip, bridge, mac) in enumerate(nics):
284
      if ip is None:
285
        ip = ""
286
      env["INSTANCE_NIC%d_IP" % idx] = ip
287
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
288
      env["INSTANCE_NIC%d_HWADDR" % idx] = mac
289
  else:
290
    nic_count = 0
291

    
292
  env["INSTANCE_NIC_COUNT"] = nic_count
293

    
294
  return env
295

    
296

    
297
def _BuildInstanceHookEnvByObject(instance, override=None):
298
  """Builds instance related env variables for hooks from an object.
299

300
  Args:
301
    instance: objects.Instance object of instance
302
    override: dict of values to override
303
  """
304
  args = {
305
    'name': instance.name,
306
    'primary_node': instance.primary_node,
307
    'secondary_nodes': instance.secondary_nodes,
308
    'os_type': instance.os,
309
    'status': instance.os,
310
    'memory': instance.memory,
311
    'vcpus': instance.vcpus,
312
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
313
  }
314
  if override:
315
    args.update(override)
316
  return _BuildInstanceHookEnv(**args)
317

    
318

    
319
def _HasValidVG(vglist, vgname):
320
  """Checks if the volume group list is valid.
321

322
  A non-None return value means there's an error, and the return value
323
  is the error message.
324

325
  """
326
  vgsize = vglist.get(vgname, None)
327
  if vgsize is None:
328
    return "volume group '%s' missing" % vgname
329
  elif vgsize < 20480:
330
    return ("volume group '%s' too small (20480MiB required, %dMib found)" %
331
            (vgname, vgsize))
332
  return None
333

    
334

    
335
def _InitSSHSetup(node):
336
  """Setup the SSH configuration for the cluster.
337

338

339
  This generates a dsa keypair for root, adds the pub key to the
340
  permitted hosts and adds the hostkey to its own known hosts.
341

342
  Args:
343
    node: the name of this host as a fqdn
344

345
  """
346
  priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
347

    
348
  for name in priv_key, pub_key:
349
    if os.path.exists(name):
350
      utils.CreateBackup(name)
351
    utils.RemoveFile(name)
352

    
353
  result = utils.RunCmd(["ssh-keygen", "-t", "dsa",
354
                         "-f", priv_key,
355
                         "-q", "-N", ""])
356
  if result.failed:
357
    raise errors.OpExecError("Could not generate ssh keypair, error %s" %
358
                             result.output)
359

    
360
  f = open(pub_key, 'r')
361
  try:
362
    utils.AddAuthorizedKey(auth_keys, f.read(8192))
363
  finally:
364
    f.close()
365

    
366

    
367
def _InitGanetiServerSetup(ss):
368
  """Setup the necessary configuration for the initial node daemon.
369

370
  This creates the nodepass file containing the shared password for
371
  the cluster and also generates the SSL certificate.
372

373
  """
374
  # Create pseudo random password
375
  randpass = sha.new(os.urandom(64)).hexdigest()
376
  # and write it into sstore
377
  ss.SetKey(ss.SS_NODED_PASS, randpass)
378

    
379
  result = utils.RunCmd(["openssl", "req", "-new", "-newkey", "rsa:1024",
380
                         "-days", str(365*5), "-nodes", "-x509",
381
                         "-keyout", constants.SSL_CERT_FILE,
382
                         "-out", constants.SSL_CERT_FILE, "-batch"])
383
  if result.failed:
384
    raise errors.OpExecError("could not generate server ssl cert, command"
385
                             " %s had exitcode %s and error message %s" %
386
                             (result.cmd, result.exit_code, result.output))
387

    
388
  os.chmod(constants.SSL_CERT_FILE, 0400)
389

    
390
  result = utils.RunCmd([constants.NODE_INITD_SCRIPT, "restart"])
391

    
392
  if result.failed:
393
    raise errors.OpExecError("Could not start the node daemon, command %s"
394
                             " had exitcode %s and error %s" %
395
                             (result.cmd, result.exit_code, result.output))
396

    
397

    
398
def _CheckInstanceBridgesExist(instance):
399
  """Check that the brigdes needed by an instance exist.
400

401
  """
402
  # check bridges existance
403
  brlist = [nic.bridge for nic in instance.nics]
404
  if not rpc.call_bridges_exist(instance.primary_node, brlist):
405
    raise errors.OpPrereqError("one or more target bridges %s does not"
406
                               " exist on destination node '%s'" %
407
                               (brlist, instance.primary_node))
408

    
409

    
410
class LUInitCluster(LogicalUnit):
411
  """Initialise the cluster.
412

413
  """
414
  HPATH = "cluster-init"
415
  HTYPE = constants.HTYPE_CLUSTER
416
  _OP_REQP = ["cluster_name", "hypervisor_type", "mac_prefix",
417
              "def_bridge", "master_netdev", "file_storage_dir"]
418
  REQ_CLUSTER = False
419

    
420
  def BuildHooksEnv(self):
421
    """Build hooks env.
422

423
    Notes: Since we don't require a cluster, we must manually add
424
    ourselves in the post-run node list.
425

426
    """
427
    env = {"OP_TARGET": self.op.cluster_name}
428
    return env, [], [self.hostname.name]
429

    
430
  def CheckPrereq(self):
431
    """Verify that the passed name is a valid one.
432

433
    """
434
    if config.ConfigWriter.IsCluster():
435
      raise errors.OpPrereqError("Cluster is already initialised")
436

    
437
    if self.op.hypervisor_type == constants.HT_XEN_HVM31:
438
      if not os.path.exists(constants.VNC_PASSWORD_FILE):
439
        raise errors.OpPrereqError("Please prepare the cluster VNC"
440
                                   "password file %s" %
441
                                   constants.VNC_PASSWORD_FILE)
442

    
443
    self.hostname = hostname = utils.HostInfo()
444

    
445
    if hostname.ip.startswith("127."):
446
      raise errors.OpPrereqError("This host's IP resolves to the private"
447
                                 " range (%s). Please fix DNS or %s." %
448
                                 (hostname.ip, constants.ETC_HOSTS))
449

    
450
    if not utils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT,
451
                         source=constants.LOCALHOST_IP_ADDRESS):
452
      raise errors.OpPrereqError("Inconsistency: this host's name resolves"
453
                                 " to %s,\nbut this ip address does not"
454
                                 " belong to this host."
455
                                 " Aborting." % hostname.ip)
456

    
457
    self.clustername = clustername = utils.HostInfo(self.op.cluster_name)
458

    
459
    if utils.TcpPing(clustername.ip, constants.DEFAULT_NODED_PORT,
460
                     timeout=5):
461
      raise errors.OpPrereqError("Cluster IP already active. Aborting.")
462

    
463
    secondary_ip = getattr(self.op, "secondary_ip", None)
464
    if secondary_ip and not utils.IsValidIP(secondary_ip):
465
      raise errors.OpPrereqError("Invalid secondary ip given")
466
    if (secondary_ip and
467
        secondary_ip != hostname.ip and
468
        (not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
469
                           source=constants.LOCALHOST_IP_ADDRESS))):
470
      raise errors.OpPrereqError("You gave %s as secondary IP,"
471
                                 " but it does not belong to this host." %
472
                                 secondary_ip)
473
    self.secondary_ip = secondary_ip
474

    
475
    if not hasattr(self.op, "vg_name"):
476
      self.op.vg_name = None
477
    # if vg_name not None, checks if volume group is valid
478
    if self.op.vg_name:
479
      vgstatus = _HasValidVG(utils.ListVolumeGroups(), self.op.vg_name)
480
      if vgstatus:
481
        raise errors.OpPrereqError("Error: %s\nspecify --no-lvm-storage if"
482
                                   " you are not using lvm" % vgstatus)
483

    
484
    self.op.file_storage_dir = os.path.normpath(self.op.file_storage_dir)
485

    
486
    if not os.path.isabs(self.op.file_storage_dir):
487
      raise errors.OpPrereqError("The file storage directory you have is"
488
                                 " not an absolute path.")
489

    
490
    if not os.path.exists(self.op.file_storage_dir):
491
      try:
492
        os.makedirs(self.op.file_storage_dir, 0750)
493
      except OSError, err:
494
        raise errors.OpPrereqError("Cannot create file storage directory"
495
                                   " '%s': %s" %
496
                                   (self.op.file_storage_dir, err))
497

    
498
    if not os.path.isdir(self.op.file_storage_dir):
499
      raise errors.OpPrereqError("The file storage directory '%s' is not"
500
                                 " a directory." % self.op.file_storage_dir)
501

    
502
    if not re.match("^[0-9a-z]{2}:[0-9a-z]{2}:[0-9a-z]{2}$",
503
                    self.op.mac_prefix):
504
      raise errors.OpPrereqError("Invalid mac prefix given '%s'" %
505
                                 self.op.mac_prefix)
506

    
507
    if self.op.hypervisor_type not in constants.HYPER_TYPES:
508
      raise errors.OpPrereqError("Invalid hypervisor type given '%s'" %
509
                                 self.op.hypervisor_type)
510

    
511
    result = utils.RunCmd(["ip", "link", "show", "dev", self.op.master_netdev])
512
    if result.failed:
513
      raise errors.OpPrereqError("Invalid master netdev given (%s): '%s'" %
514
                                 (self.op.master_netdev,
515
                                  result.output.strip()))
516

    
517
    if not (os.path.isfile(constants.NODE_INITD_SCRIPT) and
518
            os.access(constants.NODE_INITD_SCRIPT, os.X_OK)):
519
      raise errors.OpPrereqError("Init.d script '%s' missing or not"
520
                                 " executable." % constants.NODE_INITD_SCRIPT)
521

    
522
  def Exec(self, feedback_fn):
523
    """Initialize the cluster.
524

525
    """
526
    clustername = self.clustername
527
    hostname = self.hostname
528

    
529
    # set up the simple store
530
    self.sstore = ss = ssconf.SimpleStore()
531
    ss.SetKey(ss.SS_HYPERVISOR, self.op.hypervisor_type)
532
    ss.SetKey(ss.SS_MASTER_NODE, hostname.name)
533
    ss.SetKey(ss.SS_MASTER_IP, clustername.ip)
534
    ss.SetKey(ss.SS_MASTER_NETDEV, self.op.master_netdev)
535
    ss.SetKey(ss.SS_CLUSTER_NAME, clustername.name)
536
    ss.SetKey(ss.SS_FILE_STORAGE_DIR, self.op.file_storage_dir)
537

    
538
    # set up the inter-node password and certificate
539
    _InitGanetiServerSetup(ss)
540

    
541
    # start the master ip
542
    rpc.call_node_start_master(hostname.name)
543

    
544
    # set up ssh config and /etc/hosts
545
    f = open(constants.SSH_HOST_RSA_PUB, 'r')
546
    try:
547
      sshline = f.read()
548
    finally:
549
      f.close()
550
    sshkey = sshline.split(" ")[1]
551

    
552
    _AddHostToEtcHosts(hostname.name)
553
    _InitSSHSetup(hostname.name)
554

    
555
    # init of cluster config file
556
    self.cfg = cfgw = config.ConfigWriter()
557
    cfgw.InitConfig(hostname.name, hostname.ip, self.secondary_ip,
558
                    sshkey, self.op.mac_prefix,
559
                    self.op.vg_name, self.op.def_bridge)
560

    
561
    ssh.WriteKnownHostsFile(cfgw, ss, constants.SSH_KNOWN_HOSTS_FILE)
562

    
563

    
564
class LUDestroyCluster(NoHooksLU):
565
  """Logical unit for destroying the cluster.
566

567
  """
568
  _OP_REQP = []
569

    
570
  def CheckPrereq(self):
571
    """Check prerequisites.
572

573
    This checks whether the cluster is empty.
574

575
    Any errors are signalled by raising errors.OpPrereqError.
576

577
    """
578
    master = self.sstore.GetMasterNode()
579

    
580
    nodelist = self.cfg.GetNodeList()
581
    if len(nodelist) != 1 or nodelist[0] != master:
582
      raise errors.OpPrereqError("There are still %d node(s) in"
583
                                 " this cluster." % (len(nodelist) - 1))
584
    instancelist = self.cfg.GetInstanceList()
585
    if instancelist:
586
      raise errors.OpPrereqError("There are still %d instance(s) in"
587
                                 " this cluster." % len(instancelist))
588

    
589
  def Exec(self, feedback_fn):
590
    """Destroys the cluster.
591

592
    """
593
    master = self.sstore.GetMasterNode()
594
    if not rpc.call_node_stop_master(master):
595
      raise errors.OpExecError("Could not disable the master role")
596
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
597
    utils.CreateBackup(priv_key)
598
    utils.CreateBackup(pub_key)
599
    rpc.call_node_leave_cluster(master)
600

    
601

    
602
class LUVerifyCluster(NoHooksLU):
603
  """Verifies the cluster status.
604

605
  """
606
  _OP_REQP = []
607

    
608
  def _VerifyNode(self, node, file_list, local_cksum, vglist, node_result,
609
                  remote_version, feedback_fn):
610
    """Run multiple tests against a node.
611

612
    Test list:
613
      - compares ganeti version
614
      - checks vg existance and size > 20G
615
      - checks config file checksum
616
      - checks ssh to other nodes
617

618
    Args:
619
      node: name of the node to check
620
      file_list: required list of files
621
      local_cksum: dictionary of local files and their checksums
622

623
    """
624
    # compares ganeti version
625
    local_version = constants.PROTOCOL_VERSION
626
    if not remote_version:
627
      feedback_fn("  - ERROR: connection to %s failed" % (node))
628
      return True
629

    
630
    if local_version != remote_version:
631
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
632
                      (local_version, node, remote_version))
633
      return True
634

    
635
    # checks vg existance and size > 20G
636

    
637
    bad = False
638
    if not vglist:
639
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
640
                      (node,))
641
      bad = True
642
    else:
643
      vgstatus = _HasValidVG(vglist, self.cfg.GetVGName())
644
      if vgstatus:
645
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
646
        bad = True
647

    
648
    # checks config file checksum
649
    # checks ssh to any
650

    
651
    if 'filelist' not in node_result:
652
      bad = True
653
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
654
    else:
655
      remote_cksum = node_result['filelist']
656
      for file_name in file_list:
657
        if file_name not in remote_cksum:
658
          bad = True
659
          feedback_fn("  - ERROR: file '%s' missing" % file_name)
660
        elif remote_cksum[file_name] != local_cksum[file_name]:
661
          bad = True
662
          feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
663

    
664
    if 'nodelist' not in node_result:
665
      bad = True
666
      feedback_fn("  - ERROR: node hasn't returned node connectivity data")
667
    else:
668
      if node_result['nodelist']:
669
        bad = True
670
        for node in node_result['nodelist']:
671
          feedback_fn("  - ERROR: communication with node '%s': %s" %
672
                          (node, node_result['nodelist'][node]))
673
    hyp_result = node_result.get('hypervisor', None)
674
    if hyp_result is not None:
675
      feedback_fn("  - ERROR: hypervisor verify failure: '%s'" % hyp_result)
676
    return bad
677

    
678
  def _VerifyInstance(self, instance, node_vol_is, node_instance, feedback_fn):
679
    """Verify an instance.
680

681
    This function checks to see if the required block devices are
682
    available on the instance's node.
683

684
    """
685
    bad = False
686

    
687
    instancelist = self.cfg.GetInstanceList()
688
    if not instance in instancelist:
689
      feedback_fn("  - ERROR: instance %s not in instance list %s" %
690
                      (instance, instancelist))
691
      bad = True
692

    
693
    instanceconfig = self.cfg.GetInstanceInfo(instance)
694
    node_current = instanceconfig.primary_node
695

    
696
    node_vol_should = {}
697
    instanceconfig.MapLVsByNode(node_vol_should)
698

    
699
    for node in node_vol_should:
700
      for volume in node_vol_should[node]:
701
        if node not in node_vol_is or volume not in node_vol_is[node]:
702
          feedback_fn("  - ERROR: volume %s missing on node %s" %
703
                          (volume, node))
704
          bad = True
705

    
706
    if not instanceconfig.status == 'down':
707
      if (node_current not in node_instance or
708
          not instance in node_instance[node_current]):
709
        feedback_fn("  - ERROR: instance %s not running on node %s" %
710
                        (instance, node_current))
711
        bad = True
712

    
713
    for node in node_instance:
714
      if (not node == node_current):
715
        if instance in node_instance[node]:
716
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
717
                          (instance, node))
718
          bad = True
719

    
720
    return bad
721

    
722
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
723
    """Verify if there are any unknown volumes in the cluster.
724

725
    The .os, .swap and backup volumes are ignored. All other volumes are
726
    reported as unknown.
727

728
    """
729
    bad = False
730

    
731
    for node in node_vol_is:
732
      for volume in node_vol_is[node]:
733
        if node not in node_vol_should or volume not in node_vol_should[node]:
734
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
735
                      (volume, node))
736
          bad = True
737
    return bad
738

    
739
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
740
    """Verify the list of running instances.
741

742
    This checks what instances are running but unknown to the cluster.
743

744
    """
745
    bad = False
746
    for node in node_instance:
747
      for runninginstance in node_instance[node]:
748
        if runninginstance not in instancelist:
749
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
750
                          (runninginstance, node))
751
          bad = True
752
    return bad
753

    
754
  def CheckPrereq(self):
755
    """Check prerequisites.
756

757
    This has no prerequisites.
758

759
    """
760
    pass
761

    
762
  def Exec(self, feedback_fn):
763
    """Verify integrity of cluster, performing various test on nodes.
764

765
    """
766
    bad = False
767
    feedback_fn("* Verifying global settings")
768
    for msg in self.cfg.VerifyConfig():
769
      feedback_fn("  - ERROR: %s" % msg)
770

    
771
    vg_name = self.cfg.GetVGName()
772
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
773
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
774
    node_volume = {}
775
    node_instance = {}
776

    
777
    # FIXME: verify OS list
778
    # do local checksums
779
    file_names = list(self.sstore.GetFileList())
780
    file_names.append(constants.SSL_CERT_FILE)
781
    file_names.append(constants.CLUSTER_CONF_FILE)
782
    local_checksums = utils.FingerprintFiles(file_names)
783

    
784
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
785
    all_volumeinfo = rpc.call_volume_list(nodelist, vg_name)
786
    all_instanceinfo = rpc.call_instance_list(nodelist)
787
    all_vglist = rpc.call_vg_list(nodelist)
788
    node_verify_param = {
789
      'filelist': file_names,
790
      'nodelist': nodelist,
791
      'hypervisor': None,
792
      }
793
    all_nvinfo = rpc.call_node_verify(nodelist, node_verify_param)
794
    all_rversion = rpc.call_version(nodelist)
795

    
796
    for node in nodelist:
797
      feedback_fn("* Verifying node %s" % node)
798
      result = self._VerifyNode(node, file_names, local_checksums,
799
                                all_vglist[node], all_nvinfo[node],
800
                                all_rversion[node], feedback_fn)
801
      bad = bad or result
802

    
803
      # node_volume
804
      volumeinfo = all_volumeinfo[node]
805

    
806
      if isinstance(volumeinfo, basestring):
807
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
808
                    (node, volumeinfo[-400:].encode('string_escape')))
809
        bad = True
810
        node_volume[node] = {}
811
      elif not isinstance(volumeinfo, dict):
812
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
813
        bad = True
814
        continue
815
      else:
816
        node_volume[node] = volumeinfo
817

    
818
      # node_instance
819
      nodeinstance = all_instanceinfo[node]
820
      if type(nodeinstance) != list:
821
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
822
        bad = True
823
        continue
824

    
825
      node_instance[node] = nodeinstance
826

    
827
    node_vol_should = {}
828

    
829
    for instance in instancelist:
830
      feedback_fn("* Verifying instance %s" % instance)
831
      result =  self._VerifyInstance(instance, node_volume, node_instance,
832
                                     feedback_fn)
833
      bad = bad or result
834

    
835
      inst_config = self.cfg.GetInstanceInfo(instance)
836

    
837
      inst_config.MapLVsByNode(node_vol_should)
838

    
839
    feedback_fn("* Verifying orphan volumes")
840
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
841
                                       feedback_fn)
842
    bad = bad or result
843

    
844
    feedback_fn("* Verifying remaining instances")
845
    result = self._VerifyOrphanInstances(instancelist, node_instance,
846
                                         feedback_fn)
847
    bad = bad or result
848

    
849
    return int(bad)
850

    
851

    
852
class LUVerifyDisks(NoHooksLU):
853
  """Verifies the cluster disks status.
854

855
  """
856
  _OP_REQP = []
857

    
858
  def CheckPrereq(self):
859
    """Check prerequisites.
860

861
    This has no prerequisites.
862

863
    """
864
    pass
865

    
866
  def Exec(self, feedback_fn):
867
    """Verify integrity of cluster disks.
868

869
    """
870
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
871

    
872
    vg_name = self.cfg.GetVGName()
873
    nodes = utils.NiceSort(self.cfg.GetNodeList())
874
    instances = [self.cfg.GetInstanceInfo(name)
875
                 for name in self.cfg.GetInstanceList()]
876

    
877
    nv_dict = {}
878
    for inst in instances:
879
      inst_lvs = {}
880
      if (inst.status != "up" or
881
          inst.disk_template not in constants.DTS_NET_MIRROR):
882
        continue
883
      inst.MapLVsByNode(inst_lvs)
884
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
885
      for node, vol_list in inst_lvs.iteritems():
886
        for vol in vol_list:
887
          nv_dict[(node, vol)] = inst
888

    
889
    if not nv_dict:
890
      return result
891

    
892
    node_lvs = rpc.call_volume_list(nodes, vg_name)
893

    
894
    to_act = set()
895
    for node in nodes:
896
      # node_volume
897
      lvs = node_lvs[node]
898

    
899
      if isinstance(lvs, basestring):
900
        logger.Info("error enumerating LVs on node %s: %s" % (node, lvs))
901
        res_nlvm[node] = lvs
902
      elif not isinstance(lvs, dict):
903
        logger.Info("connection to node %s failed or invalid data returned" %
904
                    (node,))
905
        res_nodes.append(node)
906
        continue
907

    
908
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
909
        inst = nv_dict.pop((node, lv_name), None)
910
        if (not lv_online and inst is not None
911
            and inst.name not in res_instances):
912
          res_instances.append(inst.name)
913

    
914
    # any leftover items in nv_dict are missing LVs, let's arrange the
915
    # data better
916
    for key, inst in nv_dict.iteritems():
917
      if inst.name not in res_missing:
918
        res_missing[inst.name] = []
919
      res_missing[inst.name].append(key)
920

    
921
    return result
922

    
923

    
924
class LURenameCluster(LogicalUnit):
925
  """Rename the cluster.
926

927
  """
928
  HPATH = "cluster-rename"
929
  HTYPE = constants.HTYPE_CLUSTER
930
  _OP_REQP = ["name"]
931

    
932
  def BuildHooksEnv(self):
933
    """Build hooks env.
934

935
    """
936
    env = {
937
      "OP_TARGET": self.sstore.GetClusterName(),
938
      "NEW_NAME": self.op.name,
939
      }
940
    mn = self.sstore.GetMasterNode()
941
    return env, [mn], [mn]
942

    
943
  def CheckPrereq(self):
944
    """Verify that the passed name is a valid one.
945

946
    """
947
    hostname = utils.HostInfo(self.op.name)
948

    
949
    new_name = hostname.name
950
    self.ip = new_ip = hostname.ip
951
    old_name = self.sstore.GetClusterName()
952
    old_ip = self.sstore.GetMasterIP()
953
    if new_name == old_name and new_ip == old_ip:
954
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
955
                                 " cluster has changed")
956
    if new_ip != old_ip:
957
      result = utils.RunCmd(["fping", "-q", new_ip])
958
      if not result.failed:
959
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
960
                                   " reachable on the network. Aborting." %
961
                                   new_ip)
962

    
963
    self.op.name = new_name
964

    
965
  def Exec(self, feedback_fn):
966
    """Rename the cluster.
967

968
    """
969
    clustername = self.op.name
970
    ip = self.ip
971
    ss = self.sstore
972

    
973
    # shutdown the master IP
974
    master = ss.GetMasterNode()
975
    if not rpc.call_node_stop_master(master):
976
      raise errors.OpExecError("Could not disable the master role")
977

    
978
    try:
979
      # modify the sstore
980
      ss.SetKey(ss.SS_MASTER_IP, ip)
981
      ss.SetKey(ss.SS_CLUSTER_NAME, clustername)
982

    
983
      # Distribute updated ss config to all nodes
984
      myself = self.cfg.GetNodeInfo(master)
985
      dist_nodes = self.cfg.GetNodeList()
986
      if myself.name in dist_nodes:
987
        dist_nodes.remove(myself.name)
988

    
989
      logger.Debug("Copying updated ssconf data to all nodes")
990
      for keyname in [ss.SS_CLUSTER_NAME, ss.SS_MASTER_IP]:
991
        fname = ss.KeyToFilename(keyname)
992
        result = rpc.call_upload_file(dist_nodes, fname)
993
        for to_node in dist_nodes:
994
          if not result[to_node]:
995
            logger.Error("copy of file %s to node %s failed" %
996
                         (fname, to_node))
997
    finally:
998
      if not rpc.call_node_start_master(master):
999
        logger.Error("Could not re-enable the master role on the master,"
1000
                     " please restart manually.")
1001

    
1002

    
1003
def _RecursiveCheckIfLVMBased(disk):
1004
  """Check if the given disk or its children are lvm-based.
1005

1006
  Args:
1007
    disk: ganeti.objects.Disk object
1008

1009
  Returns:
1010
    boolean indicating whether a LD_LV dev_type was found or not
1011

1012
  """
1013
  if disk.children:
1014
    for chdisk in disk.children:
1015
      if _RecursiveCheckIfLVMBased(chdisk):
1016
        return True
1017
  return disk.dev_type == constants.LD_LV
1018

    
1019

    
1020
class LUSetClusterParams(LogicalUnit):
1021
  """Change the parameters of the cluster.
1022

1023
  """
1024
  HPATH = "cluster-modify"
1025
  HTYPE = constants.HTYPE_CLUSTER
1026
  _OP_REQP = []
1027

    
1028
  def BuildHooksEnv(self):
1029
    """Build hooks env.
1030

1031
    """
1032
    env = {
1033
      "OP_TARGET": self.sstore.GetClusterName(),
1034
      "NEW_VG_NAME": self.op.vg_name,
1035
      }
1036
    mn = self.sstore.GetMasterNode()
1037
    return env, [mn], [mn]
1038

    
1039
  def CheckPrereq(self):
1040
    """Check prerequisites.
1041

1042
    This checks whether the given params don't conflict and
1043
    if the given volume group is valid.
1044

1045
    """
1046
    if not self.op.vg_name:
1047
      instances = [self.cfg.GetInstanceInfo(name)
1048
                   for name in self.cfg.GetInstanceList()]
1049
      for inst in instances:
1050
        for disk in inst.disks:
1051
          if _RecursiveCheckIfLVMBased(disk):
1052
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1053
                                       " lvm-based instances exist")
1054

    
1055
    # if vg_name not None, checks given volume group on all nodes
1056
    if self.op.vg_name:
1057
      node_list = self.cfg.GetNodeList()
1058
      vglist = rpc.call_vg_list(node_list)
1059
      for node in node_list:
1060
        vgstatus = _HasValidVG(vglist[node], self.op.vg_name)
1061
        if vgstatus:
1062
          raise errors.OpPrereqError("Error on node '%s': %s" %
1063
                                     (node, vgstatus))
1064

    
1065
  def Exec(self, feedback_fn):
1066
    """Change the parameters of the cluster.
1067

1068
    """
1069
    if self.op.vg_name != self.cfg.GetVGName():
1070
      self.cfg.SetVGName(self.op.vg_name)
1071
    else:
1072
      feedback_fn("Cluster LVM configuration already in desired"
1073
                  " state, not changing")
1074

    
1075

    
1076
def _WaitForSync(cfgw, instance, proc, oneshot=False, unlock=False):
1077
  """Sleep and poll for an instance's disk to sync.
1078

1079
  """
1080
  if not instance.disks:
1081
    return True
1082

    
1083
  if not oneshot:
1084
    proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1085

    
1086
  node = instance.primary_node
1087

    
1088
  for dev in instance.disks:
1089
    cfgw.SetDiskID(dev, node)
1090

    
1091
  retries = 0
1092
  while True:
1093
    max_time = 0
1094
    done = True
1095
    cumul_degraded = False
1096
    rstats = rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1097
    if not rstats:
1098
      proc.LogWarning("Can't get any data from node %s" % node)
1099
      retries += 1
1100
      if retries >= 10:
1101
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1102
                                 " aborting." % node)
1103
      time.sleep(6)
1104
      continue
1105
    retries = 0
1106
    for i in range(len(rstats)):
1107
      mstat = rstats[i]
1108
      if mstat is None:
1109
        proc.LogWarning("Can't compute data for node %s/%s" %
1110
                        (node, instance.disks[i].iv_name))
1111
        continue
1112
      # we ignore the ldisk parameter
1113
      perc_done, est_time, is_degraded, _ = mstat
1114
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1115
      if perc_done is not None:
1116
        done = False
1117
        if est_time is not None:
1118
          rem_time = "%d estimated seconds remaining" % est_time
1119
          max_time = est_time
1120
        else:
1121
          rem_time = "no time estimate"
1122
        proc.LogInfo("- device %s: %5.2f%% done, %s" %
1123
                     (instance.disks[i].iv_name, perc_done, rem_time))
1124
    if done or oneshot:
1125
      break
1126

    
1127
    if unlock:
1128
      utils.Unlock('cmd')
1129
    try:
1130
      time.sleep(min(60, max_time))
1131
    finally:
1132
      if unlock:
1133
        utils.Lock('cmd')
1134

    
1135
  if done:
1136
    proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1137
  return not cumul_degraded
1138

    
1139

    
1140
def _CheckDiskConsistency(cfgw, dev, node, on_primary, ldisk=False):
1141
  """Check that mirrors are not degraded.
1142

1143
  The ldisk parameter, if True, will change the test from the
1144
  is_degraded attribute (which represents overall non-ok status for
1145
  the device(s)) to the ldisk (representing the local storage status).
1146

1147
  """
1148
  cfgw.SetDiskID(dev, node)
1149
  if ldisk:
1150
    idx = 6
1151
  else:
1152
    idx = 5
1153

    
1154
  result = True
1155
  if on_primary or dev.AssembleOnSecondary():
1156
    rstats = rpc.call_blockdev_find(node, dev)
1157
    if not rstats:
1158
      logger.ToStderr("Node %s: Disk degraded, not found or node down" % node)
1159
      result = False
1160
    else:
1161
      result = result and (not rstats[idx])
1162
  if dev.children:
1163
    for child in dev.children:
1164
      result = result and _CheckDiskConsistency(cfgw, child, node, on_primary)
1165

    
1166
  return result
1167

    
1168

    
1169
class LUDiagnoseOS(NoHooksLU):
1170
  """Logical unit for OS diagnose/query.
1171

1172
  """
1173
  _OP_REQP = []
1174

    
1175
  def CheckPrereq(self):
1176
    """Check prerequisites.
1177

1178
    This always succeeds, since this is a pure query LU.
1179

1180
    """
1181
    return
1182

    
1183
  def Exec(self, feedback_fn):
1184
    """Compute the list of OSes.
1185

1186
    """
1187
    node_list = self.cfg.GetNodeList()
1188
    node_data = rpc.call_os_diagnose(node_list)
1189
    if node_data == False:
1190
      raise errors.OpExecError("Can't gather the list of OSes")
1191
    return node_data
1192

    
1193

    
1194
class LURemoveNode(LogicalUnit):
1195
  """Logical unit for removing a node.
1196

1197
  """
1198
  HPATH = "node-remove"
1199
  HTYPE = constants.HTYPE_NODE
1200
  _OP_REQP = ["node_name"]
1201

    
1202
  def BuildHooksEnv(self):
1203
    """Build hooks env.
1204

1205
    This doesn't run on the target node in the pre phase as a failed
1206
    node would not allows itself to run.
1207

1208
    """
1209
    env = {
1210
      "OP_TARGET": self.op.node_name,
1211
      "NODE_NAME": self.op.node_name,
1212
      }
1213
    all_nodes = self.cfg.GetNodeList()
1214
    all_nodes.remove(self.op.node_name)
1215
    return env, all_nodes, all_nodes
1216

    
1217
  def CheckPrereq(self):
1218
    """Check prerequisites.
1219

1220
    This checks:
1221
     - the node exists in the configuration
1222
     - it does not have primary or secondary instances
1223
     - it's not the master
1224

1225
    Any errors are signalled by raising errors.OpPrereqError.
1226

1227
    """
1228
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1229
    if node is None:
1230
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1231

    
1232
    instance_list = self.cfg.GetInstanceList()
1233

    
1234
    masternode = self.sstore.GetMasterNode()
1235
    if node.name == masternode:
1236
      raise errors.OpPrereqError("Node is the master node,"
1237
                                 " you need to failover first.")
1238

    
1239
    for instance_name in instance_list:
1240
      instance = self.cfg.GetInstanceInfo(instance_name)
1241
      if node.name == instance.primary_node:
1242
        raise errors.OpPrereqError("Instance %s still running on the node,"
1243
                                   " please remove first." % instance_name)
1244
      if node.name in instance.secondary_nodes:
1245
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1246
                                   " please remove first." % instance_name)
1247
    self.op.node_name = node.name
1248
    self.node = node
1249

    
1250
  def Exec(self, feedback_fn):
1251
    """Removes the node from the cluster.
1252

1253
    """
1254
    node = self.node
1255
    logger.Info("stopping the node daemon and removing configs from node %s" %
1256
                node.name)
1257

    
1258
    rpc.call_node_leave_cluster(node.name)
1259

    
1260
    self.ssh.Run(node.name, 'root', "%s stop" % constants.NODE_INITD_SCRIPT)
1261

    
1262
    logger.Info("Removing node %s from config" % node.name)
1263

    
1264
    self.cfg.RemoveNode(node.name)
1265

    
1266
    _RemoveHostFromEtcHosts(node.name)
1267

    
1268

    
1269
class LUQueryNodes(NoHooksLU):
1270
  """Logical unit for querying nodes.
1271

1272
  """
1273
  _OP_REQP = ["output_fields", "names"]
1274

    
1275
  def CheckPrereq(self):
1276
    """Check prerequisites.
1277

1278
    This checks that the fields required are valid output fields.
1279

1280
    """
1281
    self.dynamic_fields = frozenset(["dtotal", "dfree",
1282
                                     "mtotal", "mnode", "mfree",
1283
                                     "bootid"])
1284

    
1285
    _CheckOutputFields(static=["name", "pinst_cnt", "sinst_cnt",
1286
                               "pinst_list", "sinst_list",
1287
                               "pip", "sip"],
1288
                       dynamic=self.dynamic_fields,
1289
                       selected=self.op.output_fields)
1290

    
1291
    self.wanted = _GetWantedNodes(self, self.op.names)
1292

    
1293
  def Exec(self, feedback_fn):
1294
    """Computes the list of nodes and their attributes.
1295

1296
    """
1297
    nodenames = self.wanted
1298
    nodelist = [self.cfg.GetNodeInfo(name) for name in nodenames]
1299

    
1300
    # begin data gathering
1301

    
1302
    if self.dynamic_fields.intersection(self.op.output_fields):
1303
      live_data = {}
1304
      node_data = rpc.call_node_info(nodenames, self.cfg.GetVGName())
1305
      for name in nodenames:
1306
        nodeinfo = node_data.get(name, None)
1307
        if nodeinfo:
1308
          live_data[name] = {
1309
            "mtotal": utils.TryConvert(int, nodeinfo['memory_total']),
1310
            "mnode": utils.TryConvert(int, nodeinfo['memory_dom0']),
1311
            "mfree": utils.TryConvert(int, nodeinfo['memory_free']),
1312
            "dtotal": utils.TryConvert(int, nodeinfo['vg_size']),
1313
            "dfree": utils.TryConvert(int, nodeinfo['vg_free']),
1314
            "bootid": nodeinfo['bootid'],
1315
            }
1316
        else:
1317
          live_data[name] = {}
1318
    else:
1319
      live_data = dict.fromkeys(nodenames, {})
1320

    
1321
    node_to_primary = dict([(name, set()) for name in nodenames])
1322
    node_to_secondary = dict([(name, set()) for name in nodenames])
1323

    
1324
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1325
                             "sinst_cnt", "sinst_list"))
1326
    if inst_fields & frozenset(self.op.output_fields):
1327
      instancelist = self.cfg.GetInstanceList()
1328

    
1329
      for instance_name in instancelist:
1330
        inst = self.cfg.GetInstanceInfo(instance_name)
1331
        if inst.primary_node in node_to_primary:
1332
          node_to_primary[inst.primary_node].add(inst.name)
1333
        for secnode in inst.secondary_nodes:
1334
          if secnode in node_to_secondary:
1335
            node_to_secondary[secnode].add(inst.name)
1336

    
1337
    # end data gathering
1338

    
1339
    output = []
1340
    for node in nodelist:
1341
      node_output = []
1342
      for field in self.op.output_fields:
1343
        if field == "name":
1344
          val = node.name
1345
        elif field == "pinst_list":
1346
          val = list(node_to_primary[node.name])
1347
        elif field == "sinst_list":
1348
          val = list(node_to_secondary[node.name])
1349
        elif field == "pinst_cnt":
1350
          val = len(node_to_primary[node.name])
1351
        elif field == "sinst_cnt":
1352
          val = len(node_to_secondary[node.name])
1353
        elif field == "pip":
1354
          val = node.primary_ip
1355
        elif field == "sip":
1356
          val = node.secondary_ip
1357
        elif field in self.dynamic_fields:
1358
          val = live_data[node.name].get(field, None)
1359
        else:
1360
          raise errors.ParameterError(field)
1361
        node_output.append(val)
1362
      output.append(node_output)
1363

    
1364
    return output
1365

    
1366

    
1367
class LUQueryNodeVolumes(NoHooksLU):
1368
  """Logical unit for getting volumes on node(s).
1369

1370
  """
1371
  _OP_REQP = ["nodes", "output_fields"]
1372

    
1373
  def CheckPrereq(self):
1374
    """Check prerequisites.
1375

1376
    This checks that the fields required are valid output fields.
1377

1378
    """
1379
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1380

    
1381
    _CheckOutputFields(static=["node"],
1382
                       dynamic=["phys", "vg", "name", "size", "instance"],
1383
                       selected=self.op.output_fields)
1384

    
1385

    
1386
  def Exec(self, feedback_fn):
1387
    """Computes the list of nodes and their attributes.
1388

1389
    """
1390
    nodenames = self.nodes
1391
    volumes = rpc.call_node_volumes(nodenames)
1392

    
1393
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1394
             in self.cfg.GetInstanceList()]
1395

    
1396
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1397

    
1398
    output = []
1399
    for node in nodenames:
1400
      if node not in volumes or not volumes[node]:
1401
        continue
1402

    
1403
      node_vols = volumes[node][:]
1404
      node_vols.sort(key=lambda vol: vol['dev'])
1405

    
1406
      for vol in node_vols:
1407
        node_output = []
1408
        for field in self.op.output_fields:
1409
          if field == "node":
1410
            val = node
1411
          elif field == "phys":
1412
            val = vol['dev']
1413
          elif field == "vg":
1414
            val = vol['vg']
1415
          elif field == "name":
1416
            val = vol['name']
1417
          elif field == "size":
1418
            val = int(float(vol['size']))
1419
          elif field == "instance":
1420
            for inst in ilist:
1421
              if node not in lv_by_node[inst]:
1422
                continue
1423
              if vol['name'] in lv_by_node[inst][node]:
1424
                val = inst.name
1425
                break
1426
            else:
1427
              val = '-'
1428
          else:
1429
            raise errors.ParameterError(field)
1430
          node_output.append(str(val))
1431

    
1432
        output.append(node_output)
1433

    
1434
    return output
1435

    
1436

    
1437
class LUAddNode(LogicalUnit):
1438
  """Logical unit for adding node to the cluster.
1439

1440
  """
1441
  HPATH = "node-add"
1442
  HTYPE = constants.HTYPE_NODE
1443
  _OP_REQP = ["node_name"]
1444

    
1445
  def BuildHooksEnv(self):
1446
    """Build hooks env.
1447

1448
    This will run on all nodes before, and on all nodes + the new node after.
1449

1450
    """
1451
    env = {
1452
      "OP_TARGET": self.op.node_name,
1453
      "NODE_NAME": self.op.node_name,
1454
      "NODE_PIP": self.op.primary_ip,
1455
      "NODE_SIP": self.op.secondary_ip,
1456
      }
1457
    nodes_0 = self.cfg.GetNodeList()
1458
    nodes_1 = nodes_0 + [self.op.node_name, ]
1459
    return env, nodes_0, nodes_1
1460

    
1461
  def CheckPrereq(self):
1462
    """Check prerequisites.
1463

1464
    This checks:
1465
     - the new node is not already in the config
1466
     - it is resolvable
1467
     - its parameters (single/dual homed) matches the cluster
1468

1469
    Any errors are signalled by raising errors.OpPrereqError.
1470

1471
    """
1472
    node_name = self.op.node_name
1473
    cfg = self.cfg
1474

    
1475
    dns_data = utils.HostInfo(node_name)
1476

    
1477
    node = dns_data.name
1478
    primary_ip = self.op.primary_ip = dns_data.ip
1479
    secondary_ip = getattr(self.op, "secondary_ip", None)
1480
    if secondary_ip is None:
1481
      secondary_ip = primary_ip
1482
    if not utils.IsValidIP(secondary_ip):
1483
      raise errors.OpPrereqError("Invalid secondary IP given")
1484
    self.op.secondary_ip = secondary_ip
1485
    node_list = cfg.GetNodeList()
1486
    if node in node_list:
1487
      raise errors.OpPrereqError("Node %s is already in the configuration"
1488
                                 % node)
1489

    
1490
    for existing_node_name in node_list:
1491
      existing_node = cfg.GetNodeInfo(existing_node_name)
1492
      if (existing_node.primary_ip == primary_ip or
1493
          existing_node.secondary_ip == primary_ip or
1494
          existing_node.primary_ip == secondary_ip or
1495
          existing_node.secondary_ip == secondary_ip):
1496
        raise errors.OpPrereqError("New node ip address(es) conflict with"
1497
                                   " existing node %s" % existing_node.name)
1498

    
1499
    # check that the type of the node (single versus dual homed) is the
1500
    # same as for the master
1501
    myself = cfg.GetNodeInfo(self.sstore.GetMasterNode())
1502
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1503
    newbie_singlehomed = secondary_ip == primary_ip
1504
    if master_singlehomed != newbie_singlehomed:
1505
      if master_singlehomed:
1506
        raise errors.OpPrereqError("The master has no private ip but the"
1507
                                   " new node has one")
1508
      else:
1509
        raise errors.OpPrereqError("The master has a private ip but the"
1510
                                   " new node doesn't have one")
1511

    
1512
    # checks reachablity
1513
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
1514
      raise errors.OpPrereqError("Node not reachable by ping")
1515

    
1516
    if not newbie_singlehomed:
1517
      # check reachability from my secondary ip to newbie's secondary ip
1518
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
1519
                           source=myself.secondary_ip):
1520
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
1521
                                   " based ping to noded port")
1522

    
1523
    self.new_node = objects.Node(name=node,
1524
                                 primary_ip=primary_ip,
1525
                                 secondary_ip=secondary_ip)
1526

    
1527
    if self.sstore.GetHypervisorType() == constants.HT_XEN_HVM31:
1528
      if not os.path.exists(constants.VNC_PASSWORD_FILE):
1529
        raise errors.OpPrereqError("Cluster VNC password file %s missing" %
1530
                                   constants.VNC_PASSWORD_FILE)
1531

    
1532
  def Exec(self, feedback_fn):
1533
    """Adds the new node to the cluster.
1534

1535
    """
1536
    new_node = self.new_node
1537
    node = new_node.name
1538

    
1539
    # set up inter-node password and certificate and restarts the node daemon
1540
    gntpass = self.sstore.GetNodeDaemonPassword()
1541
    if not re.match('^[a-zA-Z0-9.]{1,64}$', gntpass):
1542
      raise errors.OpExecError("ganeti password corruption detected")
1543
    f = open(constants.SSL_CERT_FILE)
1544
    try:
1545
      gntpem = f.read(8192)
1546
    finally:
1547
      f.close()
1548
    # in the base64 pem encoding, neither '!' nor '.' are valid chars,
1549
    # so we use this to detect an invalid certificate; as long as the
1550
    # cert doesn't contain this, the here-document will be correctly
1551
    # parsed by the shell sequence below
1552
    if re.search('^!EOF\.', gntpem, re.MULTILINE):
1553
      raise errors.OpExecError("invalid PEM encoding in the SSL certificate")
1554
    if not gntpem.endswith("\n"):
1555
      raise errors.OpExecError("PEM must end with newline")
1556
    logger.Info("copy cluster pass to %s and starting the node daemon" % node)
1557

    
1558
    # and then connect with ssh to set password and start ganeti-noded
1559
    # note that all the below variables are sanitized at this point,
1560
    # either by being constants or by the checks above
1561
    ss = self.sstore
1562
    mycommand = ("umask 077 && "
1563
                 "echo '%s' > '%s' && "
1564
                 "cat > '%s' << '!EOF.' && \n"
1565
                 "%s!EOF.\n%s restart" %
1566
                 (gntpass, ss.KeyToFilename(ss.SS_NODED_PASS),
1567
                  constants.SSL_CERT_FILE, gntpem,
1568
                  constants.NODE_INITD_SCRIPT))
1569

    
1570
    result = self.ssh.Run(node, 'root', mycommand, batch=False, ask_key=True)
1571
    if result.failed:
1572
      raise errors.OpExecError("Remote command on node %s, error: %s,"
1573
                               " output: %s" %
1574
                               (node, result.fail_reason, result.output))
1575

    
1576
    # check connectivity
1577
    time.sleep(4)
1578

    
1579
    result = rpc.call_version([node])[node]
1580
    if result:
1581
      if constants.PROTOCOL_VERSION == result:
1582
        logger.Info("communication to node %s fine, sw version %s match" %
1583
                    (node, result))
1584
      else:
1585
        raise errors.OpExecError("Version mismatch master version %s,"
1586
                                 " node version %s" %
1587
                                 (constants.PROTOCOL_VERSION, result))
1588
    else:
1589
      raise errors.OpExecError("Cannot get version from the new node")
1590

    
1591
    # setup ssh on node
1592
    logger.Info("copy ssh key to node %s" % node)
1593
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1594
    keyarray = []
1595
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
1596
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
1597
                priv_key, pub_key]
1598

    
1599
    for i in keyfiles:
1600
      f = open(i, 'r')
1601
      try:
1602
        keyarray.append(f.read())
1603
      finally:
1604
        f.close()
1605

    
1606
    result = rpc.call_node_add(node, keyarray[0], keyarray[1], keyarray[2],
1607
                               keyarray[3], keyarray[4], keyarray[5])
1608

    
1609
    if not result:
1610
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
1611

    
1612
    # Add node to our /etc/hosts, and add key to known_hosts
1613
    _AddHostToEtcHosts(new_node.name)
1614

    
1615
    if new_node.secondary_ip != new_node.primary_ip:
1616
      if not rpc.call_node_tcp_ping(new_node.name,
1617
                                    constants.LOCALHOST_IP_ADDRESS,
1618
                                    new_node.secondary_ip,
1619
                                    constants.DEFAULT_NODED_PORT,
1620
                                    10, False):
1621
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
1622
                                 " you gave (%s). Please fix and re-run this"
1623
                                 " command." % new_node.secondary_ip)
1624

    
1625
    success, msg = self.ssh.VerifyNodeHostname(node)
1626
    if not success:
1627
      raise errors.OpExecError("Node '%s' claims it has a different hostname"
1628
                               " than the one the resolver gives: %s."
1629
                               " Please fix and re-run this command." %
1630
                               (node, msg))
1631

    
1632
    # Distribute updated /etc/hosts and known_hosts to all nodes,
1633
    # including the node just added
1634
    myself = self.cfg.GetNodeInfo(self.sstore.GetMasterNode())
1635
    dist_nodes = self.cfg.GetNodeList() + [node]
1636
    if myself.name in dist_nodes:
1637
      dist_nodes.remove(myself.name)
1638

    
1639
    logger.Debug("Copying hosts and known_hosts to all nodes")
1640
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
1641
      result = rpc.call_upload_file(dist_nodes, fname)
1642
      for to_node in dist_nodes:
1643
        if not result[to_node]:
1644
          logger.Error("copy of file %s to node %s failed" %
1645
                       (fname, to_node))
1646

    
1647
    to_copy = ss.GetFileList()
1648
    if self.sstore.GetHypervisorType() == constants.HT_XEN_HVM31:
1649
      to_copy.append(constants.VNC_PASSWORD_FILE)
1650
    for fname in to_copy:
1651
      if not self.ssh.CopyFileToNode(node, fname):
1652
        logger.Error("could not copy file %s to node %s" % (fname, node))
1653

    
1654
    logger.Info("adding node %s to cluster.conf" % node)
1655
    self.cfg.AddNode(new_node)
1656

    
1657

    
1658
class LUMasterFailover(LogicalUnit):
1659
  """Failover the master node to the current node.
1660

1661
  This is a special LU in that it must run on a non-master node.
1662

1663
  """
1664
  HPATH = "master-failover"
1665
  HTYPE = constants.HTYPE_CLUSTER
1666
  REQ_MASTER = False
1667
  _OP_REQP = []
1668

    
1669
  def BuildHooksEnv(self):
1670
    """Build hooks env.
1671

1672
    This will run on the new master only in the pre phase, and on all
1673
    the nodes in the post phase.
1674

1675
    """
1676
    env = {
1677
      "OP_TARGET": self.new_master,
1678
      "NEW_MASTER": self.new_master,
1679
      "OLD_MASTER": self.old_master,
1680
      }
1681
    return env, [self.new_master], self.cfg.GetNodeList()
1682

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

1686
    This checks that we are not already the master.
1687

1688
    """
1689
    self.new_master = utils.HostInfo().name
1690
    self.old_master = self.sstore.GetMasterNode()
1691

    
1692
    if self.old_master == self.new_master:
1693
      raise errors.OpPrereqError("This commands must be run on the node"
1694
                                 " where you want the new master to be."
1695
                                 " %s is already the master" %
1696
                                 self.old_master)
1697

    
1698
  def Exec(self, feedback_fn):
1699
    """Failover the master node.
1700

1701
    This command, when run on a non-master node, will cause the current
1702
    master to cease being master, and the non-master to become new
1703
    master.
1704

1705
    """
1706
    #TODO: do not rely on gethostname returning the FQDN
1707
    logger.Info("setting master to %s, old master: %s" %
1708
                (self.new_master, self.old_master))
1709

    
1710
    if not rpc.call_node_stop_master(self.old_master):
1711
      logger.Error("could disable the master role on the old master"
1712
                   " %s, please disable manually" % self.old_master)
1713

    
1714
    ss = self.sstore
1715
    ss.SetKey(ss.SS_MASTER_NODE, self.new_master)
1716
    if not rpc.call_upload_file(self.cfg.GetNodeList(),
1717
                                ss.KeyToFilename(ss.SS_MASTER_NODE)):
1718
      logger.Error("could not distribute the new simple store master file"
1719
                   " to the other nodes, please check.")
1720

    
1721
    if not rpc.call_node_start_master(self.new_master):
1722
      logger.Error("could not start the master role on the new master"
1723
                   " %s, please check" % self.new_master)
1724
      feedback_fn("Error in activating the master IP on the new master,"
1725
                  " please fix manually.")
1726

    
1727

    
1728

    
1729
class LUQueryClusterInfo(NoHooksLU):
1730
  """Query cluster configuration.
1731

1732
  """
1733
  _OP_REQP = []
1734
  REQ_MASTER = False
1735

    
1736
  def CheckPrereq(self):
1737
    """No prerequsites needed for this LU.
1738

1739
    """
1740
    pass
1741

    
1742
  def Exec(self, feedback_fn):
1743
    """Return cluster config.
1744

1745
    """
1746
    result = {
1747
      "name": self.sstore.GetClusterName(),
1748
      "software_version": constants.RELEASE_VERSION,
1749
      "protocol_version": constants.PROTOCOL_VERSION,
1750
      "config_version": constants.CONFIG_VERSION,
1751
      "os_api_version": constants.OS_API_VERSION,
1752
      "export_version": constants.EXPORT_VERSION,
1753
      "master": self.sstore.GetMasterNode(),
1754
      "architecture": (platform.architecture()[0], platform.machine()),
1755
      }
1756

    
1757
    return result
1758

    
1759

    
1760
class LUClusterCopyFile(NoHooksLU):
1761
  """Copy file to cluster.
1762

1763
  """
1764
  _OP_REQP = ["nodes", "filename"]
1765

    
1766
  def CheckPrereq(self):
1767
    """Check prerequisites.
1768

1769
    It should check that the named file exists and that the given list
1770
    of nodes is valid.
1771

1772
    """
1773
    if not os.path.exists(self.op.filename):
1774
      raise errors.OpPrereqError("No such filename '%s'" % self.op.filename)
1775

    
1776
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1777

    
1778
  def Exec(self, feedback_fn):
1779
    """Copy a file from master to some nodes.
1780

1781
    Args:
1782
      opts - class with options as members
1783
      args - list containing a single element, the file name
1784
    Opts used:
1785
      nodes - list containing the name of target nodes; if empty, all nodes
1786

1787
    """
1788
    filename = self.op.filename
1789

    
1790
    myname = utils.HostInfo().name
1791

    
1792
    for node in self.nodes:
1793
      if node == myname:
1794
        continue
1795
      if not self.ssh.CopyFileToNode(node, filename):
1796
        logger.Error("Copy of file %s to node %s failed" % (filename, node))
1797

    
1798

    
1799
class LUDumpClusterConfig(NoHooksLU):
1800
  """Return a text-representation of the cluster-config.
1801

1802
  """
1803
  _OP_REQP = []
1804

    
1805
  def CheckPrereq(self):
1806
    """No prerequisites.
1807

1808
    """
1809
    pass
1810

    
1811
  def Exec(self, feedback_fn):
1812
    """Dump a representation of the cluster config to the standard output.
1813

1814
    """
1815
    return self.cfg.DumpConfig()
1816

    
1817

    
1818
class LURunClusterCommand(NoHooksLU):
1819
  """Run a command on some nodes.
1820

1821
  """
1822
  _OP_REQP = ["command", "nodes"]
1823

    
1824
  def CheckPrereq(self):
1825
    """Check prerequisites.
1826

1827
    It checks that the given list of nodes is valid.
1828

1829
    """
1830
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1831

    
1832
  def Exec(self, feedback_fn):
1833
    """Run a command on some nodes.
1834

1835
    """
1836
    # put the master at the end of the nodes list
1837
    master_node = self.sstore.GetMasterNode()
1838
    if master_node in self.nodes:
1839
      self.nodes.remove(master_node)
1840
      self.nodes.append(master_node)
1841

    
1842
    data = []
1843
    for node in self.nodes:
1844
      result = self.ssh.Run(node, "root", self.op.command)
1845
      data.append((node, result.output, result.exit_code))
1846

    
1847
    return data
1848

    
1849

    
1850
class LUActivateInstanceDisks(NoHooksLU):
1851
  """Bring up an instance's disks.
1852

1853
  """
1854
  _OP_REQP = ["instance_name"]
1855

    
1856
  def CheckPrereq(self):
1857
    """Check prerequisites.
1858

1859
    This checks that the instance is in the cluster.
1860

1861
    """
1862
    instance = self.cfg.GetInstanceInfo(
1863
      self.cfg.ExpandInstanceName(self.op.instance_name))
1864
    if instance is None:
1865
      raise errors.OpPrereqError("Instance '%s' not known" %
1866
                                 self.op.instance_name)
1867
    self.instance = instance
1868

    
1869

    
1870
  def Exec(self, feedback_fn):
1871
    """Activate the disks.
1872

1873
    """
1874
    disks_ok, disks_info = _AssembleInstanceDisks(self.instance, self.cfg)
1875
    if not disks_ok:
1876
      raise errors.OpExecError("Cannot activate block devices")
1877

    
1878
    return disks_info
1879

    
1880

    
1881
def _AssembleInstanceDisks(instance, cfg, ignore_secondaries=False):
1882
  """Prepare the block devices for an instance.
1883

1884
  This sets up the block devices on all nodes.
1885

1886
  Args:
1887
    instance: a ganeti.objects.Instance object
1888
    ignore_secondaries: if true, errors on secondary nodes won't result
1889
                        in an error return from the function
1890

1891
  Returns:
1892
    false if the operation failed
1893
    list of (host, instance_visible_name, node_visible_name) if the operation
1894
         suceeded with the mapping from node devices to instance devices
1895
  """
1896
  device_info = []
1897
  disks_ok = True
1898
  iname = instance.name
1899
  # With the two passes mechanism we try to reduce the window of
1900
  # opportunity for the race condition of switching DRBD to primary
1901
  # before handshaking occured, but we do not eliminate it
1902

    
1903
  # The proper fix would be to wait (with some limits) until the
1904
  # connection has been made and drbd transitions from WFConnection
1905
  # into any other network-connected state (Connected, SyncTarget,
1906
  # SyncSource, etc.)
1907

    
1908
  # 1st pass, assemble on all nodes in secondary mode
1909
  for inst_disk in instance.disks:
1910
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1911
      cfg.SetDiskID(node_disk, node)
1912
      result = rpc.call_blockdev_assemble(node, node_disk, iname, False)
1913
      if not result:
1914
        logger.Error("could not prepare block device %s on node %s"
1915
                     " (is_primary=False, pass=1)" % (inst_disk.iv_name, node))
1916
        if not ignore_secondaries:
1917
          disks_ok = False
1918

    
1919
  # FIXME: race condition on drbd migration to primary
1920

    
1921
  # 2nd pass, do only the primary node
1922
  for inst_disk in instance.disks:
1923
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1924
      if node != instance.primary_node:
1925
        continue
1926
      cfg.SetDiskID(node_disk, node)
1927
      result = rpc.call_blockdev_assemble(node, node_disk, iname, True)
1928
      if not result:
1929
        logger.Error("could not prepare block device %s on node %s"
1930
                     " (is_primary=True, pass=2)" % (inst_disk.iv_name, node))
1931
        disks_ok = False
1932
    device_info.append((instance.primary_node, inst_disk.iv_name, result))
1933

    
1934
  # leave the disks configured for the primary node
1935
  # this is a workaround that would be fixed better by
1936
  # improving the logical/physical id handling
1937
  for disk in instance.disks:
1938
    cfg.SetDiskID(disk, instance.primary_node)
1939

    
1940
  return disks_ok, device_info
1941

    
1942

    
1943
def _StartInstanceDisks(cfg, instance, force):
1944
  """Start the disks of an instance.
1945

1946
  """
1947
  disks_ok, dummy = _AssembleInstanceDisks(instance, cfg,
1948
                                           ignore_secondaries=force)
1949
  if not disks_ok:
1950
    _ShutdownInstanceDisks(instance, cfg)
1951
    if force is not None and not force:
1952
      logger.Error("If the message above refers to a secondary node,"
1953
                   " you can retry the operation using '--force'.")
1954
    raise errors.OpExecError("Disk consistency error")
1955

    
1956

    
1957
class LUDeactivateInstanceDisks(NoHooksLU):
1958
  """Shutdown an instance's disks.
1959

1960
  """
1961
  _OP_REQP = ["instance_name"]
1962

    
1963
  def CheckPrereq(self):
1964
    """Check prerequisites.
1965

1966
    This checks that the instance is in the cluster.
1967

1968
    """
1969
    instance = self.cfg.GetInstanceInfo(
1970
      self.cfg.ExpandInstanceName(self.op.instance_name))
1971
    if instance is None:
1972
      raise errors.OpPrereqError("Instance '%s' not known" %
1973
                                 self.op.instance_name)
1974
    self.instance = instance
1975

    
1976
  def Exec(self, feedback_fn):
1977
    """Deactivate the disks
1978

1979
    """
1980
    instance = self.instance
1981
    ins_l = rpc.call_instance_list([instance.primary_node])
1982
    ins_l = ins_l[instance.primary_node]
1983
    if not type(ins_l) is list:
1984
      raise errors.OpExecError("Can't contact node '%s'" %
1985
                               instance.primary_node)
1986

    
1987
    if self.instance.name in ins_l:
1988
      raise errors.OpExecError("Instance is running, can't shutdown"
1989
                               " block devices.")
1990

    
1991
    _ShutdownInstanceDisks(instance, self.cfg)
1992

    
1993

    
1994
def _ShutdownInstanceDisks(instance, cfg, ignore_primary=False):
1995
  """Shutdown block devices of an instance.
1996

1997
  This does the shutdown on all nodes of the instance.
1998

1999
  If the ignore_primary is false, errors on the primary node are
2000
  ignored.
2001

2002
  """
2003
  result = True
2004
  for disk in instance.disks:
2005
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2006
      cfg.SetDiskID(top_disk, node)
2007
      if not rpc.call_blockdev_shutdown(node, top_disk):
2008
        logger.Error("could not shutdown block device %s on node %s" %
2009
                     (disk.iv_name, node))
2010
        if not ignore_primary or node != instance.primary_node:
2011
          result = False
2012
  return result
2013

    
2014

    
2015
def _CheckNodeFreeMemory(cfg, node, reason, requested):
2016
  """Checks if a node has enough free memory.
2017

2018
  This function check if a given node has the needed amount of free
2019
  memory. In case the node has less memory or we cannot get the
2020
  information from the node, this function raise an OpPrereqError
2021
  exception.
2022

2023
  Args:
2024
    - cfg: a ConfigWriter instance
2025
    - node: the node name
2026
    - reason: string to use in the error message
2027
    - requested: the amount of memory in MiB
2028

2029
  """
2030
  nodeinfo = rpc.call_node_info([node], cfg.GetVGName())
2031
  if not nodeinfo or not isinstance(nodeinfo, dict):
2032
    raise errors.OpPrereqError("Could not contact node %s for resource"
2033
                             " information" % (node,))
2034

    
2035
  free_mem = nodeinfo[node].get('memory_free')
2036
  if not isinstance(free_mem, int):
2037
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2038
                             " was '%s'" % (node, free_mem))
2039
  if requested > free_mem:
2040
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2041
                             " needed %s MiB, available %s MiB" %
2042
                             (node, reason, requested, free_mem))
2043

    
2044

    
2045
class LUStartupInstance(LogicalUnit):
2046
  """Starts an instance.
2047

2048
  """
2049
  HPATH = "instance-start"
2050
  HTYPE = constants.HTYPE_INSTANCE
2051
  _OP_REQP = ["instance_name", "force"]
2052

    
2053
  def BuildHooksEnv(self):
2054
    """Build hooks env.
2055

2056
    This runs on master, primary and secondary nodes of the instance.
2057

2058
    """
2059
    env = {
2060
      "FORCE": self.op.force,
2061
      }
2062
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2063
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2064
          list(self.instance.secondary_nodes))
2065
    return env, nl, nl
2066

    
2067
  def CheckPrereq(self):
2068
    """Check prerequisites.
2069

2070
    This checks that the instance is in the cluster.
2071

2072
    """
2073
    instance = self.cfg.GetInstanceInfo(
2074
      self.cfg.ExpandInstanceName(self.op.instance_name))
2075
    if instance is None:
2076
      raise errors.OpPrereqError("Instance '%s' not known" %
2077
                                 self.op.instance_name)
2078

    
2079
    # check bridges existance
2080
    _CheckInstanceBridgesExist(instance)
2081

    
2082
    _CheckNodeFreeMemory(self.cfg, instance.primary_node,
2083
                         "starting instance %s" % instance.name,
2084
                         instance.memory)
2085

    
2086
    self.instance = instance
2087
    self.op.instance_name = instance.name
2088

    
2089
  def Exec(self, feedback_fn):
2090
    """Start the instance.
2091

2092
    """
2093
    instance = self.instance
2094
    force = self.op.force
2095
    extra_args = getattr(self.op, "extra_args", "")
2096

    
2097
    self.cfg.MarkInstanceUp(instance.name)
2098

    
2099
    node_current = instance.primary_node
2100

    
2101
    _StartInstanceDisks(self.cfg, instance, force)
2102

    
2103
    if not rpc.call_instance_start(node_current, instance, extra_args):
2104
      _ShutdownInstanceDisks(instance, self.cfg)
2105
      raise errors.OpExecError("Could not start instance")
2106

    
2107

    
2108
class LURebootInstance(LogicalUnit):
2109
  """Reboot an instance.
2110

2111
  """
2112
  HPATH = "instance-reboot"
2113
  HTYPE = constants.HTYPE_INSTANCE
2114
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2115

    
2116
  def BuildHooksEnv(self):
2117
    """Build hooks env.
2118

2119
    This runs on master, primary and secondary nodes of the instance.
2120

2121
    """
2122
    env = {
2123
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2124
      }
2125
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2126
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2127
          list(self.instance.secondary_nodes))
2128
    return env, nl, nl
2129

    
2130
  def CheckPrereq(self):
2131
    """Check prerequisites.
2132

2133
    This checks that the instance is in the cluster.
2134

2135
    """
2136
    instance = self.cfg.GetInstanceInfo(
2137
      self.cfg.ExpandInstanceName(self.op.instance_name))
2138
    if instance is None:
2139
      raise errors.OpPrereqError("Instance '%s' not known" %
2140
                                 self.op.instance_name)
2141

    
2142
    # check bridges existance
2143
    _CheckInstanceBridgesExist(instance)
2144

    
2145
    self.instance = instance
2146
    self.op.instance_name = instance.name
2147

    
2148
  def Exec(self, feedback_fn):
2149
    """Reboot the instance.
2150

2151
    """
2152
    instance = self.instance
2153
    ignore_secondaries = self.op.ignore_secondaries
2154
    reboot_type = self.op.reboot_type
2155
    extra_args = getattr(self.op, "extra_args", "")
2156

    
2157
    node_current = instance.primary_node
2158

    
2159
    if reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2160
                           constants.INSTANCE_REBOOT_HARD,
2161
                           constants.INSTANCE_REBOOT_FULL]:
2162
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2163
                                  (constants.INSTANCE_REBOOT_SOFT,
2164
                                   constants.INSTANCE_REBOOT_HARD,
2165
                                   constants.INSTANCE_REBOOT_FULL))
2166

    
2167
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2168
                       constants.INSTANCE_REBOOT_HARD]:
2169
      if not rpc.call_instance_reboot(node_current, instance,
2170
                                      reboot_type, extra_args):
2171
        raise errors.OpExecError("Could not reboot instance")
2172
    else:
2173
      if not rpc.call_instance_shutdown(node_current, instance):
2174
        raise errors.OpExecError("could not shutdown instance for full reboot")
2175
      _ShutdownInstanceDisks(instance, self.cfg)
2176
      _StartInstanceDisks(self.cfg, instance, ignore_secondaries)
2177
      if not rpc.call_instance_start(node_current, instance, extra_args):
2178
        _ShutdownInstanceDisks(instance, self.cfg)
2179
        raise errors.OpExecError("Could not start instance for full reboot")
2180

    
2181
    self.cfg.MarkInstanceUp(instance.name)
2182

    
2183

    
2184
class LUShutdownInstance(LogicalUnit):
2185
  """Shutdown an instance.
2186

2187
  """
2188
  HPATH = "instance-stop"
2189
  HTYPE = constants.HTYPE_INSTANCE
2190
  _OP_REQP = ["instance_name"]
2191

    
2192
  def BuildHooksEnv(self):
2193
    """Build hooks env.
2194

2195
    This runs on master, primary and secondary nodes of the instance.
2196

2197
    """
2198
    env = _BuildInstanceHookEnvByObject(self.instance)
2199
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2200
          list(self.instance.secondary_nodes))
2201
    return env, nl, nl
2202

    
2203
  def CheckPrereq(self):
2204
    """Check prerequisites.
2205

2206
    This checks that the instance is in the cluster.
2207

2208
    """
2209
    instance = self.cfg.GetInstanceInfo(
2210
      self.cfg.ExpandInstanceName(self.op.instance_name))
2211
    if instance is None:
2212
      raise errors.OpPrereqError("Instance '%s' not known" %
2213
                                 self.op.instance_name)
2214
    self.instance = instance
2215

    
2216
  def Exec(self, feedback_fn):
2217
    """Shutdown the instance.
2218

2219
    """
2220
    instance = self.instance
2221
    node_current = instance.primary_node
2222
    self.cfg.MarkInstanceDown(instance.name)
2223
    if not rpc.call_instance_shutdown(node_current, instance):
2224
      logger.Error("could not shutdown instance")
2225

    
2226
    _ShutdownInstanceDisks(instance, self.cfg)
2227

    
2228

    
2229
class LUReinstallInstance(LogicalUnit):
2230
  """Reinstall an instance.
2231

2232
  """
2233
  HPATH = "instance-reinstall"
2234
  HTYPE = constants.HTYPE_INSTANCE
2235
  _OP_REQP = ["instance_name"]
2236

    
2237
  def BuildHooksEnv(self):
2238
    """Build hooks env.
2239

2240
    This runs on master, primary and secondary nodes of the instance.
2241

2242
    """
2243
    env = _BuildInstanceHookEnvByObject(self.instance)
2244
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2245
          list(self.instance.secondary_nodes))
2246
    return env, nl, nl
2247

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

2251
    This checks that the instance is in the cluster and is not running.
2252

2253
    """
2254
    instance = self.cfg.GetInstanceInfo(
2255
      self.cfg.ExpandInstanceName(self.op.instance_name))
2256
    if instance is None:
2257
      raise errors.OpPrereqError("Instance '%s' not known" %
2258
                                 self.op.instance_name)
2259
    if instance.disk_template == constants.DT_DISKLESS:
2260
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2261
                                 self.op.instance_name)
2262
    if instance.status != "down":
2263
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2264
                                 self.op.instance_name)
2265
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2266
    if remote_info:
2267
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2268
                                 (self.op.instance_name,
2269
                                  instance.primary_node))
2270

    
2271
    self.op.os_type = getattr(self.op, "os_type", None)
2272
    if self.op.os_type is not None:
2273
      # OS verification
2274
      pnode = self.cfg.GetNodeInfo(
2275
        self.cfg.ExpandNodeName(instance.primary_node))
2276
      if pnode is None:
2277
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2278
                                   self.op.pnode)
2279
      os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
2280
      if not os_obj:
2281
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2282
                                   " primary node"  % self.op.os_type)
2283

    
2284
    self.instance = instance
2285

    
2286
  def Exec(self, feedback_fn):
2287
    """Reinstall the instance.
2288

2289
    """
2290
    inst = self.instance
2291

    
2292
    if self.op.os_type is not None:
2293
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2294
      inst.os = self.op.os_type
2295
      self.cfg.AddInstance(inst)
2296

    
2297
    _StartInstanceDisks(self.cfg, inst, None)
2298
    try:
2299
      feedback_fn("Running the instance OS create scripts...")
2300
      if not rpc.call_instance_os_add(inst.primary_node, inst, "sda", "sdb"):
2301
        raise errors.OpExecError("Could not install OS for instance %s"
2302
                                 " on node %s" %
2303
                                 (inst.name, inst.primary_node))
2304
    finally:
2305
      _ShutdownInstanceDisks(inst, self.cfg)
2306

    
2307

    
2308
class LURenameInstance(LogicalUnit):
2309
  """Rename an instance.
2310

2311
  """
2312
  HPATH = "instance-rename"
2313
  HTYPE = constants.HTYPE_INSTANCE
2314
  _OP_REQP = ["instance_name", "new_name"]
2315

    
2316
  def BuildHooksEnv(self):
2317
    """Build hooks env.
2318

2319
    This runs on master, primary and secondary nodes of the instance.
2320

2321
    """
2322
    env = _BuildInstanceHookEnvByObject(self.instance)
2323
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2324
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2325
          list(self.instance.secondary_nodes))
2326
    return env, nl, nl
2327

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

2331
    This checks that the instance is in the cluster and is not running.
2332

2333
    """
2334
    instance = self.cfg.GetInstanceInfo(
2335
      self.cfg.ExpandInstanceName(self.op.instance_name))
2336
    if instance is None:
2337
      raise errors.OpPrereqError("Instance '%s' not known" %
2338
                                 self.op.instance_name)
2339
    if instance.status != "down":
2340
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2341
                                 self.op.instance_name)
2342
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2343
    if remote_info:
2344
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2345
                                 (self.op.instance_name,
2346
                                  instance.primary_node))
2347
    self.instance = instance
2348

    
2349
    # new name verification
2350
    name_info = utils.HostInfo(self.op.new_name)
2351

    
2352
    self.op.new_name = new_name = name_info.name
2353
    instance_list = self.cfg.GetInstanceList()
2354
    if new_name in instance_list:
2355
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2356
                                 instance_name)
2357

    
2358
    if not getattr(self.op, "ignore_ip", False):
2359
      command = ["fping", "-q", name_info.ip]
2360
      result = utils.RunCmd(command)
2361
      if not result.failed:
2362
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2363
                                   (name_info.ip, new_name))
2364

    
2365

    
2366
  def Exec(self, feedback_fn):
2367
    """Reinstall the instance.
2368

2369
    """
2370
    inst = self.instance
2371
    old_name = inst.name
2372

    
2373
    if inst.disk_template == constants.DT_FILE:
2374
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2375

    
2376
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2377

    
2378
    # re-read the instance from the configuration after rename
2379
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2380

    
2381
    if inst.disk_template == constants.DT_FILE:
2382
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2383
      result = rpc.call_file_storage_dir_rename(inst.primary_node,
2384
                                                old_file_storage_dir,
2385
                                                new_file_storage_dir)
2386

    
2387
      if not result:
2388
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2389
                                 " directory '%s' to '%s' (but the instance"
2390
                                 " has been renamed in Ganeti)" % (
2391
                                 inst.primary_node, old_file_storage_dir,
2392
                                 new_file_storage_dir))
2393

    
2394
      if not result[0]:
2395
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2396
                                 " (but the instance has been renamed in"
2397
                                 " Ganeti)" % (old_file_storage_dir,
2398
                                               new_file_storage_dir))
2399

    
2400
    _StartInstanceDisks(self.cfg, inst, None)
2401
    try:
2402
      if not rpc.call_instance_run_rename(inst.primary_node, inst, old_name,
2403
                                          "sda", "sdb"):
2404
        msg = ("Could run OS rename script for instance %s on node %s (but the"
2405
               " instance has been renamed in Ganeti)" %
2406
               (inst.name, inst.primary_node))
2407
        logger.Error(msg)
2408
    finally:
2409
      _ShutdownInstanceDisks(inst, self.cfg)
2410

    
2411

    
2412
class LURemoveInstance(LogicalUnit):
2413
  """Remove an instance.
2414

2415
  """
2416
  HPATH = "instance-remove"
2417
  HTYPE = constants.HTYPE_INSTANCE
2418
  _OP_REQP = ["instance_name"]
2419

    
2420
  def BuildHooksEnv(self):
2421
    """Build hooks env.
2422

2423
    This runs on master, primary and secondary nodes of the instance.
2424

2425
    """
2426
    env = _BuildInstanceHookEnvByObject(self.instance)
2427
    nl = [self.sstore.GetMasterNode()]
2428
    return env, nl, nl
2429

    
2430
  def CheckPrereq(self):
2431
    """Check prerequisites.
2432

2433
    This checks that the instance is in the cluster.
2434

2435
    """
2436
    instance = self.cfg.GetInstanceInfo(
2437
      self.cfg.ExpandInstanceName(self.op.instance_name))
2438
    if instance is None:
2439
      raise errors.OpPrereqError("Instance '%s' not known" %
2440
                                 self.op.instance_name)
2441
    self.instance = instance
2442

    
2443
  def Exec(self, feedback_fn):
2444
    """Remove the instance.
2445

2446
    """
2447
    instance = self.instance
2448
    logger.Info("shutting down instance %s on node %s" %
2449
                (instance.name, instance.primary_node))
2450

    
2451
    if not rpc.call_instance_shutdown(instance.primary_node, instance):
2452
      if self.op.ignore_failures:
2453
        feedback_fn("Warning: can't shutdown instance")
2454
      else:
2455
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2456
                                 (instance.name, instance.primary_node))
2457

    
2458
    logger.Info("removing block devices for instance %s" % instance.name)
2459

    
2460
    if not _RemoveDisks(instance, self.cfg):
2461
      if self.op.ignore_failures:
2462
        feedback_fn("Warning: can't remove instance's disks")
2463
      else:
2464
        raise errors.OpExecError("Can't remove instance's disks")
2465

    
2466
    logger.Info("removing instance %s out of cluster config" % instance.name)
2467

    
2468
    self.cfg.RemoveInstance(instance.name)
2469

    
2470

    
2471
class LUQueryInstances(NoHooksLU):
2472
  """Logical unit for querying instances.
2473

2474
  """
2475
  _OP_REQP = ["output_fields", "names"]
2476

    
2477
  def CheckPrereq(self):
2478
    """Check prerequisites.
2479

2480
    This checks that the fields required are valid output fields.
2481

2482
    """
2483
    self.dynamic_fields = frozenset(["oper_state", "oper_ram", "status"])
2484
    _CheckOutputFields(static=["name", "os", "pnode", "snodes",
2485
                               "admin_state", "admin_ram",
2486
                               "disk_template", "ip", "mac", "bridge",
2487
                               "sda_size", "sdb_size", "vcpus"],
2488
                       dynamic=self.dynamic_fields,
2489
                       selected=self.op.output_fields)
2490

    
2491
    self.wanted = _GetWantedInstances(self, self.op.names)
2492

    
2493
  def Exec(self, feedback_fn):
2494
    """Computes the list of nodes and their attributes.
2495

2496
    """
2497
    instance_names = self.wanted
2498
    instance_list = [self.cfg.GetInstanceInfo(iname) for iname
2499
                     in instance_names]
2500

    
2501
    # begin data gathering
2502

    
2503
    nodes = frozenset([inst.primary_node for inst in instance_list])
2504

    
2505
    bad_nodes = []
2506
    if self.dynamic_fields.intersection(self.op.output_fields):
2507
      live_data = {}
2508
      node_data = rpc.call_all_instances_info(nodes)
2509
      for name in nodes:
2510
        result = node_data[name]
2511
        if result:
2512
          live_data.update(result)
2513
        elif result == False:
2514
          bad_nodes.append(name)
2515
        # else no instance is alive
2516
    else:
2517
      live_data = dict([(name, {}) for name in instance_names])
2518

    
2519
    # end data gathering
2520

    
2521
    output = []
2522
    for instance in instance_list:
2523
      iout = []
2524
      for field in self.op.output_fields:
2525
        if field == "name":
2526
          val = instance.name
2527
        elif field == "os":
2528
          val = instance.os
2529
        elif field == "pnode":
2530
          val = instance.primary_node
2531
        elif field == "snodes":
2532
          val = list(instance.secondary_nodes)
2533
        elif field == "admin_state":
2534
          val = (instance.status != "down")
2535
        elif field == "oper_state":
2536
          if instance.primary_node in bad_nodes:
2537
            val = None
2538
          else:
2539
            val = bool(live_data.get(instance.name))
2540
        elif field == "status":
2541
          if instance.primary_node in bad_nodes:
2542
            val = "ERROR_nodedown"
2543
          else:
2544
            running = bool(live_data.get(instance.name))
2545
            if running:
2546
              if instance.status != "down":
2547
                val = "running"
2548
              else:
2549
                val = "ERROR_up"
2550
            else:
2551
              if instance.status != "down":
2552
                val = "ERROR_down"
2553
              else:
2554
                val = "ADMIN_down"
2555
        elif field == "admin_ram":
2556
          val = instance.memory
2557
        elif field == "oper_ram":
2558
          if instance.primary_node in bad_nodes:
2559
            val = None
2560
          elif instance.name in live_data:
2561
            val = live_data[instance.name].get("memory", "?")
2562
          else:
2563
            val = "-"
2564
        elif field == "disk_template":
2565
          val = instance.disk_template
2566
        elif field == "ip":
2567
          val = instance.nics[0].ip
2568
        elif field == "bridge":
2569
          val = instance.nics[0].bridge
2570
        elif field == "mac":
2571
          val = instance.nics[0].mac
2572
        elif field == "sda_size" or field == "sdb_size":
2573
          disk = instance.FindDisk(field[:3])
2574
          if disk is None:
2575
            val = None
2576
          else:
2577
            val = disk.size
2578
        elif field == "vcpus":
2579
          val = instance.vcpus
2580
        else:
2581
          raise errors.ParameterError(field)
2582
        iout.append(val)
2583
      output.append(iout)
2584

    
2585
    return output
2586

    
2587

    
2588
class LUFailoverInstance(LogicalUnit):
2589
  """Failover an instance.
2590

2591
  """
2592
  HPATH = "instance-failover"
2593
  HTYPE = constants.HTYPE_INSTANCE
2594
  _OP_REQP = ["instance_name", "ignore_consistency"]
2595

    
2596
  def BuildHooksEnv(self):
2597
    """Build hooks env.
2598

2599
    This runs on master, primary and secondary nodes of the instance.
2600

2601
    """
2602
    env = {
2603
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2604
      }
2605
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2606
    nl = [self.sstore.GetMasterNode()] + list(self.instance.secondary_nodes)
2607
    return env, nl, nl
2608

    
2609
  def CheckPrereq(self):
2610
    """Check prerequisites.
2611

2612
    This checks that the instance is in the cluster.
2613

2614
    """
2615
    instance = self.cfg.GetInstanceInfo(
2616
      self.cfg.ExpandInstanceName(self.op.instance_name))
2617
    if instance is None:
2618
      raise errors.OpPrereqError("Instance '%s' not known" %
2619
                                 self.op.instance_name)
2620

    
2621
    if instance.disk_template not in constants.DTS_NET_MIRROR:
2622
      raise errors.OpPrereqError("Instance's disk layout is not"
2623
                                 " network mirrored, cannot failover.")
2624

    
2625
    secondary_nodes = instance.secondary_nodes
2626
    if not secondary_nodes:
2627
      raise errors.ProgrammerError("no secondary node but using "
2628
                                   "DT_REMOTE_RAID1 template")
2629

    
2630
    target_node = secondary_nodes[0]
2631
    # check memory requirements on the secondary node
2632
    _CheckNodeFreeMemory(self.cfg, target_node, "failing over instance %s" %
2633
                         instance.name, instance.memory)
2634

    
2635
    # check bridge existance
2636
    brlist = [nic.bridge for nic in instance.nics]
2637
    if not rpc.call_bridges_exist(target_node, brlist):
2638
      raise errors.OpPrereqError("One or more target bridges %s does not"
2639
                                 " exist on destination node '%s'" %
2640
                                 (brlist, target_node))
2641

    
2642
    self.instance = instance
2643

    
2644
  def Exec(self, feedback_fn):
2645
    """Failover an instance.
2646

2647
    The failover is done by shutting it down on its present node and
2648
    starting it on the secondary.
2649

2650
    """
2651
    instance = self.instance
2652

    
2653
    source_node = instance.primary_node
2654
    target_node = instance.secondary_nodes[0]
2655

    
2656
    feedback_fn("* checking disk consistency between source and target")
2657
    for dev in instance.disks:
2658
      # for remote_raid1, these are md over drbd
2659
      if not _CheckDiskConsistency(self.cfg, dev, target_node, False):
2660
        if instance.status == "up" and not self.op.ignore_consistency:
2661
          raise errors.OpExecError("Disk %s is degraded on target node,"
2662
                                   " aborting failover." % dev.iv_name)
2663

    
2664
    feedback_fn("* shutting down instance on source node")
2665
    logger.Info("Shutting down instance %s on node %s" %
2666
                (instance.name, source_node))
2667

    
2668
    if not rpc.call_instance_shutdown(source_node, instance):
2669
      if self.op.ignore_consistency:
2670
        logger.Error("Could not shutdown instance %s on node %s. Proceeding"
2671
                     " anyway. Please make sure node %s is down"  %
2672
                     (instance.name, source_node, source_node))
2673
      else:
2674
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2675
                                 (instance.name, source_node))
2676

    
2677
    feedback_fn("* deactivating the instance's disks on source node")
2678
    if not _ShutdownInstanceDisks(instance, self.cfg, ignore_primary=True):
2679
      raise errors.OpExecError("Can't shut down the instance's disks.")
2680

    
2681
    instance.primary_node = target_node
2682
    # distribute new instance config to the other nodes
2683
    self.cfg.AddInstance(instance)
2684

    
2685
    # Only start the instance if it's marked as up
2686
    if instance.status == "up":
2687
      feedback_fn("* activating the instance's disks on target node")
2688
      logger.Info("Starting instance %s on node %s" %
2689
                  (instance.name, target_node))
2690

    
2691
      disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
2692
                                               ignore_secondaries=True)
2693
      if not disks_ok:
2694
        _ShutdownInstanceDisks(instance, self.cfg)
2695
        raise errors.OpExecError("Can't activate the instance's disks")
2696

    
2697
      feedback_fn("* starting the instance on the target node")
2698
      if not rpc.call_instance_start(target_node, instance, None):
2699
        _ShutdownInstanceDisks(instance, self.cfg)
2700
        raise errors.OpExecError("Could not start instance %s on node %s." %
2701
                                 (instance.name, target_node))
2702

    
2703

    
2704
def _CreateBlockDevOnPrimary(cfg, node, instance, device, info):
2705
  """Create a tree of block devices on the primary node.
2706

2707
  This always creates all devices.
2708

2709
  """
2710
  if device.children:
2711
    for child in device.children:
2712
      if not _CreateBlockDevOnPrimary(cfg, node, instance, child, info):
2713
        return False
2714

    
2715
  cfg.SetDiskID(device, node)
2716
  new_id = rpc.call_blockdev_create(node, device, device.size,
2717
                                    instance.name, True, info)
2718
  if not new_id:
2719
    return False
2720
  if device.physical_id is None:
2721
    device.physical_id = new_id
2722
  return True
2723

    
2724

    
2725
def _CreateBlockDevOnSecondary(cfg, node, instance, device, force, info):
2726
  """Create a tree of block devices on a secondary node.
2727

2728
  If this device type has to be created on secondaries, create it and
2729
  all its children.
2730

2731
  If not, just recurse to children keeping the same 'force' value.
2732

2733
  """
2734
  if device.CreateOnSecondary():
2735
    force = True
2736
  if device.children:
2737
    for child in device.children:
2738
      if not _CreateBlockDevOnSecondary(cfg, node, instance,
2739
                                        child, force, info):
2740
        return False
2741

    
2742
  if not force:
2743
    return True
2744
  cfg.SetDiskID(device, node)
2745
  new_id = rpc.call_blockdev_create(node, device, device.size,
2746
                                    instance.name, False, info)
2747
  if not new_id:
2748
    return False
2749
  if device.physical_id is None:
2750
    device.physical_id = new_id
2751
  return True
2752

    
2753

    
2754
def _GenerateUniqueNames(cfg, exts):
2755
  """Generate a suitable LV name.
2756

2757
  This will generate a logical volume name for the given instance.
2758

2759
  """
2760
  results = []
2761
  for val in exts:
2762
    new_id = cfg.GenerateUniqueID()
2763
    results.append("%s%s" % (new_id, val))
2764
  return results
2765

    
2766

    
2767
def _GenerateMDDRBDBranch(cfg, primary, secondary, size, names):
2768
  """Generate a drbd device complete with its children.
2769

2770
  """
2771
  port = cfg.AllocatePort()
2772
  vgname = cfg.GetVGName()
2773
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
2774
                          logical_id=(vgname, names[0]))
2775
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
2776
                          logical_id=(vgname, names[1]))
2777
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD7, size=size,
2778
                          logical_id = (primary, secondary, port),
2779
                          children = [dev_data, dev_meta])
2780
  return drbd_dev
2781

    
2782

    
2783
def _GenerateDRBD8Branch(cfg, primary, secondary, size, names, iv_name):
2784
  """Generate a drbd8 device complete with its children.
2785

2786
  """
2787
  port = cfg.AllocatePort()
2788
  vgname = cfg.GetVGName()
2789
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
2790
                          logical_id=(vgname, names[0]))
2791
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
2792
                          logical_id=(vgname, names[1]))
2793
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
2794
                          logical_id = (primary, secondary, port),
2795
                          children = [dev_data, dev_meta],
2796
                          iv_name=iv_name)
2797
  return drbd_dev
2798

    
2799

    
2800
def _GenerateDiskTemplate(cfg, template_name,
2801
                          instance_name, primary_node,
2802
                          secondary_nodes, disk_sz, swap_sz,
2803
                          file_storage_dir, file_driver):
2804
  """Generate the entire disk layout for a given template type.
2805

2806
  """
2807
  #TODO: compute space requirements
2808

    
2809
  vgname = cfg.GetVGName()
2810
  if template_name == constants.DT_DISKLESS:
2811
    disks = []
2812
  elif template_name == constants.DT_PLAIN:
2813
    if len(secondary_nodes) != 0:
2814
      raise errors.ProgrammerError("Wrong template configuration")
2815

    
2816
    names = _GenerateUniqueNames(cfg, [".sda", ".sdb"])
2817
    sda_dev = objects.Disk(dev_type=constants.LD_LV, size=disk_sz,
2818
                           logical_id=(vgname, names[0]),
2819
                           iv_name = "sda")
2820
    sdb_dev = objects.Disk(dev_type=constants.LD_LV, size=swap_sz,
2821
                           logical_id=(vgname, names[1]),
2822
                           iv_name = "sdb")
2823
    disks = [sda_dev, sdb_dev]
2824
  elif template_name == constants.DT_DRBD8:
2825
    if len(secondary_nodes) != 1:
2826
      raise errors.ProgrammerError("Wrong template configuration")
2827
    remote_node = secondary_nodes[0]
2828
    names = _GenerateUniqueNames(cfg, [".sda_data", ".sda_meta",
2829
                                       ".sdb_data", ".sdb_meta"])
2830
    drbd_sda_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2831
                                         disk_sz, names[0:2], "sda")
2832
    drbd_sdb_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2833
                                         swap_sz, names[2:4], "sdb")
2834
    disks = [drbd_sda_dev, drbd_sdb_dev]
2835
  elif template_name == constants.DT_FILE:
2836
    if len(secondary_nodes) != 0:
2837
      raise errors.ProgrammerError("Wrong template configuration")
2838

    
2839
    file_sda_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk_sz,
2840
                                iv_name="sda", logical_id=(file_driver,
2841
                                "%s/sda" % file_storage_dir))
2842
    file_sdb_dev = objects.Disk(dev_type=constants.LD_FILE, size=swap_sz,
2843
                                iv_name="sdb", logical_id=(file_driver,
2844
                                "%s/sdb" % file_storage_dir))
2845
    disks = [file_sda_dev, file_sdb_dev]
2846
  else:
2847
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
2848
  return disks
2849

    
2850

    
2851
def _GetInstanceInfoText(instance):
2852
  """Compute that text that should be added to the disk's metadata.
2853

2854
  """
2855
  return "originstname+%s" % instance.name
2856

    
2857

    
2858
def _CreateDisks(cfg, instance):
2859
  """Create all disks for an instance.
2860

2861
  This abstracts away some work from AddInstance.
2862

2863
  Args:
2864
    instance: the instance object
2865

2866
  Returns:
2867
    True or False showing the success of the creation process
2868

2869
  """
2870
  info = _GetInstanceInfoText(instance)
2871

    
2872
  if instance.disk_template == constants.DT_FILE:
2873
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
2874
    result = rpc.call_file_storage_dir_create(instance.primary_node,
2875
                                              file_storage_dir)
2876

    
2877
    if not result:
2878
      logger.Error("Could not connect to node '%s'" % inst.primary_node)
2879
      return False
2880

    
2881
    if not result[0]:
2882
      logger.Error("failed to create directory '%s'" % file_storage_dir)
2883
      return False
2884

    
2885
  for device in instance.disks:
2886
    logger.Info("creating volume %s for instance %s" %
2887
                (device.iv_name, instance.name))
2888
    #HARDCODE
2889
    for secondary_node in instance.secondary_nodes:
2890
      if not _CreateBlockDevOnSecondary(cfg, secondary_node, instance,
2891
                                        device, False, info):
2892
        logger.Error("failed to create volume %s (%s) on secondary node %s!" %
2893
                     (device.iv_name, device, secondary_node))
2894
        return False
2895
    #HARDCODE
2896
    if not _CreateBlockDevOnPrimary(cfg, instance.primary_node,
2897
                                    instance, device, info):
2898
      logger.Error("failed to create volume %s on primary!" %
2899
                   device.iv_name)
2900
      return False
2901

    
2902
  return True
2903

    
2904

    
2905
def _RemoveDisks(instance, cfg):
2906
  """Remove all disks for an instance.
2907

2908
  This abstracts away some work from `AddInstance()` and
2909
  `RemoveInstance()`. Note that in case some of the devices couldn't
2910
  be removed, the removal will continue with the other ones (compare
2911
  with `_CreateDisks()`).
2912

2913
  Args:
2914
    instance: the instance object
2915

2916
  Returns:
2917
    True or False showing the success of the removal proces
2918

2919
  """
2920
  logger.Info("removing block devices for instance %s" % instance.name)
2921

    
2922
  result = True
2923
  for device in instance.disks:
2924
    for node, disk in device.ComputeNodeTree(instance.primary_node):
2925
      cfg.SetDiskID(disk, node)
2926
      if not rpc.call_blockdev_remove(node, disk):
2927
        logger.Error("could not remove block device %s on node %s,"
2928
                     " continuing anyway" %
2929
                     (device.iv_name, node))
2930
        result = False
2931

    
2932
  if instance.disk_template == constants.DT_FILE:
2933
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
2934
    if not rpc.call_file_storage_dir_remove(instance.primary_node,
2935
                                            file_storage_dir):
2936
      logger.Error("could not remove directory '%s'" % file_storage_dir)
2937
      result = False
2938

    
2939
  return result
2940

    
2941

    
2942
class LUCreateInstance(LogicalUnit):
2943
  """Create an instance.
2944

2945
  """
2946
  HPATH = "instance-add"
2947
  HTYPE = constants.HTYPE_INSTANCE
2948
  _OP_REQP = ["instance_name", "mem_size", "disk_size", "pnode",
2949
              "disk_template", "swap_size", "mode", "start", "vcpus",
2950
              "wait_for_sync", "ip_check", "mac"]
2951

    
2952
  def BuildHooksEnv(self):
2953
    """Build hooks env.
2954

2955
    This runs on master, primary and secondary nodes of the instance.
2956

2957
    """
2958
    env = {
2959
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
2960
      "INSTANCE_DISK_SIZE": self.op.disk_size,
2961
      "INSTANCE_SWAP_SIZE": self.op.swap_size,
2962
      "INSTANCE_ADD_MODE": self.op.mode,
2963
      }
2964
    if self.op.mode == constants.INSTANCE_IMPORT:
2965
      env["INSTANCE_SRC_NODE"] = self.op.src_node
2966
      env["INSTANCE_SRC_PATH"] = self.op.src_path
2967
      env["INSTANCE_SRC_IMAGE"] = self.src_image
2968

    
2969
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
2970
      primary_node=self.op.pnode,
2971
      secondary_nodes=self.secondaries,
2972
      status=self.instance_status,
2973
      os_type=self.op.os_type,
2974
      memory=self.op.mem_size,
2975
      vcpus=self.op.vcpus,
2976
      nics=[(self.inst_ip, self.op.bridge, self.op.mac)],
2977
    ))
2978

    
2979
    nl = ([self.sstore.GetMasterNode(), self.op.pnode] +
2980
          self.secondaries)
2981
    return env, nl, nl
2982

    
2983

    
2984
  def CheckPrereq(self):
2985
    """Check prerequisites.
2986

2987
    """
2988
    for attr in ["kernel_path", "initrd_path", "hvm_boot_order"]:
2989
      if not hasattr(self.op, attr):
2990
        setattr(self.op, attr, None)
2991

    
2992
    if self.op.mode not in (constants.INSTANCE_CREATE,
2993
                            constants.INSTANCE_IMPORT):
2994
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
2995
                                 self.op.mode)
2996

    
2997
    if (not self.cfg.GetVGName() and
2998
        self.op.disk_template not in constants.DTS_NOT_LVM):
2999
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3000
                                 " instances")
3001

    
3002
    if self.op.mode == constants.INSTANCE_IMPORT:
3003
      src_node = getattr(self.op, "src_node", None)
3004
      src_path = getattr(self.op, "src_path", None)
3005
      if src_node is None or src_path is None:
3006
        raise errors.OpPrereqError("Importing an instance requires source"
3007
                                   " node and path options")
3008
      src_node_full = self.cfg.ExpandNodeName(src_node)
3009
      if src_node_full is None:
3010
        raise errors.OpPrereqError("Unknown source node '%s'" % src_node)
3011
      self.op.src_node = src_node = src_node_full
3012

    
3013
      if not os.path.isabs(src_path):
3014
        raise errors.OpPrereqError("The source path must be absolute")
3015

    
3016
      export_info = rpc.call_export_info(src_node, src_path)
3017

    
3018
      if not export_info:
3019
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3020

    
3021
      if not export_info.has_section(constants.INISECT_EXP):
3022
        raise errors.ProgrammerError("Corrupted export config")
3023

    
3024
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3025
      if (int(ei_version) != constants.EXPORT_VERSION):
3026
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3027
                                   (ei_version, constants.EXPORT_VERSION))
3028

    
3029
      if int(export_info.get(constants.INISECT_INS, 'disk_count')) > 1:
3030
        raise errors.OpPrereqError("Can't import instance with more than"
3031
                                   " one data disk")
3032

    
3033
      # FIXME: are the old os-es, disk sizes, etc. useful?
3034
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3035
      diskimage = os.path.join(src_path, export_info.get(constants.INISECT_INS,
3036
                                                         'disk0_dump'))
3037
      self.src_image = diskimage
3038
    else: # INSTANCE_CREATE
3039
      if getattr(self.op, "os_type", None) is None:
3040
        raise errors.OpPrereqError("No guest OS specified")
3041

    
3042
    # check primary node
3043
    pnode = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.pnode))
3044
    if pnode is None:
3045
      raise errors.OpPrereqError("Primary node '%s' is unknown" %
3046
                                 self.op.pnode)
3047
    self.op.pnode = pnode.name
3048
    self.pnode = pnode
3049
    self.secondaries = []
3050
    # disk template and mirror node verification
3051
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3052
      raise errors.OpPrereqError("Invalid disk template name")
3053

    
3054
    if (self.op.file_driver and
3055
        not self.op.file_driver in constants.FILE_DRIVER):
3056
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3057
                                 self.op.file_driver)
3058

    
3059
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3060
        raise errors.OpPrereqError("File storage directory not a relative"
3061
                                   " path")
3062

    
3063
    if self.op.disk_template in constants.DTS_NET_MIRROR:
3064
      if getattr(self.op, "snode", None) is None:
3065
        raise errors.OpPrereqError("The networked disk templates need"
3066
                                   " a mirror node")
3067

    
3068
      snode_name = self.cfg.ExpandNodeName(self.op.snode)
3069
      if snode_name is None:
3070
        raise errors.OpPrereqError("Unknown secondary node '%s'" %
3071
                                   self.op.snode)
3072
      elif snode_name == pnode.name:
3073
        raise errors.OpPrereqError("The secondary node cannot be"
3074
                                   " the primary node.")
3075
      self.secondaries.append(snode_name)
3076

    
3077
    # Required free disk space as a function of disk and swap space
3078
    req_size_dict = {
3079
      constants.DT_DISKLESS: None,
3080
      constants.DT_PLAIN: self.op.disk_size + self.op.swap_size,
3081
      # 256 MB are added for drbd metadata, 128MB for each drbd device
3082
      constants.DT_DRBD8: self.op.disk_size + self.op.swap_size + 256,
3083
      constants.DT_FILE: None,
3084
    }
3085

    
3086
    if self.op.disk_template not in req_size_dict:
3087
      raise errors.ProgrammerError("Disk template '%s' size requirement"
3088
                                   " is unknown" %  self.op.disk_template)
3089

    
3090
    req_size = req_size_dict[self.op.disk_template]
3091

    
3092
    # Check lv size requirements
3093
    if req_size is not None:
3094
      nodenames = [pnode.name] + self.secondaries
3095
      nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
3096
      for node in nodenames:
3097
        info = nodeinfo.get(node, None)
3098
        if not info:
3099
          raise errors.OpPrereqError("Cannot get current information"
3100
                                     " from node '%s'" % nodeinfo)
3101
        vg_free = info.get('vg_free', None)
3102
        if not isinstance(vg_free, int):
3103
          raise errors.OpPrereqError("Can't compute free disk space on"
3104
                                     " node %s" % node)
3105
        if req_size > info['vg_free']:
3106
          raise errors.OpPrereqError("Not enough disk space on target node %s."
3107
                                     " %d MB available, %d MB required" %
3108
                                     (node, info['vg_free'], req_size))
3109

    
3110
    # os verification
3111
    os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
3112
    if not os_obj:
3113
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
3114
                                 " primary node"  % self.op.os_type)
3115

    
3116
    if self.op.kernel_path == constants.VALUE_NONE:
3117
      raise errors.OpPrereqError("Can't set instance kernel to none")
3118

    
3119
    # instance verification
3120
    hostname1 = utils.HostInfo(self.op.instance_name)
3121

    
3122
    self.op.instance_name = instance_name = hostname1.name
3123
    instance_list = self.cfg.GetInstanceList()
3124
    if instance_name in instance_list:
3125
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3126
                                 instance_name)
3127

    
3128
    ip = getattr(self.op, "ip", None)
3129
    if ip is None or ip.lower() == "none":
3130
      inst_ip = None
3131
    elif ip.lower() == "auto":
3132
      inst_ip = hostname1.ip
3133
    else:
3134
      if not utils.IsValidIP(ip):
3135
        raise errors.OpPrereqError("given IP address '%s' doesn't look"
3136
                                   " like a valid IP" % ip)
3137
      inst_ip = ip
3138
    self.inst_ip = inst_ip
3139

    
3140
    if self.op.start and not self.op.ip_check:
3141
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
3142
                                 " adding an instance in start mode")
3143

    
3144
    if self.op.ip_check:
3145
      if utils.TcpPing(hostname1.ip, constants.DEFAULT_NODED_PORT):
3146
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3147
                                   (hostname1.ip, instance_name))
3148

    
3149
    # MAC address verification
3150
    if self.op.mac != "auto":
3151
      if not utils.IsValidMac(self.op.mac.lower()):
3152
        raise errors.OpPrereqError("invalid MAC address specified: %s" %
3153
                                   self.op.mac)
3154

    
3155
    # bridge verification
3156
    bridge = getattr(self.op, "bridge", None)
3157
    if bridge is None:
3158
      self.op.bridge = self.cfg.GetDefBridge()
3159
    else:
3160
      self.op.bridge = bridge
3161

    
3162
    if not rpc.call_bridges_exist(self.pnode.name, [self.op.bridge]):
3163
      raise errors.OpPrereqError("target bridge '%s' does not exist on"
3164
                                 " destination node '%s'" %
3165
                                 (self.op.bridge, pnode.name))
3166

    
3167
    # boot order verification
3168
    if self.op.hvm_boot_order is not None:
3169
      if len(self.op.hvm_boot_order.strip("acdn")) != 0:
3170
        raise errors.OpPrereqError("invalid boot order specified,"
3171
                                   " must be one or more of [acdn]")
3172

    
3173
    if self.op.start:
3174
      self.instance_status = 'up'
3175
    else:
3176
      self.instance_status = 'down'
3177

    
3178
  def Exec(self, feedback_fn):
3179
    """Create and add the instance to the cluster.
3180

3181
    """
3182
    instance = self.op.instance_name
3183
    pnode_name = self.pnode.name
3184

    
3185
    if self.op.mac == "auto":
3186
      mac_address = self.cfg.GenerateMAC()
3187
    else:
3188
      mac_address = self.op.mac
3189

    
3190
    nic = objects.NIC(bridge=self.op.bridge, mac=mac_address)
3191
    if self.inst_ip is not None:
3192
      nic.ip = self.inst_ip
3193

    
3194
    ht_kind = self.sstore.GetHypervisorType()
3195
    if ht_kind in constants.HTS_REQ_PORT:
3196
      network_port = self.cfg.AllocatePort()
3197
    else:
3198
      network_port = None
3199

    
3200
    # this is needed because os.path.join does not accept None arguments
3201
    if self.op.file_storage_dir is None:
3202
      string_file_storage_dir = ""
3203
    else:
3204
      string_file_storage_dir = self.op.file_storage_dir
3205

    
3206
    # build the full file storage dir path
3207
    file_storage_dir = os.path.normpath(os.path.join(
3208
                                        self.sstore.GetFileStorageDir(),
3209
                                        string_file_storage_dir, instance))
3210

    
3211

    
3212
    disks = _GenerateDiskTemplate(self.cfg,
3213
                                  self.op.disk_template,
3214
                                  instance, pnode_name,
3215
                                  self.secondaries, self.op.disk_size,
3216
                                  self.op.swap_size,
3217
                                  file_storage_dir,
3218
                                  self.op.file_driver)
3219

    
3220
    iobj = objects.Instance(name=instance, os=self.op.os_type,
3221
                            primary_node=pnode_name,
3222
                            memory=self.op.mem_size,
3223
                            vcpus=self.op.vcpus,
3224
                            nics=[nic], disks=disks,
3225
                            disk_template=self.op.disk_template,
3226
                            status=self.instance_status,
3227
                            network_port=network_port,
3228
                            kernel_path=self.op.kernel_path,
3229
                            initrd_path=self.op.initrd_path,
3230
                            hvm_boot_order=self.op.hvm_boot_order,
3231
                            )
3232

    
3233
    feedback_fn("* creating instance disks...")
3234
    if not _CreateDisks(self.cfg, iobj):
3235
      _RemoveDisks(iobj, self.cfg)
3236
      raise errors.OpExecError("Device creation failed, reverting...")
3237

    
3238
    feedback_fn("adding instance %s to cluster config" % instance)
3239

    
3240
    self.cfg.AddInstance(iobj)
3241

    
3242
    if self.op.wait_for_sync:
3243
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc)
3244
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
3245
      # make sure the disks are not degraded (still sync-ing is ok)
3246
      time.sleep(15)
3247
      feedback_fn("* checking mirrors status")
3248
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc, oneshot=True)
3249
    else:
3250
      disk_abort = False
3251

    
3252
    if disk_abort:
3253
      _RemoveDisks(iobj, self.cfg)
3254
      self.cfg.RemoveInstance(iobj.name)
3255
      raise errors.OpExecError("There are some degraded disks for"
3256
                               " this instance")
3257

    
3258
    feedback_fn("creating os for instance %s on node %s" %
3259
                (instance, pnode_name))
3260

    
3261
    if iobj.disk_template != constants.DT_DISKLESS:
3262
      if self.op.mode == constants.INSTANCE_CREATE:
3263
        feedback_fn("* running the instance OS create scripts...")
3264
        if not rpc.call_instance_os_add(pnode_name, iobj, "sda", "sdb"):
3265
          raise errors.OpExecError("could not add os for instance %s"
3266
                                   " on node %s" %
3267
                                   (instance, pnode_name))
3268

    
3269
      elif self.op.mode == constants.INSTANCE_IMPORT:
3270
        feedback_fn("* running the instance OS import scripts...")
3271
        src_node = self.op.src_node
3272
        src_image = self.src_image
3273
        if not rpc.call_instance_os_import(pnode_name, iobj, "sda", "sdb",
3274
                                                src_node, src_image):
3275
          raise errors.OpExecError("Could not import os for instance"
3276
                                   " %s on node %s" %
3277
                                   (instance, pnode_name))
3278
      else:
3279
        # also checked in the prereq part
3280
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
3281
                                     % self.op.mode)
3282

    
3283
    if self.op.start:
3284
      logger.Info("starting instance %s on node %s" % (instance, pnode_name))
3285
      feedback_fn("* starting instance...")
3286
      if not rpc.call_instance_start(pnode_name, iobj, None):
3287
        raise errors.OpExecError("Could not start instance")
3288

    
3289

    
3290
class LUConnectConsole(NoHooksLU):
3291
  """Connect to an instance's console.
3292

3293
  This is somewhat special in that it returns the command line that
3294
  you need to run on the master node in order to connect to the
3295
  console.
3296

3297
  """
3298
  _OP_REQP = ["instance_name"]
3299

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

3303
    This checks that the instance is in the cluster.
3304

3305
    """
3306
    instance = self.cfg.GetInstanceInfo(
3307
      self.cfg.ExpandInstanceName(self.op.instance_name))
3308
    if instance is None:
3309
      raise errors.OpPrereqError("Instance '%s' not known" %
3310
                                 self.op.instance_name)
3311
    self.instance = instance
3312

    
3313
  def Exec(self, feedback_fn):
3314
    """Connect to the console of an instance
3315

3316
    """
3317
    instance = self.instance
3318
    node = instance.primary_node
3319

    
3320
    node_insts = rpc.call_instance_list([node])[node]
3321
    if node_insts is False:
3322
      raise errors.OpExecError("Can't connect to node %s." % node)
3323

    
3324
    if instance.name not in node_insts:
3325
      raise errors.OpExecError("Instance %s is not running." % instance.name)
3326

    
3327
    logger.Debug("connecting to console of %s on %s" % (instance.name, node))
3328

    
3329
    hyper = hypervisor.GetHypervisor()
3330
    console_cmd = hyper.GetShellCommandForConsole(instance)
3331

    
3332
    # build ssh cmdline
3333
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
3334

    
3335

    
3336
class LUReplaceDisks(LogicalUnit):
3337
  """Replace the disks of an instance.
3338

3339
  """
3340
  HPATH = "mirrors-replace"
3341
  HTYPE = constants.HTYPE_INSTANCE
3342
  _OP_REQP = ["instance_name", "mode", "disks"]
3343

    
3344
  def BuildHooksEnv(self):
3345
    """Build hooks env.
3346

3347
    This runs on the master, the primary and all the secondaries.
3348

3349
    """
3350
    env = {
3351
      "MODE": self.op.mode,
3352
      "NEW_SECONDARY": self.op.remote_node,
3353
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
3354
      }
3355
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3356
    nl = [
3357
      self.sstore.GetMasterNode(),
3358
      self.instance.primary_node,
3359
      ]
3360
    if self.op.remote_node is not None:
3361
      nl.append(self.op.remote_node)
3362
    return env, nl, nl
3363

    
3364
  def CheckPrereq(self):
3365
    """Check prerequisites.
3366

3367
    This checks that the instance is in the cluster.
3368

3369
    """
3370
    instance = self.cfg.GetInstanceInfo(
3371
      self.cfg.ExpandInstanceName(self.op.instance_name))
3372
    if instance is None:
3373
      raise errors.OpPrereqError("Instance '%s' not known" %
3374
                                 self.op.instance_name)
3375
    self.instance = instance
3376
    self.op.instance_name = instance.name
3377

    
3378
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3379
      raise errors.OpPrereqError("Instance's disk layout is not"
3380
                                 " network mirrored.")
3381

    
3382
    if len(instance.secondary_nodes) != 1:
3383
      raise errors.OpPrereqError("The instance has a strange layout,"
3384
                                 " expected one secondary but found %d" %
3385
                                 len(instance.secondary_nodes))
3386

    
3387
    self.sec_node = instance.secondary_nodes[0]
3388

    
3389
    remote_node = getattr(self.op, "remote_node", None)
3390
    if remote_node is not None:
3391
      remote_node = self.cfg.ExpandNodeName(remote_node)
3392
      if remote_node is None:
3393
        raise errors.OpPrereqError("Node '%s' not known" %
3394
                                   self.op.remote_node)
3395
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
3396
    else:
3397
      self.remote_node_info = None
3398
    if remote_node == instance.primary_node:
3399
      raise errors.OpPrereqError("The specified node is the primary node of"
3400
                                 " the instance.")
3401
    elif remote_node == self.sec_node:
3402
      if self.op.mode == constants.REPLACE_DISK_SEC:
3403
        # this is for DRBD8, where we can't execute the same mode of
3404
        # replacement as for drbd7 (no different port allocated)
3405
        raise errors.OpPrereqError("Same secondary given, cannot execute"
3406
                                   " replacement")
3407
      # the user gave the current secondary, switch to
3408
      # 'no-replace-secondary' mode for drbd7
3409
      remote_node = None
3410
    if (instance.disk_template == constants.DT_REMOTE_RAID1 and
3411
        self.op.mode != constants.REPLACE_DISK_ALL):
3412
      raise errors.OpPrereqError("Template 'remote_raid1' only allows all"
3413
                                 " disks replacement, not individual ones")
3414
    if instance.disk_template == constants.DT_DRBD8:
3415
      if (self.op.mode == constants.REPLACE_DISK_ALL and
3416
          remote_node is not None):
3417
        # switch to replace secondary mode
3418
        self.op.mode = constants.REPLACE_DISK_SEC
3419

    
3420
      if self.op.mode == constants.REPLACE_DISK_ALL:
3421
        raise errors.OpPrereqError("Template 'drbd' only allows primary or"
3422
                                   " secondary disk replacement, not"
3423
                                   " both at once")
3424
      elif self.op.mode == constants.REPLACE_DISK_PRI:
3425
        if remote_node is not None:
3426
          raise errors.OpPrereqError("Template 'drbd' does not allow changing"
3427
                                     " the secondary while doing a primary"
3428
                                     " node disk replacement")
3429
        self.tgt_node = instance.primary_node
3430
        self.oth_node = instance.secondary_nodes[0]
3431
      elif self.op.mode == constants.REPLACE_DISK_SEC:
3432
        self.new_node = remote_node # this can be None, in which case
3433
                                    # we don't change the secondary
3434
        self.tgt_node = instance.secondary_nodes[0]
3435
        self.oth_node = instance.primary_node
3436
      else:
3437
        raise errors.ProgrammerError("Unhandled disk replace mode")
3438

    
3439
    for name in self.op.disks:
3440
      if instance.FindDisk(name) is None:
3441
        raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
3442
                                   (name, instance.name))
3443
    self.op.remote_node = remote_node
3444

    
3445
  def _ExecRR1(self, feedback_fn):
3446
    """Replace the disks of an instance.
3447

3448
    """
3449
    instance = self.instance
3450
    iv_names = {}
3451
    # start of work
3452
    if self.op.remote_node is None:
3453
      remote_node = self.sec_node
3454
    else:
3455
      remote_node = self.op.remote_node
3456
    cfg = self.cfg
3457
    for dev in instance.disks:
3458
      size = dev.size
3459
      lv_names = [".%s_%s" % (dev.iv_name, suf) for suf in ["data", "meta"]]
3460
      names = _GenerateUniqueNames(cfg, lv_names)
3461
      new_drbd = _GenerateMDDRBDBranch(cfg, instance.primary_node,
3462
                                       remote_node, size, names)
3463
      iv_names[dev.iv_name] = (dev, dev.children[0], new_drbd)
3464
      logger.Info("adding new mirror component on secondary for %s" %
3465
                  dev.iv_name)
3466
      #HARDCODE
3467
      if not _CreateBlockDevOnSecondary(cfg, remote_node, instance,
3468
                                        new_drbd, False,
3469
                                        _GetInstanceInfoText(instance)):
3470
        raise errors.OpExecError("Failed to create new component on secondary"
3471
                                 " node %s. Full abort, cleanup manually!" %
3472
                                 remote_node)
3473

    
3474
      logger.Info("adding new mirror component on primary")
3475
      #HARDCODE
3476
      if not _CreateBlockDevOnPrimary(cfg, instance.primary_node,
3477
                                      instance, new_drbd,
3478
                                      _GetInstanceInfoText(instance)):
3479
        # remove secondary dev
3480
        cfg.SetDiskID(new_drbd, remote_node)
3481
        rpc.call_blockdev_remove(remote_node, new_drbd)
3482
        raise errors.OpExecError("Failed to create volume on primary!"
3483
                                 " Full abort, cleanup manually!!")
3484

    
3485
      # the device exists now
3486
      # call the primary node to add the mirror to md
3487
      logger.Info("adding new mirror component to md")
3488
      if not rpc.call_blockdev_addchildren(instance.primary_node, dev,
3489
                                           [new_drbd]):
3490
        logger.Error("Can't add mirror compoment to md!")
3491
        cfg.SetDiskID(new_drbd, remote_node)
3492
        if not rpc.call_blockdev_remove(remote_node, new_drbd):
3493
          logger.Error("Can't rollback on secondary")
3494
        cfg.SetDiskID(new_drbd, instance.primary_node)
3495
        if not rpc.call_blockdev_remove(instance.primary_node, new_drbd):
3496
          logger.Error("Can't rollback on primary")
3497
        raise errors.OpExecError("Full abort, cleanup manually!!")
3498

    
3499
      dev.children.append(new_drbd)
3500
      cfg.AddInstance(instance)
3501

    
3502
    # this can fail as the old devices are degraded and _WaitForSync
3503
    # does a combined result over all disks, so we don't check its
3504
    # return value
3505
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3506

    
3507
    # so check manually all the devices
3508
    for name in iv_names:
3509
      dev, child, new_drbd = iv_names[name]
3510
      cfg.SetDiskID(dev, instance.primary_node)
3511
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
3512
      if is_degr:
3513
        raise errors.OpExecError("MD device %s is degraded!" % name)
3514
      cfg.SetDiskID(new_drbd, instance.primary_node)
3515
      is_degr = rpc.call_blockdev_find(instance.primary_node, new_drbd)[5]
3516
      if is_degr:
3517
        raise errors.OpExecError("New drbd device %s is degraded!" % name)
3518

    
3519
    for name in iv_names:
3520
      dev, child, new_drbd = iv_names[name]
3521
      logger.Info("remove mirror %s component" % name)
3522
      cfg.SetDiskID(dev, instance.primary_node)
3523
      if not rpc.call_blockdev_removechildren(instance.primary_node,
3524
                                              dev, [child]):
3525
        logger.Error("Can't remove child from mirror, aborting"
3526
                     " *this device cleanup*.\nYou need to cleanup manually!!")
3527
        continue
3528

    
3529
      for node in child.logical_id[:2]:
3530
        logger.Info("remove child device on %s" % node)
3531
        cfg.SetDiskID(child, node)
3532
        if not rpc.call_blockdev_remove(node, child):
3533
          logger.Error("Warning: failed to remove device from node %s,"
3534
                       " continuing operation." % node)
3535

    
3536
      dev.children.remove(child)
3537

    
3538
      cfg.AddInstance(instance)
3539

    
3540
  def _ExecD8DiskOnly(self, feedback_fn):
3541
    """Replace a disk on the primary or secondary for dbrd8.
3542

3543
    The algorithm for replace is quite complicated:
3544
      - for each disk to be replaced:
3545
        - create new LVs on the target node with unique names
3546
        - detach old LVs from the drbd device
3547
        - rename old LVs to name_replaced.<time_t>
3548
        - rename new LVs to old LVs
3549
        - attach the new LVs (with the old names now) to the drbd device
3550
      - wait for sync across all devices
3551
      - for each modified disk:
3552
        - remove old LVs (which have the name name_replaces.<time_t>)
3553

3554
    Failures are not very well handled.
3555

3556
    """
3557
    steps_total = 6
3558
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3559
    instance = self.instance
3560
    iv_names = {}
3561
    vgname = self.cfg.GetVGName()
3562
    # start of work
3563
    cfg = self.cfg
3564
    tgt_node = self.tgt_node
3565
    oth_node = self.oth_node
3566

    
3567
    # Step: check device activation
3568
    self.proc.LogStep(1, steps_total, "check device existence")
3569
    info("checking volume groups")
3570
    my_vg = cfg.GetVGName()
3571
    results = rpc.call_vg_list([oth_node, tgt_node])
3572
    if not results:
3573
      raise errors.OpExecError("Can't list volume groups on the nodes")
3574
    for node in oth_node, tgt_node:
3575
      res = results.get(node, False)
3576
      if not res or my_vg not in res:
3577
        raise errors.OpExecError("Volume group '%s' not found on %s" %
3578
                                 (my_vg, node))
3579
    for dev in instance.disks:
3580
      if not dev.iv_name in self.op.disks:
3581
        continue
3582
      for node in tgt_node, oth_node:
3583
        info("checking %s on %s" % (dev.iv_name, node))
3584
        cfg.SetDiskID(dev, node)
3585
        if not rpc.call_blockdev_find(node, dev):
3586
          raise errors.OpExecError("Can't find device %s on node %s" %
3587
                                   (dev.iv_name, node))
3588

    
3589
    # Step: check other node consistency
3590
    self.proc.LogStep(2, steps_total, "check peer consistency")
3591
    for dev in instance.disks:
3592
      if not dev.iv_name in self.op.disks:
3593
        continue
3594
      info("checking %s consistency on %s" % (dev.iv_name, oth_node))
3595
      if not _CheckDiskConsistency(self.cfg, dev, oth_node,
3596
                                   oth_node==instance.primary_node):
3597
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
3598
                                 " to replace disks on this node (%s)" %
3599
                                 (oth_node, tgt_node))
3600

    
3601
    # Step: create new storage
3602
    self.proc.LogStep(3, steps_total, "allocate new storage")
3603
    for dev in instance.disks:
3604
      if not dev.iv_name in self.op.disks:
3605
        continue
3606
      size = dev.size
3607
      cfg.SetDiskID(dev, tgt_node)
3608
      lv_names = [".%s_%s" % (dev.iv_name, suf) for suf in ["data", "meta"]]
3609
      names = _GenerateUniqueNames(cfg, lv_names)
3610
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3611
                             logical_id=(vgname, names[0]))
3612
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3613
                             logical_id=(vgname, names[1]))
3614
      new_lvs = [lv_data, lv_meta]
3615
      old_lvs = dev.children
3616
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
3617
      info("creating new local storage on %s for %s" %
3618
           (tgt_node, dev.iv_name))
3619
      # since we *always* want to create this LV, we use the
3620
      # _Create...OnPrimary (which forces the creation), even if we
3621
      # are talking about the secondary node
3622
      for new_lv in new_lvs:
3623
        if not _CreateBlockDevOnPrimary(cfg, tgt_node, instance, new_lv,
3624
                                        _GetInstanceInfoText(instance)):
3625
          raise errors.OpExecError("Failed to create new LV named '%s' on"
3626
                                   " node '%s'" %
3627
                                   (new_lv.logical_id[1], tgt_node))
3628

    
3629
    # Step: for each lv, detach+rename*2+attach
3630
    self.proc.LogStep(4, steps_total, "change drbd configuration")
3631
    for dev, old_lvs, new_lvs in iv_names.itervalues():
3632
      info("detaching %s drbd from local storage" % dev.iv_name)
3633
      if not rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs):
3634
        raise errors.OpExecError("Can't detach drbd from local storage on node"
3635
                                 " %s for device %s" % (tgt_node, dev.iv_name))
3636
      #dev.children = []
3637
      #cfg.Update(instance)
3638

    
3639
      # ok, we created the new LVs, so now we know we have the needed
3640
      # storage; as such, we proceed on the target node to rename
3641
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
3642
      # using the assumption that logical_id == physical_id (which in
3643
      # turn is the unique_id on that node)
3644

    
3645
      # FIXME(iustin): use a better name for the replaced LVs
3646
      temp_suffix = int(time.time())
3647
      ren_fn = lambda d, suff: (d.physical_id[0],
3648
                                d.physical_id[1] + "_replaced-%s" % suff)
3649
      # build the rename list based on what LVs exist on the node
3650
      rlist = []
3651
      for to_ren in old_lvs:
3652
        find_res = rpc.call_blockdev_find(tgt_node, to_ren)
3653
        if find_res is not None: # device exists
3654
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
3655

    
3656
      info("renaming the old LVs on the target node")
3657
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3658
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
3659
      # now we rename the new LVs to the old LVs
3660
      info("renaming the new LVs on the target node")
3661
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
3662
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3663
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
3664

    
3665
      for old, new in zip(old_lvs, new_lvs):
3666
        new.logical_id = old.logical_id
3667
        cfg.SetDiskID(new, tgt_node)
3668

    
3669
      for disk in old_lvs:
3670
        disk.logical_id = ren_fn(disk, temp_suffix)
3671
        cfg.SetDiskID(disk, tgt_node)
3672

    
3673
      # now that the new lvs have the old name, we can add them to the device
3674
      info("adding new mirror component on %s" % tgt_node)
3675
      if not rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs):
3676
        for new_lv in new_lvs:
3677
          if not rpc.call_blockdev_remove(tgt_node, new_lv):
3678
            warning("Can't rollback device %s", hint="manually cleanup unused"
3679
                    " logical volumes")
3680
        raise errors.OpExecError("Can't add local storage to drbd")
3681

    
3682
      dev.children = new_lvs
3683
      cfg.Update(instance)
3684

    
3685
    # Step: wait for sync
3686

    
3687
    # this can fail as the old devices are degraded and _WaitForSync
3688
    # does a combined result over all disks, so we don't check its
3689
    # return value
3690
    self.proc.LogStep(5, steps_total, "sync devices")
3691
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3692

    
3693
    # so check manually all the devices
3694
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3695
      cfg.SetDiskID(dev, instance.primary_node)
3696
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
3697
      if is_degr:
3698
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
3699

    
3700
    # Step: remove old storage
3701
    self.proc.LogStep(6, steps_total, "removing old storage")
3702
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3703
      info("remove logical volumes for %s" % name)
3704
      for lv in old_lvs:
3705
        cfg.SetDiskID(lv, tgt_node)
3706
        if not rpc.call_blockdev_remove(tgt_node, lv):
3707
          warning("Can't remove old LV", hint="manually remove unused LVs")
3708
          continue
3709

    
3710
  def _ExecD8Secondary(self, feedback_fn):
3711
    """Replace the secondary node for drbd8.
3712

3713
    The algorithm for replace is quite complicated:
3714
      - for all disks of the instance:
3715
        - create new LVs on the new node with same names
3716
        - shutdown the drbd device on the old secondary
3717
        - disconnect the drbd network on the primary
3718
        - create the drbd device on the new secondary
3719
        - network attach the drbd on the primary, using an artifice:
3720
          the drbd code for Attach() will connect to the network if it
3721
          finds a device which is connected to the good local disks but
3722
          not network enabled
3723
      - wait for sync across all devices
3724
      - remove all disks from the old secondary
3725

3726
    Failures are not very well handled.
3727

3728
    """
3729
    steps_total = 6
3730
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3731
    instance = self.instance
3732
    iv_names = {}
3733
    vgname = self.cfg.GetVGName()
3734
    # start of work
3735
    cfg = self.cfg
3736
    old_node = self.tgt_node
3737
    new_node = self.new_node
3738
    pri_node = instance.primary_node
3739

    
3740
    # Step: check device activation
3741
    self.proc.LogStep(1, steps_total, "check device existence")
3742
    info("checking volume groups")
3743
    my_vg = cfg.GetVGName()
3744
    results = rpc.call_vg_list([pri_node, new_node])
3745
    if not results:
3746
      raise errors.OpExecError("Can't list volume groups on the nodes")
3747
    for node in pri_node, new_node:
3748
      res = results.get(node, False)
3749
      if not res or my_vg not in res:
3750
        raise errors.OpExecError("Volume group '%s' not found on %s" %
3751
                                 (my_vg, node))
3752
    for dev in instance.disks:
3753
      if not dev.iv_name in self.op.disks:
3754
        continue
3755
      info("checking %s on %s" % (dev.iv_name, pri_node))
3756
      cfg.SetDiskID(dev, pri_node)
3757
      if not rpc.call_blockdev_find(pri_node, dev):
3758
        raise errors.OpExecError("Can't find device %s on node %s" %
3759
                                 (dev.iv_name, pri_node))
3760

    
3761
    # Step: check other node consistency
3762
    self.proc.LogStep(2, steps_total, "check peer consistency")
3763
    for dev in instance.disks:
3764
      if not dev.iv_name in self.op.disks:
3765
        continue
3766
      info("checking %s consistency on %s" % (dev.iv_name, pri_node))
3767
      if not _CheckDiskConsistency(self.cfg, dev, pri_node, True, ldisk=True):
3768
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
3769
                                 " unsafe to replace the secondary" %
3770
                                 pri_node)
3771

    
3772
    # Step: create new storage
3773
    self.proc.LogStep(3, steps_total, "allocate new storage")
3774
    for dev in instance.disks:
3775
      size = dev.size
3776
      info("adding new local storage on %s for %s" % (new_node, dev.iv_name))
3777
      # since we *always* want to create this LV, we use the
3778
      # _Create...OnPrimary (which forces the creation), even if we
3779
      # are talking about the secondary node
3780
      for new_lv in dev.children:
3781
        if not _CreateBlockDevOnPrimary(cfg, new_node, instance, new_lv,
3782
                                        _GetInstanceInfoText(instance)):
3783
          raise errors.OpExecError("Failed to create new LV named '%s' on"
3784
                                   " node '%s'" %
3785
                                   (new_lv.logical_id[1], new_node))
3786

    
3787
      iv_names[dev.iv_name] = (dev, dev.children)
3788

    
3789
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
3790
    for dev in instance.disks:
3791
      size = dev.size
3792
      info("activating a new drbd on %s for %s" % (new_node, dev.iv_name))
3793
      # create new devices on new_node
3794
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
3795
                              logical_id=(pri_node, new_node,
3796
                                          dev.logical_id[2]),
3797
                              children=dev.children)
3798
      if not _CreateBlockDevOnSecondary(cfg, new_node, instance,
3799
                                        new_drbd, False,
3800
                                      _GetInstanceInfoText(instance)):
3801
        raise errors.OpExecError("Failed to create new DRBD on"
3802
                                 " node '%s'" % new_node)
3803

    
3804
    for dev in instance.disks:
3805
      # we have new devices, shutdown the drbd on the old secondary
3806
      info("shutting down drbd for %s on old node" % dev.iv_name)
3807
      cfg.SetDiskID(dev, old_node)
3808
      if not rpc.call_blockdev_shutdown(old_node, dev):
3809
        warning("Failed to shutdown drbd for %s on old node" % dev.iv_name,
3810
                hint="Please cleanup this device manually as soon as possible")
3811

    
3812
    info("detaching primary drbds from the network (=> standalone)")
3813
    done = 0
3814
    for dev in instance.disks:
3815
      cfg.SetDiskID(dev, pri_node)
3816
      # set the physical (unique in bdev terms) id to None, meaning
3817
      # detach from network
3818
      dev.physical_id = (None,) * len(dev.physical_id)
3819
      # and 'find' the device, which will 'fix' it to match the
3820
      # standalone state
3821
      if rpc.call_blockdev_find(pri_node, dev):
3822
        done += 1
3823
      else:
3824
        warning("Failed to detach drbd %s from network, unusual case" %
3825
                dev.iv_name)
3826

    
3827
    if not done:
3828
      # no detaches succeeded (very unlikely)
3829
      raise errors.OpExecError("Can't detach at least one DRBD from old node")
3830

    
3831
    # if we managed to detach at least one, we update all the disks of
3832
    # the instance to point to the new secondary
3833
    info("updating instance configuration")
3834
    for dev in instance.disks:
3835
      dev.logical_id = (pri_node, new_node) + dev.logical_id[2:]
3836
      cfg.SetDiskID(dev, pri_node)
3837
    cfg.Update(instance)
3838

    
3839
    # and now perform the drbd attach
3840
    info("attaching primary drbds to new secondary (standalone => connected)")
3841
    failures = []
3842
    for dev in instance.disks:
3843
      info("attaching primary drbd for %s to new secondary node" % dev.iv_name)
3844
      # since the attach is smart, it's enough to 'find' the device,
3845
      # it will automatically activate the network, if the physical_id
3846
      # is correct
3847
      cfg.SetDiskID(dev, pri_node)
3848
      if not rpc.call_blockdev_find(pri_node, dev):
3849
        warning("can't attach drbd %s to new secondary!" % dev.iv_name,
3850
                "please do a gnt-instance info to see the status of disks")
3851

    
3852
    # this can fail as the old devices are degraded and _WaitForSync
3853
    # does a combined result over all disks, so we don't check its
3854
    # return value
3855
    self.proc.LogStep(5, steps_total, "sync devices")
3856
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3857

    
3858
    # so check manually all the devices
3859
    for name, (dev, old_lvs) in iv_names.iteritems():
3860
      cfg.SetDiskID(dev, pri_node)
3861
      is_degr = rpc.call_blockdev_find(pri_node, dev)[5]
3862
      if is_degr:
3863
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
3864

    
3865
    self.proc.LogStep(6, steps_total, "removing old storage")
3866
    for name, (dev, old_lvs) in iv_names.iteritems():
3867
      info("remove logical volumes for %s" % name)
3868
      for lv in old_lvs:
3869
        cfg.SetDiskID(lv, old_node)
3870
        if not rpc.call_blockdev_remove(old_node, lv):
3871
          warning("Can't remove LV on old secondary",
3872
                  hint="Cleanup stale volumes by hand")
3873

    
3874
  def Exec(self, feedback_fn):
3875
    """Execute disk replacement.
3876

3877
    This dispatches the disk replacement to the appropriate handler.
3878

3879
    """
3880
    instance = self.instance
3881
    if instance.disk_template == constants.DT_REMOTE_RAID1:
3882
      fn = self._ExecRR1
3883
    elif instance.disk_template == constants.DT_DRBD8:
3884
      if self.op.remote_node is None:
3885
        fn = self._ExecD8DiskOnly
3886
      else:
3887
        fn = self._ExecD8Secondary
3888
    else:
3889
      raise errors.ProgrammerError("Unhandled disk replacement case")
3890
    return fn(feedback_fn)
3891

    
3892

    
3893
class LUQueryInstanceData(NoHooksLU):
3894
  """Query runtime instance data.
3895

3896
  """
3897
  _OP_REQP = ["instances"]
3898

    
3899
  def CheckPrereq(self):
3900
    """Check prerequisites.
3901

3902
    This only checks the optional instance list against the existing names.
3903

3904
    """
3905
    if not isinstance(self.op.instances, list):
3906
      raise errors.OpPrereqError("Invalid argument type 'instances'")
3907
    if self.op.instances:
3908
      self.wanted_instances = []
3909
      names = self.op.instances
3910
      for name in names:
3911
        instance = self.cfg.GetInstanceInfo(self.cfg.ExpandInstanceName(name))
3912
        if instance is None:
3913
          raise errors.OpPrereqError("No such instance name '%s'" % name)
3914
        self.wanted_instances.append(instance)
3915
    else:
3916
      self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
3917
                               in self.cfg.GetInstanceList()]
3918
    return
3919

    
3920

    
3921
  def _ComputeDiskStatus(self, instance, snode, dev):
3922
    """Compute block device status.
3923

3924
    """
3925
    self.cfg.SetDiskID(dev, instance.primary_node)
3926
    dev_pstatus = rpc.call_blockdev_find(instance.primary_node, dev)
3927
    if dev.dev_type in constants.LDS_DRBD:
3928
      # we change the snode then (otherwise we use the one passed in)
3929
      if dev.logical_id[0] == instance.primary_node:
3930
        snode = dev.logical_id[1]
3931
      else:
3932
        snode = dev.logical_id[0]
3933

    
3934
    if snode:
3935
      self.cfg.SetDiskID(dev, snode)
3936
      dev_sstatus = rpc.call_blockdev_find(snode, dev)
3937
    else:
3938
      dev_sstatus = None
3939

    
3940
    if dev.children:
3941
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
3942
                      for child in dev.children]
3943
    else:
3944
      dev_children = []
3945

    
3946
    data = {
3947
      "iv_name": dev.iv_name,
3948
      "dev_type": dev.dev_type,
3949
      "logical_id": dev.logical_id,
3950
      "physical_id": dev.physical_id,
3951
      "pstatus": dev_pstatus,
3952
      "sstatus": dev_sstatus,
3953
      "children": dev_children,
3954
      }
3955

    
3956
    return data
3957

    
3958
  def Exec(self, feedback_fn):
3959
    """Gather and return data"""
3960
    result = {}
3961
    for instance in self.wanted_instances:
3962
      remote_info = rpc.call_instance_info(instance.primary_node,
3963
                                                instance.name)
3964
      if remote_info and "state" in remote_info:
3965
        remote_state = "up"
3966
      else:
3967
        remote_state = "down"
3968
      if instance.status == "down":
3969
        config_state = "down"
3970
      else:
3971
        config_state = "up"
3972

    
3973
      disks = [self._ComputeDiskStatus(instance, None, device)
3974
               for device in instance.disks]
3975

    
3976
      idict = {
3977
        "name": instance.name,
3978
        "config_state": config_state,
3979
        "run_state": remote_state,
3980
        "pnode": instance.primary_node,
3981
        "snodes": instance.secondary_nodes,
3982
        "os": instance.os,
3983
        "memory": instance.memory,
3984
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
3985
        "disks": disks,
3986
        "network_port": instance.network_port,
3987
        "vcpus": instance.vcpus,
3988
        "kernel_path": instance.kernel_path,
3989
        "initrd_path": instance.initrd_path,
3990
        "hvm_boot_order": instance.hvm_boot_order,
3991
        }
3992

    
3993
      result[instance.name] = idict
3994

    
3995
    return result
3996

    
3997

    
3998
class LUSetInstanceParams(LogicalUnit):
3999
  """Modifies an instances's parameters.
4000

4001
  """
4002
  HPATH = "instance-modify"
4003
  HTYPE = constants.HTYPE_INSTANCE
4004
  _OP_REQP = ["instance_name"]
4005

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

4009
    This runs on the master, primary and secondaries.
4010

4011
    """
4012
    args = dict()
4013
    if self.mem:
4014
      args['memory'] = self.mem
4015
    if self.vcpus:
4016
      args['vcpus'] = self.vcpus
4017
    if self.do_ip or self.do_bridge or self.mac:
4018
      if self.do_ip:
4019
        ip = self.ip
4020
      else:
4021
        ip = self.instance.nics[0].ip
4022
      if self.bridge:
4023
        bridge = self.bridge
4024
      else:
4025
        bridge = self.instance.nics[0].bridge
4026
      if self.mac:
4027
        mac = self.mac
4028
      else:
4029
        mac = self.instance.nics[0].mac
4030
      args['nics'] = [(ip, bridge, mac)]
4031
    env = _BuildInstanceHookEnvByObject(self.instance, override=args)
4032
    nl = [self.sstore.GetMasterNode(),
4033
          self.instance.primary_node] + list(self.instance.secondary_nodes)
4034
    return env, nl, nl
4035

    
4036
  def CheckPrereq(self):
4037
    """Check prerequisites.
4038

4039
    This only checks the instance list against the existing names.
4040

4041
    """
4042
    self.mem = getattr(self.op, "mem", None)
4043
    self.vcpus = getattr(self.op, "vcpus", None)
4044
    self.ip = getattr(self.op, "ip", None)
4045
    self.mac = getattr(self.op, "mac", None)
4046
    self.bridge = getattr(self.op, "bridge", None)
4047
    self.kernel_path = getattr(self.op, "kernel_path", None)
4048
    self.initrd_path = getattr(self.op, "initrd_path", None)
4049
    self.hvm_boot_order = getattr(self.op, "hvm_boot_order", None)
4050
    all_params = [self.mem, self.vcpus, self.ip, self.bridge, self.mac,
4051
                  self.kernel_path, self.initrd_path, self.hvm_boot_order]
4052
    if all_params.count(None) == len(all_params):
4053
      raise errors.OpPrereqError("No changes submitted")
4054
    if self.mem is not None:
4055
      try:
4056
        self.mem = int(self.mem)
4057
      except ValueError, err:
4058
        raise errors.OpPrereqError("Invalid memory size: %s" % str(err))
4059
    if self.vcpus is not None:
4060
      try:
4061
        self.vcpus = int(self.vcpus)
4062
      except ValueError, err:
4063
        raise errors.OpPrereqError("Invalid vcpus number: %s" % str(err))
4064
    if self.ip is not None:
4065
      self.do_ip = True
4066
      if self.ip.lower() == "none":
4067
        self.ip = None
4068
      else:
4069
        if not utils.IsValidIP(self.ip):
4070
          raise errors.OpPrereqError("Invalid IP address '%s'." % self.ip)
4071
    else:
4072
      self.do_ip = False
4073
    self.do_bridge = (self.bridge is not None)
4074
    if self.mac is not None:
4075
      if self.cfg.IsMacInUse(self.mac):
4076
        raise errors.OpPrereqError('MAC address %s already in use in cluster' %
4077
                                   self.mac)
4078
      if not utils.IsValidMac(self.mac):
4079
        raise errors.OpPrereqError('Invalid MAC address %s' % self.mac)
4080

    
4081
    if self.kernel_path is not None:
4082
      self.do_kernel_path = True
4083
      if self.kernel_path == constants.VALUE_NONE:
4084
        raise errors.OpPrereqError("Can't set instance to no kernel")
4085

    
4086
      if self.kernel_path != constants.VALUE_DEFAULT:
4087
        if not os.path.isabs(self.kernel_path):
4088
          raise errors.OpPrereqError("The kernel path must be an absolute"
4089
                                    " filename")
4090
    else:
4091
      self.do_kernel_path = False
4092

    
4093
    if self.initrd_path is not None:
4094
      self.do_initrd_path = True
4095
      if self.initrd_path not in (constants.VALUE_NONE,
4096
                                  constants.VALUE_DEFAULT):
4097
        if not os.path.isabs(self.initrd_path):
4098
          raise errors.OpPrereqError("The initrd path must be an absolute"
4099
                                    " filename")
4100
    else:
4101
      self.do_initrd_path = False
4102

    
4103
    # boot order verification
4104
    if self.hvm_boot_order is not None:
4105
      if self.hvm_boot_order != constants.VALUE_DEFAULT:
4106
        if len(self.hvm_boot_order.strip("acdn")) != 0:
4107
          raise errors.OpPrereqError("invalid boot order specified,"
4108
                                     " must be one or more of [acdn]"
4109
                                     " or 'default'")
4110

    
4111
    instance = self.cfg.GetInstanceInfo(
4112
      self.cfg.ExpandInstanceName(self.op.instance_name))
4113
    if instance is None:
4114
      raise errors.OpPrereqError("No such instance name '%s'" %
4115
                                 self.op.instance_name)
4116
    self.op.instance_name = instance.name
4117
    self.instance = instance
4118
    return
4119

    
4120
  def Exec(self, feedback_fn):
4121
    """Modifies an instance.
4122

4123
    All parameters take effect only at the next restart of the instance.
4124
    """
4125
    result = []
4126
    instance = self.instance
4127
    if self.mem:
4128
      instance.memory = self.mem
4129
      result.append(("mem", self.mem))
4130
    if self.vcpus:
4131
      instance.vcpus = self.vcpus
4132
      result.append(("vcpus",  self.vcpus))
4133
    if self.do_ip:
4134
      instance.nics[0].ip = self.ip
4135
      result.append(("ip", self.ip))
4136
    if self.bridge:
4137
      instance.nics[0].bridge = self.bridge
4138
      result.append(("bridge", self.bridge))
4139
    if self.mac:
4140
      instance.nics[0].mac = self.mac
4141
      result.append(("mac", self.mac))
4142
    if self.do_kernel_path:
4143
      instance.kernel_path = self.kernel_path
4144
      result.append(("kernel_path", self.kernel_path))
4145
    if self.do_initrd_path:
4146
      instance.initrd_path = self.initrd_path
4147
      result.append(("initrd_path", self.initrd_path))
4148
    if self.hvm_boot_order:
4149
      if self.hvm_boot_order == constants.VALUE_DEFAULT:
4150
        instance.hvm_boot_order = None
4151
      else:
4152
        instance.hvm_boot_order = self.hvm_boot_order
4153
      result.append(("hvm_boot_order", self.hvm_boot_order))
4154

    
4155
    self.cfg.AddInstance(instance)
4156

    
4157
    return result
4158

    
4159

    
4160
class LUQueryExports(NoHooksLU):
4161
  """Query the exports list
4162

4163
  """
4164
  _OP_REQP = []
4165

    
4166
  def CheckPrereq(self):
4167
    """Check that the nodelist contains only existing nodes.
4168

4169
    """
4170
    self.nodes = _GetWantedNodes(self, getattr(self.op, "nodes", None))
4171

    
4172
  def Exec(self, feedback_fn):
4173
    """Compute the list of all the exported system images.
4174

4175
    Returns:
4176
      a dictionary with the structure node->(export-list)
4177
      where export-list is a list of the instances exported on
4178
      that node.
4179

4180
    """
4181
    return rpc.call_export_list(self.nodes)
4182

    
4183

    
4184
class LUExportInstance(LogicalUnit):
4185
  """Export an instance to an image in the cluster.
4186

4187
  """
4188
  HPATH = "instance-export"
4189
  HTYPE = constants.HTYPE_INSTANCE
4190
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
4191

    
4192
  def BuildHooksEnv(self):
4193
    """Build hooks env.
4194

4195
    This will run on the master, primary node and target node.
4196

4197
    """
4198
    env = {
4199
      "EXPORT_NODE": self.op.target_node,
4200
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
4201
      }
4202
    env.update(_BuildInstanceHookEnvByObject(self.instance))
4203
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
4204
          self.op.target_node]
4205
    return env, nl, nl
4206

    
4207
  def CheckPrereq(self):
4208
    """Check prerequisites.
4209

4210
    This checks that the instance name is a valid one.
4211

4212
    """
4213
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
4214
    self.instance = self.cfg.GetInstanceInfo(instance_name)
4215
    if self.instance is None:
4216
      raise errors.OpPrereqError("Instance '%s' not found" %
4217
                                 self.op.instance_name)
4218

    
4219
    # node verification
4220
    dst_node_short = self.cfg.ExpandNodeName(self.op.target_node)
4221
    self.dst_node = self.cfg.GetNodeInfo(dst_node_short)
4222

    
4223
    if self.dst_node is None:
4224
      raise errors.OpPrereqError("Destination node '%s' is unknown." %
4225
                                 self.op.target_node)
4226
    self.op.target_node = self.dst_node.name
4227

    
4228
  def Exec(self, feedback_fn):
4229
    """Export an instance to an image in the cluster.
4230

4231
    """
4232
    instance = self.instance
4233
    dst_node = self.dst_node
4234
    src_node = instance.primary_node
4235
    if self.op.shutdown:
4236
      # shutdown the instance, but not the disks
4237
      if not rpc.call_instance_shutdown(src_node, instance):
4238
         raise errors.OpExecError("Could not shutdown instance %s on node %s" %
4239
                                 (instance.name, source_node))
4240

    
4241
    vgname = self.cfg.GetVGName()
4242

    
4243
    snap_disks = []
4244

    
4245
    try:
4246
      for disk in instance.disks:
4247
        if disk.iv_name == "sda":
4248
          # new_dev_name will be a snapshot of an lvm leaf of the one we passed
4249
          new_dev_name = rpc.call_blockdev_snapshot(src_node, disk)
4250

    
4251
          if not new_dev_name:
4252
            logger.Error("could not snapshot block device %s on node %s" %
4253
                         (disk.logical_id[1], src_node))
4254
          else:
4255
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
4256
                                      logical_id=(vgname, new_dev_name),
4257
                                      physical_id=(vgname, new_dev_name),
4258
                                      iv_name=disk.iv_name)
4259
            snap_disks.append(new_dev)
4260

    
4261
    finally:
4262
      if self.op.shutdown and instance.status == "up":
4263
        if not rpc.call_instance_start(src_node, instance, None):
4264
          _ShutdownInstanceDisks(instance, self.cfg)
4265
          raise errors.OpExecError("Could not start instance")
4266

    
4267
    # TODO: check for size
4268

    
4269
    for dev in snap_disks:
4270
      if not rpc.call_snapshot_export(src_node, dev, dst_node.name, instance):
4271
        logger.Error("could not export block device %s from node %s to node %s"
4272
                     % (dev.logical_id[1], src_node, dst_node.name))
4273
      if not rpc.call_blockdev_remove(src_node, dev):
4274
        logger.Error("could not remove snapshot block device %s from node %s" %
4275
                     (dev.logical_id[1], src_node))
4276

    
4277
    if not rpc.call_finalize_export(dst_node.name, instance, snap_disks):
4278
      logger.Error("could not finalize export for instance %s on node %s" %
4279
                   (instance.name, dst_node.name))
4280

    
4281
    nodelist = self.cfg.GetNodeList()
4282
    nodelist.remove(dst_node.name)
4283

    
4284
    # on one-node clusters nodelist will be empty after the removal
4285
    # if we proceed the backup would be removed because OpQueryExports
4286
    # substitutes an empty list with the full cluster node list.
4287
    if nodelist:
4288
      op = opcodes.OpQueryExports(nodes=nodelist)
4289
      exportlist = self.proc.ChainOpCode(op)
4290
      for node in exportlist:
4291
        if instance.name in exportlist[node]:
4292
          if not rpc.call_export_remove(node, instance.name):
4293
            logger.Error("could not remove older export for instance %s"
4294
                         " on node %s" % (instance.name, node))
4295

    
4296

    
4297
class TagsLU(NoHooksLU):
4298
  """Generic tags LU.
4299

4300
  This is an abstract class which is the parent of all the other tags LUs.
4301

4302
  """
4303
  def CheckPrereq(self):
4304
    """Check prerequisites.
4305

4306
    """
4307
    if self.op.kind == constants.TAG_CLUSTER:
4308
      self.target = self.cfg.GetClusterInfo()
4309
    elif self.op.kind == constants.TAG_NODE:
4310
      name = self.cfg.ExpandNodeName(self.op.name)
4311
      if name is None:
4312
        raise errors.OpPrereqError("Invalid node name (%s)" %
4313
                                   (self.op.name,))
4314
      self.op.name = name
4315
      self.target = self.cfg.GetNodeInfo(name)
4316
    elif self.op.kind == constants.TAG_INSTANCE:
4317
      name = self.cfg.ExpandInstanceName(self.op.name)
4318
      if name is None:
4319
        raise errors.OpPrereqError("Invalid instance name (%s)" %
4320
                                   (self.op.name,))
4321
      self.op.name = name
4322
      self.target = self.cfg.GetInstanceInfo(name)
4323
    else:
4324
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
4325
                                 str(self.op.kind))
4326

    
4327

    
4328
class LUGetTags(TagsLU):
4329
  """Returns the tags of a given object.
4330

4331
  """
4332
  _OP_REQP = ["kind", "name"]
4333

    
4334
  def Exec(self, feedback_fn):
4335
    """Returns the tag list.
4336

4337
    """
4338
    return self.target.GetTags()
4339

    
4340

    
4341
class LUSearchTags(NoHooksLU):
4342
  """Searches the tags for a given pattern.
4343

4344
  """
4345
  _OP_REQP = ["pattern"]
4346

    
4347
  def CheckPrereq(self):
4348
    """Check prerequisites.
4349

4350
    This checks the pattern passed for validity by compiling it.
4351

4352
    """
4353
    try:
4354
      self.re = re.compile(self.op.pattern)
4355
    except re.error, err:
4356
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
4357
                                 (self.op.pattern, err))
4358

    
4359
  def Exec(self, feedback_fn):
4360
    """Returns the tag list.
4361

4362
    """
4363
    cfg = self.cfg
4364
    tgts = [("/cluster", cfg.GetClusterInfo())]
4365
    ilist = [cfg.GetInstanceInfo(name) for name in cfg.GetInstanceList()]
4366
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
4367
    nlist = [cfg.GetNodeInfo(name) for name in cfg.GetNodeList()]
4368
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
4369
    results = []
4370
    for path, target in tgts:
4371
      for tag in target.GetTags():
4372
        if self.re.search(tag):
4373
          results.append((path, tag))
4374
    return results
4375

    
4376

    
4377
class LUAddTags(TagsLU):
4378
  """Sets a tag on a given object.
4379

4380
  """
4381
  _OP_REQP = ["kind", "name", "tags"]
4382

    
4383
  def CheckPrereq(self):
4384
    """Check prerequisites.
4385

4386
    This checks the type and length of the tag name and value.
4387

4388
    """
4389
    TagsLU.CheckPrereq(self)
4390
    for tag in self.op.tags:
4391
      objects.TaggableObject.ValidateTag(tag)
4392

    
4393
  def Exec(self, feedback_fn):
4394
    """Sets the tag.
4395

4396
    """
4397
    try:
4398
      for tag in self.op.tags:
4399
        self.target.AddTag(tag)
4400
    except errors.TagError, err:
4401
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
4402
    try:
4403
      self.cfg.Update(self.target)
4404
    except errors.ConfigurationError:
4405
      raise errors.OpRetryError("There has been a modification to the"
4406
                                " config file and the operation has been"
4407
                                " aborted. Please retry.")
4408

    
4409

    
4410
class LUDelTags(TagsLU):
4411
  """Delete a list of tags from a given object.
4412

4413
  """
4414
  _OP_REQP = ["kind", "name", "tags"]
4415

    
4416
  def CheckPrereq(self):
4417
    """Check prerequisites.
4418

4419
    This checks that we have the given tag.
4420

4421
    """
4422
    TagsLU.CheckPrereq(self)
4423
    for tag in self.op.tags:
4424
      objects.TaggableObject.ValidateTag(tag)
4425
    del_tags = frozenset(self.op.tags)
4426
    cur_tags = self.target.GetTags()
4427
    if not del_tags <= cur_tags:
4428
      diff_tags = del_tags - cur_tags
4429
      diff_names = ["'%s'" % tag for tag in diff_tags]
4430
      diff_names.sort()
4431
      raise errors.OpPrereqError("Tag(s) %s not found" %
4432
                                 (",".join(diff_names)))
4433

    
4434
  def Exec(self, feedback_fn):
4435
    """Remove the tag from the object.
4436

4437
    """
4438
    for tag in self.op.tags:
4439
      self.target.RemoveTag(tag)
4440
    try:
4441
      self.cfg.Update(self.target)
4442
    except errors.ConfigurationError:
4443
      raise errors.OpRetryError("There has been a modification to the"
4444
                                " config file and the operation has been"
4445
                                " aborted. Please retry.")
4446

    
4447
class LUTestDelay(NoHooksLU):
4448
  """Sleep for a specified amount of time.
4449

4450
  This LU sleeps on the master and/or nodes for a specified amoutn of
4451
  time.
4452

4453
  """
4454
  _OP_REQP = ["duration", "on_master", "on_nodes"]
4455

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

4459
    This checks that we have a good list of nodes and/or the duration
4460
    is valid.
4461

4462
    """
4463

    
4464
    if self.op.on_nodes:
4465
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
4466

    
4467
  def Exec(self, feedback_fn):
4468
    """Do the actual sleep.
4469

4470
    """
4471
    if self.op.on_master:
4472
      if not utils.TestDelay(self.op.duration):
4473
        raise errors.OpExecError("Error during master delay test")
4474
    if self.op.on_nodes:
4475
      result = rpc.call_test_delay(self.op.on_nodes, self.op.duration)
4476
      if not result:
4477
        raise errors.OpExecError("Complete failure from rpc call")
4478
      for node, node_result in result.items():
4479
        if not node_result:
4480
          raise errors.OpExecError("Failure during rpc call to node %s,"
4481
                                   " result: %s" % (node, node_result))