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 mkvdfs(in_img, out_img, fsoptions):
73 """ This function is incomplete. """
74 fullpathmkvdfs = find_binary_path("mkfs.vdfs")
75 # args = fullpathmkvdfs + " -i -r "+ in_img + " -z 1024M -s " + out_img
76 args = fullpathmkvdfs + " " + fsoptions + " -r " + in_img + " " + out_img
77 msger.verbose("vdfs args: %s" % args)
78 runner.show("%s --help" % fullpathmkvdfs)
79 # if not sys.stdout.isatty():
80 # args.append("-no-progress")
81 # runner.show("%s --help" % fullpathmkvdfs)
82 ret = runner.show(args)
84 runner.show ("vdfs error")
85 raise VdfsError("' %s' exited with error (%d)" % (args, ret))
87 def mksquashfs(in_img, out_img):
88 fullpathmksquashfs = find_binary_path("mksquashfs")
89 args = [fullpathmksquashfs, in_img, out_img]
91 if not sys.stdout.isatty():
92 args.append("-no-progress")
94 ret = runner.show(args)
96 raise SquashfsError("'%s' exited with error (%d)" % (' '.join(args), ret))
98 def resize2fs(fs, size):
99 resize2fs = find_binary_path("resize2fs")
101 # it means to minimalize it
102 return runner.show([resize2fs, '-M', fs])
104 return runner.show([resize2fs, fs, "%sK" % (size / 1024,)])
106 class BindChrootMount:
107 """Represents a bind mount of a directory into a chroot."""
108 def __init__(self, src, chroot, dest = None, option = None):
109 self.root = os.path.abspath(os.path.expanduser(chroot))
110 self.mount_option = option
112 self.orig_src = self.src = src
113 if os.path.islink(src):
114 self.src = os.readlink(src)
115 if not self.src.startswith('/'):
116 self.src = os.path.abspath(os.path.join(os.path.dirname(src),
121 self.dest = os.path.join(self.root, dest.lstrip('/'))
124 self.mountcmd = find_binary_path("mount")
125 self.umountcmd = find_binary_path("umount")
128 with open('/proc/mounts') as f:
130 if line.split()[1] == os.path.abspath(self.dest):
136 if self.mounted or self.ismounted():
142 if err.errno == errno.ENOSPC:
143 msger.warning("No space left on device '%s'" % err.filename)
146 if self.mount_option:
147 cmdline = [self.mountcmd, "-o" ,"bind", "-o", "%s" % \
148 self.mount_option, self.src, self.dest]
150 cmdline = [self.mountcmd, "-o" ,"bind", self.src, self.dest]
151 rc, errout = runner.runtool(cmdline, catch=2)
153 raise MountError("Bind-mounting '%s' to '%s' failed: %s" %
154 (self.src, self.dest, errout))
157 if os.path.islink(self.orig_src):
158 dest = os.path.join(self.root, self.orig_src.lstrip('/'))
159 if not os.path.exists(dest):
160 os.symlink(self.src, dest)
163 if self.mounted or self.ismounted():
164 runner.show([self.umountcmd, "-l", self.dest])
168 """LoopbackMount compatibility layer for old API"""
169 def __init__(self, lofile, mountdir, fstype = None):
170 self.diskmount = DiskMount(LoopbackDisk(lofile,size = 0),mountdir,fstype,rmmountdir = True)
172 self.losetupcmd = find_binary_path("losetup")
175 self.diskmount.cleanup()
178 self.diskmount.unmount()
182 runner.show([self.losetupcmd, "-d", self.loopdev])
190 self.loopdev = get_loop_device(self.losetupcmd, self.lofile)
194 self.diskmount.mount()
196 class SparseLoopbackMount(LoopbackMount):
197 """SparseLoopbackMount compatibility layer for old API"""
198 def __init__(self, lofile, mountdir, size, fstype = None):
199 self.diskmount = DiskMount(SparseLoopbackDisk(lofile,size),mountdir,fstype,rmmountdir = True)
201 def expand(self, create = False, size = None):
202 self.diskmount.disk.expand(create, size)
204 def truncate(self, size = None):
205 self.diskmount.disk.truncate(size)
208 self.diskmount.disk.create()
210 class SparseExtLoopbackMount(SparseLoopbackMount):
211 """SparseExtLoopbackMount compatibility layer for old API"""
212 def __init__(self, lofile, mountdir, size, fstype, blocksize, fslabel):
213 self.diskmount = ExtDiskMount(SparseLoopbackDisk(lofile,size), mountdir, fstype, blocksize, fslabel, rmmountdir = True)
216 def __format_filesystem(self):
217 self.diskmount.__format_filesystem()
220 self.diskmount.disk.create()
222 def resize(self, size = None):
223 return self.diskmount.__resize_filesystem(size)
226 self.diskmount.mount()
229 self.extdiskmount.__fsck()
231 def __get_size_from_filesystem(self):
232 return self.diskmount.__get_size_from_filesystem()
234 def __resize_to_minimal(self):
235 return self.diskmount.__resize_to_minimal()
237 def resparse(self, size = None):
238 return self.diskmount.resparse(size)
241 """Generic base object for a disk
243 The 'create' method must make the disk visible as a block device - eg
244 by calling losetup. For RawDisk, this is obviously a no-op. The 'cleanup'
245 method must undo the 'create' operation.
247 def __init__(self, size, device = None):
248 self._device = device
257 def get_device(self):
259 def set_device(self, path):
261 device = property(get_device, set_device)
265 size = property(get_size)
269 """A Disk backed by a block device.
270 Note that create() is a no-op.
272 def __init__(self, size, device):
273 Disk.__init__(self, size, device)
281 class LoopbackDisk(Disk):
282 """A Disk backed by a file via the loop module."""
283 def __init__(self, lofile, size):
284 Disk.__init__(self, size)
286 self.losetupcmd = find_binary_path("losetup")
292 return os.path.exists(self.lofile)
295 if self.device is not None:
298 self.device = get_loop_device(self.losetupcmd, self.lofile)
301 if self.device is None:
303 msger.debug("Losetup remove %s" % self.device)
304 rc = runner.show([self.losetupcmd, "-d", self.device])
307 class SparseLoopbackDisk(LoopbackDisk):
308 """A Disk backed by a sparse file via the loop module."""
309 def __init__(self, lofile, size):
310 LoopbackDisk.__init__(self, lofile, size)
312 def expand(self, create = False, size = None):
316 if not os.path.exists(self.lofile):
317 makedirs(os.path.dirname(self.lofile))
322 msger.debug("Extending sparse file %s to %d" % (self.lofile, size))
324 fd = os.open(self.lofile, flags, 0644)
326 fd = os.open(self.lofile, flags)
331 os.ftruncate(fd, size)
333 # may be limited by 2G in 32bit env
334 os.ftruncate(fd, 2**31L)
338 def truncate(self, size = None):
342 msger.debug("Truncating sparse file %s to %d" % (self.lofile, size))
343 fd = os.open(self.lofile, os.O_WRONLY)
344 os.ftruncate(fd, size)
348 self.expand(create = True)
349 LoopbackDisk.create(self)
352 """A generic base class to deal with mounting things."""
353 def __init__(self, mountdir):
354 self.mountdir = mountdir
359 def mount(self, options = None):
365 class DiskMount(Mount):
366 """A Mount object that handles mounting of a Disk."""
367 def __init__(self, disk, mountdir, fstype = None, rmmountdir = True):
368 Mount.__init__(self, mountdir)
372 self.rmmountdir = rmmountdir
377 self.mkfscmd = find_binary_path("mkfs." + self.fstype)
380 self.mountcmd = find_binary_path("mount")
381 self.umountcmd = find_binary_path("umount")
389 msger.debug("Unmounting directory %s" % self.mountdir)
390 runner.quiet('sync') # sync the data on this mount point
391 rc = runner.show([self.umountcmd, "-l", self.mountdir])
395 raise MountError("Failed to umount %s" % self.mountdir)
396 if self.rmdir and not self.mounted:
398 os.rmdir(self.mountdir)
408 def mount(self, options = None):
412 if not os.path.isdir(self.mountdir):
413 msger.debug("Creating mount point %s" % self.mountdir)
414 os.makedirs(self.mountdir)
415 self.rmdir = self.rmmountdir
419 msger.debug("Mounting %s at %s" % (self.disk.device, self.mountdir))
421 args = [ self.mountcmd, "-o", options, self.disk.device, self.mountdir ]
423 args = [ self.mountcmd, self.disk.device, self.mountdir ]
425 args.extend(["-t", self.fstype])
427 rc = runner.show(args)
429 raise MountError("Failed to mount '%s' to '%s' with command '%s'. Retval: %s" %
430 (self.disk.device, self.mountdir, " ".join(args), rc))
434 class ExtDiskMount(DiskMount):
435 """A DiskMount object that is able to format/resize ext[23] filesystems."""
436 def __init__(self, disk, mountdir, fstype, blocksize, fslabel, rmmountdir=True, skipformat = False, fsopts = None, fsuuid=None):
437 DiskMount.__init__(self, disk, mountdir, fstype, rmmountdir)
438 self.blocksize = blocksize
439 self.fslabel = fslabel.replace("/", "")
440 self.uuid = fsuuid or str(uuid.uuid4())
441 self.skipformat = skipformat
444 self.dumpe2fs = find_binary_path("dumpe2fs")
445 self.tune2fs = find_binary_path("tune2fs")
447 def __parse_field(self, output, field):
448 for line in output.split("\n"):
449 if line.startswith(field + ":"):
450 return line[len(field) + 1:].strip()
452 raise KeyError("Failed to find field '%s' in output" % field)
454 def __format_filesystem(self):
456 msger.debug("Skip filesystem format.")
459 msger.verbose("Formating %s filesystem on %s" % (self.fstype, self.disk.device))
460 cmdlist = [self.mkfscmd, "-F", "-L", self.fslabel, "-m", "1", "-b",
461 str(self.blocksize), "-U", self.uuid]
463 cmdlist.extend(self.extopts.split())
464 cmdlist.extend([self.disk.device])
466 rc, errout = runner.runtool(cmdlist, catch=2)
468 raise MountError("Error creating %s filesystem on disk %s:\n%s" %
469 (self.fstype, self.disk.device, errout))
472 msger.debug("Tuning filesystem on %s" % self.disk.device)
473 runner.show([self.tune2fs, "-c0", "-i0", "-Odir_index", "-ouser_xattr,acl", self.disk.device])
475 def __resize_filesystem(self, size = None):
476 msger.info("Resizing filesystem ...")
477 current_size = os.stat(self.disk.lofile)[stat.ST_SIZE]
480 size = self.disk.size
482 if size == current_size:
485 if size > current_size:
486 self.disk.expand(size)
490 resize2fs(self.disk.lofile, size)
495 if not self.disk.fixed() and self.disk.exists():
501 self.__resize_filesystem()
503 self.__format_filesystem()
505 def mount(self, options = None):
507 DiskMount.mount(self, options)
510 msger.info("Checking filesystem %s" % self.disk.lofile)
511 runner.quiet(["/sbin/e2fsck", "-f", "-y", self.disk.lofile])
513 def __get_size_from_filesystem(self):
514 return int(self.__parse_field(runner.outs([self.dumpe2fs, '-h', self.disk.lofile]),
515 "Block count")) * self.blocksize
517 def __resize_to_minimal(self):
518 msger.info("Resizing filesystem to minimal ...")
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, fsuuid = None):
550 DiskMount.__init__(self, disk, mountdir, fstype, rmmountdir)
551 self.blocksize = blocksize
552 self.fslabel = fslabel.replace("/", "")
553 rand1 = random.randint(0, 2**16 - 1)
554 rand2 = random.randint(0, 2**16 - 1)
555 self.uuid = fsuuid or "%04X-%04X" % (rand1, rand2)
556 self.skipformat = skipformat
558 self.fsckcmd = find_binary_path("fsck." + self.fstype)
560 def __format_filesystem(self):
562 msger.debug("Skip filesystem format.")
565 msger.verbose("Formating %s filesystem on %s" % (self.fstype, self.disk.device))
566 rc = runner.show([self.mkfscmd, "-n", self.fslabel,
567 "-i", self.uuid.replace("-", ""), self.disk.device])
569 raise MountError("Error creating %s filesystem on disk %s" % (self.fstype,self.disk.device))
571 msger.verbose("Tuning filesystem on %s" % self.disk.device)
573 def __resize_filesystem(self, size = None):
574 current_size = os.stat(self.disk.lofile)[stat.ST_SIZE]
577 size = self.disk.size
579 if size == current_size:
582 if size > current_size:
583 self.disk.expand(size)
587 #resize2fs(self.disk.lofile, size)
592 if not self.disk.fixed() and self.disk.exists():
598 self.__resize_filesystem()
600 self.__format_filesystem()
602 def mount(self, options = None):
604 DiskMount.mount(self, options)
607 msger.debug("Checking filesystem %s" % self.disk.lofile)
608 runner.show([self.fsckcmd, "-y", self.disk.lofile])
610 def __get_size_from_filesystem(self):
611 return self.disk.size
613 def __resize_to_minimal(self):
617 # Use a binary search to find the minimal size
618 # we can resize the image to
621 top = self.__get_size_from_filesystem()
624 def resparse(self, size = None):
626 minsize = self.__resize_to_minimal()
627 self.disk.truncate(minsize)
628 self.__resize_filesystem(size)
631 class BtrfsDiskMount(DiskMount):
632 """A DiskMount object that is able to format/resize btrfs filesystems."""
633 def __init__(self, disk, mountdir, fstype, blocksize, fslabel, rmmountdir=True, skipformat = False, fsopts = None, fsuuid = None):
635 DiskMount.__init__(self, disk, mountdir, fstype, rmmountdir)
636 self.blocksize = blocksize
637 self.fslabel = fslabel.replace("/", "")
638 self.uuid = fsuuid or None
639 self.skipformat = skipformat
641 self.blkidcmd = find_binary_path("blkid")
642 self.btrfsckcmd = find_binary_path("btrfsck")
644 def __check_btrfs(self):
646 """ Need to load btrfs module to mount it """
648 for line in open("/proc/filesystems").xreadlines():
649 if line.find("btrfs") > -1:
653 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.")
655 # disable selinux, selinux will block write
656 if os.path.exists("/usr/sbin/setenforce"):
657 runner.show(["/usr/sbin/setenforce", "0"])
659 def __parse_field(self, output, field):
660 for line in output.split(" "):
661 if line.startswith(field + "="):
662 return line[len(field) + 1:].strip().replace("\"", "")
664 raise KeyError("Failed to find field '%s' in output" % field)
666 def __format_filesystem(self):
668 msger.debug("Skip filesystem format.")
671 msger.verbose("Formating %s filesystem on %s" % (self.fstype, self.disk.device))
672 rc = runner.show([self.mkfscmd, "-L", self.fslabel, self.disk.device])
674 raise MountError("Error creating %s filesystem on disk %s" % (self.fstype,self.disk.device))
676 self.uuid = self.__parse_field(runner.outs([self.blkidcmd, self.disk.device]), "UUID")
678 def __resize_filesystem(self, size = None):
679 current_size = os.stat(self.disk.lofile)[stat.ST_SIZE]
682 size = self.disk.size
684 if size == current_size:
687 if size > current_size:
688 self.disk.expand(size)
695 if not self.disk.fixed() and self.disk.exists():
701 self.__resize_filesystem()
703 self.__format_filesystem()
705 def mount(self, options = None):
707 DiskMount.mount(self, options)
710 msger.debug("Checking filesystem %s" % self.disk.lofile)
711 runner.quiet([self.btrfsckcmd, self.disk.lofile])
713 def __get_size_from_filesystem(self):
714 return self.disk.size
716 def __resize_to_minimal(self):
719 return self.__get_size_from_filesystem()
721 def resparse(self, size = None):
723 minsize = self.__resize_to_minimal()
724 self.disk.truncate(minsize)
725 self.__resize_filesystem(size)
728 class DeviceMapperSnapshot(object):
729 def __init__(self, imgloop, cowloop):
730 self.imgloop = imgloop
731 self.cowloop = cowloop
733 self.__created = False
735 self.dmsetupcmd = find_binary_path("dmsetup")
737 """Load dm_snapshot if it isn't loaded"""
738 load_module("dm_snapshot")
741 if self.__name is None:
743 return os.path.join("/dev/mapper", self.__name)
744 path = property(get_path)
750 self.imgloop.create()
751 self.cowloop.create()
753 self.__name = "imgcreate-%d-%d" % (os.getpid(),
754 random.randint(0, 2**16))
756 size = os.stat(self.imgloop.lofile)[stat.ST_SIZE]
758 table = "0 %d snapshot %s %s p 8" % (size / 512,
762 args = [self.dmsetupcmd, "create", self.__name, "--table", table]
763 if runner.show(args) != 0:
764 self.cowloop.cleanup()
765 self.imgloop.cleanup()
766 raise SnapshotError("Could not create snapshot device using: " + ' '.join(args))
768 self.__created = True
770 def remove(self, ignore_errors = False):
771 if not self.__created:
775 rc = runner.show([self.dmsetupcmd, "remove", self.__name])
776 if not ignore_errors and rc != 0:
777 raise SnapshotError("Could not remove snapshot device")
780 self.__created = False
782 self.cowloop.cleanup()
783 self.imgloop.cleanup()
785 def get_cow_used(self):
786 if not self.__created:
790 # dmsetup status on a snapshot returns e.g.
791 # "0 8388608 snapshot 416/1048576"
792 # or, more generally:
794 # where C is the number of 512 byte sectors in use
796 out = runner.outs([self.dmsetupcmd, "status", self.__name])
798 return int((out.split()[3]).split('/')[0]) * 512
800 raise SnapshotError("Failed to parse dmsetup status: " + out)
802 def create_image_minimizer(path, image, minimal_size):
804 Builds a copy-on-write image which can be used to
805 create a device-mapper snapshot of an image where
806 the image's filesystem is as small as possible
809 1) Create a sparse COW
810 2) Loopback mount the image and the COW
811 3) Create a device-mapper snapshot of the image
813 4) Resize the filesystem to the minimal size
814 5) Determine the amount of space used in the COW
815 6) Restroy the device-mapper snapshot
816 7) Truncate the COW, removing unused space
817 8) Create a squashfs of the COW
819 imgloop = LoopbackDisk(image, None) # Passing bogus size - doesn't matter
821 cowloop = SparseLoopbackDisk(os.path.join(os.path.dirname(path), "osmin"),
824 snapshot = DeviceMapperSnapshot(imgloop, cowloop)
829 resize2fs(snapshot.path, minimal_size)
831 cow_used = snapshot.get_cow_used()
833 snapshot.remove(ignore_errors = (not sys.exc_info()[0] is None))
835 cowloop.truncate(cow_used)
837 mksquashfs(cowloop.lofile, path)
839 os.unlink(cowloop.lofile)
841 def load_module(module):
843 for line in open('/proc/modules').xreadlines():
844 if line.startswith("%s " % module):
848 msger.info("Loading %s..." % module)
849 runner.quiet(['modprobe', module])
851 class LoopDevice(object):
852 def __init__(self, loopid=None):
856 self.kpartxcmd = find_binary_path("kpartx")
857 self.losetupcmd = find_binary_path("losetup")
859 def register(self, device):
864 def reg_atexit(self):
866 atexit.register(self.close)
868 def _genloopid(self):
870 if not glob.glob("/dev/loop[0-9]*"):
873 fint = lambda x: x[9:].isdigit() and int(x[9:]) or 0
874 maxid = 1 + max(filter(lambda x: x<100,
875 map(fint, glob.glob("/dev/loop[0-9]*"))))
876 if maxid < 10: maxid = 10
877 if maxid >= 100: raise
880 def _kpseek(self, device):
881 rc, out = runner.runtool([self.kpartxcmd, '-l', '-v', device])
883 raise MountError("Can't query dm snapshot on %s" % device)
884 for line in out.splitlines():
885 if line and line.startswith("loop"):
889 def _loseek(self, device):
891 rc, out = runner.runtool([self.losetupcmd, '-a'])
893 raise MountError("Failed to run 'losetup -a'")
894 for line in out.splitlines():
895 m = re.match("([^:]+): .*", line)
896 if m and m.group(1) == device:
903 self.loopid = self._genloopid()
904 self.device = "/dev/loop%d" % self.loopid
905 if os.path.exists(self.device):
906 if self._loseek(self.device):
907 raise MountError("Device busy: %s" % self.device)
912 mknod = find_binary_path('mknod')
913 rc = runner.show([mknod, '-m664', self.device, 'b', '7', str(self.loopid)])
915 raise MountError("Failed to create device %s" % self.device)
924 except MountError, e:
925 raise CreatorError("%s" % e)
929 if self.device is None:
933 if self._kpseek(self.device):
934 runner.quiet([self.kpartxcmd, "-d", self.device])
935 if self._loseek(self.device):
936 runner.quiet([self.losetupcmd, "-d", self.device])
937 # FIXME: should sleep a while between two loseek
938 if self._loseek(self.device):
939 msger.warning("Can't cleanup loop device %s" % self.device)
941 os.unlink(self.device)
943 DEVICE_PIDFILE_DIR = "/var/tmp/mic/device"
944 DEVICE_LOCKFILE = "/var/lock/__mic_loopdev.lock"
946 def get_loop_device(losetupcmd, lofile):
947 global DEVICE_PIDFILE_DIR
948 global DEVICE_LOCKFILE
951 makedirs(os.path.dirname(DEVICE_LOCKFILE))
952 fp = open(DEVICE_LOCKFILE, 'w')
953 fcntl.flock(fp, fcntl.LOCK_EX)
956 devinst = LoopDevice()
958 # clean up left loop device first
961 # provide an avaible loop device
962 rc, out = runner.runtool([losetupcmd, "--find"])
964 loopdev = out.split()[0]
965 devinst.register(loopdev)
966 if not loopdev or not os.path.exists(loopdev):
968 loopdev = devinst.device
970 # setup a loop device for image file
971 rc = runner.show([losetupcmd, loopdev, lofile])
973 raise MountError("Failed to setup loop device for '%s'" % lofile)
977 # try to save device and pid
978 makedirs(DEVICE_PIDFILE_DIR)
979 pidfile = os.path.join(DEVICE_PIDFILE_DIR, os.path.basename(loopdev))
980 if os.path.exists(pidfile):
982 with open(pidfile, 'w') as wf:
983 wf.write(str(os.getpid()))
985 except MountError, err:
986 raise CreatorError("%s" % str(err))
991 fcntl.flock(fp, fcntl.LOCK_UN)
993 os.unlink(DEVICE_LOCKFILE)
999 def clean_loop_devices(piddir=DEVICE_PIDFILE_DIR):
1000 if not os.path.exists(piddir) or not os.path.isdir(piddir):
1003 for loopdev in os.listdir(piddir):
1004 pidfile = os.path.join(piddir, loopdev)
1006 with open(pidfile, 'r') as rf:
1007 devpid = int(rf.read())
1011 # if the process using this device is alive, skip it
1012 if not devpid or os.path.exists(os.path.join('/proc', str(devpid))):
1015 # try to clean it up
1017 devinst = LoopDevice()
1018 devinst.register(os.path.join('/dev', loopdev))