Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 0e137c28

History | View | Annotate | Download (121 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 socket
30
import time
31
import tempfile
32
import re
33
import platform
34

    
35
from ganeti import rpc
36
from ganeti import ssh
37
from ganeti import logger
38
from ganeti import utils
39
from ganeti import errors
40
from ganeti import hypervisor
41
from ganeti import config
42
from ganeti import constants
43
from ganeti import objects
44
from ganeti import opcodes
45
from ganeti import ssconf
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.processor = processor
74
    self.op = op
75
    self.cfg = cfg
76
    self.sstore = sstore
77
    for attr_name in self._OP_REQP:
78
      attr_val = getattr(op, attr_name, None)
79
      if attr_val is None:
80
        raise errors.OpPrereqError("Required parameter '%s' missing" %
81
                                   attr_name)
82
    if self.REQ_CLUSTER:
83
      if not cfg.IsCluster():
84
        raise errors.OpPrereqError("Cluster not initialized yet,"
85
                                   " use 'gnt-cluster init' first.")
86
      if self.REQ_MASTER:
87
        master = sstore.GetMasterNode()
88
        if master != utils.HostInfo().name:
89
          raise errors.OpPrereqError("Commands must be run on the master"
90
                                     " node %s" % master)
91

    
92
  def CheckPrereq(self):
93
    """Check prerequisites for this LU.
94

95
    This method should check that the prerequisites for the execution
96
    of this LU are fulfilled. It can do internode communication, but
97
    it should be idempotent - no cluster or system changes are
98
    allowed.
99

100
    The method should raise errors.OpPrereqError in case something is
101
    not fulfilled. Its return value is ignored.
102

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

108
    """
109
    raise NotImplementedError
110

    
111
  def Exec(self, feedback_fn):
112
    """Execute the LU.
113

114
    This method should implement the actual work. It should raise
115
    errors.OpExecError for failures that are somewhat dealt with in
116
    code, or expected.
117

118
    """
119
    raise NotImplementedError
120

    
121
  def BuildHooksEnv(self):
122
    """Build hooks environment for this LU.
123

124
    This method should return a three-node tuple consisting of: a dict
125
    containing the environment that will be used for running the
126
    specific hook for this LU, a list of node names on which the hook
127
    should run before the execution, and a list of node names on which
128
    the hook should run after the execution.
129

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

135
    As for the node lists, the master should not be included in the
136
    them, as it will be added by the hooks runner in case this LU
137
    requires a cluster to run on (otherwise we don't have a node
138
    list). No nodes should be returned as an empty list (and not
139
    None).
140

141
    Note that if the HPATH for a LU class is None, this function will
142
    not be called.
143

144
    """
145
    raise NotImplementedError
146

    
147

    
148
class NoHooksLU(LogicalUnit):
149
  """Simple LU which runs no hooks.
150

151
  This LU is intended as a parent for other LogicalUnits which will
152
  run no hooks, in order to reduce duplicate code.
153

154
  """
155
  HPATH = None
156
  HTYPE = None
157

    
158
  def BuildHooksEnv(self):
159
    """Build hooks env.
160

161
    This is a no-op, since we don't run hooks.
162

163
    """
164
    return {}, [], []
165

    
166

    
167
def _GetWantedNodes(lu, nodes):
168
  """Returns list of checked and expanded node names.
169

170
  Args:
171
    nodes: List of nodes (strings) or None for all
172

173
  """
174
  if not isinstance(nodes, list):
175
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
176

    
177
  if nodes:
178
    wanted = []
179

    
180
    for name in nodes:
181
      node = lu.cfg.ExpandNodeName(name)
182
      if node is None:
183
        raise errors.OpPrereqError("No such node name '%s'" % name)
184
      wanted.append(node)
185

    
186
  else:
187
    wanted = lu.cfg.GetNodeList()
188
  return utils.NiceSort(wanted)
189

    
190

    
191
def _GetWantedInstances(lu, instances):
192
  """Returns list of checked and expanded instance names.
193

194
  Args:
195
    instances: List of instances (strings) or None for all
196

197
  """
198
  if not isinstance(instances, list):
199
    raise errors.OpPrereqError("Invalid argument type 'instances'")
200

    
201
  if instances:
202
    wanted = []
203

    
204
    for name in instances:
205
      instance = lu.cfg.ExpandInstanceName(name)
206
      if instance is None:
207
        raise errors.OpPrereqError("No such instance name '%s'" % name)
208
      wanted.append(instance)
209

    
210
  else:
211
    wanted = lu.cfg.GetInstanceList()
212
  return utils.NiceSort(wanted)
213

    
214

    
215
def _CheckOutputFields(static, dynamic, selected):
216
  """Checks whether all selected fields are valid.
217

218
  Args:
219
    static: Static fields
220
    dynamic: Dynamic fields
221

222
  """
223
  static_fields = frozenset(static)
224
  dynamic_fields = frozenset(dynamic)
225

    
226
  all_fields = static_fields | dynamic_fields
227

    
228
  if not all_fields.issuperset(selected):
229
    raise errors.OpPrereqError("Unknown output fields selected: %s"
230
                               % ",".join(frozenset(selected).
231
                                          difference(all_fields)))
232

    
233

    
234
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
235
                          memory, vcpus, nics):
236
  """Builds instance related env variables for hooks from single variables.
237

238
  Args:
239
    secondary_nodes: List of secondary nodes as strings
240
  """
241
  env = {
242
    "OP_TARGET": name,
243
    "INSTANCE_NAME": name,
244
    "INSTANCE_PRIMARY": primary_node,
245
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
246
    "INSTANCE_OS_TYPE": os_type,
247
    "INSTANCE_STATUS": status,
248
    "INSTANCE_MEMORY": memory,
249
    "INSTANCE_VCPUS": vcpus,
250
  }
251

    
252
  if nics:
253
    nic_count = len(nics)
254
    for idx, (ip, bridge) in enumerate(nics):
255
      if ip is None:
256
        ip = ""
257
      env["INSTANCE_NIC%d_IP" % idx] = ip
258
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
259
  else:
260
    nic_count = 0
261

    
262
  env["INSTANCE_NIC_COUNT"] = nic_count
263

    
264
  return env
265

    
266

    
267
def _BuildInstanceHookEnvByObject(instance, override=None):
268
  """Builds instance related env variables for hooks from an object.
269

270
  Args:
271
    instance: objects.Instance object of instance
272
    override: dict of values to override
273
  """
274
  args = {
275
    'name': instance.name,
276
    'primary_node': instance.primary_node,
277
    'secondary_nodes': instance.secondary_nodes,
278
    'os_type': instance.os,
279
    'status': instance.os,
280
    'memory': instance.memory,
281
    'vcpus': instance.vcpus,
282
    'nics': [(nic.ip, nic.bridge) for nic in instance.nics],
283
  }
284
  if override:
285
    args.update(override)
286
  return _BuildInstanceHookEnv(**args)
287

    
288

    
289
def _UpdateEtcHosts(fullnode, ip):
290
  """Ensure a node has a correct entry in /etc/hosts.
291

292
  Args:
293
    fullnode - Fully qualified domain name of host. (str)
294
    ip       - IPv4 address of host (str)
295

296
  """
297
  node = fullnode.split(".", 1)[0]
298

    
299
  f = open('/etc/hosts', 'r+')
300

    
301
  inthere = False
302

    
303
  save_lines = []
304
  add_lines = []
305
  removed = False
306

    
307
  while True:
308
    rawline = f.readline()
309

    
310
    if not rawline:
311
      # End of file
312
      break
313

    
314
    line = rawline.split('\n')[0]
315

    
316
    # Strip off comments
317
    line = line.split('#')[0]
318

    
319
    if not line:
320
      # Entire line was comment, skip
321
      save_lines.append(rawline)
322
      continue
323

    
324
    fields = line.split()
325

    
326
    haveall = True
327
    havesome = False
328
    for spec in [ ip, fullnode, node ]:
329
      if spec not in fields:
330
        haveall = False
331
      if spec in fields:
332
        havesome = True
333

    
334
    if haveall:
335
      inthere = True
336
      save_lines.append(rawline)
337
      continue
338

    
339
    if havesome and not haveall:
340
      # Line (old, or manual?) which is missing some.  Remove.
341
      removed = True
342
      continue
343

    
344
    save_lines.append(rawline)
345

    
346
  if not inthere:
347
    add_lines.append('%s\t%s %s\n' % (ip, fullnode, node))
348

    
349
  if removed:
350
    if add_lines:
351
      save_lines = save_lines + add_lines
352

    
353
    # We removed a line, write a new file and replace old.
354
    fd, tmpname = tempfile.mkstemp('tmp', 'hosts_', '/etc')
355
    newfile = os.fdopen(fd, 'w')
356
    newfile.write(''.join(save_lines))
357
    newfile.close()
358
    os.rename(tmpname, '/etc/hosts')
359

    
360
  elif add_lines:
361
    # Simply appending a new line will do the trick.
362
    f.seek(0, 2)
363
    for add in add_lines:
364
      f.write(add)
365

    
366
  f.close()
367

    
368

    
369
def _UpdateKnownHosts(fullnode, ip, pubkey):
370
  """Ensure a node has a correct known_hosts entry.
371

372
  Args:
373
    fullnode - Fully qualified domain name of host. (str)
374
    ip       - IPv4 address of host (str)
375
    pubkey   - the public key of the cluster
376

377
  """
378
  if os.path.exists(constants.SSH_KNOWN_HOSTS_FILE):
379
    f = open(constants.SSH_KNOWN_HOSTS_FILE, 'r+')
380
  else:
381
    f = open(constants.SSH_KNOWN_HOSTS_FILE, 'w+')
382

    
383
  inthere = False
384

    
385
  save_lines = []
386
  add_lines = []
387
  removed = False
388

    
389
  while True:
390
    rawline = f.readline()
391
    logger.Debug('read %s' % (repr(rawline),))
392

    
393
    if not rawline:
394
      # End of file
395
      break
396

    
397
    line = rawline.split('\n')[0]
398

    
399
    parts = line.split(' ')
400
    fields = parts[0].split(',')
401
    key = parts[2]
402

    
403
    haveall = True
404
    havesome = False
405
    for spec in [ ip, fullnode ]:
406
      if spec not in fields:
407
        haveall = False
408
      if spec in fields:
409
        havesome = True
410

    
411
    logger.Debug("key, pubkey = %s." % (repr((key, pubkey)),))
412
    if haveall and key == pubkey:
413
      inthere = True
414
      save_lines.append(rawline)
415
      logger.Debug("Keeping known_hosts '%s'." % (repr(rawline),))
416
      continue
417

    
418
    if havesome and (not haveall or key != pubkey):
419
      removed = True
420
      logger.Debug("Discarding known_hosts '%s'." % (repr(rawline),))
421
      continue
422

    
423
    save_lines.append(rawline)
424

    
425
  if not inthere:
426
    add_lines.append('%s,%s ssh-rsa %s\n' % (fullnode, ip, pubkey))
427
    logger.Debug("Adding known_hosts '%s'." % (repr(add_lines[-1]),))
428

    
429
  if removed:
430
    save_lines = save_lines + add_lines
431

    
432
    # Write a new file and replace old.
433
    fd, tmpname = tempfile.mkstemp('.tmp', 'known_hosts.',
434
                                   constants.DATA_DIR)
435
    newfile = os.fdopen(fd, 'w')
436
    try:
437
      newfile.write(''.join(save_lines))
438
    finally:
439
      newfile.close()
440
    logger.Debug("Wrote new known_hosts.")
441
    os.rename(tmpname, constants.SSH_KNOWN_HOSTS_FILE)
442

    
443
  elif add_lines:
444
    # Simply appending a new line will do the trick.
445
    f.seek(0, 2)
446
    for add in add_lines:
447
      f.write(add)
448

    
449
  f.close()
450

    
451

    
452
def _HasValidVG(vglist, vgname):
453
  """Checks if the volume group list is valid.
454

455
  A non-None return value means there's an error, and the return value
456
  is the error message.
457

458
  """
459
  vgsize = vglist.get(vgname, None)
460
  if vgsize is None:
461
    return "volume group '%s' missing" % vgname
462
  elif vgsize < 20480:
463
    return ("volume group '%s' too small (20480MiB required, %dMib found)" %
464
            (vgname, vgsize))
465
  return None
466

    
467

    
468
def _InitSSHSetup(node):
469
  """Setup the SSH configuration for the cluster.
470

471

472
  This generates a dsa keypair for root, adds the pub key to the
473
  permitted hosts and adds the hostkey to its own known hosts.
474

475
  Args:
476
    node: the name of this host as a fqdn
477

478
  """
479
  if os.path.exists('/root/.ssh/id_dsa'):
480
    utils.CreateBackup('/root/.ssh/id_dsa')
481
  if os.path.exists('/root/.ssh/id_dsa.pub'):
482
    utils.CreateBackup('/root/.ssh/id_dsa.pub')
483

    
484
  utils.RemoveFile('/root/.ssh/id_dsa')
485
  utils.RemoveFile('/root/.ssh/id_dsa.pub')
486

    
487
  result = utils.RunCmd(["ssh-keygen", "-t", "dsa",
488
                         "-f", "/root/.ssh/id_dsa",
489
                         "-q", "-N", ""])
490
  if result.failed:
491
    raise errors.OpExecError("Could not generate ssh keypair, error %s" %
492
                             result.output)
493

    
494
  f = open('/root/.ssh/id_dsa.pub', 'r')
495
  try:
496
    utils.AddAuthorizedKey('/root/.ssh/authorized_keys', f.read(8192))
497
  finally:
498
    f.close()
499

    
500

    
501
def _InitGanetiServerSetup(ss):
502
  """Setup the necessary configuration for the initial node daemon.
503

504
  This creates the nodepass file containing the shared password for
505
  the cluster and also generates the SSL certificate.
506

507
  """
508
  # Create pseudo random password
509
  randpass = sha.new(os.urandom(64)).hexdigest()
510
  # and write it into sstore
511
  ss.SetKey(ss.SS_NODED_PASS, randpass)
512

    
513
  result = utils.RunCmd(["openssl", "req", "-new", "-newkey", "rsa:1024",
514
                         "-days", str(365*5), "-nodes", "-x509",
515
                         "-keyout", constants.SSL_CERT_FILE,
516
                         "-out", constants.SSL_CERT_FILE, "-batch"])
517
  if result.failed:
518
    raise errors.OpExecError("could not generate server ssl cert, command"
519
                             " %s had exitcode %s and error message %s" %
520
                             (result.cmd, result.exit_code, result.output))
521

    
522
  os.chmod(constants.SSL_CERT_FILE, 0400)
523

    
524
  result = utils.RunCmd([constants.NODE_INITD_SCRIPT, "restart"])
525

    
526
  if result.failed:
527
    raise errors.OpExecError("Could not start the node daemon, command %s"
528
                             " had exitcode %s and error %s" %
529
                             (result.cmd, result.exit_code, result.output))
530

    
531

    
532
class LUInitCluster(LogicalUnit):
533
  """Initialise the cluster.
534

535
  """
536
  HPATH = "cluster-init"
537
  HTYPE = constants.HTYPE_CLUSTER
538
  _OP_REQP = ["cluster_name", "hypervisor_type", "vg_name", "mac_prefix",
539
              "def_bridge", "master_netdev"]
540
  REQ_CLUSTER = False
541

    
542
  def BuildHooksEnv(self):
543
    """Build hooks env.
544

545
    Notes: Since we don't require a cluster, we must manually add
546
    ourselves in the post-run node list.
547

548
    """
549
    env = {"OP_TARGET": self.op.cluster_name}
550
    return env, [], [self.hostname.name]
551

    
552
  def CheckPrereq(self):
553
    """Verify that the passed name is a valid one.
554

555
    """
556
    if config.ConfigWriter.IsCluster():
557
      raise errors.OpPrereqError("Cluster is already initialised")
558

    
559
    self.hostname = hostname = utils.HostInfo()
560

    
561
    if hostname.ip.startswith("127."):
562
      raise errors.OpPrereqError("This host's IP resolves to the private"
563
                                 " range (%s). Please fix DNS or /etc/hosts." %
564
                                 (hostname.ip,))
565

    
566
    self.clustername = clustername = utils.HostInfo(self.op.cluster_name)
567

    
568
    if not utils.TcpPing(constants.LOCALHOST_IP_ADDRESS, hostname.ip,
569
                         constants.DEFAULT_NODED_PORT):
570
      raise errors.OpPrereqError("Inconsistency: this host's name resolves"
571
                                 " to %s,\nbut this ip address does not"
572
                                 " belong to this host."
573
                                 " Aborting." % hostname.ip)
574

    
575
    secondary_ip = getattr(self.op, "secondary_ip", None)
576
    if secondary_ip and not utils.IsValidIP(secondary_ip):
577
      raise errors.OpPrereqError("Invalid secondary ip given")
578
    if (secondary_ip and
579
        secondary_ip != hostname.ip and
580
        (not utils.TcpPing(constants.LOCALHOST_IP_ADDRESS, secondary_ip,
581
                           constants.DEFAULT_NODED_PORT))):
582
      raise errors.OpPrereqError("You gave %s as secondary IP,\n"
583
                                 "but it does not belong to this host." %
584
                                 secondary_ip)
585
    self.secondary_ip = secondary_ip
586

    
587
    # checks presence of the volume group given
588
    vgstatus = _HasValidVG(utils.ListVolumeGroups(), self.op.vg_name)
589

    
590
    if vgstatus:
591
      raise errors.OpPrereqError("Error: %s" % vgstatus)
592

    
593
    if not re.match("^[0-9a-z]{2}:[0-9a-z]{2}:[0-9a-z]{2}$",
594
                    self.op.mac_prefix):
595
      raise errors.OpPrereqError("Invalid mac prefix given '%s'" %
596
                                 self.op.mac_prefix)
597

    
598
    if self.op.hypervisor_type not in hypervisor.VALID_HTYPES:
599
      raise errors.OpPrereqError("Invalid hypervisor type given '%s'" %
600
                                 self.op.hypervisor_type)
601

    
602
    result = utils.RunCmd(["ip", "link", "show", "dev", self.op.master_netdev])
603
    if result.failed:
604
      raise errors.OpPrereqError("Invalid master netdev given (%s): '%s'" %
605
                                 (self.op.master_netdev,
606
                                  result.output.strip()))
607

    
608
  def Exec(self, feedback_fn):
609
    """Initialize the cluster.
610

611
    """
612
    clustername = self.clustername
613
    hostname = self.hostname
614

    
615
    # set up the simple store
616
    self.sstore = ss = ssconf.SimpleStore()
617
    ss.SetKey(ss.SS_HYPERVISOR, self.op.hypervisor_type)
618
    ss.SetKey(ss.SS_MASTER_NODE, hostname.name)
619
    ss.SetKey(ss.SS_MASTER_IP, clustername.ip)
620
    ss.SetKey(ss.SS_MASTER_NETDEV, self.op.master_netdev)
621
    ss.SetKey(ss.SS_CLUSTER_NAME, clustername.name)
622

    
623
    # set up the inter-node password and certificate
624
    _InitGanetiServerSetup(ss)
625

    
626
    # start the master ip
627
    rpc.call_node_start_master(hostname.name)
628

    
629
    # set up ssh config and /etc/hosts
630
    f = open('/etc/ssh/ssh_host_rsa_key.pub', 'r')
631
    try:
632
      sshline = f.read()
633
    finally:
634
      f.close()
635
    sshkey = sshline.split(" ")[1]
636

    
637
    _UpdateEtcHosts(hostname.name, hostname.ip)
638

    
639
    _UpdateKnownHosts(hostname.name, hostname.ip, sshkey)
640

    
641
    _InitSSHSetup(hostname.name)
642

    
643
    # init of cluster config file
644
    self.cfg = cfgw = config.ConfigWriter()
645
    cfgw.InitConfig(hostname.name, hostname.ip, self.secondary_ip,
646
                    sshkey, self.op.mac_prefix,
647
                    self.op.vg_name, self.op.def_bridge)
648

    
649

    
650
class LUDestroyCluster(NoHooksLU):
651
  """Logical unit for destroying the cluster.
652

653
  """
654
  _OP_REQP = []
655

    
656
  def CheckPrereq(self):
657
    """Check prerequisites.
658

659
    This checks whether the cluster is empty.
660

661
    Any errors are signalled by raising errors.OpPrereqError.
662

663
    """
664
    master = self.sstore.GetMasterNode()
665

    
666
    nodelist = self.cfg.GetNodeList()
667
    if len(nodelist) != 1 or nodelist[0] != master:
668
      raise errors.OpPrereqError("There are still %d node(s) in"
669
                                 " this cluster." % (len(nodelist) - 1))
670
    instancelist = self.cfg.GetInstanceList()
671
    if instancelist:
672
      raise errors.OpPrereqError("There are still %d instance(s) in"
673
                                 " this cluster." % len(instancelist))
674

    
675
  def Exec(self, feedback_fn):
676
    """Destroys the cluster.
677

678
    """
679
    utils.CreateBackup('/root/.ssh/id_dsa')
680
    utils.CreateBackup('/root/.ssh/id_dsa.pub')
681
    rpc.call_node_leave_cluster(self.sstore.GetMasterNode())
682

    
683

    
684
class LUVerifyCluster(NoHooksLU):
685
  """Verifies the cluster status.
686

687
  """
688
  _OP_REQP = []
689

    
690
  def _VerifyNode(self, node, file_list, local_cksum, vglist, node_result,
691
                  remote_version, feedback_fn):
692
    """Run multiple tests against a node.
693

694
    Test list:
695
      - compares ganeti version
696
      - checks vg existance and size > 20G
697
      - checks config file checksum
698
      - checks ssh to other nodes
699

700
    Args:
701
      node: name of the node to check
702
      file_list: required list of files
703
      local_cksum: dictionary of local files and their checksums
704

705
    """
706
    # compares ganeti version
707
    local_version = constants.PROTOCOL_VERSION
708
    if not remote_version:
709
      feedback_fn(" - ERROR: connection to %s failed" % (node))
710
      return True
711

    
712
    if local_version != remote_version:
713
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
714
                      (local_version, node, remote_version))
715
      return True
716

    
717
    # checks vg existance and size > 20G
718

    
719
    bad = False
720
    if not vglist:
721
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
722
                      (node,))
723
      bad = True
724
    else:
725
      vgstatus = _HasValidVG(vglist, self.cfg.GetVGName())
726
      if vgstatus:
727
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
728
        bad = True
729

    
730
    # checks config file checksum
731
    # checks ssh to any
732

    
733
    if 'filelist' not in node_result:
734
      bad = True
735
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
736
    else:
737
      remote_cksum = node_result['filelist']
738
      for file_name in file_list:
739
        if file_name not in remote_cksum:
740
          bad = True
741
          feedback_fn("  - ERROR: file '%s' missing" % file_name)
742
        elif remote_cksum[file_name] != local_cksum[file_name]:
743
          bad = True
744
          feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
745

    
746
    if 'nodelist' not in node_result:
747
      bad = True
748
      feedback_fn("  - ERROR: node hasn't returned node connectivity data")
749
    else:
750
      if node_result['nodelist']:
751
        bad = True
752
        for node in node_result['nodelist']:
753
          feedback_fn("  - ERROR: communication with node '%s': %s" %
754
                          (node, node_result['nodelist'][node]))
755
    hyp_result = node_result.get('hypervisor', None)
756
    if hyp_result is not None:
757
      feedback_fn("  - ERROR: hypervisor verify failure: '%s'" % hyp_result)
758
    return bad
759

    
760
  def _VerifyInstance(self, instance, node_vol_is, node_instance, feedback_fn):
761
    """Verify an instance.
762

763
    This function checks to see if the required block devices are
764
    available on the instance's node.
765

766
    """
767
    bad = False
768

    
769
    instancelist = self.cfg.GetInstanceList()
770
    if not instance in instancelist:
771
      feedback_fn("  - ERROR: instance %s not in instance list %s" %
772
                      (instance, instancelist))
773
      bad = True
774

    
775
    instanceconfig = self.cfg.GetInstanceInfo(instance)
776
    node_current = instanceconfig.primary_node
777

    
778
    node_vol_should = {}
779
    instanceconfig.MapLVsByNode(node_vol_should)
780

    
781
    for node in node_vol_should:
782
      for volume in node_vol_should[node]:
783
        if node not in node_vol_is or volume not in node_vol_is[node]:
784
          feedback_fn("  - ERROR: volume %s missing on node %s" %
785
                          (volume, node))
786
          bad = True
787

    
788
    if not instanceconfig.status == 'down':
789
      if not instance in node_instance[node_current]:
790
        feedback_fn("  - ERROR: instance %s not running on node %s" %
791
                        (instance, node_current))
792
        bad = True
793

    
794
    for node in node_instance:
795
      if (not node == node_current):
796
        if instance in node_instance[node]:
797
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
798
                          (instance, node))
799
          bad = True
800

    
801
    return not bad
802

    
803
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
804
    """Verify if there are any unknown volumes in the cluster.
805

806
    The .os, .swap and backup volumes are ignored. All other volumes are
807
    reported as unknown.
808

809
    """
810
    bad = False
811

    
812
    for node in node_vol_is:
813
      for volume in node_vol_is[node]:
814
        if node not in node_vol_should or volume not in node_vol_should[node]:
815
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
816
                      (volume, node))
817
          bad = True
818
    return bad
819

    
820
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
821
    """Verify the list of running instances.
822

823
    This checks what instances are running but unknown to the cluster.
824

825
    """
826
    bad = False
827
    for node in node_instance:
828
      for runninginstance in node_instance[node]:
829
        if runninginstance not in instancelist:
830
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
831
                          (runninginstance, node))
832
          bad = True
833
    return bad
834

    
835
  def CheckPrereq(self):
836
    """Check prerequisites.
837

838
    This has no prerequisites.
839

840
    """
841
    pass
842

    
843
  def Exec(self, feedback_fn):
844
    """Verify integrity of cluster, performing various test on nodes.
845

846
    """
847
    bad = False
848
    feedback_fn("* Verifying global settings")
849
    self.cfg.VerifyConfig()
850

    
851
    master = self.sstore.GetMasterNode()
852
    vg_name = self.cfg.GetVGName()
853
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
854
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
855
    node_volume = {}
856
    node_instance = {}
857

    
858
    # FIXME: verify OS list
859
    # do local checksums
860
    file_names = list(self.sstore.GetFileList())
861
    file_names.append(constants.SSL_CERT_FILE)
862
    file_names.append(constants.CLUSTER_CONF_FILE)
863
    local_checksums = utils.FingerprintFiles(file_names)
864

    
865
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
866
    all_volumeinfo = rpc.call_volume_list(nodelist, vg_name)
867
    all_instanceinfo = rpc.call_instance_list(nodelist)
868
    all_vglist = rpc.call_vg_list(nodelist)
869
    node_verify_param = {
870
      'filelist': file_names,
871
      'nodelist': nodelist,
872
      'hypervisor': None,
873
      }
874
    all_nvinfo = rpc.call_node_verify(nodelist, node_verify_param)
875
    all_rversion = rpc.call_version(nodelist)
876

    
877
    for node in nodelist:
878
      feedback_fn("* Verifying node %s" % node)
879
      result = self._VerifyNode(node, file_names, local_checksums,
880
                                all_vglist[node], all_nvinfo[node],
881
                                all_rversion[node], feedback_fn)
882
      bad = bad or result
883

    
884
      # node_volume
885
      volumeinfo = all_volumeinfo[node]
886

    
887
      if type(volumeinfo) != dict:
888
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
889
        bad = True
890
        continue
891

    
892
      node_volume[node] = volumeinfo
893

    
894
      # node_instance
895
      nodeinstance = all_instanceinfo[node]
896
      if type(nodeinstance) != list:
897
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
898
        bad = True
899
        continue
900

    
901
      node_instance[node] = nodeinstance
902

    
903
    node_vol_should = {}
904

    
905
    for instance in instancelist:
906
      feedback_fn("* Verifying instance %s" % instance)
907
      result =  self._VerifyInstance(instance, node_volume, node_instance,
908
                                     feedback_fn)
909
      bad = bad or result
910

    
911
      inst_config = self.cfg.GetInstanceInfo(instance)
912

    
913
      inst_config.MapLVsByNode(node_vol_should)
914

    
915
    feedback_fn("* Verifying orphan volumes")
916
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
917
                                       feedback_fn)
918
    bad = bad or result
919

    
920
    feedback_fn("* Verifying remaining instances")
921
    result = self._VerifyOrphanInstances(instancelist, node_instance,
922
                                         feedback_fn)
923
    bad = bad or result
924

    
925
    return int(bad)
926

    
927

    
928
class LURenameCluster(LogicalUnit):
929
  """Rename the cluster.
930

931
  """
932
  HPATH = "cluster-rename"
933
  HTYPE = constants.HTYPE_CLUSTER
934
  _OP_REQP = ["name"]
935

    
936
  def BuildHooksEnv(self):
937
    """Build hooks env.
938

939
    """
940
    env = {
941
      "OP_TARGET": self.op.sstore.GetClusterName(),
942
      "NEW_NAME": self.op.name,
943
      }
944
    mn = self.sstore.GetMasterNode()
945
    return env, [mn], [mn]
946

    
947
  def CheckPrereq(self):
948
    """Verify that the passed name is a valid one.
949

950
    """
951
    hostname = utils.HostInfo(self.op.name)
952

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

    
967
    self.op.name = new_name
968

    
969
  def Exec(self, feedback_fn):
970
    """Rename the cluster.
971

972
    """
973
    clustername = self.op.name
974
    ip = self.ip
975
    ss = self.sstore
976

    
977
    # shutdown the master IP
978
    master = ss.GetMasterNode()
979
    if not rpc.call_node_stop_master(master):
980
      raise errors.OpExecError("Could not disable the master role")
981

    
982
    try:
983
      # modify the sstore
984
      ss.SetKey(ss.SS_MASTER_IP, ip)
985
      ss.SetKey(ss.SS_CLUSTER_NAME, clustername)
986

    
987
      # Distribute updated ss config to all nodes
988
      myself = self.cfg.GetNodeInfo(master)
989
      dist_nodes = self.cfg.GetNodeList()
990
      if myself.name in dist_nodes:
991
        dist_nodes.remove(myself.name)
992

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

    
1006

    
1007
def _WaitForSync(cfgw, instance, oneshot=False, unlock=False):
1008
  """Sleep and poll for an instance's disk to sync.
1009

1010
  """
1011
  if not instance.disks:
1012
    return True
1013

    
1014
  if not oneshot:
1015
    logger.ToStdout("Waiting for instance %s to sync disks." % instance.name)
1016

    
1017
  node = instance.primary_node
1018

    
1019
  for dev in instance.disks:
1020
    cfgw.SetDiskID(dev, node)
1021

    
1022
  retries = 0
1023
  while True:
1024
    max_time = 0
1025
    done = True
1026
    cumul_degraded = False
1027
    rstats = rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1028
    if not rstats:
1029
      logger.ToStderr("Can't get any data from node %s" % node)
1030
      retries += 1
1031
      if retries >= 10:
1032
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1033
                                 " aborting." % node)
1034
      time.sleep(6)
1035
      continue
1036
    retries = 0
1037
    for i in range(len(rstats)):
1038
      mstat = rstats[i]
1039
      if mstat is None:
1040
        logger.ToStderr("Can't compute data for node %s/%s" %
1041
                        (node, instance.disks[i].iv_name))
1042
        continue
1043
      perc_done, est_time, is_degraded = mstat
1044
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1045
      if perc_done is not None:
1046
        done = False
1047
        if est_time is not None:
1048
          rem_time = "%d estimated seconds remaining" % est_time
1049
          max_time = est_time
1050
        else:
1051
          rem_time = "no time estimate"
1052
        logger.ToStdout("- device %s: %5.2f%% done, %s" %
1053
                        (instance.disks[i].iv_name, perc_done, rem_time))
1054
    if done or oneshot:
1055
      break
1056

    
1057
    if unlock:
1058
      utils.Unlock('cmd')
1059
    try:
1060
      time.sleep(min(60, max_time))
1061
    finally:
1062
      if unlock:
1063
        utils.Lock('cmd')
1064

    
1065
  if done:
1066
    logger.ToStdout("Instance %s's disks are in sync." % instance.name)
1067
  return not cumul_degraded
1068

    
1069

    
1070
def _CheckDiskConsistency(cfgw, dev, node, on_primary):
1071
  """Check that mirrors are not degraded.
1072

1073
  """
1074
  cfgw.SetDiskID(dev, node)
1075

    
1076
  result = True
1077
  if on_primary or dev.AssembleOnSecondary():
1078
    rstats = rpc.call_blockdev_find(node, dev)
1079
    if not rstats:
1080
      logger.ToStderr("Can't get any data from node %s" % node)
1081
      result = False
1082
    else:
1083
      result = result and (not rstats[5])
1084
  if dev.children:
1085
    for child in dev.children:
1086
      result = result and _CheckDiskConsistency(cfgw, child, node, on_primary)
1087

    
1088
  return result
1089

    
1090

    
1091
class LUDiagnoseOS(NoHooksLU):
1092
  """Logical unit for OS diagnose/query.
1093

1094
  """
1095
  _OP_REQP = []
1096

    
1097
  def CheckPrereq(self):
1098
    """Check prerequisites.
1099

1100
    This always succeeds, since this is a pure query LU.
1101

1102
    """
1103
    return
1104

    
1105
  def Exec(self, feedback_fn):
1106
    """Compute the list of OSes.
1107

1108
    """
1109
    node_list = self.cfg.GetNodeList()
1110
    node_data = rpc.call_os_diagnose(node_list)
1111
    if node_data == False:
1112
      raise errors.OpExecError("Can't gather the list of OSes")
1113
    return node_data
1114

    
1115

    
1116
class LURemoveNode(LogicalUnit):
1117
  """Logical unit for removing a node.
1118

1119
  """
1120
  HPATH = "node-remove"
1121
  HTYPE = constants.HTYPE_NODE
1122
  _OP_REQP = ["node_name"]
1123

    
1124
  def BuildHooksEnv(self):
1125
    """Build hooks env.
1126

1127
    This doesn't run on the target node in the pre phase as a failed
1128
    node would not allows itself to run.
1129

1130
    """
1131
    env = {
1132
      "OP_TARGET": self.op.node_name,
1133
      "NODE_NAME": self.op.node_name,
1134
      }
1135
    all_nodes = self.cfg.GetNodeList()
1136
    all_nodes.remove(self.op.node_name)
1137
    return env, all_nodes, all_nodes
1138

    
1139
  def CheckPrereq(self):
1140
    """Check prerequisites.
1141

1142
    This checks:
1143
     - the node exists in the configuration
1144
     - it does not have primary or secondary instances
1145
     - it's not the master
1146

1147
    Any errors are signalled by raising errors.OpPrereqError.
1148

1149
    """
1150
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1151
    if node is None:
1152
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1153

    
1154
    instance_list = self.cfg.GetInstanceList()
1155

    
1156
    masternode = self.sstore.GetMasterNode()
1157
    if node.name == masternode:
1158
      raise errors.OpPrereqError("Node is the master node,"
1159
                                 " you need to failover first.")
1160

    
1161
    for instance_name in instance_list:
1162
      instance = self.cfg.GetInstanceInfo(instance_name)
1163
      if node.name == instance.primary_node:
1164
        raise errors.OpPrereqError("Instance %s still running on the node,"
1165
                                   " please remove first." % instance_name)
1166
      if node.name in instance.secondary_nodes:
1167
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1168
                                   " please remove first." % instance_name)
1169
    self.op.node_name = node.name
1170
    self.node = node
1171

    
1172
  def Exec(self, feedback_fn):
1173
    """Removes the node from the cluster.
1174

1175
    """
1176
    node = self.node
1177
    logger.Info("stopping the node daemon and removing configs from node %s" %
1178
                node.name)
1179

    
1180
    rpc.call_node_leave_cluster(node.name)
1181

    
1182
    ssh.SSHCall(node.name, 'root', "%s stop" % constants.NODE_INITD_SCRIPT)
1183

    
1184
    logger.Info("Removing node %s from config" % node.name)
1185

    
1186
    self.cfg.RemoveNode(node.name)
1187

    
1188

    
1189
class LUQueryNodes(NoHooksLU):
1190
  """Logical unit for querying nodes.
1191

1192
  """
1193
  _OP_REQP = ["output_fields", "names"]
1194

    
1195
  def CheckPrereq(self):
1196
    """Check prerequisites.
1197

1198
    This checks that the fields required are valid output fields.
1199

1200
    """
1201
    self.dynamic_fields = frozenset(["dtotal", "dfree",
1202
                                     "mtotal", "mnode", "mfree",
1203
                                     "bootid"])
1204

    
1205
    _CheckOutputFields(static=["name", "pinst_cnt", "sinst_cnt",
1206
                               "pinst_list", "sinst_list",
1207
                               "pip", "sip"],
1208
                       dynamic=self.dynamic_fields,
1209
                       selected=self.op.output_fields)
1210

    
1211
    self.wanted = _GetWantedNodes(self, self.op.names)
1212

    
1213
  def Exec(self, feedback_fn):
1214
    """Computes the list of nodes and their attributes.
1215

1216
    """
1217
    nodenames = self.wanted
1218
    nodelist = [self.cfg.GetNodeInfo(name) for name in nodenames]
1219

    
1220
    # begin data gathering
1221

    
1222
    if self.dynamic_fields.intersection(self.op.output_fields):
1223
      live_data = {}
1224
      node_data = rpc.call_node_info(nodenames, self.cfg.GetVGName())
1225
      for name in nodenames:
1226
        nodeinfo = node_data.get(name, None)
1227
        if nodeinfo:
1228
          live_data[name] = {
1229
            "mtotal": utils.TryConvert(int, nodeinfo['memory_total']),
1230
            "mnode": utils.TryConvert(int, nodeinfo['memory_dom0']),
1231
            "mfree": utils.TryConvert(int, nodeinfo['memory_free']),
1232
            "dtotal": utils.TryConvert(int, nodeinfo['vg_size']),
1233
            "dfree": utils.TryConvert(int, nodeinfo['vg_free']),
1234
            "bootid": nodeinfo['bootid'],
1235
            }
1236
        else:
1237
          live_data[name] = {}
1238
    else:
1239
      live_data = dict.fromkeys(nodenames, {})
1240

    
1241
    node_to_primary = dict([(name, set()) for name in nodenames])
1242
    node_to_secondary = dict([(name, set()) for name in nodenames])
1243

    
1244
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1245
                             "sinst_cnt", "sinst_list"))
1246
    if inst_fields & frozenset(self.op.output_fields):
1247
      instancelist = self.cfg.GetInstanceList()
1248

    
1249
      for instance_name in instancelist:
1250
        inst = self.cfg.GetInstanceInfo(instance_name)
1251
        if inst.primary_node in node_to_primary:
1252
          node_to_primary[inst.primary_node].add(inst.name)
1253
        for secnode in inst.secondary_nodes:
1254
          if secnode in node_to_secondary:
1255
            node_to_secondary[secnode].add(inst.name)
1256

    
1257
    # end data gathering
1258

    
1259
    output = []
1260
    for node in nodelist:
1261
      node_output = []
1262
      for field in self.op.output_fields:
1263
        if field == "name":
1264
          val = node.name
1265
        elif field == "pinst_list":
1266
          val = list(node_to_primary[node.name])
1267
        elif field == "sinst_list":
1268
          val = list(node_to_secondary[node.name])
1269
        elif field == "pinst_cnt":
1270
          val = len(node_to_primary[node.name])
1271
        elif field == "sinst_cnt":
1272
          val = len(node_to_secondary[node.name])
1273
        elif field == "pip":
1274
          val = node.primary_ip
1275
        elif field == "sip":
1276
          val = node.secondary_ip
1277
        elif field in self.dynamic_fields:
1278
          val = live_data[node.name].get(field, None)
1279
        else:
1280
          raise errors.ParameterError(field)
1281
        node_output.append(val)
1282
      output.append(node_output)
1283

    
1284
    return output
1285

    
1286

    
1287
class LUQueryNodeVolumes(NoHooksLU):
1288
  """Logical unit for getting volumes on node(s).
1289

1290
  """
1291
  _OP_REQP = ["nodes", "output_fields"]
1292

    
1293
  def CheckPrereq(self):
1294
    """Check prerequisites.
1295

1296
    This checks that the fields required are valid output fields.
1297

1298
    """
1299
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1300

    
1301
    _CheckOutputFields(static=["node"],
1302
                       dynamic=["phys", "vg", "name", "size", "instance"],
1303
                       selected=self.op.output_fields)
1304

    
1305

    
1306
  def Exec(self, feedback_fn):
1307
    """Computes the list of nodes and their attributes.
1308

1309
    """
1310
    nodenames = self.nodes
1311
    volumes = rpc.call_node_volumes(nodenames)
1312

    
1313
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1314
             in self.cfg.GetInstanceList()]
1315

    
1316
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1317

    
1318
    output = []
1319
    for node in nodenames:
1320
      if node not in volumes or not volumes[node]:
1321
        continue
1322

    
1323
      node_vols = volumes[node][:]
1324
      node_vols.sort(key=lambda vol: vol['dev'])
1325

    
1326
      for vol in node_vols:
1327
        node_output = []
1328
        for field in self.op.output_fields:
1329
          if field == "node":
1330
            val = node
1331
          elif field == "phys":
1332
            val = vol['dev']
1333
          elif field == "vg":
1334
            val = vol['vg']
1335
          elif field == "name":
1336
            val = vol['name']
1337
          elif field == "size":
1338
            val = int(float(vol['size']))
1339
          elif field == "instance":
1340
            for inst in ilist:
1341
              if node not in lv_by_node[inst]:
1342
                continue
1343
              if vol['name'] in lv_by_node[inst][node]:
1344
                val = inst.name
1345
                break
1346
            else:
1347
              val = '-'
1348
          else:
1349
            raise errors.ParameterError(field)
1350
          node_output.append(str(val))
1351

    
1352
        output.append(node_output)
1353

    
1354
    return output
1355

    
1356

    
1357
class LUAddNode(LogicalUnit):
1358
  """Logical unit for adding node to the cluster.
1359

1360
  """
1361
  HPATH = "node-add"
1362
  HTYPE = constants.HTYPE_NODE
1363
  _OP_REQP = ["node_name"]
1364

    
1365
  def BuildHooksEnv(self):
1366
    """Build hooks env.
1367

1368
    This will run on all nodes before, and on all nodes + the new node after.
1369

1370
    """
1371
    env = {
1372
      "OP_TARGET": self.op.node_name,
1373
      "NODE_NAME": self.op.node_name,
1374
      "NODE_PIP": self.op.primary_ip,
1375
      "NODE_SIP": self.op.secondary_ip,
1376
      }
1377
    nodes_0 = self.cfg.GetNodeList()
1378
    nodes_1 = nodes_0 + [self.op.node_name, ]
1379
    return env, nodes_0, nodes_1
1380

    
1381
  def CheckPrereq(self):
1382
    """Check prerequisites.
1383

1384
    This checks:
1385
     - the new node is not already in the config
1386
     - it is resolvable
1387
     - its parameters (single/dual homed) matches the cluster
1388

1389
    Any errors are signalled by raising errors.OpPrereqError.
1390

1391
    """
1392
    node_name = self.op.node_name
1393
    cfg = self.cfg
1394

    
1395
    dns_data = utils.HostInfo(node_name)
1396

    
1397
    node = dns_data.name
1398
    primary_ip = self.op.primary_ip = dns_data.ip
1399
    secondary_ip = getattr(self.op, "secondary_ip", None)
1400
    if secondary_ip is None:
1401
      secondary_ip = primary_ip
1402
    if not utils.IsValidIP(secondary_ip):
1403
      raise errors.OpPrereqError("Invalid secondary IP given")
1404
    self.op.secondary_ip = secondary_ip
1405
    node_list = cfg.GetNodeList()
1406
    if node in node_list:
1407
      raise errors.OpPrereqError("Node %s is already in the configuration"
1408
                                 % node)
1409

    
1410
    for existing_node_name in node_list:
1411
      existing_node = cfg.GetNodeInfo(existing_node_name)
1412
      if (existing_node.primary_ip == primary_ip or
1413
          existing_node.secondary_ip == primary_ip or
1414
          existing_node.primary_ip == secondary_ip or
1415
          existing_node.secondary_ip == secondary_ip):
1416
        raise errors.OpPrereqError("New node ip address(es) conflict with"
1417
                                   " existing node %s" % existing_node.name)
1418

    
1419
    # check that the type of the node (single versus dual homed) is the
1420
    # same as for the master
1421
    myself = cfg.GetNodeInfo(self.sstore.GetMasterNode())
1422
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1423
    newbie_singlehomed = secondary_ip == primary_ip
1424
    if master_singlehomed != newbie_singlehomed:
1425
      if master_singlehomed:
1426
        raise errors.OpPrereqError("The master has no private ip but the"
1427
                                   " new node has one")
1428
      else:
1429
        raise errors.OpPrereqError("The master has a private ip but the"
1430
                                   " new node doesn't have one")
1431

    
1432
    # checks reachablity
1433
    if not utils.TcpPing(utils.HostInfo().name,
1434
                         primary_ip,
1435
                         constants.DEFAULT_NODED_PORT):
1436
      raise errors.OpPrereqError("Node not reachable by ping")
1437

    
1438
    if not newbie_singlehomed:
1439
      # check reachability from my secondary ip to newbie's secondary ip
1440
      if not utils.TcpPing(myself.secondary_ip,
1441
                           secondary_ip,
1442
                           constants.DEFAULT_NODED_PORT):
1443
        raise errors.OpPrereqError(
1444
          "Node secondary ip not reachable by TCP based ping to noded port")
1445

    
1446
    self.new_node = objects.Node(name=node,
1447
                                 primary_ip=primary_ip,
1448
                                 secondary_ip=secondary_ip)
1449

    
1450
  def Exec(self, feedback_fn):
1451
    """Adds the new node to the cluster.
1452

1453
    """
1454
    new_node = self.new_node
1455
    node = new_node.name
1456

    
1457
    # set up inter-node password and certificate and restarts the node daemon
1458
    gntpass = self.sstore.GetNodeDaemonPassword()
1459
    if not re.match('^[a-zA-Z0-9.]{1,64}$', gntpass):
1460
      raise errors.OpExecError("ganeti password corruption detected")
1461
    f = open(constants.SSL_CERT_FILE)
1462
    try:
1463
      gntpem = f.read(8192)
1464
    finally:
1465
      f.close()
1466
    # in the base64 pem encoding, neither '!' nor '.' are valid chars,
1467
    # so we use this to detect an invalid certificate; as long as the
1468
    # cert doesn't contain this, the here-document will be correctly
1469
    # parsed by the shell sequence below
1470
    if re.search('^!EOF\.', gntpem, re.MULTILINE):
1471
      raise errors.OpExecError("invalid PEM encoding in the SSL certificate")
1472
    if not gntpem.endswith("\n"):
1473
      raise errors.OpExecError("PEM must end with newline")
1474
    logger.Info("copy cluster pass to %s and starting the node daemon" % node)
1475

    
1476
    # and then connect with ssh to set password and start ganeti-noded
1477
    # note that all the below variables are sanitized at this point,
1478
    # either by being constants or by the checks above
1479
    ss = self.sstore
1480
    mycommand = ("umask 077 && "
1481
                 "echo '%s' > '%s' && "
1482
                 "cat > '%s' << '!EOF.' && \n"
1483
                 "%s!EOF.\n%s restart" %
1484
                 (gntpass, ss.KeyToFilename(ss.SS_NODED_PASS),
1485
                  constants.SSL_CERT_FILE, gntpem,
1486
                  constants.NODE_INITD_SCRIPT))
1487

    
1488
    result = ssh.SSHCall(node, 'root', mycommand, batch=False, ask_key=True)
1489
    if result.failed:
1490
      raise errors.OpExecError("Remote command on node %s, error: %s,"
1491
                               " output: %s" %
1492
                               (node, result.fail_reason, result.output))
1493

    
1494
    # check connectivity
1495
    time.sleep(4)
1496

    
1497
    result = rpc.call_version([node])[node]
1498
    if result:
1499
      if constants.PROTOCOL_VERSION == result:
1500
        logger.Info("communication to node %s fine, sw version %s match" %
1501
                    (node, result))
1502
      else:
1503
        raise errors.OpExecError("Version mismatch master version %s,"
1504
                                 " node version %s" %
1505
                                 (constants.PROTOCOL_VERSION, result))
1506
    else:
1507
      raise errors.OpExecError("Cannot get version from the new node")
1508

    
1509
    # setup ssh on node
1510
    logger.Info("copy ssh key to node %s" % node)
1511
    keyarray = []
1512
    keyfiles = ["/etc/ssh/ssh_host_dsa_key", "/etc/ssh/ssh_host_dsa_key.pub",
1513
                "/etc/ssh/ssh_host_rsa_key", "/etc/ssh/ssh_host_rsa_key.pub",
1514
                "/root/.ssh/id_dsa", "/root/.ssh/id_dsa.pub"]
1515

    
1516
    for i in keyfiles:
1517
      f = open(i, 'r')
1518
      try:
1519
        keyarray.append(f.read())
1520
      finally:
1521
        f.close()
1522

    
1523
    result = rpc.call_node_add(node, keyarray[0], keyarray[1], keyarray[2],
1524
                               keyarray[3], keyarray[4], keyarray[5])
1525

    
1526
    if not result:
1527
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
1528

    
1529
    # Add node to our /etc/hosts, and add key to known_hosts
1530
    _UpdateEtcHosts(new_node.name, new_node.primary_ip)
1531
    _UpdateKnownHosts(new_node.name, new_node.primary_ip,
1532
                      self.cfg.GetHostKey())
1533

    
1534
    if new_node.secondary_ip != new_node.primary_ip:
1535
      if not rpc.call_node_tcp_ping(new_node.name,
1536
                                    constants.LOCALHOST_IP_ADDRESS,
1537
                                    new_node.secondary_ip,
1538
                                    constants.DEFAULT_NODED_PORT,
1539
                                    10, False):
1540
        raise errors.OpExecError("Node claims it doesn't have the"
1541
                                 " secondary ip you gave (%s).\n"
1542
                                 "Please fix and re-run this command." %
1543
                                 new_node.secondary_ip)
1544

    
1545
    success, msg = ssh.VerifyNodeHostname(node)
1546
    if not success:
1547
      raise errors.OpExecError("Node '%s' claims it has a different hostname"
1548
                               " than the one the resolver gives: %s.\n"
1549
                               "Please fix and re-run this command." %
1550
                               (node, msg))
1551

    
1552
    # Distribute updated /etc/hosts and known_hosts to all nodes,
1553
    # including the node just added
1554
    myself = self.cfg.GetNodeInfo(self.sstore.GetMasterNode())
1555
    dist_nodes = self.cfg.GetNodeList() + [node]
1556
    if myself.name in dist_nodes:
1557
      dist_nodes.remove(myself.name)
1558

    
1559
    logger.Debug("Copying hosts and known_hosts to all nodes")
1560
    for fname in ("/etc/hosts", constants.SSH_KNOWN_HOSTS_FILE):
1561
      result = rpc.call_upload_file(dist_nodes, fname)
1562
      for to_node in dist_nodes:
1563
        if not result[to_node]:
1564
          logger.Error("copy of file %s to node %s failed" %
1565
                       (fname, to_node))
1566

    
1567
    to_copy = ss.GetFileList()
1568
    for fname in to_copy:
1569
      if not ssh.CopyFileToNode(node, fname):
1570
        logger.Error("could not copy file %s to node %s" % (fname, node))
1571

    
1572
    logger.Info("adding node %s to cluster.conf" % node)
1573
    self.cfg.AddNode(new_node)
1574

    
1575

    
1576
class LUMasterFailover(LogicalUnit):
1577
  """Failover the master node to the current node.
1578

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

1581
  """
1582
  HPATH = "master-failover"
1583
  HTYPE = constants.HTYPE_CLUSTER
1584
  REQ_MASTER = False
1585
  _OP_REQP = []
1586

    
1587
  def BuildHooksEnv(self):
1588
    """Build hooks env.
1589

1590
    This will run on the new master only in the pre phase, and on all
1591
    the nodes in the post phase.
1592

1593
    """
1594
    env = {
1595
      "OP_TARGET": self.new_master,
1596
      "NEW_MASTER": self.new_master,
1597
      "OLD_MASTER": self.old_master,
1598
      }
1599
    return env, [self.new_master], self.cfg.GetNodeList()
1600

    
1601
  def CheckPrereq(self):
1602
    """Check prerequisites.
1603

1604
    This checks that we are not already the master.
1605

1606
    """
1607
    self.new_master = utils.HostInfo().name
1608
    self.old_master = self.sstore.GetMasterNode()
1609

    
1610
    if self.old_master == self.new_master:
1611
      raise errors.OpPrereqError("This commands must be run on the node"
1612
                                 " where you want the new master to be.\n"
1613
                                 "%s is already the master" %
1614
                                 self.old_master)
1615

    
1616
  def Exec(self, feedback_fn):
1617
    """Failover the master node.
1618

1619
    This command, when run on a non-master node, will cause the current
1620
    master to cease being master, and the non-master to become new
1621
    master.
1622

1623
    """
1624
    #TODO: do not rely on gethostname returning the FQDN
1625
    logger.Info("setting master to %s, old master: %s" %
1626
                (self.new_master, self.old_master))
1627

    
1628
    if not rpc.call_node_stop_master(self.old_master):
1629
      logger.Error("could disable the master role on the old master"
1630
                   " %s, please disable manually" % self.old_master)
1631

    
1632
    ss = self.sstore
1633
    ss.SetKey(ss.SS_MASTER_NODE, self.new_master)
1634
    if not rpc.call_upload_file(self.cfg.GetNodeList(),
1635
                                ss.KeyToFilename(ss.SS_MASTER_NODE)):
1636
      logger.Error("could not distribute the new simple store master file"
1637
                   " to the other nodes, please check.")
1638

    
1639
    if not rpc.call_node_start_master(self.new_master):
1640
      logger.Error("could not start the master role on the new master"
1641
                   " %s, please check" % self.new_master)
1642
      feedback_fn("Error in activating the master IP on the new master,\n"
1643
                  "please fix manually.")
1644

    
1645

    
1646

    
1647
class LUQueryClusterInfo(NoHooksLU):
1648
  """Query cluster configuration.
1649

1650
  """
1651
  _OP_REQP = []
1652
  REQ_MASTER = False
1653

    
1654
  def CheckPrereq(self):
1655
    """No prerequsites needed for this LU.
1656

1657
    """
1658
    pass
1659

    
1660
  def Exec(self, feedback_fn):
1661
    """Return cluster config.
1662

1663
    """
1664
    result = {
1665
      "name": self.sstore.GetClusterName(),
1666
      "software_version": constants.RELEASE_VERSION,
1667
      "protocol_version": constants.PROTOCOL_VERSION,
1668
      "config_version": constants.CONFIG_VERSION,
1669
      "os_api_version": constants.OS_API_VERSION,
1670
      "export_version": constants.EXPORT_VERSION,
1671
      "master": self.sstore.GetMasterNode(),
1672
      "architecture": (platform.architecture()[0], platform.machine()),
1673
      }
1674

    
1675
    return result
1676

    
1677

    
1678
class LUClusterCopyFile(NoHooksLU):
1679
  """Copy file to cluster.
1680

1681
  """
1682
  _OP_REQP = ["nodes", "filename"]
1683

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

1687
    It should check that the named file exists and that the given list
1688
    of nodes is valid.
1689

1690
    """
1691
    if not os.path.exists(self.op.filename):
1692
      raise errors.OpPrereqError("No such filename '%s'" % self.op.filename)
1693

    
1694
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1695

    
1696
  def Exec(self, feedback_fn):
1697
    """Copy a file from master to some nodes.
1698

1699
    Args:
1700
      opts - class with options as members
1701
      args - list containing a single element, the file name
1702
    Opts used:
1703
      nodes - list containing the name of target nodes; if empty, all nodes
1704

1705
    """
1706
    filename = self.op.filename
1707

    
1708
    myname = utils.HostInfo().name
1709

    
1710
    for node in self.nodes:
1711
      if node == myname:
1712
        continue
1713
      if not ssh.CopyFileToNode(node, filename):
1714
        logger.Error("Copy of file %s to node %s failed" % (filename, node))
1715

    
1716

    
1717
class LUDumpClusterConfig(NoHooksLU):
1718
  """Return a text-representation of the cluster-config.
1719

1720
  """
1721
  _OP_REQP = []
1722

    
1723
  def CheckPrereq(self):
1724
    """No prerequisites.
1725

1726
    """
1727
    pass
1728

    
1729
  def Exec(self, feedback_fn):
1730
    """Dump a representation of the cluster config to the standard output.
1731

1732
    """
1733
    return self.cfg.DumpConfig()
1734

    
1735

    
1736
class LURunClusterCommand(NoHooksLU):
1737
  """Run a command on some nodes.
1738

1739
  """
1740
  _OP_REQP = ["command", "nodes"]
1741

    
1742
  def CheckPrereq(self):
1743
    """Check prerequisites.
1744

1745
    It checks that the given list of nodes is valid.
1746

1747
    """
1748
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1749

    
1750
  def Exec(self, feedback_fn):
1751
    """Run a command on some nodes.
1752

1753
    """
1754
    data = []
1755
    for node in self.nodes:
1756
      result = ssh.SSHCall(node, "root", self.op.command)
1757
      data.append((node, result.output, result.exit_code))
1758

    
1759
    return data
1760

    
1761

    
1762
class LUActivateInstanceDisks(NoHooksLU):
1763
  """Bring up an instance's disks.
1764

1765
  """
1766
  _OP_REQP = ["instance_name"]
1767

    
1768
  def CheckPrereq(self):
1769
    """Check prerequisites.
1770

1771
    This checks that the instance is in the cluster.
1772

1773
    """
1774
    instance = self.cfg.GetInstanceInfo(
1775
      self.cfg.ExpandInstanceName(self.op.instance_name))
1776
    if instance is None:
1777
      raise errors.OpPrereqError("Instance '%s' not known" %
1778
                                 self.op.instance_name)
1779
    self.instance = instance
1780

    
1781

    
1782
  def Exec(self, feedback_fn):
1783
    """Activate the disks.
1784

1785
    """
1786
    disks_ok, disks_info = _AssembleInstanceDisks(self.instance, self.cfg)
1787
    if not disks_ok:
1788
      raise errors.OpExecError("Cannot activate block devices")
1789

    
1790
    return disks_info
1791

    
1792

    
1793
def _AssembleInstanceDisks(instance, cfg, ignore_secondaries=False):
1794
  """Prepare the block devices for an instance.
1795

1796
  This sets up the block devices on all nodes.
1797

1798
  Args:
1799
    instance: a ganeti.objects.Instance object
1800
    ignore_secondaries: if true, errors on secondary nodes won't result
1801
                        in an error return from the function
1802

1803
  Returns:
1804
    false if the operation failed
1805
    list of (host, instance_visible_name, node_visible_name) if the operation
1806
         suceeded with the mapping from node devices to instance devices
1807
  """
1808
  device_info = []
1809
  disks_ok = True
1810
  for inst_disk in instance.disks:
1811
    master_result = None
1812
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1813
      cfg.SetDiskID(node_disk, node)
1814
      is_primary = node == instance.primary_node
1815
      result = rpc.call_blockdev_assemble(node, node_disk, is_primary)
1816
      if not result:
1817
        logger.Error("could not prepare block device %s on node %s (is_pri"
1818
                     "mary=%s)" % (inst_disk.iv_name, node, is_primary))
1819
        if is_primary or not ignore_secondaries:
1820
          disks_ok = False
1821
      if is_primary:
1822
        master_result = result
1823
    device_info.append((instance.primary_node, inst_disk.iv_name,
1824
                        master_result))
1825

    
1826
  return disks_ok, device_info
1827

    
1828

    
1829
def _StartInstanceDisks(cfg, instance, force):
1830
  """Start the disks of an instance.
1831

1832
  """
1833
  disks_ok, dummy = _AssembleInstanceDisks(instance, cfg,
1834
                                           ignore_secondaries=force)
1835
  if not disks_ok:
1836
    _ShutdownInstanceDisks(instance, cfg)
1837
    if force is not None and not force:
1838
      logger.Error("If the message above refers to a secondary node,"
1839
                   " you can retry the operation using '--force'.")
1840
    raise errors.OpExecError("Disk consistency error")
1841

    
1842

    
1843
class LUDeactivateInstanceDisks(NoHooksLU):
1844
  """Shutdown an instance's disks.
1845

1846
  """
1847
  _OP_REQP = ["instance_name"]
1848

    
1849
  def CheckPrereq(self):
1850
    """Check prerequisites.
1851

1852
    This checks that the instance is in the cluster.
1853

1854
    """
1855
    instance = self.cfg.GetInstanceInfo(
1856
      self.cfg.ExpandInstanceName(self.op.instance_name))
1857
    if instance is None:
1858
      raise errors.OpPrereqError("Instance '%s' not known" %
1859
                                 self.op.instance_name)
1860
    self.instance = instance
1861

    
1862
  def Exec(self, feedback_fn):
1863
    """Deactivate the disks
1864

1865
    """
1866
    instance = self.instance
1867
    ins_l = rpc.call_instance_list([instance.primary_node])
1868
    ins_l = ins_l[instance.primary_node]
1869
    if not type(ins_l) is list:
1870
      raise errors.OpExecError("Can't contact node '%s'" %
1871
                               instance.primary_node)
1872

    
1873
    if self.instance.name in ins_l:
1874
      raise errors.OpExecError("Instance is running, can't shutdown"
1875
                               " block devices.")
1876

    
1877
    _ShutdownInstanceDisks(instance, self.cfg)
1878

    
1879

    
1880
def _ShutdownInstanceDisks(instance, cfg, ignore_primary=False):
1881
  """Shutdown block devices of an instance.
1882

1883
  This does the shutdown on all nodes of the instance.
1884

1885
  If the ignore_primary is false, errors on the primary node are
1886
  ignored.
1887

1888
  """
1889
  result = True
1890
  for disk in instance.disks:
1891
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
1892
      cfg.SetDiskID(top_disk, node)
1893
      if not rpc.call_blockdev_shutdown(node, top_disk):
1894
        logger.Error("could not shutdown block device %s on node %s" %
1895
                     (disk.iv_name, node))
1896
        if not ignore_primary or node != instance.primary_node:
1897
          result = False
1898
  return result
1899

    
1900

    
1901
class LUStartupInstance(LogicalUnit):
1902
  """Starts an instance.
1903

1904
  """
1905
  HPATH = "instance-start"
1906
  HTYPE = constants.HTYPE_INSTANCE
1907
  _OP_REQP = ["instance_name", "force"]
1908

    
1909
  def BuildHooksEnv(self):
1910
    """Build hooks env.
1911

1912
    This runs on master, primary and secondary nodes of the instance.
1913

1914
    """
1915
    env = {
1916
      "FORCE": self.op.force,
1917
      }
1918
    env.update(_BuildInstanceHookEnvByObject(self.instance))
1919
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
1920
          list(self.instance.secondary_nodes))
1921
    return env, nl, nl
1922

    
1923
  def CheckPrereq(self):
1924
    """Check prerequisites.
1925

1926
    This checks that the instance is in the cluster.
1927

1928
    """
1929
    instance = self.cfg.GetInstanceInfo(
1930
      self.cfg.ExpandInstanceName(self.op.instance_name))
1931
    if instance is None:
1932
      raise errors.OpPrereqError("Instance '%s' not known" %
1933
                                 self.op.instance_name)
1934

    
1935
    # check bridges existance
1936
    brlist = [nic.bridge for nic in instance.nics]
1937
    if not rpc.call_bridges_exist(instance.primary_node, brlist):
1938
      raise errors.OpPrereqError("one or more target bridges %s does not"
1939
                                 " exist on destination node '%s'" %
1940
                                 (brlist, instance.primary_node))
1941

    
1942
    self.instance = instance
1943
    self.op.instance_name = instance.name
1944

    
1945
  def Exec(self, feedback_fn):
1946
    """Start the instance.
1947

1948
    """
1949
    instance = self.instance
1950
    force = self.op.force
1951
    extra_args = getattr(self.op, "extra_args", "")
1952

    
1953
    node_current = instance.primary_node
1954

    
1955
    nodeinfo = rpc.call_node_info([node_current], self.cfg.GetVGName())
1956
    if not nodeinfo:
1957
      raise errors.OpExecError("Could not contact node %s for infos" %
1958
                               (node_current))
1959

    
1960
    freememory = nodeinfo[node_current]['memory_free']
1961
    memory = instance.memory
1962
    if memory > freememory:
1963
      raise errors.OpExecError("Not enough memory to start instance"
1964
                               " %s on node %s"
1965
                               " needed %s MiB, available %s MiB" %
1966
                               (instance.name, node_current, memory,
1967
                                freememory))
1968

    
1969
    _StartInstanceDisks(self.cfg, instance, force)
1970

    
1971
    if not rpc.call_instance_start(node_current, instance, extra_args):
1972
      _ShutdownInstanceDisks(instance, self.cfg)
1973
      raise errors.OpExecError("Could not start instance")
1974

    
1975
    self.cfg.MarkInstanceUp(instance.name)
1976

    
1977

    
1978
class LUShutdownInstance(LogicalUnit):
1979
  """Shutdown an instance.
1980

1981
  """
1982
  HPATH = "instance-stop"
1983
  HTYPE = constants.HTYPE_INSTANCE
1984
  _OP_REQP = ["instance_name"]
1985

    
1986
  def BuildHooksEnv(self):
1987
    """Build hooks env.
1988

1989
    This runs on master, primary and secondary nodes of the instance.
1990

1991
    """
1992
    env = _BuildInstanceHookEnvByObject(self.instance)
1993
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
1994
          list(self.instance.secondary_nodes))
1995
    return env, nl, nl
1996

    
1997
  def CheckPrereq(self):
1998
    """Check prerequisites.
1999

2000
    This checks that the instance is in the cluster.
2001

2002
    """
2003
    instance = self.cfg.GetInstanceInfo(
2004
      self.cfg.ExpandInstanceName(self.op.instance_name))
2005
    if instance is None:
2006
      raise errors.OpPrereqError("Instance '%s' not known" %
2007
                                 self.op.instance_name)
2008
    self.instance = instance
2009

    
2010
  def Exec(self, feedback_fn):
2011
    """Shutdown the instance.
2012

2013
    """
2014
    instance = self.instance
2015
    node_current = instance.primary_node
2016
    if not rpc.call_instance_shutdown(node_current, instance):
2017
      logger.Error("could not shutdown instance")
2018

    
2019
    self.cfg.MarkInstanceDown(instance.name)
2020
    _ShutdownInstanceDisks(instance, self.cfg)
2021

    
2022

    
2023
class LUReinstallInstance(LogicalUnit):
2024
  """Reinstall an instance.
2025

2026
  """
2027
  HPATH = "instance-reinstall"
2028
  HTYPE = constants.HTYPE_INSTANCE
2029
  _OP_REQP = ["instance_name"]
2030

    
2031
  def BuildHooksEnv(self):
2032
    """Build hooks env.
2033

2034
    This runs on master, primary and secondary nodes of the instance.
2035

2036
    """
2037
    env = _BuildInstanceHookEnvByObject(self.instance)
2038
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2039
          list(self.instance.secondary_nodes))
2040
    return env, nl, nl
2041

    
2042
  def CheckPrereq(self):
2043
    """Check prerequisites.
2044

2045
    This checks that the instance is in the cluster and is not running.
2046

2047
    """
2048
    instance = self.cfg.GetInstanceInfo(
2049
      self.cfg.ExpandInstanceName(self.op.instance_name))
2050
    if instance is None:
2051
      raise errors.OpPrereqError("Instance '%s' not known" %
2052
                                 self.op.instance_name)
2053
    if instance.disk_template == constants.DT_DISKLESS:
2054
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2055
                                 self.op.instance_name)
2056
    if instance.status != "down":
2057
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2058
                                 self.op.instance_name)
2059
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2060
    if remote_info:
2061
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2062
                                 (self.op.instance_name,
2063
                                  instance.primary_node))
2064

    
2065
    self.op.os_type = getattr(self.op, "os_type", None)
2066
    if self.op.os_type is not None:
2067
      # OS verification
2068
      pnode = self.cfg.GetNodeInfo(
2069
        self.cfg.ExpandNodeName(instance.primary_node))
2070
      if pnode is None:
2071
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2072
                                   self.op.pnode)
2073
      os_obj = rpc.call_os_get([pnode.name], self.op.os_type)[pnode.name]
2074
      if not isinstance(os_obj, objects.OS):
2075
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2076
                                   " primary node"  % self.op.os_type)
2077

    
2078
    self.instance = instance
2079

    
2080
  def Exec(self, feedback_fn):
2081
    """Reinstall the instance.
2082

2083
    """
2084
    inst = self.instance
2085

    
2086
    if self.op.os_type is not None:
2087
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2088
      inst.os = self.op.os_type
2089
      self.cfg.AddInstance(inst)
2090

    
2091
    _StartInstanceDisks(self.cfg, inst, None)
2092
    try:
2093
      feedback_fn("Running the instance OS create scripts...")
2094
      if not rpc.call_instance_os_add(inst.primary_node, inst, "sda", "sdb"):
2095
        raise errors.OpExecError("Could not install OS for instance %s "
2096
                                 "on node %s" %
2097
                                 (inst.name, inst.primary_node))
2098
    finally:
2099
      _ShutdownInstanceDisks(inst, self.cfg)
2100

    
2101

    
2102
class LURenameInstance(LogicalUnit):
2103
  """Rename an instance.
2104

2105
  """
2106
  HPATH = "instance-rename"
2107
  HTYPE = constants.HTYPE_INSTANCE
2108
  _OP_REQP = ["instance_name", "new_name"]
2109

    
2110
  def BuildHooksEnv(self):
2111
    """Build hooks env.
2112

2113
    This runs on master, primary and secondary nodes of the instance.
2114

2115
    """
2116
    env = _BuildInstanceHookEnvByObject(self.instance)
2117
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2118
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2119
          list(self.instance.secondary_nodes))
2120
    return env, nl, nl
2121

    
2122
  def CheckPrereq(self):
2123
    """Check prerequisites.
2124

2125
    This checks that the instance is in the cluster and is not running.
2126

2127
    """
2128
    instance = self.cfg.GetInstanceInfo(
2129
      self.cfg.ExpandInstanceName(self.op.instance_name))
2130
    if instance is None:
2131
      raise errors.OpPrereqError("Instance '%s' not known" %
2132
                                 self.op.instance_name)
2133
    if instance.status != "down":
2134
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2135
                                 self.op.instance_name)
2136
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2137
    if remote_info:
2138
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2139
                                 (self.op.instance_name,
2140
                                  instance.primary_node))
2141
    self.instance = instance
2142

    
2143
    # new name verification
2144
    name_info = utils.HostInfo(self.op.new_name)
2145

    
2146
    self.op.new_name = new_name = name_info.name
2147
    if not getattr(self.op, "ignore_ip", False):
2148
      command = ["fping", "-q", name_info.ip]
2149
      result = utils.RunCmd(command)
2150
      if not result.failed:
2151
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2152
                                   (name_info.ip, new_name))
2153

    
2154

    
2155
  def Exec(self, feedback_fn):
2156
    """Reinstall the instance.
2157

2158
    """
2159
    inst = self.instance
2160
    old_name = inst.name
2161

    
2162
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2163

    
2164
    # re-read the instance from the configuration after rename
2165
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2166

    
2167
    _StartInstanceDisks(self.cfg, inst, None)
2168
    try:
2169
      if not rpc.call_instance_run_rename(inst.primary_node, inst, old_name,
2170
                                          "sda", "sdb"):
2171
        msg = ("Could run OS rename script for instance %s\n"
2172
               "on node %s\n"
2173
               "(but the instance has been renamed in Ganeti)" %
2174
               (inst.name, inst.primary_node))
2175
        logger.Error(msg)
2176
    finally:
2177
      _ShutdownInstanceDisks(inst, self.cfg)
2178

    
2179

    
2180
class LURemoveInstance(LogicalUnit):
2181
  """Remove an instance.
2182

2183
  """
2184
  HPATH = "instance-remove"
2185
  HTYPE = constants.HTYPE_INSTANCE
2186
  _OP_REQP = ["instance_name"]
2187

    
2188
  def BuildHooksEnv(self):
2189
    """Build hooks env.
2190

2191
    This runs on master, primary and secondary nodes of the instance.
2192

2193
    """
2194
    env = _BuildInstanceHookEnvByObject(self.instance)
2195
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2196
          list(self.instance.secondary_nodes))
2197
    return env, nl, nl
2198

    
2199
  def CheckPrereq(self):
2200
    """Check prerequisites.
2201

2202
    This checks that the instance is in the cluster.
2203

2204
    """
2205
    instance = self.cfg.GetInstanceInfo(
2206
      self.cfg.ExpandInstanceName(self.op.instance_name))
2207
    if instance is None:
2208
      raise errors.OpPrereqError("Instance '%s' not known" %
2209
                                 self.op.instance_name)
2210
    self.instance = instance
2211

    
2212
  def Exec(self, feedback_fn):
2213
    """Remove the instance.
2214

2215
    """
2216
    instance = self.instance
2217
    logger.Info("shutting down instance %s on node %s" %
2218
                (instance.name, instance.primary_node))
2219

    
2220
    if not rpc.call_instance_shutdown(instance.primary_node, instance):
2221
      raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2222
                               (instance.name, instance.primary_node))
2223

    
2224
    logger.Info("removing block devices for instance %s" % instance.name)
2225

    
2226
    _RemoveDisks(instance, self.cfg)
2227

    
2228
    logger.Info("removing instance %s out of cluster config" % instance.name)
2229

    
2230
    self.cfg.RemoveInstance(instance.name)
2231

    
2232

    
2233
class LUQueryInstances(NoHooksLU):
2234
  """Logical unit for querying instances.
2235

2236
  """
2237
  _OP_REQP = ["output_fields", "names"]
2238

    
2239
  def CheckPrereq(self):
2240
    """Check prerequisites.
2241

2242
    This checks that the fields required are valid output fields.
2243

2244
    """
2245
    self.dynamic_fields = frozenset(["oper_state", "oper_ram"])
2246
    _CheckOutputFields(static=["name", "os", "pnode", "snodes",
2247
                               "admin_state", "admin_ram",
2248
                               "disk_template", "ip", "mac", "bridge",
2249
                               "sda_size", "sdb_size"],
2250
                       dynamic=self.dynamic_fields,
2251
                       selected=self.op.output_fields)
2252

    
2253
    self.wanted = _GetWantedInstances(self, self.op.names)
2254

    
2255
  def Exec(self, feedback_fn):
2256
    """Computes the list of nodes and their attributes.
2257

2258
    """
2259
    instance_names = self.wanted
2260
    instance_list = [self.cfg.GetInstanceInfo(iname) for iname
2261
                     in instance_names]
2262

    
2263
    # begin data gathering
2264

    
2265
    nodes = frozenset([inst.primary_node for inst in instance_list])
2266

    
2267
    bad_nodes = []
2268
    if self.dynamic_fields.intersection(self.op.output_fields):
2269
      live_data = {}
2270
      node_data = rpc.call_all_instances_info(nodes)
2271
      for name in nodes:
2272
        result = node_data[name]
2273
        if result:
2274
          live_data.update(result)
2275
        elif result == False:
2276
          bad_nodes.append(name)
2277
        # else no instance is alive
2278
    else:
2279
      live_data = dict([(name, {}) for name in instance_names])
2280

    
2281
    # end data gathering
2282

    
2283
    output = []
2284
    for instance in instance_list:
2285
      iout = []
2286
      for field in self.op.output_fields:
2287
        if field == "name":
2288
          val = instance.name
2289
        elif field == "os":
2290
          val = instance.os
2291
        elif field == "pnode":
2292
          val = instance.primary_node
2293
        elif field == "snodes":
2294
          val = list(instance.secondary_nodes)
2295
        elif field == "admin_state":
2296
          val = (instance.status != "down")
2297
        elif field == "oper_state":
2298
          if instance.primary_node in bad_nodes:
2299
            val = None
2300
          else:
2301
            val = bool(live_data.get(instance.name))
2302
        elif field == "admin_ram":
2303
          val = instance.memory
2304
        elif field == "oper_ram":
2305
          if instance.primary_node in bad_nodes:
2306
            val = None
2307
          elif instance.name in live_data:
2308
            val = live_data[instance.name].get("memory", "?")
2309
          else:
2310
            val = "-"
2311
        elif field == "disk_template":
2312
          val = instance.disk_template
2313
        elif field == "ip":
2314
          val = instance.nics[0].ip
2315
        elif field == "bridge":
2316
          val = instance.nics[0].bridge
2317
        elif field == "mac":
2318
          val = instance.nics[0].mac
2319
        elif field == "sda_size" or field == "sdb_size":
2320
          disk = instance.FindDisk(field[:3])
2321
          if disk is None:
2322
            val = None
2323
          else:
2324
            val = disk.size
2325
        else:
2326
          raise errors.ParameterError(field)
2327
        iout.append(val)
2328
      output.append(iout)
2329

    
2330
    return output
2331

    
2332

    
2333
class LUFailoverInstance(LogicalUnit):
2334
  """Failover an instance.
2335

2336
  """
2337
  HPATH = "instance-failover"
2338
  HTYPE = constants.HTYPE_INSTANCE
2339
  _OP_REQP = ["instance_name", "ignore_consistency"]
2340

    
2341
  def BuildHooksEnv(self):
2342
    """Build hooks env.
2343

2344
    This runs on master, primary and secondary nodes of the instance.
2345

2346
    """
2347
    env = {
2348
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2349
      }
2350
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2351
    nl = [self.sstore.GetMasterNode()] + list(self.instance.secondary_nodes)
2352
    return env, nl, nl
2353

    
2354
  def CheckPrereq(self):
2355
    """Check prerequisites.
2356

2357
    This checks that the instance is in the cluster.
2358

2359
    """
2360
    instance = self.cfg.GetInstanceInfo(
2361
      self.cfg.ExpandInstanceName(self.op.instance_name))
2362
    if instance is None:
2363
      raise errors.OpPrereqError("Instance '%s' not known" %
2364
                                 self.op.instance_name)
2365

    
2366
    if instance.disk_template != constants.DT_REMOTE_RAID1:
2367
      raise errors.OpPrereqError("Instance's disk layout is not"
2368
                                 " remote_raid1.")
2369

    
2370
    secondary_nodes = instance.secondary_nodes
2371
    if not secondary_nodes:
2372
      raise errors.ProgrammerError("no secondary node but using "
2373
                                   "DT_REMOTE_RAID1 template")
2374

    
2375
    # check memory requirements on the secondary node
2376
    target_node = secondary_nodes[0]
2377
    nodeinfo = rpc.call_node_info([target_node], self.cfg.GetVGName())
2378
    info = nodeinfo.get(target_node, None)
2379
    if not info:
2380
      raise errors.OpPrereqError("Cannot get current information"
2381
                                 " from node '%s'" % nodeinfo)
2382
    if instance.memory > info['memory_free']:
2383
      raise errors.OpPrereqError("Not enough memory on target node %s."
2384
                                 " %d MB available, %d MB required" %
2385
                                 (target_node, info['memory_free'],
2386
                                  instance.memory))
2387

    
2388
    # check bridge existance
2389
    brlist = [nic.bridge for nic in instance.nics]
2390
    if not rpc.call_bridges_exist(instance.primary_node, brlist):
2391
      raise errors.OpPrereqError("One or more target bridges %s does not"
2392
                                 " exist on destination node '%s'" %
2393
                                 (brlist, instance.primary_node))
2394

    
2395
    self.instance = instance
2396

    
2397
  def Exec(self, feedback_fn):
2398
    """Failover an instance.
2399

2400
    The failover is done by shutting it down on its present node and
2401
    starting it on the secondary.
2402

2403
    """
2404
    instance = self.instance
2405

    
2406
    source_node = instance.primary_node
2407
    target_node = instance.secondary_nodes[0]
2408

    
2409
    feedback_fn("* checking disk consistency between source and target")
2410
    for dev in instance.disks:
2411
      # for remote_raid1, these are md over drbd
2412
      if not _CheckDiskConsistency(self.cfg, dev, target_node, False):
2413
        if not self.op.ignore_consistency:
2414
          raise errors.OpExecError("Disk %s is degraded on target node,"
2415
                                   " aborting failover." % dev.iv_name)
2416

    
2417
    feedback_fn("* checking target node resource availability")
2418
    nodeinfo = rpc.call_node_info([target_node], self.cfg.GetVGName())
2419

    
2420
    if not nodeinfo:
2421
      raise errors.OpExecError("Could not contact target node %s." %
2422
                               target_node)
2423

    
2424
    free_memory = int(nodeinfo[target_node]['memory_free'])
2425
    memory = instance.memory
2426
    if memory > free_memory:
2427
      raise errors.OpExecError("Not enough memory to create instance %s on"
2428
                               " node %s. needed %s MiB, available %s MiB" %
2429
                               (instance.name, target_node, memory,
2430
                                free_memory))
2431

    
2432
    feedback_fn("* shutting down instance on source node")
2433
    logger.Info("Shutting down instance %s on node %s" %
2434
                (instance.name, source_node))
2435

    
2436
    if not rpc.call_instance_shutdown(source_node, instance):
2437
      logger.Error("Could not shutdown instance %s on node %s. Proceeding"
2438
                   " anyway. Please make sure node %s is down"  %
2439
                   (instance.name, source_node, source_node))
2440

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

    
2445
    instance.primary_node = target_node
2446
    # distribute new instance config to the other nodes
2447
    self.cfg.AddInstance(instance)
2448

    
2449
    feedback_fn("* activating the instance's disks on target node")
2450
    logger.Info("Starting instance %s on node %s" %
2451
                (instance.name, target_node))
2452

    
2453
    disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
2454
                                             ignore_secondaries=True)
2455
    if not disks_ok:
2456
      _ShutdownInstanceDisks(instance, self.cfg)
2457
      raise errors.OpExecError("Can't activate the instance's disks")
2458

    
2459
    feedback_fn("* starting the instance on the target node")
2460
    if not rpc.call_instance_start(target_node, instance, None):
2461
      _ShutdownInstanceDisks(instance, self.cfg)
2462
      raise errors.OpExecError("Could not start instance %s on node %s." %
2463
                               (instance.name, target_node))
2464

    
2465

    
2466
def _CreateBlockDevOnPrimary(cfg, node, device, info):
2467
  """Create a tree of block devices on the primary node.
2468

2469
  This always creates all devices.
2470

2471
  """
2472
  if device.children:
2473
    for child in device.children:
2474
      if not _CreateBlockDevOnPrimary(cfg, node, child, info):
2475
        return False
2476

    
2477
  cfg.SetDiskID(device, node)
2478
  new_id = rpc.call_blockdev_create(node, device, device.size, True, info)
2479
  if not new_id:
2480
    return False
2481
  if device.physical_id is None:
2482
    device.physical_id = new_id
2483
  return True
2484

    
2485

    
2486
def _CreateBlockDevOnSecondary(cfg, node, device, force, info):
2487
  """Create a tree of block devices on a secondary node.
2488

2489
  If this device type has to be created on secondaries, create it and
2490
  all its children.
2491

2492
  If not, just recurse to children keeping the same 'force' value.
2493

2494
  """
2495
  if device.CreateOnSecondary():
2496
    force = True
2497
  if device.children:
2498
    for child in device.children:
2499
      if not _CreateBlockDevOnSecondary(cfg, node, child, force, info):
2500
        return False
2501

    
2502
  if not force:
2503
    return True
2504
  cfg.SetDiskID(device, node)
2505
  new_id = rpc.call_blockdev_create(node, device, device.size, False, info)
2506
  if not new_id:
2507
    return False
2508
  if device.physical_id is None:
2509
    device.physical_id = new_id
2510
  return True
2511

    
2512

    
2513
def _GenerateUniqueNames(cfg, exts):
2514
  """Generate a suitable LV name.
2515

2516
  This will generate a logical volume name for the given instance.
2517

2518
  """
2519
  results = []
2520
  for val in exts:
2521
    new_id = cfg.GenerateUniqueID()
2522
    results.append("%s%s" % (new_id, val))
2523
  return results
2524

    
2525

    
2526
def _GenerateMDDRBDBranch(cfg, primary, secondary, size, names):
2527
  """Generate a drbd device complete with its children.
2528

2529
  """
2530
  port = cfg.AllocatePort()
2531
  vgname = cfg.GetVGName()
2532
  dev_data = objects.Disk(dev_type="lvm", size=size,
2533
                          logical_id=(vgname, names[0]))
2534
  dev_meta = objects.Disk(dev_type="lvm", size=128,
2535
                          logical_id=(vgname, names[1]))
2536
  drbd_dev = objects.Disk(dev_type="drbd", size=size,
2537
                          logical_id = (primary, secondary, port),
2538
                          children = [dev_data, dev_meta])
2539
  return drbd_dev
2540

    
2541

    
2542
def _GenerateDiskTemplate(cfg, template_name,
2543
                          instance_name, primary_node,
2544
                          secondary_nodes, disk_sz, swap_sz):
2545
  """Generate the entire disk layout for a given template type.
2546

2547
  """
2548
  #TODO: compute space requirements
2549

    
2550
  vgname = cfg.GetVGName()
2551
  if template_name == "diskless":
2552
    disks = []
2553
  elif template_name == "plain":
2554
    if len(secondary_nodes) != 0:
2555
      raise errors.ProgrammerError("Wrong template configuration")
2556

    
2557
    names = _GenerateUniqueNames(cfg, [".sda", ".sdb"])
2558
    sda_dev = objects.Disk(dev_type="lvm", size=disk_sz,
2559
                           logical_id=(vgname, names[0]),
2560
                           iv_name = "sda")
2561
    sdb_dev = objects.Disk(dev_type="lvm", size=swap_sz,
2562
                           logical_id=(vgname, names[1]),
2563
                           iv_name = "sdb")
2564
    disks = [sda_dev, sdb_dev]
2565
  elif template_name == "local_raid1":
2566
    if len(secondary_nodes) != 0:
2567
      raise errors.ProgrammerError("Wrong template configuration")
2568

    
2569

    
2570
    names = _GenerateUniqueNames(cfg, [".sda_m1", ".sda_m2",
2571
                                       ".sdb_m1", ".sdb_m2"])
2572
    sda_dev_m1 = objects.Disk(dev_type="lvm", size=disk_sz,
2573
                              logical_id=(vgname, names[0]))
2574
    sda_dev_m2 = objects.Disk(dev_type="lvm", size=disk_sz,
2575
                              logical_id=(vgname, names[1]))
2576
    md_sda_dev = objects.Disk(dev_type="md_raid1", iv_name = "sda",
2577
                              size=disk_sz,
2578
                              children = [sda_dev_m1, sda_dev_m2])
2579
    sdb_dev_m1 = objects.Disk(dev_type="lvm", size=swap_sz,
2580
                              logical_id=(vgname, names[2]))
2581
    sdb_dev_m2 = objects.Disk(dev_type="lvm", size=swap_sz,
2582
                              logical_id=(vgname, names[3]))
2583
    md_sdb_dev = objects.Disk(dev_type="md_raid1", iv_name = "sdb",
2584
                              size=swap_sz,
2585
                              children = [sdb_dev_m1, sdb_dev_m2])
2586
    disks = [md_sda_dev, md_sdb_dev]
2587
  elif template_name == constants.DT_REMOTE_RAID1:
2588
    if len(secondary_nodes) != 1:
2589
      raise errors.ProgrammerError("Wrong template configuration")
2590
    remote_node = secondary_nodes[0]
2591
    names = _GenerateUniqueNames(cfg, [".sda_data", ".sda_meta",
2592
                                       ".sdb_data", ".sdb_meta"])
2593
    drbd_sda_dev = _GenerateMDDRBDBranch(cfg, primary_node, remote_node,
2594
                                         disk_sz, names[0:2])
2595
    md_sda_dev = objects.Disk(dev_type="md_raid1", iv_name="sda",
2596
                              children = [drbd_sda_dev], size=disk_sz)
2597
    drbd_sdb_dev = _GenerateMDDRBDBranch(cfg, primary_node, remote_node,
2598
                                         swap_sz, names[2:4])
2599
    md_sdb_dev = objects.Disk(dev_type="md_raid1", iv_name="sdb",
2600
                              children = [drbd_sdb_dev], size=swap_sz)
2601
    disks = [md_sda_dev, md_sdb_dev]
2602
  else:
2603
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
2604
  return disks
2605

    
2606

    
2607
def _GetInstanceInfoText(instance):
2608
  """Compute that text that should be added to the disk's metadata.
2609

2610
  """
2611
  return "originstname+%s" % instance.name
2612

    
2613

    
2614
def _CreateDisks(cfg, instance):
2615
  """Create all disks for an instance.
2616

2617
  This abstracts away some work from AddInstance.
2618

2619
  Args:
2620
    instance: the instance object
2621

2622
  Returns:
2623
    True or False showing the success of the creation process
2624

2625
  """
2626
  info = _GetInstanceInfoText(instance)
2627

    
2628
  for device in instance.disks:
2629
    logger.Info("creating volume %s for instance %s" %
2630
              (device.iv_name, instance.name))
2631
    #HARDCODE
2632
    for secondary_node in instance.secondary_nodes:
2633
      if not _CreateBlockDevOnSecondary(cfg, secondary_node, device, False,
2634
                                        info):
2635
        logger.Error("failed to create volume %s (%s) on secondary node %s!" %
2636
                     (device.iv_name, device, secondary_node))
2637
        return False
2638
    #HARDCODE
2639
    if not _CreateBlockDevOnPrimary(cfg, instance.primary_node, device, info):
2640
      logger.Error("failed to create volume %s on primary!" %
2641
                   device.iv_name)
2642
      return False
2643
  return True
2644

    
2645

    
2646
def _RemoveDisks(instance, cfg):
2647
  """Remove all disks for an instance.
2648

2649
  This abstracts away some work from `AddInstance()` and
2650
  `RemoveInstance()`. Note that in case some of the devices couldn't
2651
  be remove, the removal will continue with the other ones (compare
2652
  with `_CreateDisks()`).
2653

2654
  Args:
2655
    instance: the instance object
2656

2657
  Returns:
2658
    True or False showing the success of the removal proces
2659

2660
  """
2661
  logger.Info("removing block devices for instance %s" % instance.name)
2662

    
2663
  result = True
2664
  for device in instance.disks:
2665
    for node, disk in device.ComputeNodeTree(instance.primary_node):
2666
      cfg.SetDiskID(disk, node)
2667
      if not rpc.call_blockdev_remove(node, disk):
2668
        logger.Error("could not remove block device %s on node %s,"
2669
                     " continuing anyway" %
2670
                     (device.iv_name, node))
2671
        result = False
2672
  return result
2673

    
2674

    
2675
class LUCreateInstance(LogicalUnit):
2676
  """Create an instance.
2677

2678
  """
2679
  HPATH = "instance-add"
2680
  HTYPE = constants.HTYPE_INSTANCE
2681
  _OP_REQP = ["instance_name", "mem_size", "disk_size", "pnode",
2682
              "disk_template", "swap_size", "mode", "start", "vcpus",
2683
              "wait_for_sync", "ip_check"]
2684

    
2685
  def BuildHooksEnv(self):
2686
    """Build hooks env.
2687

2688
    This runs on master, primary and secondary nodes of the instance.
2689

2690
    """
2691
    env = {
2692
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
2693
      "INSTANCE_DISK_SIZE": self.op.disk_size,
2694
      "INSTANCE_SWAP_SIZE": self.op.swap_size,
2695
      "INSTANCE_ADD_MODE": self.op.mode,
2696
      }
2697
    if self.op.mode == constants.INSTANCE_IMPORT:
2698
      env["INSTANCE_SRC_NODE"] = self.op.src_node
2699
      env["INSTANCE_SRC_PATH"] = self.op.src_path
2700
      env["INSTANCE_SRC_IMAGE"] = self.src_image
2701

    
2702
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
2703
      primary_node=self.op.pnode,
2704
      secondary_nodes=self.secondaries,
2705
      status=self.instance_status,
2706
      os_type=self.op.os_type,
2707
      memory=self.op.mem_size,
2708
      vcpus=self.op.vcpus,
2709
      nics=[(self.inst_ip, self.op.bridge)],
2710
    ))
2711

    
2712
    nl = ([self.sstore.GetMasterNode(), self.op.pnode] +
2713
          self.secondaries)
2714
    return env, nl, nl
2715

    
2716

    
2717
  def CheckPrereq(self):
2718
    """Check prerequisites.
2719

2720
    """
2721
    if self.op.mode not in (constants.INSTANCE_CREATE,
2722
                            constants.INSTANCE_IMPORT):
2723
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
2724
                                 self.op.mode)
2725

    
2726
    if self.op.mode == constants.INSTANCE_IMPORT:
2727
      src_node = getattr(self.op, "src_node", None)
2728
      src_path = getattr(self.op, "src_path", None)
2729
      if src_node is None or src_path is None:
2730
        raise errors.OpPrereqError("Importing an instance requires source"
2731
                                   " node and path options")
2732
      src_node_full = self.cfg.ExpandNodeName(src_node)
2733
      if src_node_full is None:
2734
        raise errors.OpPrereqError("Unknown source node '%s'" % src_node)
2735
      self.op.src_node = src_node = src_node_full
2736

    
2737
      if not os.path.isabs(src_path):
2738
        raise errors.OpPrereqError("The source path must be absolute")
2739

    
2740
      export_info = rpc.call_export_info(src_node, src_path)
2741

    
2742
      if not export_info:
2743
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
2744

    
2745
      if not export_info.has_section(constants.INISECT_EXP):
2746
        raise errors.ProgrammerError("Corrupted export config")
2747

    
2748
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
2749
      if (int(ei_version) != constants.EXPORT_VERSION):
2750
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
2751
                                   (ei_version, constants.EXPORT_VERSION))
2752

    
2753
      if int(export_info.get(constants.INISECT_INS, 'disk_count')) > 1:
2754
        raise errors.OpPrereqError("Can't import instance with more than"
2755
                                   " one data disk")
2756

    
2757
      # FIXME: are the old os-es, disk sizes, etc. useful?
2758
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
2759
      diskimage = os.path.join(src_path, export_info.get(constants.INISECT_INS,
2760
                                                         'disk0_dump'))
2761
      self.src_image = diskimage
2762
    else: # INSTANCE_CREATE
2763
      if getattr(self.op, "os_type", None) is None:
2764
        raise errors.OpPrereqError("No guest OS specified")
2765

    
2766
    # check primary node
2767
    pnode = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.pnode))
2768
    if pnode is None:
2769
      raise errors.OpPrereqError("Primary node '%s' is unknown" %
2770
                                 self.op.pnode)
2771
    self.op.pnode = pnode.name
2772
    self.pnode = pnode
2773
    self.secondaries = []
2774
    # disk template and mirror node verification
2775
    if self.op.disk_template not in constants.DISK_TEMPLATES:
2776
      raise errors.OpPrereqError("Invalid disk template name")
2777

    
2778
    if self.op.disk_template == constants.DT_REMOTE_RAID1:
2779
      if getattr(self.op, "snode", None) is None:
2780
        raise errors.OpPrereqError("The 'remote_raid1' disk template needs"
2781
                                   " a mirror node")
2782

    
2783
      snode_name = self.cfg.ExpandNodeName(self.op.snode)
2784
      if snode_name is None:
2785
        raise errors.OpPrereqError("Unknown secondary node '%s'" %
2786
                                   self.op.snode)
2787
      elif snode_name == pnode.name:
2788
        raise errors.OpPrereqError("The secondary node cannot be"
2789
                                   " the primary node.")
2790
      self.secondaries.append(snode_name)
2791

    
2792
    # Check lv size requirements
2793
    nodenames = [pnode.name] + self.secondaries
2794
    nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
2795

    
2796
    # Required free disk space as a function of disk and swap space
2797
    req_size_dict = {
2798
      constants.DT_DISKLESS: 0,
2799
      constants.DT_PLAIN: self.op.disk_size + self.op.swap_size,
2800
      constants.DT_LOCAL_RAID1: (self.op.disk_size + self.op.swap_size) * 2,
2801
      # 256 MB are added for drbd metadata, 128MB for each drbd device
2802
      constants.DT_REMOTE_RAID1: self.op.disk_size + self.op.swap_size + 256,
2803
    }
2804

    
2805
    if self.op.disk_template not in req_size_dict:
2806
      raise errors.ProgrammerError("Disk template '%s' size requirement"
2807
                                   " is unknown" %  self.op.disk_template)
2808

    
2809
    req_size = req_size_dict[self.op.disk_template]
2810

    
2811
    for node in nodenames:
2812
      info = nodeinfo.get(node, None)
2813
      if not info:
2814
        raise errors.OpPrereqError("Cannot get current information"
2815
                                   " from node '%s'" % nodeinfo)
2816
      if req_size > info['vg_free']:
2817
        raise errors.OpPrereqError("Not enough disk space on target node %s."
2818
                                   " %d MB available, %d MB required" %
2819
                                   (node, info['vg_free'], req_size))
2820

    
2821
    # os verification
2822
    os_obj = rpc.call_os_get([pnode.name], self.op.os_type)[pnode.name]
2823
    if not isinstance(os_obj, objects.OS):
2824
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
2825
                                 " primary node"  % self.op.os_type)
2826

    
2827
    # instance verification
2828
    hostname1 = utils.HostInfo(self.op.instance_name)
2829

    
2830
    self.op.instance_name = instance_name = hostname1.name
2831
    instance_list = self.cfg.GetInstanceList()
2832
    if instance_name in instance_list:
2833
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2834
                                 instance_name)
2835

    
2836
    ip = getattr(self.op, "ip", None)
2837
    if ip is None or ip.lower() == "none":
2838
      inst_ip = None
2839
    elif ip.lower() == "auto":
2840
      inst_ip = hostname1.ip
2841
    else:
2842
      if not utils.IsValidIP(ip):
2843
        raise errors.OpPrereqError("given IP address '%s' doesn't look"
2844
                                   " like a valid IP" % ip)
2845
      inst_ip = ip
2846
    self.inst_ip = inst_ip
2847

    
2848
    if self.op.start and not self.op.ip_check:
2849
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
2850
                                 " adding an instance in start mode")
2851

    
2852
    if self.op.ip_check:
2853
      if utils.TcpPing(utils.HostInfo().name, hostname1.ip,
2854
                       constants.DEFAULT_NODED_PORT):
2855
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2856
                                   (hostname1.ip, instance_name))
2857

    
2858
    # bridge verification
2859
    bridge = getattr(self.op, "bridge", None)
2860
    if bridge is None:
2861
      self.op.bridge = self.cfg.GetDefBridge()
2862
    else:
2863
      self.op.bridge = bridge
2864

    
2865
    if not rpc.call_bridges_exist(self.pnode.name, [self.op.bridge]):
2866
      raise errors.OpPrereqError("target bridge '%s' does not exist on"
2867
                                 " destination node '%s'" %
2868
                                 (self.op.bridge, pnode.name))
2869

    
2870
    if self.op.start:
2871
      self.instance_status = 'up'
2872
    else:
2873
      self.instance_status = 'down'
2874

    
2875
  def Exec(self, feedback_fn):
2876
    """Create and add the instance to the cluster.
2877

2878
    """
2879
    instance = self.op.instance_name
2880
    pnode_name = self.pnode.name
2881

    
2882
    nic = objects.NIC(bridge=self.op.bridge, mac=self.cfg.GenerateMAC())
2883
    if self.inst_ip is not None:
2884
      nic.ip = self.inst_ip
2885

    
2886
    disks = _GenerateDiskTemplate(self.cfg,
2887
                                  self.op.disk_template,
2888
                                  instance, pnode_name,
2889
                                  self.secondaries, self.op.disk_size,
2890
                                  self.op.swap_size)
2891

    
2892
    iobj = objects.Instance(name=instance, os=self.op.os_type,
2893
                            primary_node=pnode_name,
2894
                            memory=self.op.mem_size,
2895
                            vcpus=self.op.vcpus,
2896
                            nics=[nic], disks=disks,
2897
                            disk_template=self.op.disk_template,
2898
                            status=self.instance_status,
2899
                            )
2900

    
2901
    feedback_fn("* creating instance disks...")
2902
    if not _CreateDisks(self.cfg, iobj):
2903
      _RemoveDisks(iobj, self.cfg)
2904
      raise errors.OpExecError("Device creation failed, reverting...")
2905

    
2906
    feedback_fn("adding instance %s to cluster config" % instance)
2907

    
2908
    self.cfg.AddInstance(iobj)
2909

    
2910
    if self.op.wait_for_sync:
2911
      disk_abort = not _WaitForSync(self.cfg, iobj)
2912
    elif iobj.disk_template == constants.DT_REMOTE_RAID1:
2913
      # make sure the disks are not degraded (still sync-ing is ok)
2914
      time.sleep(15)
2915
      feedback_fn("* checking mirrors status")
2916
      disk_abort = not _WaitForSync(self.cfg, iobj, oneshot=True)
2917
    else:
2918
      disk_abort = False
2919

    
2920
    if disk_abort:
2921
      _RemoveDisks(iobj, self.cfg)
2922
      self.cfg.RemoveInstance(iobj.name)
2923
      raise errors.OpExecError("There are some degraded disks for"
2924
                               " this instance")
2925

    
2926
    feedback_fn("creating os for instance %s on node %s" %
2927
                (instance, pnode_name))
2928

    
2929
    if iobj.disk_template != constants.DT_DISKLESS:
2930
      if self.op.mode == constants.INSTANCE_CREATE:
2931
        feedback_fn("* running the instance OS create scripts...")
2932
        if not rpc.call_instance_os_add(pnode_name, iobj, "sda", "sdb"):
2933
          raise errors.OpExecError("could not add os for instance %s"
2934
                                   " on node %s" %
2935
                                   (instance, pnode_name))
2936

    
2937
      elif self.op.mode == constants.INSTANCE_IMPORT:
2938
        feedback_fn("* running the instance OS import scripts...")
2939
        src_node = self.op.src_node
2940
        src_image = self.src_image
2941
        if not rpc.call_instance_os_import(pnode_name, iobj, "sda", "sdb",
2942
                                                src_node, src_image):
2943
          raise errors.OpExecError("Could not import os for instance"
2944
                                   " %s on node %s" %
2945
                                   (instance, pnode_name))
2946
      else:
2947
        # also checked in the prereq part
2948
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
2949
                                     % self.op.mode)
2950

    
2951
    if self.op.start:
2952
      logger.Info("starting instance %s on node %s" % (instance, pnode_name))
2953
      feedback_fn("* starting instance...")
2954
      if not rpc.call_instance_start(pnode_name, iobj, None):
2955
        raise errors.OpExecError("Could not start instance")
2956

    
2957

    
2958
class LUConnectConsole(NoHooksLU):
2959
  """Connect to an instance's console.
2960

2961
  This is somewhat special in that it returns the command line that
2962
  you need to run on the master node in order to connect to the
2963
  console.
2964

2965
  """
2966
  _OP_REQP = ["instance_name"]
2967

    
2968
  def CheckPrereq(self):
2969
    """Check prerequisites.
2970

2971
    This checks that the instance is in the cluster.
2972

2973
    """
2974
    instance = self.cfg.GetInstanceInfo(
2975
      self.cfg.ExpandInstanceName(self.op.instance_name))
2976
    if instance is None:
2977
      raise errors.OpPrereqError("Instance '%s' not known" %
2978
                                 self.op.instance_name)
2979
    self.instance = instance
2980

    
2981
  def Exec(self, feedback_fn):
2982
    """Connect to the console of an instance
2983

2984
    """
2985
    instance = self.instance
2986
    node = instance.primary_node
2987

    
2988
    node_insts = rpc.call_instance_list([node])[node]
2989
    if node_insts is False:
2990
      raise errors.OpExecError("Can't connect to node %s." % node)
2991

    
2992
    if instance.name not in node_insts:
2993
      raise errors.OpExecError("Instance %s is not running." % instance.name)
2994

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

    
2997
    hyper = hypervisor.GetHypervisor()
2998
    console_cmd = hyper.GetShellCommandForConsole(instance.name)
2999
    # build ssh cmdline
3000
    argv = ["ssh", "-q", "-t"]
3001
    argv.extend(ssh.KNOWN_HOSTS_OPTS)
3002
    argv.extend(ssh.BATCH_MODE_OPTS)
3003
    argv.append(node)
3004
    argv.append(console_cmd)
3005
    return "ssh", argv
3006

    
3007

    
3008
class LUAddMDDRBDComponent(LogicalUnit):
3009
  """Adda new mirror member to an instance's disk.
3010

3011
  """
3012
  HPATH = "mirror-add"
3013
  HTYPE = constants.HTYPE_INSTANCE
3014
  _OP_REQP = ["instance_name", "remote_node", "disk_name"]
3015

    
3016
  def BuildHooksEnv(self):
3017
    """Build hooks env.
3018

3019
    This runs on the master, the primary and all the secondaries.
3020

3021
    """
3022
    env = {
3023
      "NEW_SECONDARY": self.op.remote_node,
3024
      "DISK_NAME": self.op.disk_name,
3025
      }
3026
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3027
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
3028
          self.op.remote_node,] + list(self.instance.secondary_nodes)
3029
    return env, nl, nl
3030

    
3031
  def CheckPrereq(self):
3032
    """Check prerequisites.
3033

3034
    This checks that the instance is in the cluster.
3035

3036
    """
3037
    instance = self.cfg.GetInstanceInfo(
3038
      self.cfg.ExpandInstanceName(self.op.instance_name))
3039
    if instance is None:
3040
      raise errors.OpPrereqError("Instance '%s' not known" %
3041
                                 self.op.instance_name)
3042
    self.instance = instance
3043

    
3044
    remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
3045
    if remote_node is None:
3046
      raise errors.OpPrereqError("Node '%s' not known" % self.op.remote_node)
3047
    self.remote_node = remote_node
3048

    
3049
    if remote_node == instance.primary_node:
3050
      raise errors.OpPrereqError("The specified node is the primary node of"
3051
                                 " the instance.")
3052

    
3053
    if instance.disk_template != constants.DT_REMOTE_RAID1:
3054
      raise errors.OpPrereqError("Instance's disk layout is not"
3055
                                 " remote_raid1.")
3056
    for disk in instance.disks:
3057
      if disk.iv_name == self.op.disk_name:
3058
        break
3059
    else:
3060
      raise errors.OpPrereqError("Can't find this device ('%s') in the"
3061
                                 " instance." % self.op.disk_name)
3062
    if len(disk.children) > 1:
3063
      raise errors.OpPrereqError("The device already has two slave"
3064
                                 " devices.\n"
3065
                                 "This would create a 3-disk raid1"
3066
                                 " which we don't allow.")
3067
    self.disk = disk
3068

    
3069
  def Exec(self, feedback_fn):
3070
    """Add the mirror component
3071

3072
    """
3073
    disk = self.disk
3074
    instance = self.instance
3075

    
3076
    remote_node = self.remote_node
3077
    lv_names = [".%s_%s" % (disk.iv_name, suf) for suf in ["data", "meta"]]
3078
    names = _GenerateUniqueNames(self.cfg, lv_names)
3079
    new_drbd = _GenerateMDDRBDBranch(self.cfg, instance.primary_node,
3080
                                     remote_node, disk.size, names)
3081

    
3082
    logger.Info("adding new mirror component on secondary")
3083
    #HARDCODE
3084
    if not _CreateBlockDevOnSecondary(self.cfg, remote_node, new_drbd, False,
3085
                                      _GetInstanceInfoText(instance)):
3086
      raise errors.OpExecError("Failed to create new component on secondary"
3087
                               " node %s" % remote_node)
3088

    
3089
    logger.Info("adding new mirror component on primary")
3090
    #HARDCODE
3091
    if not _CreateBlockDevOnPrimary(self.cfg, instance.primary_node, new_drbd,
3092
                                    _GetInstanceInfoText(instance)):
3093
      # remove secondary dev
3094
      self.cfg.SetDiskID(new_drbd, remote_node)
3095
      rpc.call_blockdev_remove(remote_node, new_drbd)
3096
      raise errors.OpExecError("Failed to create volume on primary")
3097

    
3098
    # the device exists now
3099
    # call the primary node to add the mirror to md
3100
    logger.Info("adding new mirror component to md")
3101
    if not rpc.call_blockdev_addchild(instance.primary_node,
3102
                                           disk, new_drbd):
3103
      logger.Error("Can't add mirror compoment to md!")
3104
      self.cfg.SetDiskID(new_drbd, remote_node)
3105
      if not rpc.call_blockdev_remove(remote_node, new_drbd):
3106
        logger.Error("Can't rollback on secondary")
3107
      self.cfg.SetDiskID(new_drbd, instance.primary_node)
3108
      if not rpc.call_blockdev_remove(instance.primary_node, new_drbd):
3109
        logger.Error("Can't rollback on primary")
3110
      raise errors.OpExecError("Can't add mirror component to md array")
3111

    
3112
    disk.children.append(new_drbd)
3113

    
3114
    self.cfg.AddInstance(instance)
3115

    
3116
    _WaitForSync(self.cfg, instance)
3117

    
3118
    return 0
3119

    
3120

    
3121
class LURemoveMDDRBDComponent(LogicalUnit):
3122
  """Remove a component from a remote_raid1 disk.
3123

3124
  """
3125
  HPATH = "mirror-remove"
3126
  HTYPE = constants.HTYPE_INSTANCE
3127
  _OP_REQP = ["instance_name", "disk_name", "disk_id"]
3128

    
3129
  def BuildHooksEnv(self):
3130
    """Build hooks env.
3131

3132
    This runs on the master, the primary and all the secondaries.
3133

3134
    """
3135
    env = {
3136
      "DISK_NAME": self.op.disk_name,
3137
      "DISK_ID": self.op.disk_id,
3138
      "OLD_SECONDARY": self.old_secondary,
3139
      }
3140
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3141
    nl = [self.sstore.GetMasterNode(),
3142
          self.instance.primary_node] + list(self.instance.secondary_nodes)
3143
    return env, nl, nl
3144

    
3145
  def CheckPrereq(self):
3146
    """Check prerequisites.
3147

3148
    This checks that the instance is in the cluster.
3149

3150
    """
3151
    instance = self.cfg.GetInstanceInfo(
3152
      self.cfg.ExpandInstanceName(self.op.instance_name))
3153
    if instance is None:
3154
      raise errors.OpPrereqError("Instance '%s' not known" %
3155
                                 self.op.instance_name)
3156
    self.instance = instance
3157

    
3158
    if instance.disk_template != constants.DT_REMOTE_RAID1:
3159
      raise errors.OpPrereqError("Instance's disk layout is not"
3160
                                 " remote_raid1.")
3161
    for disk in instance.disks:
3162
      if disk.iv_name == self.op.disk_name:
3163
        break
3164
    else:
3165
      raise errors.OpPrereqError("Can't find this device ('%s') in the"
3166
                                 " instance." % self.op.disk_name)
3167
    for child in disk.children:
3168
      if child.dev_type == "drbd" and child.logical_id[2] == self.op.disk_id:
3169
        break
3170
    else:
3171
      raise errors.OpPrereqError("Can't find the device with this port.")
3172

    
3173
    if len(disk.children) < 2:
3174
      raise errors.OpPrereqError("Cannot remove the last component from"
3175
                                 " a mirror.")
3176
    self.disk = disk
3177
    self.child = child
3178
    if self.child.logical_id[0] == instance.primary_node:
3179
      oid = 1
3180
    else:
3181
      oid = 0
3182
    self.old_secondary = self.child.logical_id[oid]
3183

    
3184
  def Exec(self, feedback_fn):
3185
    """Remove the mirror component
3186

3187
    """
3188
    instance = self.instance
3189
    disk = self.disk
3190
    child = self.child
3191
    logger.Info("remove mirror component")
3192
    self.cfg.SetDiskID(disk, instance.primary_node)
3193
    if not rpc.call_blockdev_removechild(instance.primary_node,
3194
                                              disk, child):
3195
      raise errors.OpExecError("Can't remove child from mirror.")
3196

    
3197
    for node in child.logical_id[:2]:
3198
      self.cfg.SetDiskID(child, node)
3199
      if not rpc.call_blockdev_remove(node, child):
3200
        logger.Error("Warning: failed to remove device from node %s,"
3201
                     " continuing operation." % node)
3202

    
3203
    disk.children.remove(child)
3204
    self.cfg.AddInstance(instance)
3205

    
3206

    
3207
class LUReplaceDisks(LogicalUnit):
3208
  """Replace the disks of an instance.
3209

3210
  """
3211
  HPATH = "mirrors-replace"
3212
  HTYPE = constants.HTYPE_INSTANCE
3213
  _OP_REQP = ["instance_name"]
3214

    
3215
  def BuildHooksEnv(self):
3216
    """Build hooks env.
3217

3218
    This runs on the master, the primary and all the secondaries.
3219

3220
    """
3221
    env = {
3222
      "NEW_SECONDARY": self.op.remote_node,
3223
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
3224
      }
3225
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3226
    nl = [self.sstore.GetMasterNode(),
3227
          self.instance.primary_node] + list(self.instance.secondary_nodes)
3228
    return env, nl, nl
3229

    
3230
  def CheckPrereq(self):
3231
    """Check prerequisites.
3232

3233
    This checks that the instance is in the cluster.
3234

3235
    """
3236
    instance = self.cfg.GetInstanceInfo(
3237
      self.cfg.ExpandInstanceName(self.op.instance_name))
3238
    if instance is None:
3239
      raise errors.OpPrereqError("Instance '%s' not known" %
3240
                                 self.op.instance_name)
3241
    self.instance = instance
3242

    
3243
    if instance.disk_template != constants.DT_REMOTE_RAID1:
3244
      raise errors.OpPrereqError("Instance's disk layout is not"
3245
                                 " remote_raid1.")
3246

    
3247
    if len(instance.secondary_nodes) != 1:
3248
      raise errors.OpPrereqError("The instance has a strange layout,"
3249
                                 " expected one secondary but found %d" %
3250
                                 len(instance.secondary_nodes))
3251

    
3252
    remote_node = getattr(self.op, "remote_node", None)
3253
    if remote_node is None:
3254
      remote_node = instance.secondary_nodes[0]
3255
    else:
3256
      remote_node = self.cfg.ExpandNodeName(remote_node)
3257
      if remote_node is None:
3258
        raise errors.OpPrereqError("Node '%s' not known" %
3259
                                   self.op.remote_node)
3260
    if remote_node == instance.primary_node:
3261
      raise errors.OpPrereqError("The specified node is the primary node of"
3262
                                 " the instance.")
3263
    self.op.remote_node = remote_node
3264

    
3265
  def Exec(self, feedback_fn):
3266
    """Replace the disks of an instance.
3267

3268
    """
3269
    instance = self.instance
3270
    iv_names = {}
3271
    # start of work
3272
    remote_node = self.op.remote_node
3273
    cfg = self.cfg
3274
    for dev in instance.disks:
3275
      size = dev.size
3276
      lv_names = [".%s_%s" % (dev.iv_name, suf) for suf in ["data", "meta"]]
3277
      names = _GenerateUniqueNames(cfg, lv_names)
3278
      new_drbd = _GenerateMDDRBDBranch(cfg, instance.primary_node,
3279
                                       remote_node, size, names)
3280
      iv_names[dev.iv_name] = (dev, dev.children[0], new_drbd)
3281
      logger.Info("adding new mirror component on secondary for %s" %
3282
                  dev.iv_name)
3283
      #HARDCODE
3284
      if not _CreateBlockDevOnSecondary(cfg, remote_node, new_drbd, False,
3285
                                        _GetInstanceInfoText(instance)):
3286
        raise errors.OpExecError("Failed to create new component on"
3287
                                 " secondary node %s\n"
3288
                                 "Full abort, cleanup manually!" %
3289
                                 remote_node)
3290

    
3291
      logger.Info("adding new mirror component on primary")
3292
      #HARDCODE
3293
      if not _CreateBlockDevOnPrimary(cfg, instance.primary_node, new_drbd,
3294
                                      _GetInstanceInfoText(instance)):
3295
        # remove secondary dev
3296
        cfg.SetDiskID(new_drbd, remote_node)
3297
        rpc.call_blockdev_remove(remote_node, new_drbd)
3298
        raise errors.OpExecError("Failed to create volume on primary!\n"
3299
                                 "Full abort, cleanup manually!!")
3300

    
3301
      # the device exists now
3302
      # call the primary node to add the mirror to md
3303
      logger.Info("adding new mirror component to md")
3304
      if not rpc.call_blockdev_addchild(instance.primary_node, dev,
3305
                                        new_drbd):
3306
        logger.Error("Can't add mirror compoment to md!")
3307
        cfg.SetDiskID(new_drbd, remote_node)
3308
        if not rpc.call_blockdev_remove(remote_node, new_drbd):
3309
          logger.Error("Can't rollback on secondary")
3310
        cfg.SetDiskID(new_drbd, instance.primary_node)
3311
        if not rpc.call_blockdev_remove(instance.primary_node, new_drbd):
3312
          logger.Error("Can't rollback on primary")
3313
        raise errors.OpExecError("Full abort, cleanup manually!!")
3314

    
3315
      dev.children.append(new_drbd)
3316
      cfg.AddInstance(instance)
3317

    
3318
    # this can fail as the old devices are degraded and _WaitForSync
3319
    # does a combined result over all disks, so we don't check its
3320
    # return value
3321
    _WaitForSync(cfg, instance, unlock=True)
3322

    
3323
    # so check manually all the devices
3324
    for name in iv_names:
3325
      dev, child, new_drbd = iv_names[name]
3326
      cfg.SetDiskID(dev, instance.primary_node)
3327
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
3328
      if is_degr:
3329
        raise errors.OpExecError("MD device %s is degraded!" % name)
3330
      cfg.SetDiskID(new_drbd, instance.primary_node)
3331
      is_degr = rpc.call_blockdev_find(instance.primary_node, new_drbd)[5]
3332
      if is_degr:
3333
        raise errors.OpExecError("New drbd device %s is degraded!" % name)
3334

    
3335
    for name in iv_names:
3336
      dev, child, new_drbd = iv_names[name]
3337
      logger.Info("remove mirror %s component" % name)
3338
      cfg.SetDiskID(dev, instance.primary_node)
3339
      if not rpc.call_blockdev_removechild(instance.primary_node,
3340
                                                dev, child):
3341
        logger.Error("Can't remove child from mirror, aborting"
3342
                     " *this device cleanup*.\nYou need to cleanup manually!!")
3343
        continue
3344

    
3345
      for node in child.logical_id[:2]:
3346
        logger.Info("remove child device on %s" % node)
3347
        cfg.SetDiskID(child, node)
3348
        if not rpc.call_blockdev_remove(node, child):
3349
          logger.Error("Warning: failed to remove device from node %s,"
3350
                       " continuing operation." % node)
3351

    
3352
      dev.children.remove(child)
3353

    
3354
      cfg.AddInstance(instance)
3355

    
3356

    
3357
class LUQueryInstanceData(NoHooksLU):
3358
  """Query runtime instance data.
3359

3360
  """
3361
  _OP_REQP = ["instances"]
3362

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

3366
    This only checks the optional instance list against the existing names.
3367

3368
    """
3369
    if not isinstance(self.op.instances, list):
3370
      raise errors.OpPrereqError("Invalid argument type 'instances'")
3371
    if self.op.instances:
3372
      self.wanted_instances = []
3373
      names = self.op.instances
3374
      for name in names:
3375
        instance = self.cfg.GetInstanceInfo(self.cfg.ExpandInstanceName(name))
3376
        if instance is None:
3377
          raise errors.OpPrereqError("No such instance name '%s'" % name)
3378
      self.wanted_instances.append(instance)
3379
    else:
3380
      self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
3381
                               in self.cfg.GetInstanceList()]
3382
    return
3383

    
3384

    
3385
  def _ComputeDiskStatus(self, instance, snode, dev):
3386
    """Compute block device status.
3387

3388
    """
3389
    self.cfg.SetDiskID(dev, instance.primary_node)
3390
    dev_pstatus = rpc.call_blockdev_find(instance.primary_node, dev)
3391
    if dev.dev_type == "drbd":
3392
      # we change the snode then (otherwise we use the one passed in)
3393
      if dev.logical_id[0] == instance.primary_node:
3394
        snode = dev.logical_id[1]
3395
      else:
3396
        snode = dev.logical_id[0]
3397

    
3398
    if snode:
3399
      self.cfg.SetDiskID(dev, snode)
3400
      dev_sstatus = rpc.call_blockdev_find(snode, dev)
3401
    else:
3402
      dev_sstatus = None
3403

    
3404
    if dev.children:
3405
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
3406
                      for child in dev.children]
3407
    else:
3408
      dev_children = []
3409

    
3410
    data = {
3411
      "iv_name": dev.iv_name,
3412
      "dev_type": dev.dev_type,
3413
      "logical_id": dev.logical_id,
3414
      "physical_id": dev.physical_id,
3415
      "pstatus": dev_pstatus,
3416
      "sstatus": dev_sstatus,
3417
      "children": dev_children,
3418
      }
3419

    
3420
    return data
3421

    
3422
  def Exec(self, feedback_fn):
3423
    """Gather and return data"""
3424
    result = {}
3425
    for instance in self.wanted_instances:
3426
      remote_info = rpc.call_instance_info(instance.primary_node,
3427
                                                instance.name)
3428
      if remote_info and "state" in remote_info:
3429
        remote_state = "up"
3430
      else:
3431
        remote_state = "down"
3432
      if instance.status == "down":
3433
        config_state = "down"
3434
      else:
3435
        config_state = "up"
3436

    
3437
      disks = [self._ComputeDiskStatus(instance, None, device)
3438
               for device in instance.disks]
3439

    
3440
      idict = {
3441
        "name": instance.name,
3442
        "config_state": config_state,
3443
        "run_state": remote_state,
3444
        "pnode": instance.primary_node,
3445
        "snodes": instance.secondary_nodes,
3446
        "os": instance.os,
3447
        "memory": instance.memory,
3448
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
3449
        "disks": disks,
3450
        }
3451

    
3452
      result[instance.name] = idict
3453

    
3454
    return result
3455

    
3456

    
3457
class LUSetInstanceParms(LogicalUnit):
3458
  """Modifies an instances's parameters.
3459

3460
  """
3461
  HPATH = "instance-modify"
3462
  HTYPE = constants.HTYPE_INSTANCE
3463
  _OP_REQP = ["instance_name"]
3464

    
3465
  def BuildHooksEnv(self):
3466
    """Build hooks env.
3467

3468
    This runs on the master, primary and secondaries.
3469

3470
    """
3471
    args = dict()
3472
    if self.mem:
3473
      args['memory'] = self.mem
3474
    if self.vcpus:
3475
      args['vcpus'] = self.vcpus
3476
    if self.do_ip or self.do_bridge:
3477
      if self.do_ip:
3478
        ip = self.ip
3479
      else:
3480
        ip = self.instance.nics[0].ip
3481
      if self.bridge:
3482
        bridge = self.bridge
3483
      else:
3484
        bridge = self.instance.nics[0].bridge
3485
      args['nics'] = [(ip, bridge)]
3486
    env = _BuildInstanceHookEnvByObject(self.instance, override=args)
3487
    nl = [self.sstore.GetMasterNode(),
3488
          self.instance.primary_node] + list(self.instance.secondary_nodes)
3489
    return env, nl, nl
3490

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

3494
    This only checks the instance list against the existing names.
3495

3496
    """
3497
    self.mem = getattr(self.op, "mem", None)
3498
    self.vcpus = getattr(self.op, "vcpus", None)
3499
    self.ip = getattr(self.op, "ip", None)
3500
    self.bridge = getattr(self.op, "bridge", None)
3501
    if [self.mem, self.vcpus, self.ip, self.bridge].count(None) == 4:
3502
      raise errors.OpPrereqError("No changes submitted")
3503
    if self.mem is not None:
3504
      try:
3505
        self.mem = int(self.mem)
3506
      except ValueError, err:
3507
        raise errors.OpPrereqError("Invalid memory size: %s" % str(err))
3508
    if self.vcpus is not None:
3509
      try:
3510
        self.vcpus = int(self.vcpus)
3511
      except ValueError, err:
3512
        raise errors.OpPrereqError("Invalid vcpus number: %s" % str(err))
3513
    if self.ip is not None:
3514
      self.do_ip = True
3515
      if self.ip.lower() == "none":
3516
        self.ip = None
3517
      else:
3518
        if not utils.IsValidIP(self.ip):
3519
          raise errors.OpPrereqError("Invalid IP address '%s'." % self.ip)
3520
    else:
3521
      self.do_ip = False
3522
    self.do_bridge = (self.bridge is not None)
3523

    
3524
    instance = self.cfg.GetInstanceInfo(
3525
      self.cfg.ExpandInstanceName(self.op.instance_name))
3526
    if instance is None:
3527
      raise errors.OpPrereqError("No such instance name '%s'" %
3528
                                 self.op.instance_name)
3529
    self.op.instance_name = instance.name
3530
    self.instance = instance
3531
    return
3532

    
3533
  def Exec(self, feedback_fn):
3534
    """Modifies an instance.
3535

3536
    All parameters take effect only at the next restart of the instance.
3537
    """
3538
    result = []
3539
    instance = self.instance
3540
    if self.mem:
3541
      instance.memory = self.mem
3542
      result.append(("mem", self.mem))
3543
    if self.vcpus:
3544
      instance.vcpus = self.vcpus
3545
      result.append(("vcpus",  self.vcpus))
3546
    if self.do_ip:
3547
      instance.nics[0].ip = self.ip
3548
      result.append(("ip", self.ip))
3549
    if self.bridge:
3550
      instance.nics[0].bridge = self.bridge
3551
      result.append(("bridge", self.bridge))
3552

    
3553
    self.cfg.AddInstance(instance)
3554

    
3555
    return result
3556

    
3557

    
3558
class LUQueryExports(NoHooksLU):
3559
  """Query the exports list
3560

3561
  """
3562
  _OP_REQP = []
3563

    
3564
  def CheckPrereq(self):
3565
    """Check that the nodelist contains only existing nodes.
3566

3567
    """
3568
    self.nodes = _GetWantedNodes(self, getattr(self.op, "nodes", None))
3569

    
3570
  def Exec(self, feedback_fn):
3571
    """Compute the list of all the exported system images.
3572

3573
    Returns:
3574
      a dictionary with the structure node->(export-list)
3575
      where export-list is a list of the instances exported on
3576
      that node.
3577

3578
    """
3579
    return rpc.call_export_list(self.nodes)
3580

    
3581

    
3582
class LUExportInstance(LogicalUnit):
3583
  """Export an instance to an image in the cluster.
3584

3585
  """
3586
  HPATH = "instance-export"
3587
  HTYPE = constants.HTYPE_INSTANCE
3588
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
3589

    
3590
  def BuildHooksEnv(self):
3591
    """Build hooks env.
3592

3593
    This will run on the master, primary node and target node.
3594

3595
    """
3596
    env = {
3597
      "EXPORT_NODE": self.op.target_node,
3598
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
3599
      }
3600
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3601
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
3602
          self.op.target_node]
3603
    return env, nl, nl
3604

    
3605
  def CheckPrereq(self):
3606
    """Check prerequisites.
3607

3608
    This checks that the instance name is a valid one.
3609

3610
    """
3611
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
3612
    self.instance = self.cfg.GetInstanceInfo(instance_name)
3613
    if self.instance is None:
3614
      raise errors.OpPrereqError("Instance '%s' not found" %
3615
                                 self.op.instance_name)
3616

    
3617
    # node verification
3618
    dst_node_short = self.cfg.ExpandNodeName(self.op.target_node)
3619
    self.dst_node = self.cfg.GetNodeInfo(dst_node_short)
3620

    
3621
    if self.dst_node is None:
3622
      raise errors.OpPrereqError("Destination node '%s' is unknown." %
3623
                                 self.op.target_node)
3624
    self.op.target_node = self.dst_node.name
3625

    
3626
  def Exec(self, feedback_fn):
3627
    """Export an instance to an image in the cluster.
3628

3629
    """
3630
    instance = self.instance
3631
    dst_node = self.dst_node
3632
    src_node = instance.primary_node
3633
    # shutdown the instance, unless requested not to do so
3634
    if self.op.shutdown:
3635
      op = opcodes.OpShutdownInstance(instance_name=instance.name)
3636
      self.processor.ChainOpCode(op, feedback_fn)
3637

    
3638
    vgname = self.cfg.GetVGName()
3639

    
3640
    snap_disks = []
3641

    
3642
    try:
3643
      for disk in instance.disks:
3644
        if disk.iv_name == "sda":
3645
          # new_dev_name will be a snapshot of an lvm leaf of the one we passed
3646
          new_dev_name = rpc.call_blockdev_snapshot(src_node, disk)
3647

    
3648
          if not new_dev_name:
3649
            logger.Error("could not snapshot block device %s on node %s" %
3650
                         (disk.logical_id[1], src_node))
3651
          else:
3652
            new_dev = objects.Disk(dev_type="lvm", size=disk.size,
3653
                                      logical_id=(vgname, new_dev_name),
3654
                                      physical_id=(vgname, new_dev_name),
3655
                                      iv_name=disk.iv_name)
3656
            snap_disks.append(new_dev)
3657

    
3658
    finally:
3659
      if self.op.shutdown:
3660
        op = opcodes.OpStartupInstance(instance_name=instance.name,
3661
                                       force=False)
3662
        self.processor.ChainOpCode(op, feedback_fn)
3663

    
3664
    # TODO: check for size
3665

    
3666
    for dev in snap_disks:
3667
      if not rpc.call_snapshot_export(src_node, dev, dst_node.name,
3668
                                           instance):
3669
        logger.Error("could not export block device %s from node"
3670
                     " %s to node %s" %
3671
                     (dev.logical_id[1], src_node, dst_node.name))
3672
      if not rpc.call_blockdev_remove(src_node, dev):
3673
        logger.Error("could not remove snapshot block device %s from"
3674
                     " node %s" % (dev.logical_id[1], src_node))
3675

    
3676
    if not rpc.call_finalize_export(dst_node.name, instance, snap_disks):
3677
      logger.Error("could not finalize export for instance %s on node %s" %
3678
                   (instance.name, dst_node.name))
3679

    
3680
    nodelist = self.cfg.GetNodeList()
3681
    nodelist.remove(dst_node.name)
3682

    
3683
    # on one-node clusters nodelist will be empty after the removal
3684
    # if we proceed the backup would be removed because OpQueryExports
3685
    # substitutes an empty list with the full cluster node list.
3686
    if nodelist:
3687
      op = opcodes.OpQueryExports(nodes=nodelist)
3688
      exportlist = self.processor.ChainOpCode(op, feedback_fn)
3689
      for node in exportlist:
3690
        if instance.name in exportlist[node]:
3691
          if not rpc.call_export_remove(node, instance.name):
3692
            logger.Error("could not remove older export for instance %s"
3693
                         " on node %s" % (instance.name, node))
3694

    
3695

    
3696
class TagsLU(NoHooksLU):
3697
  """Generic tags LU.
3698

3699
  This is an abstract class which is the parent of all the other tags LUs.
3700

3701
  """
3702
  def CheckPrereq(self):
3703
    """Check prerequisites.
3704

3705
    """
3706
    if self.op.kind == constants.TAG_CLUSTER:
3707
      self.target = self.cfg.GetClusterInfo()
3708
    elif self.op.kind == constants.TAG_NODE:
3709
      name = self.cfg.ExpandNodeName(self.op.name)
3710
      if name is None:
3711
        raise errors.OpPrereqError("Invalid node name (%s)" %
3712
                                   (self.op.name,))
3713
      self.op.name = name
3714
      self.target = self.cfg.GetNodeInfo(name)
3715
    elif self.op.kind == constants.TAG_INSTANCE:
3716
      name = self.cfg.ExpandInstanceName(self.op.name)
3717
      if name is None:
3718
        raise errors.OpPrereqError("Invalid instance name (%s)" %
3719
                                   (self.op.name,))
3720
      self.op.name = name
3721
      self.target = self.cfg.GetInstanceInfo(name)
3722
    else:
3723
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
3724
                                 str(self.op.kind))
3725

    
3726

    
3727
class LUGetTags(TagsLU):
3728
  """Returns the tags of a given object.
3729

3730
  """
3731
  _OP_REQP = ["kind", "name"]
3732

    
3733
  def Exec(self, feedback_fn):
3734
    """Returns the tag list.
3735

3736
    """
3737
    return self.target.GetTags()
3738

    
3739

    
3740
class LUAddTags(TagsLU):
3741
  """Sets a tag on a given object.
3742

3743
  """
3744
  _OP_REQP = ["kind", "name", "tags"]
3745

    
3746
  def CheckPrereq(self):
3747
    """Check prerequisites.
3748

3749
    This checks the type and length of the tag name and value.
3750

3751
    """
3752
    TagsLU.CheckPrereq(self)
3753
    for tag in self.op.tags:
3754
      objects.TaggableObject.ValidateTag(tag)
3755

    
3756
  def Exec(self, feedback_fn):
3757
    """Sets the tag.
3758

3759
    """
3760
    try:
3761
      for tag in self.op.tags:
3762
        self.target.AddTag(tag)
3763
    except errors.TagError, err:
3764
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
3765
    try:
3766
      self.cfg.Update(self.target)
3767
    except errors.ConfigurationError:
3768
      raise errors.OpRetryError("There has been a modification to the"
3769
                                " config file and the operation has been"
3770
                                " aborted. Please retry.")
3771

    
3772

    
3773
class LUDelTags(TagsLU):
3774
  """Delete a list of tags from a given object.
3775

3776
  """
3777
  _OP_REQP = ["kind", "name", "tags"]
3778

    
3779
  def CheckPrereq(self):
3780
    """Check prerequisites.
3781

3782
    This checks that we have the given tag.
3783

3784
    """
3785
    TagsLU.CheckPrereq(self)
3786
    for tag in self.op.tags:
3787
      objects.TaggableObject.ValidateTag(tag)
3788
    del_tags = frozenset(self.op.tags)
3789
    cur_tags = self.target.GetTags()
3790
    if not del_tags <= cur_tags:
3791
      diff_tags = del_tags - cur_tags
3792
      diff_names = ["'%s'" % tag for tag in diff_tags]
3793
      diff_names.sort()
3794
      raise errors.OpPrereqError("Tag(s) %s not found" %
3795
                                 (",".join(diff_names)))
3796

    
3797
  def Exec(self, feedback_fn):
3798
    """Remove the tag from the object.
3799

3800
    """
3801
    for tag in self.op.tags:
3802
      self.target.RemoveTag(tag)
3803
    try:
3804
      self.cfg.Update(self.target)
3805
    except errors.ConfigurationError:
3806
      raise errors.OpRetryError("There has been a modification to the"
3807
                                " config file and the operation has been"
3808
                                " aborted. Please retry.")