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,)])
92 fuser = find_binary_path("fuser")
93 if not os.path.exists(fp):
96 rc = runner.quiet([fuser, "-s", fp])
98 for pid in runner.outs([fuser, fp]).split():
99 fd = open("/proc/%s/cmdline" % pid, "r")
102 if cmdline[:-1] == "/bin/bash":
108 class BindChrootMount:
109 """Represents a bind mount of a directory into a chroot."""
110 def __init__(self, src, chroot, dest = None, option = None):
111 self.root = os.path.abspath(os.path.expanduser(chroot))
114 self.orig_src = self.src = src
115 if os.path.islink(src):
116 self.src = os.readlink(src)
117 if not self.src.startswith('/'):
118 self.src = os.path.abspath(os.path.join(os.path.dirname(src),
123 self.dest = os.path.join(self.root, dest.lstrip('/'))
126 self.mountcmd = find_binary_path("mount")
127 self.umountcmd = find_binary_path("umount")
130 with open('/proc/mounts') as f:
132 if line.split()[1] == os.path.abspath(self.dest):
137 def has_chroot_instance(self):
138 lock = os.path.join(self.root, ".chroot.lock")
139 return my_fuser(lock)
142 if self.mounted or self.ismounted():
146 rc = runner.show([self.mountcmd, "--bind", self.src, self.dest])
148 raise MountError("Bind-mounting '%s' to '%s' failed" %
149 (self.src, self.dest))
151 rc = runner.show([self.mountcmd, "--bind", "-o", "remount,%s" % self.option, self.dest])
153 raise MountError("Bind-remounting '%s' failed" % self.dest)
156 if os.path.islink(self.orig_src):
157 dest = os.path.join(self.root, self.orig_src.lstrip('/'))
158 if not os.path.exists(dest):
159 os.symlink(self.src, dest)
162 if self.has_chroot_instance():
166 runner.show([self.umountcmd, "-l", self.dest])
170 """LoopbackMount compatibility layer for old API"""
171 def __init__(self, lofile, mountdir, fstype = None):
172 self.diskmount = DiskMount(LoopbackDisk(lofile,size = 0),mountdir,fstype,rmmountdir = True)
174 self.losetupcmd = find_binary_path("losetup")
177 self.diskmount.cleanup()
180 self.diskmount.unmount()
184 runner.show([self.losetupcmd, "-d", self.loopdev])
192 self.loopdev = get_loop_device(self.losetupcmd, self.lofile)
196 self.diskmount.mount()
198 class SparseLoopbackMount(LoopbackMount):
199 """SparseLoopbackMount compatibility layer for old API"""
200 def __init__(self, lofile, mountdir, size, fstype = None):
201 self.diskmount = DiskMount(SparseLoopbackDisk(lofile,size),mountdir,fstype,rmmountdir = True)
203 def expand(self, create = False, size = None):
204 self.diskmount.disk.expand(create, size)
206 def truncate(self, size = None):
207 self.diskmount.disk.truncate(size)
210 self.diskmount.disk.create()
212 class SparseExtLoopbackMount(SparseLoopbackMount):
213 """SparseExtLoopbackMount compatibility layer for old API"""
214 def __init__(self, lofile, mountdir, size, fstype, blocksize, fslabel):
215 self.diskmount = ExtDiskMount(SparseLoopbackDisk(lofile,size), mountdir, fstype, blocksize, fslabel, rmmountdir = True)
218 def __format_filesystem(self):
219 self.diskmount.__format_filesystem()
222 self.diskmount.disk.create()
224 def resize(self, size = None):
225 return self.diskmount.__resize_filesystem(size)
228 self.diskmount.mount()
231 self.extdiskmount.__fsck()
233 def __get_size_from_filesystem(self):
234 return self.diskmount.__get_size_from_filesystem()
236 def __resize_to_minimal(self):
237 return self.diskmount.__resize_to_minimal()
239 def resparse(self, size = None):
240 return self.diskmount.resparse(size)
243 """Generic base object for a disk
245 The 'create' method must make the disk visible as a block device - eg
246 by calling losetup. For RawDisk, this is obviously a no-op. The 'cleanup'
247 method must undo the 'create' operation.
249 def __init__(self, size, device = None):
250 self._device = device
259 def get_device(self):
261 def set_device(self, path):
263 device = property(get_device, set_device)
267 size = property(get_size)
271 """A Disk backed by a block device.
272 Note that create() is a no-op.
274 def __init__(self, size, device):
275 Disk.__init__(self, size, device)
283 class LoopbackDisk(Disk):
284 """A Disk backed by a file via the loop module."""
285 def __init__(self, lofile, size):
286 Disk.__init__(self, size)
288 self.losetupcmd = find_binary_path("losetup")
294 return os.path.exists(self.lofile)
297 if self.device is not None:
300 self.device = get_loop_device(self.losetupcmd, self.lofile)
303 if self.device is None:
305 msger.debug("Losetup remove %s" % self.device)
306 rc = runner.show([self.losetupcmd, "-d", self.device])
309 class SparseLoopbackDisk(LoopbackDisk):
310 """A Disk backed by a sparse file via the loop module."""
311 def __init__(self, lofile, size):
312 LoopbackDisk.__init__(self, lofile, size)
314 def expand(self, create = False, size = None):
318 if not os.path.exists(self.lofile):
319 makedirs(os.path.dirname(self.lofile))
324 msger.debug("Extending sparse file %s to %d" % (self.lofile, size))
326 fd = os.open(self.lofile, flags, 0644)
328 fd = os.open(self.lofile, flags)
333 os.ftruncate(fd, size)
335 # may be limited by 2G in 32bit env
336 os.ftruncate(fd, 2**31L)
340 def truncate(self, size = None):
344 msger.debug("Truncating sparse file %s to %d" % (self.lofile, size))
345 fd = os.open(self.lofile, os.O_WRONLY)
346 os.ftruncate(fd, size)
350 self.expand(create = True)
351 LoopbackDisk.create(self)
354 """A generic base class to deal with mounting things."""
355 def __init__(self, mountdir):
356 self.mountdir = mountdir
361 def mount(self, options = None):
367 class DiskMount(Mount):
368 """A Mount object that handles mounting of a Disk."""
369 def __init__(self, disk, mountdir, fstype = None, rmmountdir = True):
370 Mount.__init__(self, mountdir)
374 self.rmmountdir = rmmountdir
379 self.mkfscmd = find_binary_path("mkfs." + self.fstype)
382 self.mountcmd = find_binary_path("mount")
383 self.umountcmd = find_binary_path("umount")
391 msger.debug("Unmounting directory %s" % self.mountdir)
392 runner.quiet('sync') # sync the data on this mount point
393 rc = runner.show([self.umountcmd, "-l", self.mountdir])
397 raise MountError("Failed to umount %s" % self.mountdir)
398 if self.rmdir and not self.mounted:
400 os.rmdir(self.mountdir)
410 def mount(self, options = None):
414 if not os.path.isdir(self.mountdir):
415 msger.debug("Creating mount point %s" % self.mountdir)
416 os.makedirs(self.mountdir)
417 self.rmdir = self.rmmountdir
421 msger.debug("Mounting %s at %s" % (self.disk.device, self.mountdir))
423 args = [ self.mountcmd, "-o", options, self.disk.device, self.mountdir ]
425 args = [ self.mountcmd, self.disk.device, self.mountdir ]
427 args.extend(["-t", self.fstype])
429 rc = runner.show(args)
431 raise MountError("Failed to mount '%s' to '%s' with command '%s'. Retval: %s" %
432 (self.disk.device, self.mountdir, " ".join(args), rc))
436 class ExtDiskMount(DiskMount):
437 """A DiskMount object that is able to format/resize ext[23] filesystems."""
438 def __init__(self, disk, mountdir, fstype, blocksize, fslabel, rmmountdir=True, skipformat = False, fsopts = None):
439 DiskMount.__init__(self, disk, mountdir, fstype, rmmountdir)
440 self.blocksize = blocksize
441 self.fslabel = fslabel.replace("/", "")
442 self.uuid = str(uuid.uuid4())
443 self.skipformat = skipformat
446 self.dumpe2fs = find_binary_path("dumpe2fs")
447 self.tune2fs = find_binary_path("tune2fs")
449 def __parse_field(self, output, field):
450 for line in output.split("\n"):
451 if line.startswith(field + ":"):
452 return line[len(field) + 1:].strip()
454 raise KeyError("Failed to find field '%s' in output" % field)
456 def __format_filesystem(self):
458 msger.debug("Skip filesystem format.")
461 msger.verbose("Formating %s filesystem on %s" % (self.fstype, self.disk.device))
462 cmdlist = [self.mkfscmd, "-F", "-L", self.fslabel, "-m", "1", "-b",
463 str(self.blocksize), "-U", self.uuid]
465 cmdlist.extend(self.extopts.split())
466 cmdlist.extend([self.disk.device])
468 rc, errout = runner.runtool(cmdlist, catch=2)
470 raise MountError("Error creating %s filesystem on disk %s:\n%s" %
471 (self.fstype, self.disk.device, errout))
474 msger.debug("Tuning filesystem on %s" % self.disk.device)
475 runner.show([self.tune2fs, "-c0", "-i0", "-Odir_index", "-ouser_xattr,acl", self.disk.device])
477 def __resize_filesystem(self, size = None):
478 current_size = os.stat(self.disk.lofile)[stat.ST_SIZE]
481 size = self.disk.size
483 if size == current_size:
486 if size > current_size:
487 self.disk.expand(size)
491 resize2fs(self.disk.lofile, size)
496 if not self.disk.fixed() and self.disk.exists():
502 self.__resize_filesystem()
504 self.__format_filesystem()
506 def mount(self, options = None):
508 DiskMount.mount(self, options)
511 msger.info("Checking filesystem %s" % self.disk.lofile)
512 runner.quiet(["/sbin/e2fsck", "-f", "-y", self.disk.lofile])
514 def __get_size_from_filesystem(self):
515 return int(self.__parse_field(runner.outs([self.dumpe2fs, '-h', self.disk.lofile]),
516 "Block count")) * self.blocksize
518 def __resize_to_minimal(self):
522 # Use a binary search to find the minimal size
523 # we can resize the image to
526 top = self.__get_size_from_filesystem()
527 while top != (bot + 1):
528 t = bot + ((top - bot) / 2)
530 if not resize2fs(self.disk.lofile, t):
536 def resparse(self, size = None):
541 minsize = self.__resize_to_minimal()
542 self.disk.truncate(minsize)
544 self.__resize_filesystem(size)
547 class VfatDiskMount(DiskMount):
548 """A DiskMount object that is able to format vfat/msdos filesystems."""
549 def __init__(self, disk, mountdir, fstype, blocksize, fslabel, rmmountdir=True, skipformat = False, fsopts = None):
550 DiskMount.__init__(self, disk, mountdir, fstype, rmmountdir)
551 self.blocksize = blocksize
552 self.fslabel = fslabel.replace("/", "")
554 self.skipformat = skipformat
556 self.fsckcmd = find_binary_path("fsck." + self.fstype)
558 def __format_filesystem(self):
560 msger.debug("Skip filesystem format.")
563 msger.verbose("Formating %s filesystem on %s" % (self.fstype, self.disk.device))
564 rc = runner.show([self.mkfscmd, "-n", self.fslabel, self.disk.device])
566 raise MountError("Error creating %s filesystem on disk %s" % (self.fstype,self.disk.device))
568 msger.verbose("Tuning filesystem on %s" % self.disk.device)
570 def __resize_filesystem(self, size = None):
571 current_size = os.stat(self.disk.lofile)[stat.ST_SIZE]
574 size = self.disk.size
576 if size == current_size:
579 if size > current_size:
580 self.disk.expand(size)
584 #resize2fs(self.disk.lofile, size)
589 if not self.disk.fixed() and self.disk.exists():
595 self.__resize_filesystem()
597 self.__format_filesystem()
599 def mount(self, options = None):
601 DiskMount.mount(self, options)
604 msger.debug("Checking filesystem %s" % self.disk.lofile)
605 runner.show([self.fsckcmd, "-y", self.disk.lofile])
607 def __get_size_from_filesystem(self):
608 return self.disk.size
610 def __resize_to_minimal(self):
614 # Use a binary search to find the minimal size
615 # we can resize the image to
618 top = self.__get_size_from_filesystem()
621 def resparse(self, size = None):
623 minsize = self.__resize_to_minimal()
624 self.disk.truncate(minsize)
625 self.__resize_filesystem(size)
628 class BtrfsDiskMount(DiskMount):
629 """A DiskMount object that is able to format/resize btrfs filesystems."""
630 def __init__(self, disk, mountdir, fstype, blocksize, fslabel, rmmountdir=True, skipformat = False, fsopts = None):
632 DiskMount.__init__(self, disk, mountdir, fstype, rmmountdir)
633 self.blocksize = blocksize
634 self.fslabel = fslabel.replace("/", "")
636 self.skipformat = skipformat
638 self.blkidcmd = find_binary_path("blkid")
639 self.btrfsckcmd = find_binary_path("btrfsck")
641 def __check_btrfs(self):
643 """ Need to load btrfs module to mount it """
645 for line in open("/proc/filesystems").xreadlines():
646 if line.find("btrfs") > -1:
650 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.")
652 # disable selinux, selinux will block write
653 if os.path.exists("/usr/sbin/setenforce"):
654 runner.show(["/usr/sbin/setenforce", "0"])
656 def __parse_field(self, output, field):
657 for line in output.split(" "):
658 if line.startswith(field + "="):
659 return line[len(field) + 1:].strip().replace("\"", "")
661 raise KeyError("Failed to find field '%s' in output" % field)
663 def __format_filesystem(self):
665 msger.debug("Skip filesystem format.")
668 msger.verbose("Formating %s filesystem on %s" % (self.fstype, self.disk.device))
669 rc = runner.show([self.mkfscmd, "-L", self.fslabel, self.disk.device])
671 raise MountError("Error creating %s filesystem on disk %s" % (self.fstype,self.disk.device))
673 self.uuid = self.__parse_field(runner.outs([self.blkidcmd, self.disk.device]), "UUID")
675 def __resize_filesystem(self, size = None):
676 current_size = os.stat(self.disk.lofile)[stat.ST_SIZE]
679 size = self.disk.size
681 if size == current_size:
684 if size > current_size:
685 self.disk.expand(size)
692 if not self.disk.fixed() and self.disk.exists():
698 self.__resize_filesystem()
700 self.__format_filesystem()
702 def mount(self, options = None):
704 DiskMount.mount(self, options)
707 msger.debug("Checking filesystem %s" % self.disk.lofile)
708 runner.quiet([self.btrfsckcmd, self.disk.lofile])
710 def __get_size_from_filesystem(self):
711 return self.disk.size
713 def __resize_to_minimal(self):
716 return self.__get_size_from_filesystem()
718 def resparse(self, size = None):
720 minsize = self.__resize_to_minimal()
721 self.disk.truncate(minsize)
722 self.__resize_filesystem(size)
725 class DeviceMapperSnapshot(object):
726 def __init__(self, imgloop, cowloop):
727 self.imgloop = imgloop
728 self.cowloop = cowloop
730 self.__created = False
732 self.dmsetupcmd = find_binary_path("dmsetup")
734 """Load dm_snapshot if it isn't loaded"""
735 load_module("dm_snapshot")
738 if self.__name is None:
740 return os.path.join("/dev/mapper", self.__name)
741 path = property(get_path)
747 self.imgloop.create()
748 self.cowloop.create()
750 self.__name = "imgcreate-%d-%d" % (os.getpid(),
751 random.randint(0, 2**16))
753 size = os.stat(self.imgloop.lofile)[stat.ST_SIZE]
755 table = "0 %d snapshot %s %s p 8" % (size / 512,
759 args = [self.dmsetupcmd, "create", self.__name, "--table", table]
760 if runner.show(args) != 0:
761 self.cowloop.cleanup()
762 self.imgloop.cleanup()
763 raise SnapshotError("Could not create snapshot device using: " + ' '.join(args))
765 self.__created = True
767 def remove(self, ignore_errors = False):
768 if not self.__created:
772 rc = runner.show([self.dmsetupcmd, "remove", self.__name])
773 if not ignore_errors and rc != 0:
774 raise SnapshotError("Could not remove snapshot device")
777 self.__created = False
779 self.cowloop.cleanup()
780 self.imgloop.cleanup()
782 def get_cow_used(self):
783 if not self.__created:
787 # dmsetup status on a snapshot returns e.g.
788 # "0 8388608 snapshot 416/1048576"
789 # or, more generally:
791 # where C is the number of 512 byte sectors in use
793 out = runner.outs([self.dmsetupcmd, "status", self.__name])
795 return int((out.split()[3]).split('/')[0]) * 512
797 raise SnapshotError("Failed to parse dmsetup status: " + out)
799 def create_image_minimizer(path, image, minimal_size):
801 Builds a copy-on-write image which can be used to
802 create a device-mapper snapshot of an image where
803 the image's filesystem is as small as possible
806 1) Create a sparse COW
807 2) Loopback mount the image and the COW
808 3) Create a device-mapper snapshot of the image
810 4) Resize the filesystem to the minimal size
811 5) Determine the amount of space used in the COW
812 6) Restroy the device-mapper snapshot
813 7) Truncate the COW, removing unused space
814 8) Create a squashfs of the COW
816 imgloop = LoopbackDisk(image, None) # Passing bogus size - doesn't matter
818 cowloop = SparseLoopbackDisk(os.path.join(os.path.dirname(path), "osmin"),
821 snapshot = DeviceMapperSnapshot(imgloop, cowloop)
826 resize2fs(snapshot.path, minimal_size)
828 cow_used = snapshot.get_cow_used()
830 snapshot.remove(ignore_errors = (not sys.exc_info()[0] is None))
832 cowloop.truncate(cow_used)
834 mksquashfs(cowloop.lofile, path)
836 os.unlink(cowloop.lofile)
838 def load_module(module):
840 for line in open('/proc/modules').xreadlines():
841 if line.startswith("%s " % module):
845 msger.info("Loading %s..." % module)
846 runner.quiet(['modprobe', module])
848 class LoopDevice(object):
849 def __init__(self, loopid=None):
853 self.kpartxcmd = find_binary_path("kpartx")
854 self.losetupcmd = find_binary_path("losetup")
856 def register(self, device):
861 def reg_atexit(self):
863 atexit.register(self.close)
865 def _genloopid(self):
867 if not glob.glob("/dev/loop[0-9]*"):
870 fint = lambda x: x[9:].isdigit() and int(x[9:]) or 0
871 maxid = 1 + max(filter(lambda x: x<100,
872 map(fint, glob.glob("/dev/loop[0-9]*"))))
873 if maxid < 10: maxid = 10
874 if maxid >= 100: raise
877 def _kpseek(self, device):
878 rc, out = runner.runtool([self.kpartxcmd, '-l', '-v', device])
880 raise MountError("Can't query dm snapshot on %s" % device)
881 for line in out.splitlines():
882 if line and line.startswith("loop"):
886 def _loseek(self, device):
888 rc, out = runner.runtool([self.losetupcmd, '-a'])
890 raise MountError("Failed to run 'losetup -a'")
891 for line in out.splitlines():
892 m = re.match("([^:]+): .*", line)
893 if m and m.group(1) == device:
900 self.loopid = self._genloopid()
901 self.device = "/dev/loop%d" % self.loopid
902 if os.path.exists(self.device):
903 if self._loseek(self.device):
904 raise MountError("Device busy: %s" % self.device)
909 mknod = find_binary_path('mknod')
910 rc = runner.show([mknod, '-m664', self.device, 'b', '7', str(self.loopid)])
912 raise MountError("Failed to create device %s" % self.device)
921 except MountError, e:
922 msger.error("%s" % e)
926 if self.device is None:
930 if self._kpseek(self.device):
932 for i in range(3, os.sysconf("SC_OPEN_MAX")):
937 runner.quiet([self.kpartxcmd, "-d", self.device])
938 if self._loseek(self.device):
939 runner.quiet([self.losetupcmd, "-d", self.device])
940 # FIXME: should sleep a while between two loseek
941 if self._loseek(self.device):
942 msger.warning("Can't cleanup loop device %s" % self.device)
944 os.unlink(self.device)
946 DEVICE_PIDFILE_DIR = "/var/tmp/mic/device"
947 DEVICE_LOCKFILE = "/var/lock/__mic_loopdev.lock"
949 def get_loop_device(losetupcmd, lofile):
950 global DEVICE_PIDFILE_DIR
951 global DEVICE_LOCKFILE
954 makedirs(os.path.dirname(DEVICE_LOCKFILE))
955 fp = open(DEVICE_LOCKFILE, 'w')
956 fcntl.flock(fp, fcntl.LOCK_EX)
959 devinst = LoopDevice()
961 # clean up left loop device first
964 # provide an avaible loop device
965 rc, out = runner.runtool([losetupcmd, "--find"])
967 loopdev = out.split()[0]
968 devinst.register(loopdev)
969 if not loopdev or not os.path.exists(loopdev):
971 loopdev = devinst.device
973 # setup a loop device for image file
974 rc = runner.show([losetupcmd, loopdev, lofile])
976 raise MountError("Failed to setup loop device for '%s'" % lofile)
980 # try to save device and pid
981 makedirs(DEVICE_PIDFILE_DIR)
982 pidfile = os.path.join(DEVICE_PIDFILE_DIR, os.path.basename(loopdev))
983 if os.path.exists(pidfile):
985 with open(pidfile, 'w') as wf:
986 wf.write(str(os.getpid()))
988 except MountError, err:
989 raise CreatorError("%s" % str(err))
994 fcntl.flock(fp, fcntl.LOCK_UN)
996 os.unlink(DEVICE_LOCKFILE)
1002 def clean_loop_devices(piddir=DEVICE_PIDFILE_DIR):
1003 if not os.path.exists(piddir) or not os.path.isdir(piddir):
1006 for loopdev in os.listdir(piddir):
1007 pidfile = os.path.join(piddir, loopdev)
1009 with open(pidfile, 'r') as rf:
1010 devpid = int(rf.read())
1014 # if the process using this device is alive, skip it
1015 if not devpid or os.path.exists(os.path.join('/proc', str(devpid))):
1018 # try to clean it up
1020 devinst = LoopDevice()
1021 devinst.register(os.path.join('/dev', loopdev))