Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ cb91d46e

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 _GetWantedNodes(lu, nodes):
168
  """Returns list of checked and expanded nodes.
169

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

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

    
177
  if nodes:
178
    wanted_nodes = []
179

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

    
186
    return wanted_nodes
187
  else:
188
    return [lu.cfg.GetNodeInfo(name) for name in lu.cfg.GetNodeList()]
189

    
190

    
191
def _CheckOutputFields(static, dynamic, selected):
192
  """Checks whether all selected fields are valid.
193

194
  Args:
195
    static: Static fields
196
    dynamic: Dynamic fields
197

198
  """
199
  static_fields = frozenset(static)
200
  dynamic_fields = frozenset(dynamic)
201

    
202
  all_fields = static_fields | dynamic_fields
203

    
204
  if not all_fields.issuperset(selected):
205
    raise errors.OpPrereqError, ("Unknown output fields selected: %s"
206
                                 % ",".join(frozenset(selected).
207
                                            difference(all_fields)))
208

    
209

    
210
def _UpdateEtcHosts(fullnode, ip):
211
  """Ensure a node has a correct entry in /etc/hosts.
212

213
  Args:
214
    fullnode - Fully qualified domain name of host. (str)
215
    ip       - IPv4 address of host (str)
216

217
  """
218
  node = fullnode.split(".", 1)[0]
219

    
220
  f = open('/etc/hosts', 'r+')
221

    
222
  inthere = False
223

    
224
  save_lines = []
225
  add_lines = []
226
  removed = False
227

    
228
  while True:
229
    rawline = f.readline()
230

    
231
    if not rawline:
232
      # End of file
233
      break
234

    
235
    line = rawline.split('\n')[0]
236

    
237
    # Strip off comments
238
    line = line.split('#')[0]
239

    
240
    if not line:
241
      # Entire line was comment, skip
242
      save_lines.append(rawline)
243
      continue
244

    
245
    fields = line.split()
246

    
247
    haveall = True
248
    havesome = False
249
    for spec in [ ip, fullnode, node ]:
250
      if spec not in fields:
251
        haveall = False
252
      if spec in fields:
253
        havesome = True
254

    
255
    if haveall:
256
      inthere = True
257
      save_lines.append(rawline)
258
      continue
259

    
260
    if havesome and not haveall:
261
      # Line (old, or manual?) which is missing some.  Remove.
262
      removed = True
263
      continue
264

    
265
    save_lines.append(rawline)
266

    
267
  if not inthere:
268
    add_lines.append('%s\t%s %s\n' % (ip, fullnode, node))
269

    
270
  if removed:
271
    if add_lines:
272
      save_lines = save_lines + add_lines
273

    
274
    # We removed a line, write a new file and replace old.
275
    fd, tmpname = tempfile.mkstemp('tmp', 'hosts_', '/etc')
276
    newfile = os.fdopen(fd, 'w')
277
    newfile.write(''.join(save_lines))
278
    newfile.close()
279
    os.rename(tmpname, '/etc/hosts')
280

    
281
  elif add_lines:
282
    # Simply appending a new line will do the trick.
283
    f.seek(0, 2)
284
    for add in add_lines:
285
      f.write(add)
286

    
287
  f.close()
288

    
289

    
290
def _UpdateKnownHosts(fullnode, ip, pubkey):
291
  """Ensure a node has a correct known_hosts entry.
292

293
  Args:
294
    fullnode - Fully qualified domain name of host. (str)
295
    ip       - IPv4 address of host (str)
296
    pubkey   - the public key of the cluster
297

298
  """
299
  if os.path.exists('/etc/ssh/ssh_known_hosts'):
300
    f = open('/etc/ssh/ssh_known_hosts', 'r+')
301
  else:
302
    f = open('/etc/ssh/ssh_known_hosts', 'w+')
303

    
304
  inthere = False
305

    
306
  save_lines = []
307
  add_lines = []
308
  removed = False
309

    
310
  while True:
311
    rawline = f.readline()
312
    logger.Debug('read %s' % (repr(rawline),))
313

    
314
    if not rawline:
315
      # End of file
316
      break
317

    
318
    line = rawline.split('\n')[0]
319

    
320
    parts = line.split(' ')
321
    fields = parts[0].split(',')
322
    key = parts[2]
323

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

    
332
    logger.Debug("key, pubkey = %s." % (repr((key, pubkey)),))
333
    if haveall and key == pubkey:
334
      inthere = True
335
      save_lines.append(rawline)
336
      logger.Debug("Keeping known_hosts '%s'." % (repr(rawline),))
337
      continue
338

    
339
    if havesome and (not haveall or key != pubkey):
340
      removed = True
341
      logger.Debug("Discarding known_hosts '%s'." % (repr(rawline),))
342
      continue
343

    
344
    save_lines.append(rawline)
345

    
346
  if not inthere:
347
    add_lines.append('%s,%s ssh-rsa %s\n' % (fullnode, ip, pubkey))
348
    logger.Debug("Adding known_hosts '%s'." % (repr(add_lines[-1]),))
349

    
350
  if removed:
351
    save_lines = save_lines + add_lines
352

    
353
    # Write a new file and replace old.
354
    fd, tmpname = tempfile.mkstemp('tmp', 'ssh_known_hosts_', '/etc/ssh')
355
    newfile = os.fdopen(fd, 'w')
356
    newfile.write(''.join(save_lines))
357
    newfile.close()
358
    logger.Debug("Wrote new known_hosts.")
359
    os.rename(tmpname, '/etc/ssh/ssh_known_hosts')
360

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

    
367
  f.close()
368

    
369

    
370
def _HasValidVG(vglist, vgname):
371
  """Checks if the volume group list is valid.
372

373
  A non-None return value means there's an error, and the return value
374
  is the error message.
375

376
  """
377
  vgsize = vglist.get(vgname, None)
378
  if vgsize is None:
379
    return "volume group '%s' missing" % vgname
380
  elif vgsize < 20480:
381
    return ("volume group '%s' too small (20480MiB required, %dMib found)" %
382
            (vgname, vgsize))
383
  return None
384

    
385

    
386
def _InitSSHSetup(node):
387
  """Setup the SSH configuration for the cluster.
388

389

390
  This generates a dsa keypair for root, adds the pub key to the
391
  permitted hosts and adds the hostkey to its own known hosts.
392

393
  Args:
394
    node: the name of this host as a fqdn
395

396
  """
397
  utils.RemoveFile('/root/.ssh/known_hosts')
398

    
399
  if os.path.exists('/root/.ssh/id_dsa'):
400
    utils.CreateBackup('/root/.ssh/id_dsa')
401
  if os.path.exists('/root/.ssh/id_dsa.pub'):
402
    utils.CreateBackup('/root/.ssh/id_dsa.pub')
403

    
404
  utils.RemoveFile('/root/.ssh/id_dsa')
405
  utils.RemoveFile('/root/.ssh/id_dsa.pub')
406

    
407
  result = utils.RunCmd(["ssh-keygen", "-t", "dsa",
408
                         "-f", "/root/.ssh/id_dsa",
409
                         "-q", "-N", ""])
410
  if result.failed:
411
    raise errors.OpExecError, ("could not generate ssh keypair, error %s" %
412
                               result.output)
413

    
414
  f = open('/root/.ssh/id_dsa.pub', 'r')
415
  try:
416
    utils.AddAuthorizedKey('/root/.ssh/authorized_keys', f.read(8192))
417
  finally:
418
    f.close()
419

    
420

    
421
def _InitGanetiServerSetup(ss):
422
  """Setup the necessary configuration for the initial node daemon.
423

424
  This creates the nodepass file containing the shared password for
425
  the cluster and also generates the SSL certificate.
426

427
  """
428
  # Create pseudo random password
429
  randpass = sha.new(os.urandom(64)).hexdigest()
430
  # and write it into sstore
431
  ss.SetKey(ss.SS_NODED_PASS, randpass)
432

    
433
  result = utils.RunCmd(["openssl", "req", "-new", "-newkey", "rsa:1024",
434
                         "-days", str(365*5), "-nodes", "-x509",
435
                         "-keyout", constants.SSL_CERT_FILE,
436
                         "-out", constants.SSL_CERT_FILE, "-batch"])
437
  if result.failed:
438
    raise errors.OpExecError, ("could not generate server ssl cert, command"
439
                               " %s had exitcode %s and error message %s" %
440
                               (result.cmd, result.exit_code, result.output))
441

    
442
  os.chmod(constants.SSL_CERT_FILE, 0400)
443

    
444
  result = utils.RunCmd([constants.NODE_INITD_SCRIPT, "restart"])
445

    
446
  if result.failed:
447
    raise errors.OpExecError, ("could not start the node daemon, command %s"
448
                               " had exitcode %s and error %s" %
449
                               (result.cmd, result.exit_code, result.output))
450

    
451

    
452
class LUInitCluster(LogicalUnit):
453
  """Initialise the cluster.
454

455
  """
456
  HPATH = "cluster-init"
457
  HTYPE = constants.HTYPE_CLUSTER
458
  _OP_REQP = ["cluster_name", "hypervisor_type", "vg_name", "mac_prefix",
459
              "def_bridge", "master_netdev"]
460
  REQ_CLUSTER = False
461

    
462
  def BuildHooksEnv(self):
463
    """Build hooks env.
464

465
    Notes: Since we don't require a cluster, we must manually add
466
    ourselves in the post-run node list.
467

468
    """
469

    
470
    env = {"CLUSTER": self.op.cluster_name,
471
           "MASTER": self.hostname['hostname_full']}
472
    return env, [], [self.hostname['hostname_full']]
473

    
474
  def CheckPrereq(self):
475
    """Verify that the passed name is a valid one.
476

477
    """
478
    if config.ConfigWriter.IsCluster():
479
      raise errors.OpPrereqError, ("Cluster is already initialised")
480

    
481
    hostname_local = socket.gethostname()
482
    self.hostname = hostname = utils.LookupHostname(hostname_local)
483
    if not hostname:
484
      raise errors.OpPrereqError, ("Cannot resolve my own hostname ('%s')" %
485
                                   hostname_local)
486

    
487
    self.clustername = clustername = utils.LookupHostname(self.op.cluster_name)
488
    if not clustername:
489
      raise errors.OpPrereqError, ("Cannot resolve given cluster name ('%s')"
490
                                   % self.op.cluster_name)
491

    
492
    result = utils.RunCmd(["fping", "-S127.0.0.1", "-q", hostname['ip']])
493
    if result.failed:
494
      raise errors.OpPrereqError, ("Inconsistency: this host's name resolves"
495
                                   " to %s,\nbut this ip address does not"
496
                                   " belong to this host."
497
                                   " Aborting." % hostname['ip'])
498

    
499
    secondary_ip = getattr(self.op, "secondary_ip", None)
500
    if secondary_ip and not utils.IsValidIP(secondary_ip):
501
      raise errors.OpPrereqError, ("Invalid secondary ip given")
502
    if secondary_ip and secondary_ip != hostname['ip']:
503
      result = utils.RunCmd(["fping", "-S127.0.0.1", "-q", secondary_ip])
504
      if result.failed:
505
        raise errors.OpPrereqError, ("You gave %s as secondary IP,\n"
506
                                     "but it does not belong to this host." %
507
                                     secondary_ip)
508
    self.secondary_ip = secondary_ip
509

    
510
    # checks presence of the volume group given
511
    vgstatus = _HasValidVG(utils.ListVolumeGroups(), self.op.vg_name)
512

    
513
    if vgstatus:
514
      raise errors.OpPrereqError, ("Error: %s" % vgstatus)
515

    
516
    if not re.match("^[0-9a-z]{2}:[0-9a-z]{2}:[0-9a-z]{2}$",
517
                    self.op.mac_prefix):
518
      raise errors.OpPrereqError, ("Invalid mac prefix given '%s'" %
519
                                   self.op.mac_prefix)
520

    
521
    if self.op.hypervisor_type not in hypervisor.VALID_HTYPES:
522
      raise errors.OpPrereqError, ("Invalid hypervisor type given '%s'" %
523
                                   self.op.hypervisor_type)
524

    
525
    result = utils.RunCmd(["ip", "link", "show", "dev", self.op.master_netdev])
526
    if result.failed:
527
      raise errors.OpPrereqError, ("Invalid master netdev given (%s): '%s'" %
528
                                   (self.op.master_netdev, result.output))
529

    
530
  def Exec(self, feedback_fn):
531
    """Initialize the cluster.
532

533
    """
534
    clustername = self.clustername
535
    hostname = self.hostname
536

    
537
    # set up the simple store
538
    ss = ssconf.SimpleStore()
539
    ss.SetKey(ss.SS_HYPERVISOR, self.op.hypervisor_type)
540
    ss.SetKey(ss.SS_MASTER_NODE, hostname['hostname_full'])
541
    ss.SetKey(ss.SS_MASTER_IP, clustername['ip'])
542
    ss.SetKey(ss.SS_MASTER_NETDEV, self.op.master_netdev)
543

    
544
    # set up the inter-node password and certificate
545
    _InitGanetiServerSetup(ss)
546

    
547
    # start the master ip
548
    rpc.call_node_start_master(hostname['hostname_full'])
549

    
550
    # set up ssh config and /etc/hosts
551
    f = open('/etc/ssh/ssh_host_rsa_key.pub', 'r')
552
    try:
553
      sshline = f.read()
554
    finally:
555
      f.close()
556
    sshkey = sshline.split(" ")[1]
557

    
558
    _UpdateEtcHosts(hostname['hostname_full'],
559
                    hostname['ip'],
560
                    )
561

    
562
    _UpdateKnownHosts(hostname['hostname_full'],
563
                      hostname['ip'],
564
                      sshkey,
565
                      )
566

    
567
    _InitSSHSetup(hostname['hostname'])
568

    
569
    # init of cluster config file
570
    cfgw = config.ConfigWriter()
571
    cfgw.InitConfig(hostname['hostname'], hostname['ip'], self.secondary_ip,
572
                    clustername['hostname'], sshkey, self.op.mac_prefix,
573
                    self.op.vg_name, self.op.def_bridge)
574

    
575

    
576
class LUDestroyCluster(NoHooksLU):
577
  """Logical unit for destroying the cluster.
578

579
  """
580
  _OP_REQP = []
581

    
582
  def CheckPrereq(self):
583
    """Check prerequisites.
584

585
    This checks whether the cluster is empty.
586

587
    Any errors are signalled by raising errors.OpPrereqError.
588

589
    """
590
    master = self.sstore.GetMasterNode()
591

    
592
    nodelist = self.cfg.GetNodeList()
593
    if len(nodelist) > 0 and nodelist != [master]:
594
      raise errors.OpPrereqError, ("There are still %d node(s) in "
595
                                   "this cluster." % (len(nodelist) - 1))
596

    
597
  def Exec(self, feedback_fn):
598
    """Destroys the cluster.
599

600
    """
601
    utils.CreateBackup('/root/.ssh/id_dsa')
602
    utils.CreateBackup('/root/.ssh/id_dsa.pub')
603
    rpc.call_node_leave_cluster(self.sstore.GetMasterNode())
604

    
605

    
606
class LUVerifyCluster(NoHooksLU):
607
  """Verifies the cluster status.
608

609
  """
610
  _OP_REQP = []
611

    
612
  def _VerifyNode(self, node, file_list, local_cksum, vglist, node_result,
613
                  remote_version, feedback_fn):
614
    """Run multiple tests against a node.
615

616
    Test list:
617
      - compares ganeti version
618
      - checks vg existance and size > 20G
619
      - checks config file checksum
620
      - checks ssh to other nodes
621

622
    Args:
623
      node: name of the node to check
624
      file_list: required list of files
625
      local_cksum: dictionary of local files and their checksums
626
    """
627
    # compares ganeti version
628
    local_version = constants.PROTOCOL_VERSION
629
    if not remote_version:
630
      feedback_fn(" - ERROR: connection to %s failed" % (node))
631
      return True
632

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

    
638
    # checks vg existance and size > 20G
639

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

    
651
    # checks config file checksum
652
    # checks ssh to any
653

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

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

    
681
  def _VerifyInstance(self, instance, node_vol_is, node_instance, feedback_fn):
682
    """Verify an instance.
683

684
    This function checks to see if the required block devices are
685
    available on the instance's node.
686

687
    """
688
    bad = False
689

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

    
696
    instanceconfig = self.cfg.GetInstanceInfo(instance)
697
    node_current = instanceconfig.primary_node
698

    
699
    node_vol_should = {}
700
    instanceconfig.MapLVsByNode(node_vol_should)
701

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

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

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

    
722
    return not bad
723

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

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

730
    """
731
    bad = False
732

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

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

744
    This checks what instances are running but unknown to the cluster.
745

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

    
756
  def CheckPrereq(self):
757
    """Check prerequisites.
758

759
    This has no prerequisites.
760

761
    """
762
    pass
763

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

767
    """
768
    bad = False
769
    feedback_fn("* Verifying global settings")
770
    self.cfg.VerifyConfig()
771

    
772
    master = self.sstore.GetMasterNode()
773
    vg_name = self.cfg.GetVGName()
774
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
775
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
776
    node_volume = {}
777
    node_instance = {}
778

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

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

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

    
805
      # node_volume
806
      volumeinfo = all_volumeinfo[node]
807

    
808
      if type(volumeinfo) != dict:
809
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
810
        bad = True
811
        continue
812

    
813
      node_volume[node] = volumeinfo
814

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

    
822
      node_instance[node] = nodeinstance
823

    
824
    node_vol_should = {}
825

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

    
832
      inst_config = self.cfg.GetInstanceInfo(instance)
833

    
834
      inst_config.MapLVsByNode(node_vol_should)
835

    
836
    feedback_fn("* Verifying orphan volumes")
837
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
838
                                       feedback_fn)
839
    bad = bad or result
840

    
841
    feedback_fn("* Verifying remaining instances")
842
    result = self._VerifyOrphanInstances(instancelist, node_instance,
843
                                         feedback_fn)
844
    bad = bad or result
845

    
846
    return int(bad)
847

    
848

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

852
  """
853
  if not instance.disks:
854
    return True
855

    
856
  if not oneshot:
857
    logger.ToStdout("Waiting for instance %s to sync disks." % instance.name)
858

    
859
  node = instance.primary_node
860

    
861
  for dev in instance.disks:
862
    cfgw.SetDiskID(dev, node)
863

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

    
899
    if unlock:
900
      utils.Unlock('cmd')
901
    try:
902
      time.sleep(min(60, max_time))
903
    finally:
904
      if unlock:
905
        utils.Lock('cmd')
906

    
907
  if done:
908
    logger.ToStdout("Instance %s's disks are in sync." % instance.name)
909
  return not cumul_degraded
910

    
911

    
912
def _CheckDiskConsistency(cfgw, dev, node, on_primary):
913
  """Check that mirrors are not degraded.
914

915
  """
916

    
917
  cfgw.SetDiskID(dev, node)
918

    
919
  result = True
920
  if on_primary or dev.AssembleOnSecondary():
921
    rstats = rpc.call_blockdev_find(node, dev)
922
    if not rstats:
923
      logger.ToStderr("Can't get any data from node %s" % node)
924
      result = False
925
    else:
926
      result = result and (not rstats[5])
927
  if dev.children:
928
    for child in dev.children:
929
      result = result and _CheckDiskConsistency(cfgw, child, node, on_primary)
930

    
931
  return result
932

    
933

    
934
class LUDiagnoseOS(NoHooksLU):
935
  """Logical unit for OS diagnose/query.
936

937
  """
938
  _OP_REQP = []
939

    
940
  def CheckPrereq(self):
941
    """Check prerequisites.
942

943
    This always succeeds, since this is a pure query LU.
944

945
    """
946
    return
947

    
948
  def Exec(self, feedback_fn):
949
    """Compute the list of OSes.
950

951
    """
952
    node_list = self.cfg.GetNodeList()
953
    node_data = rpc.call_os_diagnose(node_list)
954
    if node_data == False:
955
      raise errors.OpExecError, "Can't gather the list of OSes"
956
    return node_data
957

    
958

    
959
class LURemoveNode(LogicalUnit):
960
  """Logical unit for removing a node.
961

962
  """
963
  HPATH = "node-remove"
964
  HTYPE = constants.HTYPE_NODE
965
  _OP_REQP = ["node_name"]
966

    
967
  def BuildHooksEnv(self):
968
    """Build hooks env.
969

970
    This doesn't run on the target node in the pre phase as a failed
971
    node would not allows itself to run.
972

973
    """
974
    all_nodes = self.cfg.GetNodeList()
975
    all_nodes.remove(self.op.node_name)
976
    return {"NODE_NAME": self.op.node_name}, all_nodes, all_nodes
977

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

981
    This checks:
982
     - the node exists in the configuration
983
     - it does not have primary or secondary instances
984
     - it's not the master
985

986
    Any errors are signalled by raising errors.OpPrereqError.
987

988
    """
989

    
990
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
991
    if node is None:
992
      logger.Error("Error: Node '%s' is unknown." % self.op.node_name)
993
      return 1
994

    
995
    instance_list = self.cfg.GetInstanceList()
996

    
997
    masternode = self.sstore.GetMasterNode()
998
    if node.name == masternode:
999
      raise errors.OpPrereqError, ("Node is the master node,"
1000
                                   " you need to failover first.")
1001

    
1002
    for instance_name in instance_list:
1003
      instance = self.cfg.GetInstanceInfo(instance_name)
1004
      if node.name == instance.primary_node:
1005
        raise errors.OpPrereqError, ("Instance %s still running on the node,"
1006
                                     " please remove first." % instance_name)
1007
      if node.name in instance.secondary_nodes:
1008
        raise errors.OpPrereqError, ("Instance %s has node as a secondary,"
1009
                                     " please remove first." % instance_name)
1010
    self.op.node_name = node.name
1011
    self.node = node
1012

    
1013
  def Exec(self, feedback_fn):
1014
    """Removes the node from the cluster.
1015

1016
    """
1017
    node = self.node
1018
    logger.Info("stopping the node daemon and removing configs from node %s" %
1019
                node.name)
1020

    
1021
    rpc.call_node_leave_cluster(node.name)
1022

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

    
1025
    logger.Info("Removing node %s from config" % node.name)
1026

    
1027
    self.cfg.RemoveNode(node.name)
1028

    
1029

    
1030
class LUQueryNodes(NoHooksLU):
1031
  """Logical unit for querying nodes.
1032

1033
  """
1034
  _OP_REQP = ["output_fields"]
1035

    
1036
  def CheckPrereq(self):
1037
    """Check prerequisites.
1038

1039
    This checks that the fields required are valid output fields.
1040

1041
    """
1042
    self.dynamic_fields = frozenset(["dtotal", "dfree",
1043
                                     "mtotal", "mnode", "mfree"])
1044

    
1045
    _CheckOutputFields(static=["name", "pinst", "sinst", "pip", "sip"],
1046
                       dynamic=self.dynamic_fields,
1047
                       selected=self.op.output_fields)
1048

    
1049

    
1050
  def Exec(self, feedback_fn):
1051
    """Computes the list of nodes and their attributes.
1052

1053
    """
1054
    nodenames = utils.NiceSort(self.cfg.GetNodeList())
1055
    nodelist = [self.cfg.GetNodeInfo(name) for name in nodenames]
1056

    
1057

    
1058
    # begin data gathering
1059

    
1060
    if self.dynamic_fields.intersection(self.op.output_fields):
1061
      live_data = {}
1062
      node_data = rpc.call_node_info(nodenames, self.cfg.GetVGName())
1063
      for name in nodenames:
1064
        nodeinfo = node_data.get(name, None)
1065
        if nodeinfo:
1066
          live_data[name] = {
1067
            "mtotal": utils.TryConvert(int, nodeinfo['memory_total']),
1068
            "mnode": utils.TryConvert(int, nodeinfo['memory_dom0']),
1069
            "mfree": utils.TryConvert(int, nodeinfo['memory_free']),
1070
            "dtotal": utils.TryConvert(int, nodeinfo['vg_size']),
1071
            "dfree": utils.TryConvert(int, nodeinfo['vg_free']),
1072
            }
1073
        else:
1074
          live_data[name] = {}
1075
    else:
1076
      live_data = dict.fromkeys(nodenames, {})
1077

    
1078
    node_to_primary = dict.fromkeys(nodenames, 0)
1079
    node_to_secondary = dict.fromkeys(nodenames, 0)
1080

    
1081
    if "pinst" in self.op.output_fields or "sinst" in self.op.output_fields:
1082
      instancelist = self.cfg.GetInstanceList()
1083

    
1084
      for instance in instancelist:
1085
        instanceinfo = self.cfg.GetInstanceInfo(instance)
1086
        node_to_primary[instanceinfo.primary_node] += 1
1087
        for secnode in instanceinfo.secondary_nodes:
1088
          node_to_secondary[secnode] += 1
1089

    
1090
    # end data gathering
1091

    
1092
    output = []
1093
    for node in nodelist:
1094
      node_output = []
1095
      for field in self.op.output_fields:
1096
        if field == "name":
1097
          val = node.name
1098
        elif field == "pinst":
1099
          val = node_to_primary[node.name]
1100
        elif field == "sinst":
1101
          val = node_to_secondary[node.name]
1102
        elif field == "pip":
1103
          val = node.primary_ip
1104
        elif field == "sip":
1105
          val = node.secondary_ip
1106
        elif field in self.dynamic_fields:
1107
          val = live_data[node.name].get(field, "?")
1108
        else:
1109
          raise errors.ParameterError, field
1110
        val = str(val)
1111
        node_output.append(val)
1112
      output.append(node_output)
1113

    
1114
    return output
1115

    
1116

    
1117
class LUQueryNodeVolumes(NoHooksLU):
1118
  """Logical unit for getting volumes on node(s).
1119

1120
  """
1121
  _OP_REQP = ["nodes", "output_fields"]
1122

    
1123
  def CheckPrereq(self):
1124
    """Check prerequisites.
1125

1126
    This checks that the fields required are valid output fields.
1127

1128
    """
1129
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1130

    
1131
    _CheckOutputFields(static=["node"],
1132
                       dynamic=["phys", "vg", "name", "size", "instance"],
1133
                       selected=self.op.output_fields)
1134

    
1135

    
1136
  def Exec(self, feedback_fn):
1137
    """Computes the list of nodes and their attributes.
1138

1139
    """
1140
    nodenames = utils.NiceSort([node.name for node in self.nodes])
1141
    volumes = rpc.call_node_volumes(nodenames)
1142

    
1143
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1144
             in self.cfg.GetInstanceList()]
1145

    
1146
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1147

    
1148
    output = []
1149
    for node in nodenames:
1150
      node_vols = volumes[node][:]
1151
      node_vols.sort(key=lambda vol: vol['dev'])
1152

    
1153
      for vol in node_vols:
1154
        node_output = []
1155
        for field in self.op.output_fields:
1156
          if field == "node":
1157
            val = node
1158
          elif field == "phys":
1159
            val = vol['dev']
1160
          elif field == "vg":
1161
            val = vol['vg']
1162
          elif field == "name":
1163
            val = vol['name']
1164
          elif field == "size":
1165
            val = int(float(vol['size']))
1166
          elif field == "instance":
1167
            for inst in ilist:
1168
              if node not in lv_by_node[inst]:
1169
                continue
1170
              if vol['name'] in lv_by_node[inst][node]:
1171
                val = inst.name
1172
                break
1173
            else:
1174
              val = '-'
1175
          else:
1176
            raise errors.ParameterError, field
1177
          node_output.append(str(val))
1178

    
1179
        output.append(node_output)
1180

    
1181
    return output
1182

    
1183

    
1184
def _CheckNodesDirs(node_list, paths):
1185
  """Verify if the given nodes have the same files.
1186

1187
  Args:
1188
    node_list: the list of node names to check
1189
    paths: the list of directories to checksum and compare
1190

1191
  Returns:
1192
    list of (node, different_file, message); if empty, the files are in sync
1193

1194
  """
1195
  file_names = []
1196
  for dir_name in paths:
1197
    flist = [os.path.join(dir_name, name) for name in os.listdir(dir_name)]
1198
    flist = [name for name in flist if os.path.isfile(name)]
1199
    file_names.extend(flist)
1200

    
1201
  local_checksums = utils.FingerprintFiles(file_names)
1202

    
1203
  results = []
1204
  verify_params = {'filelist': file_names}
1205
  all_node_results = rpc.call_node_verify(node_list, verify_params)
1206
  for node_name in node_list:
1207
    node_result = all_node_results.get(node_name, False)
1208
    if not node_result or 'filelist' not in node_result:
1209
      results.append((node_name, "'all files'", "node communication error"))
1210
      continue
1211
    remote_checksums = node_result['filelist']
1212
    for fname in local_checksums:
1213
      if fname not in remote_checksums:
1214
        results.append((node_name, fname, "missing file"))
1215
      elif remote_checksums[fname] != local_checksums[fname]:
1216
        results.append((node_name, fname, "wrong checksum"))
1217
  return results
1218

    
1219

    
1220
class LUAddNode(LogicalUnit):
1221
  """Logical unit for adding node to the cluster.
1222

1223
  """
1224
  HPATH = "node-add"
1225
  HTYPE = constants.HTYPE_NODE
1226
  _OP_REQP = ["node_name"]
1227

    
1228
  def BuildHooksEnv(self):
1229
    """Build hooks env.
1230

1231
    This will run on all nodes before, and on all nodes + the new node after.
1232

1233
    """
1234
    env = {
1235
      "NODE_NAME": self.op.node_name,
1236
      "NODE_PIP": self.op.primary_ip,
1237
      "NODE_SIP": self.op.secondary_ip,
1238
      }
1239
    nodes_0 = self.cfg.GetNodeList()
1240
    nodes_1 = nodes_0 + [self.op.node_name, ]
1241
    return env, nodes_0, nodes_1
1242

    
1243
  def CheckPrereq(self):
1244
    """Check prerequisites.
1245

1246
    This checks:
1247
     - the new node is not already in the config
1248
     - it is resolvable
1249
     - its parameters (single/dual homed) matches the cluster
1250

1251
    Any errors are signalled by raising errors.OpPrereqError.
1252

1253
    """
1254
    node_name = self.op.node_name
1255
    cfg = self.cfg
1256

    
1257
    dns_data = utils.LookupHostname(node_name)
1258
    if not dns_data:
1259
      raise errors.OpPrereqError, ("Node %s is not resolvable" % node_name)
1260

    
1261
    node = dns_data['hostname']
1262
    primary_ip = self.op.primary_ip = dns_data['ip']
1263
    secondary_ip = getattr(self.op, "secondary_ip", None)
1264
    if secondary_ip is None:
1265
      secondary_ip = primary_ip
1266
    if not utils.IsValidIP(secondary_ip):
1267
      raise errors.OpPrereqError, ("Invalid secondary IP given")
1268
    self.op.secondary_ip = secondary_ip
1269
    node_list = cfg.GetNodeList()
1270
    if node in node_list:
1271
      raise errors.OpPrereqError, ("Node %s is already in the configuration"
1272
                                   % node)
1273

    
1274
    for existing_node_name in node_list:
1275
      existing_node = cfg.GetNodeInfo(existing_node_name)
1276
      if (existing_node.primary_ip == primary_ip or
1277
          existing_node.secondary_ip == primary_ip or
1278
          existing_node.primary_ip == secondary_ip or
1279
          existing_node.secondary_ip == secondary_ip):
1280
        raise errors.OpPrereqError, ("New node ip address(es) conflict with"
1281
                                     " existing node %s" % existing_node.name)
1282

    
1283
    # check that the type of the node (single versus dual homed) is the
1284
    # same as for the master
1285
    myself = cfg.GetNodeInfo(self.sstore.GetMasterNode())
1286
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1287
    newbie_singlehomed = secondary_ip == primary_ip
1288
    if master_singlehomed != newbie_singlehomed:
1289
      if master_singlehomed:
1290
        raise errors.OpPrereqError, ("The master has no private ip but the"
1291
                                     " new node has one")
1292
      else:
1293
        raise errors.OpPrereqError ("The master has a private ip but the"
1294
                                    " new node doesn't have one")
1295

    
1296
    # checks reachablity
1297
    command = ["fping", "-q", primary_ip]
1298
    result = utils.RunCmd(command)
1299
    if result.failed:
1300
      raise errors.OpPrereqError, ("Node not reachable by ping")
1301

    
1302
    if not newbie_singlehomed:
1303
      # check reachability from my secondary ip to newbie's secondary ip
1304
      command = ["fping", "-S%s" % myself.secondary_ip, "-q", secondary_ip]
1305
      result = utils.RunCmd(command)
1306
      if result.failed:
1307
        raise errors.OpPrereqError, ("Node secondary ip not reachable by ping")
1308

    
1309
    self.new_node = objects.Node(name=node,
1310
                                 primary_ip=primary_ip,
1311
                                 secondary_ip=secondary_ip)
1312

    
1313
  def Exec(self, feedback_fn):
1314
    """Adds the new node to the cluster.
1315

1316
    """
1317
    new_node = self.new_node
1318
    node = new_node.name
1319

    
1320
    # set up inter-node password and certificate and restarts the node daemon
1321
    gntpass = self.sstore.GetNodeDaemonPassword()
1322
    if not re.match('^[a-zA-Z0-9.]{1,64}$', gntpass):
1323
      raise errors.OpExecError, ("ganeti password corruption detected")
1324
    f = open(constants.SSL_CERT_FILE)
1325
    try:
1326
      gntpem = f.read(8192)
1327
    finally:
1328
      f.close()
1329
    # in the base64 pem encoding, neither '!' nor '.' are valid chars,
1330
    # so we use this to detect an invalid certificate; as long as the
1331
    # cert doesn't contain this, the here-document will be correctly
1332
    # parsed by the shell sequence below
1333
    if re.search('^!EOF\.', gntpem, re.MULTILINE):
1334
      raise errors.OpExecError, ("invalid PEM encoding in the SSL certificate")
1335
    if not gntpem.endswith("\n"):
1336
      raise errors.OpExecError, ("PEM must end with newline")
1337
    logger.Info("copy cluster pass to %s and starting the node daemon" % node)
1338

    
1339
    # remove first the root's known_hosts file
1340
    utils.RemoveFile("/root/.ssh/known_hosts")
1341
    # and then connect with ssh to set password and start ganeti-noded
1342
    # note that all the below variables are sanitized at this point,
1343
    # either by being constants or by the checks above
1344
    ss = self.sstore
1345
    mycommand = ("umask 077 && "
1346
                 "echo '%s' > '%s' && "
1347
                 "cat > '%s' << '!EOF.' && \n"
1348
                 "%s!EOF.\n%s restart" %
1349
                 (gntpass, ss.KeyToFilename(ss.SS_NODED_PASS),
1350
                  constants.SSL_CERT_FILE, gntpem,
1351
                  constants.NODE_INITD_SCRIPT))
1352

    
1353
    result = ssh.SSHCall(node, 'root', mycommand, batch=False, ask_key=True)
1354
    if result.failed:
1355
      raise errors.OpExecError, ("Remote command on node %s, error: %s,"
1356
                                 " output: %s" %
1357
                                 (node, result.fail_reason, result.output))
1358

    
1359
    # check connectivity
1360
    time.sleep(4)
1361

    
1362
    result = rpc.call_version([node])[node]
1363
    if result:
1364
      if constants.PROTOCOL_VERSION == result:
1365
        logger.Info("communication to node %s fine, sw version %s match" %
1366
                    (node, result))
1367
      else:
1368
        raise errors.OpExecError, ("Version mismatch master version %s,"
1369
                                   " node version %s" %
1370
                                   (constants.PROTOCOL_VERSION, result))
1371
    else:
1372
      raise errors.OpExecError, ("Cannot get version from the new node")
1373

    
1374
    # setup ssh on node
1375
    logger.Info("copy ssh key to node %s" % node)
1376
    keyarray = []
1377
    keyfiles = ["/etc/ssh/ssh_host_dsa_key", "/etc/ssh/ssh_host_dsa_key.pub",
1378
                "/etc/ssh/ssh_host_rsa_key", "/etc/ssh/ssh_host_rsa_key.pub",
1379
                "/root/.ssh/id_dsa", "/root/.ssh/id_dsa.pub"]
1380

    
1381
    for i in keyfiles:
1382
      f = open(i, 'r')
1383
      try:
1384
        keyarray.append(f.read())
1385
      finally:
1386
        f.close()
1387

    
1388
    result = rpc.call_node_add(node, keyarray[0], keyarray[1], keyarray[2],
1389
                               keyarray[3], keyarray[4], keyarray[5])
1390

    
1391
    if not result:
1392
      raise errors.OpExecError, ("Cannot transfer ssh keys to the new node")
1393

    
1394
    # Add node to our /etc/hosts, and add key to known_hosts
1395
    _UpdateEtcHosts(new_node.name, new_node.primary_ip)
1396
    _UpdateKnownHosts(new_node.name, new_node.primary_ip,
1397
                      self.cfg.GetHostKey())
1398

    
1399
    if new_node.secondary_ip != new_node.primary_ip:
1400
      result = ssh.SSHCall(node, "root",
1401
                           "fping -S 127.0.0.1 -q %s" % new_node.secondary_ip)
1402
      if result.failed:
1403
        raise errors.OpExecError, ("Node claims it doesn't have the"
1404
                                   " secondary ip you gave (%s).\n"
1405
                                   "Please fix and re-run this command." %
1406
                                   new_node.secondary_ip)
1407

    
1408
    # Distribute updated /etc/hosts and known_hosts to all nodes,
1409
    # including the node just added
1410
    myself = self.cfg.GetNodeInfo(self.sstore.GetMasterNode())
1411
    dist_nodes = self.cfg.GetNodeList() + [node]
1412
    if myself.name in dist_nodes:
1413
      dist_nodes.remove(myself.name)
1414

    
1415
    logger.Debug("Copying hosts and known_hosts to all nodes")
1416
    for fname in ("/etc/hosts", "/etc/ssh/ssh_known_hosts"):
1417
      result = rpc.call_upload_file(dist_nodes, fname)
1418
      for to_node in dist_nodes:
1419
        if not result[to_node]:
1420
          logger.Error("copy of file %s to node %s failed" %
1421
                       (fname, to_node))
1422

    
1423
    to_copy = ss.GetFileList()
1424
    for fname in to_copy:
1425
      if not ssh.CopyFileToNode(node, fname):
1426
        logger.Error("could not copy file %s to node %s" % (fname, node))
1427

    
1428
    logger.Info("adding node %s to cluster.conf" % node)
1429
    self.cfg.AddNode(new_node)
1430

    
1431

    
1432
class LUMasterFailover(LogicalUnit):
1433
  """Failover the master node to the current node.
1434

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

1437
  """
1438
  HPATH = "master-failover"
1439
  HTYPE = constants.HTYPE_CLUSTER
1440
  REQ_MASTER = False
1441
  _OP_REQP = []
1442

    
1443
  def BuildHooksEnv(self):
1444
    """Build hooks env.
1445

1446
    This will run on the new master only in the pre phase, and on all
1447
    the nodes in the post phase.
1448

1449
    """
1450
    env = {
1451
      "NEW_MASTER": self.new_master,
1452
      "OLD_MASTER": self.old_master,
1453
      }
1454
    return env, [self.new_master], self.cfg.GetNodeList()
1455

    
1456
  def CheckPrereq(self):
1457
    """Check prerequisites.
1458

1459
    This checks that we are not already the master.
1460

1461
    """
1462
    self.new_master = socket.gethostname()
1463

    
1464
    self.old_master = self.sstore.GetMasterNode()
1465

    
1466
    if self.old_master == self.new_master:
1467
      raise errors.OpPrereqError, ("This commands must be run on the node"
1468
                                   " where you want the new master to be.\n"
1469
                                   "%s is already the master" %
1470
                                   self.old_master)
1471

    
1472
  def Exec(self, feedback_fn):
1473
    """Failover the master node.
1474

1475
    This command, when run on a non-master node, will cause the current
1476
    master to cease being master, and the non-master to become new
1477
    master.
1478

1479
    """
1480

    
1481
    #TODO: do not rely on gethostname returning the FQDN
1482
    logger.Info("setting master to %s, old master: %s" %
1483
                (self.new_master, self.old_master))
1484

    
1485
    if not rpc.call_node_stop_master(self.old_master):
1486
      logger.Error("could disable the master role on the old master"
1487
                   " %s, please disable manually" % self.old_master)
1488

    
1489
    ss = self.sstore
1490
    ss.SetKey(ss.SS_MASTER_NODE, self.new_master)
1491
    if not rpc.call_upload_file(self.cfg.GetNodeList(),
1492
                                ss.KeyToFilename(ss.SS_MASTER_NODE)):
1493
      logger.Error("could not distribute the new simple store master file"
1494
                   " to the other nodes, please check.")
1495

    
1496
    if not rpc.call_node_start_master(self.new_master):
1497
      logger.Error("could not start the master role on the new master"
1498
                   " %s, please check" % self.new_master)
1499
      feedback_fn("Error in activating the master IP on the new master,\n"
1500
                  "please fix manually.")
1501

    
1502

    
1503

    
1504
class LUQueryClusterInfo(NoHooksLU):
1505
  """Query cluster configuration.
1506

1507
  """
1508
  _OP_REQP = []
1509

    
1510
  def CheckPrereq(self):
1511
    """No prerequsites needed for this LU.
1512

1513
    """
1514
    pass
1515

    
1516
  def Exec(self, feedback_fn):
1517
    """Return cluster config.
1518

1519
    """
1520
    instances = [self.cfg.GetInstanceInfo(name)
1521
                 for name in self.cfg.GetInstanceList()]
1522
    result = {
1523
      "name": self.cfg.GetClusterName(),
1524
      "software_version": constants.RELEASE_VERSION,
1525
      "protocol_version": constants.PROTOCOL_VERSION,
1526
      "config_version": constants.CONFIG_VERSION,
1527
      "os_api_version": constants.OS_API_VERSION,
1528
      "export_version": constants.EXPORT_VERSION,
1529
      "master": self.sstore.GetMasterNode(),
1530
      "architecture": (platform.architecture()[0], platform.machine()),
1531
      "instances": [(instance.name, instance.primary_node)
1532
                    for instance in instances],
1533
      "nodes": self.cfg.GetNodeList(),
1534
      }
1535

    
1536
    return result
1537

    
1538

    
1539
class LUClusterCopyFile(NoHooksLU):
1540
  """Copy file to cluster.
1541

1542
  """
1543
  _OP_REQP = ["nodes", "filename"]
1544

    
1545
  def CheckPrereq(self):
1546
    """Check prerequisites.
1547

1548
    It should check that the named file exists and that the given list
1549
    of nodes is valid.
1550

1551
    """
1552
    if not os.path.exists(self.op.filename):
1553
      raise errors.OpPrereqError("No such filename '%s'" % self.op.filename)
1554

    
1555
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1556

    
1557
  def Exec(self, feedback_fn):
1558
    """Copy a file from master to some nodes.
1559

1560
    Args:
1561
      opts - class with options as members
1562
      args - list containing a single element, the file name
1563
    Opts used:
1564
      nodes - list containing the name of target nodes; if empty, all nodes
1565

1566
    """
1567
    filename = self.op.filename
1568

    
1569
    myname = socket.gethostname()
1570

    
1571
    for node in self.nodes:
1572
      if node == myname:
1573
        continue
1574
      if not ssh.CopyFileToNode(node, filename):
1575
        logger.Error("Copy of file %s to node %s failed" % (filename, node))
1576

    
1577

    
1578
class LUDumpClusterConfig(NoHooksLU):
1579
  """Return a text-representation of the cluster-config.
1580

1581
  """
1582
  _OP_REQP = []
1583

    
1584
  def CheckPrereq(self):
1585
    """No prerequisites.
1586

1587
    """
1588
    pass
1589

    
1590
  def Exec(self, feedback_fn):
1591
    """Dump a representation of the cluster config to the standard output.
1592

1593
    """
1594
    return self.cfg.DumpConfig()
1595

    
1596

    
1597
class LURunClusterCommand(NoHooksLU):
1598
  """Run a command on some nodes.
1599

1600
  """
1601
  _OP_REQP = ["command", "nodes"]
1602

    
1603
  def CheckPrereq(self):
1604
    """Check prerequisites.
1605

1606
    It checks that the given list of nodes is valid.
1607

1608
    """
1609
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1610

    
1611
  def Exec(self, feedback_fn):
1612
    """Run a command on some nodes.
1613

1614
    """
1615
    data = []
1616
    for node in self.nodes:
1617
      result = utils.RunCmd(["ssh", node.name, self.op.command])
1618
      data.append((node.name, result.cmd, result.output, result.exit_code))
1619

    
1620
    return data
1621

    
1622

    
1623
class LUActivateInstanceDisks(NoHooksLU):
1624
  """Bring up an instance's disks.
1625

1626
  """
1627
  _OP_REQP = ["instance_name"]
1628

    
1629
  def CheckPrereq(self):
1630
    """Check prerequisites.
1631

1632
    This checks that the instance is in the cluster.
1633

1634
    """
1635
    instance = self.cfg.GetInstanceInfo(
1636
      self.cfg.ExpandInstanceName(self.op.instance_name))
1637
    if instance is None:
1638
      raise errors.OpPrereqError, ("Instance '%s' not known" %
1639
                                   self.op.instance_name)
1640
    self.instance = instance
1641

    
1642

    
1643
  def Exec(self, feedback_fn):
1644
    """Activate the disks.
1645

1646
    """
1647
    disks_ok, disks_info = _AssembleInstanceDisks(self.instance, self.cfg)
1648
    if not disks_ok:
1649
      raise errors.OpExecError, ("Cannot activate block devices")
1650

    
1651
    return disks_info
1652

    
1653

    
1654
def _AssembleInstanceDisks(instance, cfg, ignore_secondaries=False):
1655
  """Prepare the block devices for an instance.
1656

1657
  This sets up the block devices on all nodes.
1658

1659
  Args:
1660
    instance: a ganeti.objects.Instance object
1661
    ignore_secondaries: if true, errors on secondary nodes won't result
1662
                        in an error return from the function
1663

1664
  Returns:
1665
    false if the operation failed
1666
    list of (host, instance_visible_name, node_visible_name) if the operation
1667
         suceeded with the mapping from node devices to instance devices
1668
  """
1669
  device_info = []
1670
  disks_ok = True
1671
  for inst_disk in instance.disks:
1672
    master_result = None
1673
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1674
      cfg.SetDiskID(node_disk, node)
1675
      is_primary = node == instance.primary_node
1676
      result = rpc.call_blockdev_assemble(node, node_disk, is_primary)
1677
      if not result:
1678
        logger.Error("could not prepare block device %s on node %s (is_pri"
1679
                     "mary=%s)" % (inst_disk.iv_name, node, is_primary))
1680
        if is_primary or not ignore_secondaries:
1681
          disks_ok = False
1682
      if is_primary:
1683
        master_result = result
1684
    device_info.append((instance.primary_node, inst_disk.iv_name,
1685
                        master_result))
1686

    
1687
  return disks_ok, device_info
1688

    
1689

    
1690
class LUDeactivateInstanceDisks(NoHooksLU):
1691
  """Shutdown an instance's disks.
1692

1693
  """
1694
  _OP_REQP = ["instance_name"]
1695

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

1699
    This checks that the instance is in the cluster.
1700

1701
    """
1702
    instance = self.cfg.GetInstanceInfo(
1703
      self.cfg.ExpandInstanceName(self.op.instance_name))
1704
    if instance is None:
1705
      raise errors.OpPrereqError, ("Instance '%s' not known" %
1706
                                   self.op.instance_name)
1707
    self.instance = instance
1708

    
1709
  def Exec(self, feedback_fn):
1710
    """Deactivate the disks
1711

1712
    """
1713
    instance = self.instance
1714
    ins_l = rpc.call_instance_list([instance.primary_node])
1715
    ins_l = ins_l[instance.primary_node]
1716
    if not type(ins_l) is list:
1717
      raise errors.OpExecError, ("Can't contact node '%s'" %
1718
                                 instance.primary_node)
1719

    
1720
    if self.instance.name in ins_l:
1721
      raise errors.OpExecError, ("Instance is running, can't shutdown"
1722
                                 " block devices.")
1723

    
1724
    _ShutdownInstanceDisks(instance, self.cfg)
1725

    
1726

    
1727
def _ShutdownInstanceDisks(instance, cfg, ignore_primary=False):
1728
  """Shutdown block devices of an instance.
1729

1730
  This does the shutdown on all nodes of the instance.
1731

1732
  If the ignore_primary is false, errors on the primary node are
1733
  ignored.
1734

1735
  """
1736
  result = True
1737
  for disk in instance.disks:
1738
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
1739
      cfg.SetDiskID(top_disk, node)
1740
      if not rpc.call_blockdev_shutdown(node, top_disk):
1741
        logger.Error("could not shutdown block device %s on node %s" %
1742
                     (disk.iv_name, node))
1743
        if not ignore_primary or node != instance.primary_node:
1744
          result = False
1745
  return result
1746

    
1747

    
1748
class LUStartupInstance(LogicalUnit):
1749
  """Starts an instance.
1750

1751
  """
1752
  HPATH = "instance-start"
1753
  HTYPE = constants.HTYPE_INSTANCE
1754
  _OP_REQP = ["instance_name", "force"]
1755

    
1756
  def BuildHooksEnv(self):
1757
    """Build hooks env.
1758

1759
    This runs on master, primary and secondary nodes of the instance.
1760

1761
    """
1762
    env = {
1763
      "INSTANCE_NAME": self.op.instance_name,
1764
      "INSTANCE_PRIMARY": self.instance.primary_node,
1765
      "INSTANCE_SECONDARIES": " ".join(self.instance.secondary_nodes),
1766
      "FORCE": self.op.force,
1767
      }
1768
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
1769
          list(self.instance.secondary_nodes))
1770
    return env, nl, nl
1771

    
1772
  def CheckPrereq(self):
1773
    """Check prerequisites.
1774

1775
    This checks that the instance is in the cluster.
1776

1777
    """
1778
    instance = self.cfg.GetInstanceInfo(
1779
      self.cfg.ExpandInstanceName(self.op.instance_name))
1780
    if instance is None:
1781
      raise errors.OpPrereqError, ("Instance '%s' not known" %
1782
                                   self.op.instance_name)
1783

    
1784
    # check bridges existance
1785
    brlist = [nic.bridge for nic in instance.nics]
1786
    if not rpc.call_bridges_exist(instance.primary_node, brlist):
1787
      raise errors.OpPrereqError, ("one or more target bridges %s does not"
1788
                                   " exist on destination node '%s'" %
1789
                                   (brlist, instance.primary_node))
1790

    
1791
    self.instance = instance
1792
    self.op.instance_name = instance.name
1793

    
1794
  def Exec(self, feedback_fn):
1795
    """Start the instance.
1796

1797
    """
1798
    instance = self.instance
1799
    force = self.op.force
1800
    extra_args = getattr(self.op, "extra_args", "")
1801

    
1802
    node_current = instance.primary_node
1803

    
1804
    nodeinfo = rpc.call_node_info([node_current], self.cfg.GetVGName())
1805
    if not nodeinfo:
1806
      raise errors.OpExecError, ("Could not contact node %s for infos" %
1807
                                 (node_current))
1808

    
1809
    freememory = nodeinfo[node_current]['memory_free']
1810
    memory = instance.memory
1811
    if memory > freememory:
1812
      raise errors.OpExecError, ("Not enough memory to start instance"
1813
                                 " %s on node %s"
1814
                                 " needed %s MiB, available %s MiB" %
1815
                                 (instance.name, node_current, memory,
1816
                                  freememory))
1817

    
1818
    disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
1819
                                             ignore_secondaries=force)
1820
    if not disks_ok:
1821
      _ShutdownInstanceDisks(instance, self.cfg)
1822
      if not force:
1823
        logger.Error("If the message above refers to a secondary node,"
1824
                     " you can retry the operation using '--force'.")
1825
      raise errors.OpExecError, ("Disk consistency error")
1826

    
1827
    if not rpc.call_instance_start(node_current, instance, extra_args):
1828
      _ShutdownInstanceDisks(instance, self.cfg)
1829
      raise errors.OpExecError, ("Could not start instance")
1830

    
1831
    self.cfg.MarkInstanceUp(instance.name)
1832

    
1833

    
1834
class LUShutdownInstance(LogicalUnit):
1835
  """Shutdown an instance.
1836

1837
  """
1838
  HPATH = "instance-stop"
1839
  HTYPE = constants.HTYPE_INSTANCE
1840
  _OP_REQP = ["instance_name"]
1841

    
1842
  def BuildHooksEnv(self):
1843
    """Build hooks env.
1844

1845
    This runs on master, primary and secondary nodes of the instance.
1846

1847
    """
1848
    env = {
1849
      "INSTANCE_NAME": self.op.instance_name,
1850
      "INSTANCE_PRIMARY": self.instance.primary_node,
1851
      "INSTANCE_SECONDARIES": " ".join(self.instance.secondary_nodes),
1852
      }
1853
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
1854
          list(self.instance.secondary_nodes))
1855
    return env, nl, nl
1856

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

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

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

    
1870
  def Exec(self, feedback_fn):
1871
    """Shutdown the instance.
1872

1873
    """
1874
    instance = self.instance
1875
    node_current = instance.primary_node
1876
    if not rpc.call_instance_shutdown(node_current, instance):
1877
      logger.Error("could not shutdown instance")
1878

    
1879
    self.cfg.MarkInstanceDown(instance.name)
1880
    _ShutdownInstanceDisks(instance, self.cfg)
1881

    
1882

    
1883
class LURemoveInstance(LogicalUnit):
1884
  """Remove an instance.
1885

1886
  """
1887
  HPATH = "instance-remove"
1888
  HTYPE = constants.HTYPE_INSTANCE
1889
  _OP_REQP = ["instance_name"]
1890

    
1891
  def BuildHooksEnv(self):
1892
    """Build hooks env.
1893

1894
    This runs on master, primary and secondary nodes of the instance.
1895

1896
    """
1897
    env = {
1898
      "INSTANCE_NAME": self.op.instance_name,
1899
      "INSTANCE_PRIMARY": self.instance.primary_node,
1900
      "INSTANCE_SECONDARIES": " ".join(self.instance.secondary_nodes),
1901
      }
1902
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
1903
          list(self.instance.secondary_nodes))
1904
    return env, nl, nl
1905

    
1906
  def CheckPrereq(self):
1907
    """Check prerequisites.
1908

1909
    This checks that the instance is in the cluster.
1910

1911
    """
1912
    instance = self.cfg.GetInstanceInfo(
1913
      self.cfg.ExpandInstanceName(self.op.instance_name))
1914
    if instance is None:
1915
      raise errors.OpPrereqError, ("Instance '%s' not known" %
1916
                                   self.op.instance_name)
1917
    self.instance = instance
1918

    
1919
  def Exec(self, feedback_fn):
1920
    """Remove the instance.
1921

1922
    """
1923
    instance = self.instance
1924
    logger.Info("shutting down instance %s on node %s" %
1925
                (instance.name, instance.primary_node))
1926

    
1927
    if not rpc.call_instance_shutdown(instance.primary_node, instance):
1928
      raise errors.OpExecError, ("Could not shutdown instance %s on node %s" %
1929
                                 (instance.name, instance.primary_node))
1930

    
1931
    logger.Info("removing block devices for instance %s" % instance.name)
1932

    
1933
    _RemoveDisks(instance, self.cfg)
1934

    
1935
    logger.Info("removing instance %s out of cluster config" % instance.name)
1936

    
1937
    self.cfg.RemoveInstance(instance.name)
1938

    
1939

    
1940
class LUQueryInstances(NoHooksLU):
1941
  """Logical unit for querying instances.
1942

1943
  """
1944
  _OP_REQP = ["output_fields"]
1945

    
1946
  def CheckPrereq(self):
1947
    """Check prerequisites.
1948

1949
    This checks that the fields required are valid output fields.
1950

1951
    """
1952
    self.dynamic_fields = frozenset(["oper_state", "oper_ram"])
1953
    _CheckOutputFields(static=["name", "os", "pnode", "snodes",
1954
                               "admin_state", "admin_ram",
1955
                               "disk_template", "ip", "mac", "bridge"],
1956
                       dynamic=self.dynamic_fields,
1957
                       selected=self.op.output_fields)
1958

    
1959
  def Exec(self, feedback_fn):
1960
    """Computes the list of nodes and their attributes.
1961

1962
    """
1963

    
1964
    instance_names = utils.NiceSort(self.cfg.GetInstanceList())
1965
    instance_list = [self.cfg.GetInstanceInfo(iname) for iname
1966
                     in instance_names]
1967

    
1968
    # begin data gathering
1969

    
1970
    nodes = frozenset([inst.primary_node for inst in instance_list])
1971

    
1972
    bad_nodes = []
1973
    if self.dynamic_fields.intersection(self.op.output_fields):
1974
      live_data = {}
1975
      node_data = rpc.call_all_instances_info(nodes)
1976
      for name in nodes:
1977
        result = node_data[name]
1978
        if result:
1979
          live_data.update(result)
1980
        elif result == False:
1981
          bad_nodes.append(name)
1982
        # else no instance is alive
1983
    else:
1984
      live_data = dict([(name, {}) for name in instance_names])
1985

    
1986
    # end data gathering
1987

    
1988
    output = []
1989
    for instance in instance_list:
1990
      iout = []
1991
      for field in self.op.output_fields:
1992
        if field == "name":
1993
          val = instance.name
1994
        elif field == "os":
1995
          val = instance.os
1996
        elif field == "pnode":
1997
          val = instance.primary_node
1998
        elif field == "snodes":
1999
          val = ",".join(instance.secondary_nodes) or "-"
2000
        elif field == "admin_state":
2001
          if instance.status == "down":
2002
            val = "no"
2003
          else:
2004
            val = "yes"
2005
        elif field == "oper_state":
2006
          if instance.primary_node in bad_nodes:
2007
            val = "(node down)"
2008
          else:
2009
            if live_data.get(instance.name):
2010
              val = "running"
2011
            else:
2012
              val = "stopped"
2013
        elif field == "admin_ram":
2014
          val = instance.memory
2015
        elif field == "oper_ram":
2016
          if instance.primary_node in bad_nodes:
2017
            val = "(node down)"
2018
          elif instance.name in live_data:
2019
            val = live_data[instance.name].get("memory", "?")
2020
          else:
2021
            val = "-"
2022
        elif field == "disk_template":
2023
          val = instance.disk_template
2024
        elif field == "ip":
2025
          val = instance.nics[0].ip
2026
        elif field == "bridge":
2027
          val = instance.nics[0].bridge
2028
        elif field == "mac":
2029
          val = instance.nics[0].mac
2030
        else:
2031
          raise errors.ParameterError, field
2032
        val = str(val)
2033
        iout.append(val)
2034
      output.append(iout)
2035

    
2036
    return output
2037

    
2038

    
2039
class LUFailoverInstance(LogicalUnit):
2040
  """Failover an instance.
2041

2042
  """
2043
  HPATH = "instance-failover"
2044
  HTYPE = constants.HTYPE_INSTANCE
2045
  _OP_REQP = ["instance_name", "ignore_consistency"]
2046

    
2047
  def BuildHooksEnv(self):
2048
    """Build hooks env.
2049

2050
    This runs on master, primary and secondary nodes of the instance.
2051

2052
    """
2053
    env = {
2054
      "INSTANCE_NAME": self.op.instance_name,
2055
      "INSTANCE_PRIMARY": self.instance.primary_node,
2056
      "INSTANCE_SECONDARIES": " ".join(self.instance.secondary_nodes),
2057
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2058
      }
2059
    nl = [self.sstore.GetMasterNode()] + list(self.instance.secondary_nodes)
2060
    return env, nl, nl
2061

    
2062
  def CheckPrereq(self):
2063
    """Check prerequisites.
2064

2065
    This checks that the instance is in the cluster.
2066

2067
    """
2068
    instance = self.cfg.GetInstanceInfo(
2069
      self.cfg.ExpandInstanceName(self.op.instance_name))
2070
    if instance is None:
2071
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2072
                                   self.op.instance_name)
2073

    
2074
    # check memory requirements on the secondary node
2075
    target_node = instance.secondary_nodes[0]
2076
    nodeinfo = rpc.call_node_info([target_node], self.cfg.GetVGName())
2077
    info = nodeinfo.get(target_node, None)
2078
    if not info:
2079
      raise errors.OpPrereqError, ("Cannot get current information"
2080
                                   " from node '%s'" % nodeinfo)
2081
    if instance.memory > info['memory_free']:
2082
      raise errors.OpPrereqError, ("Not enough memory on target node %s."
2083
                                   " %d MB available, %d MB required" %
2084
                                   (target_node, info['memory_free'],
2085
                                    instance.memory))
2086

    
2087
    # check bridge existance
2088
    brlist = [nic.bridge for nic in instance.nics]
2089
    if not rpc.call_bridges_exist(instance.primary_node, brlist):
2090
      raise errors.OpPrereqError, ("one or more target bridges %s does not"
2091
                                   " exist on destination node '%s'" %
2092
                                   (brlist, instance.primary_node))
2093

    
2094
    self.instance = instance
2095

    
2096
  def Exec(self, feedback_fn):
2097
    """Failover an instance.
2098

2099
    The failover is done by shutting it down on its present node and
2100
    starting it on the secondary.
2101

2102
    """
2103
    instance = self.instance
2104

    
2105
    source_node = instance.primary_node
2106
    target_node = instance.secondary_nodes[0]
2107

    
2108
    feedback_fn("* checking disk consistency between source and target")
2109
    for dev in instance.disks:
2110
      # for remote_raid1, these are md over drbd
2111
      if not _CheckDiskConsistency(self.cfg, dev, target_node, False):
2112
        if not self.op.ignore_consistency:
2113
          raise errors.OpExecError, ("Disk %s is degraded on target node,"
2114
                                     " aborting failover." % dev.iv_name)
2115

    
2116
    feedback_fn("* checking target node resource availability")
2117
    nodeinfo = rpc.call_node_info([target_node], self.cfg.GetVGName())
2118

    
2119
    if not nodeinfo:
2120
      raise errors.OpExecError, ("Could not contact target node %s." %
2121
                                 target_node)
2122

    
2123
    free_memory = int(nodeinfo[target_node]['memory_free'])
2124
    memory = instance.memory
2125
    if memory > free_memory:
2126
      raise errors.OpExecError, ("Not enough memory to create instance %s on"
2127
                                 " node %s. needed %s MiB, available %s MiB" %
2128
                                 (instance.name, target_node, memory,
2129
                                  free_memory))
2130

    
2131
    feedback_fn("* shutting down instance on source node")
2132
    logger.Info("Shutting down instance %s on node %s" %
2133
                (instance.name, source_node))
2134

    
2135
    if not rpc.call_instance_shutdown(source_node, instance):
2136
      logger.Error("Could not shutdown instance %s on node %s. Proceeding"
2137
                   " anyway. Please make sure node %s is down"  %
2138
                   (instance.name, source_node, source_node))
2139

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

    
2144
    instance.primary_node = target_node
2145
    # distribute new instance config to the other nodes
2146
    self.cfg.AddInstance(instance)
2147

    
2148
    feedback_fn("* activating the instance's disks on target node")
2149
    logger.Info("Starting instance %s on node %s" %
2150
                (instance.name, target_node))
2151

    
2152
    disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
2153
                                             ignore_secondaries=True)
2154
    if not disks_ok:
2155
      _ShutdownInstanceDisks(instance, self.cfg)
2156
      raise errors.OpExecError, ("Can't activate the instance's disks")
2157

    
2158
    feedback_fn("* starting the instance on the target node")
2159
    if not rpc.call_instance_start(target_node, instance, None):
2160
      _ShutdownInstanceDisks(instance, self.cfg)
2161
      raise errors.OpExecError("Could not start instance %s on node %s." %
2162
                               (instance.name, target_node))
2163

    
2164

    
2165
def _CreateBlockDevOnPrimary(cfg, node, device):
2166
  """Create a tree of block devices on the primary node.
2167

2168
  This always creates all devices.
2169

2170
  """
2171

    
2172
  if device.children:
2173
    for child in device.children:
2174
      if not _CreateBlockDevOnPrimary(cfg, node, child):
2175
        return False
2176

    
2177
  cfg.SetDiskID(device, node)
2178
  new_id = rpc.call_blockdev_create(node, device, device.size, True)
2179
  if not new_id:
2180
    return False
2181
  if device.physical_id is None:
2182
    device.physical_id = new_id
2183
  return True
2184

    
2185

    
2186
def _CreateBlockDevOnSecondary(cfg, node, device, force):
2187
  """Create a tree of block devices on a secondary node.
2188

2189
  If this device type has to be created on secondaries, create it and
2190
  all its children.
2191

2192
  If not, just recurse to children keeping the same 'force' value.
2193

2194
  """
2195
  if device.CreateOnSecondary():
2196
    force = True
2197
  if device.children:
2198
    for child in device.children:
2199
      if not _CreateBlockDevOnSecondary(cfg, node, child, force):
2200
        return False
2201

    
2202
  if not force:
2203
    return True
2204
  cfg.SetDiskID(device, node)
2205
  new_id = rpc.call_blockdev_create(node, device, device.size, False)
2206
  if not new_id:
2207
    return False
2208
  if device.physical_id is None:
2209
    device.physical_id = new_id
2210
  return True
2211

    
2212

    
2213
def _GenerateMDDRBDBranch(cfg, vgname, primary, secondary, size, base):
2214
  """Generate a drbd device complete with its children.
2215

2216
  """
2217
  port = cfg.AllocatePort()
2218
  base = "%s_%s" % (base, port)
2219
  dev_data = objects.Disk(dev_type="lvm", size=size,
2220
                          logical_id=(vgname, "%s.data" % base))
2221
  dev_meta = objects.Disk(dev_type="lvm", size=128,
2222
                          logical_id=(vgname, "%s.meta" % base))
2223
  drbd_dev = objects.Disk(dev_type="drbd", size=size,
2224
                          logical_id = (primary, secondary, port),
2225
                          children = [dev_data, dev_meta])
2226
  return drbd_dev
2227

    
2228

    
2229
def _GenerateDiskTemplate(cfg, vgname, template_name,
2230
                          instance_name, primary_node,
2231
                          secondary_nodes, disk_sz, swap_sz):
2232
  """Generate the entire disk layout for a given template type.
2233

2234
  """
2235
  #TODO: compute space requirements
2236

    
2237
  if template_name == "diskless":
2238
    disks = []
2239
  elif template_name == "plain":
2240
    if len(secondary_nodes) != 0:
2241
      raise errors.ProgrammerError("Wrong template configuration")
2242
    sda_dev = objects.Disk(dev_type="lvm", size=disk_sz,
2243
                           logical_id=(vgname, "%s.os" % instance_name),
2244
                           iv_name = "sda")
2245
    sdb_dev = objects.Disk(dev_type="lvm", size=swap_sz,
2246
                           logical_id=(vgname, "%s.swap" % instance_name),
2247
                           iv_name = "sdb")
2248
    disks = [sda_dev, sdb_dev]
2249
  elif template_name == "local_raid1":
2250
    if len(secondary_nodes) != 0:
2251
      raise errors.ProgrammerError("Wrong template configuration")
2252
    sda_dev_m1 = objects.Disk(dev_type="lvm", size=disk_sz,
2253
                              logical_id=(vgname, "%s.os_m1" % instance_name))
2254
    sda_dev_m2 = objects.Disk(dev_type="lvm", size=disk_sz,
2255
                              logical_id=(vgname, "%s.os_m2" % instance_name))
2256
    md_sda_dev = objects.Disk(dev_type="md_raid1", iv_name = "sda",
2257
                              size=disk_sz,
2258
                              children = [sda_dev_m1, sda_dev_m2])
2259
    sdb_dev_m1 = objects.Disk(dev_type="lvm", size=swap_sz,
2260
                              logical_id=(vgname, "%s.swap_m1" %
2261
                                          instance_name))
2262
    sdb_dev_m2 = objects.Disk(dev_type="lvm", size=swap_sz,
2263
                              logical_id=(vgname, "%s.swap_m2" %
2264
                                          instance_name))
2265
    md_sdb_dev = objects.Disk(dev_type="md_raid1", iv_name = "sdb",
2266
                              size=swap_sz,
2267
                              children = [sdb_dev_m1, sdb_dev_m2])
2268
    disks = [md_sda_dev, md_sdb_dev]
2269
  elif template_name == "remote_raid1":
2270
    if len(secondary_nodes) != 1:
2271
      raise errors.ProgrammerError("Wrong template configuration")
2272
    remote_node = secondary_nodes[0]
2273
    drbd_sda_dev = _GenerateMDDRBDBranch(cfg, vgname,
2274
                                         primary_node, remote_node, disk_sz,
2275
                                         "%s-sda" % instance_name)
2276
    md_sda_dev = objects.Disk(dev_type="md_raid1", iv_name="sda",
2277
                              children = [drbd_sda_dev], size=disk_sz)
2278
    drbd_sdb_dev = _GenerateMDDRBDBranch(cfg, vgname,
2279
                                         primary_node, remote_node, swap_sz,
2280
                                         "%s-sdb" % instance_name)
2281
    md_sdb_dev = objects.Disk(dev_type="md_raid1", iv_name="sdb",
2282
                              children = [drbd_sdb_dev], size=swap_sz)
2283
    disks = [md_sda_dev, md_sdb_dev]
2284
  else:
2285
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
2286
  return disks
2287

    
2288

    
2289
def _CreateDisks(cfg, instance):
2290
  """Create all disks for an instance.
2291

2292
  This abstracts away some work from AddInstance.
2293

2294
  Args:
2295
    instance: the instance object
2296

2297
  Returns:
2298
    True or False showing the success of the creation process
2299

2300
  """
2301
  for device in instance.disks:
2302
    logger.Info("creating volume %s for instance %s" %
2303
              (device.iv_name, instance.name))
2304
    #HARDCODE
2305
    for secondary_node in instance.secondary_nodes:
2306
      if not _CreateBlockDevOnSecondary(cfg, secondary_node, device, False):
2307
        logger.Error("failed to create volume %s (%s) on secondary node %s!" %
2308
                     (device.iv_name, device, secondary_node))
2309
        return False
2310
    #HARDCODE
2311
    if not _CreateBlockDevOnPrimary(cfg, instance.primary_node, device):
2312
      logger.Error("failed to create volume %s on primary!" %
2313
                   device.iv_name)
2314
      return False
2315
  return True
2316

    
2317

    
2318
def _RemoveDisks(instance, cfg):
2319
  """Remove all disks for an instance.
2320

2321
  This abstracts away some work from `AddInstance()` and
2322
  `RemoveInstance()`. Note that in case some of the devices couldn't
2323
  be remove, the removal will continue with the other ones (compare
2324
  with `_CreateDisks()`).
2325

2326
  Args:
2327
    instance: the instance object
2328

2329
  Returns:
2330
    True or False showing the success of the removal proces
2331

2332
  """
2333
  logger.Info("removing block devices for instance %s" % instance.name)
2334

    
2335
  result = True
2336
  for device in instance.disks:
2337
    for node, disk in device.ComputeNodeTree(instance.primary_node):
2338
      cfg.SetDiskID(disk, node)
2339
      if not rpc.call_blockdev_remove(node, disk):
2340
        logger.Error("could not remove block device %s on node %s,"
2341
                     " continuing anyway" %
2342
                     (device.iv_name, node))
2343
        result = False
2344
  return result
2345

    
2346

    
2347
class LUCreateInstance(LogicalUnit):
2348
  """Create an instance.
2349

2350
  """
2351
  HPATH = "instance-add"
2352
  HTYPE = constants.HTYPE_INSTANCE
2353
  _OP_REQP = ["instance_name", "mem_size", "disk_size", "pnode",
2354
              "disk_template", "swap_size", "mode", "start", "vcpus",
2355
              "wait_for_sync"]
2356

    
2357
  def BuildHooksEnv(self):
2358
    """Build hooks env.
2359

2360
    This runs on master, primary and secondary nodes of the instance.
2361

2362
    """
2363
    env = {
2364
      "INSTANCE_NAME": self.op.instance_name,
2365
      "INSTANCE_PRIMARY": self.op.pnode,
2366
      "INSTANCE_SECONDARIES": " ".join(self.secondaries),
2367
      "DISK_TEMPLATE": self.op.disk_template,
2368
      "MEM_SIZE": self.op.mem_size,
2369
      "DISK_SIZE": self.op.disk_size,
2370
      "SWAP_SIZE": self.op.swap_size,
2371
      "VCPUS": self.op.vcpus,
2372
      "BRIDGE": self.op.bridge,
2373
      "INSTANCE_ADD_MODE": self.op.mode,
2374
      }
2375
    if self.op.mode == constants.INSTANCE_IMPORT:
2376
      env["SRC_NODE"] = self.op.src_node
2377
      env["SRC_PATH"] = self.op.src_path
2378
      env["SRC_IMAGE"] = self.src_image
2379
    if self.inst_ip:
2380
      env["INSTANCE_IP"] = self.inst_ip
2381

    
2382
    nl = ([self.sstore.GetMasterNode(), self.op.pnode] +
2383
          self.secondaries)
2384
    return env, nl, nl
2385

    
2386

    
2387
  def CheckPrereq(self):
2388
    """Check prerequisites.
2389

2390
    """
2391
    if self.op.mode not in (constants.INSTANCE_CREATE,
2392
                            constants.INSTANCE_IMPORT):
2393
      raise errors.OpPrereqError, ("Invalid instance creation mode '%s'" %
2394
                                   self.op.mode)
2395

    
2396
    if self.op.mode == constants.INSTANCE_IMPORT:
2397
      src_node = getattr(self.op, "src_node", None)
2398
      src_path = getattr(self.op, "src_path", None)
2399
      if src_node is None or src_path is None:
2400
        raise errors.OpPrereqError, ("Importing an instance requires source"
2401
                                     " node and path options")
2402
      src_node_full = self.cfg.ExpandNodeName(src_node)
2403
      if src_node_full is None:
2404
        raise errors.OpPrereqError, ("Unknown source node '%s'" % src_node)
2405
      self.op.src_node = src_node = src_node_full
2406

    
2407
      if not os.path.isabs(src_path):
2408
        raise errors.OpPrereqError, ("The source path must be absolute")
2409

    
2410
      export_info = rpc.call_export_info(src_node, src_path)
2411

    
2412
      if not export_info:
2413
        raise errors.OpPrereqError, ("No export found in dir %s" % src_path)
2414

    
2415
      if not export_info.has_section(constants.INISECT_EXP):
2416
        raise errors.ProgrammerError, ("Corrupted export config")
2417

    
2418
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
2419
      if (int(ei_version) != constants.EXPORT_VERSION):
2420
        raise errors.OpPrereqError, ("Wrong export version %s (wanted %d)" %
2421
                                     (ei_version, constants.EXPORT_VERSION))
2422

    
2423
      if int(export_info.get(constants.INISECT_INS, 'disk_count')) > 1:
2424
        raise errors.OpPrereqError, ("Can't import instance with more than"
2425
                                     " one data disk")
2426

    
2427
      # FIXME: are the old os-es, disk sizes, etc. useful?
2428
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
2429
      diskimage = os.path.join(src_path, export_info.get(constants.INISECT_INS,
2430
                                                         'disk0_dump'))
2431
      self.src_image = diskimage
2432
    else: # INSTANCE_CREATE
2433
      if getattr(self.op, "os_type", None) is None:
2434
        raise errors.OpPrereqError, ("No guest OS specified")
2435

    
2436
    # check primary node
2437
    pnode = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.pnode))
2438
    if pnode is None:
2439
      raise errors.OpPrereqError, ("Primary node '%s' is uknown" %
2440
                                   self.op.pnode)
2441
    self.op.pnode = pnode.name
2442
    self.pnode = pnode
2443
    self.secondaries = []
2444
    # disk template and mirror node verification
2445
    if self.op.disk_template not in constants.DISK_TEMPLATES:
2446
      raise errors.OpPrereqError, ("Invalid disk template name")
2447

    
2448
    if self.op.disk_template == constants.DT_REMOTE_RAID1:
2449
      if getattr(self.op, "snode", None) is None:
2450
        raise errors.OpPrereqError, ("The 'remote_raid1' disk template needs"
2451
                                     " a mirror node")
2452

    
2453
      snode_name = self.cfg.ExpandNodeName(self.op.snode)
2454
      if snode_name is None:
2455
        raise errors.OpPrereqError, ("Unknown secondary node '%s'" %
2456
                                     self.op.snode)
2457
      elif snode_name == pnode.name:
2458
        raise errors.OpPrereqError, ("The secondary node cannot be"
2459
                                     " the primary node.")
2460
      self.secondaries.append(snode_name)
2461

    
2462
    # Check lv size requirements
2463
    nodenames = [pnode.name] + self.secondaries
2464
    nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
2465

    
2466
    # Required free disk space as a function of disk and swap space
2467
    req_size_dict = {
2468
      constants.DT_DISKLESS: 0,
2469
      constants.DT_PLAIN: self.op.disk_size + self.op.swap_size,
2470
      constants.DT_LOCAL_RAID1: (self.op.disk_size + self.op.swap_size) * 2,
2471
      # 256 MB are added for drbd metadata, 128MB for each drbd device
2472
      constants.DT_REMOTE_RAID1: self.op.disk_size + self.op.swap_size + 256,
2473
    }
2474

    
2475
    if self.op.disk_template not in req_size_dict:
2476
      raise errors.ProgrammerError, ("Disk template '%s' size requirement"
2477
                                     " is unknown" %  self.op.disk_template)
2478

    
2479
    req_size = req_size_dict[self.op.disk_template]
2480

    
2481
    for node in nodenames:
2482
      info = nodeinfo.get(node, None)
2483
      if not info:
2484
        raise errors.OpPrereqError, ("Cannot get current information"
2485
                                     " from node '%s'" % nodeinfo)
2486
      if req_size > info['vg_free']:
2487
        raise errors.OpPrereqError, ("Not enough disk space on target node %s."
2488
                                     " %d MB available, %d MB required" %
2489
                                     (node, info['vg_free'], req_size))
2490

    
2491
    # os verification
2492
    os_obj = rpc.call_os_get([pnode.name], self.op.os_type)[pnode.name]
2493
    if not isinstance(os_obj, objects.OS):
2494
      raise errors.OpPrereqError, ("OS '%s' not in supported os list for"
2495
                                   " primary node"  % self.op.os_type)
2496

    
2497
    # instance verification
2498
    hostname1 = utils.LookupHostname(self.op.instance_name)
2499
    if not hostname1:
2500
      raise errors.OpPrereqError, ("Instance name '%s' not found in dns" %
2501
                                   self.op.instance_name)
2502

    
2503
    self.op.instance_name = instance_name = hostname1['hostname']
2504
    instance_list = self.cfg.GetInstanceList()
2505
    if instance_name in instance_list:
2506
      raise errors.OpPrereqError, ("Instance '%s' is already in the cluster" %
2507
                                   instance_name)
2508

    
2509
    ip = getattr(self.op, "ip", None)
2510
    if ip is None or ip.lower() == "none":
2511
      inst_ip = None
2512
    elif ip.lower() == "auto":
2513
      inst_ip = hostname1['ip']
2514
    else:
2515
      if not utils.IsValidIP(ip):
2516
        raise errors.OpPrereqError, ("given IP address '%s' doesn't look"
2517
                                     " like a valid IP" % ip)
2518
      inst_ip = ip
2519
    self.inst_ip = inst_ip
2520

    
2521
    command = ["fping", "-q", hostname1['ip']]
2522
    result = utils.RunCmd(command)
2523
    if not result.failed:
2524
      raise errors.OpPrereqError, ("IP %s of instance %s already in use" %
2525
                                   (hostname1['ip'], instance_name))
2526

    
2527
    # bridge verification
2528
    bridge = getattr(self.op, "bridge", None)
2529
    if bridge is None:
2530
      self.op.bridge = self.cfg.GetDefBridge()
2531
    else:
2532
      self.op.bridge = bridge
2533

    
2534
    if not rpc.call_bridges_exist(self.pnode.name, [self.op.bridge]):
2535
      raise errors.OpPrereqError, ("target bridge '%s' does not exist on"
2536
                                   " destination node '%s'" %
2537
                                   (self.op.bridge, pnode.name))
2538

    
2539
    if self.op.start:
2540
      self.instance_status = 'up'
2541
    else:
2542
      self.instance_status = 'down'
2543

    
2544
  def Exec(self, feedback_fn):
2545
    """Create and add the instance to the cluster.
2546

2547
    """
2548
    instance = self.op.instance_name
2549
    pnode_name = self.pnode.name
2550

    
2551
    nic = objects.NIC(bridge=self.op.bridge, mac=self.cfg.GenerateMAC())
2552
    if self.inst_ip is not None:
2553
      nic.ip = self.inst_ip
2554

    
2555
    disks = _GenerateDiskTemplate(self.cfg, self.cfg.GetVGName(),
2556
                                  self.op.disk_template,
2557
                                  instance, pnode_name,
2558
                                  self.secondaries, self.op.disk_size,
2559
                                  self.op.swap_size)
2560

    
2561
    iobj = objects.Instance(name=instance, os=self.op.os_type,
2562
                            primary_node=pnode_name,
2563
                            memory=self.op.mem_size,
2564
                            vcpus=self.op.vcpus,
2565
                            nics=[nic], disks=disks,
2566
                            disk_template=self.op.disk_template,
2567
                            status=self.instance_status,
2568
                            )
2569

    
2570
    feedback_fn("* creating instance disks...")
2571
    if not _CreateDisks(self.cfg, iobj):
2572
      _RemoveDisks(iobj, self.cfg)
2573
      raise errors.OpExecError, ("Device creation failed, reverting...")
2574

    
2575
    feedback_fn("adding instance %s to cluster config" % instance)
2576

    
2577
    self.cfg.AddInstance(iobj)
2578

    
2579
    if self.op.wait_for_sync:
2580
      disk_abort = not _WaitForSync(self.cfg, iobj)
2581
    elif iobj.disk_template == "remote_raid1":
2582
      # make sure the disks are not degraded (still sync-ing is ok)
2583
      time.sleep(15)
2584
      feedback_fn("* checking mirrors status")
2585
      disk_abort = not _WaitForSync(self.cfg, iobj, oneshot=True)
2586
    else:
2587
      disk_abort = False
2588

    
2589
    if disk_abort:
2590
      _RemoveDisks(iobj, self.cfg)
2591
      self.cfg.RemoveInstance(iobj.name)
2592
      raise errors.OpExecError, ("There are some degraded disks for"
2593
                                      " this instance")
2594

    
2595
    feedback_fn("creating os for instance %s on node %s" %
2596
                (instance, pnode_name))
2597

    
2598
    if iobj.disk_template != constants.DT_DISKLESS:
2599
      if self.op.mode == constants.INSTANCE_CREATE:
2600
        feedback_fn("* running the instance OS create scripts...")
2601
        if not rpc.call_instance_os_add(pnode_name, iobj, "sda", "sdb"):
2602
          raise errors.OpExecError, ("could not add os for instance %s"
2603
                                          " on node %s" %
2604
                                          (instance, pnode_name))
2605

    
2606
      elif self.op.mode == constants.INSTANCE_IMPORT:
2607
        feedback_fn("* running the instance OS import scripts...")
2608
        src_node = self.op.src_node
2609
        src_image = self.src_image
2610
        if not rpc.call_instance_os_import(pnode_name, iobj, "sda", "sdb",
2611
                                                src_node, src_image):
2612
          raise errors.OpExecError, ("Could not import os for instance"
2613
                                          " %s on node %s" %
2614
                                          (instance, pnode_name))
2615
      else:
2616
        # also checked in the prereq part
2617
        raise errors.ProgrammerError, ("Unknown OS initialization mode '%s'"
2618
                                       % self.op.mode)
2619

    
2620
    if self.op.start:
2621
      logger.Info("starting instance %s on node %s" % (instance, pnode_name))
2622
      feedback_fn("* starting instance...")
2623
      if not rpc.call_instance_start(pnode_name, iobj, None):
2624
        raise errors.OpExecError, ("Could not start instance")
2625

    
2626

    
2627
class LUConnectConsole(NoHooksLU):
2628
  """Connect to an instance's console.
2629

2630
  This is somewhat special in that it returns the command line that
2631
  you need to run on the master node in order to connect to the
2632
  console.
2633

2634
  """
2635
  _OP_REQP = ["instance_name"]
2636

    
2637
  def CheckPrereq(self):
2638
    """Check prerequisites.
2639

2640
    This checks that the instance is in the cluster.
2641

2642
    """
2643
    instance = self.cfg.GetInstanceInfo(
2644
      self.cfg.ExpandInstanceName(self.op.instance_name))
2645
    if instance is None:
2646
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2647
                                   self.op.instance_name)
2648
    self.instance = instance
2649

    
2650
  def Exec(self, feedback_fn):
2651
    """Connect to the console of an instance
2652

2653
    """
2654
    instance = self.instance
2655
    node = instance.primary_node
2656

    
2657
    node_insts = rpc.call_instance_list([node])[node]
2658
    if node_insts is False:
2659
      raise errors.OpExecError, ("Can't connect to node %s." % node)
2660

    
2661
    if instance.name not in node_insts:
2662
      raise errors.OpExecError, ("Instance %s is not running." % instance.name)
2663

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

    
2666
    hyper = hypervisor.GetHypervisor()
2667
    console_cmd = hyper.GetShellCommandForConsole(instance.name)
2668
    return node, console_cmd
2669

    
2670

    
2671
class LUAddMDDRBDComponent(LogicalUnit):
2672
  """Adda new mirror member to an instance's disk.
2673

2674
  """
2675
  HPATH = "mirror-add"
2676
  HTYPE = constants.HTYPE_INSTANCE
2677
  _OP_REQP = ["instance_name", "remote_node", "disk_name"]
2678

    
2679
  def BuildHooksEnv(self):
2680
    """Build hooks env.
2681

2682
    This runs on the master, the primary and all the secondaries.
2683

2684
    """
2685
    env = {
2686
      "INSTANCE_NAME": self.op.instance_name,
2687
      "NEW_SECONDARY": self.op.remote_node,
2688
      "DISK_NAME": self.op.disk_name,
2689
      }
2690
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
2691
          self.op.remote_node,] + list(self.instance.secondary_nodes)
2692
    return env, nl, nl
2693

    
2694
  def CheckPrereq(self):
2695
    """Check prerequisites.
2696

2697
    This checks that the instance is in the cluster.
2698

2699
    """
2700
    instance = self.cfg.GetInstanceInfo(
2701
      self.cfg.ExpandInstanceName(self.op.instance_name))
2702
    if instance is None:
2703
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2704
                                   self.op.instance_name)
2705
    self.instance = instance
2706

    
2707
    remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
2708
    if remote_node is None:
2709
      raise errors.OpPrereqError, ("Node '%s' not known" % self.op.remote_node)
2710
    self.remote_node = remote_node
2711

    
2712
    if remote_node == instance.primary_node:
2713
      raise errors.OpPrereqError, ("The specified node is the primary node of"
2714
                                   " the instance.")
2715

    
2716
    if instance.disk_template != constants.DT_REMOTE_RAID1:
2717
      raise errors.OpPrereqError, ("Instance's disk layout is not"
2718
                                   " remote_raid1.")
2719
    for disk in instance.disks:
2720
      if disk.iv_name == self.op.disk_name:
2721
        break
2722
    else:
2723
      raise errors.OpPrereqError, ("Can't find this device ('%s') in the"
2724
                                   " instance." % self.op.disk_name)
2725
    if len(disk.children) > 1:
2726
      raise errors.OpPrereqError, ("The device already has two slave"
2727
                                   " devices.\n"
2728
                                   "This would create a 3-disk raid1"
2729
                                   " which we don't allow.")
2730
    self.disk = disk
2731

    
2732
  def Exec(self, feedback_fn):
2733
    """Add the mirror component
2734

2735
    """
2736
    disk = self.disk
2737
    instance = self.instance
2738

    
2739
    remote_node = self.remote_node
2740
    new_drbd = _GenerateMDDRBDBranch(self.cfg, self.cfg.GetVGName(),
2741
                                     instance.primary_node, remote_node,
2742
                                     disk.size, "%s-%s" %
2743
                                     (instance.name, self.op.disk_name))
2744

    
2745
    logger.Info("adding new mirror component on secondary")
2746
    #HARDCODE
2747
    if not _CreateBlockDevOnSecondary(self.cfg, remote_node, new_drbd, False):
2748
      raise errors.OpExecError, ("Failed to create new component on secondary"
2749
                                 " node %s" % remote_node)
2750

    
2751
    logger.Info("adding new mirror component on primary")
2752
    #HARDCODE
2753
    if not _CreateBlockDevOnPrimary(self.cfg, instance.primary_node, new_drbd):
2754
      # remove secondary dev
2755
      self.cfg.SetDiskID(new_drbd, remote_node)
2756
      rpc.call_blockdev_remove(remote_node, new_drbd)
2757
      raise errors.OpExecError, ("Failed to create volume on primary")
2758

    
2759
    # the device exists now
2760
    # call the primary node to add the mirror to md
2761
    logger.Info("adding new mirror component to md")
2762
    if not rpc.call_blockdev_addchild(instance.primary_node,
2763
                                           disk, new_drbd):
2764
      logger.Error("Can't add mirror compoment to md!")
2765
      self.cfg.SetDiskID(new_drbd, remote_node)
2766
      if not rpc.call_blockdev_remove(remote_node, new_drbd):
2767
        logger.Error("Can't rollback on secondary")
2768
      self.cfg.SetDiskID(new_drbd, instance.primary_node)
2769
      if not rpc.call_blockdev_remove(instance.primary_node, new_drbd):
2770
        logger.Error("Can't rollback on primary")
2771
      raise errors.OpExecError, "Can't add mirror component to md array"
2772

    
2773
    disk.children.append(new_drbd)
2774

    
2775
    self.cfg.AddInstance(instance)
2776

    
2777
    _WaitForSync(self.cfg, instance)
2778

    
2779
    return 0
2780

    
2781

    
2782
class LURemoveMDDRBDComponent(LogicalUnit):
2783
  """Remove a component from a remote_raid1 disk.
2784

2785
  """
2786
  HPATH = "mirror-remove"
2787
  HTYPE = constants.HTYPE_INSTANCE
2788
  _OP_REQP = ["instance_name", "disk_name", "disk_id"]
2789

    
2790
  def BuildHooksEnv(self):
2791
    """Build hooks env.
2792

2793
    This runs on the master, the primary and all the secondaries.
2794

2795
    """
2796
    env = {
2797
      "INSTANCE_NAME": self.op.instance_name,
2798
      "DISK_NAME": self.op.disk_name,
2799
      "DISK_ID": self.op.disk_id,
2800
      "OLD_SECONDARY": self.old_secondary,
2801
      }
2802
    nl = [self.sstore.GetMasterNode(),
2803
          self.instance.primary_node] + list(self.instance.secondary_nodes)
2804
    return env, nl, nl
2805

    
2806
  def CheckPrereq(self):
2807
    """Check prerequisites.
2808

2809
    This checks that the instance is in the cluster.
2810

2811
    """
2812
    instance = self.cfg.GetInstanceInfo(
2813
      self.cfg.ExpandInstanceName(self.op.instance_name))
2814
    if instance is None:
2815
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2816
                                   self.op.instance_name)
2817
    self.instance = instance
2818

    
2819
    if instance.disk_template != constants.DT_REMOTE_RAID1:
2820
      raise errors.OpPrereqError, ("Instance's disk layout is not"
2821
                                   " remote_raid1.")
2822
    for disk in instance.disks:
2823
      if disk.iv_name == self.op.disk_name:
2824
        break
2825
    else:
2826
      raise errors.OpPrereqError, ("Can't find this device ('%s') in the"
2827
                                   " instance." % self.op.disk_name)
2828
    for child in disk.children:
2829
      if child.dev_type == "drbd" and child.logical_id[2] == self.op.disk_id:
2830
        break
2831
    else:
2832
      raise errors.OpPrereqError, ("Can't find the device with this port.")
2833

    
2834
    if len(disk.children) < 2:
2835
      raise errors.OpPrereqError, ("Cannot remove the last component from"
2836
                                   " a mirror.")
2837
    self.disk = disk
2838
    self.child = child
2839
    if self.child.logical_id[0] == instance.primary_node:
2840
      oid = 1
2841
    else:
2842
      oid = 0
2843
    self.old_secondary = self.child.logical_id[oid]
2844

    
2845
  def Exec(self, feedback_fn):
2846
    """Remove the mirror component
2847

2848
    """
2849
    instance = self.instance
2850
    disk = self.disk
2851
    child = self.child
2852
    logger.Info("remove mirror component")
2853
    self.cfg.SetDiskID(disk, instance.primary_node)
2854
    if not rpc.call_blockdev_removechild(instance.primary_node,
2855
                                              disk, child):
2856
      raise errors.OpExecError, ("Can't remove child from mirror.")
2857

    
2858
    for node in child.logical_id[:2]:
2859
      self.cfg.SetDiskID(child, node)
2860
      if not rpc.call_blockdev_remove(node, child):
2861
        logger.Error("Warning: failed to remove device from node %s,"
2862
                     " continuing operation." % node)
2863

    
2864
    disk.children.remove(child)
2865
    self.cfg.AddInstance(instance)
2866

    
2867

    
2868
class LUReplaceDisks(LogicalUnit):
2869
  """Replace the disks of an instance.
2870

2871
  """
2872
  HPATH = "mirrors-replace"
2873
  HTYPE = constants.HTYPE_INSTANCE
2874
  _OP_REQP = ["instance_name"]
2875

    
2876
  def BuildHooksEnv(self):
2877
    """Build hooks env.
2878

2879
    This runs on the master, the primary and all the secondaries.
2880

2881
    """
2882
    env = {
2883
      "INSTANCE_NAME": self.op.instance_name,
2884
      "NEW_SECONDARY": self.op.remote_node,
2885
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
2886
      }
2887
    nl = [self.sstore.GetMasterNode(),
2888
          self.instance.primary_node] + list(self.instance.secondary_nodes)
2889
    return env, nl, nl
2890

    
2891
  def CheckPrereq(self):
2892
    """Check prerequisites.
2893

2894
    This checks that the instance is in the cluster.
2895

2896
    """
2897
    instance = self.cfg.GetInstanceInfo(
2898
      self.cfg.ExpandInstanceName(self.op.instance_name))
2899
    if instance is None:
2900
      raise errors.OpPrereqError, ("Instance '%s' not known" %
2901
                                   self.op.instance_name)
2902
    self.instance = instance
2903

    
2904
    if instance.disk_template != constants.DT_REMOTE_RAID1:
2905
      raise errors.OpPrereqError, ("Instance's disk layout is not"
2906
                                   " remote_raid1.")
2907

    
2908
    if len(instance.secondary_nodes) != 1:
2909
      raise errors.OpPrereqError, ("The instance has a strange layout,"
2910
                                   " expected one secondary but found %d" %
2911
                                   len(instance.secondary_nodes))
2912

    
2913
    remote_node = getattr(self.op, "remote_node", None)
2914
    if remote_node is None:
2915
      remote_node = instance.secondary_nodes[0]
2916
    else:
2917
      remote_node = self.cfg.ExpandNodeName(remote_node)
2918
      if remote_node is None:
2919
        raise errors.OpPrereqError, ("Node '%s' not known" %
2920
                                     self.op.remote_node)
2921
    if remote_node == instance.primary_node:
2922
      raise errors.OpPrereqError, ("The specified node is the primary node of"
2923
                                   " the instance.")
2924
    self.op.remote_node = remote_node
2925

    
2926
  def Exec(self, feedback_fn):
2927
    """Replace the disks of an instance.
2928

2929
    """
2930
    instance = self.instance
2931
    iv_names = {}
2932
    # start of work
2933
    remote_node = self.op.remote_node
2934
    cfg = self.cfg
2935
    vgname = cfg.GetVGName()
2936
    for dev in instance.disks:
2937
      size = dev.size
2938
      new_drbd = _GenerateMDDRBDBranch(cfg, vgname, instance.primary_node,
2939
                                       remote_node, size,
2940
                                       "%s-%s" % (instance.name, dev.iv_name))
2941
      iv_names[dev.iv_name] = (dev, dev.children[0], new_drbd)
2942
      logger.Info("adding new mirror component on secondary for %s" %
2943
                  dev.iv_name)
2944
      #HARDCODE
2945
      if not _CreateBlockDevOnSecondary(cfg, remote_node, new_drbd, False):
2946
        raise errors.OpExecError, ("Failed to create new component on"
2947
                                   " secondary node %s\n"
2948
                                   "Full abort, cleanup manually!" %
2949
                                   remote_node)
2950

    
2951
      logger.Info("adding new mirror component on primary")
2952
      #HARDCODE
2953
      if not _CreateBlockDevOnPrimary(cfg, instance.primary_node, new_drbd):
2954
        # remove secondary dev
2955
        cfg.SetDiskID(new_drbd, remote_node)
2956
        rpc.call_blockdev_remove(remote_node, new_drbd)
2957
        raise errors.OpExecError("Failed to create volume on primary!\n"
2958
                                 "Full abort, cleanup manually!!")
2959

    
2960
      # the device exists now
2961
      # call the primary node to add the mirror to md
2962
      logger.Info("adding new mirror component to md")
2963
      if not rpc.call_blockdev_addchild(instance.primary_node, dev,
2964
                                        new_drbd):
2965
        logger.Error("Can't add mirror compoment to md!")
2966
        cfg.SetDiskID(new_drbd, remote_node)
2967
        if not rpc.call_blockdev_remove(remote_node, new_drbd):
2968
          logger.Error("Can't rollback on secondary")
2969
        cfg.SetDiskID(new_drbd, instance.primary_node)
2970
        if not rpc.call_blockdev_remove(instance.primary_node, new_drbd):
2971
          logger.Error("Can't rollback on primary")
2972
        raise errors.OpExecError, ("Full abort, cleanup manually!!")
2973

    
2974
      dev.children.append(new_drbd)
2975
      cfg.AddInstance(instance)
2976

    
2977
    # this can fail as the old devices are degraded and _WaitForSync
2978
    # does a combined result over all disks, so we don't check its
2979
    # return value
2980
    _WaitForSync(cfg, instance, unlock=True)
2981

    
2982
    # so check manually all the devices
2983
    for name in iv_names:
2984
      dev, child, new_drbd = iv_names[name]
2985
      cfg.SetDiskID(dev, instance.primary_node)
2986
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
2987
      if is_degr:
2988
        raise errors.OpExecError, ("MD device %s is degraded!" % name)
2989
      cfg.SetDiskID(new_drbd, instance.primary_node)
2990
      is_degr = rpc.call_blockdev_find(instance.primary_node, new_drbd)[5]
2991
      if is_degr:
2992
        raise errors.OpExecError, ("New drbd device %s is degraded!" % name)
2993

    
2994
    for name in iv_names:
2995
      dev, child, new_drbd = iv_names[name]
2996
      logger.Info("remove mirror %s component" % name)
2997
      cfg.SetDiskID(dev, instance.primary_node)
2998
      if not rpc.call_blockdev_removechild(instance.primary_node,
2999
                                                dev, child):
3000
        logger.Error("Can't remove child from mirror, aborting"
3001
                     " *this device cleanup*.\nYou need to cleanup manually!!")
3002
        continue
3003

    
3004
      for node in child.logical_id[:2]:
3005
        logger.Info("remove child device on %s" % node)
3006
        cfg.SetDiskID(child, node)
3007
        if not rpc.call_blockdev_remove(node, child):
3008
          logger.Error("Warning: failed to remove device from node %s,"
3009
                       " continuing operation." % node)
3010

    
3011
      dev.children.remove(child)
3012

    
3013
      cfg.AddInstance(instance)
3014

    
3015

    
3016
class LUQueryInstanceData(NoHooksLU):
3017
  """Query runtime instance data.
3018

3019
  """
3020
  _OP_REQP = ["instances"]
3021

    
3022
  def CheckPrereq(self):
3023
    """Check prerequisites.
3024

3025
    This only checks the optional instance list against the existing names.
3026

3027
    """
3028
    if not isinstance(self.op.instances, list):
3029
      raise errors.OpPrereqError, "Invalid argument type 'instances'"
3030
    if self.op.instances:
3031
      self.wanted_instances = []
3032
      names = self.op.instances
3033
      for name in names:
3034
        instance = self.cfg.GetInstanceInfo(self.cfg.ExpandInstanceName(name))
3035
        if instance is None:
3036
          raise errors.OpPrereqError, ("No such instance name '%s'" % name)
3037
      self.wanted_instances.append(instance)
3038
    else:
3039
      self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
3040
                               in self.cfg.GetInstanceList()]
3041
    return
3042

    
3043

    
3044
  def _ComputeDiskStatus(self, instance, snode, dev):
3045
    """Compute block device status.
3046

3047
    """
3048
    self.cfg.SetDiskID(dev, instance.primary_node)
3049
    dev_pstatus = rpc.call_blockdev_find(instance.primary_node, dev)
3050
    if dev.dev_type == "drbd":
3051
      # we change the snode then (otherwise we use the one passed in)
3052
      if dev.logical_id[0] == instance.primary_node:
3053
        snode = dev.logical_id[1]
3054
      else:
3055
        snode = dev.logical_id[0]
3056

    
3057
    if snode:
3058
      self.cfg.SetDiskID(dev, snode)
3059
      dev_sstatus = rpc.call_blockdev_find(snode, dev)
3060
    else:
3061
      dev_sstatus = None
3062

    
3063
    if dev.children:
3064
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
3065
                      for child in dev.children]
3066
    else:
3067
      dev_children = []
3068

    
3069
    data = {
3070
      "iv_name": dev.iv_name,
3071
      "dev_type": dev.dev_type,
3072
      "logical_id": dev.logical_id,
3073
      "physical_id": dev.physical_id,
3074
      "pstatus": dev_pstatus,
3075
      "sstatus": dev_sstatus,
3076
      "children": dev_children,
3077
      }
3078

    
3079
    return data
3080

    
3081
  def Exec(self, feedback_fn):
3082
    """Gather and return data"""
3083

    
3084
    result = {}
3085
    for instance in self.wanted_instances:
3086
      remote_info = rpc.call_instance_info(instance.primary_node,
3087
                                                instance.name)
3088
      if remote_info and "state" in remote_info:
3089
        remote_state = "up"
3090
      else:
3091
        remote_state = "down"
3092
      if instance.status == "down":
3093
        config_state = "down"
3094
      else:
3095
        config_state = "up"
3096

    
3097
      disks = [self._ComputeDiskStatus(instance, None, device)
3098
               for device in instance.disks]
3099

    
3100
      idict = {
3101
        "name": instance.name,
3102
        "config_state": config_state,
3103
        "run_state": remote_state,
3104
        "pnode": instance.primary_node,
3105
        "snodes": instance.secondary_nodes,
3106
        "os": instance.os,
3107
        "memory": instance.memory,
3108
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
3109
        "disks": disks,
3110
        }
3111

    
3112
      result[instance.name] = idict
3113

    
3114
    return result
3115

    
3116

    
3117
class LUQueryNodeData(NoHooksLU):
3118
  """Logical unit for querying node data.
3119

3120
  """
3121
  _OP_REQP = ["nodes"]
3122

    
3123
  def CheckPrereq(self):
3124
    """Check prerequisites.
3125

3126
    This only checks the optional node list against the existing names.
3127

3128
    """
3129
    self.wanted_nodes = _GetWantedNodes(self, self.op.nodes)
3130

    
3131
  def Exec(self, feedback_fn):
3132
    """Compute and return the list of nodes.
3133

3134
    """
3135

    
3136
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3137
             in self.cfg.GetInstanceList()]
3138
    result = []
3139
    for node in self.wanted_nodes:
3140
      result.append((node.name, node.primary_ip, node.secondary_ip,
3141
                     [inst.name for inst in ilist
3142
                      if inst.primary_node == node.name],
3143
                     [inst.name for inst in ilist
3144
                      if node.name in inst.secondary_nodes],
3145
                     ))
3146
    return result
3147

    
3148

    
3149
class LUSetInstanceParms(LogicalUnit):
3150
  """Modifies an instances's parameters.
3151

3152
  """
3153
  HPATH = "instance-modify"
3154
  HTYPE = constants.HTYPE_INSTANCE
3155
  _OP_REQP = ["instance_name"]
3156

    
3157
  def BuildHooksEnv(self):
3158
    """Build hooks env.
3159

3160
    This runs on the master, primary and secondaries.
3161

3162
    """
3163
    env = {
3164
      "INSTANCE_NAME": self.op.instance_name,
3165
      }
3166
    if self.mem:
3167
      env["MEM_SIZE"] = self.mem
3168
    if self.vcpus:
3169
      env["VCPUS"] = self.vcpus
3170
    if self.do_ip:
3171
      env["INSTANCE_IP"] = self.ip
3172
    if self.bridge:
3173
      env["BRIDGE"] = self.bridge
3174

    
3175
    nl = [self.sstore.GetMasterNode(),
3176
          self.instance.primary_node] + list(self.instance.secondary_nodes)
3177

    
3178
    return env, nl, nl
3179

    
3180
  def CheckPrereq(self):
3181
    """Check prerequisites.
3182

3183
    This only checks the instance list against the existing names.
3184

3185
    """
3186
    self.mem = getattr(self.op, "mem", None)
3187
    self.vcpus = getattr(self.op, "vcpus", None)
3188
    self.ip = getattr(self.op, "ip", None)
3189
    self.bridge = getattr(self.op, "bridge", None)
3190
    if [self.mem, self.vcpus, self.ip, self.bridge].count(None) == 4:
3191
      raise errors.OpPrereqError, ("No changes submitted")
3192
    if self.mem is not None:
3193
      try:
3194
        self.mem = int(self.mem)
3195
      except ValueError, err:
3196
        raise errors.OpPrereqError, ("Invalid memory size: %s" % str(err))
3197
    if self.vcpus is not None:
3198
      try:
3199
        self.vcpus = int(self.vcpus)
3200
      except ValueError, err:
3201
        raise errors.OpPrereqError, ("Invalid vcpus number: %s" % str(err))
3202
    if self.ip is not None:
3203
      self.do_ip = True
3204
      if self.ip.lower() == "none":
3205
        self.ip = None
3206
      else:
3207
        if not utils.IsValidIP(self.ip):
3208
          raise errors.OpPrereqError, ("Invalid IP address '%s'." % self.ip)
3209
    else:
3210
      self.do_ip = False
3211

    
3212
    instance = self.cfg.GetInstanceInfo(
3213
      self.cfg.ExpandInstanceName(self.op.instance_name))
3214
    if instance is None:
3215
      raise errors.OpPrereqError, ("No such instance name '%s'" %
3216
                                   self.op.instance_name)
3217
    self.op.instance_name = instance.name
3218
    self.instance = instance
3219
    return
3220

    
3221
  def Exec(self, feedback_fn):
3222
    """Modifies an instance.
3223

3224
    All parameters take effect only at the next restart of the instance.
3225
    """
3226
    result = []
3227
    instance = self.instance
3228
    if self.mem:
3229
      instance.memory = self.mem
3230
      result.append(("mem", self.mem))
3231
    if self.vcpus:
3232
      instance.vcpus = self.vcpus
3233
      result.append(("vcpus",  self.vcpus))
3234
    if self.do_ip:
3235
      instance.nics[0].ip = self.ip
3236
      result.append(("ip", self.ip))
3237
    if self.bridge:
3238
      instance.nics[0].bridge = self.bridge
3239
      result.append(("bridge", self.bridge))
3240

    
3241
    self.cfg.AddInstance(instance)
3242

    
3243
    return result
3244

    
3245

    
3246
class LUQueryExports(NoHooksLU):
3247
  """Query the exports list
3248

3249
  """
3250
  _OP_REQP = []
3251

    
3252
  def CheckPrereq(self):
3253
    """Check that the nodelist contains only existing nodes.
3254

3255
    """
3256
    self.nodes = _GetWantedNodes(self, getattr(self.op, "nodes", None))
3257

    
3258
  def Exec(self, feedback_fn):
3259
    """Compute the list of all the exported system images.
3260

3261
    Returns:
3262
      a dictionary with the structure node->(export-list)
3263
      where export-list is a list of the instances exported on
3264
      that node.
3265

3266
    """
3267
    return rpc.call_export_list([node.name for node in self.nodes])
3268

    
3269

    
3270
class LUExportInstance(LogicalUnit):
3271
  """Export an instance to an image in the cluster.
3272

3273
  """
3274
  HPATH = "instance-export"
3275
  HTYPE = constants.HTYPE_INSTANCE
3276
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
3277

    
3278
  def BuildHooksEnv(self):
3279
    """Build hooks env.
3280

3281
    This will run on the master, primary node and target node.
3282

3283
    """
3284
    env = {
3285
      "INSTANCE_NAME": self.op.instance_name,
3286
      "EXPORT_NODE": self.op.target_node,
3287
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
3288
      }
3289
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
3290
          self.op.target_node]
3291
    return env, nl, nl
3292

    
3293
  def CheckPrereq(self):
3294
    """Check prerequisites.
3295

3296
    This checks that the instance name is a valid one.
3297

3298
    """
3299
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
3300
    self.instance = self.cfg.GetInstanceInfo(instance_name)
3301
    if self.instance is None:
3302
      raise errors.OpPrereqError, ("Instance '%s' not found" %
3303
                                   self.op.instance_name)
3304

    
3305
    # node verification
3306
    dst_node_short = self.cfg.ExpandNodeName(self.op.target_node)
3307
    self.dst_node = self.cfg.GetNodeInfo(dst_node_short)
3308

    
3309
    if self.dst_node is None:
3310
      raise errors.OpPrereqError, ("Destination node '%s' is uknown." %
3311
                                   self.op.target_node)
3312
    self.op.target_node = self.dst_node.name
3313

    
3314
  def Exec(self, feedback_fn):
3315
    """Export an instance to an image in the cluster.
3316

3317
    """
3318
    instance = self.instance
3319
    dst_node = self.dst_node
3320
    src_node = instance.primary_node
3321
    # shutdown the instance, unless requested not to do so
3322
    if self.op.shutdown:
3323
      op = opcodes.OpShutdownInstance(instance_name=instance.name)
3324
      self.processor.ChainOpCode(op, feedback_fn)
3325

    
3326
    vgname = self.cfg.GetVGName()
3327

    
3328
    snap_disks = []
3329

    
3330
    try:
3331
      for disk in instance.disks:
3332
        if disk.iv_name == "sda":
3333
          # new_dev_name will be a snapshot of an lvm leaf of the one we passed
3334
          new_dev_name = rpc.call_blockdev_snapshot(src_node, disk)
3335

    
3336
          if not new_dev_name:
3337
            logger.Error("could not snapshot block device %s on node %s" %
3338
                         (disk.logical_id[1], src_node))
3339
          else:
3340
            new_dev = objects.Disk(dev_type="lvm", size=disk.size,
3341
                                      logical_id=(vgname, new_dev_name),
3342
                                      physical_id=(vgname, new_dev_name),
3343
                                      iv_name=disk.iv_name)
3344
            snap_disks.append(new_dev)
3345

    
3346
    finally:
3347
      if self.op.shutdown:
3348
        op = opcodes.OpStartupInstance(instance_name=instance.name,
3349
                                       force=False)
3350
        self.processor.ChainOpCode(op, feedback_fn)
3351

    
3352
    # TODO: check for size
3353

    
3354
    for dev in snap_disks:
3355
      if not rpc.call_snapshot_export(src_node, dev, dst_node.name,
3356
                                           instance):
3357
        logger.Error("could not export block device %s from node"
3358
                     " %s to node %s" %
3359
                     (dev.logical_id[1], src_node, dst_node.name))
3360
      if not rpc.call_blockdev_remove(src_node, dev):
3361
        logger.Error("could not remove snapshot block device %s from"
3362
                     " node %s" % (dev.logical_id[1], src_node))
3363

    
3364
    if not rpc.call_finalize_export(dst_node.name, instance, snap_disks):
3365
      logger.Error("could not finalize export for instance %s on node %s" %
3366
                   (instance.name, dst_node.name))
3367

    
3368
    nodelist = self.cfg.GetNodeList()
3369
    nodelist.remove(dst_node.name)
3370

    
3371
    # on one-node clusters nodelist will be empty after the removal
3372
    # if we proceed the backup would be removed because OpQueryExports
3373
    # substitutes an empty list with the full cluster node list.
3374
    if nodelist:
3375
      op = opcodes.OpQueryExports(nodes=nodelist)
3376
      exportlist = self.processor.ChainOpCode(op, feedback_fn)
3377
      for node in exportlist:
3378
        if instance.name in exportlist[node]:
3379
          if not rpc.call_export_remove(node, instance.name):
3380
            logger.Error("could not remove older export for instance %s"
3381
                         " on node %s" % (instance.name, node))