summaryrefslogtreecommitdiffstats
path: root/partitioning.py
blob: 49b1bc50cf4e4be3f0cfd6eaca49a76d88a0cc06 (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
#
# partitioning.py: partitioning and other disk management
#
# Matt Wilson <msw@redhat.com>
#
# Copyright 2001 Red Hat, Inc.
#
# This software may be freely redistributed under the terms of the GNU
# library public license.
#
# You should have received a copy of the GNU Library Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

if __name__ == "__main__":
    import sys
    sys.path.append ("isys")
    sys.path.append ("balkan")

import isys
import parted
import math
import raid
import fsset
import os
import iutil
from translate import _
from log import log
from constants import *
from flags import flags

# different types of partition requests
# REQUEST_PREEXIST is a placeholder for a pre-existing partition on the system
# REQUEST_NEW is a request for a partition which will be automatically
#              created based on various constraints on size, drive, etc
# REQUEST_RAID is a request for a raid device
# REQUEST_PROTECTED is a preexisting partition which can't change
#              (harddrive install, harddrive with the isos on it)
#
REQUEST_PREEXIST = 1
REQUEST_NEW = 2
REQUEST_RAID = 4
REQUEST_PROTECTED = 8

fsTypes = {}

fs_type = parted.file_system_type_get_next ()
while fs_type:
    fsTypes[fs_type.name] = fs_type
    fs_type = parted.file_system_type_get_next (fs_type)

class PartitioningError:
    def __init__ (self, value):
        self.value = value

    def __str__ (self):
        return self.value

class PartitioningWarning:
    def __init__ (self, value):
        self.value = value

    def __str__ (self):
        return self.value

def get_flags (part):
    string=""
    if not part.is_active ():
        return string
    first=1
    flag = parted.partition_flag_next (0)
    while flag:
        if part.get_flag (flag):
            string = string + parted.partition_flag_get_name (flag)
            if first:
                first = 0
            else:
                string = string + ", "
        flag = parted.partition_flag_next (flag)
    return string

def start_sector_to_cyl(device, sector):
    return int(math.floor((float(sector)
                           / (device.heads * device.sectors)) + 1))

def end_sector_to_cyl(device, sector):
    return int(math.ceil(float((sector + 1))
                         / (device.heads * device.sectors)))

def start_cyl_to_sector(device, cyl):
    return long((cyl - 1) * (device.heads * device.sectors))

def end_cyl_to_sector(device, cyl):
    return long(((cyl) * (device.heads * device.sectors)) - 1)

def getPartSize(partition):
    return partition.geom.length 

def getPartSizeMB(partition):
    return (partition.geom.length * partition.geom.disk.dev.sector_size
            / 1024.0 / 1024.0)

def getDeviceSizeMB(dev):
    return (float(dev.heads * dev.cylinders * dev.sectors) / (1024 * 1024)
            * dev.sector_size)

def get_partition_by_name(disks, partname):
    for diskname in disks.keys():
        disk = disks[diskname]
        part = disk.next_partition()
        while part:
            if get_partition_name(part) == partname:
               return part

            part = disk.next_partition(part)

    return None

def get_partition_name(partition):
    if (partition.geom.disk.dev.type == parted.DEVICE_DAC960
        or partition.geom.disk.dev.type == parted.DEVICE_CPQARRAY):
        return "%sp%d" % (partition.geom.disk.dev.path[5:],
                          partition.num)
    return "%s%d" % (partition.geom.disk.dev.path[5:],
                     partition.num)

def get_partition_file_system_type(part):
    if part.fs_type == None:
        return None
    if part.fs_type.name == "linux-swap":
        ptype = fsset.fileSystemTypeGet("swap")
    elif part.fs_type.name == "FAT":
        ptype = fsset.fileSystemTypeGet("vfat")
    else:
        try:
            ptype = fsset.fileSystemTypeGet(part.fs_type.name)
        except:
            ptype = fsset.fileSystemTypeGet("foreign")

    return ptype

def set_partition_file_system_type(part, fstype):
    if fstype == None:
        return
    try:
        part.set_system(fstype.getPartedFileSystemType())
        for flag in fstype.getPartedPartitionFlags():
            if not part.is_flag_available(flag):
                raise PartitioningError, ("requested FileSystemType needs "
                                          "a flag that is not available.")
            part.set_flag(flag, 1)
    except:
        print "Failed to set partition type to ",fstype.getName()
        pass

def get_partition_drive(partition):
    return "%s" %(partition.geom.disk.dev.path[5:])

def filter_partitions(disk, func):
    rc = []
    part = disk.next_partition ()
    while part:
        if func(part):
            rc.append(part)
        part = disk.next_partition (part)

    return rc

def get_logical_partitions(disk):
    func = lambda part: (part.is_active()
                         and part.type & parted.PARTITION_LOGICAL)
    return filter_partitions(disk, func)

def get_primary_partitions(disk):
    func = lambda part: part.type == parted.PARTITION_PRIMARY
    return filter_partitions(disk, func)

# returns a list of partitions which can make up RAID devices
def get_raid_partitions(disk):
    func = lambda part: (part.is_active()
                         and part.get_flag(parted.PARTITION_RAID) == 1)
    return filter_partitions(disk, func)

# returns a list of the actual raid device requests
def get_raid_devices(requests):
    raidRequests = []
    for request in requests:
        if request.type == REQUEST_RAID:
            raidRequests.append(request)
            
    return raidRequests


# returns a list of tuples of raid partitions which can be used or are used
# with whether they're used (0 if not, 1 if so)   eg (part, size, used)
def get_available_raid_partitions(diskset, requests, request):
    rc = []
    drives = diskset.disks.keys()
    raiddevs = get_raid_devices(requests.requests)
    drives.sort()
    for drive in drives:
        disk = diskset.disks[drive]
        for part in get_raid_partitions(disk):
            partname = get_partition_name(part)
            used = 0
            for raid in raiddevs:
                if raid.raidmembers:
                    for raidmem in raid.raidmembers:
                        if partname == requests.getRequestByID(raidmem).device:
                            if raid.device == request.device:
                                used = 2
                            else:
                                used = 1
                            break
                if used:
                    break

            if not used:
                rc.append((partname, getPartSizeMB(part), 0))
            elif used == 2:
                rc.append((partname, getPartSizeMB(part), 1))
    return rc

# set of functions to determine if the given level is RAIDX or X
def isRaid5(raidlevel):
    if raidlevel == "RAID5":
        return 1
    elif raidlevel == 5:
        return 1
    return 0

def isRaid1(raidlevel):
    if raidlevel == "RAID1":
        return 1
    elif raidlevel == 1:
        return 1
    return 0

def isRaid0(raidlevel):
    if raidlevel == "RAID0":
        return 1
    elif raidlevel == 0:
        return 1
    return 0


# return minimum numer of raid members required for a raid level
def get_raid_min_members(raidlevel):
    if isRaid0(raidlevel):
        return 2
    elif isRaid1(raidlevel):
        return 2
    elif isRaid5(raidlevel):
        return 3
    else:
        raise ValueError, "invalid raidlevel in get_raid_min_members"

# return max num of spares available for raidlevel and total num of members
def get_raid_max_spares(raidlevel, nummembers):
    if isRaid0(raidlevel):
        return 0
    elif isRaid1(raidlevel) or isRaid5(raidlevel):
        return max(0, nummembers - get_raid_min_members(raidlevel))
    else:
        raise ValueError, "invalid raidlevel in get_raid_max_spares"

def get_raid_device_size(raidrequest, partitions, diskset):
    if not raidrequest.raidmembers or not raidrequest.raidlevel:
        return 0
    
    raidlevel = raidrequest.raidlevel
    nummembers = len(raidrequest.raidmembers) - raidrequest.raidspares
    smallest = None
    sum = 0
    for member in raidrequest.raidmembers:
        req = partitions.getRequestByID(member)
        device = req.device
        part = get_partition_by_name(diskset.disks, device)
        partsize =  part.geom.length * part.geom.disk.dev.sector_size

        if isRaid0(raidlevel):
            sum = sum + partsize
        else:
            if not smallest:
                smallest = partsize
            elif partsize < smallest:
                smallest = partsize

    if isRaid0(raidlevel):
        return sum
    elif isRaid1(raidlevel):
        return smallest
    elif isRaid5(raidlevel):
        return (nummembers-1) * smallest
    else:
        raise ValueError, "Invalid raidlevel in get_raid_device_size()"

# sanityCheckMountPoint
def sanityCheckMountPoint(mntpt, fstype, reqtype):
    if mntpt:
        passed = 1
        if not mntpt:
            passed = 0
        else:
            if mntpt[0] != '/' or (len(mntpt) > 1 and mntpt[-1:] == '/'):
                passed = 0
                
        if not passed:
            return _("The mount point is invalid.  Mount points must start "
                     "with '/' and cannot end with '/', and must contain "
                     "printable characters.")
        else:
            return None
    else:
        if fstype and fstype.isMountable() and reqtype == REQUEST_NEW:
            return _("Please specify a mount point for this partition.")
        else:
            # its an existing partition so don't force a mount point
            return None

def isMountPointInUse(reqpartitions, newrequest):
    mntpt = newrequest.mountpoint
    if not mntpt:
        return None
    
    if reqpartitions and reqpartitions.requests:
        for request in reqpartitions.requests:
            if request.mountpoint == mntpt:
                used = 0
                if (not newrequest.device
                    or request.device != newrequest.device):
                        used = 1                

                if used:
                    return _("The mount point %s is already in use, please "
                             "choose a different mount point." %(mntpt))
    return None

# figure out whether we should format by default
def isFormatOnByDefault(request):
    deflist = ['/home', '/usr/local/', '/opt', '/var/www']

    # check first to see if its a Linux filesystem or not
    if not request.fstype:
        return 0

    if not request.fstype.isLinuxNativeFS():
        return 0

    if request.fstype.isMountable():
        if request.mountpoint and request.mountpoint in deflist:
            return 0
        else:
            return 1
    else:
        if request.fstype.getName() == "swap":
            return 1

    # be safe for anything else and default to off
    return 0

def doMountPointLinuxFSChecks(newrequest):
    mustbeonroot = ['/bin','/dev','/sbin','/etc','/lib','/root','/mnt']
    mustbeonlinuxfs = ['/', '/boot', '/var', '/tmp', '/usr', '/home']

    if not newrequest.mountpoint:
        return None

    if newrequest.fstype == None:
        return None

    if newrequest.fstype.isMountable():    
        if newrequest.mountpoint in mustbeonroot:
            return _("This mount point is invalid.  This directory must "
                     "be on the / filesystem.")
        
    if not newrequest.fstype.isLinuxNativeFS():
        if newrequest.mountpoint in mustbeonlinuxfs:
            return _("This mount point must be on a linux filesystem.")

    return None
    
def doPartitionSizeCheck(newrequest):
    if not newrequest.fstype:
        return None

    # XXX need to figure out the size for partitions specified by cyl range
    if newrequest.size and newrequest.size > newrequest.fstype.getMaxSize():
        return (_("The size of the %s partition (size = %s MB) "
                  "exceeds the maximum size of %s MB.")
                % (newrequest.fstype.getName(), newrequest.size,
                   newrequest.fstype.getMaxSize()))

    if (newrequest.size and newrequest.maxSize
        and (newrequest.size > newrequest.maxSize)):
        return (_("The size of the requested partition (size = %s MB) "
                 "exceeds the maximum size of %s MB.")
                % (newrequest.size, newrequest.maxSize))

    if newrequest.size and newrequest.size < 0:
        return _("The size of the requested partition is "
                 "negative! (size = %s MB)") % (newrequest.size)

    if newrequest.start and newrequest.start < 1:
        return _("Partitions can't start below the first cylinder.")

    if newrequest.end and newrequest.end < 1:
        return _("Partitions can't end on a negative cylinder.")

    return None


# returns error string if something not right about request
def sanityCheckPartitionRequest(reqpartitions, newrequest):
    # see if mount point is valid if its a new partition request
    mntpt = newrequest.mountpoint
    fstype = newrequest.fstype
    reqtype = newrequest.type

    rc = doPartitionSizeCheck(newrequest)
    if rc:
        return rc

    rc = sanityCheckMountPoint(mntpt, fstype, reqtype)
    if rc:
        return rc

    rc = isMountPointInUse(reqpartitions, newrequest)
    if rc:
        return rc
    
    rc = doMountPointLinuxFSChecks(newrequest)
    if rc:
        return rc
    
    return None

# return error string is something not right about raid request
def sanityCheckRaidRequest(reqpartitions, newraid):
    if not newraid.raidmembers or not newraid.raidlevel:
        return _("No members in RAID request, or not RAID level specified.")

    # XXX fix this sanity case
##     for member in newraid.raidmembers:
##         part = member.partition
##         if part.get_flag(parted.PARTITION_RAID) != 1:
##             return _("Some members of RAID request are not RAID partitions.")

    rc = sanityCheckPartitionRequest(reqpartitions, newraid)
    if rc:
        return rc

    # XXX fix this code to look to see if there is a bootable partition
    bootreq = reqpartitions.getBootableRequest()
    if not bootreq and newraid.mountpoint:
        if ((newraid.mountpoint == "/boot" or newraid.mountpoint == "/")
            and not isRaid1(newraid.raidlevel)):
            return _("Bootable partitions can only be on RAID1 devices.")

    minmembers = get_raid_min_members(newraid.raidlevel)
    if len(newraid.raidmembers) < minmembers:
        return _("A RAID device of type %s "
                 "requires at least %s members.") % (newraid.raidlevel,
                                                     minmembers)

    if newraid.raidspares:
        if (len(newraid.raidmembers) - newraid.raidspares) < minmembers:
            return _("This RAID device can have a maximum of %s spares. "
                     "To have more spares you will need to add members to "
                     "the RAID device.") % (len(newraid.raidmembers)
                                            - minmembers )
    return None


# add delete specs to requests for all logical partitions in part
def deleteAllLogicalPartitions(part, requests):
    for partition in get_logical_partitions(part.geom.disk):
        request = requests.getRequestByDeviceName(get_partition_name(partition))
        requests.removeRequest(request)
        if request.type == REQUEST_PREEXIST:
            drive = get_partition_drive(partition)
            delete = DeleteSpec(drive, partition.geom.start, partition.geom.end)
            requests.addDelete(delete)
            

class DeleteSpec:
    def __init__(self, drive, start, end):
        self.drive = drive
        self.start = start
        self.end = end

    def __str__(self):
        return "drive: %s  start: %s  end: %s" %(self.drive, self.start, self.end)


class PartitionSpec:
    def __init__(self, fstype, requesttype = REQUEST_NEW,
                 size = None, grow = 0, maxSize = None,
                 mountpoint = None, origfstype = None,
                 start = None, end = None, partnum = None,
                 drive = None, primary = None,
                 format = None, options = None, 
                 constraint = None, migrate = None,
                 raidmembers = None, raidlevel = None, 
                 raidspares = None, badblocks = None):
        #
        # requesttype: REQUEST_PREEXIST or REQUEST_NEW or REQUEST_RAID
        #
        # XXX: unenforced requirements for a partition spec
        # must have (size) || (start && end)
        #           fs_type, mountpoint
        #           if partnum, require drive
        #
        # Some notes:
        #   format  - if is 1, format.
        #   migrate - if is 1, convert from origfstype to fstype.
        #
        self.type = requesttype
        self.fstype = fstype
        self.origfstype = origfstype
        self.size = size
        self.grow = grow
        self.maxSize = maxSize
        self.mountpoint = mountpoint
        self.start = start
        self.end = end
        self.partnum = partnum
        self.drive = drive
        self.primary = primary
        self.format = format
        self.badblocks = badblocks
        self.migrate = migrate
        self.options = options
        self.constraint = constraint
        self.partition = None
        self.requestSize = size
        # XXX these are PartedPartitionDevice, should be requests        
        self.raidmembers = raidmembers
        self.raidlevel = raidlevel
        self.raidspares = raidspares
        
        # device is what we currently think the device is
        # realDevice is used by partitions which are pre-existing
        self.device = None
        self.realDevice = None

        # there has to be a way to go from device -> drive... but for now
        self.currentDrive = None

        # unique id for each request
        self.uniqueID = None

        # ignore booting constraints for this request
        self.ignoreBootConstraints = 0

    def __str__(self):
        if self.fstype:
            fsname = self.fstype.getName()
        else:
            fsname = "None"
        raidmem = []
        if self.raidmembers:
            for i in self.raidmembers:
                raidmem.append(i)
                
        return "mountpoint: %s   type: %s   uniqueID:%s\n" %(self.mountpoint, fsname, self.uniqueID) +\
               "  size: %sM   requestSize: %sM  grow: %s   max: %s\n" %(self.size, self.requestSize, self.grow, self.maxSize) +\
               "  start: %s   end: %s   partnum: %s\n" %(self.start, self.end, self.partnum) +\
               "  drive: %s   primary: %s  \n" %(self.drive, self.primary) +\
               "  format: %s, options: %s" %(self.format, self.options) +\
               "  device: %s, currentDrive: %s\n" %(self.device, self.currentDrive)+\
               "  raidlevel: %s" % (self.raidlevel)+\
               "  raidspares: %s" % (self.raidspares)+\
               "  raidmembers: %s" % (raidmem)

    # turn a partition request into a fsset entry
    def toEntry(self, partitions):
        if self.type == REQUEST_RAID:
            raidmems = []
            for member in self.raidmembers:
                raidmems.append(partitions.getRequestByID(member).device)
            device = fsset.RAIDDevice(int(self.raidlevel[-1:]),
                                      raidmems,
                                      spares = self.raidspares)
        else:
            device = fsset.PartitionDevice(self.device)

        # pin down our partitions so that we can reread the table
        device.solidify()
        
        if self.fstype.getName() == "swap":
            mountpoint = "swap"
        else:
            mountpoint = self.mountpoint

        entry = fsset.FileSystemSetEntry(device, mountpoint, self.fstype,
                                         origfsystem=self.origfstype)
        if self.format:
            entry.setFormat(self.format)

        if self.migrate:
            entry.setMigrate(self.migrate)

        if self.badblocks:
            entry.setBadblocks(self.badblocks)
            
        return entry

class Partitions:
    def __init__ (self, diskset = None):
        # requests for partitions including preexisting partitions
        # a list of PartitionSpec objects
        self.requests = []

        # preexisting partitions which should be deleted
        # a list of DeleteSpec objects
        self.deletes = []

        # auto partitioning requests
        # a list of PartitionSpec objects
        # these are set by the installclass and then folded into self.requests
        self.autoPartitionRequests = []

        # CLEARPART_TYPE_LINUX, CLEARPART_TYPE_ALL, CLEARPART_TYPE_NONE
        # used by installclasses to say which partitions to clear
        self.autoClearPartType = None

        # drives to clear partitions on (following self.autoClearPartType)
        # note that None clears ALL drives 
        self.autoClearPartDrives = None

        # internal counter... if you use it as an ID, increment it to avoid
        # problems later on
        self.nextUniqueID = 1

        # partition method
        self.useAutopartitioning = 1
        self.useFdisk = 0

        if diskset:
            self.setFromDisk(diskset)


    # clear out the delete list and initialize all partitions which
    # currently exist on the disk
    def setFromDisk(self, diskset):
        self.deletes = []
        self.requests = []
        diskset.refreshDevices()
        drives = diskset.disks.keys()
        drives.sort()
        for drive in drives:
            disk = diskset.disks[drive]
            part = disk.next_partition()
            while part:
                if part.type & parted.PARTITION_METADATA:
                    part = disk.next_partition(part)
                    continue

                format = 0
                if part.type & parted.PARTITION_FREESPACE:
                    ptype = None
                elif part.type & parted.PARTITION_EXTENDED:
                    ptype = None
                elif part.get_flag(parted.PARTITION_RAID) == 1:
                    ptype = None
                elif part.fs_type:
                    ptype = get_partition_file_system_type(part)
                    if part.fs_type.name == "linux-swap":
                        # XXX this is a hack
                        format = 1
                else:
                    ptype = fsset.fileSystemTypeGet("foreign")
                    
                start = part.geom.start
                end = part.geom.end
                size = getPartSizeMB(part)
                drive = get_partition_drive(part)
                
                spec = PartitionSpec(ptype, origfstype = ptype,
                                     requesttype = REQUEST_PREEXIST,
                                     start = start, end = end, size = size,
                                     drive = drive, format = format)
                spec.device = fsset.PartedPartitionDevice(part).getDevice()

                self.addRequest(spec)
                part = disk.next_partition(part)

    def addRequest (self, request):
#        print "adding %s" %(self.nextUniqueID)
        if not request.uniqueID:
            request.uniqueID = self.nextUniqueID
            self.nextUniqueID = self.nextUniqueID + 1
        self.requests.append(request)
        self.requests.sort()

    def addDelete (self, delete):
        self.deletes.append(delete)
        self.deletes.sort()

    def removeRequest (self, request):
        self.requests.remove(request)

    def getRequestByMountPoint(self, mount):
        for request in self.requests:
            if request.mountpoint == mount:
                return request
        return None

    def getRequestByDeviceName(self, device):
        for request in self.requests:
            if request.device == device:
                return request
        return None

    def getRequestByID(self, id):
        for request in self.requests:
            if request.uniqueID == id:
                return request
        return None

    def getRaidRequests(self):
        retval = []
        for request in self.requests:
            if request.type == REQUEST_RAID:
                retval.append(request)

        return retval

    def isRaidMember(self, request):
        raiddev = self.getRaidRequests()
        if not raiddev or not request.device:
            return 0
        for dev in raiddev:
            if not dev.raidmembers:
                continue
            for member in dev.raidmembers:
                if request.device == self.getRequestByID(member).device:
                    return 1
        return 0

    def getMigratableRequests(self):
        retval = []
        for request in self.requests:
            if request.type != REQUEST_PREEXIST:
                continue
            
            if request.origfstype:
                if request.origfstype.isMigratable():
                    retval.append(request)

        return retval
    
    # return name of boot mount point in current requests
    def getBootableRequest(self):
        bootreq = None
        
        if not bootreq and iutil.getArch() == "ia64":
            bootreq = self.getRequestByMountPoint("/boot/efi")
        if not bootreq:
            bootreq = self.getRequestByMountPoint("/boot")
        if not bootreq:
            bootreq = self.getRequestByMountPoint("/")
            
        return bootreq

    def sortRequests(self):
        n = 0
        while n < len(self.requests):
            for request in self.requests:
                if request.size < self.requests[n].size:
                    tmp = self.requests[n]
                    index = self.requests.index(request)
                    self.requests[n] = request
                    self.requests[index] = tmp
            n = n + 1
        tmp = self.getBootableRequest()
        if tmp:
            index = self.requests.index(tmp)
            self.requests[index] = self.requests[0]
            self.requests[0] = tmp

    def copy (self):
        new = Partitions()
        for request in self.requests:
            new.addRequest(request)
        for delete in self.deletes:
            new.addDelete(delete)
        new.autoPartitionRequests = self.autoPartitionRequests
        new.autoClearPartType = self.autoClearPartType
        new.autoClearPartDrives = self.autoClearPartDrives
        new.nextUniqueID = self.nextUniqueID
        new.useAutopartitioning = self.useAutopartitioning
        new.useFdisk = self.useFdisk
        
        return new
           

class DiskSet:
    skippedDisks = []
    def __init__ (self):
        self.disks = {}

    def getLabels(self):
        labels = {}
        
        drives = self.disks.keys()
        drives.sort()

        for drive in drives:
            disk = self.disks[drive]
            part = disk.next_partition ()
            while part:
                if part.fs_type and (part.fs_type.name == "ext2"
                                     or part.fs_type.name == "ext3"):
                    node = get_partition_name(part)
                    label = isys.readExt2Label(node)
                    if label:
                        labels[node] = label
                part = disk.next_partition(part)

        return labels

    def findExistingRootPartitions(self, intf):
        rootparts = []

        drives = self.disks.keys()
        drives.sort()
        
        mdList = raid.startAllRaid(drives)

        for dev in mdList:
            # XXX multifsify
            if not fsset.isValidExt2 (dev):
                continue

            try:
                isys.mount(dev, '/mnt/sysimage', readOnly = 1)
            except SystemError, (errno, msg):
                intf.messageWindow(_("Error"),
                                   _("Error mounting filesystem "
                                     "on %s: %s") % (dev, msg))
                continue
            if os.access ('/mnt/sysimage/etc/fstab', os.R_OK):
                rootparts.append ((dev, "ext2"))
            isys.umount('/mnt/sysimage')

        raid.stopAllRaid(mdList)
        
        drives = self.disks.keys()
        drives.sort()

        for drive in drives:
            disk = self.disks[drive]
            part = disk.next_partition ()
            while part:
                if (part.is_active()
                    and (part.get_flag(parted.PARTITION_RAID)
                         or part.get_flag(parted.PARTITION_LVM))):
                    # skip RAID and LVM partitions.
                    # XXX check for raid superblocks on non-autoraid partitions
                    #  (#32562)
                    pass
                elif part.fs_type and (part.fs_type.name == "ext2"
                                     or part.fs_type.name == "ext3"
                                     or part.fs_type.name == "reiserfs"):
                    node = get_partition_name(part)
		    try:
			isys.mount(node, '/mnt/sysimage', part.fs_type.name)
		    except SystemError, (errno, msg):
			intf.messageWindow(_("Error"),
                                           _("Error mounting filesystem on "
                                             "%s: %s") % (node, msg))
                        part = disk.next_partition(part)
			continue
		    if os.access ('/mnt/sysimage/etc/fstab', os.R_OK):
			rootparts.append ((node, part.fs_type.name))
		    isys.umount('/mnt/sysimage')
                elif part.fs_type and (part.fs_type.name == "FAT"):
                    try:
                        isys.mount(node, '/mnt/sysimage', fstype = "vfat",
                                   readOnly = 1)
                    except:
			log("failed to mount vfat filesystem on %s\n" 
                            % dev)
                        part = disk.next_partition(part)
			continue
                        
		    if os.access('/mnt/sysimage/redhat.img', os.R_OK):
                        rootparts.append((node, "vfat"))

		    isys.umount('/mnt/sysimage')
                    
                part = disk.next_partition(part)
        return rootparts

    def driveList (self):
	drives = isys.hardDriveDict().keys()
	drives.sort (isys.compareDrives)
	return drives

    def drivesByName (self):
	return isys.hardDriveDict()

    def addPartition (self, device, type, spec):
        if not self.disks.has_key (device):
            raise PartitioningError, ("unknown device passed to "
                                      "addPartition: %s" % (device,))
        disk = self.disks[device]

        part = disk.next_partition ()
        status = 0
        while part:
            if (part.type == parted.PARTITION_FREESPACE
                and part.geom.length >= spec.size):
                newp = disk.partition_new (type, spec.fs_type,
                                           part.geom.start,
                                           part.geom.start + spec.size)
                constraint = disk.constraint_any ()
                try:
                    disk.add_partition (newp, constraint)
                    status = 1
                    break
                except parted.error, msg:
                    raise PartitioningError, msg
            part = disk.next_partition (part)
        if not status:
            raise PartitioningError, ("Not enough free space on %s to create "
                                      "new partition" % (device,))
        return newp
    
    def deleteAllPartitions (self):
        for disk in self.disks.values():
            disk.delete_all ()

    def savePartitions (self):
        for disk in self.disks.values():
            disk.write()
            del disk
        self.refreshDevices()

    def refreshDevices (self):
        self.disks = {}
        self.openDevices()

    def closeDevices (self):
        for disk in self.disks.keys():
            del self.disks[disk]

    def openDevices (self):
        if self.disks:
            return
        for drive in self.driveList ():
            if drive in DiskSet.skippedDisks:
                continue
            deviceFile = isys.makeDevInode(drive)
            if isys.driveIsRemovable(drive) and not flags.expert:
                DiskSet.skippedDisks.append(drive)
                continue
            try:
                dev = parted.PedDevice.get (deviceFile)
            except parted.error, msg:
                DiskSet.skippedDisks.append(drive)
                continue
            try:
                disk = parted.PedDisk.open(dev)
                self.disks[drive] = disk
            except parted.error, msg:
                DiskSet.skippedDisks.append(drive)

    def partitionTypes (self):
        rc = []
        drives = self.disks.keys()
        drives.sort

        for drive in drives:
            disk = self.disks[drive]
            part = disk.next_partition ()
            while part:
                if part.type in (parted.PARTITION_PRIMARY,
                                 parted.PARTITION_LOGICAL):
                    device = get_partition_name(part)
                    if part.fs_type:
                        ptype = part.fs_type.name
                    else:
                        ptype = None
                    rc.append (device, ptype)
                part = disk.next_partition (part)
      
        return rc

    def diskState (self):
        rc = ""
        for disk in self.disks.values():
            rc = rc + ("%s: %s length %ld, maximum "
                       "primary partitions: %d\n" %
                       (disk.dev.path,
                        disk.dev.model,
                        disk.dev.length,
                        disk.max_primary_partition_count))

            part = disk.next_partition()
            if part:
                rc = rc + ("Device    Type         Filesystem   Start      "
                           "End        Length        Flags\n")
                rc = rc + ("------    ----         ----------   -----      "
                           "---        ------        -----\n")
            while part:
                if not part.type & parted.PARTITION_METADATA:
                    device = ""
                    fs_type_name = ""
                    if part.num > 0:
                        device = get_partition_name(part)
                    if part.fs_type:
                        fs_type_name = part.fs_type.name
                    flags = get_flags (part)
                    rc = rc + ("%-9s %-12s %-12s %-10ld %-10ld %-10ld %7s\n"
                               % (device, part.type_name, fs_type_name,
                              part.geom.start, part.geom.end, part.geom.length,
                              flags))
                part = disk.next_partition(part)
        return rc

def partitionObjectsInitialize(diskset, partitions, dir):
    if dir == DISPATCH_BACK:
        diskset.closeDevices()
        return
    
    # read in drive info
    diskset.refreshDevices()
    partitions.setFromDisk(diskset)

def partitionMethodSetup(partitions, dispatch):

    # turn on/off step based on 3 paths:
    #  - use fdisk, then set mount points
    #  - use autopartitioning, then set mount points
    #  - use interactive partitioning tool, continue

    dispatch.skipStep("autopartition",
                      skip = not partitions.useAutopartitioning)
    dispatch.skipStep("autopartitionexecute",
                      skip = not partitions.useAutopartitioning)
    dispatch.skipStep("fdisk", skip = not partitions.useFdisk)

    protected = dispatch.method.protectedPartitions()
    if protected:
        for device in protected:
            request = partitions.getRequestByDeviceName(device)
            request.type = REQUEST_PROTECTED

    
# shorthand mainly for installclasses
#
# make a list of tuples of the form:
#    (mntpt, fstype, minsize, maxsize, grow, format)
#
# mntpt = None for non-mountable, otherwise is mount point
# fstype = None to use default, otherwise a string
# minsize = smallest size
# maxsize = max size, or None means no max
# grow = 0 or 1, should partition be grown
# format = 0 or 1, whether to format
#
def autoCreatePartitionRequests(autoreq):
    requests = []
    for (mntpt, fstype, minsize, maxsize, grow, format) in autoreq:
        if fstype:
            ptype = fsset.fileSystemTypeGet(fstype)
        else:
            ptype = fsset.fileSystemTypeGetDefault()
            
        newrequest = PartitionSpec(ptype,
                                   mountpoint = mntpt,
                                   size = minsize,
                                   maxSize = maxsize,
                                   grow = grow,
                                   requesttype = REQUEST_NEW,
                                   format = format)
        
        requests.append(newrequest)

    return requests

# returns shorthand (see above) request for the "boot" dir
# depends on arch 
def getAutopartitionBoot():
    if iutil.getArch() == "ia64":
        return ("/boot/efi", "vfat", 100, None, 0, 1)
    else:
        return ("/boot", None, 50, None, 0, 1)
        

def confirmDeleteRequest(intf, request):
    if request.device:
        if request.type == REQUEST_RAID:
            errmsg = _("You are about to delete a RAID device.\n\n"
                       "Are you sure?")
        else:
            errmsg = _("You are about to delete the /dev/%s partition.\n\n"
                       "Are you sure?" % request.device)
            
    else:
        errmsg = _("Are you sure you want to delete this partition?")

    rc = intf.messageWindow(_("Confirm Delete"), errmsg, type="yesno")
    return rc

def confirmResetPartitionState(intf):
    rc = intf.messageWindow(_("Confirm Reset"),
                            _("Are you sure you want to reset the "
                              "partition table to its original state?"),
                            type="yesno")
    return rc

# does this partition contain partitions we can't delete?
def containsImmutablePart(part, requestlist):
    if not part:
        return None
    
    if not part.type & parted.PARTITION_EXTENDED:
        return None

    disk = part.geom.disk
    while part:
        if not part.is_active():
            part = disk.next_partition(part)
            continue

        device = get_partition_name(part)
        request = requestlist.getRequestByDeviceName(device)

        if request:
            if request.type == REQUEST_PROTECTED:
                return _("the partition in use by the installer.")

            if requestlist.isRaidMember(request):
                return _("a partition which is a member of a RAID array.")
        
        part = disk.next_partition(part)
#
# handle deleting a partition - pass in the list of requests and the
# partition to be deleted
#
def doDeletePartitionByRequest(intf, requestlist, partition):
    if partition == None:
        intf.messageWindow(_("Unable To Remove"),
                           _("You must first select a partition to remove."))
        return 0
    elif type(partition) == type("RAID"):
        device = partition
    elif partition.type & parted.PARTITION_FREESPACE:
        intf.messageWindow(_("Unable To Remove"),
                           _("You cannot remove free space."))
        return 0
    else:
        device = get_partition_name(partition)

    ret = containsImmutablePart(partition, requestlist)
    if ret:
        intf.messageWindow(_("Unable To Remove"),
                           _("You cannot remove this "
                             "partition, as it is an extended partition "
                             "which contains %s") %(ret))
        return 0
        

    # see if device is in our partition requests, remove
    request = requestlist.getRequestByDeviceName(device)
    if request:
        if request.type == REQUEST_PROTECTED:
            intf.messageWindow(_("Unable To Remove"),
                               _("You cannot remove this "
                                 "partition, as it is holding the data for "
                                 "the hard drive install."))
            return 0

        if requestlist.isRaidMember(request):
            intf.messageWindow(_("Unable To Remove"),
                               _("You cannot remove this "
                                 "partition, as it is part of a RAID device."))
            return 0

        if confirmDeleteRequest(intf, request):
            requestlist.removeRequest(request)
        else:
            return 0

        if request.type == REQUEST_PREEXIST:
            # get the drive
            drive = get_partition_drive(partition)

            if partition.type & parted.PARTITION_EXTENDED:
                deleteAllLogicalPartitions(partition, requestlist)

            delete = DeleteSpec(drive, partition.geom.start,
                                partition.geom.end)
            requestlist.addDelete(delete)
    else: # shouldn't happen
        raise ValueError, "Deleting a non-existent partition"

    del partition
    return 1


def doEditPartitionByRequest(intf, requestlist, part):
    if part == None:
        intf.messageWindow(_("Unable To Edit"),
                           _("You must select a partition to edit"))

        return (None, None)
    elif type(part) == type("RAID"):
        request = requestlist.getRequestByDeviceName(part)

        return ("RAID", request)
    elif part.type & parted.PARTITION_FREESPACE:
        request = PartitionSpec(fsset.fileSystemTypeGetDefault(), REQUEST_NEW,
                                start = start_sector_to_cyl(part.geom.disk.dev,
                                                            part.geom.start),
                                end = end_sector_to_cyl(part.geom.disk.dev,
                                                        part.geom.end),
                                drive = [ get_partition_drive(part) ])

        return ("PARTITION", request)
    elif part.type & parted.PARTITION_EXTENDED:
        return (None, None)

    ret = containsImmutablePart(part, requestlist)
    if ret:
        intf.messageWindow(_("Unable To Edit"),
                           _("You cannot edit this "
                             "partition, as it is an extended partition "
                             "which contains %s") %(ret))
        return 0

    request = requestlist.getRequestByDeviceName(get_partition_name(part))
    if request:
        if request.type == REQUEST_PROTECTED:
            intf.messageWindow(_("Unable to Edit"),
                               _("You cannot edit this "
                      "partition, as it is in use by the installer."))
            return (None, None)
        if requestlist.isRaidMember(request):
            intf.messageWindow( _("Unable to Edit"),
                               _("You cannot edit this partition "
                                 "as it is part of a RAID device"))
            return (None, None)

        return ("PARTITION", request)
    else: # shouldn't ever happen
        raise ValueError, ("Trying to edit non-existent partition %s"
                           % (get_partition_name(part)))
    
    
def partitioningComplete(dispatch, bl, fsset, diskSet, partitions):
    fsset.reset()
    for request in partitions.requests:
        # XXX improve sanity checking
        if (not request.fstype or (request.fstype.isMountable()
                                   and not request.mountpoint)):
            continue
        entry = request.toEntry(partitions)
        fsset.add (entry)