lvmstrap 23.3 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/python
#

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


"""Program which configures LVM on the Ganeti nodes.

This program wipes disks and creates a volume group on top of them. It
can also show disk information to help you decide which disks you want
to wipe.

The error handling is done by raising our own exceptions from most of
the functions; these exceptions then handled globally in the main()
function. The exceptions that each function can raise are not
documented individually, since almost every error path ends in a
raise.

Another two exceptions that are handled globally are IOError and
OSError. The idea behind this is, since we run as root, we should
usually not get these errors, but if we do it's most probably a system
error, so they should be handled and the user instructed to report
them.
"""


import os
import sys
import optparse
import time

from ganeti.utils import RunCmd
from ganeti import constants

USAGE = ("\tlvmstrap.py diskinfo\n"
         "\tlvmstrap.py [--vgname=NAME] { --alldisks | --disks DISKLIST }"
         " create")

verbose_flag = False


class Error(Exception):
  """Generic exception"""
  pass


class ProgrammingError(Error):
  """Exception denoting invalid assumptions in programming.

  This should catch sysfs tree changes, or otherwise incorrect
  assumptions about the contents of the /sys/block/... directories.
  """
  pass


class SysconfigError(Error):
  """Exception denoting invalid system configuration.

  If the system configuration is somehow wrong (e.g. /dev files
  missing, or having mismatched major/minor numbers relative to
  /sys/block devices), this exception will be raised.

  This should usually mean that the installation of the Xen node
  failed in some steps.
  """
  pass


class PrereqError(Error):
  """Exception denoting invalid prerequisites.

  If the node does not meet the requirements for cluster membership, this
  exception will be raised. Things like wrong kernel version, or no
  free disks, etc. belong here.

  This should usually mean that the build steps for the Xen node were
  not followed correctly.
  """
  pass


class OperationalError(Error):
  """Exception denoting actual errors.

  Errors during the bootstrapping are signaled using this exception.
  """
  pass


class ParameterError(Error):
  """Exception denoting invalid input from user.

  Wrong disks given as parameters will be signaled using this
  exception.
  """
  pass

def Usage():
  """Shows program usage information and exits the program."""

  print >> sys.stderr, "Usage:"
  print >> sys.stderr, USAGE
  sys.exit(2)


def ParseOptions():
  """Parses the command line options.

  In case of command line errors, it will show the usage and exit the
  program.

  Returns:
    (options, args), as returned by OptionParser.parse_args
  """
  global verbose_flag

  parser = optparse.OptionParser(usage="\n%s" % USAGE,
                                 version="%%prog (ganeti) %s" %
                                 constants.RELEASE_VERSION)

  parser.add_option("--alldisks", dest="alldisks",
                    help="erase ALL disks", action="store_true",
                    default=False)
  parser.add_option("-d", "--disks", dest="disks",
                    help="Choose disks (e.g. hda,hdg)",
                    metavar="DISKLIST")
  parser.add_option("-v", "--verbose",
                    action="store_true", dest="verbose", default=False,
                    help="print command execution messages to stdout")
  parser.add_option("-g", "--vg-name", type="string",
                    dest="vgname", default="xenvg", metavar="NAME",
                    help="the volume group to be created [default: xenvg]")


  options, args = parser.parse_args()
  if len(args) != 1:
    Usage()

  verbose_flag = options.verbose

  return options, args


def ExecCommand(command):
  """Executes a command.

  This is just a wrapper around commands.getstatusoutput, with the
  difference that if the command line argument -v has been given, it
  will print the command line and the command output on stdout.

  Args:
    the command line
  Returns:
    (status, output) where status is the exit status and output the
      stdout and stderr of the command together
  """

  if verbose_flag:
    print command
  result = RunCmd(command)
  if verbose_flag:
    print result.output
  return result


def CheckPrereq():
  """Check the prerequisites of this program.

  It check that it runs on Linux 2.6, and that /sys is mounted and the
  fact that /sys/block is a directory.
  """

  if os.getuid() != 0:
    raise PrereqError("This tool runs as root only. Really.")

  osname, nodename, release, version, arch = os.uname()
  if osname != 'Linux':
193
194
    raise PrereqError("This tool only runs on Linux"
                      " (detected OS: %s)." % osname)
Iustin Pop's avatar
Iustin Pop committed
195
196

  if not release.startswith("2.6."):
197
198
    raise PrereqError("Wrong major kernel version (detected %s, needs"
                      " 2.6.*)" % release)
Iustin Pop's avatar
Iustin Pop committed
199
200

  if not os.path.ismount("/sys"):
201
202
    raise PrereqError("Can't find a filesystem mounted at /sys."
                      " Please mount /sys.")
Iustin Pop's avatar
Iustin Pop committed
203
204

  if not os.path.isdir("/sys/block"):
205
206
    raise SysconfigError("Can't find /sys/block directory. Has the"
                         " layout of /sys changed?")
Iustin Pop's avatar
Iustin Pop committed
207
208

  if not os.path.ismount("/proc"):
209
210
    raise PrereqError("Can't find a filesystem mounted at /proc."
                      " Please mount /proc.")
Iustin Pop's avatar
Iustin Pop committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230

  if not os.path.exists("/proc/mounts"):
    raise SysconfigError("Can't find /proc/mounts")


def CheckVGExists(vgname):
  """Checks to see if a volume group exists.

  Args:
    vgname: the volume group name

  Returns:
    a four-tuple (exists, lv_count, vg_size, vg_free), where:
      exists: True if the volume exists, otherwise False; if False,
        all other members of the tuple are None
      lv_count: The number of logical volumes in the volume group
      vg_size: The total size of the volume group (in gibibytes)
      vg_free: The available space in the volume group
  """

231
232
233
  result = ExecCommand("vgs --nohead -o lv_count,vg_size,vg_free"
                       " --nosuffix --units g"
                       " --ignorelockingfailure %s" % vgname)
Iustin Pop's avatar
Iustin Pop committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
  if not result.failed:
    try:
      lv_count, vg_size, vg_free = result.stdout.strip().split()
    except ValueError:
      # This means the output of vgdisplay can't be parsed
      raise PrereqError("cannot parse output of vgs (%s)" % result.stdout)
  else:
    lv_count = vg_size = vg_free = None

  return not result.failed, lv_count, vg_size, vg_free


def CheckSysDev(name, devnum):
  """Checks consistency between /sys and /dev trees.

  In /sys/block/<name>/dev and /sys/block/<name>/<part>/dev are the
  kernel-known device numbers. The /dev/<name> block/char devices are
  created by userspace and thus could differ from the kernel
  view. This function checks the consistency between the device number
  read from /sys and the actual device number in /dev.

  Note that since the system could be using udev which removes and
  recreates the device nodes on partition table rescan, we need to do
  some retries here. Since we only do a stat, we can afford to do many
  short retries.

  Args:
   name: the device name, e.g. 'sda'
   devnum: the device number, e.g. 0x803 (2051 in decimal) for sda3

  Returns:
    None; failure of the check is signalled by raising a
      SysconfigError exception
  """

  path = "/dev/%s" % name
  for retries in range(40):
    if os.path.exists(path):
      break
    time.sleep(0.250)
  else:
275
276
    raise SysconfigError("the device file %s does not exist, but the block"
                         " device exists in the /sys/block tree" % path)
Iustin Pop's avatar
Iustin Pop committed
277
278
  rdev = os.stat(path).st_rdev
  if devnum != rdev:
279
280
    raise SysconfigError("For device %s, the major:minor in /dev is %04x"
                         " while the major:minor in sysfs is %s" %
Iustin Pop's avatar
Iustin Pop committed
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
                         (path, rdev, devnum))


def ReadDev(syspath):
  """Reads the device number from a sysfs path.

  The device number is given in sysfs under a block device directory
  in a file named 'dev' which contains major:minor (in ASCII). This
  function reads that file and converts the major:minor pair to a dev
  number.

  Args:
    syspath: the path to a block device dir in sysfs, e.g. /sys/block/sda

  Returns:
    the device number
  """

  if not os.path.exists("%s/dev" % syspath):
    raise ProgrammingError("Invalid path passed to ReadDev: %s" % syspath)
  f = open("%s/dev" % syspath)
  data = f.read().strip()
  f.close()
  major, minor = data.split(":", 1)
  major = int(major)
  minor = int(minor)
  dev = os.makedev(major, minor)
  return dev


def ReadSize(syspath):
  """Reads the size from a sysfs path.

  The size is given in sysfs under a block device directory in a file
  named 'size' which contains the number of sectors (in ASCII). This
  function reads that file and converts the number in sectors to the
  size in bytes.

  Args:
    syspath: the path to a block device dir in sysfs, e.g. /sys/block/sda

  Returns:
    the device size in bytes
  """

  if not os.path.exists("%s/size" % syspath):
    raise ProgrammingError("Invalid path passed to ReadSize: %s" % syspath)
  f = open("%s/size" % syspath)
  data = f.read().strip()
  f.close()
  size = 512L * int(data)
  return size


def ReadPV(name):
  """Reads physical volume information.

  This function tries to see if a block device is a physical volume.

  Args:
    dev: the device name (e.g. sda)
  Returns:
    The name of the volume group to which this PV belongs, or
    "" if this PV is not in use, or
    None if this is not a PV
  """

  result = ExecCommand("pvdisplay -c /dev/%s" % name)
  if result.failed:
    return None
  vgname = result.stdout.strip().split(":")[1]
  return vgname


def GetDiskList():
  """Computes the block device list for this system.

  This function examines the /sys/block tree and using information
  therein, computes the status of the block device.

  Returns:
    [(name, size, dev, partitions, inuse), ...]
  where:
    name is the block device name (e.g. sda)
    size the size in bytes
    dev  the device number (e.g. 8704 for hdg)
    partitions is [(name, size, dev), ...] mirroring the disk list data
    inuse is a boolean showing the in-use status of the disk, computed as the
      possibility of re-reading the partition table (the meaning of the
      operation varies with the kernel version, but is usually accurate;
      a mounted disk/partition or swap-area or PV with active LVs on it
      is busy)
  """

  dlist = []
  for name in os.listdir("/sys/block"):
    if (not name.startswith("hd") and
        not name.startswith("sd") and
Michael Hanselmann's avatar
Michael Hanselmann committed
379
        not name.startswith("ubd")):
Iustin Pop's avatar
Iustin Pop committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
      continue

    size = ReadSize("/sys/block/%s" % name)

    f = open("/sys/block/%s/removable" % name)
    removable = int(f.read().strip())
    f.close()

    if removable:
      continue

    dev = ReadDev("/sys/block/%s" % name)
    CheckSysDev(name, dev)
    inuse = not CheckReread(name)
    # Enumerate partitions of the block device
    partitions = []
    for partname in os.listdir("/sys/block/%s" % name):
      if not partname.startswith(name):
        continue
      partdev = ReadDev("/sys/block/%s/%s" % (name, partname))
      partsize = ReadSize("/sys/block/%s/%s" % (name, partname))
      CheckSysDev(partname, partdev)
      partitions.append((partname, partsize, partdev))
    partitions.sort()
    dlist.append((name, size, dev, partitions, inuse))
  dlist.sort()
  return dlist


def GetMountInfo():
  """Reads /proc/mounts and computes the mountpoint-devnum mapping.

  This function reads /proc/mounts, finds the mounted filesystems
  (excepting a hard-coded blacklist of network and virtual
  filesystems) and does a stat on these mountpoints. The st_dev number
  of the results is memorised for later matching against the
  /sys/block devices.

  Returns:
   a mountpoint: device number dictionary
  """

  f = open("/proc/mounts", "r")
  mountlines = f.readlines()
  f.close()
  mounts = {}
  for line in mountlines:
    device, mountpoint, fstype, rest = line.split(None, 3)
    # fs type blacklist
    if fstype in ["nfs", "nfs4", "autofs", "tmpfs", "proc", "sysfs"]:
      continue
    try:
      dev = os.stat(mountpoint).st_dev
    except OSError, err:
      # this should be a fairly rare error, since we are blacklisting
      # network filesystems; with this in mind, we'll ignore it,
      # since the rereadpt check catches in-use filesystems,
      # and this is used for disk information only
      print >> sys.stderr, ("Can't stat mountpoint '%s': %s" %
                            (mountpoint, err))
      print >> sys.stderr, "Ignoring."
      continue
    mounts[dev] = mountpoint
  return mounts


def DevInfo(name, dev, mountinfo):
  """Computes miscellaneous informations about a block device.

  Args:
    name: the device name, e.g. sda

  Returns:
    (mpath, whatvg, fileinfo), where
    mpath is the mount path where this device is mounted or None
    whatvg is the result of the ReadPV function
    fileinfo is the output of file -bs on the device
  """

  if dev in mountinfo:
    mpath = mountinfo[dev]
  else:
    mpath = None

  whatvg = ReadPV(name)

  result = ExecCommand("file -bs /dev/%s" % name)
  if result.failed:
    fileinfo = "<error: %s>" % result.stderr
  fileinfo = result.stdout[:45]
  return mpath, whatvg, fileinfo


def ShowDiskInfo():
  """Shows a nicely formatted block device list for this system.

  This function shows the user a table with the informations gathered
  by the other functions defined, in order to help the user make a
  choice about which disks should be allocated to our volume group.

  """
  mounts = GetMountInfo()
  dlist = GetDiskList()

  print "------- Disk information -------"
  print ("%5s %7s %4s %5s %-10s %s" %
         ("Name", "Size[M]", "Used", "Mount", "LVM?", "Info"))

  flatlist = []
  # Flatten the [(disk, [partition,...]), ...] list
  for name, size, dev, parts, inuse in dlist:
    if inuse:
      str_inuse = "yes"
    else:
      str_inuse = "no"
    flatlist.append((name, size, dev, str_inuse))
    for partname, partsize, partdev in parts:
      flatlist.append((partname, partsize, partdev, ""))

  for name, size, dev, in_use in flatlist:
    mp, vgname, fileinfo = DevInfo(name, dev, mounts)
    if mp is None:
      mp = "-"
    if vgname is None:
      lvminfo = "-"
    elif vgname == "":
      lvminfo = "yes,free"
    else:
      lvminfo = "in %s" % vgname

    if len(name) > 3:
      # Indent partitions
      name = " %s" % name
    print ("%-5s %7.2f %-4s %-5s %-10s %s" %
           (name, float(size) / 1024 / 1024, in_use, mp, lvminfo, fileinfo))


def CheckReread(name):
  """Check to see if a block device is in use.

  Uses blockdev to reread the partition table of a block device, and
  thus compute the in-use status. See the discussion in GetDiskList
  about the meaning of 'in use'.

  Returns:
    boolean, the in-use status of the device
  """

  for retries in range(3):
    result = ExecCommand("blockdev --rereadpt /dev/%s" % name)
    if not result.failed:
      break
    time.sleep(2)

  return not result.failed


def WipeDisk(name):
  """Wipes a block device.

  This function wipes a block device, by clearing and re-reading the
  partition table. If not successful, it writes back the old partition
  data, and leaves the cleanup to the user.

  Args:
    the device name (e.g. sda)
  """

  if not CheckReread(name):
549
550
    raise OperationalError("CRITICAL: disk %s you selected seems to be in"
                           " use. ABORTING!" % name)
Iustin Pop's avatar
Iustin Pop committed
551
552
553
554

  fd = os.open("/dev/%s" % name, os.O_RDWR | os.O_SYNC)
  olddata = os.read(fd, 512)
  if len(olddata) != 512:
555
556
    raise OperationalError("CRITICAL: Can't read partition table information"
                           " from /dev/%s (needed 512 bytes, got %d" %
Iustin Pop's avatar
Iustin Pop committed
557
558
559
560
561
562
563
                           (name, len(olddata)))
  newdata = "\0" * 512
  os.lseek(fd, 0, 0)
  bytes_written = os.write(fd, newdata)
  os.close(fd)
  if bytes_written != 512:
    raise OperationalError("CRITICAL: Can't write partition table information"
564
565
                           " to /dev/%s (tried to write 512 bytes, written"
                           " %d. I don't know how to cleanup. Sorry." %
Iustin Pop's avatar
Iustin Pop committed
566
567
568
569
570
571
                           (name, bytes_written))

  if not CheckReread(name):
    fd = os.open("/dev/%s" % name, os.O_RDWR | os.O_SYNC)
    os.write(fd, olddata)
    os.close(fd)
572
573
574
575
576
    raise OperationalError("CRITICAL: disk %s which I have just wiped cannot"
                           " reread partition table. Most likely, it is"
                           " in use. You have to clean after this yourself."
                           " I tried to restore the old partition table,"
                           " but I cannot guarantee nothing has broken." %
Iustin Pop's avatar
Iustin Pop committed
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
                           name)


def PartitionDisk(name):
  """Partitions a disk.

  This function creates a single partition spanning the entire disk,
  by means of fdisk.

  Args:
    the device name, e.g. sda
  """
  result = ExecCommand(
    'echo ,,8e, | sfdisk /dev/%s' % name)
  if result.failed:
592
593
594
595
596
    raise OperationalError("CRITICAL: disk %s which I have just partitioned"
                           " cannot reread its partition table, or there"
                           " is some other sfdisk error. Likely, it is in"
                           " use. You have to clean this yourself. Error"
                           " message from sfdisk: %s" %
Iustin Pop's avatar
Iustin Pop committed
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
                           (name, result.output))


def CreatePVOnDisk(name):
  """Creates a physical volume on a block device.

  This function creates a physical volume on a block device, overriding
  all warnings. So it can wipe existing PVs and PVs which are in a VG.

  Args:
    the device name, e.g. sda

  """
  result = ExecCommand("pvcreate -yff /dev/%s1 " % name)
  if result.failed:
612
613
614
    raise OperationalError("I cannot create a physical volume on"
                           " partition /dev/%s1. Error message: %s."
                           " Please clean up yourself." %
Iustin Pop's avatar
Iustin Pop committed
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
                           (name, result.output))


def CreateVG(vgname, disks):
  """Creates the volume group.

  This function creates a volume group named `vgname` on the disks
  given as parameters. The physical extent size is set to 64MB.

  Args:
    disks: a list of disk names, e.g. ['sda','sdb']

  """
  pnames = ["'/dev/%s1'" % disk for disk in disks]
  result = ExecCommand("vgcreate -s 64MB '%s' %s" % (vgname, " ".join(pnames)))
  if result.failed:
631
632
633
    raise OperationalError("I cannot create the volume group %s from"
                           " disks %s. Error message: %s. Please clean up"
                           " yourself." %
Iustin Pop's avatar
Iustin Pop committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
                           (vgname, " ".join(disks), result.output))


def ValidateDiskList(options):
  """Validates or computes the disk list for create.

  This function either computes the available disk list (if the user
  gave --alldisks option), or validates the user-given disk list (by
  using the --disks option) such that all given disks are present and
  not in use.

  Args:
    the options returned from OptParser.parse_options

  Returns:
    a list of disk names, e.g. ['sda', 'sdb']
  """

  sysdisks = GetDiskList()
  if not sysdisks:
654
655
    raise PrereqError("no disks found (I looked for"
                      " non-removable block devices).")
Iustin Pop's avatar
Iustin Pop committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
  sysd_free = []
  sysd_used = []
  for name, size, dev, part, used in sysdisks:
    if used:
      sysd_used.append(name)
    else:
      sysd_free.append(name)

  if not sysd_free:
    raise PrereqError("no free disks found! (%d in-use disks)" %
                      len(sysd_used))
  if options.alldisks:
    disklist = sysd_free
  elif options.disks:
    disklist = options.disks.split(",")
    for name in disklist:
      if name in sysd_used:
        raise ParameterError("disk %s is in use, cannot wipe!" % name)
      if name not in sysd_free:
        raise ParameterError("cannot find disk %s!" % name)
  else:
    raise ParameterError("Please use either --alldisks or --disks!")

  return disklist

681

Iustin Pop's avatar
Iustin Pop committed
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
def BootStrap():
  """Actual main routine."""

  CheckPrereq()

  options, args = ParseOptions()
  vgname = options.vgname
  command = args.pop(0)
  if command == "diskinfo":
    ShowDiskInfo()
    return
  if command != "create":
    Usage()

  exists, lv_count, vg_size, vg_free = CheckVGExists(vgname)
  if exists:
    raise PrereqError("It seems volume group '%s' already exists:\n"
                      "  LV count: %s, size: %s, free: %s." %
                      (vgname, lv_count, vg_size, vg_free))


  disklist = ValidateDiskList(options)

  for disk in disklist:
    WipeDisk(disk)
    PartitionDisk(disk)
  for disk in disklist:
    CreatePVOnDisk(disk)
  CreateVG(vgname, disklist)

  status, lv_count, size, free = CheckVGExists(vgname)
  if status:
    print "Done! %s: size %s GiB, disks: %s" % (vgname, size,
715
                                              ",".join(disklist))
Iustin Pop's avatar
Iustin Pop committed
716
  else:
717
718
    raise OperationalError("Although everything seemed ok, the volume"
                           " group did not get created.")
Iustin Pop's avatar
Iustin Pop committed
719
720
721
722
723
724
725
726
727
728
729
730


def main():
  """application entry point.

  This is just a wrapper over BootStrap, to handle our own exceptions.
  """

  try:
    BootStrap()
  except PrereqError, err:
    print >> sys.stderr, "The prerequisites for running this tool are not met."
731
732
    print >> sys.stderr, ("Please make sure you followed all the steps in"
                          " the build document.")
Iustin Pop's avatar
Iustin Pop committed
733
734
735
    print >> sys.stderr, "Description: %s" % str(err)
    sys.exit(1)
  except SysconfigError, err:
736
737
738
739
    print >> sys.stderr, ("This system's configuration seems wrong, at"
                          " least is not what I expect.")
    print >> sys.stderr, ("Please check that the installation didn't fail"
                          " at some step.")
Iustin Pop's avatar
Iustin Pop committed
740
741
742
    print >> sys.stderr, "Description: %s" % str(err)
    sys.exit(1)
  except ParameterError, err:
743
744
    print >> sys.stderr, ("Some parameters you gave to the program or the"
                          " invocation is wrong. ")
Iustin Pop's avatar
Iustin Pop committed
745
746
747
    print >> sys.stderr, "Description: %s" % str(err)
    Usage()
  except OperationalError, err:
748
749
750
751
752
753
    print >> sys.stderr, ("A serious error has happened while modifying"
                          " the system's configuration.")
    print >> sys.stderr, ("Please review the error message below and make"
                          " sure you clean up yourself.")
    print >> sys.stderr, ("It is most likely that the system configuration"
                          " has been partially altered.")
Iustin Pop's avatar
Iustin Pop committed
754
755
756
    print >> sys.stderr, str(err)
    sys.exit(1)
  except ProgrammingError, err:
757
758
    print >> sys.stderr, ("Internal application error. Please signal this"
                          " to xencluster-team.")
Iustin Pop's avatar
Iustin Pop committed
759
760
761
762
763
764
765
766
767
768
769
770
771
    print >> sys.stderr, "Error description: %s" % str(err)
    sys.exit(1)
  except Error, err:
    print >> sys.stderr, "Unhandled application error: %s" % err
    sys.exit(1)
  except (IOError, OSError), err:
    print >> sys.stderr, "I/O error detected, please report."
    print >> sys.stderr, "Description: %s" % str(err)
    sys.exit(1)


if __name__ == "__main__":
  main()