Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 880478f8

History | View | Annotate | Download (108.3 kB)

1
#!/usr/bin/python
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 != socket.gethostname():
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 _UpdateEtcHosts(fullnode, ip):
168
  """Ensure a node has a correct entry in /etc/hosts.
169

170
  Args:
171
    fullnode - Fully qualified domain name of host. (str)
172
    ip       - IPv4 address of host (str)
173

174
  """
175
  node = fullnode.split(".", 1)[0]
176

    
177
  f = open('/etc/hosts', 'r+')
178

    
179
  inthere = False
180

    
181
  save_lines = []
182
  add_lines = []
183
  removed = False
184

    
185
  while True:
186
    rawline = f.readline()
187

    
188
    if not rawline:
189
      # End of file
190
      break
191

    
192
    line = rawline.split('\n')[0]
193

    
194
    # Strip off comments
195
    line = line.split('#')[0]
196

    
197
    if not line:
198
      # Entire line was comment, skip
199
      save_lines.append(rawline)
200
      continue
201

    
202
    fields = line.split()
203

    
204
    haveall = True
205
    havesome = False
206
    for spec in [ ip, fullnode, node ]:
207
      if spec not in fields:
208
        haveall = False
209
      if spec in fields:
210
        havesome = True
211

    
212
    if haveall:
213
      inthere = True
214
      save_lines.append(rawline)
215
      continue
216

    
217
    if havesome and not haveall:
218
      # Line (old, or manual?) which is missing some.  Remove.
219
      removed = True
220
      continue
221

    
222
    save_lines.append(rawline)
223

    
224
  if not inthere:
225
    add_lines.append('%s\t%s %s\n' % (ip, fullnode, node))
226

    
227
  if removed:
228
    if add_lines:
229
      save_lines = save_lines + add_lines
230

    
231
    # We removed a line, write a new file and replace old.
232
    fd, tmpname = tempfile.mkstemp('tmp', 'hosts_', '/etc')
233
    newfile = os.fdopen(fd, 'w')
234
    newfile.write(''.join(save_lines))
235
    newfile.close()
236
    os.rename(tmpname, '/etc/hosts')
237

    
238
  elif add_lines:
239
    # Simply appending a new line will do the trick.
240
    f.seek(0, 2)
241
    for add in add_lines:
242
      f.write(add)
243

    
244
  f.close()
245

    
246

    
247
def _UpdateKnownHosts(fullnode, ip, pubkey):
248
  """Ensure a node has a correct known_hosts entry.
249

250
  Args:
251
    fullnode - Fully qualified domain name of host. (str)
252
    ip       - IPv4 address of host (str)
253
    pubkey   - the public key of the cluster
254

255
  """
256
  if os.path.exists('/etc/ssh/ssh_known_hosts'):
257
    f = open('/etc/ssh/ssh_known_hosts', 'r+')
258
  else:
259
    f = open('/etc/ssh/ssh_known_hosts', 'w+')
260

    
261
  inthere = False
262

    
263
  save_lines = []
264
  add_lines = []
265
  removed = False
266

    
267
  while True:
268
    rawline = f.readline()
269
    logger.Debug('read %s' % (repr(rawline),))
270

    
271
    if not rawline:
272
      # End of file
273
      break
274

    
275
    line = rawline.split('\n')[0]
276

    
277
    parts = line.split(' ')
278
    fields = parts[0].split(',')
279
    key = parts[2]
280

    
281
    haveall = True
282
    havesome = False
283
    for spec in [ ip, fullnode ]:
284
      if spec not in fields:
285
        haveall = False
286
      if spec in fields:
287
        havesome = True
288

    
289
    logger.Debug("key, pubkey = %s." % (repr((key, pubkey)),))
290
    if haveall and key == pubkey:
291
      inthere = True
292
      save_lines.append(rawline)
293
      logger.Debug("Keeping known_hosts '%s'." % (repr(rawline),))
294
      continue
295

    
296
    if havesome and (not haveall or key != pubkey):
297
      removed = True
298
      logger.Debug("Discarding known_hosts '%s'." % (repr(rawline),))
299
      continue
300

    
301
    save_lines.append(rawline)
302

    
303
  if not inthere:
304
    add_lines.append('%s,%s ssh-rsa %s\n' % (fullnode, ip, pubkey))
305
    logger.Debug("Adding known_hosts '%s'." % (repr(add_lines[-1]),))
306

    
307
  if removed:
308
    save_lines = save_lines + add_lines
309

    
310
    # Write a new file and replace old.
311
    fd, tmpname = tempfile.mkstemp('tmp', 'ssh_known_hosts_', '/etc/ssh')
312
    newfile = os.fdopen(fd, 'w')
313
    newfile.write(''.join(save_lines))
314
    newfile.close()
315
    logger.Debug("Wrote new known_hosts.")
316
    os.rename(tmpname, '/etc/ssh/ssh_known_hosts')
317

    
318
  elif add_lines:
319
    # Simply appending a new line will do the trick.
320
    f.seek(0, 2)
321
    for add in add_lines:
322
      f.write(add)
323

    
324
  f.close()
325

    
326

    
327
def _HasValidVG(vglist, vgname):
328
  """Checks if the volume group list is valid.
329

330
  A non-None return value means there's an error, and the return value
331
  is the error message.
332

333
  """
334
  vgsize = vglist.get(vgname, None)
335
  if vgsize is None:
336
    return "volume group '%s' missing" % vgname
337
  elif vgsize < 20480:
338
    return ("volume group '%s' too small (20480MiB required, %dMib found)" %
339
            (vgname, vgsize))
340
  return None
341

    
342

    
343
def _InitSSHSetup(node):
344
  """Setup the SSH configuration for the cluster.
345

346

347
  This generates a dsa keypair for root, adds the pub key to the
348
  permitted hosts and adds the hostkey to its own known hosts.
349

350
  Args:
351
    node: the name of this host as a fqdn
352

353
  """
354
  utils.RemoveFile('/root/.ssh/known_hosts')
355

    
356
  if os.path.exists('/root/.ssh/id_dsa'):
357
    utils.CreateBackup('/root/.ssh/id_dsa')
358
  if os.path.exists('/root/.ssh/id_dsa.pub'):
359
    utils.CreateBackup('/root/.ssh/id_dsa.pub')
360

    
361
  utils.RemoveFile('/root/.ssh/id_dsa')
362
  utils.RemoveFile('/root/.ssh/id_dsa.pub')
363

    
364
  result = utils.RunCmd(["ssh-keygen", "-t", "dsa",
365
                         "-f", "/root/.ssh/id_dsa",
366
                         "-q", "-N", ""])
367
  if result.failed:
368
    raise errors.OpExecError, ("could not generate ssh keypair, error %s" %
369
                               result.output)
370

    
371
  f = open('/root/.ssh/id_dsa.pub', 'r')
372
  try:
373
    utils.AddAuthorizedKey('/root/.ssh/authorized_keys', f.read(8192))
374
  finally:
375
    f.close()
376

    
377

    
378
def _InitGanetiServerSetup(ss):
379
  """Setup the necessary configuration for the initial node daemon.
380

381
  This creates the nodepass file containing the shared password for
382
  the cluster and also generates the SSL certificate.
383

384
  """
385
  # Create pseudo random password
386
  randpass = sha.new(os.urandom(64)).hexdigest()
387
  # and write it into sstore
388
  ss.SetKey(ss.SS_NODED_PASS, randpass)
389

    
390
  result = utils.RunCmd(["openssl", "req", "-new", "-newkey", "rsa:1024",
391
                         "-days", str(365*5), "-nodes", "-x509",
392
                         "-keyout", constants.SSL_CERT_FILE,
393
                         "-out", constants.SSL_CERT_FILE, "-batch"])
394
  if result.failed:
395
    raise errors.OpExecError, ("could not generate server ssl cert, command"
396
                               " %s had exitcode %s and error message %s" %
397
                               (result.cmd, result.exit_code, result.output))
398

    
399
  os.chmod(constants.SSL_CERT_FILE, 0400)
400

    
401
  result = utils.RunCmd([constants.NODE_INITD_SCRIPT, "restart"])
402

    
403
  if result.failed:
404
    raise errors.OpExecError, ("could not start the node daemon, command %s"
405
                               " had exitcode %s and error %s" %
406
                               (result.cmd, result.exit_code, result.output))
407

    
408

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

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

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

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

425
    """
426

    
427
    env = {"CLUSTER": self.op.cluster_name,
428
           "MASTER": self.hostname['hostname_full']}
429
    return env, [], [self.hostname['hostname_full']]
430

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

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

    
438
    hostname_local = socket.gethostname()
439
    self.hostname = hostname = utils.LookupHostname(hostname_local)
440
    if not hostname:
441
      raise errors.OpPrereqError, ("Cannot resolve my own hostname ('%s')" %
442
                                   hostname_local)
443

    
444
    self.clustername = clustername = utils.LookupHostname(self.op.cluster_name)
445
    if not clustername:
446
      raise errors.OpPrereqError, ("Cannot resolve given cluster name ('%s')"
447
                                   % self.op.cluster_name)
448

    
449
    result = utils.RunCmd(["fping", "-S127.0.0.1", "-q", hostname['ip']])
450
    if result.failed:
451
      raise errors.OpPrereqError, ("Inconsistency: this host's name resolves"
452
                                   " to %s,\nbut this ip address does not"
453
                                   " belong to this host."
454
                                   " Aborting." % hostname['ip'])
455

    
456
    secondary_ip = getattr(self.op, "secondary_ip", None)
457
    if secondary_ip and not utils.IsValidIP(secondary_ip):
458
      raise errors.OpPrereqError, ("Invalid secondary ip given")
459
    if secondary_ip and secondary_ip != hostname['ip']:
460
      result = utils.RunCmd(["fping", "-S127.0.0.1", "-q", secondary_ip])
461
      if result.failed:
462
        raise errors.OpPrereqError, ("You gave %s as secondary IP,\n"
463
                                     "but it does not belong to this host." %
464
                                     secondary_ip)
465
    self.secondary_ip = secondary_ip
466

    
467
    # checks presence of the volume group given
468
    vgstatus = _HasValidVG(utils.ListVolumeGroups(), self.op.vg_name)
469

    
470
    if vgstatus:
471
      raise errors.OpPrereqError, ("Error: %s" % vgstatus)
472

    
473
    if not re.match("^[0-9a-z]{2}:[0-9a-z]{2}:[0-9a-z]{2}$",
474
                    self.op.mac_prefix):
475
      raise errors.OpPrereqError, ("Invalid mac prefix given '%s'" %
476
                                   self.op.mac_prefix)
477

    
478
    if self.op.hypervisor_type not in hypervisor.VALID_HTYPES:
479
      raise errors.OpPrereqError, ("Invalid hypervisor type given '%s'" %
480
                                   self.op.hypervisor_type)
481

    
482
    result = utils.RunCmd(["ip", "link", "show", "dev", self.op.master_netdev])
483
    if result.failed:
484
      raise errors.OpPrereqError, ("Invalid master netdev given (%s): '%s'" %
485
                                   (self.op.master_netdev, result.output))
486

    
487
  def Exec(self, feedback_fn):
488
    """Initialize the cluster.
489

490
    """
491
    clustername = self.clustername
492
    hostname = self.hostname
493

    
494
    # set up the simple store
495
    ss = ssconf.SimpleStore()
496
    ss.SetKey(ss.SS_HYPERVISOR, self.op.hypervisor_type)
497
    ss.SetKey(ss.SS_MASTER_NODE, hostname['hostname_full'])
498
    ss.SetKey(ss.SS_MASTER_IP, clustername['ip'])
499
    ss.SetKey(ss.SS_MASTER_NETDEV, self.op.master_netdev)
500

    
501
    # set up the inter-node password and certificate
502
    _InitGanetiServerSetup(ss)
503

    
504
    # start the master ip
505
    rpc.call_node_start_master(hostname['hostname_full'])
506

    
507
    # set up ssh config and /etc/hosts
508
    f = open('/etc/ssh/ssh_host_rsa_key.pub', 'r')
509
    try:
510
      sshline = f.read()
511
    finally:
512
      f.close()
513
    sshkey = sshline.split(" ")[1]
514

    
515
    _UpdateEtcHosts(hostname['hostname_full'],
516
                    hostname['ip'],
517
                    )
518

    
519
    _UpdateKnownHosts(hostname['hostname_full'],
520
                      hostname['ip'],
521
                      sshkey,
522
                      )
523

    
524
    _InitSSHSetup(hostname['hostname'])
525

    
526
    # init of cluster config file
527
    cfgw = config.ConfigWriter()
528
    cfgw.InitConfig(hostname['hostname'], hostname['ip'], self.secondary_ip,
529
                    clustername['hostname'], sshkey, self.op.mac_prefix,
530
                    self.op.vg_name, self.op.def_bridge)
531

    
532

    
533
class LUDestroyCluster(NoHooksLU):
534
  """Logical unit for destroying the cluster.
535

536
  """
537
  _OP_REQP = []
538

    
539
  def CheckPrereq(self):
540
    """Check prerequisites.
541

542
    This checks whether the cluster is empty.
543

544
    Any errors are signalled by raising errors.OpPrereqError.
545

546
    """
547
    master = self.sstore.GetMasterNode()
548

    
549
    nodelist = self.cfg.GetNodeList()
550
    if len(nodelist) > 0 and nodelist != [master]:
551
      raise errors.OpPrereqError, ("There are still %d node(s) in "
552
                                   "this cluster." % (len(nodelist) - 1))
553

    
554
  def Exec(self, feedback_fn):
555
    """Destroys the cluster.
556

557
    """
558
    utils.CreateBackup('/root/.ssh/id_dsa')
559
    utils.CreateBackup('/root/.ssh/id_dsa.pub')
560
    rpc.call_node_leave_cluster(self.sstore.GetMasterNode())
561

    
562

    
563
class LUVerifyCluster(NoHooksLU):
564
  """Verifies the cluster status.
565

566
  """
567
  _OP_REQP = []
568

    
569
  def _VerifyNode(self, node, file_list, local_cksum, vglist, node_result,
570
                  remote_version, feedback_fn):
571
    """Run multiple tests against a node.
572

573
    Test list:
574
      - compares ganeti version
575
      - checks vg existance and size > 20G
576
      - checks config file checksum
577
      - checks ssh to other nodes
578

579
    Args:
580
      node: name of the node to check
581
      file_list: required list of files
582
      local_cksum: dictionary of local files and their checksums
583
    """
584
    # compares ganeti version
585
    local_version = constants.PROTOCOL_VERSION
586
    if not remote_version:
587
      feedback_fn(" - ERROR: connection to %s failed" % (node))
588
      return True
589

    
590
    if local_version != remote_version:
591
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
592
                      (local_version, node, remote_version))
593
      return True
594

    
595
    # checks vg existance and size > 20G
596

    
597
    bad = False
598
    if not vglist:
599
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
600
                      (node,))
601
      bad = True
602
    else:
603
      vgstatus = _HasValidVG(vglist, self.cfg.GetVGName())
604
      if vgstatus:
605
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
606
        bad = True
607

    
608
    # checks config file checksum
609
    # checks ssh to any
610

    
611
    if 'filelist' not in node_result:
612
      bad = True
613
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
614
    else:
615
      remote_cksum = node_result['filelist']
616
      for file_name in file_list:
617
        if file_name not in remote_cksum:
618
          bad = True
619
          feedback_fn("  - ERROR: file '%s' missing" % file_name)
620
        elif remote_cksum[file_name] != local_cksum[file_name]:
621
          bad = True
622
          feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
623

    
624
    if 'nodelist' not in node_result:
625
      bad = True
626
      feedback_fn("  - ERROR: node hasn't returned node connectivity data")
627
    else:
628
      if node_result['nodelist']:
629
        bad = True
630
        for node in node_result['nodelist']:
631
          feedback_fn("  - ERROR: communication with node '%s': %s" %
632
                          (node, node_result['nodelist'][node]))
633
    hyp_result = node_result.get('hypervisor', None)
634
    if hyp_result is not None:
635
      feedback_fn("  - ERROR: hypervisor verify failure: '%s'" % hyp_result)
636
    return bad
637

    
638
  def _VerifyInstance(self, instance, node_vol_is, node_instance, feedback_fn):
639
    """Verify an instance.
640

641
    This function checks to see if the required block devices are
642
    available on the instance's node.
643

644
    """
645
    bad = False
646

    
647
    instancelist = self.cfg.GetInstanceList()
648
    if not instance in instancelist:
649
      feedback_fn("  - ERROR: instance %s not in instance list %s" %
650
                      (instance, instancelist))
651
      bad = True
652

    
653
    instanceconfig = self.cfg.GetInstanceInfo(instance)
654
    node_current = instanceconfig.primary_node
655

    
656
    node_vol_should = {}
657
    instanceconfig.MapLVsByNode(node_vol_should)
658

    
659
    for node in node_vol_should:
660
      for volume in node_vol_should[node]:
661
        if node not in node_vol_is or volume not in node_vol_is[node]:
662
          feedback_fn("  - ERROR: volume %s missing on node %s" %
663
                          (volume, node))
664
          bad = True
665

    
666
    if not instanceconfig.status == 'down':
667
      if not instance in node_instance[node_current]:
668
        feedback_fn("  - ERROR: instance %s not running on node %s" %
669
                        (instance, node_current))
670
        bad = True
671

    
672
    for node in node_instance:
673
      if (not node == node_current):
674
        if instance in node_instance[node]:
675
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
676
                          (instance, node))
677
          bad = True
678

    
679
    return not bad
680

    
681
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
682
    """Verify if there are any unknown volumes in the cluster.
683

684
    The .os, .swap and backup volumes are ignored. All other volumes are
685
    reported as unknown.
686

687
    """
688
    bad = False
689

    
690
    for node in node_vol_is:
691
      for volume in node_vol_is[node]:
692
        if node not in node_vol_should or volume not in node_vol_should[node]:
693
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
694
                      (volume, node))
695
          bad = True
696
    return bad
697

    
698

    
699
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
700
    """Verify the list of running instances.
701

702
    This checks what instances are running but unknown to the cluster.
703

704
    """
705
    bad = False
706
    for node in node_instance:
707
      for runninginstance in node_instance[node]:
708
        if runninginstance not in instancelist:
709
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
710
                          (runninginstance, node))
711
          bad = True
712
    return bad
713

    
714
  def _VerifyNodeConfigFiles(self, ismaster, node, file_list, feedback_fn):
715
    """Verify the list of node config files"""
716

    
717
    bad = False
718
    for file_name in constants.MASTER_CONFIGFILES:
719
      if ismaster and file_name not in file_list:
720
        feedback_fn("  - ERROR: master config file %s missing from master"
721
                    " node %s" % (file_name, node))
722
        bad = True
723
      elif not ismaster and file_name in file_list:
724
        feedback_fn("  - ERROR: master config file %s should not exist"
725
                    " on non-master node %s" % (file_name, node))
726
        bad = True
727

    
728
    for file_name in constants.NODE_CONFIGFILES:
729
      if file_name not in file_list:
730
        feedback_fn("  - ERROR: config file %s missing from node %s" %
731
                    (file_name, node))
732
        bad = True
733

    
734
    return bad
735

    
736
  def CheckPrereq(self):
737
    """Check prerequisites.
738

739
    This has no prerequisites.
740

741
    """
742
    pass
743

    
744
  def Exec(self, feedback_fn):
745
    """Verify integrity of cluster, performing various test on nodes.
746

747
    """
748
    bad = False
749
    feedback_fn("* Verifying global settings")
750
    self.cfg.VerifyConfig()
751

    
752
    master = self.sstore.GetMasterNode()
753
    vg_name = self.cfg.GetVGName()
754
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
755
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
756
    node_volume = {}
757
    node_instance = {}
758

    
759
    # FIXME: verify OS list
760
    # do local checksums
761
    file_names = constants.CLUSTER_CONF_FILES
762
    local_checksums = utils.FingerprintFiles(file_names)
763

    
764
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
765
    all_configfile = rpc.call_configfile_list(nodelist)
766
    all_volumeinfo = rpc.call_volume_list(nodelist, vg_name)
767
    all_instanceinfo = rpc.call_instance_list(nodelist)
768
    all_vglist = rpc.call_vg_list(nodelist)
769
    node_verify_param = {
770
      'filelist': file_names,
771
      'nodelist': nodelist,
772
      'hypervisor': None,
773
      }
774
    all_nvinfo = rpc.call_node_verify(nodelist, node_verify_param)
775
    all_rversion = rpc.call_version(nodelist)
776

    
777
    for node in nodelist:
778
      feedback_fn("* Verifying node %s" % node)
779
      result = self._VerifyNode(node, file_names, local_checksums,
780
                                all_vglist[node], all_nvinfo[node],
781
                                all_rversion[node], feedback_fn)
782
      bad = bad or result
783
      # node_configfile
784
      nodeconfigfile = all_configfile[node]
785

    
786
      if not nodeconfigfile:
787
        feedback_fn("  - ERROR: connection to %s failed" % (node))
788
        bad = True
789
        continue
790

    
791
      bad = bad or self._VerifyNodeConfigFiles(node==master, node,
792
                                               nodeconfigfile, feedback_fn)
793

    
794
      # node_volume
795
      volumeinfo = all_volumeinfo[node]
796

    
797
      if type(volumeinfo) != dict:
798
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
799
        bad = True
800
        continue
801

    
802
      node_volume[node] = volumeinfo
803

    
804
      # node_instance
805
      nodeinstance = all_instanceinfo[node]
806
      if type(nodeinstance) != list:
807
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
808
        bad = True
809
        continue
810

    
811
      node_instance[node] = nodeinstance
812

    
813
    node_vol_should = {}
814

    
815
    for instance in instancelist:
816
      feedback_fn("* Verifying instance %s" % instance)
817
      result =  self._VerifyInstance(instance, node_volume, node_instance,
818
                                     feedback_fn)
819
      bad = bad or result
820

    
821
      inst_config = self.cfg.GetInstanceInfo(instance)
822

    
823
      inst_config.MapLVsByNode(node_vol_should)
824

    
825
    feedback_fn("* Verifying orphan volumes")
826
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
827
                                       feedback_fn)
828
    bad = bad or result
829

    
830
    feedback_fn("* Verifying remaining instances")
831
    result = self._VerifyOrphanInstances(instancelist, node_instance,
832
                                         feedback_fn)
833
    bad = bad or result
834

    
835
    return int(bad)
836

    
837

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

841
  """
842
  if not instance.disks:
843
    return True
844

    
845
  if not oneshot:
846
    logger.ToStdout("Waiting for instance %s to sync disks." % instance.name)
847

    
848
  node = instance.primary_node
849

    
850
  for dev in instance.disks:
851
    cfgw.SetDiskID(dev, node)
852

    
853
  retries = 0
854
  while True:
855
    max_time = 0
856
    done = True
857
    cumul_degraded = False
858
    rstats = rpc.call_blockdev_getmirrorstatus(node, instance.disks)
859
    if not rstats:
860
      logger.ToStderr("Can't get any data from node %s" % node)
861
      retries += 1
862
      if retries >= 10:
863
        raise errors.RemoteError, ("Can't contact node %s for mirror data,"
864
                                   " aborting." % node)
865
      time.sleep(6)
866
      continue
867
    retries = 0
868
    for i in range(len(rstats)):
869
      mstat = rstats[i]
870
      if mstat is None:
871
        logger.ToStderr("Can't compute data for node %s/%s" %
872
                        (node, instance.disks[i].iv_name))
873
        continue
874
      perc_done, est_time, is_degraded = mstat
875
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
876
      if perc_done is not None:
877
        done = False
878
        if est_time is not None:
879
          rem_time = "%d estimated seconds remaining" % est_time
880
          max_time = est_time
881
        else:
882
          rem_time = "no time estimate"
883
        logger.ToStdout("- device %s: %5.2f%% done, %s" %
884
                        (instance.disks[i].iv_name, perc_done, rem_time))
885
    if done or oneshot:
886
      break
887

    
888
    if unlock:
889
      utils.Unlock('cmd')
890
    try:
891
      time.sleep(min(60, max_time))
892
    finally:
893
      if unlock:
894
        utils.Lock('cmd')
895

    
896
  if done:
897
    logger.ToStdout("Instance %s's disks are in sync." % instance.name)
898
  return not cumul_degraded
899

    
900

    
901
def _CheckDiskConsistency(cfgw, dev, node, on_primary):
902
  """Check that mirrors are not degraded.
903

904
  """
905

    
906
  cfgw.SetDiskID(dev, node)
907

    
908
  result = True
909
  if on_primary or dev.AssembleOnSecondary():
910
    rstats = rpc.call_blockdev_find(node, dev)
911
    if not rstats:
912
      logger.ToStderr("Can't get any data from node %s" % node)
913
      result = False
914
    else:
915
      result = result and (not rstats[5])
916
  if dev.children:
917
    for child in dev.children:
918
      result = result and _CheckDiskConsistency(cfgw, child, node, on_primary)
919

    
920
  return result
921

    
922

    
923
class LUDiagnoseOS(NoHooksLU):
924
  """Logical unit for OS diagnose/query.
925

926
  """
927
  _OP_REQP = []
928

    
929
  def CheckPrereq(self):
930
    """Check prerequisites.
931

932
    This always succeeds, since this is a pure query LU.
933

934
    """
935
    return
936

    
937
  def Exec(self, feedback_fn):
938
    """Compute the list of OSes.
939

940
    """
941
    node_list = self.cfg.GetNodeList()
942
    node_data = rpc.call_os_diagnose(node_list)
943
    if node_data == False:
944
      raise errors.OpExecError, "Can't gather the list of OSes"
945
    return node_data
946

    
947

    
948
class LURemoveNode(LogicalUnit):
949
  """Logical unit for removing a node.
950

951
  """
952
  HPATH = "node-remove"
953
  HTYPE = constants.HTYPE_NODE
954
  _OP_REQP = ["node_name"]
955

    
956
  def BuildHooksEnv(self):
957
    """Build hooks env.
958

959
    This doesn't run on the target node in the pre phase as a failed
960
    node would not allows itself to run.
961

962
    """
963
    all_nodes = self.cfg.GetNodeList()
964
    all_nodes.remove(self.op.node_name)
965
    return {"NODE_NAME": self.op.node_name}, all_nodes, all_nodes
966

    
967
  def CheckPrereq(self):
968
    """Check prerequisites.
969

970
    This checks:
971
     - the node exists in the configuration
972
     - it does not have primary or secondary instances
973
     - it's not the master
974

975
    Any errors are signalled by raising errors.OpPrereqError.
976

977
    """
978

    
979
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
980
    if node is None:
981
      logger.Error("Error: Node '%s' is unknown." % self.op.node_name)
982
      return 1
983

    
984
    instance_list = self.cfg.GetInstanceList()
985

    
986
    masternode = self.sstore.GetMasterNode()
987
    if node.name == masternode:
988
      raise errors.OpPrereqError, ("Node is the master node,"
989
                                   " you need to failover first.")
990

    
991
    for instance_name in instance_list:
992
      instance = self.cfg.GetInstanceInfo(instance_name)
993
      if node.name == instance.primary_node:
994
        raise errors.OpPrereqError, ("Instance %s still running on the node,"
995
                                     " please remove first." % instance_name)
996
      if node.name in instance.secondary_nodes:
997
        raise errors.OpPrereqError, ("Instance %s has node as a secondary,"
998
                                     " please remove first." % instance_name)
999
    self.op.node_name = node.name
1000
    self.node = node
1001

    
1002
  def Exec(self, feedback_fn):
1003
    """Removes the node from the cluster.
1004

1005
    """
1006
    node = self.node
1007
    logger.Info("stopping the node daemon and removing configs from node %s" %
1008
                node.name)
1009

    
1010
    rpc.call_node_leave_cluster(node.name)
1011

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

    
1014
    logger.Info("Removing node %s from config" % node.name)
1015

    
1016
    self.cfg.RemoveNode(node.name)
1017

    
1018

    
1019
class LUQueryNodes(NoHooksLU):
1020
  """Logical unit for querying nodes.
1021

1022
  """
1023
  _OP_REQP = ["output_fields"]
1024

    
1025
  def CheckPrereq(self):
1026
    """Check prerequisites.
1027

1028
    This checks that the fields required are valid output fields.
1029

1030
    """
1031
    self.static_fields = frozenset(["name", "pinst", "sinst", "pip", "sip"])
1032
    self.dynamic_fields = frozenset(["dtotal", "dfree",
1033
                                     "mtotal", "mnode", "mfree"])
1034
    self.all_fields = self.static_fields | self.dynamic_fields
1035

    
1036
    if not self.all_fields.issuperset(self.op.output_fields):
1037
      raise errors.OpPrereqError, ("Unknown output fields selected: %s"
1038
                                   % ",".join(frozenset(self.op.output_fields).
1039
                                              difference(self.all_fields)))
1040

    
1041

    
1042
  def Exec(self, feedback_fn):
1043
    """Computes the list of nodes and their attributes.
1044

1045
    """
1046
    nodenames = utils.NiceSort(self.cfg.GetNodeList())
1047
    nodelist = [self.cfg.GetNodeInfo(name) for name in nodenames]
1048

    
1049

    
1050
    # begin data gathering
1051

    
1052
    if self.dynamic_fields.intersection(self.op.output_fields):
1053
      live_data = {}
1054
      node_data = rpc.call_node_info(nodenames, self.cfg.GetVGName())
1055
      for name in nodenames:
1056
        nodeinfo = node_data.get(name, None)
1057
        if nodeinfo:
1058
          live_data[name] = {
1059
            "mtotal": utils.TryConvert(int, nodeinfo['memory_total']),
1060
            "mnode": utils.TryConvert(int, nodeinfo['memory_dom0']),
1061
            "mfree": utils.TryConvert(int, nodeinfo['memory_free']),
1062
            "dtotal": utils.TryConvert(int, nodeinfo['vg_size']),
1063
            "dfree": utils.TryConvert(int, nodeinfo['vg_free']),
1064
            }
1065
        else:
1066
          live_data[name] = {}
1067
    else:
1068
      live_data = dict.fromkeys(nodenames, {})
1069

    
1070
    node_to_primary = dict.fromkeys(nodenames, 0)
1071
    node_to_secondary = dict.fromkeys(nodenames, 0)
1072

    
1073
    if "pinst" in self.op.output_fields or "sinst" in self.op.output_fields:
1074
      instancelist = self.cfg.GetInstanceList()
1075

    
1076
      for instance in instancelist:
1077
        instanceinfo = self.cfg.GetInstanceInfo(instance)
1078
        node_to_primary[instanceinfo.primary_node] += 1
1079
        for secnode in instanceinfo.secondary_nodes:
1080
          node_to_secondary[secnode] += 1
1081

    
1082
    # end data gathering
1083

    
1084
    output = []
1085
    for node in nodelist:
1086
      node_output = []
1087
      for field in self.op.output_fields:
1088
        if field == "name":
1089
          val = node.name
1090
        elif field == "pinst":
1091
          val = node_to_primary[node.name]
1092
        elif field == "sinst":
1093
          val = node_to_secondary[node.name]
1094
        elif field == "pip":
1095
          val = node.primary_ip
1096
        elif field == "sip":
1097
          val = node.secondary_ip
1098
        elif field in self.dynamic_fields:
1099
          val = live_data[node.name].get(field, "?")
1100
        else:
1101
          raise errors.ParameterError, field
1102
        val = str(val)
1103
        node_output.append(val)
1104
      output.append(node_output)
1105

    
1106
    return output
1107

    
1108

    
1109
def _CheckNodesDirs(node_list, paths):
1110
  """Verify if the given nodes have the same files.
1111

1112
  Args:
1113
    node_list: the list of node names to check
1114
    paths: the list of directories to checksum and compare
1115

1116
  Returns:
1117
    list of (node, different_file, message); if empty, the files are in sync
1118

1119
  """
1120
  file_names = []
1121
  for dir_name in paths:
1122
    flist = [os.path.join(dir_name, name) for name in os.listdir(dir_name)]
1123
    flist = [name for name in flist if os.path.isfile(name)]
1124
    file_names.extend(flist)
1125

    
1126
  local_checksums = utils.FingerprintFiles(file_names)
1127

    
1128
  results = []
1129
  verify_params = {'filelist': file_names}
1130
  all_node_results = rpc.call_node_verify(node_list, verify_params)
1131
  for node_name in node_list:
1132
    node_result = all_node_results.get(node_name, False)
1133
    if not node_result or 'filelist' not in node_result:
1134
      results.append((node_name, "'all files'", "node communication error"))
1135
      continue
1136
    remote_checksums = node_result['filelist']
1137
    for fname in local_checksums:
1138
      if fname not in remote_checksums:
1139
        results.append((node_name, fname, "missing file"))
1140
      elif remote_checksums[fname] != local_checksums[fname]:
1141
        results.append((node_name, fname, "wrong checksum"))
1142
  return results
1143

    
1144

    
1145
class LUAddNode(LogicalUnit):
1146
  """Logical unit for adding node to the cluster.
1147

1148
  """
1149
  HPATH = "node-add"
1150
  HTYPE = constants.HTYPE_NODE
1151
  _OP_REQP = ["node_name"]
1152

    
1153
  def BuildHooksEnv(self):
1154
    """Build hooks env.
1155

1156
    This will run on all nodes before, and on all nodes + the new node after.
1157

1158
    """
1159
    env = {
1160
      "NODE_NAME": self.op.node_name,
1161
      "NODE_PIP": self.op.primary_ip,
1162
      "NODE_SIP": self.op.secondary_ip,
1163
      }
1164
    nodes_0 = self.cfg.GetNodeList()
1165
    nodes_1 = nodes_0 + [self.op.node_name, ]
1166
    return env, nodes_0, nodes_1
1167

    
1168
  def CheckPrereq(self):
1169
    """Check prerequisites.
1170

1171
    This checks:
1172
     - the new node is not already in the config
1173
     - it is resolvable
1174
     - its parameters (single/dual homed) matches the cluster
1175

1176
    Any errors are signalled by raising errors.OpPrereqError.
1177

1178
    """
1179
    node_name = self.op.node_name
1180
    cfg = self.cfg
1181

    
1182
    dns_data = utils.LookupHostname(node_name)
1183
    if not dns_data:
1184
      raise errors.OpPrereqError, ("Node %s is not resolvable" % node_name)
1185

    
1186
    node = dns_data['hostname']
1187
    primary_ip = self.op.primary_ip = dns_data['ip']
1188
    secondary_ip = getattr(self.op, "secondary_ip", None)
1189
    if secondary_ip is None:
1190
      secondary_ip = primary_ip
1191
    if not utils.IsValidIP(secondary_ip):
1192
      raise errors.OpPrereqError, ("Invalid secondary IP given")
1193
    self.op.secondary_ip = secondary_ip
1194
    node_list = cfg.GetNodeList()
1195
    if node in node_list:
1196
      raise errors.OpPrereqError, ("Node %s is already in the configuration"
1197
                                   % node)
1198

    
1199
    for existing_node_name in node_list:
1200
      existing_node = cfg.GetNodeInfo(existing_node_name)
1201
      if (existing_node.primary_ip == primary_ip or
1202
          existing_node.secondary_ip == primary_ip or
1203
          existing_node.primary_ip == secondary_ip or
1204
          existing_node.secondary_ip == secondary_ip):
1205
        raise errors.OpPrereqError, ("New node ip address(es) conflict with"
1206
                                     " existing node %s" % existing_node.name)
1207

    
1208
    # check that the type of the node (single versus dual homed) is the
1209
    # same as for the master
1210
    myself = cfg.GetNodeInfo(self.sstore.GetMasterNode())
1211
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1212
    newbie_singlehomed = secondary_ip == primary_ip
1213
    if master_singlehomed != newbie_singlehomed:
1214
      if master_singlehomed:
1215
        raise errors.OpPrereqError, ("The master has no private ip but the"
1216
                                     " new node has one")
1217
      else:
1218
        raise errors.OpPrereqError ("The master has a private ip but the"
1219
                                    " new node doesn't have one")
1220

    
1221
    # checks reachablity
1222
    command = ["fping", "-q", primary_ip]
1223
    result = utils.RunCmd(command)
1224
    if result.failed:
1225
      raise errors.OpPrereqError, ("Node not reachable by ping")
1226

    
1227
    if not newbie_singlehomed:
1228
      # check reachability from my secondary ip to newbie's secondary ip
1229
      command = ["fping", "-S%s" % myself.secondary_ip, "-q", secondary_ip]
1230
      result = utils.RunCmd(command)
1231
      if result.failed:
1232
        raise errors.OpPrereqError, ("Node secondary ip not reachable by ping")
1233

    
1234
    self.new_node = objects.Node(name=node,
1235
                                 primary_ip=primary_ip,
1236
                                 secondary_ip=secondary_ip)
1237

    
1238
  def Exec(self, feedback_fn):
1239
    """Adds the new node to the cluster.
1240

1241
    """
1242
    new_node = self.new_node
1243
    node = new_node.name
1244

    
1245
    # set up inter-node password and certificate and restarts the node daemon
1246
    gntpass = self.sstore.GetNodeDaemonPassword()
1247
    if not re.match('^[a-zA-Z0-9.]{1,64}$', gntpass):
1248
      raise errors.OpExecError, ("ganeti password corruption detected")
1249
    f = open(constants.SSL_CERT_FILE)
1250
    try:
1251
      gntpem = f.read(8192)
1252
    finally:
1253
      f.close()
1254
    # in the base64 pem encoding, neither '!' nor '.' are valid chars,
1255
    # so we use this to detect an invalid certificate; as long as the
1256
    # cert doesn't contain this, the here-document will be correctly
1257
    # parsed by the shell sequence below
1258
    if re.search('^!EOF\.', gntpem, re.MULTILINE):
1259
      raise errors.OpExecError, ("invalid PEM encoding in the SSL certificate")
1260
    if not gntpem.endswith("\n"):
1261
      raise errors.OpExecError, ("PEM must end with newline")
1262
    logger.Info("copy cluster pass to %s and starting the node daemon" % node)
1263

    
1264
    # remove first the root's known_hosts file
1265
    utils.RemoveFile("/root/.ssh/known_hosts")
1266
    # and then connect with ssh to set password and start ganeti-noded
1267
    # note that all the below variables are sanitized at this point,
1268
    # either by being constants or by the checks above
1269
    ss = self.sstore
1270
    mycommand = ("umask 077 && "
1271
                 "echo '%s' > '%s' && "
1272
                 "cat > '%s' << '!EOF.' && \n"
1273
                 "%s!EOF.\n%s restart" %
1274
                 (gntpass, ss.KeyToFilename(ss.SS_NODED_PASS),
1275
                  constants.SSL_CERT_FILE, gntpem,
1276
                  constants.NODE_INITD_SCRIPT))
1277

    
1278
    result = ssh.SSHCall(node, 'root', mycommand, batch=False, ask_key=True)
1279
    if result.failed:
1280
      raise errors.OpExecError, ("Remote command on node %s, error: %s,"
1281
                                 " output: %s" %
1282
                                 (node, result.fail_reason, result.output))
1283

    
1284
    # check connectivity
1285
    time.sleep(4)
1286

    
1287
    result = rpc.call_version([node])[node]
1288
    if result:
1289
      if constants.PROTOCOL_VERSION == result:
1290
        logger.Info("communication to node %s fine, sw version %s match" %
1291
                    (node, result))
1292
      else:
1293
        raise errors.OpExecError, ("Version mismatch master version %s,"
1294
                                   " node version %s" %
1295
                                   (constants.PROTOCOL_VERSION, result))
1296
    else:
1297
      raise errors.OpExecError, ("Cannot get version from the new node")
1298

    
1299
    # setup ssh on node
1300
    logger.Info("copy ssh key to node %s" % node)
1301
    keyarray = []
1302
    keyfiles = ["/etc/ssh/ssh_host_dsa_key", "/etc/ssh/ssh_host_dsa_key.pub",
1303
                "/etc/ssh/ssh_host_rsa_key", "/etc/ssh/ssh_host_rsa_key.pub",
1304
                "/root/.ssh/id_dsa", "/root/.ssh/id_dsa.pub"]
1305

    
1306
    for i in keyfiles:
1307
      f = open(i, 'r')
1308
      try:
1309
        keyarray.append(f.read())
1310
      finally:
1311
        f.close()
1312

    
1313
    result = rpc.call_node_add(node, keyarray[0], keyarray[1], keyarray[2],
1314
                               keyarray[3], keyarray[4], keyarray[5])
1315

    
1316
    if not result:
1317
      raise errors.OpExecError, ("Cannot transfer ssh keys to the new node")
1318

    
1319
    # Add node to our /etc/hosts, and add key to known_hosts
1320
    _UpdateEtcHosts(new_node.name, new_node.primary_ip)
1321
    _UpdateKnownHosts(new_node.name, new_node.primary_ip,
1322
                      self.cfg.GetHostKey())
1323

    
1324
    if new_node.secondary_ip != new_node.primary_ip:
1325
      result = ssh.SSHCall(node, "root",
1326
                           "fping -S 127.0.0.1 -q %s" % new_node.secondary_ip)
1327
      if result.failed:
1328
        raise errors.OpExecError, ("Node claims it doesn't have the"
1329
                                   " secondary ip you gave (%s).\n"
1330
                                   "Please fix and re-run this command." %
1331
                                   new_node.secondary_ip)
1332

    
1333
    # Distribute updated /etc/hosts and known_hosts to all nodes,
1334
    # including the node just added
1335
    myself = self.cfg.GetNodeInfo(self.sstore.GetMasterNode())
1336
    dist_nodes = self.cfg.GetNodeList() + [node]
1337
    if myself.name in dist_nodes:
1338
      dist_nodes.remove(myself.name)
1339

    
1340
    logger.Debug("Copying hosts and known_hosts to all nodes")
1341
    for fname in ("/etc/hosts", "/etc/ssh/ssh_known_hosts"):
1342
      result = rpc.call_upload_file(dist_nodes, fname)
1343
      for to_node in dist_nodes:
1344
        if not result[to_node]:
1345
          logger.Error("copy of file %s to node %s failed" %
1346
                       (fname, to_node))
1347

    
1348
    to_copy = [constants.MASTER_CRON_FILE]
1349
    to_copy.extend(ss.GetFileList())
1350
    for fname in to_copy:
1351
      if not ssh.CopyFileToNode(node, fname):
1352
        logger.Error("could not copy file %s to node %s" % (fname, node))
1353

    
1354
    logger.Info("adding node %s to cluster.conf" % node)
1355
    self.cfg.AddNode(new_node)
1356

    
1357

    
1358
class LUMasterFailover(LogicalUnit):
1359
  """Failover the master node to the current node.
1360

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

1363
  """
1364
  HPATH = "master-failover"
1365
  HTYPE = constants.HTYPE_CLUSTER
1366
  REQ_MASTER = False
1367
  _OP_REQP = []
1368

    
1369
  def BuildHooksEnv(self):
1370
    """Build hooks env.
1371

1372
    This will run on the new master only in the pre phase, and on all
1373
    the nodes in the post phase.
1374

1375
    """
1376
    env = {
1377
      "NEW_MASTER": self.new_master,
1378
      "OLD_MASTER": self.old_master,
1379
      }
1380
    return env, [self.new_master], self.cfg.GetNodeList()
1381

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

1385
    This checks that we are not already the master.
1386

1387
    """
1388
    self.new_master = socket.gethostname()
1389

    
1390
    self.old_master = self.sstore.GetMasterNode()
1391

    
1392
    if self.old_master == self.new_master:
1393
      raise errors.OpPrereqError, ("This commands must be run on the node"
1394
                                   " where you want the new master to be.\n"
1395
                                   "%s is already the master" %
1396
                                   self.old_master)
1397

    
1398
  def Exec(self, feedback_fn):
1399
    """Failover the master node.
1400

1401
    This command, when run on a non-master node, will cause the current
1402
    master to cease being master, and the non-master to become new
1403
    master.
1404

1405
    """
1406

    
1407
    #TODO: do not rely on gethostname returning the FQDN
1408
    logger.Info("setting master to %s, old master: %s" %
1409
                (self.new_master, self.old_master))
1410

    
1411
    if not rpc.call_node_stop_master(self.old_master):
1412
      logger.Error("could disable the master role on the old master"
1413
                   " %s, please disable manually" % self.old_master)
1414

    
1415
    ss = self.sstore
1416
    ss.SetKey(ss.SS_MASTER_NODE, self.new_master)
1417
    if not rpc.call_upload_file(self.cfg.GetNodeList(),
1418
                                ss.KeyToFilename(ss.SS_MASTER_NODE)):
1419
      logger.Error("could not distribute the new simple store master file"
1420
                   " to the other nodes, please check.")
1421

    
1422
    if not rpc.call_node_start_master(self.new_master):
1423
      logger.Error("could not start the master role on the new master"
1424
                   " %s, please check" % self.new_master)
1425
      feedback_fn("Error in activating the master IP on the new master,\n"
1426
                  "please fix manually.")
1427

    
1428

    
1429

    
1430
class LUQueryClusterInfo(NoHooksLU):
1431
  """Query cluster configuration.
1432

1433
  """
1434
  _OP_REQP = []
1435

    
1436
  def CheckPrereq(self):
1437
    """No prerequsites needed for this LU.
1438

1439
    """
1440
    pass
1441

    
1442
  def Exec(self, feedback_fn):
1443
    """Return cluster config.
1444

1445
    """
1446
    instances = [self.cfg.GetInstanceInfo(name)
1447
                 for name in self.cfg.GetInstanceList()]
1448
    result = {
1449
      "name": self.cfg.GetClusterName(),
1450
      "software_version": constants.RELEASE_VERSION,
1451
      "protocol_version": constants.PROTOCOL_VERSION,
1452
      "config_version": constants.CONFIG_VERSION,
1453
      "os_api_version": constants.OS_API_VERSION,
1454
      "export_version": constants.EXPORT_VERSION,
1455
      "master": self.sstore.GetMasterNode(),
1456
      "architecture": (platform.architecture()[0], platform.machine()),
1457
      "instances": [(instance.name, instance.primary_node)
1458
                    for instance in instances],
1459
      "nodes": self.cfg.GetNodeList(),
1460
      }
1461

    
1462
    return result
1463

    
1464

    
1465
class LUClusterCopyFile(NoHooksLU):
1466
  """Copy file to cluster.
1467

1468
  """
1469
  _OP_REQP = ["nodes", "filename"]
1470

    
1471
  def CheckPrereq(self):
1472
    """Check prerequisites.
1473

1474
    It should check that the named file exists and that the given list
1475
    of nodes is valid.
1476

1477
    """
1478
    if not os.path.exists(self.op.filename):
1479
      raise errors.OpPrereqError("No such filename '%s'" % self.op.filename)
1480
    if self.op.nodes:
1481
      nodes = self.op.nodes
1482
    else:
1483
      nodes = self.cfg.GetNodeList()
1484
    self.nodes = []
1485
    for node in nodes:
1486
      nname = self.cfg.ExpandNodeName(node)
1487
      if nname is None:
1488
        raise errors.OpPrereqError, ("Node '%s' is unknown." % node)
1489
      self.nodes.append(nname)
1490

    
1491
  def Exec(self, feedback_fn):
1492
    """Copy a file from master to some nodes.
1493

1494
    Args:
1495
      opts - class with options as members
1496
      args - list containing a single element, the file name
1497
    Opts used:
1498
      nodes - list containing the name of target nodes; if empty, all nodes
1499

1500
    """
1501
    filename = self.op.filename
1502

    
1503
    myname = socket.gethostname()
1504

    
1505
    for node in self.nodes:
1506
      if node == myname:
1507
        continue
1508
      if not ssh.CopyFileToNode(node, filename):
1509
        logger.Error("Copy of file %s to node %s failed" % (filename, node))
1510

    
1511

    
1512
class LUDumpClusterConfig(NoHooksLU):
1513
  """Return a text-representation of the cluster-config.
1514

1515
  """
1516
  _OP_REQP = []
1517

    
1518
  def CheckPrereq(self):
1519
    """No prerequisites.
1520

1521
    """
1522
    pass
1523

    
1524
  def Exec(self, feedback_fn):
1525
    """Dump a representation of the cluster config to the standard output.
1526

1527
    """
1528
    return self.cfg.DumpConfig()
1529

    
1530

    
1531
class LURunClusterCommand(NoHooksLU):
1532
  """Run a command on some nodes.
1533

1534
  """
1535
  _OP_REQP = ["command", "nodes"]
1536

    
1537
  def CheckPrereq(self):
1538
    """Check prerequisites.
1539

1540
    It checks that the given list of nodes is valid.
1541

1542
    """
1543
    if self.op.nodes:
1544
      nodes = self.op.nodes
1545
    else:
1546
      nodes = self.cfg.GetNodeList()
1547
    self.nodes = []
1548
    for node in nodes:
1549
      nname = self.cfg.ExpandNodeName(node)
1550
      if nname is None:
1551
        raise errors.OpPrereqError, ("Node '%s' is unknown." % node)
1552
      self.nodes.append(nname)
1553

    
1554
  def Exec(self, feedback_fn):
1555
    """Run a command on some nodes.
1556

1557
    """
1558
    data = []
1559
    for node in self.nodes:
1560
      result = utils.RunCmd(["ssh", node, self.op.command])
1561
      data.append((node, result.cmd, result.output, result.exit_code))
1562

    
1563
    return data
1564

    
1565

    
1566
class LUActivateInstanceDisks(NoHooksLU):
1567
  """Bring up an instance's disks.
1568

1569
  """
1570
  _OP_REQP = ["instance_name"]
1571

    
1572
  def CheckPrereq(self):
1573
    """Check prerequisites.
1574

1575
    This checks that the instance is in the cluster.
1576

1577
    """
1578
    instance = self.cfg.GetInstanceInfo(
1579
      self.cfg.ExpandInstanceName(self.op.instance_name))
1580
    if instance is None:
1581
      raise errors.OpPrereqError, ("Instance '%s' not known" %
1582
                                   self.op.instance_name)
1583
    self.instance = instance
1584

    
1585

    
1586
  def Exec(self, feedback_fn):
1587
    """Activate the disks.
1588

1589
    """
1590
    disks_ok, disks_info = _AssembleInstanceDisks(self.instance, self.cfg)
1591
    if not disks_ok:
1592
      raise errors.OpExecError, ("Cannot activate block devices")
1593

    
1594
    return disks_info
1595

    
1596

    
1597
def _AssembleInstanceDisks(instance, cfg, ignore_secondaries=False):
1598
  """Prepare the block devices for an instance.
1599

1600
  This sets up the block devices on all nodes.
1601

1602
  Args:
1603
    instance: a ganeti.objects.Instance object
1604
    ignore_secondaries: if true, errors on secondary nodes won't result
1605
                        in an error return from the function
1606

1607
  Returns:
1608
    false if the operation failed
1609
    list of (host, instance_visible_name, node_visible_name) if the operation
1610
         suceeded with the mapping from node devices to instance devices
1611
  """
1612
  device_info = []
1613
  disks_ok = True
1614
  for inst_disk in instance.disks:
1615
    master_result = None
1616
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1617
      cfg.SetDiskID(node_disk, node)
1618
      is_primary = node == instance.primary_node
1619
      result = rpc.call_blockdev_assemble(node, node_disk, is_primary)
1620
      if not result:
1621
        logger.Error("could not prepare block device %s on node %s (is_pri"
1622
                     "mary=%s)" % (inst_disk.iv_name, node, is_primary))
1623
        if is_primary or not ignore_secondaries:
1624
          disks_ok = False
1625
      if is_primary:
1626
        master_result = result
1627
    device_info.append((instance.primary_node, inst_disk.iv_name,
1628
                        master_result))
1629

    
1630
  return disks_ok, device_info
1631

    
1632

    
1633
class LUDeactivateInstanceDisks(NoHooksLU):
1634
  """Shutdown an instance's disks.
1635

1636
  """
1637
  _OP_REQP = ["instance_name"]
1638

    
1639
  def CheckPrereq(self):
1640
    """Check prerequisites.
1641

1642
    This checks that the instance is in the cluster.
1643

1644
    """
1645
    instance = self.cfg.GetInstanceInfo(
1646
      self.cfg.ExpandInstanceName(self.op.instance_name))
1647
    if instance is None:
1648
      raise errors.OpPrereqError, ("Instance '%s' not known" %
1649
                                   self.op.instance_name)
1650
    self.instance = instance
1651

    
1652
  def Exec(self, feedback_fn):
1653
    """Deactivate the disks
1654

1655
    """
1656
    instance = self.instance
1657
    ins_l = rpc.call_instance_list([instance.primary_node])
1658
    ins_l = ins_l[instance.primary_node]
1659
    if not type(ins_l) is list:
1660
      raise errors.OpExecError, ("Can't contact node '%s'" %
1661
                                 instance.primary_node)
1662

    
1663
    if self.instance.name in ins_l:
1664
      raise errors.OpExecError, ("Instance is running, can't shutdown"
1665
                                 " block devices.")
1666

    
1667
    _ShutdownInstanceDisks(instance, self.cfg)
1668

    
1669

    
1670
def _ShutdownInstanceDisks(instance, cfg, ignore_primary=False):
1671
  """Shutdown block devices of an instance.
1672

1673
  This does the shutdown on all nodes of the instance.
1674

1675
  If the ignore_primary is false, errors on the primary node are
1676
  ignored.
1677

1678
  """
1679
  result = True
1680
  for disk in instance.disks:
1681
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
1682
      cfg.SetDiskID(top_disk, node)
1683
      if not rpc.call_blockdev_shutdown(node, top_disk):
1684
        logger.Error("could not shutdown block device %s on node %s" %
1685
                     (disk.iv_name, node))
1686
        if not ignore_primary or node != instance.primary_node:
1687
          result = False
1688
  return result
1689

    
1690

    
1691
class LUStartupInstance(LogicalUnit):
1692
  """Starts an instance.
1693

1694
  """
1695
  HPATH = "instance-start"
1696
  HTYPE = constants.HTYPE_INSTANCE
1697
  _OP_REQP = ["instance_name", "force"]
1698

    
1699
  def BuildHooksEnv(self):
1700
    """Build hooks env.
1701

1702
    This runs on master, primary and secondary nodes of the instance.
1703

1704
    """
1705
    env = {
1706
      "INSTANCE_NAME": self.op.instance_name,
1707
      "INSTANCE_PRIMARY": self.instance.primary_node,
1708
      "INSTANCE_SECONDARIES": " ".join(self.instance.secondary_nodes),
1709
      "FORCE": self.op.force,
1710
      }
1711
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
1712
          list(self.instance.secondary_nodes))
1713
    return env, nl, nl
1714

    
1715
  def CheckPrereq(self):
1716
    """Check prerequisites.
1717

1718
    This checks that the instance is in the cluster.
1719

1720
    """
1721
    instance = self.cfg.GetInstanceInfo(
1722
      self.cfg.ExpandInstanceName(self.op.instance_name))
1723
    if instance is None:
1724
      raise errors.OpPrereqError, ("Instance '%s' not known" %
1725
                                   self.op.instance_name)
1726

    
1727
    # check bridges existance
1728
    brlist = [nic.bridge for nic in instance.nics]
1729
    if not rpc.call_bridges_exist(instance.primary_node, brlist):
1730
      raise errors.OpPrereqError, ("one or more target bridges %s does not"
1731
                                   " exist on destination node '%s'" %
1732
                                   (brlist, instance.primary_node))
1733

    
1734
    self.instance = instance
1735
    self.op.instance_name = instance.name
1736

    
1737
  def Exec(self, feedback_fn):
1738
    """Start the instance.
1739

1740
    """
1741
    instance = self.instance
1742
    force = self.op.force
1743
    extra_args = getattr(self.op, "extra_args", "")
1744

    
1745
    node_current = instance.primary_node
1746

    
1747
    nodeinfo = rpc.call_node_info([node_current], self.cfg.GetVGName())
1748
    if not nodeinfo:
1749
      raise errors.OpExecError, ("Could not contact node %s for infos" %
1750
                                 (node_current))
1751

    
1752
    freememory = nodeinfo[node_current]['memory_free']
1753
    memory = instance.memory
1754
    if memory > freememory:
1755
      raise errors.OpExecError, ("Not enough memory to start instance"
1756
                                 " %s on node %s"
1757
                                 " needed %s MiB, available %s MiB" %
1758
                                 (instance.name, node_current, memory,
1759
                                  freememory))
1760

    
1761
    disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
1762
                                             ignore_secondaries=force)
1763
    if not disks_ok:
1764
      _ShutdownInstanceDisks(instance, self.cfg)
1765
      if not force:
1766
        logger.Error("If the message above refers to a secondary node,"
1767
                     " you can retry the operation using '--force'.")
1768
      raise errors.OpExecError, ("Disk consistency error")
1769

    
1770
    if not rpc.call_instance_start(node_current, instance, extra_args):
1771
      _ShutdownInstanceDisks(instance, self.cfg)
1772
      raise errors.OpExecError, ("Could not start instance")
1773

    
1774
    self.cfg.MarkInstanceUp(instance.name)
1775

    
1776

    
1777
class LUShutdownInstance(LogicalUnit):
1778
  """Shutdown an instance.
1779

1780
  """
1781
  HPATH = "instance-stop"
1782
  HTYPE = constants.HTYPE_INSTANCE
1783
  _OP_REQP = ["instance_name"]
1784

    
1785
  def BuildHooksEnv(self):
1786
    """Build hooks env.
1787

1788
    This runs on master, primary and secondary nodes of the instance.
1789

1790
    """
1791
    env = {
1792
      "INSTANCE_NAME": self.op.instance_name,
1793
      "INSTANCE_PRIMARY": self.instance.primary_node,
1794
      "INSTANCE_SECONDARIES": " ".join(self.instance.secondary_nodes),
1795
      }
1796
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
1797
          list(self.instance.secondary_nodes))
1798
    return env, nl, nl
1799

    
1800
  def CheckPrereq(self):
1801
    """Check prerequisites.
1802

1803
    This checks that the instance is in the cluster.
1804

1805
    """
1806
    instance = self.cfg.GetInstanceInfo(
1807
      self.cfg.ExpandInstanceName(self.op.instance_name))
1808
    if instance is None:
1809
      raise errors.OpPrereqError, ("Instance '%s' not known" %
1810
                                   self.op.instance_name)
1811
    self.instance = instance
1812

    
1813
  def Exec(self, feedback_fn):
1814
    """Shutdown the instance.
1815

1816
    """
1817
    instance = self.instance
1818
    node_current = instance.primary_node
1819
    if not rpc.call_instance_shutdown(node_current, instance):
1820
      logger.Error("could not shutdown instance")
1821

    
1822
    self.cfg.MarkInstanceDown(instance.name)
1823
    _ShutdownInstanceDisks(instance, self.cfg)
1824

    
1825

    
1826
class LURemoveInstance(LogicalUnit):
1827
  """Remove an instance.
1828

1829
  """
1830
  HPATH = "instance-remove"
1831
  HTYPE = constants.HTYPE_INSTANCE
1832
  _OP_REQP = ["instance_name"]
1833

    
1834
  def BuildHooksEnv(self):
1835
    """Build hooks env.
1836

1837
    This runs on master, primary and secondary nodes of the instance.
1838

1839
    """
1840
    env = {
1841
      "INSTANCE_NAME": self.op.instance_name,
1842
      "INSTANCE_PRIMARY": self.instance.primary_node,
1843
      "INSTANCE_SECONDARIES": " ".join(self.instance.secondary_nodes),
1844
      }
1845
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
1846
          list(self.instance.secondary_nodes))
1847
    return env, nl, nl
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
    """Remove the instance.
1864

1865
    """
1866
    instance = self.instance
1867
    logger.Info("shutting down instance %s on node %s" %
1868
                (instance.name, instance.primary_node))
1869

    
1870
    if not rpc.call_instance_shutdown(instance.primary_node, instance):
1871
      raise errors.OpExecError, ("Could not shutdown instance %s on node %s" %
1872
                                 (instance.name, instance.primary_node))
1873

    
1874
    logger.Info("removing block devices for instance %s" % instance.name)
1875

    
1876
    _RemoveDisks(instance, self.cfg)
1877

    
1878
    logger.Info("removing instance %s out of cluster config" % instance.name)
1879

    
1880
    self.cfg.RemoveInstance(instance.name)
1881

    
1882

    
1883
class LUQueryInstances(NoHooksLU):
1884
  """Logical unit for querying instances.
1885

1886
  """
1887
  OP_REQP = ["output_fields"]
1888

    
1889
  def CheckPrereq(self):
1890
    """Check prerequisites.
1891

1892
    This checks that the fields required are valid output fields.
1893

1894
    """
1895

    
1896
    self.static_fields = frozenset(["name", "os", "pnode", "snodes",
1897
                                    "admin_state", "admin_ram",
1898
                                    "disk_template", "ip", "mac", "bridge"])
1899
    self.dynamic_fields = frozenset(["oper_state", "oper_ram"])
1900
    self.all_fields = self.static_fields | self.dynamic_fields
1901

    
1902
    if not self.all_fields.issuperset(self.op.output_fields):
1903
      raise errors.OpPrereqError, ("Unknown output fields selected: %s"
1904
                                   % ",".join(frozenset(self.op.output_fields).
1905
                                              difference(self.all_fields)))
1906

    
1907
  def Exec(self, feedback_fn):
1908
    """Computes the list of nodes and their attributes.
1909

1910
    """
1911

    
1912
    instance_names = utils.NiceSort(self.cfg.GetInstanceList())
1913
    instance_list = [self.cfg.GetInstanceInfo(iname) for iname
1914
                     in instance_names]
1915

    
1916
    # begin data gathering
1917

    
1918
    nodes = frozenset([inst.primary_node for inst in instance_list])
1919

    
1920
    bad_nodes = []
1921
    if self.dynamic_fields.intersection(self.op.output_fields):
1922
      live_data = {}
1923
      node_data = rpc.call_all_instances_info(nodes)
1924
      for name in nodes:
1925
        result = node_data[name]
1926
        if result:
1927
          live_data.update(result)
1928
        elif result == False:
1929
          bad_nodes.append(name)
1930
        # else no instance is alive
1931
    else:
1932
      live_data = dict([(name, {}) for name in instance_names])
1933

    
1934
    # end data gathering
1935

    
1936
    output = []
1937
    for instance in instance_list:
1938
      iout = []
1939
      for field in self.op.output_fields:
1940
        if field == "name":
1941
          val = instance.name
1942
        elif field == "os":
1943
          val = instance.os
1944
        elif field == "pnode":
1945
          val = instance.primary_node
1946
        elif field == "snodes":
1947
          val = ",".join(instance.secondary_nodes) or "-"
1948
        elif field == "admin_state":
1949
          if instance.status == "down":
1950
            val = "no"
1951
          else:
1952
            val = "yes"
1953
        elif field == "oper_state":
1954
          if instance.primary_node in bad_nodes:
1955
            val = "(node down)"
1956
          else:
1957
            if live_data.get(instance.name):
1958
              val = "running"
1959
            else:
1960
              val = "stopped"
1961
        elif field == "admin_ram":
1962
          val = instance.memory
1963
        elif field == "oper_ram":
1964
          if instance.primary_node in bad_nodes:
1965
            val = "(node down)"
1966
          elif instance.name in live_data:
1967
            val = live_data[instance.name].get("memory", "?")
1968
          else:
1969
            val = "-"
1970
        elif field == "disk_template":
1971
          val = instance.disk_template
1972
        elif field == "ip":
1973
          val = instance.nics[0].ip
1974
        elif field == "bridge":
1975
          val = instance.nics[0].bridge
1976
        elif field == "mac":
1977
          val = instance.nics[0].mac
1978
        else:
1979
          raise errors.ParameterError, field
1980
        val = str(val)
1981
        iout.append(val)
1982
      output.append(iout)
1983

    
1984
    return output
1985

    
1986

    
1987
class LUFailoverInstance(LogicalUnit):
1988
  """Failover an instance.
1989

1990
  """
1991
  HPATH = "instance-failover"
1992
  HTYPE = constants.HTYPE_INSTANCE
1993
  _OP_REQP = ["instance_name", "ignore_consistency"]
1994

    
1995
  def BuildHooksEnv(self):
1996
    """Build hooks env.
1997

1998
    This runs on master, primary and secondary nodes of the instance.
1999

2000
    """
2001
    env = {
2002
      "INSTANCE_NAME": self.op.instance_name,
2003
      "INSTANCE_PRIMARY": self.instance.primary_node,
2004
      "INSTANCE_SECONDARIES": " ".join(self.instance.secondary_nodes),
2005
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2006
      }
2007
    nl = [self.sstore.GetMasterNode()] + list(self.instance.secondary_nodes)
2008
    return env, nl, nl
2009

    
2010
  def CheckPrereq(self):
2011
    """Check prerequisites.
2012

2013
    This checks that the instance is in the cluster.
2014

2015
    """
2016
    instance = self.cfg.GetInstanceInfo(
2017
      self.cfg.ExpandInstanceName(self.op.instance_name))
2018
    if instance is None:
2019
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2020
                                   self.op.instance_name)
2021

    
2022
    # check memory requirements on the secondary node
2023
    target_node = instance.secondary_nodes[0]
2024
    nodeinfo = rpc.call_node_info([target_node], self.cfg.GetVGName())
2025
    info = nodeinfo.get(target_node, None)
2026
    if not info:
2027
      raise errors.OpPrereqError, ("Cannot get current information"
2028
                                   " from node '%s'" % nodeinfo)
2029
    if instance.memory > info['memory_free']:
2030
      raise errors.OpPrereqError, ("Not enough memory on target node %s."
2031
                                   " %d MB available, %d MB required" %
2032
                                   (target_node, info['memory_free'],
2033
                                    instance.memory))
2034

    
2035
    # check bridge existance
2036
    brlist = [nic.bridge for nic in instance.nics]
2037
    if not rpc.call_bridges_exist(instance.primary_node, brlist):
2038
      raise errors.OpPrereqError, ("one or more target bridges %s does not"
2039
                                   " exist on destination node '%s'" %
2040
                                   (brlist, instance.primary_node))
2041

    
2042
    self.instance = instance
2043

    
2044
  def Exec(self, feedback_fn):
2045
    """Failover an instance.
2046

2047
    The failover is done by shutting it down on its present node and
2048
    starting it on the secondary.
2049

2050
    """
2051
    instance = self.instance
2052

    
2053
    source_node = instance.primary_node
2054
    target_node = instance.secondary_nodes[0]
2055

    
2056
    feedback_fn("* checking disk consistency between source and target")
2057
    for dev in instance.disks:
2058
      # for remote_raid1, these are md over drbd
2059
      if not _CheckDiskConsistency(self.cfg, dev, target_node, False):
2060
        if not self.op.ignore_consistency:
2061
          raise errors.OpExecError, ("Disk %s is degraded on target node,"
2062
                                     " aborting failover." % dev.iv_name)
2063

    
2064
    feedback_fn("* checking target node resource availability")
2065
    nodeinfo = rpc.call_node_info([target_node], self.cfg.GetVGName())
2066

    
2067
    if not nodeinfo:
2068
      raise errors.OpExecError, ("Could not contact target node %s." %
2069
                                 target_node)
2070

    
2071
    free_memory = int(nodeinfo[target_node]['memory_free'])
2072
    memory = instance.memory
2073
    if memory > free_memory:
2074
      raise errors.OpExecError, ("Not enough memory to create instance %s on"
2075
                                 " node %s. needed %s MiB, available %s MiB" %
2076
                                 (instance.name, target_node, memory,
2077
                                  free_memory))
2078

    
2079
    feedback_fn("* shutting down instance on source node")
2080
    logger.Info("Shutting down instance %s on node %s" %
2081
                (instance.name, source_node))
2082

    
2083
    if not rpc.call_instance_shutdown(source_node, instance):
2084
      logger.Error("Could not shutdown instance %s on node %s. Proceeding"
2085
                   " anyway. Please make sure node %s is down"  %
2086
                   (instance.name, source_node, source_node))
2087

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

    
2092
    instance.primary_node = target_node
2093
    # distribute new instance config to the other nodes
2094
    self.cfg.AddInstance(instance)
2095

    
2096
    feedback_fn("* activating the instance's disks on target node")
2097
    logger.Info("Starting instance %s on node %s" %
2098
                (instance.name, target_node))
2099

    
2100
    disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
2101
                                             ignore_secondaries=True)
2102
    if not disks_ok:
2103
      _ShutdownInstanceDisks(instance, self.cfg)
2104
      raise errors.OpExecError, ("Can't activate the instance's disks")
2105

    
2106
    feedback_fn("* starting the instance on the target node")
2107
    if not rpc.call_instance_start(target_node, instance, None):
2108
      _ShutdownInstanceDisks(instance, self.cfg)
2109
      raise errors.OpExecError("Could not start instance %s on node %s." %
2110
                               (instance.name, target_node))
2111

    
2112

    
2113
def _CreateBlockDevOnPrimary(cfg, node, device):
2114
  """Create a tree of block devices on the primary node.
2115

2116
  This always creates all devices.
2117

2118
  """
2119

    
2120
  if device.children:
2121
    for child in device.children:
2122
      if not _CreateBlockDevOnPrimary(cfg, node, child):
2123
        return False
2124

    
2125
  cfg.SetDiskID(device, node)
2126
  new_id = rpc.call_blockdev_create(node, device, device.size, True)
2127
  if not new_id:
2128
    return False
2129
  if device.physical_id is None:
2130
    device.physical_id = new_id
2131
  return True
2132

    
2133

    
2134
def _CreateBlockDevOnSecondary(cfg, node, device, force):
2135
  """Create a tree of block devices on a secondary node.
2136

2137
  If this device type has to be created on secondaries, create it and
2138
  all its children.
2139

2140
  If not, just recurse to children keeping the same 'force' value.
2141

2142
  """
2143
  if device.CreateOnSecondary():
2144
    force = True
2145
  if device.children:
2146
    for child in device.children:
2147
      if not _CreateBlockDevOnSecondary(cfg, node, child, force):
2148
        return False
2149

    
2150
  if not force:
2151
    return True
2152
  cfg.SetDiskID(device, node)
2153
  new_id = rpc.call_blockdev_create(node, device, device.size, False)
2154
  if not new_id:
2155
    return False
2156
  if device.physical_id is None:
2157
    device.physical_id = new_id
2158
  return True
2159

    
2160

    
2161
def _GenerateMDDRBDBranch(cfg, vgname, primary, secondary, size, base):
2162
  """Generate a drbd device complete with its children.
2163

2164
  """
2165
  port = cfg.AllocatePort()
2166
  base = "%s_%s" % (base, port)
2167
  dev_data = objects.Disk(dev_type="lvm", size=size,
2168
                          logical_id=(vgname, "%s.data" % base))
2169
  dev_meta = objects.Disk(dev_type="lvm", size=128,
2170
                          logical_id=(vgname, "%s.meta" % base))
2171
  drbd_dev = objects.Disk(dev_type="drbd", size=size,
2172
                          logical_id = (primary, secondary, port),
2173
                          children = [dev_data, dev_meta])
2174
  return drbd_dev
2175

    
2176

    
2177
def _GenerateDiskTemplate(cfg, vgname, template_name,
2178
                          instance_name, primary_node,
2179
                          secondary_nodes, disk_sz, swap_sz):
2180
  """Generate the entire disk layout for a given template type.
2181

2182
  """
2183
  #TODO: compute space requirements
2184

    
2185
  if template_name == "diskless":
2186
    disks = []
2187
  elif template_name == "plain":
2188
    if len(secondary_nodes) != 0:
2189
      raise errors.ProgrammerError("Wrong template configuration")
2190
    sda_dev = objects.Disk(dev_type="lvm", size=disk_sz,
2191
                           logical_id=(vgname, "%s.os" % instance_name),
2192
                           iv_name = "sda")
2193
    sdb_dev = objects.Disk(dev_type="lvm", size=swap_sz,
2194
                           logical_id=(vgname, "%s.swap" % instance_name),
2195
                           iv_name = "sdb")
2196
    disks = [sda_dev, sdb_dev]
2197
  elif template_name == "local_raid1":
2198
    if len(secondary_nodes) != 0:
2199
      raise errors.ProgrammerError("Wrong template configuration")
2200
    sda_dev_m1 = objects.Disk(dev_type="lvm", size=disk_sz,
2201
                              logical_id=(vgname, "%s.os_m1" % instance_name))
2202
    sda_dev_m2 = objects.Disk(dev_type="lvm", size=disk_sz,
2203
                              logical_id=(vgname, "%s.os_m2" % instance_name))
2204
    md_sda_dev = objects.Disk(dev_type="md_raid1", iv_name = "sda",
2205
                              size=disk_sz,
2206
                              children = [sda_dev_m1, sda_dev_m2])
2207
    sdb_dev_m1 = objects.Disk(dev_type="lvm", size=swap_sz,
2208
                              logical_id=(vgname, "%s.swap_m1" %
2209
                                          instance_name))
2210
    sdb_dev_m2 = objects.Disk(dev_type="lvm", size=swap_sz,
2211
                              logical_id=(vgname, "%s.swap_m2" %
2212
                                          instance_name))
2213
    md_sdb_dev = objects.Disk(dev_type="md_raid1", iv_name = "sdb",
2214
                              size=swap_sz,
2215
                              children = [sdb_dev_m1, sdb_dev_m2])
2216
    disks = [md_sda_dev, md_sdb_dev]
2217
  elif template_name == "remote_raid1":
2218
    if len(secondary_nodes) != 1:
2219
      raise errors.ProgrammerError("Wrong template configuration")
2220
    remote_node = secondary_nodes[0]
2221
    drbd_sda_dev = _GenerateMDDRBDBranch(cfg, vgname,
2222
                                         primary_node, remote_node, disk_sz,
2223
                                         "%s-sda" % instance_name)
2224
    md_sda_dev = objects.Disk(dev_type="md_raid1", iv_name="sda",
2225
                              children = [drbd_sda_dev], size=disk_sz)
2226
    drbd_sdb_dev = _GenerateMDDRBDBranch(cfg, vgname,
2227
                                         primary_node, remote_node, swap_sz,
2228
                                         "%s-sdb" % instance_name)
2229
    md_sdb_dev = objects.Disk(dev_type="md_raid1", iv_name="sdb",
2230
                              children = [drbd_sdb_dev], size=swap_sz)
2231
    disks = [md_sda_dev, md_sdb_dev]
2232
  else:
2233
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
2234
  return disks
2235

    
2236

    
2237
def _CreateDisks(cfg, instance):
2238
  """Create all disks for an instance.
2239

2240
  This abstracts away some work from AddInstance.
2241

2242
  Args:
2243
    instance: the instance object
2244

2245
  Returns:
2246
    True or False showing the success of the creation process
2247

2248
  """
2249
  for device in instance.disks:
2250
    logger.Info("creating volume %s for instance %s" %
2251
              (device.iv_name, instance.name))
2252
    #HARDCODE
2253
    for secondary_node in instance.secondary_nodes:
2254
      if not _CreateBlockDevOnSecondary(cfg, secondary_node, device, False):
2255
        logger.Error("failed to create volume %s (%s) on secondary node %s!" %
2256
                     (device.iv_name, device, secondary_node))
2257
        return False
2258
    #HARDCODE
2259
    if not _CreateBlockDevOnPrimary(cfg, instance.primary_node, device):
2260
      logger.Error("failed to create volume %s on primary!" %
2261
                   device.iv_name)
2262
      return False
2263
  return True
2264

    
2265

    
2266
def _RemoveDisks(instance, cfg):
2267
  """Remove all disks for an instance.
2268

2269
  This abstracts away some work from `AddInstance()` and
2270
  `RemoveInstance()`. Note that in case some of the devices couldn't
2271
  be remove, the removal will continue with the other ones (compare
2272
  with `_CreateDisks()`).
2273

2274
  Args:
2275
    instance: the instance object
2276

2277
  Returns:
2278
    True or False showing the success of the removal proces
2279

2280
  """
2281
  logger.Info("removing block devices for instance %s" % instance.name)
2282

    
2283
  result = True
2284
  for device in instance.disks:
2285
    for node, disk in device.ComputeNodeTree(instance.primary_node):
2286
      cfg.SetDiskID(disk, node)
2287
      if not rpc.call_blockdev_remove(node, disk):
2288
        logger.Error("could not remove block device %s on node %s,"
2289
                     " continuing anyway" %
2290
                     (device.iv_name, node))
2291
        result = False
2292
  return result
2293

    
2294

    
2295
class LUCreateInstance(LogicalUnit):
2296
  """Create an instance.
2297

2298
  """
2299
  HPATH = "instance-add"
2300
  HTYPE = constants.HTYPE_INSTANCE
2301
  _OP_REQP = ["instance_name", "mem_size", "disk_size", "pnode",
2302
              "disk_template", "swap_size", "mode", "start", "vcpus",
2303
              "wait_for_sync"]
2304

    
2305
  def BuildHooksEnv(self):
2306
    """Build hooks env.
2307

2308
    This runs on master, primary and secondary nodes of the instance.
2309

2310
    """
2311
    env = {
2312
      "INSTANCE_NAME": self.op.instance_name,
2313
      "INSTANCE_PRIMARY": self.op.pnode,
2314
      "INSTANCE_SECONDARIES": " ".join(self.secondaries),
2315
      "DISK_TEMPLATE": self.op.disk_template,
2316
      "MEM_SIZE": self.op.mem_size,
2317
      "DISK_SIZE": self.op.disk_size,
2318
      "SWAP_SIZE": self.op.swap_size,
2319
      "VCPUS": self.op.vcpus,
2320
      "BRIDGE": self.op.bridge,
2321
      "INSTANCE_ADD_MODE": self.op.mode,
2322
      }
2323
    if self.op.mode == constants.INSTANCE_IMPORT:
2324
      env["SRC_NODE"] = self.op.src_node
2325
      env["SRC_PATH"] = self.op.src_path
2326
      env["SRC_IMAGE"] = self.src_image
2327
    if self.inst_ip:
2328
      env["INSTANCE_IP"] = self.inst_ip
2329

    
2330
    nl = ([self.sstore.GetMasterNode(), self.op.pnode] +
2331
          self.secondaries)
2332
    return env, nl, nl
2333

    
2334

    
2335
  def CheckPrereq(self):
2336
    """Check prerequisites.
2337

2338
    """
2339
    if self.op.mode not in (constants.INSTANCE_CREATE,
2340
                            constants.INSTANCE_IMPORT):
2341
      raise errors.OpPrereqError, ("Invalid instance creation mode '%s'" %
2342
                                   self.op.mode)
2343

    
2344
    if self.op.mode == constants.INSTANCE_IMPORT:
2345
      src_node = getattr(self.op, "src_node", None)
2346
      src_path = getattr(self.op, "src_path", None)
2347
      if src_node is None or src_path is None:
2348
        raise errors.OpPrereqError, ("Importing an instance requires source"
2349
                                     " node and path options")
2350
      src_node_full = self.cfg.ExpandNodeName(src_node)
2351
      if src_node_full is None:
2352
        raise errors.OpPrereqError, ("Unknown source node '%s'" % src_node)
2353
      self.op.src_node = src_node = src_node_full
2354

    
2355
      if not os.path.isabs(src_path):
2356
        raise errors.OpPrereqError, ("The source path must be absolute")
2357

    
2358
      export_info = rpc.call_export_info(src_node, src_path)
2359

    
2360
      if not export_info:
2361
        raise errors.OpPrereqError, ("No export found in dir %s" % src_path)
2362

    
2363
      if not export_info.has_section(constants.INISECT_EXP):
2364
        raise errors.ProgrammerError, ("Corrupted export config")
2365

    
2366
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
2367
      if (int(ei_version) != constants.EXPORT_VERSION):
2368
        raise errors.OpPrereqError, ("Wrong export version %s (wanted %d)" %
2369
                                     (ei_version, constants.EXPORT_VERSION))
2370

    
2371
      if int(export_info.get(constants.INISECT_INS, 'disk_count')) > 1:
2372
        raise errors.OpPrereqError, ("Can't import instance with more than"
2373
                                     " one data disk")
2374

    
2375
      # FIXME: are the old os-es, disk sizes, etc. useful?
2376
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
2377
      diskimage = os.path.join(src_path, export_info.get(constants.INISECT_INS,
2378
                                                         'disk0_dump'))
2379
      self.src_image = diskimage
2380
    else: # INSTANCE_CREATE
2381
      if getattr(self.op, "os_type", None) is None:
2382
        raise errors.OpPrereqError, ("No guest OS specified")
2383

    
2384
    # check primary node
2385
    pnode = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.pnode))
2386
    if pnode is None:
2387
      raise errors.OpPrereqError, ("Primary node '%s' is uknown" %
2388
                                   self.op.pnode)
2389
    self.op.pnode = pnode.name
2390
    self.pnode = pnode
2391
    self.secondaries = []
2392
    # disk template and mirror node verification
2393
    if self.op.disk_template not in constants.DISK_TEMPLATES:
2394
      raise errors.OpPrereqError, ("Invalid disk template name")
2395

    
2396
    if self.op.disk_template == constants.DT_REMOTE_RAID1:
2397
      if getattr(self.op, "snode", None) is None:
2398
        raise errors.OpPrereqError, ("The 'remote_raid1' disk template needs"
2399
                                     " a mirror node")
2400

    
2401
      snode_name = self.cfg.ExpandNodeName(self.op.snode)
2402
      if snode_name is None:
2403
        raise errors.OpPrereqError, ("Unknown secondary node '%s'" %
2404
                                     self.op.snode)
2405
      elif snode_name == pnode.name:
2406
        raise errors.OpPrereqError, ("The secondary node cannot be"
2407
                                     " the primary node.")
2408
      self.secondaries.append(snode_name)
2409

    
2410
    # Check lv size requirements
2411
    nodenames = [pnode.name] + self.secondaries
2412
    nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
2413

    
2414
    # Required free disk space as a function of disk and swap space
2415
    req_size_dict = {
2416
      constants.DT_DISKLESS: 0,
2417
      constants.DT_PLAIN: self.op.disk_size + self.op.swap_size,
2418
      constants.DT_LOCAL_RAID1: (self.op.disk_size + self.op.swap_size) * 2,
2419
      # 256 MB are added for drbd metadata, 128MB for each drbd device
2420
      constants.DT_REMOTE_RAID1: self.op.disk_size + self.op.swap_size + 256,
2421
    }
2422

    
2423
    if self.op.disk_template not in req_size_dict:
2424
      raise errors.ProgrammerError, ("Disk template '%s' size requirement"
2425
                                     " is unknown" %  self.op.disk_template)
2426

    
2427
    req_size = req_size_dict[self.op.disk_template]
2428

    
2429
    for node in nodenames:
2430
      info = nodeinfo.get(node, None)
2431
      if not info:
2432
        raise errors.OpPrereqError, ("Cannot get current information"
2433
                                     " from node '%s'" % nodeinfo)
2434
      if req_size > info['vg_free']:
2435
        raise errors.OpPrereqError, ("Not enough disk space on target node %s."
2436
                                     " %d MB available, %d MB required" %
2437
                                     (node, info['vg_free'], req_size))
2438

    
2439
    # os verification
2440
    os_obj = rpc.call_os_get([pnode.name], self.op.os_type)[pnode.name]
2441
    if not isinstance(os_obj, objects.OS):
2442
      raise errors.OpPrereqError, ("OS '%s' not in supported os list for"
2443
                                   " primary node"  % self.op.os_type)
2444

    
2445
    # instance verification
2446
    hostname1 = utils.LookupHostname(self.op.instance_name)
2447
    if not hostname1:
2448
      raise errors.OpPrereqError, ("Instance name '%s' not found in dns" %
2449
                                   self.op.instance_name)
2450

    
2451
    self.op.instance_name = instance_name = hostname1['hostname']
2452
    instance_list = self.cfg.GetInstanceList()
2453
    if instance_name in instance_list:
2454
      raise errors.OpPrereqError, ("Instance '%s' is already in the cluster" %
2455
                                   instance_name)
2456

    
2457
    ip = getattr(self.op, "ip", None)
2458
    if ip is None or ip.lower() == "none":
2459
      inst_ip = None
2460
    elif ip.lower() == "auto":
2461
      inst_ip = hostname1['ip']
2462
    else:
2463
      if not utils.IsValidIP(ip):
2464
        raise errors.OpPrereqError, ("given IP address '%s' doesn't look"
2465
                                     " like a valid IP" % ip)
2466
      inst_ip = ip
2467
    self.inst_ip = inst_ip
2468

    
2469
    command = ["fping", "-q", hostname1['ip']]
2470
    result = utils.RunCmd(command)
2471
    if not result.failed:
2472
      raise errors.OpPrereqError, ("IP %s of instance %s already in use" %
2473
                                   (hostname1['ip'], instance_name))
2474

    
2475
    # bridge verification
2476
    bridge = getattr(self.op, "bridge", None)
2477
    if bridge is None:
2478
      self.op.bridge = self.cfg.GetDefBridge()
2479
    else:
2480
      self.op.bridge = bridge
2481

    
2482
    if not rpc.call_bridges_exist(self.pnode.name, [self.op.bridge]):
2483
      raise errors.OpPrereqError, ("target bridge '%s' does not exist on"
2484
                                   " destination node '%s'" %
2485
                                   (self.op.bridge, pnode.name))
2486

    
2487
    if self.op.start:
2488
      self.instance_status = 'up'
2489
    else:
2490
      self.instance_status = 'down'
2491

    
2492
  def Exec(self, feedback_fn):
2493
    """Create and add the instance to the cluster.
2494

2495
    """
2496
    instance = self.op.instance_name
2497
    pnode_name = self.pnode.name
2498

    
2499
    nic = objects.NIC(bridge=self.op.bridge, mac=self.cfg.GenerateMAC())
2500
    if self.inst_ip is not None:
2501
      nic.ip = self.inst_ip
2502

    
2503
    disks = _GenerateDiskTemplate(self.cfg, self.cfg.GetVGName(),
2504
                                  self.op.disk_template,
2505
                                  instance, pnode_name,
2506
                                  self.secondaries, self.op.disk_size,
2507
                                  self.op.swap_size)
2508

    
2509
    iobj = objects.Instance(name=instance, os=self.op.os_type,
2510
                            primary_node=pnode_name,
2511
                            memory=self.op.mem_size,
2512
                            vcpus=self.op.vcpus,
2513
                            nics=[nic], disks=disks,
2514
                            disk_template=self.op.disk_template,
2515
                            status=self.instance_status,
2516
                            )
2517

    
2518
    feedback_fn("* creating instance disks...")
2519
    if not _CreateDisks(self.cfg, iobj):
2520
      _RemoveDisks(iobj, self.cfg)
2521
      raise errors.OpExecError, ("Device creation failed, reverting...")
2522

    
2523
    feedback_fn("adding instance %s to cluster config" % instance)
2524

    
2525
    self.cfg.AddInstance(iobj)
2526

    
2527
    if self.op.wait_for_sync:
2528
      disk_abort = not _WaitForSync(self.cfg, iobj)
2529
    elif iobj.disk_template == "remote_raid1":
2530
      # make sure the disks are not degraded (still sync-ing is ok)
2531
      time.sleep(15)
2532
      feedback_fn("* checking mirrors status")
2533
      disk_abort = not _WaitForSync(self.cfg, iobj, oneshot=True)
2534
    else:
2535
      disk_abort = False
2536

    
2537
    if disk_abort:
2538
      _RemoveDisks(iobj, self.cfg)
2539
      self.cfg.RemoveInstance(iobj.name)
2540
      raise errors.OpExecError, ("There are some degraded disks for"
2541
                                      " this instance")
2542

    
2543
    feedback_fn("creating os for instance %s on node %s" %
2544
                (instance, pnode_name))
2545

    
2546
    if iobj.disk_template != constants.DT_DISKLESS:
2547
      if self.op.mode == constants.INSTANCE_CREATE:
2548
        feedback_fn("* running the instance OS create scripts...")
2549
        if not rpc.call_instance_os_add(pnode_name, iobj, "sda", "sdb"):
2550
          raise errors.OpExecError, ("could not add os for instance %s"
2551
                                          " on node %s" %
2552
                                          (instance, pnode_name))
2553

    
2554
      elif self.op.mode == constants.INSTANCE_IMPORT:
2555
        feedback_fn("* running the instance OS import scripts...")
2556
        src_node = self.op.src_node
2557
        src_image = self.src_image
2558
        if not rpc.call_instance_os_import(pnode_name, iobj, "sda", "sdb",
2559
                                                src_node, src_image):
2560
          raise errors.OpExecError, ("Could not import os for instance"
2561
                                          " %s on node %s" %
2562
                                          (instance, pnode_name))
2563
      else:
2564
        # also checked in the prereq part
2565
        raise errors.ProgrammerError, ("Unknown OS initialization mode '%s'"
2566
                                       % self.op.mode)
2567

    
2568
    if self.op.start:
2569
      logger.Info("starting instance %s on node %s" % (instance, pnode_name))
2570
      feedback_fn("* starting instance...")
2571
      if not rpc.call_instance_start(pnode_name, iobj, None):
2572
        raise errors.OpExecError, ("Could not start instance")
2573

    
2574

    
2575
class LUConnectConsole(NoHooksLU):
2576
  """Connect to an instance's console.
2577

2578
  This is somewhat special in that it returns the command line that
2579
  you need to run on the master node in order to connect to the
2580
  console.
2581

2582
  """
2583
  _OP_REQP = ["instance_name"]
2584

    
2585
  def CheckPrereq(self):
2586
    """Check prerequisites.
2587

2588
    This checks that the instance is in the cluster.
2589

2590
    """
2591
    instance = self.cfg.GetInstanceInfo(
2592
      self.cfg.ExpandInstanceName(self.op.instance_name))
2593
    if instance is None:
2594
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2595
                                   self.op.instance_name)
2596
    self.instance = instance
2597

    
2598
  def Exec(self, feedback_fn):
2599
    """Connect to the console of an instance
2600

2601
    """
2602
    instance = self.instance
2603
    node = instance.primary_node
2604

    
2605
    node_insts = rpc.call_instance_list([node])[node]
2606
    if node_insts is False:
2607
      raise errors.OpExecError, ("Can't connect to node %s." % node)
2608

    
2609
    if instance.name not in node_insts:
2610
      raise errors.OpExecError, ("Instance %s is not running." % instance.name)
2611

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

    
2614
    hyper = hypervisor.GetHypervisor()
2615
    console_cmd = hyper.GetShellCommandForConsole(instance.name)
2616
    return node, console_cmd
2617

    
2618

    
2619
class LUAddMDDRBDComponent(LogicalUnit):
2620
  """Adda new mirror member to an instance's disk.
2621

2622
  """
2623
  HPATH = "mirror-add"
2624
  HTYPE = constants.HTYPE_INSTANCE
2625
  _OP_REQP = ["instance_name", "remote_node", "disk_name"]
2626

    
2627
  def BuildHooksEnv(self):
2628
    """Build hooks env.
2629

2630
    This runs on the master, the primary and all the secondaries.
2631

2632
    """
2633
    env = {
2634
      "INSTANCE_NAME": self.op.instance_name,
2635
      "NEW_SECONDARY": self.op.remote_node,
2636
      "DISK_NAME": self.op.disk_name,
2637
      }
2638
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
2639
          self.op.remote_node,] + list(self.instance.secondary_nodes)
2640
    return env, nl, nl
2641

    
2642
  def CheckPrereq(self):
2643
    """Check prerequisites.
2644

2645
    This checks that the instance is in the cluster.
2646

2647
    """
2648
    instance = self.cfg.GetInstanceInfo(
2649
      self.cfg.ExpandInstanceName(self.op.instance_name))
2650
    if instance is None:
2651
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2652
                                   self.op.instance_name)
2653
    self.instance = instance
2654

    
2655
    remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
2656
    if remote_node is None:
2657
      raise errors.OpPrereqError, ("Node '%s' not known" % self.op.remote_node)
2658
    self.remote_node = remote_node
2659

    
2660
    if remote_node == instance.primary_node:
2661
      raise errors.OpPrereqError, ("The specified node is the primary node of"
2662
                                   " the instance.")
2663

    
2664
    if instance.disk_template != constants.DT_REMOTE_RAID1:
2665
      raise errors.OpPrereqError, ("Instance's disk layout is not"
2666
                                   " remote_raid1.")
2667
    for disk in instance.disks:
2668
      if disk.iv_name == self.op.disk_name:
2669
        break
2670
    else:
2671
      raise errors.OpPrereqError, ("Can't find this device ('%s') in the"
2672
                                   " instance." % self.op.disk_name)
2673
    if len(disk.children) > 1:
2674
      raise errors.OpPrereqError, ("The device already has two slave"
2675
                                   " devices.\n"
2676
                                   "This would create a 3-disk raid1"
2677
                                   " which we don't allow.")
2678
    self.disk = disk
2679

    
2680
  def Exec(self, feedback_fn):
2681
    """Add the mirror component
2682

2683
    """
2684
    disk = self.disk
2685
    instance = self.instance
2686

    
2687
    remote_node = self.remote_node
2688
    new_drbd = _GenerateMDDRBDBranch(self.cfg, self.cfg.GetVGName(),
2689
                                     instance.primary_node, remote_node,
2690
                                     disk.size, "%s-%s" %
2691
                                     (instance.name, self.op.disk_name))
2692

    
2693
    logger.Info("adding new mirror component on secondary")
2694
    #HARDCODE
2695
    if not _CreateBlockDevOnSecondary(self.cfg, remote_node, new_drbd, False):
2696
      raise errors.OpExecError, ("Failed to create new component on secondary"
2697
                                 " node %s" % remote_node)
2698

    
2699
    logger.Info("adding new mirror component on primary")
2700
    #HARDCODE
2701
    if not _CreateBlockDevOnPrimary(self.cfg, instance.primary_node, new_drbd):
2702
      # remove secondary dev
2703
      self.cfg.SetDiskID(new_drbd, remote_node)
2704
      rpc.call_blockdev_remove(remote_node, new_drbd)
2705
      raise errors.OpExecError, ("Failed to create volume on primary")
2706

    
2707
    # the device exists now
2708
    # call the primary node to add the mirror to md
2709
    logger.Info("adding new mirror component to md")
2710
    if not rpc.call_blockdev_addchild(instance.primary_node,
2711
                                           disk, new_drbd):
2712
      logger.Error("Can't add mirror compoment to md!")
2713
      self.cfg.SetDiskID(new_drbd, remote_node)
2714
      if not rpc.call_blockdev_remove(remote_node, new_drbd):
2715
        logger.Error("Can't rollback on secondary")
2716
      self.cfg.SetDiskID(new_drbd, instance.primary_node)
2717
      if not rpc.call_blockdev_remove(instance.primary_node, new_drbd):
2718
        logger.Error("Can't rollback on primary")
2719
      raise errors.OpExecError, "Can't add mirror component to md array"
2720

    
2721
    disk.children.append(new_drbd)
2722

    
2723
    self.cfg.AddInstance(instance)
2724

    
2725
    _WaitForSync(self.cfg, instance)
2726

    
2727
    return 0
2728

    
2729

    
2730
class LURemoveMDDRBDComponent(LogicalUnit):
2731
  """Remove a component from a remote_raid1 disk.
2732

2733
  """
2734
  HPATH = "mirror-remove"
2735
  HTYPE = constants.HTYPE_INSTANCE
2736
  _OP_REQP = ["instance_name", "disk_name", "disk_id"]
2737

    
2738
  def BuildHooksEnv(self):
2739
    """Build hooks env.
2740

2741
    This runs on the master, the primary and all the secondaries.
2742

2743
    """
2744
    env = {
2745
      "INSTANCE_NAME": self.op.instance_name,
2746
      "DISK_NAME": self.op.disk_name,
2747
      "DISK_ID": self.op.disk_id,
2748
      "OLD_SECONDARY": self.old_secondary,
2749
      }
2750
    nl = [self.sstore.GetMasterNode(),
2751
          self.instance.primary_node] + list(self.instance.secondary_nodes)
2752
    return env, nl, nl
2753

    
2754
  def CheckPrereq(self):
2755
    """Check prerequisites.
2756

2757
    This checks that the instance is in the cluster.
2758

2759
    """
2760
    instance = self.cfg.GetInstanceInfo(
2761
      self.cfg.ExpandInstanceName(self.op.instance_name))
2762
    if instance is None:
2763
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2764
                                   self.op.instance_name)
2765
    self.instance = instance
2766

    
2767
    if instance.disk_template != constants.DT_REMOTE_RAID1:
2768
      raise errors.OpPrereqError, ("Instance's disk layout is not"
2769
                                   " remote_raid1.")
2770
    for disk in instance.disks:
2771
      if disk.iv_name == self.op.disk_name:
2772
        break
2773
    else:
2774
      raise errors.OpPrereqError, ("Can't find this device ('%s') in the"
2775
                                   " instance." % self.op.disk_name)
2776
    for child in disk.children:
2777
      if child.dev_type == "drbd" and child.logical_id[2] == self.op.disk_id:
2778
        break
2779
    else:
2780
      raise errors.OpPrereqError, ("Can't find the device with this port.")
2781

    
2782
    if len(disk.children) < 2:
2783
      raise errors.OpPrereqError, ("Cannot remove the last component from"
2784
                                   " a mirror.")
2785
    self.disk = disk
2786
    self.child = child
2787
    if self.child.logical_id[0] == instance.primary_node:
2788
      oid = 1
2789
    else:
2790
      oid = 0
2791
    self.old_secondary = self.child.logical_id[oid]
2792

    
2793
  def Exec(self, feedback_fn):
2794
    """Remove the mirror component
2795

2796
    """
2797
    instance = self.instance
2798
    disk = self.disk
2799
    child = self.child
2800
    logger.Info("remove mirror component")
2801
    self.cfg.SetDiskID(disk, instance.primary_node)
2802
    if not rpc.call_blockdev_removechild(instance.primary_node,
2803
                                              disk, child):
2804
      raise errors.OpExecError, ("Can't remove child from mirror.")
2805

    
2806
    for node in child.logical_id[:2]:
2807
      self.cfg.SetDiskID(child, node)
2808
      if not rpc.call_blockdev_remove(node, child):
2809
        logger.Error("Warning: failed to remove device from node %s,"
2810
                     " continuing operation." % node)
2811

    
2812
    disk.children.remove(child)
2813
    self.cfg.AddInstance(instance)
2814

    
2815

    
2816
class LUReplaceDisks(LogicalUnit):
2817
  """Replace the disks of an instance.
2818

2819
  """
2820
  HPATH = "mirrors-replace"
2821
  HTYPE = constants.HTYPE_INSTANCE
2822
  _OP_REQP = ["instance_name"]
2823

    
2824
  def BuildHooksEnv(self):
2825
    """Build hooks env.
2826

2827
    This runs on the master, the primary and all the secondaries.
2828

2829
    """
2830
    env = {
2831
      "INSTANCE_NAME": self.op.instance_name,
2832
      "NEW_SECONDARY": self.op.remote_node,
2833
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
2834
      }
2835
    nl = [self.sstore.GetMasterNode(),
2836
          self.instance.primary_node] + list(self.instance.secondary_nodes)
2837
    return env, nl, nl
2838

    
2839
  def CheckPrereq(self):
2840
    """Check prerequisites.
2841

2842
    This checks that the instance is in the cluster.
2843

2844
    """
2845
    instance = self.cfg.GetInstanceInfo(
2846
      self.cfg.ExpandInstanceName(self.op.instance_name))
2847
    if instance is None:
2848
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2849
                                   self.op.instance_name)
2850
    self.instance = instance
2851

    
2852
    if instance.disk_template != constants.DT_REMOTE_RAID1:
2853
      raise errors.OpPrereqError, ("Instance's disk layout is not"
2854
                                   " remote_raid1.")
2855

    
2856
    if len(instance.secondary_nodes) != 1:
2857
      raise errors.OpPrereqError, ("The instance has a strange layout,"
2858
                                   " expected one secondary but found %d" %
2859
                                   len(instance.secondary_nodes))
2860

    
2861
    remote_node = getattr(self.op, "remote_node", None)
2862
    if remote_node is None:
2863
      remote_node = instance.secondary_nodes[0]
2864
    else:
2865
      remote_node = self.cfg.ExpandNodeName(remote_node)
2866
      if remote_node is None:
2867
        raise errors.OpPrereqError, ("Node '%s' not known" %
2868
                                     self.op.remote_node)
2869
    if remote_node == instance.primary_node:
2870
      raise errors.OpPrereqError, ("The specified node is the primary node of"
2871
                                   " the instance.")
2872
    self.op.remote_node = remote_node
2873

    
2874
  def Exec(self, feedback_fn):
2875
    """Replace the disks of an instance.
2876

2877
    """
2878
    instance = self.instance
2879
    iv_names = {}
2880
    # start of work
2881
    remote_node = self.op.remote_node
2882
    cfg = self.cfg
2883
    vgname = cfg.GetVGName()
2884
    for dev in instance.disks:
2885
      size = dev.size
2886
      new_drbd = _GenerateMDDRBDBranch(cfg, vgname, instance.primary_node,
2887
                                       remote_node, size,
2888
                                       "%s-%s" % (instance.name, dev.iv_name))
2889
      iv_names[dev.iv_name] = (dev, dev.children[0], new_drbd)
2890
      logger.Info("adding new mirror component on secondary for %s" %
2891
                  dev.iv_name)
2892
      #HARDCODE
2893
      if not _CreateBlockDevOnSecondary(cfg, remote_node, new_drbd, False):
2894
        raise errors.OpExecError, ("Failed to create new component on"
2895
                                   " secondary node %s\n"
2896
                                   "Full abort, cleanup manually!" %
2897
                                   remote_node)
2898

    
2899
      logger.Info("adding new mirror component on primary")
2900
      #HARDCODE
2901
      if not _CreateBlockDevOnPrimary(cfg, instance.primary_node, new_drbd):
2902
        # remove secondary dev
2903
        cfg.SetDiskID(new_drbd, remote_node)
2904
        rpc.call_blockdev_remove(remote_node, new_drbd)
2905
        raise errors.OpExecError("Failed to create volume on primary!\n"
2906
                                 "Full abort, cleanup manually!!")
2907

    
2908
      # the device exists now
2909
      # call the primary node to add the mirror to md
2910
      logger.Info("adding new mirror component to md")
2911
      if not rpc.call_blockdev_addchild(instance.primary_node, dev,
2912
                                        new_drbd):
2913
        logger.Error("Can't add mirror compoment to md!")
2914
        cfg.SetDiskID(new_drbd, remote_node)
2915
        if not rpc.call_blockdev_remove(remote_node, new_drbd):
2916
          logger.Error("Can't rollback on secondary")
2917
        cfg.SetDiskID(new_drbd, instance.primary_node)
2918
        if not rpc.call_blockdev_remove(instance.primary_node, new_drbd):
2919
          logger.Error("Can't rollback on primary")
2920
        raise errors.OpExecError, ("Full abort, cleanup manually!!")
2921

    
2922
      dev.children.append(new_drbd)
2923
      cfg.AddInstance(instance)
2924

    
2925
    # this can fail as the old devices are degraded and _WaitForSync
2926
    # does a combined result over all disks, so we don't check its
2927
    # return value
2928
    _WaitForSync(cfg, instance, unlock=True)
2929

    
2930
    # so check manually all the devices
2931
    for name in iv_names:
2932
      dev, child, new_drbd = iv_names[name]
2933
      cfg.SetDiskID(dev, instance.primary_node)
2934
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
2935
      if is_degr:
2936
        raise errors.OpExecError, ("MD device %s is degraded!" % name)
2937
      cfg.SetDiskID(new_drbd, instance.primary_node)
2938
      is_degr = rpc.call_blockdev_find(instance.primary_node, new_drbd)[5]
2939
      if is_degr:
2940
        raise errors.OpExecError, ("New drbd device %s is degraded!" % name)
2941

    
2942
    for name in iv_names:
2943
      dev, child, new_drbd = iv_names[name]
2944
      logger.Info("remove mirror %s component" % name)
2945
      cfg.SetDiskID(dev, instance.primary_node)
2946
      if not rpc.call_blockdev_removechild(instance.primary_node,
2947
                                                dev, child):
2948
        logger.Error("Can't remove child from mirror, aborting"
2949
                     " *this device cleanup*.\nYou need to cleanup manually!!")
2950
        continue
2951

    
2952
      for node in child.logical_id[:2]:
2953
        logger.Info("remove child device on %s" % node)
2954
        cfg.SetDiskID(child, node)
2955
        if not rpc.call_blockdev_remove(node, child):
2956
          logger.Error("Warning: failed to remove device from node %s,"
2957
                       " continuing operation." % node)
2958

    
2959
      dev.children.remove(child)
2960

    
2961
      cfg.AddInstance(instance)
2962

    
2963

    
2964
class LUQueryInstanceData(NoHooksLU):
2965
  """Query runtime instance data.
2966

2967
  """
2968
  _OP_REQP = ["instances"]
2969

    
2970
  def CheckPrereq(self):
2971
    """Check prerequisites.
2972

2973
    This only checks the optional instance list against the existing names.
2974

2975
    """
2976
    if not isinstance(self.op.instances, list):
2977
      raise errors.OpPrereqError, "Invalid argument type 'instances'"
2978
    if self.op.instances:
2979
      self.wanted_instances = []
2980
      names = self.op.instances
2981
      for name in names:
2982
        instance = self.cfg.GetInstanceInfo(self.cfg.ExpandInstanceName(name))
2983
        if instance is None:
2984
          raise errors.OpPrereqError, ("No such instance name '%s'" % name)
2985
      self.wanted_instances.append(instance)
2986
    else:
2987
      self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2988
                               in self.cfg.GetInstanceList()]
2989
    return
2990

    
2991

    
2992
  def _ComputeDiskStatus(self, instance, snode, dev):
2993
    """Compute block device status.
2994

2995
    """
2996
    self.cfg.SetDiskID(dev, instance.primary_node)
2997
    dev_pstatus = rpc.call_blockdev_find(instance.primary_node, dev)
2998
    if dev.dev_type == "drbd":
2999
      # we change the snode then (otherwise we use the one passed in)
3000
      if dev.logical_id[0] == instance.primary_node:
3001
        snode = dev.logical_id[1]
3002
      else:
3003
        snode = dev.logical_id[0]
3004

    
3005
    if snode:
3006
      self.cfg.SetDiskID(dev, snode)
3007
      dev_sstatus = rpc.call_blockdev_find(snode, dev)
3008
    else:
3009
      dev_sstatus = None
3010

    
3011
    if dev.children:
3012
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
3013
                      for child in dev.children]
3014
    else:
3015
      dev_children = []
3016

    
3017
    data = {
3018
      "iv_name": dev.iv_name,
3019
      "dev_type": dev.dev_type,
3020
      "logical_id": dev.logical_id,
3021
      "physical_id": dev.physical_id,
3022
      "pstatus": dev_pstatus,
3023
      "sstatus": dev_sstatus,
3024
      "children": dev_children,
3025
      }
3026

    
3027
    return data
3028

    
3029
  def Exec(self, feedback_fn):
3030
    """Gather and return data"""
3031

    
3032
    result = {}
3033
    for instance in self.wanted_instances:
3034
      remote_info = rpc.call_instance_info(instance.primary_node,
3035
                                                instance.name)
3036
      if remote_info and "state" in remote_info:
3037
        remote_state = "up"
3038
      else:
3039
        remote_state = "down"
3040
      if instance.status == "down":
3041
        config_state = "down"
3042
      else:
3043
        config_state = "up"
3044

    
3045
      disks = [self._ComputeDiskStatus(instance, None, device)
3046
               for device in instance.disks]
3047

    
3048
      idict = {
3049
        "name": instance.name,
3050
        "config_state": config_state,
3051
        "run_state": remote_state,
3052
        "pnode": instance.primary_node,
3053
        "snodes": instance.secondary_nodes,
3054
        "os": instance.os,
3055
        "memory": instance.memory,
3056
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
3057
        "disks": disks,
3058
        }
3059

    
3060
      result[instance.name] = idict
3061

    
3062
    return result
3063

    
3064

    
3065
class LUQueryNodeData(NoHooksLU):
3066
  """Logical unit for querying node data.
3067

3068
  """
3069
  _OP_REQP = ["nodes"]
3070

    
3071
  def CheckPrereq(self):
3072
    """Check prerequisites.
3073

3074
    This only checks the optional node list against the existing names.
3075

3076
    """
3077
    if not isinstance(self.op.nodes, list):
3078
      raise errors.OpPrereqError, "Invalid argument type 'nodes'"
3079
    if self.op.nodes:
3080
      self.wanted_nodes = []
3081
      names = self.op.nodes
3082
      for name in names:
3083
        node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(name))
3084
        if node is None:
3085
          raise errors.OpPrereqError, ("No such node name '%s'" % name)
3086
      self.wanted_nodes.append(node)
3087
    else:
3088
      self.wanted_nodes = [self.cfg.GetNodeInfo(name) for name
3089
                           in self.cfg.GetNodeList()]
3090
    return
3091

    
3092
  def Exec(self, feedback_fn):
3093
    """Compute and return the list of nodes.
3094

3095
    """
3096

    
3097
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3098
             in self.cfg.GetInstanceList()]
3099
    result = []
3100
    for node in self.wanted_nodes:
3101
      result.append((node.name, node.primary_ip, node.secondary_ip,
3102
                     [inst.name for inst in ilist
3103
                      if inst.primary_node == node.name],
3104
                     [inst.name for inst in ilist
3105
                      if node.name in inst.secondary_nodes],
3106
                     ))
3107
    return result
3108

    
3109

    
3110
class LUSetInstanceParms(LogicalUnit):
3111
  """Modifies an instances's parameters.
3112

3113
  """
3114
  HPATH = "instance-modify"
3115
  HTYPE = constants.HTYPE_INSTANCE
3116
  _OP_REQP = ["instance_name"]
3117

    
3118
  def BuildHooksEnv(self):
3119
    """Build hooks env.
3120

3121
    This runs on the master, primary and secondaries.
3122

3123
    """
3124
    env = {
3125
      "INSTANCE_NAME": self.op.instance_name,
3126
      }
3127
    if self.mem:
3128
      env["MEM_SIZE"] = self.mem
3129
    if self.vcpus:
3130
      env["VCPUS"] = self.vcpus
3131
    if self.do_ip:
3132
      env["INSTANCE_IP"] = self.ip
3133
    if self.bridge:
3134
      env["BRIDGE"] = self.bridge
3135

    
3136
    nl = [self.sstore.GetMasterNode(),
3137
          self.instance.primary_node] + list(self.instance.secondary_nodes)
3138

    
3139
    return env, nl, nl
3140

    
3141
  def CheckPrereq(self):
3142
    """Check prerequisites.
3143

3144
    This only checks the instance list against the existing names.
3145

3146
    """
3147
    self.mem = getattr(self.op, "mem", None)
3148
    self.vcpus = getattr(self.op, "vcpus", None)
3149
    self.ip = getattr(self.op, "ip", None)
3150
    self.bridge = getattr(self.op, "bridge", None)
3151
    if [self.mem, self.vcpus, self.ip, self.bridge].count(None) == 4:
3152
      raise errors.OpPrereqError, ("No changes submitted")
3153
    if self.mem is not None:
3154
      try:
3155
        self.mem = int(self.mem)
3156
      except ValueError, err:
3157
        raise errors.OpPrereqError, ("Invalid memory size: %s" % str(err))
3158
    if self.vcpus is not None:
3159
      try:
3160
        self.vcpus = int(self.vcpus)
3161
      except ValueError, err:
3162
        raise errors.OpPrereqError, ("Invalid vcpus number: %s" % str(err))
3163
    if self.ip is not None:
3164
      self.do_ip = True
3165
      if self.ip.lower() == "none":
3166
        self.ip = None
3167
      else:
3168
        if not utils.IsValidIP(self.ip):
3169
          raise errors.OpPrereqError, ("Invalid IP address '%s'." % self.ip)
3170
    else:
3171
      self.do_ip = False
3172

    
3173
    instance = self.cfg.GetInstanceInfo(
3174
      self.cfg.ExpandInstanceName(self.op.instance_name))
3175
    if instance is None:
3176
      raise errors.OpPrereqError, ("No such instance name '%s'" %
3177
                                   self.op.instance_name)
3178
    self.op.instance_name = instance.name
3179
    self.instance = instance
3180
    return
3181

    
3182
  def Exec(self, feedback_fn):
3183
    """Modifies an instance.
3184

3185
    All parameters take effect only at the next restart of the instance.
3186
    """
3187
    result = []
3188
    instance = self.instance
3189
    if self.mem:
3190
      instance.memory = self.mem
3191
      result.append(("mem", self.mem))
3192
    if self.vcpus:
3193
      instance.vcpus = self.vcpus
3194
      result.append(("vcpus",  self.vcpus))
3195
    if self.do_ip:
3196
      instance.nics[0].ip = self.ip
3197
      result.append(("ip", self.ip))
3198
    if self.bridge:
3199
      instance.nics[0].bridge = self.bridge
3200
      result.append(("bridge", self.bridge))
3201

    
3202
    self.cfg.AddInstance(instance)
3203

    
3204
    return result
3205

    
3206

    
3207
class LUQueryExports(NoHooksLU):
3208
  """Query the exports list
3209

3210
  """
3211
  _OP_REQP = []
3212

    
3213
  def CheckPrereq(self):
3214
    """Check that the nodelist contains only existing nodes.
3215

3216
    """
3217
    nodes = getattr(self.op, "nodes", None)
3218
    if not nodes:
3219
      self.op.nodes = self.cfg.GetNodeList()
3220
    else:
3221
      expnodes = [self.cfg.ExpandNodeName(node) for node in nodes]
3222
      if expnodes.count(None) > 0:
3223
        raise errors.OpPrereqError, ("At least one of the given nodes %s"
3224
                                     " is unknown" % self.op.nodes)
3225
      self.op.nodes = expnodes
3226

    
3227
  def Exec(self, feedback_fn):
3228

    
3229
    """Compute the list of all the exported system images.
3230

3231
    Returns:
3232
      a dictionary with the structure node->(export-list)
3233
      where export-list is a list of the instances exported on
3234
      that node.
3235

3236
    """
3237
    return rpc.call_export_list(self.op.nodes)
3238

    
3239

    
3240
class LUExportInstance(LogicalUnit):
3241
  """Export an instance to an image in the cluster.
3242

3243
  """
3244
  HPATH = "instance-export"
3245
  HTYPE = constants.HTYPE_INSTANCE
3246
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
3247

    
3248
  def BuildHooksEnv(self):
3249
    """Build hooks env.
3250

3251
    This will run on the master, primary node and target node.
3252

3253
    """
3254
    env = {
3255
      "INSTANCE_NAME": self.op.instance_name,
3256
      "EXPORT_NODE": self.op.target_node,
3257
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
3258
      }
3259
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
3260
          self.op.target_node]
3261
    return env, nl, nl
3262

    
3263
  def CheckPrereq(self):
3264
    """Check prerequisites.
3265

3266
    This checks that the instance name is a valid one.
3267

3268
    """
3269
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
3270
    self.instance = self.cfg.GetInstanceInfo(instance_name)
3271
    if self.instance is None:
3272
      raise errors.OpPrereqError, ("Instance '%s' not found" %
3273
                                   self.op.instance_name)
3274

    
3275
    # node verification
3276
    dst_node_short = self.cfg.ExpandNodeName(self.op.target_node)
3277
    self.dst_node = self.cfg.GetNodeInfo(dst_node_short)
3278

    
3279
    if self.dst_node is None:
3280
      raise errors.OpPrereqError, ("Destination node '%s' is uknown." %
3281
                                   self.op.target_node)
3282
    self.op.target_node = self.dst_node.name
3283

    
3284
  def Exec(self, feedback_fn):
3285
    """Export an instance to an image in the cluster.
3286

3287
    """
3288
    instance = self.instance
3289
    dst_node = self.dst_node
3290
    src_node = instance.primary_node
3291
    # shutdown the instance, unless requested not to do so
3292
    if self.op.shutdown:
3293
      op = opcodes.OpShutdownInstance(instance_name=instance.name)
3294
      self.processor.ChainOpCode(op, feedback_fn)
3295

    
3296
    vgname = self.cfg.GetVGName()
3297

    
3298
    snap_disks = []
3299

    
3300
    try:
3301
      for disk in instance.disks:
3302
        if disk.iv_name == "sda":
3303
          # new_dev_name will be a snapshot of an lvm leaf of the one we passed
3304
          new_dev_name = rpc.call_blockdev_snapshot(src_node, disk)
3305

    
3306
          if not new_dev_name:
3307
            logger.Error("could not snapshot block device %s on node %s" %
3308
                         (disk.logical_id[1], src_node))
3309
          else:
3310
            new_dev = objects.Disk(dev_type="lvm", size=disk.size,
3311
                                      logical_id=(vgname, new_dev_name),
3312
                                      physical_id=(vgname, new_dev_name),
3313
                                      iv_name=disk.iv_name)
3314
            snap_disks.append(new_dev)
3315

    
3316
    finally:
3317
      if self.op.shutdown:
3318
        op = opcodes.OpStartupInstance(instance_name=instance.name,
3319
                                       force=False)
3320
        self.processor.ChainOpCode(op, feedback_fn)
3321

    
3322
    # TODO: check for size
3323

    
3324
    for dev in snap_disks:
3325
      if not rpc.call_snapshot_export(src_node, dev, dst_node.name,
3326
                                           instance):
3327
        logger.Error("could not export block device %s from node"
3328
                     " %s to node %s" %
3329
                     (dev.logical_id[1], src_node, dst_node.name))
3330
      if not rpc.call_blockdev_remove(src_node, dev):
3331
        logger.Error("could not remove snapshot block device %s from"
3332
                     " node %s" % (dev.logical_id[1], src_node))
3333

    
3334
    if not rpc.call_finalize_export(dst_node.name, instance, snap_disks):
3335
      logger.Error("could not finalize export for instance %s on node %s" %
3336
                   (instance.name, dst_node.name))
3337

    
3338
    nodelist = self.cfg.GetNodeList()
3339
    nodelist.remove(dst_node.name)
3340

    
3341
    # on one-node clusters nodelist will be empty after the removal
3342
    # if we proceed the backup would be removed because OpQueryExports
3343
    # substitutes an empty list with the full cluster node list.
3344
    if nodelist:
3345
      op = opcodes.OpQueryExports(nodes=nodelist)
3346
      exportlist = self.processor.ChainOpCode(op, feedback_fn)
3347
      for node in exportlist:
3348
        if instance.name in exportlist[node]:
3349
          if not rpc.call_export_remove(node, instance.name):
3350
            logger.Error("could not remove older export for instance %s"
3351
                         " on node %s" % (instance.name, node))