2 # partitionedfs.py: partitioned files system class, extends fs.py
4 # Copyright 2007-2008, Red Hat Inc.
5 # Copyright 2008, Daniel P. Berrange
6 # Copyright 2008, David P. Huff
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; version 2 of the License.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Library General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 from mic.utils.errors import *
28 from mic.utils.fs_related import *
31 class PartitionedMount(Mount):
32 def __init__(self, disks, mountdir, skipformat = False):
33 Mount.__init__(self, mountdir)
35 for name in disks.keys():
36 self.disks[name] = { 'disk': disks[name], # Disk object
37 'mapped': False, # True if kpartx mapping exists
38 'numpart': 0, # Number of allocate partitions
39 'partitions': [], # indexes to self.partitions
40 # Partitions with part num higher than 3 will
41 # be put inside extended partition.
42 'extended': 0, # Size of extended partition
43 # Sector 0 is used by the MBR and can't be used
44 # as the start, so setting offset to 1.
45 'offset': 1 } # Offset of next partition (in sectors)
51 self.unmountOrder = []
52 self.parted=find_binary_path("parted")
53 self.kpartx=find_binary_path("kpartx")
54 self.mkswap=find_binary_path("mkswap")
56 self.mountcmd=find_binary_path("mount")
57 self.umountcmd=find_binary_path("umount")
58 self.skipformat = skipformat
59 self.snapshot_created = self.skipformat
60 # Size of a sector used in calculations
61 self.sector_size = 512
63 def add_partition(self, size, disk, mountpoint, fstype = None, fsopts = None, boot = False):
64 # Converting M to s for parted
65 size = size * 1024 * 1024 / self.sector_size
67 """ We need to handle subvolumes for btrfs """
68 if fstype == "btrfs" and fsopts and fsopts.find("subvol=") != -1:
69 self.btrfscmd=find_binary_path("btrfs")
71 opts = fsopts.split(",")
73 if opt.find("subvol=") != -1:
74 subvol = opt.replace("subvol=", "").strip()
77 raise MountError("No subvolume: %s" % fsopts)
78 self.subvolumes.append({'size': size, # In sectors
79 'mountpoint': mountpoint, # Mount relative to chroot
80 'fstype': fstype, # Filesystem type
81 'fsopts': fsopts, # Filesystem mount options
82 'disk': disk, # physical disk name holding partition
83 'device': None, # kpartx device node for partition
84 'mount': None, # Mount object
85 'subvol': subvol, # Subvolume name
86 'boot': boot, # Bootable flag
87 'mounted': False # Mount flag
90 """ We still need partition for "/" or non-subvolume """
91 if mountpoint == "/" or not fsopts or fsopts.find("subvol=") == -1:
92 """ Don't need subvolume for "/" because it will be set as default subvolume """
93 if fsopts and fsopts.find("subvol=") != -1:
94 opts = fsopts.split(",")
96 if opt.strip().startswith("subvol="):
99 fsopts = ",".join(opts)
100 self.partitions.append({'size': size, # In sectors
101 'mountpoint': mountpoint, # Mount relative to chroot
102 'fstype': fstype, # Filesystem type
103 'fsopts': fsopts, # Filesystem mount options
104 'disk': disk, # physical disk name holding partition
105 'device': None, # kpartx device node for partition
106 'mount': None, # Mount object
107 'num': None, # Partition number
108 'boot': boot}) # Bootable flag
110 def __create_part_to_image(self,device, parttype, fstype, start, size):
111 # Start is included to the size so we need to substract one from the end.
113 msger.debug("Added '%s' part at %d of size %d" % (parttype,start,end))
114 part_cmd = [self.parted, "-s", device, "unit", "s", "mkpart", parttype]
116 part_cmd.extend([fstype])
117 part_cmd.extend(["%d" % start, "%d" % end])
118 msger.debug(part_cmd)
119 p1 = subprocess.Popen(part_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
120 (out,err) = p1.communicate()
124 def __format_disks(self):
125 msger.debug("Assigning partitions to disks")
127 mbr_sector_skipped = False
129 for n in range(len(self.partitions)):
130 p = self.partitions[n]
132 if not self.disks.has_key(p['disk']):
133 raise MountError("No disk %s for partition %s" % (p['disk'], p['mountpoint']))
135 if not mbr_sector_skipped:
136 # This hack is used to remove one sector from the first partition,
137 # that is the used to the MBR.
139 mbr_sector_skipped = True
141 d = self.disks[p['disk']]
144 # Increase allocation of extended partition to hold this partition
145 d['extended'] += p['size']
146 p['type'] = 'logical'
147 p['num'] = d['numpart'] + 1
149 p['type'] = 'primary'
150 p['num'] = d['numpart']
152 p['start'] = d['offset']
153 d['offset'] += p['size']
154 d['partitions'].append(n)
155 msger.debug("Assigned %s to %s%d at %d at size %d" % (p['mountpoint'], p['disk'], p['num'], p['start'], p['size']))
158 msger.debug("Skipping disk format, because skipformat flag is set.")
161 for dev in self.disks.keys():
163 msger.debug("Initializing partition table for %s" % (d['disk'].device))
164 p1 = subprocess.Popen([self.parted, "-s", d['disk'].device, "mklabel", "msdos"],
165 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
166 (out,err) = p1.communicate()
169 if p1.returncode != 0:
170 # NOTE: We don't throw exception when return code is not 0, because
171 # parted always fails to reload part table with loop devices.
172 # This prevents us from distinguishing real errors based on return code.
173 msger.debug("WARNING: parted returned '%s' instead of 0 when creating partition-table for disk '%s'." % (p1.returncode,d['disk'].device))
175 msger.debug("Creating partitions")
177 for p in self.partitions:
178 d = self.disks[p['disk']]
180 self.__create_part_to_image(d['disk'].device,"extended",None,p['start'],d['extended'])
182 if p['fstype'] == "swap":
183 parted_fs_type = "linux-swap"
184 elif p['fstype'] == "vfat":
185 parted_fs_type = "fat32"
186 elif p['fstype'] == "msdos":
187 parted_fs_type = "fat16"
189 # Type for ext2/ext3/ext4/btrfs
190 parted_fs_type = "ext2"
192 # Boot ROM of OMAP boards require vfat boot partition to have an
193 # even number of sectors.
194 if p['mountpoint'] == "/boot" and p['fstype'] in ["vfat","msdos"] and p['size'] % 2:
195 msger.debug("Substracting one sector from '%s' partition to get even number of sectors for the partition." % (p['mountpoint']))
198 p1 = self.__create_part_to_image(d['disk'].device,p['type'],
199 parted_fs_type, p['start'],
202 if p1.returncode != 0:
203 # NOTE: We don't throw exception when return code is not 0, because
204 # parted always fails to reload part table with loop devices.
205 # This prevents us from distinguishing real errors based on return code.
206 msger.debug("WARNING: parted returned '%s' instead of 0 when creating partition '%s' for disk '%s'." % (p1.returncode,p['mountpoint'],d['disk'].device))
209 msger.debug("Setting boot flag for partition '%s' on disk '%s'." % (p['num'],d['disk'].device))
210 boot_cmd = [self.parted, "-s", d['disk'].device, "set", "%d" % p['num'], "boot", "on"]
211 msger.debug(boot_cmd)
212 p1 = subprocess.Popen(boot_cmd,
213 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
214 (out,err) = p1.communicate()
217 if p1.returncode != 0:
218 # NOTE: We don't throw exception when return code is not 0, because
219 # parted always fails to reload part table with loop devices.
220 # This prevents us from distinguishing real errors based on return code.
221 msger.debug("WARNING: parted returned '%s' instead of 0 when adding boot flag for partition '%s' disk '%s'." % (p1.returncode,p['num'],d['disk'].device))
223 def __map_partitions(self):
224 """Load it if dm_snapshot isn't loaded"""
225 load_module("dm_snapshot")
227 dev_null = os.open("/dev/null", os.O_WRONLY)
228 for dev in self.disks.keys():
233 msger.debug("Running kpartx on %s" % d['disk'].device )
234 kpartx = subprocess.Popen([self.kpartx, "-l", "-v", d['disk'].device],
235 stdout=subprocess.PIPE, stderr=dev_null)
237 kpartxOutput = kpartx.communicate()[0].strip().split("\n")
239 if kpartx.returncode:
241 raise MountError("Failed to query partition mapping for '%s'" %
244 # Strip trailing blank and mask verbose output
246 while i < len(kpartxOutput) and kpartxOutput[i][0:4] != "loop":
248 kpartxOutput = kpartxOutput[i:]
250 # Quick sanity check that the number of partitions matches
251 # our expectation. If it doesn't, someone broke the code
253 if len(kpartxOutput) != d['numpart']:
255 raise MountError("Unexpected number of partitions from kpartx: %d != %d" %
256 (len(kpartxOutput), d['numpart']))
258 for i in range(len(kpartxOutput)):
259 line = kpartxOutput[i]
260 newdev = line.split()[0]
261 mapperdev = "/dev/mapper/" + newdev
262 loopdev = d['disk'].device + newdev[-1]
264 msger.debug("Dev %s: %s -> %s" % (newdev, loopdev, mapperdev))
265 pnum = d['partitions'][i]
266 self.partitions[pnum]['device'] = loopdev
268 # grub's install wants partitions to be named
269 # to match their parent device + partition num
270 # kpartx doesn't work like this, so we add compat
271 # symlinks to point to /dev/mapper
272 if os.path.lexists(loopdev):
274 os.symlink(mapperdev, loopdev)
276 msger.debug("Adding partx mapping for %s" % d['disk'].device)
277 p1 = subprocess.Popen([self.kpartx, "-v", "-a", d['disk'].device],
278 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
280 (out,err) = p1.communicate()
283 if p1.returncode != 0:
284 # Make sure that the device maps are also removed on error case.
285 # The d['mapped'] isn't set to True if the kpartx fails so
286 # failed mapping will not be cleaned on cleanup either.
287 subprocess.call([self.kpartx, "-d", d['disk'].device],
288 stdout=dev_null, stderr=dev_null)
290 raise MountError("Failed to map partitions for '%s'" %
296 def __unmap_partitions(self):
297 dev_null = os.open("/dev/null", os.O_WRONLY)
298 for dev in self.disks.keys():
303 msger.debug("Removing compat symlinks")
304 for pnum in d['partitions']:
305 if self.partitions[pnum]['device'] != None:
306 os.unlink(self.partitions[pnum]['device'])
307 self.partitions[pnum]['device'] = None
309 msger.debug("Unmapping %s" % d['disk'].device)
310 rc = subprocess.call([self.kpartx, "-d", d['disk'].device],
311 stdout=dev_null, stderr=dev_null)
314 raise MountError("Failed to unmap partitions for '%s'" %
321 def __calculate_mountorder(self):
322 msger.debug("Calculating mount order")
323 for p in self.partitions:
324 self.mountOrder.append(p['mountpoint'])
325 self.unmountOrder.append(p['mountpoint'])
327 self.mountOrder.sort()
328 self.unmountOrder.sort()
329 self.unmountOrder.reverse()
333 self.__unmap_partitions()
334 for dev in self.disks.keys():
342 self.__unmount_subvolumes()
343 for mp in self.unmountOrder:
347 for p1 in self.partitions:
348 if p1['mountpoint'] == mp:
352 if p['mount'] != None:
354 """ Create subvolume snapshot here """
355 if p['fstype'] == "btrfs" and p['mountpoint'] == "/" and not self.snapshot_created:
356 self.__create_subvolume_snapshots(p, p["mount"])
362 """ Only for btrfs """
363 def __get_subvolume_id(self, rootpath, subvol):
364 if not self.btrfscmd:
365 self.btrfscmd=find_binary_path("btrfs")
366 argv = [ self.btrfscmd, "subvolume", "list", rootpath ]
367 p1 = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
368 (out,err) = p1.communicate()
370 if p1.returncode != 0:
371 raise MountError("Failed to get subvolume id from %s', return code: %d." % (rootpath, p1.returncode))
373 for line in out.split("\n"):
374 if line.endswith(" path %s" % subvol):
375 subvolid = line.split(" ")[1]
376 if not subvolid.isdigit():
377 raise MountError("Invalid subvolume id: %s" % subvolid)
378 subvolid = int(subvolid)
382 def __create_subvolume_metadata(self, p, pdisk):
383 if len(self.subvolumes) == 0:
385 argv = [ self.btrfscmd, "subvolume", "list", pdisk.mountdir ]
386 p1 = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
387 (out,err) = p1.communicate()
389 if p1.returncode != 0:
390 raise MountError("Failed to get subvolume id from %s', return code: %d." % (pdisk.mountdir, p1.returncode))
391 subvolid_items = out.split("\n")
392 subvolume_metadata = ""
393 for subvol in self.subvolumes:
394 for line in subvolid_items:
395 if line.endswith(" path %s" % subvol["subvol"]):
396 subvolid = line.split(" ")[1]
397 if not subvolid.isdigit():
398 raise MountError("Invalid subvolume id: %s" % subvolid)
399 subvolid = int(subvolid)
400 opts = subvol["fsopts"].split(",")
402 if opt.strip().startswith("subvol="):
405 fsopts = ",".join(opts)
406 subvolume_metadata += "%d\t%s\t%s\t%s\n" % (subvolid, subvol["subvol"], subvol['mountpoint'], fsopts)
407 if subvolume_metadata:
408 fd = open("%s/.subvolume_metadata" % pdisk.mountdir, "w")
409 fd.write(subvolume_metadata)
412 def __get_subvolume_metadata(self, p, pdisk):
413 subvolume_metadata_file = "%s/.subvolume_metadata" % pdisk.mountdir
414 if not os.path.exists(subvolume_metadata_file):
416 fd = open(subvolume_metadata_file, "r")
419 for line in content.split("\n"):
420 items = line.split("\t")
421 if items and len(items) == 4:
422 self.subvolumes.append({'size': 0, # In sectors
423 'mountpoint': items[2], # Mount relative to chroot
424 'fstype': "btrfs", # Filesystem type
425 'fsopts': items[3] + ",subvol=%s" % items[1], # Filesystem mount options
426 'disk': p['disk'], # physical disk name holding partition
427 'device': None, # kpartx device node for partition
428 'mount': None, # Mount object
429 'subvol': items[1], # Subvolume name
430 'boot': False, # Bootable flag
431 'mounted': False # Mount flag
434 def __create_subvolumes(self, p, pdisk):
435 """ Create all the subvolumes """
436 for subvol in self.subvolumes:
437 argv = [ self.btrfscmd, "subvolume", "create", pdisk.mountdir + "/" + subvol["subvol"]]
438 p1 = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
439 (out,err) = p1.communicate()
441 if p1.returncode != 0:
442 raise MountError("Failed to create subvolume '%s', return code: %d." % (subvol["subvol"], p1.returncode))
444 """ Set default subvolume, subvolume for "/" is default """
446 for subvolume in self.subvolumes:
447 if subvolume["mountpoint"] == "/" and p["disk"] == subvolume["disk"]:
451 """ Get default subvolume id """
452 subvolid = self. __get_subvolume_id(pdisk.mountdir, subvol["subvol"])
453 """ Set default subvolume """
455 argv = [ self.btrfscmd, "subvolume", "set-default", "%d" % subvolid, pdisk.mountdir]
456 p1 = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
457 (out,err) = p1.communicate()
459 if p1.returncode != 0:
460 raise MountError("Failed to set default subvolume id: %d', return code: %d." % (subvolid, p1.returncode))
462 self.__create_subvolume_metadata(p, pdisk)
464 def __mount_subvolumes(self, p, pdisk):
466 """ Get subvolume info """
467 self.__get_subvolume_metadata(p, pdisk)
468 """ Set default mount options """
469 if len(self.subvolumes) != 0:
470 for subvol in self.subvolumes:
471 if subvol["mountpoint"] == p["mountpoint"] == "/":
472 opts = subvol["fsopts"].split(",")
474 if opt.strip().startswith("subvol="):
477 pdisk.fsopts = ",".join(opts)
480 if len(self.subvolumes) == 0:
481 """ Return directly if no subvolumes """
484 """ Remount to make default subvolume mounted """
485 rc = subprocess.call([self.umountcmd, pdisk.mountdir])
487 raise MountError("Failed to umount %s" % pdisk.mountdir)
488 rc = subprocess.call([self.mountcmd, "-o", pdisk.fsopts, pdisk.disk.device, pdisk.mountdir])
490 raise MountError("Failed to umount %s" % pdisk.mountdir)
491 for subvol in self.subvolumes:
492 if subvol["mountpoint"] == "/":
494 subvolid = self. __get_subvolume_id(pdisk.mountdir, subvol["subvol"])
496 msger.debug("WARNING: invalid subvolume %s" % subvol["subvol"])
498 """ Replace subvolume name with subvolume ID """
499 opts = subvol["fsopts"].split(",")
501 if opt.strip().startswith("subvol="):
504 #opts.append("subvolid=%d" % subvolid)
505 opts.extend(["subvolrootid=0", "subvol=%s" % subvol["subvol"]])
506 fsopts = ",".join(opts)
507 subvol['fsopts'] = fsopts
508 mountpoint = self.mountdir + subvol['mountpoint']
510 rc = subprocess.call([self.mountcmd, "-o", fsopts, pdisk.disk.device, mountpoint])
512 raise MountError("Failed to mount subvolume %s to %s" % (subvol["subvol"], mountpoint))
513 subvol["mounted"] = True
515 def __unmount_subvolumes(self):
516 """ It may be called multiple times, so we need to chekc if it is still mounted. """
517 for subvol in self.subvolumes:
518 if subvol["mountpoint"] == "/":
520 if not subvol["mounted"]:
522 mountpoint = self.mountdir + subvol['mountpoint']
523 rc = subprocess.call([self.umountcmd, mountpoint])
525 raise MountError("Failed to unmount subvolume %s from %s" % (subvol["subvol"], mountpoint))
526 subvol["mounted"] = False
528 def __create_subvolume_snapshots(self, p, pdisk):
529 if self.snapshot_created:
532 """ Remount with subvolid=0 """
533 rc = subprocess.call([self.umountcmd, pdisk.mountdir])
535 raise MountError("Failed to umount %s" % pdisk.mountdir)
537 mountopts = pdisk.fsopts + ",subvolid=0"
539 mountopts = "subvolid=0"
540 rc = subprocess.call([self.mountcmd, "-o", mountopts, pdisk.disk.device, pdisk.mountdir])
542 raise MountError("Failed to umount %s" % pdisk.mountdir)
544 """ Create all the subvolume snapshots """
545 snapshotts = time.strftime("%Y%m%d-%H%M")
546 for subvol in self.subvolumes:
547 subvolpath = pdisk.mountdir + "/" + subvol["subvol"]
548 snapshotpath = subvolpath + "_%s-1" % snapshotts
549 argv = [ self.btrfscmd, "subvolume", "snapshot", subvolpath, snapshotpath ]
550 p1 = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
551 (out,err) = p1.communicate()
553 if p1.returncode != 0:
554 raise MountError("Failed to create subvolume snapshot '%s' for '%s', return code: %d." % (snapshotpath, subvolpath, p1.returncode))
555 self.snapshot_created = True
558 for dev in self.disks.keys():
562 self.__format_disks()
563 self.__map_partitions()
564 self.__calculate_mountorder()
566 for mp in self.mountOrder:
568 for p1 in self.partitions:
569 if p1['mountpoint'] == mp:
574 subprocess.call([self.mkswap, p['device']])
578 if p['mountpoint'] == "/":
580 if p['fstype'] == "vfat" or p['fstype'] == "msdos":
581 myDiskMount = VfatDiskMount
582 elif p['fstype'] in ("ext2", "ext3", "ext4"):
583 myDiskMount = ExtDiskMount
584 elif p['fstype'] == "btrfs":
585 myDiskMount = BtrfsDiskMount
587 raise MountError("Fail to support file system " + p['fstype'])
589 if p['fstype'] == "btrfs" and not p['fsopts']:
590 p['fsopts'] = "subvolid=0"
592 pdisk = myDiskMount(RawDisk(p['size'] * self.sector_size, p['device']),
593 self.mountdir + p['mountpoint'],
599 fsopts = p['fsopts'])
600 pdisk.mount(pdisk.fsopts)
601 if p['fstype'] == "btrfs" and p['mountpoint'] == "/":
602 if not self.skipformat:
603 self.__create_subvolumes(p, pdisk)
604 self.__mount_subvolumes(p, pdisk)
607 def resparse(self, size = None):
608 # Can't re-sparse a disk image - too hard