summaryrefslogtreecommitdiffstats
path: root/storage/formats/fs.py
blob: ec8358688e85f57dd28a89d336ccd7cda2b46e26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
# filesystems.py
# Filesystem classes for anaconda's storage configuration module.
#
# Copyright (C) 2009  Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.  You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Dave Lehman <dlehman@redhat.com>
#                    David Cantrell <dcantrell@redhat.com>
#

""" Filesystem classes for use by anaconda.

    TODO:
        - migration
        - bug 472127: allow creation of tmpfs filesystems (/tmp, /var/tmp, &c)
"""
import os
import tempfile
import isys

from ..errors import *
from . import DeviceFormat, register_device_format
import iutil
from flags import flags

# is this nasty?
log_method_call = iutil.log_method_call

import logging
log = logging.getLogger("storage")

import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)


fs_configs = {}

def get_kernel_filesystems():
    fs_list = []
    for line in open("/proc/filesystems").readlines():
        fs_list.append(line.split()[-1])
    return fs_list

global kernel_filesystems
kernel_filesystems = get_kernel_filesystems()

def fsConfigFromFile(config_file):
    """ Generate a set of attribute name/value pairs with which a
        filesystem type can be defined.

        The following config file would define a filesystem identical to
        the static Ext3FS class definition:

            type = ext3
            mkfs = "mke2fs"
            resizefs = "resize2fs"
            labelfs = "e2label"
            fsck = "e2fsck"
            packages = ["e2fsprogs"]
            formattable = True
            supported = True
            resizable = True
            bootable = True
            linuxNative = True
            maxSize = 8 * 1024 * 1024
            minSize = 0
            defaultFormatOptions = "-t ext3"
            defaultMountOptions = "defaults"

    """
    # XXX NOTUSED
    lines = open(config_file).readlines()
    fs_attrs = {}
    for line in lines:
        (key, value) = [t.strip() for t in line.split("=")]
        if not hasattr(FS, "_" + key):
            print "invalid key: %s" % key
            continue

        fs_attrs[key] = value

    if not fs_attrs.has_key("type"):
        raise ValueError, _("filesystem configuration missing a type")

    # XXX what's the policy about multiple configs for a given type?
    fs_configs[fs_attrs['type']] = fs_attrs

class FS(DeviceFormat):
    """ Filesystem class. """
    _type = "Abstract Filesystem Class"  # fs type name
    _mountType = None                    # like _type but for passing to mount
    _name = None
    _mkfs = ""                           # mkfs utility
    _modules = []                        # kernel modules required for support
    _resizefs = ""                       # resize utility
    _labelfs = ""                        # labeling utility
    _fsck = ""                           # fs check utility
    _migratefs = ""                      # fs migration utility
    _infofs = ""                         # fs info utility
    _defaultFormatOptions = []           # default options passed to mkfs
    _defaultMountOptions = ["defaults"]  # default options passed to mount
    _defaultLabelOptions = []
    _defaultCheckOptions = []
    _defaultMigrateOptions = []
    _defaultInfoOptions = []
    _migrationTarget = None
    _existingSizeFields = []
    lostAndFoundContext = None

    def __init__(self, *args, **kwargs):
        """ Create a FS instance.

            Keyword Args:

                device -- path to the device containing the filesystem
                mountpoint -- the filesystem's mountpoint
                label -- the filesystem label
                uuid -- the filesystem UUID
                mountopts -- mount options for the filesystem
                size -- the filesystem's size in MiB
                exists -- indicates whether this is an existing filesystem
                
        """
        if self.__class__ is FS:
            raise TypeError("FS is an abstract class.")

        DeviceFormat.__init__(self, *args, **kwargs)
        # TODO: fsprofiles and other ways to add format args
        self.mountpoint = kwargs.get("mountpoint")
        self.mountopts = kwargs.get("mountopts")
        self.label = kwargs.get("label")

        # filesystem size does not necessarily equal device size
        self._size = kwargs.get("size", 0)
        self._minInstanceSize = None    # min size of this FS instance
        self._mountpoint = None     # the current mountpoint when mounted
        if self.exists:
            self._size = self._getExistingSize()
            foo = self.minSize      # force calculation of minimum size

        self._targetSize = self._size

        if self.supported:
            self.loadModule()

    def _setTargetSize(self, newsize):
        """ Set a target size for this filesystem. """
        if not self.exists:
            raise FSError("filesystem has not been created")

        if newsize is None:
            # unset any outstanding resize request
            self._targetSize = None
            return

        if not self.minSize < newsize < self.maxSize:
            raise ValueError("invalid target size request")

        self._targetSize = newsize

    def _getTargetSize(self):
        """ Get this filesystem's target size. """
        return self._targetSize

    targetSize = property(_getTargetSize, _setTargetSize,
                          doc="Target size for this filesystem")

    def _getSize(self):
        """ Get this filesystem's size. """
        size = self._size
        if self.resizable and self.targetSize != size:
            size = self.targetSize
        return size

    size = property(_getSize, doc="This filesystem's size, accounting "
                                  "for pending changes")

    def _getExistingSize(self):
        """ Determine the size of this filesystem.  Filesystem must
            exist.  Each filesystem varies, but the general procedure
            is to run the filesystem dump or info utility and read
            the block size and number of blocks for the filesystem
            and compute megabytes from that.

            The loop that reads the output from the infofsProg is meant
            to be simple, but take in to account variations in output.
            The general procedure:
                1) Capture output from infofsProg.
                2) Iterate over each line of the output:
                       a) Trim leading and trailing whitespace.
                       b) Break line into fields split on ' '
                       c) If line begins with any of the strings in
                          _existingSizeFields, start at the end of
                          fields and take the first one that converts
                          to a long.  Store this in the values list.
                       d) Repeat until the values list length equals
                          the _existingSizeFields length.
                3) If the length of the values list equals the length
                   of _existingSizeFields, compute the size of this
                   filesystem by multiplying all of the values together
                   to get bytes, then convert to megabytes.  Return
                   this value.
                4) If we were unable to capture all fields, return 0.

            The caller should catch exceptions from this method.  Any
            exception raised indicates a need to change the fields we
            are looking for, the command to run and arguments, or
            something else.  If you catch an exception from this method,
            assume the filesystem cannot be resized.
        """
        size = self._size

        if self.infofsProg and self.mountable and self.exists and not size:
            try:
                values = []
                argv = self._defaultInfoOptions + [ self.device ]

                buf = iutil.execWithCapture(self.infofsProg, argv,
                                            stderr="/dev/tty5")

                for line in buf.splitlines():
                    found = False

                    line = line.strip()
                    tmp = line.split(' ')
                    tmp.reverse()

                    for field in self._existingSizeFields:
                        if line.startswith(field):
                            for subfield in tmp:
                                try:
                                    values.append(long(subfield))
                                    found = True
                                    break
                                except ValueError:
                                    continue

                        if found:
                            break

                    if len(values) == len(self._existingSizeFields):
                        break

                if len(values) != len(self._existingSizeFields):
                    return 0

                size = 1
                for value in values:
                    size *= value

                # report current size as megabytes
                size = size / 1024.0 / 1024.0
            except Exception as e:
                log.error("failed to obtain size of filesystem on %s: %s"
                          % (self.device, e))

        return size

    @property
    def currentSize(self):
        """ The filesystem's current actual size. """
        size = 0
        if self.exists:
            size = self._size
        return float(size)

    def _getFormatOptions(self, options=None):
        argv = []
        if options and isinstance(options, list):
            argv.extend(options)
        argv.extend(self.defaultFormatOptions)
        argv.append(self.device)
        return argv
    
    def doFormat(self, *args, **kwargs):
        """ Create the filesystem.

            Arguments:

                None

            Keyword Arguments:

                intf -- InstallInterface instance
                options -- list of options to pass to mkfs

        """
        log_method_call(self, type=self.mountType, device=self.device,
                        mountpoint=self.mountpoint)

        intf = kwargs.get("intf")
        options = kwargs.get("options")

        if self.exists:
            raise FormatCreateError("filesystem already exists", self.device)

        if not self.formattable:
            return

        if not self.mkfsProg:
            return

        if self.exists:
            return

        if not os.path.exists(self.device):
            raise FormatCreateError("device does not exist", self.device)

        argv = self._getFormatOptions(options=options)

        w = None
        if intf:
            w = intf.progressWindow(_("Formatting"),
                                    _("Creating filesystem on %s")
                                    % (self.device,),
                                    100, pulse = True)

        try:
            rc = iutil.execWithPulseProgress(self.mkfsProg,
                                             argv,
                                             stdout="/dev/tty5",
                                             stderr="/dev/tty5",
                                             progress=w)
        except Exception as e:
            raise FormatCreateError(e, self.device)
        finally:
            if w:
                w.pop()

        if rc:
            raise FormatCreateError("format failed: %s" % rc, self.device)
                                                                  
        self.exists = True
        self.notifyKernel()

    def doMigrate(self, intf=None):
        if not self.exists:
            raise FSError("filesystem has not been created")

        if not self.migratable or not self.migrate:
            return

        if not os.path.exists(self.device):
            raise FSError("device does not exist")

        # if journal already exists skip
        if isys.ext2HasJournal(self.device):
            log.info("Skipping migration of %s, has a journal already."
                     % self.device)
            return

        argv = self._defaultMigrateOptions[:]
        argv.append(self.device)
        try:
            rc = iutil.execWithRedirect(self.migratefsProg,
                                        argv,
                                        stdout = "/dev/tty5",
                                        stderr = "/dev/tty5",
                                        searchPath = 1)
        except Exception as e:
            raise FSMigrateError("filesystem migration failed: %s" % e,
                                 self.device)

        if rc:
            raise FSMigrateError("filesystem migration failed: %s" % rc,
                                 self.device)

        # the other option is to actually replace this instance with an
        # instance of the new filesystem type.
        self._type = self.migrationTarget

    @property
    def resizeArgs(self):
        argv = [self.device, "%d" % (self.targetSize,)]
        return argv

    def doResize(self, *args, **kwargs):
        """ Resize this filesystem to new size @newsize.

            Arguments:

                None

            Keyword Arguments:

                intf -- InstallInterface instance

        """
        intf = kwargs.get("intf")

        if not self.exists:
            raise FSResizeError("filesystem does not exist", self.device)

        if not self.resizable:
            raise FSResizeError("filesystem not resizable", self.device)

        if self.targetSize == self.currentSize:
            return

        if not self.resizefsProg:
            return

        if not os.path.exists(self.device):
            raise FSResizeError("device does not exist", self.device)

        self.doCheck(intf=intf)

        w = None
        if intf:
            w = intf.progressWindow(_("Resizing"),
                                    _("Resizing filesystem on %s")
                                    % (self.device,),
                                    100, pulse = True)

        try:
            rc = iutil.execWithPulseProgress(self.resizefsProg,
                                             self.resizeArgs,
                                             stdout="/dev/tty5",
                                             stderr="/dev/tty5",
                                             progress=w)
        except Exception as e:
            raise FSResizeError(e, self.device)
        finally:
            if w:
                w.pop()

        if rc:
            raise FSResizeError("resize failed: %s" % rc, self.device)

        self.doCheck(intf=intf)

        # XXX must be a smarter way to do this
        self._size = self.targetSize
        self.notifyKernel()

    def _getCheckArgs(self):
        argv = []
        argv.extend(self.defaultCheckOptions)
        argv.append(self.device)
        return argv

    def doCheck(self, intf=None):
        if not self.exists:
            raise FSError("filesystem has not been created")

        if not self.fsckProg:
            return

        if not os.path.exists(self.device):
            raise FSError("device does not exist")

        w = None
        if intf:
            w = intf.progressWindow(_("Checking"),
                                    _("Checking filesystem on %s")
                                    % (self.device),
                                    100, pulse = True)

        try:
            rc = iutil.execWithPulseProgress(self.fsckProg,
                                             self._getCheckArgs(),
                                             stdout="/dev/tty5",
                                             stderr="/dev/tty5",
                                             progress = w)
        except Exception as e:
            raise FSError("filesystem check failed: %s" % e)
        finally:
            if w:
                w.pop()

        if rc >= 4:
            raise FSError("filesystem check failed: %s" % rc)

    def loadModule(self):
        """Load whatever kernel module is required to support this filesystem."""
        global kernel_filesystems

        if not self._modules or self.mountType in kernel_filesystems:
            return

        for module in self._modules:
            try:
                rc = iutil.execWithRedirect("modprobe", [module],
                                            stdout="/dev/tty5", stderr="/dev/tty5",
                                            searchPath=1)
            except Exception as e:
                log.error("Could not load kernel module %s: %s" % (module, e))
                self._supported = False
                return

            if rc:
                log.error("Could not load kernel module %s" % module)
                self._supported = False
                return

        # If we successfully loaded a kernel module, for this filesystem, we
        # also need to update the list of supported filesystems.
        kernel_filesystems = get_kernel_filesystems()

    def mount(self, *args, **kwargs):
        """ Mount this filesystem.

            Arguments:

                None

            Keyword Arguments:

                options -- mount options (overrides all other option strings)
                chroot -- prefix to apply to mountpoint
                mountpoint -- mountpoint (overrides self.mountpoint)
        """
        options = kwargs.get("options", "")
        chroot = kwargs.get("chroot", "/")
        mountpoint = kwargs.get("mountpoint")

        if not self.exists:
            raise FSError("filesystem has not been created")

        if not mountpoint:
            mountpoint = self.mountpoint

        if not mountpoint:
            raise FSError("no mountpoint given")

        if self.status:
            return

        if not isinstance(self, NoDevFS) and not os.path.exists(self.device):
            raise FSError("device %s does not exist" % self.device)

        # XXX os.path.join is FUBAR:
        #
        #         os.path.join("/mnt/foo", "/") -> "/"
        #
        #mountpoint = os.path.join(chroot, mountpoint)
        chrootedMountpoint = os.path.normpath("%s/%s" % (chroot, mountpoint))
        iutil.mkdirChain(chrootedMountpoint)
        if flags.selinux:
            ret = isys.resetFileContext(mountpoint, chroot)
            log.info("set SELinux context for mountpoint %s to %s" \
                     % (mountpoint, ret))

        # passed in options override default options
        if not options or not isinstance(options, str):
            options = self.options

        try: 
            rc = isys.mount(self.device, chrootedMountpoint, 
                            fstype=self.mountType,
                            options=options,
                            bindMount=isinstance(self, BindFS))
        except Exception as e:
            raise FSError("mount failed: %s" % e)

        if rc:
            raise FSError("mount failed: %s" % rc)

        if flags.selinux:
            ret = isys.resetFileContext(mountpoint, chroot)
            log.info("set SELinux context for newly mounted filesystem "
                     "root at %s to %s" %(mountpoint, ret))
            if self.lostAndFoundContext is None:
                self.lostAndFoundContext = isys.matchPathContext("/lost+found")
            isys.setFileContext("%s/lost+found" % mountpoint,
                                self.lostAndFoundContext, chroot)

        self._mountpoint = chrootedMountpoint

    def unmount(self):
        """ Unmount this filesystem. """
        if not self.exists:
            raise FSError("filesystem has not been created")

        if not self._mountpoint:
            # not mounted
            return

        if not os.path.exists(self._mountpoint):
            raise FSError("mountpoint does not exist")

        rc = isys.umount(self._mountpoint, removeDir = False)
        if rc:
            raise FSError("umount failed")

        self._mountpoint = None

    def _getLabelArgs(self, label):
        argv = []
        argv.extend(self.defaultLabelOptions)
        argv.extend([self.device, label])
        return argv 

    def writeLabel(self, label):
        """ Create a label for this filesystem. """
        if not self.exists:
            raise FSError("filesystem has not been created")

        if not self.labelfsProg:
            return

        if not os.path.exists(self.device):
            raise FSError("device does not exist")

        argv = self._getLabelArgs(label)
        rc = iutil.execWithRedirect(self.labelfsProg,
                                    argv,
                                    stderr="/dev/tty5",
                                    searchPath=1)
        if rc:
            raise FSError("label failed")

        self.label = label
        self.notifyKernel()

    @property
    def isDirty(self):
        return False

    @property
    def mkfsProg(self):
        """ Program used to create filesystems of this type. """
        return self._mkfs

    @property
    def fsckProg(self):
        """ Program used to check filesystems of this type. """
        return self._fsck

    @property
    def resizefsProg(self):
        """ Program used to resize filesystems of this type. """
        return self._resizefs

    @property
    def labelfsProg(self):
        """ Program used to manage labels for this filesystem type. """
        return self._labelfs

    @property
    def migratefsProg(self):
        """ Program used to migrate filesystems of this type. """
        return self._migratefs

    @property
    def infofsProg(self):
        """ Program used to get information for this filesystem type. """
        return self._infofs

    @property
    def migrationTarget(self):
        return self._migrationTarget

    @property
    def utilsAvailable(self):
        # we aren't checking for fsck because we shouldn't need it
        for prog in [self.mkfsProg, self.resizefsProg, self.labelfsProg,
                     self.infofsProg]:
            if not prog:
                continue

            if not filter(lambda d: os.access("%s/%s" % (d, prog), os.X_OK),
                          os.environ["PATH"].split(":")):
                return False

        return True

    @property
    def supported(self):
        log_method_call(self, supported=self._supported)
        return self._supported and self.utilsAvailable

    @property
    def mountable(self):
        return (self.mountType in kernel_filesystems) or \
               (os.access("/sbin/mount.%s" % (self.mountType,), os.X_OK))

    @property
    def defaultFormatOptions(self):
        """ Default options passed to mkfs for this filesystem type. """
        # return a copy to prevent modification
        return self._defaultFormatOptions[:]

    @property
    def defaultMountOptions(self):
        """ Default options passed to mount for this filesystem type. """
        # return a copy to prevent modification
        return self._defaultMountOptions[:]

    @property
    def defaultLabelOptions(self):
        """ Default options passed to labeler for this filesystem type. """
        # return a copy to prevent modification
        return self._defaultLabelOptions[:]

    @property
    def defaultCheckOptions(self):
        """ Default options passed to checker for this filesystem type. """
        # return a copy to prevent modification
        return self._defaultCheckOptions[:]

    def _getOptions(self):
        options = ",".join(self.defaultMountOptions)
        if self.mountopts:
            # XXX should we clobber or append?
            options = self.mountopts
        return options

    def _setOptions(self, options):
        self.mountopts = options

    options = property(_getOptions, _setOptions)

    def _isMigratable(self):
        """ Can filesystems of this type be migrated? """
        return bool(self._migratable and self.migratefsProg and
                    filter(lambda d: os.access("%s/%s"
                                               % (d, self.migratefsProg,),
                                               os.X_OK),
                           os.environ["PATH"].split(":")) and
                    self.migrationTarget)

    migratable = property(_isMigratable)

    def _setMigrate(self, migrate):
        if not migrate:
            self._migrate = migrate
            return

        if self.migratable and self.exists:
            self._migrate = migrate
        else:
            raise ValueError("cannot set migrate on non-migratable filesystem")

    migrate = property(lambda f: f._migrate, lambda f,m: f._setMigrate(m))

    @property
    def type(self):
        _type = self._type
        if self.migrate:
            _type = self.migrationTarget

        return _type

    @property
    def mountType(self):
        if not self._mountType:
            self._mountType = self._type

        return self._mountType

    # These methods just wrap filesystem-specific methods in more
    # generically named methods so filesystems and formatted devices
    # like swap and LVM physical volumes can have a common API.
    def create(self, *args, **kwargs):
        if self.exists:
            raise FSError("filesystem already exists")

        DeviceFormat.create(self, *args, **kwargs)

        return self.doFormat(*args, **kwargs)

    def setup(self, *args, **kwargs):
        """ Mount the filesystem.

            The filesystem will be mounted at the directory indicated by
            self.mountpoint.
        """
        return self.mount(**kwargs)

    def teardown(self, *args, **kwargs):
        return self.unmount(*args, **kwargs)

    @property
    def status(self):
        # FIXME check /proc/mounts or similar
        if not self.exists:
            return False
        return self._mountpoint is not None

    def writeKS(self, f):
        f.write("%s --fstype=%s" % (self.mountpoint, self.type))


class Ext2FS(FS):
    """ ext2 filesystem. """
    _type = "ext2"
    _mkfs = "mke2fs"
    _modules = ["ext2"]
    _resizefs = "resize2fs"
    _labelfs = "e2label"
    _fsck = "e2fsck"
    _packages = ["e2fsprogs"]
    _formattable = True
    _supported = True
    _resizable = True
    _bootable = True
    _linuxNative = True
    _maxSize = 8 * 1024 * 1024
    _minSize = 0
    _defaultFormatOptions = []
    _defaultMountOptions = ["defaults"]
    _defaultCheckOptions = ["-f", "-p", "-C", "0"]
    _dump = True
    _check = True
    _migratable = True
    _migrationTarget = "ext3"
    _migratefs = "tune2fs"
    _defaultMigrateOptions = ["-j"]
    _infofs = "dumpe2fs"
    _defaultInfoOptions = ["-h"]
    _existingSizeFields = ["Block count:", "Block size:"]

    def doMigrate(self, intf=None):
        FS.doMigrate(self, intf=intf)
        self.tuneFS()

    def doFormat(self, *args, **kwargs):
        FS.doFormat(self, *args, **kwargs)
        self.tuneFS()

    def tuneFS(self):
        if not isys.ext2HasJournal(self.device):
            # only do this if there's a journal
            return

        try:
            rc = iutil.execWithRedirect("tune2fs",
                                        ["-c0", "-i0",
                                         "-ouser_xattr,acl", self.device],
                                        searchPath = True,
                                        stdout = "/dev/tty5",
                                        stderr = "/dev/tty5")
        except Exception as e:
            log.error("failed to run tune2fs on %s: %s" % (self.device, e))

    @property
    def minSize(self):
        """ Minimum size for this filesystem in MB. """
        if self._minInstanceSize is None:
            # try once in the beginning to get the minimum size for an
            # existing filesystem.
            size = self._minSize
            if self.exists and os.path.exists(self.device):
                buf = iutil.execWithCapture(self.resizefsProg,
                                            ["-P", self.device],
                                            stderr="/dev/tty5")
                for line in buf.splitlines():
                    if "minimum size of the filesystem:" not in line:
                        continue

                    (text, sep, minSize) = line.partition(": ")

                    size = int(minSize) / 1024.0

                if size is None:
                    log.warning("failed to get minimum size for %s filesystem "
                                "on %s" % (self.mountType, self.device))

            self._minInstanceSize = size

        return self._minInstanceSize

    @property
    def isDirty(self):
        return isys.ext2IsDirty(self.device)

    @property
    def resizeArgs(self):
        argv = ["-p", self.device, "%dM" % (self.targetSize,)]
        return argv

register_device_format(Ext2FS)


class Ext3FS(Ext2FS):
    """ ext3 filesystem. """
    _type = "ext3"
    _defaultFormatOptions = ["-t", "ext3"]
    _migrationTarget = "ext4"
    _modules = ["ext3"]
    _defaultMigrateOptions = ["-O", "extents"]

    def _isMigratable(self):
        """ Can filesystems of this type be migrated? """
        return (flags.cmdline.has_key("ext4migrate") and
                Ext2FS._isMigratable(self))

    migratable = property(_isMigratable)

register_device_format(Ext3FS)


class Ext4FS(Ext3FS):
    """ ext4 filesystem. """
    _type = "ext4"
    _defaultFormatOptions = ["-t", "ext4"]
    _migratable = False
    _modules = ["ext4"]

register_device_format(Ext4FS)


class FATFS(FS):
    """ FAT filesystem. """
    _type = "vfat"
    _mkfs = "mkdosfs"
    _modules = ["vfat"]
    _labelfs = "dosfslabel"
    _fsck = "dosfsck"
    _supported = True
    _formattable = True
    _maxSize = 1024 * 1024
    _packages = [ "dosfstools" ]
    _defaultMountOptions = ["umask=0077", "shortname=winnt"]

register_device_format(FATFS)


class EFIFS(FATFS):
    _type = "efi"
    _mountType = "vfat"
    _modules = ["vfat"]
    _name = "EFI System Partition"
    _minSize = 50
    _maxSize = 256
    _bootable = True

    @property
    def supported(self):
        import platform
        p = platform.getPlatform(None)
        return (isinstance(p, platform.EFI) and
                p.isEfi and
                self.utilsAvailable)

register_device_format(EFIFS)


class BTRFS(FS):
    """ btrfs filesystem """
    _type = "btrfs"
    _mkfs = "mkfs.btrfs"
    _modules = ["btrfs"]
    _resizefs = "btrfsctl"
    _formattable = True
    _linuxNative = True
    _bootable = False
    _maxLabelChars = 256
    _supported = False
    _dump = True
    _check = True
    _packages = ["btrfs-progs"]
    _maxSize = 16 * 1024 * 1024

    def _getFormatOptions(self, options=None):
        argv = []
        if options and isinstance(options, list):
            argv.extend(options)
        argv.extend(self.defaultFormatOptions)
        if self.label:
            argv.extend(["-L", self.label])
        argv.append(self.device)
        return argv

    @property
    def resizeArgs(self):
        argv = ["-r", "%dm" % (self.targetSize,), self.device]
        return argv

    @property
    def supported(self):
        """ Is this filesystem a supported type? """
        supported = self._supported
        if flags.cmdline.has_key("icantbelieveitsnotbtr"):
            supported = self.utilsAvailable

        return supported

register_device_format(BTRFS)


class GFS2(FS):
    """ gfs2 filesystem. """
    _type = "gfs2"
    _mkfs = "mkfs.gfs2"
    _modules = ["dlm", "gfs2"]
    _formattable = True
    _defaultFormatOptions = ["-j", "1", "-p", "lock_nolock", "-O"]
    _linuxNative = True
    _supported = False
    _dump = True
    _check = True
    _packages = ["gfs2-utils"]

    @property
    def supported(self):
        """ Is this filesystem a supported type? """
        supported = self._supported
        if flags.cmdline.has_key("gfs2"):
            supported = self.utilsAvailable

        return supported

register_device_format(GFS2)


class JFS(FS):
    """ JFS filesystem """
    _type = "jfs"
    _mkfs = "mkfs.jfs"
    _modules = ["jfs"]
    _labelfs = "jfs_tune"
    _defaultFormatOptions = ["-q"]
    _defaultLabelOptions = ["-L"]
    _maxLabelChars = 16
    _maxSize = 8 * 1024 * 1024
    _formattable = True
    _linuxNative = True
    _supported = False
    _dump = True
    _check = True
    _infofs = "jfs_tune"
    _defaultInfoOptions = ["-l"]
    _existingSizeFields = ["Aggregate block size:", "Aggregate size:"]

    @property
    def supported(self):
        """ Is this filesystem a supported type? """
        supported = self._supported
        if flags.cmdline.has_key("jfs"):
            supported = self.utilsAvailable

        return supported

register_device_format(JFS)


class ReiserFS(FS):
    """ reiserfs filesystem """
    _type = "reiserfs"
    _mkfs = "mkreiserfs"
    _resizefs = "resize_reiserfs"
    _modules = ["reiserfs"]
    _defaultFormatOptions = ["-f", "-f"]
    _defaultLabelOptions = ["-l"]
    _maxLabelChars = 16
    _maxSize = 16 * 1024 * 1024
    _formattable = True
    _linuxNative = True
    _supported = False
    _dump = True
    _check = True
    _packages = ["reiserfs-utils"]
    _infofs = "debugreiserfs"
    _defaultInfoOptions = []
    _existingSizeFields = ["Count of blocks on the device:", "Blocksize:"]

    @property
    def supported(self):
        """ Is this filesystem a supported type? """
        supported = self._supported
        if flags.cmdline.has_key("reiserfs"):
            supported = self.utilsAvailable

        return supported

    @property
    def resizeArgs(self):
        argv = ["-s", "%dM" % (self.targetSize,), self.device]
        return argv

register_device_format(ReiserFS)


class XFS(FS):
    """ XFS filesystem """
    _type = "xfs"
    _mkfs = "mkfs.xfs"
    _modules = ["xfs"]
    _labelfs = "xfs_admin"
    _defaultFormatOptions = ["-f"]
    _defaultLabelOptions = ["-L"]
    _maxLabelChars = 16
    _maxSize = 16 * 1024 * 1024
    _formattable = True
    _linuxNative = True
    _supported = True
    _dump = True
    _check = True
    _packages = ["xfsprogs"]
    _infofs = "xfs_db"
    _defaultInfoOptions = ["-c", "\"sb 0\"", "-c", "\"p dblocks\"",
                           "-c", "\"p blocksize\""]
    _existingSizeFields = ["dblocks =", "blocksize ="]

register_device_format(XFS)


class HFS(FS):
    _type = "hfs"
    _mkfs = "hformat"
    _modules = ["hfs"]
    _formattable = True

register_device_format(HFS)


class AppleBootstrapFS(HFS):
    _type = "appleboot"
    _mountType = "hfs"
    _name = "Apple Bootstrap"
    _bootable = True
    _minSize = 800.00 / 1024.00
    _maxSize = 1

    @property
    def supported(self):
        import platform
        return (isinstance(platform.getPlatform(None), platform.NewWorldPPC)
                and self.utilsAvailable)

    def writeKS(self, f):
        f.write("appleboot --fstype=%s" % self.type)

register_device_format(AppleBootstrapFS)


# this doesn't need to be here
class HFSPlus(FS):
    _type = "hfs+"
    _modules = ["hfsplus"]
    _udevTypes = ["hfsplus"]

register_device_format(HFSPlus)


class NTFS(FS):
    """ ntfs filesystem. """
    _type = "ntfs"
    _resizefs = "ntfsresize"
    _fsck = "ntfsresize"
    _resizable = True
    _minSize = 1
    _maxSize = 16 * 1024 * 1024
    _defaultMountOptions = ["defaults"]
    _defaultCheckOptions = ["-c"]
    _packages = ["ntfsprogs"]
    _infofs = "ntfsinfo"
    _defaultInfoOptions = ["-m"]
    _existingSizeFields = ["Cluster Size:", "Volume Size in Clusters:"]

    @property
    def minSize(self):
        """ The minimum filesystem size in megabytes. """
        if self._minInstanceSize is None:
            # we try one time to determine the minimum size.
            size = self._minSize
            if self.exists and os.path.exists(self.device):
                minSize = None
                buf = iutil.execWithCapture(self.resizefsProg,
                                            ["-m", self.device],
                                            stderr = "/dev/tty5")
                for l in buf.split("\n"):
                    if not l.startswith("Minsize"):
                        continue
                    try:
                        min = l.split(":")[1].strip()
                        minSize = int(min) + 250
                    except Exception, e:
                        minSize = None
                        log.warning("Unable to parse output for minimum size on %s: %s" %(self.device, e))

                if minSize is None:
                    log.warning("Unable to discover minimum size of filesystem "
                                "on %s" %(self.device,))
                else:
                    size = minSize

            self._minInstanceSize = size

        return self._minInstanceSize

    @property
    def resizeArgs(self):
        # You must supply at least two '-f' options to ntfsresize or
        # the proceed question will be presented to you.
        argv = ["-ff", "-s", "%dM" % (self.targetSize,), self.device]
        return argv


register_device_format(NTFS)


# if this isn't going to be mountable it might as well not be here
class NFS(FS):
    """ NFS filesystem. """
    _type = "nfs"
    _modules = ["nfs"]

    def _deviceCheck(self, devspec):
        if devspec is not None and ":" not in devspec:
            raise ValueError("device must be of the form <host>:<path>")

    @property
    def mountable(self):
        return False

    def _setDevice(self, devspec):
        self._deviceCheck(devspec)
        self._device = devspec

    def _getDevice(self):
        return self._device

    device = property(lambda f: f._getDevice(),
                      lambda f,d: f._setDevice(d),
                      doc="Full path the device this format occupies")
 
register_device_format(NFS)


class NFSv4(NFS):
    """ NFSv4 filesystem. """
    _type = "nfs4"
    _modules = ["nfs4"]

register_device_format(NFSv4)


class Iso9660FS(FS):
    """ ISO9660 filesystem. """
    _type = "iso9660"
    _formattable = False
    _supported = True
    _resizable = False
    _bootable = False
    _linuxNative = False
    _dump = False
    _check = False
    _migratable = False
    _defaultMountOptions = ["ro"]

    def writeKS(self, f):
        return

register_device_format(Iso9660FS)


class NoDevFS(FS):
    """ nodev filesystem base class """
    _type = "nodev"

    def __init__(self, *args, **kwargs):
        FS.__init__(self, *args, **kwargs)
        self.exists = True
        self.device = self.type

    def _setDevice(self, devspec):
        self._device = devspec

    def _getExistingSize(self):
        pass

    def writeKS(self, f):
        return

register_device_format(NoDevFS)


class DevPtsFS(NoDevFS):
    """ devpts filesystem. """
    _type = "devpts"
    _defaultMountOptions = ["gid=5", "mode=620"]

register_device_format(DevPtsFS)


# these don't really need to be here
class ProcFS(NoDevFS):
    _type = "proc"

register_device_format(ProcFS)


class SysFS(NoDevFS):
    _type = "sysfs"

register_device_format(SysFS)


class TmpFS(NoDevFS):
    _type = "tmpfs"

register_device_format(TmpFS)


class BindFS(FS):
    _type = "bind"

    @property
    def mountable(self):
        return True

    def _getExistingSize(self):
        pass

    def writeKS(self, f):
        return

register_device_format(BindFS)