3 # Copyright (c) 2007, Red Hat, Inc.
4 # Copyright (c) 2009, 2010, 2011 Intel, Inc.
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the Free
8 # Software Foundation; version 2 of the License
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc., 59
17 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 from __future__ import with_statement
30 from mic.utils import runner
31 from mic.utils.errors import *
34 def find_binary_inchroot(binary, chroot):
42 bin_path = "%s/%s" % (path, binary)
43 if os.path.exists("%s/%s" % (chroot, bin_path)):
47 def find_binary_path(binary):
48 if os.environ.has_key("PATH"):
49 paths = os.environ["PATH"].split(":")
52 if os.environ.has_key("HOME"):
53 paths += [os.environ["HOME"] + "/bin"]
54 paths += ["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin"]
57 bin_path = "%s/%s" % (path, binary)
58 if os.path.exists(bin_path):
60 raise CreatorError("Command '%s' is not available." % binary)
62 def makedirs(dirname):
63 """A version of os.makedirs() that doesn't throw an
64 exception if the leaf directory already exists.
69 if err.errno != errno.EEXIST:
72 def mksquashfs(in_img, out_img):
73 fullpathmksquashfs = find_binary_path("mksquashfs")
74 args = [fullpathmksquashfs, in_img, out_img]
76 if not sys.stdout.isatty():
77 args.append("-no-progress")
79 ret = runner.show(args)
81 raise SquashfsError("'%s' exited with error (%d)" % (' '.join(args), ret))
83 def resize2fs(fs, size):
84 resize2fs = find_binary_path("resize2fs")
86 # it means to minimalize it
87 return runner.show([resize2fs, '-M', fs])
89 return runner.show([resize2fs, fs, "%sK" % (size / 1024,)])
91 class BindChrootMount:
92 """Represents a bind mount of a directory into a chroot."""
93 def __init__(self, src, chroot, dest = None, option = None):
94 self.root = os.path.abspath(os.path.expanduser(chroot))
95 self.mount_option = option
97 self.orig_src = self.src = src
98 if os.path.islink(src):
99 self.src = os.readlink(src)
100 if not self.src.startswith('/'):
101 self.src = os.path.abspath(os.path.join(os.path.dirname(src),
106 self.dest = os.path.join(self.root, dest.lstrip('/'))
109 self.mountcmd = find_binary_path("mount")
110 self.umountcmd = find_binary_path("umount")
113 with open('/proc/mounts') as f:
115 if line.split()[1] == os.path.abspath(self.dest):
121 if self.mounted or self.ismounted():
127 if err.errno == errno.ENOSPC:
128 msger.warning("No space left on device '%s'" % err.filename)
131 if self.mount_option:
132 cmdline = [self.mountcmd, "-o" ,"bind", "-o", "%s" % \
133 self.mount_option, self.src, self.dest]
135 cmdline = [self.mountcmd, "-o" ,"bind", self.src, self.dest]
136 rc, errout = runner.runtool(cmdline, catch=2)
138 raise MountError("Bind-mounting '%s' to '%s' failed: %s" %
139 (self.src, self.dest, errout))
142 if os.path.islink(self.orig_src):
143 dest = os.path.join(self.root, self.orig_src.lstrip('/'))
144 if not os.path.exists(dest):
145 os.symlink(self.src, dest)
148 if self.mounted or self.ismounted():
149 runner.show([self.umountcmd, "-l", self.dest])
153 """LoopbackMount compatibility layer for old API"""
154 def __init__(self, lofile, mountdir, fstype = None):
155 self.diskmount = DiskMount(LoopbackDisk(lofile,size = 0),mountdir,fstype,rmmountdir = True)
157 self.losetupcmd = find_binary_path("losetup")
160 self.diskmount.cleanup()
163 self.diskmount.unmount()
167 runner.show([self.losetupcmd, "-d", self.loopdev])
175 self.loopdev = get_loop_device(self.losetupcmd, self.lofile)
179 self.diskmount.mount()
181 class SparseLoopbackMount(LoopbackMount):
182 """SparseLoopbackMount compatibility layer for old API"""
183 def __init__(self, lofile, mountdir, size, fstype = None):
184 self.diskmount = DiskMount(SparseLoopbackDisk(lofile,size),mountdir,fstype,rmmountdir = True)
186 def expand(self, create = False, size = None):
187 self.diskmount.disk.expand(create, size)
189 def truncate(self, size = None):
190 self.diskmount.disk.truncate(size)
193 self.diskmount.disk.create()
195 class SparseExtLoopbackMount(SparseLoopbackMount):
196 """SparseExtLoopbackMount compatibility layer for old API"""
197 def __init__(self, lofile, mountdir, size, fstype, blocksize, fslabel):
198 self.diskmount = ExtDiskMount(SparseLoopbackDisk(lofile,size), mountdir, fstype, blocksize, fslabel, rmmountdir = True)
201 def __format_filesystem(self):
202 self.diskmount.__format_filesystem()
205 self.diskmount.disk.create()
207 def resize(self, size = None):
208 return self.diskmount.__resize_filesystem(size)
211 self.diskmount.mount()
214 self.extdiskmount.__fsck()
216 def __get_size_from_filesystem(self):
217 return self.diskmount.__get_size_from_filesystem()
219 def __resize_to_minimal(self):
220 return self.diskmount.__resize_to_minimal()
222 def resparse(self, size = None):
223 return self.diskmount.resparse(size)
226 """Generic base object for a disk
228 The 'create' method must make the disk visible as a block device - eg
229 by calling losetup. For RawDisk, this is obviously a no-op. The 'cleanup'
230 method must undo the 'create' operation.
232 def __init__(self, size, device = None):
233 self._device = device
242 def get_device(self):
244 def set_device(self, path):
246 device = property(get_device, set_device)
250 size = property(get_size)
254 """A Disk backed by a block device.
255 Note that create() is a no-op.
257 def __init__(self, size, device):
258 Disk.__init__(self, size, device)
266 class LoopbackDisk(Disk):
267 """A Disk backed by a file via the loop module."""
268 def __init__(self, lofile, size):
269 Disk.__init__(self, size)
271 self.losetupcmd = find_binary_path("losetup")
277 return os.path.exists(self.lofile)
280 if self.device is not None:
283 self.device = get_loop_device(self.losetupcmd, self.lofile)
286 if self.device is None:
288 msger.debug("Losetup remove %s" % self.device)
289 rc = runner.show([self.losetupcmd, "-d", self.device])
292 class SparseLoopbackDisk(LoopbackDisk):
293 """A Disk backed by a sparse file via the loop module."""
294 def __init__(self, lofile, size):
295 LoopbackDisk.__init__(self, lofile, size)
297 def expand(self, create = False, size = None):
301 if not os.path.exists(self.lofile):
302 makedirs(os.path.dirname(self.lofile))
307 msger.debug("Extending sparse file %s to %d" % (self.lofile, size))
309 fd = os.open(self.lofile, flags, 0644)
311 fd = os.open(self.lofile, flags)
316 os.ftruncate(fd, size)
318 # may be limited by 2G in 32bit env
319 os.ftruncate(fd, 2**31L)
323 def truncate(self, size = None):
327 msger.debug("Truncating sparse file %s to %d" % (self.lofile, size))
328 fd = os.open(self.lofile, os.O_WRONLY)
329 os.ftruncate(fd, size)
333 self.expand(create = True)
334 LoopbackDisk.create(self)
337 """A generic base class to deal with mounting things."""
338 def __init__(self, mountdir):
339 self.mountdir = mountdir
344 def mount(self, options = None):
350 class DiskMount(Mount):
351 """A Mount object that handles mounting of a Disk."""
352 def __init__(self, disk, mountdir, fstype = None, rmmountdir = True):
353 Mount.__init__(self, mountdir)
357 self.rmmountdir = rmmountdir
362 self.mkfscmd = find_binary_path("mkfs." + self.fstype)
365 self.mountcmd = find_binary_path("mount")
366 self.umountcmd = find_binary_path("umount")
374 msger.debug("Unmounting directory %s" % self.mountdir)
375 runner.quiet('sync') # sync the data on this mount point
376 rc = runner.show([self.umountcmd, "-l", self.mountdir])
380 raise MountError("Failed to umount %s" % self.mountdir)
381 if self.rmdir and not self.mounted:
383 os.rmdir(self.mountdir)
393 def mount(self, options = None):
397 if not os.path.isdir(self.mountdir):
398 msger.debug("Creating mount point %s" % self.mountdir)
399 os.makedirs(self.mountdir)
400 self.rmdir = self.rmmountdir
404 msger.debug("Mounting %s at %s" % (self.disk.device, self.mountdir))
406 args = [ self.mountcmd, "-o", options, self.disk.device, self.mountdir ]
408 args = [ self.mountcmd, self.disk.device, self.mountdir ]
410 args.extend(["-t", self.fstype])
412 rc = runner.show(args)
414 raise MountError("Failed to mount '%s' to '%s' with command '%s'. Retval: %s" %
415 (self.disk.device, self.mountdir, " ".join(args), rc))
419 class ExtDiskMount(DiskMount):
420 """A DiskMount object that is able to format/resize ext[23] filesystems."""
421 def __init__(self, disk, mountdir, fstype, blocksize, fslabel, rmmountdir=True, skipformat = False, fsopts = None, fsuuid=None):
422 DiskMount.__init__(self, disk, mountdir, fstype, rmmountdir)
423 self.blocksize = blocksize
424 self.fslabel = fslabel.replace("/", "")
425 self.uuid = fsuuid or str(uuid.uuid4())
426 self.skipformat = skipformat
429 self.dumpe2fs = find_binary_path("dumpe2fs")
430 self.tune2fs = find_binary_path("tune2fs")
432 def __parse_field(self, output, field):
433 for line in output.split("\n"):
434 if line.startswith(field + ":"):
435 return line[len(field) + 1:].strip()
437 raise KeyError("Failed to find field '%s' in output" % field)
439 def __format_filesystem(self):
441 msger.debug("Skip filesystem format.")
444 msger.verbose("Formating %s filesystem on %s" % (self.fstype, self.disk.device))
445 cmdlist = [self.mkfscmd, "-F", "-L", self.fslabel, "-m", "1", "-b",
446 str(self.blocksize), "-U", self.uuid]
448 cmdlist.extend(self.extopts.split())
449 cmdlist.extend([self.disk.device])
451 rc, errout = runner.runtool(cmdlist, catch=2)
453 raise MountError("Error creating %s filesystem on disk %s:\n%s" %
454 (self.fstype, self.disk.device, errout))
457 msger.debug("Tuning filesystem on %s" % self.disk.device)
458 runner.show([self.tune2fs, "-c0", "-i0", "-Odir_index", "-ouser_xattr,acl", self.disk.device])
460 def __resize_filesystem(self, size = None):
461 msger.info("Resizing filesystem ...")
462 current_size = os.stat(self.disk.lofile)[stat.ST_SIZE]
465 size = self.disk.size
467 if size == current_size:
470 if size > current_size:
471 self.disk.expand(size)
475 resize2fs(self.disk.lofile, size)
480 if not self.disk.fixed() and self.disk.exists():
486 self.__resize_filesystem()
488 self.__format_filesystem()
490 def mount(self, options = None):
492 DiskMount.mount(self, options)
495 msger.info("Checking filesystem %s" % self.disk.lofile)
496 runner.quiet(["/sbin/e2fsck", "-f", "-y", self.disk.lofile])
498 def __get_size_from_filesystem(self):
499 return int(self.__parse_field(runner.outs([self.dumpe2fs, '-h', self.disk.lofile]),
500 "Block count")) * self.blocksize
502 def __resize_to_minimal(self):
503 msger.info("Resizing filesystem to minimal ...")
507 # Use a binary search to find the minimal size
508 # we can resize the image to
511 top = self.__get_size_from_filesystem()
512 while top != (bot + 1):
513 t = bot + ((top - bot) / 2)
515 if not resize2fs(self.disk.lofile, t):
521 def resparse(self, size = None):
526 minsize = self.__resize_to_minimal()
527 self.disk.truncate(minsize)
529 self.__resize_filesystem(size)
532 class VfatDiskMount(DiskMount):
533 """A DiskMount object that is able to format vfat/msdos filesystems."""
534 def __init__(self, disk, mountdir, fstype, blocksize, fslabel, rmmountdir=True, skipformat = False, fsopts = None, fsuuid = None):
535 DiskMount.__init__(self, disk, mountdir, fstype, rmmountdir)
536 self.blocksize = blocksize
537 self.fslabel = fslabel.replace("/", "")
538 rand1 = random.randint(0, 2**16 - 1)
539 rand2 = random.randint(0, 2**16 - 1)
540 self.uuid = fsuuid or "%04X-%04X" % (rand1, rand2)
541 self.skipformat = skipformat
543 self.fsckcmd = find_binary_path("fsck." + self.fstype)
545 def __format_filesystem(self):
547 msger.debug("Skip filesystem format.")
550 msger.verbose("Formating %s filesystem on %s" % (self.fstype, self.disk.device))
551 rc = runner.show([self.mkfscmd, "-n", self.fslabel,
552 "-i", self.uuid.replace("-", ""), self.disk.device])
554 raise MountError("Error creating %s filesystem on disk %s" % (self.fstype,self.disk.device))
556 msger.verbose("Tuning filesystem on %s" % self.disk.device)
558 def __resize_filesystem(self, size = None):
559 current_size = os.stat(self.disk.lofile)[stat.ST_SIZE]
562 size = self.disk.size
564 if size == current_size:
567 if size > current_size:
568 self.disk.expand(size)
572 #resize2fs(self.disk.lofile, size)
577 if not self.disk.fixed() and self.disk.exists():
583 self.__resize_filesystem()
585 self.__format_filesystem()
587 def mount(self, options = None):
589 DiskMount.mount(self, options)
592 msger.debug("Checking filesystem %s" % self.disk.lofile)
593 runner.show([self.fsckcmd, "-y", self.disk.lofile])
595 def __get_size_from_filesystem(self):
596 return self.disk.size
598 def __resize_to_minimal(self):
602 # Use a binary search to find the minimal size
603 # we can resize the image to
606 top = self.__get_size_from_filesystem()
609 def resparse(self, size = None):
611 minsize = self.__resize_to_minimal()
612 self.disk.truncate(minsize)
613 self.__resize_filesystem(size)
616 class BtrfsDiskMount(DiskMount):
617 """A DiskMount object that is able to format/resize btrfs filesystems."""
618 def __init__(self, disk, mountdir, fstype, blocksize, fslabel, rmmountdir=True, skipformat = False, fsopts = None, fsuuid = None):
620 DiskMount.__init__(self, disk, mountdir, fstype, rmmountdir)
621 self.blocksize = blocksize
622 self.fslabel = fslabel.replace("/", "")
623 self.uuid = fsuuid or None
624 self.skipformat = skipformat
626 self.blkidcmd = find_binary_path("blkid")
627 self.btrfsckcmd = find_binary_path("btrfsck")
629 def __check_btrfs(self):
631 """ Need to load btrfs module to mount it """
633 for line in open("/proc/filesystems").xreadlines():
634 if line.find("btrfs") > -1:
638 raise MountError("Your system can't mount btrfs filesystem, please make sure your kernel has btrfs support and the module btrfs.ko has been loaded.")
640 # disable selinux, selinux will block write
641 if os.path.exists("/usr/sbin/setenforce"):
642 runner.show(["/usr/sbin/setenforce", "0"])
644 def __parse_field(self, output, field):
645 for line in output.split(" "):
646 if line.startswith(field + "="):
647 return line[len(field) + 1:].strip().replace("\"", "")
649 raise KeyError("Failed to find field '%s' in output" % field)
651 def __format_filesystem(self):
653 msger.debug("Skip filesystem format.")
656 msger.verbose("Formating %s filesystem on %s" % (self.fstype, self.disk.device))
657 rc = runner.show([self.mkfscmd, "-L", self.fslabel, self.disk.device])
659 raise MountError("Error creating %s filesystem on disk %s" % (self.fstype,self.disk.device))
661 self.uuid = self.__parse_field(runner.outs([self.blkidcmd, self.disk.device]), "UUID")
663 def __resize_filesystem(self, size = None):
664 current_size = os.stat(self.disk.lofile)[stat.ST_SIZE]
667 size = self.disk.size
669 if size == current_size:
672 if size > current_size:
673 self.disk.expand(size)
680 if not self.disk.fixed() and self.disk.exists():
686 self.__resize_filesystem()
688 self.__format_filesystem()
690 def mount(self, options = None):
692 DiskMount.mount(self, options)
695 msger.debug("Checking filesystem %s" % self.disk.lofile)
696 runner.quiet([self.btrfsckcmd, self.disk.lofile])
698 def __get_size_from_filesystem(self):
699 return self.disk.size
701 def __resize_to_minimal(self):
704 return self.__get_size_from_filesystem()
706 def resparse(self, size = None):
708 minsize = self.__resize_to_minimal()
709 self.disk.truncate(minsize)
710 self.__resize_filesystem(size)
713 class DeviceMapperSnapshot(object):
714 def __init__(self, imgloop, cowloop):
715 self.imgloop = imgloop
716 self.cowloop = cowloop
718 self.__created = False
720 self.dmsetupcmd = find_binary_path("dmsetup")
722 """Load dm_snapshot if it isn't loaded"""
723 load_module("dm_snapshot")
726 if self.__name is None:
728 return os.path.join("/dev/mapper", self.__name)
729 path = property(get_path)
735 self.imgloop.create()
736 self.cowloop.create()
738 self.__name = "imgcreate-%d-%d" % (os.getpid(),
739 random.randint(0, 2**16))
741 size = os.stat(self.imgloop.lofile)[stat.ST_SIZE]
743 table = "0 %d snapshot %s %s p 8" % (size / 512,
747 args = [self.dmsetupcmd, "create", self.__name, "--table", table]
748 if runner.show(args) != 0:
749 self.cowloop.cleanup()
750 self.imgloop.cleanup()
751 raise SnapshotError("Could not create snapshot device using: " + ' '.join(args))
753 self.__created = True
755 def remove(self, ignore_errors = False):
756 if not self.__created:
760 rc = runner.show([self.dmsetupcmd, "remove", self.__name])
761 if not ignore_errors and rc != 0:
762 raise SnapshotError("Could not remove snapshot device")
765 self.__created = False
767 self.cowloop.cleanup()
768 self.imgloop.cleanup()
770 def get_cow_used(self):
771 if not self.__created:
775 # dmsetup status on a snapshot returns e.g.
776 # "0 8388608 snapshot 416/1048576"
777 # or, more generally:
779 # where C is the number of 512 byte sectors in use
781 out = runner.outs([self.dmsetupcmd, "status", self.__name])
783 return int((out.split()[3]).split('/')[0]) * 512
785 raise SnapshotError("Failed to parse dmsetup status: " + out)
787 def create_image_minimizer(path, image, minimal_size):
789 Builds a copy-on-write image which can be used to
790 create a device-mapper snapshot of an image where
791 the image's filesystem is as small as possible
794 1) Create a sparse COW
795 2) Loopback mount the image and the COW
796 3) Create a device-mapper snapshot of the image
798 4) Resize the filesystem to the minimal size
799 5) Determine the amount of space used in the COW
800 6) Restroy the device-mapper snapshot
801 7) Truncate the COW, removing unused space
802 8) Create a squashfs of the COW
804 imgloop = LoopbackDisk(image, None) # Passing bogus size - doesn't matter
806 cowloop = SparseLoopbackDisk(os.path.join(os.path.dirname(path), "osmin"),
809 snapshot = DeviceMapperSnapshot(imgloop, cowloop)
814 resize2fs(snapshot.path, minimal_size)
816 cow_used = snapshot.get_cow_used()
818 snapshot.remove(ignore_errors = (not sys.exc_info()[0] is None))
820 cowloop.truncate(cow_used)
822 mksquashfs(cowloop.lofile, path)
824 os.unlink(cowloop.lofile)
826 def load_module(module):
828 for line in open('/proc/modules').xreadlines():
829 if line.startswith("%s " % module):
833 msger.info("Loading %s..." % module)
834 runner.quiet(['modprobe', module])
836 class LoopDevice(object):
837 def __init__(self, loopid=None):
841 self.kpartxcmd = find_binary_path("kpartx")
842 self.losetupcmd = find_binary_path("losetup")
844 def register(self, device):
849 def reg_atexit(self):
851 atexit.register(self.close)
853 def _genloopid(self):
855 if not glob.glob("/dev/loop[0-9]*"):
858 fint = lambda x: x[9:].isdigit() and int(x[9:]) or 0
859 maxid = 1 + max(filter(lambda x: x<100,
860 map(fint, glob.glob("/dev/loop[0-9]*"))))
861 if maxid < 10: maxid = 10
862 if maxid >= 100: raise
865 def _kpseek(self, device):
866 rc, out = runner.runtool([self.kpartxcmd, '-l', '-v', device])
868 raise MountError("Can't query dm snapshot on %s" % device)
869 for line in out.splitlines():
870 if line and line.startswith("loop"):
874 def _loseek(self, device):
876 rc, out = runner.runtool([self.losetupcmd, '-a'])
878 raise MountError("Failed to run 'losetup -a'")
879 for line in out.splitlines():
880 m = re.match("([^:]+): .*", line)
881 if m and m.group(1) == device:
888 self.loopid = self._genloopid()
889 self.device = "/dev/loop%d" % self.loopid
890 if os.path.exists(self.device):
891 if self._loseek(self.device):
892 raise MountError("Device busy: %s" % self.device)
897 mknod = find_binary_path('mknod')
898 rc = runner.show([mknod, '-m664', self.device, 'b', '7', str(self.loopid)])
900 raise MountError("Failed to create device %s" % self.device)
909 except MountError, e:
910 raise CreatorError("%s" % e)
914 if self.device is None:
918 if self._kpseek(self.device):
919 runner.quiet([self.kpartxcmd, "-d", self.device])
920 if self._loseek(self.device):
921 runner.quiet([self.losetupcmd, "-d", self.device])
922 # FIXME: should sleep a while between two loseek
923 if self._loseek(self.device):
924 msger.warning("Can't cleanup loop device %s" % self.device)
926 os.unlink(self.device)
928 DEVICE_PIDFILE_DIR = "/var/tmp/mic/device"
929 DEVICE_LOCKFILE = "/var/lock/__mic_loopdev.lock"
931 def get_loop_device(losetupcmd, lofile):
932 global DEVICE_PIDFILE_DIR
933 global DEVICE_LOCKFILE
936 makedirs(os.path.dirname(DEVICE_LOCKFILE))
937 fp = open(DEVICE_LOCKFILE, 'w')
938 fcntl.flock(fp, fcntl.LOCK_EX)
941 devinst = LoopDevice()
943 # clean up left loop device first
946 # provide an avaible loop device
947 rc, out = runner.runtool([losetupcmd, "--find"])
949 loopdev = out.split()[0]
950 devinst.register(loopdev)
951 if not loopdev or not os.path.exists(loopdev):
953 loopdev = devinst.device
955 # setup a loop device for image file
956 rc = runner.show([losetupcmd, loopdev, lofile])
958 raise MountError("Failed to setup loop device for '%s'" % lofile)
962 # try to save device and pid
963 makedirs(DEVICE_PIDFILE_DIR)
964 pidfile = os.path.join(DEVICE_PIDFILE_DIR, os.path.basename(loopdev))
965 if os.path.exists(pidfile):
967 with open(pidfile, 'w') as wf:
968 wf.write(str(os.getpid()))
970 except MountError, err:
971 raise CreatorError("%s" % str(err))
976 fcntl.flock(fp, fcntl.LOCK_UN)
978 os.unlink(DEVICE_LOCKFILE)
984 def clean_loop_devices(piddir=DEVICE_PIDFILE_DIR):
985 if not os.path.exists(piddir) or not os.path.isdir(piddir):
988 for loopdev in os.listdir(piddir):
989 pidfile = os.path.join(piddir, loopdev)
991 with open(pidfile, 'r') as rf:
992 devpid = int(rf.read())
996 # if the process using this device is alive, skip it
997 if not devpid or os.path.exists(os.path.join('/proc', str(devpid))):
1000 # try to clean it up
1002 devinst = LoopDevice()
1003 devinst.register(os.path.join('/dev', loopdev))