more cleanup
[tools/mic.git] / mic / utils / partitionedfs.py
1 #
2 # partitionedfs.py: partitioned files system class, extends fs.py
3 #
4 # Copyright 2007-2008, Red Hat  Inc.
5 # Copyright 2008, Daniel P. Berrange
6 # Copyright 2008,  David P. Huff
7 #
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.
11 #
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.
16 #
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.
20
21 import os
22 import glob
23 import shutil
24 import subprocess
25 import time
26
27 from mic.utils.errors import *
28 from mic.utils.fs_related import *
29 from mic import msger
30
31 class PartitionedMount(Mount):
32     def __init__(self, disks, mountdir, skipformat = False):
33         Mount.__init__(self, mountdir)
34         self.disks = {}
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)
46
47         self.partitions = []
48         self.subvolumes = []
49         self.mapped = False
50         self.mountOrder = []
51         self.unmountOrder = []
52         self.parted=find_binary_path("parted")
53         self.kpartx=find_binary_path("kpartx")
54         self.mkswap=find_binary_path("mkswap")
55         self.btrfscmd=None
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
62
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
66
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")
70             subvol = None
71             opts = fsopts.split(",")
72             for opt in opts:
73                 if opt.find("subvol=") != -1:
74                     subvol = opt.replace("subvol=", "").strip()
75                     break
76             if not subvol:
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
88                                    })
89
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(",")
95                 for opt in opts:
96                     if opt.strip().startswith("subvol="):
97                         opts.remove(opt)
98                         break
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
109
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.
112         end = start+size-1
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]
115         if fstype:
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()
121         msger.debug(out)
122         return p1
123
124     def __format_disks(self):
125         msger.debug("Assigning partitions to disks")
126
127         mbr_sector_skipped = False
128
129         for n in range(len(self.partitions)):
130             p = self.partitions[n]
131
132             if not self.disks.has_key(p['disk']):
133                 raise MountError("No disk %s for partition %s" % (p['disk'], p['mountpoint']))
134
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.
138                 p['size'] -= 1
139                 mbr_sector_skipped = True
140
141             d = self.disks[p['disk']]
142             d['numpart'] += 1
143             if d['numpart'] > 3:
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
148             else:
149                 p['type'] = 'primary'
150                 p['num'] = d['numpart']
151
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']))
156
157         if self.skipformat:
158             msger.debug("Skipping disk format, because skipformat flag is set.")
159             return
160
161         for dev in self.disks.keys():
162             d = self.disks[dev]
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()
167             msger.debug(out)
168
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))
174
175         msger.debug("Creating partitions")
176
177         for p in self.partitions:
178             d = self.disks[p['disk']]
179             if p['num'] == 5:
180                 self.__create_part_to_image(d['disk'].device,"extended",None,p['start'],d['extended'])
181
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"
188             else:
189                 # Type for ext2/ext3/ext4/btrfs
190                 parted_fs_type = "ext2"
191
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']))
196                 p['size'] -= 1
197
198             p1 = self.__create_part_to_image(d['disk'].device,p['type'],
199                                              parted_fs_type, p['start'],
200                                              p['size'])
201
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))
207
208             if p['boot']:
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()
215                 msger.debug(out)
216
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))
222
223     def __map_partitions(self):
224         """Load it if dm_snapshot isn't loaded"""
225         load_module("dm_snapshot")
226
227         dev_null = os.open("/dev/null", os.O_WRONLY)
228         for dev in self.disks.keys():
229             d = self.disks[dev]
230             if d['mapped']:
231                 continue
232
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)
236
237             kpartxOutput = kpartx.communicate()[0].strip().split("\n")
238
239             if kpartx.returncode:
240                 os.close(dev_null)
241                 raise MountError("Failed to query partition mapping for '%s'" %
242                                  d['disk'].device)
243
244             # Strip trailing blank and mask verbose output
245             i = 0
246             while i < len(kpartxOutput) and kpartxOutput[i][0:4] != "loop":
247                i = i + 1
248             kpartxOutput = kpartxOutput[i:]
249
250             # Quick sanity check that the number of partitions matches
251             # our expectation. If it doesn't, someone broke the code
252             # further up
253             if len(kpartxOutput) != d['numpart']:
254                 os.close(dev_null)
255                 raise MountError("Unexpected number of partitions from kpartx: %d != %d" %
256                                  (len(kpartxOutput), d['numpart']))
257
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]
263
264                 msger.debug("Dev %s: %s -> %s" % (newdev, loopdev, mapperdev))
265                 pnum = d['partitions'][i]
266                 self.partitions[pnum]['device'] = loopdev
267
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):
273                     os.unlink(loopdev)
274                 os.symlink(mapperdev, loopdev)
275
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)
279
280             (out,err) = p1.communicate()
281             msger.debug(out)
282
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)
289                 os.close(dev_null)
290                 raise MountError("Failed to map partitions for '%s'" %
291                                  d['disk'].device)
292             d['mapped'] = True
293         os.close(dev_null)
294
295
296     def __unmap_partitions(self):
297         dev_null = os.open("/dev/null", os.O_WRONLY)
298         for dev in self.disks.keys():
299             d = self.disks[dev]
300             if not d['mapped']:
301                 continue
302
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
308
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)
312             if rc != 0:
313                 os.close(dev_null)
314                 raise MountError("Failed to unmap partitions for '%s'" %
315                                  d['disk'].device)
316
317             d['mapped'] = False
318             os.close(dev_null)
319
320
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'])
326
327         self.mountOrder.sort()
328         self.unmountOrder.sort()
329         self.unmountOrder.reverse()
330
331     def cleanup(self):
332         Mount.cleanup(self)
333         self.__unmap_partitions()
334         for dev in self.disks.keys():
335             d = self.disks[dev]
336             try:
337                 d['disk'].cleanup()
338             except:
339                 pass
340
341     def unmount(self):
342         self.__unmount_subvolumes()
343         for mp in self.unmountOrder:
344             if mp == 'swap':
345                 continue
346             p = None
347             for p1 in self.partitions:
348                 if p1['mountpoint'] == mp:
349                     p = p1
350                     break
351
352             if p['mount'] != None:
353                 try:
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"])
357                     p['mount'].cleanup()
358                 except:
359                     pass
360                 p['mount'] = None
361
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()
369         msger.debug(out)
370         if p1.returncode != 0:
371             raise MountError("Failed to get subvolume id from %s', return code: %d." % (rootpath, p1.returncode))
372         subvolid = -1
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)
379                 break
380         return subvolid
381
382     def __create_subvolume_metadata(self, p, pdisk):
383         if len(self.subvolumes) == 0:
384             return
385         argv = [ self.btrfscmd, "subvolume", "list", pdisk.mountdir ]
386         p1 = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
387         (out,err) = p1.communicate()
388         msger.debug(out)
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(",")
401                     for opt in opts:
402                         if opt.strip().startswith("subvol="):
403                             opts.remove(opt)
404                             break
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)
410             fd.close()
411
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):
415             return
416         fd = open(subvolume_metadata_file, "r")
417         content = fd.read()
418         fd.close()
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
432                                    })
433
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()
440             msger.debug(out)
441             if p1.returncode != 0:
442                 raise MountError("Failed to create subvolume '%s', return code: %d." % (subvol["subvol"], p1.returncode))
443
444         """ Set default subvolume, subvolume for "/" is default """
445         subvol = None
446         for subvolume in self.subvolumes:
447             if subvolume["mountpoint"] == "/" and p["disk"] == subvolume["disk"]:
448                 subvol = subvolume
449                 break
450         if subvol:
451             """ Get default subvolume id """
452             subvolid = self. __get_subvolume_id(pdisk.mountdir, subvol["subvol"])
453             """ Set default subvolume """
454             if subvolid != -1:
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()
458                 msger.debug(out)
459                 if p1.returncode != 0:
460                     raise MountError("Failed to set default subvolume id: %d', return code: %d." % (subvolid, p1.returncode))
461
462         self.__create_subvolume_metadata(p, pdisk)
463
464     def __mount_subvolumes(self, p, pdisk):
465         if self.skipformat:
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(",")
473                         for opt in opts:
474                             if opt.strip().startswith("subvol="):
475                                 opts.remove(opt)
476                                 break
477                         pdisk.fsopts = ",".join(opts)
478                         break
479
480         if len(self.subvolumes) == 0:
481             """ Return directly if no subvolumes """
482             return
483
484         """ Remount to make default subvolume mounted """
485         rc = subprocess.call([self.umountcmd, pdisk.mountdir])
486         if rc != 0:
487             raise MountError("Failed to umount %s" % pdisk.mountdir)
488         rc = subprocess.call([self.mountcmd, "-o", pdisk.fsopts, pdisk.disk.device, pdisk.mountdir])
489         if rc != 0:
490             raise MountError("Failed to umount %s" % pdisk.mountdir)
491         for subvol in self.subvolumes:
492             if subvol["mountpoint"] == "/":
493                 continue
494             subvolid = self. __get_subvolume_id(pdisk.mountdir, subvol["subvol"])
495             if subvolid == -1:
496                 msger.debug("WARNING: invalid subvolume %s" % subvol["subvol"])
497                 continue
498             """ Replace subvolume name with subvolume ID """
499             opts = subvol["fsopts"].split(",")
500             for opt in opts:
501                 if opt.strip().startswith("subvol="):
502                     opts.remove(opt)
503                     break
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']
509             makedirs(mountpoint)
510             rc = subprocess.call([self.mountcmd, "-o", fsopts, pdisk.disk.device, mountpoint])
511             if rc != 0:
512                 raise MountError("Failed to mount subvolume %s to %s" % (subvol["subvol"], mountpoint))
513             subvol["mounted"] = True
514
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"] == "/":
519                 continue
520             if not subvol["mounted"]:
521                 continue
522             mountpoint = self.mountdir + subvol['mountpoint']
523             rc = subprocess.call([self.umountcmd, mountpoint])
524             if rc != 0:
525                 raise MountError("Failed to unmount subvolume %s from %s" % (subvol["subvol"], mountpoint))
526             subvol["mounted"] = False
527
528     def __create_subvolume_snapshots(self, p, pdisk):
529         if self.snapshot_created:
530             return
531
532         """ Remount with subvolid=0 """
533         rc = subprocess.call([self.umountcmd, pdisk.mountdir])
534         if rc != 0:
535             raise MountError("Failed to umount %s" % pdisk.mountdir)
536         if pdisk.fsopts:
537             mountopts = pdisk.fsopts + ",subvolid=0"
538         else:
539             mountopts = "subvolid=0"
540         rc = subprocess.call([self.mountcmd, "-o", mountopts, pdisk.disk.device, pdisk.mountdir])
541         if rc != 0:
542             raise MountError("Failed to umount %s" % pdisk.mountdir)
543
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()
552             msger.debug(out)
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
556
557     def mount(self):
558         for dev in self.disks.keys():
559             d = self.disks[dev]
560             d['disk'].create()
561
562         self.__format_disks()
563         self.__map_partitions()
564         self.__calculate_mountorder()
565
566         for mp in self.mountOrder:
567             p = None
568             for p1 in self.partitions:
569                 if p1['mountpoint'] == mp:
570                     p = p1
571                     break
572
573             if mp == 'swap':
574                 subprocess.call([self.mkswap, p['device']])
575                 continue
576
577             rmmountdir = False
578             if p['mountpoint'] == "/":
579                 rmmountdir = True
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
586             else:
587                 raise MountError("Fail to support file system " + p['fstype'])
588
589             if p['fstype'] == "btrfs" and not p['fsopts']:
590                 p['fsopts'] = "subvolid=0"
591
592             pdisk = myDiskMount(RawDisk(p['size'] * self.sector_size, p['device']),
593                                  self.mountdir + p['mountpoint'],
594                                  p['fstype'],
595                                  4096,
596                                  p['mountpoint'],
597                                  rmmountdir,
598                                  self.skipformat,
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)
605             p['mount'] = pdisk
606
607     def resparse(self, size = None):
608         # Can't re-sparse a disk image - too hard
609         pass