-
Notifications
You must be signed in to change notification settings - Fork 84
/
partitioning.py
2258 lines (1892 loc) · 92.1 KB
/
partitioning.py
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
# partitioning.py
# Disk partitioning functions.
#
# Copyright (C) 2009, 2010, 2011, 2012, 2013 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>
#
from operator import gt, lt
from decimal import Decimal
import parted
from pykickstart.constants import AUTOPART_TYPE_BTRFS, AUTOPART_TYPE_LVM, AUTOPART_TYPE_LVM_THINP, AUTOPART_TYPE_PLAIN
from .errors import DeviceError, NoDisksError, NotEnoughFreeSpaceError, PartitioningError
from .flags import flags
from .devices import PartitionDevice, LUKSDevice, devicePathToName
from .formats import getFormat
from .devicelibs.lvm import get_pool_padding
from .size import Size
from .i18n import _
import logging
log = logging.getLogger("blivet")
def _getCandidateDisks(storage):
""" Return a list of disks to be used for autopart/reqpart.
Disks must be partitioned and have a single free region large enough
for a default-sized (500MiB) partition. They must also be in
:attr:`StorageDiscoveryConfig.clearPartDisks` if it is non-empty.
:param storage: a Blivet instance
:type storage: :class:`~.Blivet`
:returns: a list of partitioned disks with at least 500MiB of free space
:rtype: list of :class:`~.devices.StorageDevice`
"""
disks = []
for disk in storage.partitioned:
if storage.config.clearPartDisks and \
(disk.name not in storage.config.clearPartDisks):
continue
part = disk.format.firstPartition
while part:
if not part.type & parted.PARTITION_FREESPACE:
part = part.nextPartition()
continue
if Size(part.getLength(unit="B")) > PartitionDevice.defaultSize:
disks.append(disk)
break
part = part.nextPartition()
return disks
def _scheduleImplicitPartitions(storage, disks, min_luks_entropy=0):
""" Schedule creation of a lvm/btrfs member partitions for autopart.
We create one such partition on each disk. They are not allocated until
later (in :func:`doPartitioning`).
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param disks: list of partitioned disks with free space
:type disks: list of :class:`~.devices.StorageDevice`
:param min_luks_entropy: minimum entropy in bits required for
luks format creation
:type min_luks_entropy: int
:returns: list of newly created (unallocated) partitions
:rtype: list of :class:`~.devices.PartitionDevice`
"""
# create a separate pv or btrfs partition for each disk with free space
devs = []
# only schedule the partitions if either lvm or btrfs autopart was chosen
if storage.autoPartType == AUTOPART_TYPE_PLAIN:
return devs
for disk in disks:
if storage.encryptedAutoPart:
fmt_type = "luks"
fmt_args = {"passphrase": storage.encryptionPassphrase,
"cipher": storage.encryptionCipher,
"escrow_cert": storage.autoPartEscrowCert,
"add_backup_passphrase": storage.autoPartAddBackupPassphrase,
"min_luks_entropy": min_luks_entropy}
else:
if storage.autoPartType in (AUTOPART_TYPE_LVM, AUTOPART_TYPE_LVM_THINP):
fmt_type = "lvmpv"
else:
fmt_type = "btrfs"
fmt_args = {}
part = storage.newPartition(fmt_type=fmt_type,
fmt_args=fmt_args,
grow=True,
parents=[disk])
storage.createDevice(part)
devs.append(part)
return devs
def _schedulePartitions(storage, disks, implicit_devices, min_luks_entropy=0, requests=None):
""" Schedule creation of autopart/reqpart partitions.
This only schedules the requests for actual partitions.
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param disks: list of partitioned disks with free space
:type disks: list of :class:`~.devices.StorageDevice`
:param min_luks_entropy: minimum entropy in bits required for
luks format creation
:type min_luks_entropy: int
:param requests: list of partitioning requests to operate on,
or `~.storage.autoPartitionRequests` by default
:type requests: list of :class:`~.partspec.PartSpec` instances
:returns: None
:rtype: None
"""
if not requests:
requests = storage.autoPartitionRequests
# basis for requests with requiredSpace is the sum of the sizes of the
# two largest free regions
all_free = (Size(reg.getLength(unit="B")) for reg in getFreeRegions(disks))
all_free = sorted(all_free, reverse=True)
if not all_free:
# this should never happen since we've already filtered the disks
# to those with at least 500MiB free
log.error("no free space on disks %s", [d.name for d in disks])
return
free = all_free[0]
if len(all_free) > 1:
free += all_free[1]
# The boot disk must be set at this point. See if any platform-specific
# stage1 device we might allocate already exists on the boot disk.
stage1_device = None
for device in storage.devices:
if storage.bootloader.stage1_disk not in device.disks:
continue
if storage.bootloader.is_valid_stage1_device(device, early=True):
stage1_device = device
break
#
# First pass is for partitions only. We'll do LVs later.
#
for request in requests:
if ((request.lv and storage.doAutoPart and
storage.autoPartType in (AUTOPART_TYPE_LVM,
AUTOPART_TYPE_LVM_THINP)) or
(request.btr and storage.autoPartType == AUTOPART_TYPE_BTRFS)):
continue
if request.requiredSpace and request.requiredSpace > free:
continue
elif request.fstype in ("prepboot", "efi", "macefi", "hfs+") and \
(storage.bootloader.skip_bootloader or stage1_device):
# there should never be a need for more than one of these
# partitions, so skip them.
log.info("skipping unneeded stage1 %s request", request.fstype)
log.debug("%s", request)
if request.fstype in ["efi", "macefi"] and stage1_device:
# Set the mountpoint for the existing EFI boot partition
stage1_device.format.mountpoint = "/boot/efi"
log.debug("%s", stage1_device)
continue
elif request.fstype == "biosboot":
is_gpt = (stage1_device and
getattr(stage1_device.format, "labelType", None) == "gpt")
has_bios_boot = (stage1_device and
any([p.format.type == "biosboot"
for p in storage.partitions
if p.disk == stage1_device]))
if (storage.bootloader.skip_bootloader or
not (stage1_device and stage1_device.isDisk and
is_gpt and not has_bios_boot)):
# there should never be a need for more than one of these
# partitions, so skip them.
log.info("skipping unneeded stage1 %s request", request.fstype)
log.debug("%s", request)
log.debug("%s", stage1_device)
continue
if request.size > all_free[0]:
# no big enough free space for the requested partition
raise NotEnoughFreeSpaceError(_("No big enough free space on disks for "
"automatic partitioning"))
if request.encrypted and storage.encryptedAutoPart:
fmt_type = "luks"
fmt_args = {"passphrase": storage.encryptionPassphrase,
"cipher": storage.encryptionCipher,
"escrow_cert": storage.autoPartEscrowCert,
"add_backup_passphrase": storage.autoPartAddBackupPassphrase,
"min_luks_entropy": min_luks_entropy}
else:
fmt_type = request.fstype
fmt_args = {}
dev = storage.newPartition(fmt_type=fmt_type,
fmt_args=fmt_args,
size=request.size,
grow=request.grow,
maxsize=request.maxSize,
mountpoint=request.mountpoint,
parents=disks,
weight=request.weight)
# schedule the device for creation
storage.createDevice(dev)
if request.encrypted and storage.encryptedAutoPart:
luks_fmt = getFormat(request.fstype,
device=dev.path,
mountpoint=request.mountpoint)
luks_dev = LUKSDevice("luks-%s" % dev.name,
fmt=luks_fmt,
size=dev.size,
parents=dev)
storage.createDevice(luks_dev)
if storage.autoPartType in (AUTOPART_TYPE_LVM, AUTOPART_TYPE_LVM_THINP,
AUTOPART_TYPE_BTRFS):
# doing LVM/BTRFS -- make sure the newly created partition fits in some
# free space together with one of the implicitly requested partitions
smallest_implicit = sorted(implicit_devices, key=lambda d: d.size)[0]
if (request.size + smallest_implicit.size) > all_free[0]:
# not enough space to allocate the smallest implicit partition
# and the request, make the implicit partition smaller with
# fixed size in order to make space for the request
new_size = all_free[0] - request.size
# subtract the size from the biggest free region and reorder the
# list
all_free[0] -= request.size
all_free.sort(reverse=True)
if new_size > Size(0):
smallest_implicit.size = new_size
else:
implicit_devices.remove(smallest_implicit)
storage.destroyDevice(smallest_implicit)
return implicit_devices
def _scheduleVolumes(storage, devs):
""" Schedule creation of autopart lvm/btrfs volumes.
Schedules encryption of member devices if requested, schedules creation
of the container (:class:`~.devices.LVMVolumeGroupDevice` or
:class:`~.devices.BTRFSVolumeDevice`) then schedules creation of the
autopart volume requests.
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param devs: list of member partitions
:type devs: list of :class:`~.devices.PartitionDevice`
:returns: None
:rtype: None
If an appropriate bootloader stage1 device exists on the boot drive, any
autopart request to create another one will be skipped/discarded.
"""
if not devs:
return
if storage.autoPartType in (AUTOPART_TYPE_LVM, AUTOPART_TYPE_LVM_THINP):
new_container = storage.newVG
new_volume = storage.newLV
format_name = "lvmpv"
else:
new_container = storage.newBTRFS
new_volume = storage.newBTRFS
format_name = "btrfs"
if storage.encryptedAutoPart:
pvs = []
for dev in devs:
pv = LUKSDevice("luks-%s" % dev.name,
fmt=getFormat(format_name, device=dev.path),
size=dev.size,
parents=dev)
pvs.append(pv)
storage.createDevice(pv)
else:
pvs = devs
# create a vg containing all of the autopart pvs
container = new_container(parents=pvs)
storage.createDevice(container)
#
# Convert storage.autoPartitionRequests into Device instances and
# schedule them for creation.
#
# Second pass, for LVs only.
pool = None
for request in storage.autoPartitionRequests:
btr = storage.autoPartType == AUTOPART_TYPE_BTRFS and request.btr
lv = (storage.autoPartType in (AUTOPART_TYPE_LVM,
AUTOPART_TYPE_LVM_THINP) and request.lv)
thinlv = (storage.autoPartType == AUTOPART_TYPE_LVM_THINP and
request.lv and request.thin)
if thinlv and pool is None:
# create a single thin pool in the vg
pool = storage.newLV(parents=[container], thin_pool=True, grow=True)
storage.createDevice(pool)
if not btr and not lv and not thinlv:
continue
# required space isn't relevant on btrfs
if (lv or thinlv) and \
request.requiredSpace and request.requiredSpace > container.size:
continue
if request.fstype is None:
if btr:
# btrfs volumes can only contain btrfs filesystems
request.fstype = "btrfs"
else:
request.fstype = storage.defaultFSType
kwargs = {"mountpoint": request.mountpoint,
"fmt_type": request.fstype}
if lv or thinlv:
if thinlv:
parents = [pool]
else:
parents = [container]
kwargs.update({"parents": parents,
"grow": request.grow,
"maxsize": request.maxSize,
"size": request.size,
"thin_volume": thinlv})
else:
kwargs.update({"parents": [container],
"size": request.size,
"subvol": True})
dev = new_volume(**kwargs)
# schedule the device for creation
storage.createDevice(dev)
def doReqPartition(storage, requests):
"""Perform automatic partitioning of just required platform-specific
partitions. This is incompatible with doAutoPartition.
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param requests: list of partitioning requests to operate on,
or `~.storage.autoPartitionRequests` by default
:type requests: list of :class:`~.partspec.PartSpec` instances
"""
if not storage.partitioned:
raise NoDisksError(_("No usable disks selected"))
disks = _getCandidateDisks(storage)
if disks == []:
raise NotEnoughFreeSpaceError(_("Not enough free space on disks for "
"automatic partitioning"))
_schedulePartitions(storage, disks, [], requests=requests)
def doAutoPartition(storage, data, min_luks_entropy=0):
""" Perform automatic partitioning.
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param data: kickstart data
:type data: :class:`pykickstart.BaseHandler`
:param min_luks_entropy: minimum entropy in bits required for
luks format creation
:type min_luks_entropy: int
:attr:`Blivet.doAutoPart` controls whether this method creates the
automatic partitioning layout. :attr:`Blivet.autoPartType` controls
which variant of autopart used. It uses one of the pykickstart
AUTOPART_TYPE_* constants. The set of eligible disks is defined in
:attr:`StorageDiscoveryConfig.clearPartDisks`.
.. note::
Clearing of partitions is handled separately, in
:meth:`~.Blivet.clearPartitions`.
"""
# pylint: disable=unused-argument
log.debug("doAutoPart: %s", storage.doAutoPart)
log.debug("encryptedAutoPart: %s", storage.encryptedAutoPart)
log.debug("autoPartType: %s", storage.autoPartType)
log.debug("clearPartType: %s", storage.config.clearPartType)
log.debug("clearPartDisks: %s", storage.config.clearPartDisks)
log.debug("autoPartitionRequests:\n%s", "".join([str(p) for p in storage.autoPartitionRequests]))
log.debug("storage.disks: %s", [d.name for d in storage.disks])
log.debug("storage.partitioned: %s", [d.name for d in storage.partitioned])
log.debug("all names: %s", [d.name for d in storage.devices])
log.debug("boot disk: %s", getattr(storage.bootDisk, "name", None))
disks = []
devs = []
if not storage.doAutoPart:
return
if not storage.partitioned:
raise NoDisksError(_("No usable disks selected"))
disks = _getCandidateDisks(storage)
devs = _scheduleImplicitPartitions(storage, disks, min_luks_entropy)
log.debug("candidate disks: %s", disks)
log.debug("devs: %s", devs)
if disks == []:
raise NotEnoughFreeSpaceError(_("Not enough free space on disks for "
"automatic partitioning"))
devs = _schedulePartitions(storage, disks, devs, min_luks_entropy=min_luks_entropy)
# run the autopart function to allocate and grow partitions
doPartitioning(storage)
_scheduleVolumes(storage, devs)
# grow LVs
growLVM(storage)
storage.setUpBootLoader()
# only newly added swaps should appear in the fstab
new_swaps = (dev for dev in storage.swaps if not dev.format.exists)
storage.setFstabSwaps(new_swaps)
def partitionCompare(part1, part2):
""" More specifically defined partitions come first.
< 1 => x < y
0 => x == y
> 1 => x > y
:param part1: the first partition
:type part1: :class:`devices.PartitionDevice`
:param part2: the other partition
:type part2: :class:`devices.PartitionDevice`
:return: see above
:rtype: int
"""
ret = 0
# start sector overrides all other sorting factors
part1_start = part1.req_start_sector
part2_start = part2.req_start_sector
if part1_start is not None and part2_start is None:
return -1
elif part1_start is None and part2_start is not None:
return 1
elif part1_start is not None and part2_start is not None:
return cmp(part1_start, part2_start)
if part1.req_base_weight:
ret -= part1.req_base_weight
if part2.req_base_weight:
ret += part2.req_base_weight
# more specific disk specs to the front of the list
# req_disks being empty is equivalent to it being an infinitely long list
if part1.req_disks and not part2.req_disks:
ret -= 500
elif not part1.req_disks and part2.req_disks:
ret += 500
else:
ret += cmp(len(part1.req_disks), len(part2.req_disks)) * 500
# primary-only to the front of the list
ret -= cmp(part1.req_primary, part2.req_primary) * 200
# fixed size requests to the front
ret += cmp(part1.req_grow, part2.req_grow) * 100
# larger requests go to the front of the list
ret -= cmp(part1.req_base_size, part2.req_base_size) * 50
# potentially larger growable requests go to the front
if part1.req_grow and part2.req_grow:
if not part1.req_max_size and part2.req_max_size:
ret -= 25
elif part1.req_max_size and not part2.req_max_size:
ret += 25
else:
ret -= cmp(part1.req_max_size, part2.req_max_size) * 25
# give a little bump based on mountpoint
if hasattr(part1.format, "mountpoint") and \
hasattr(part2.format, "mountpoint"):
ret += cmp(part1.format.mountpoint, part2.format.mountpoint) * 10
if ret > 0:
ret = 1
elif ret < 0:
ret = -1
return ret
def getNextPartitionType(disk, no_primary=None):
""" Return the type of partition to create next on a disk.
Return a parted partition type value representing the type of the
next partition we will create on this disk.
If there is only one free primary partition and we can create an
extended partition, we do that.
If there are free primary slots and an extended partition we will
recommend creating a primary partition. This can be overridden
with the keyword argument no_primary.
:param disk: the disk from which a partition may be allocated
:type disk: :class:`parted.Disk`
:keyword no_primary: refuse to return :const:`parted.PARTITION_NORMAL`
:returns: the chosen partition type
:rtype: a parted PARTITION_* constant
"""
part_type = None
extended = disk.getExtendedPartition()
supports_extended = disk.supportsFeature(parted.DISK_TYPE_EXTENDED)
logical_count = len(disk.getLogicalPartitions())
max_logicals = disk.getMaxLogicalPartitions()
primary_count = disk.primaryPartitionCount
if primary_count < disk.maxPrimaryPartitionCount:
if primary_count == disk.maxPrimaryPartitionCount - 1:
# can we make an extended partition? now's our chance.
if not extended and supports_extended:
part_type = parted.PARTITION_EXTENDED
elif not extended:
# extended partitions not supported. primary or nothing.
if not no_primary:
part_type = parted.PARTITION_NORMAL
else:
# there is an extended and a free primary
if not no_primary:
part_type = parted.PARTITION_NORMAL
elif logical_count < max_logicals:
# we have an extended with logical slots, so use one.
part_type = parted.PARTITION_LOGICAL
else:
# there are two or more primary slots left. use one unless we're
# not supposed to make primaries.
if not no_primary:
part_type = parted.PARTITION_NORMAL
elif extended and logical_count < max_logicals:
part_type = parted.PARTITION_LOGICAL
elif extended and logical_count < max_logicals:
part_type = parted.PARTITION_LOGICAL
return part_type
def getBestFreeSpaceRegion(disk, part_type, req_size, start=None,
boot=None, best_free=None, grow=None):
""" Return the "best" free region on the specified disk.
For non-boot partitions, we return the largest free region on the
disk. For boot partitions, we return the first region that is
large enough to hold the partition.
Partition type (parted's PARTITION_NORMAL, PARTITION_LOGICAL) is
taken into account when locating a suitable free region.
For locating the best region from among several disks, the keyword
argument best_free allows the specification of a current "best"
free region with which to compare the best from this disk. The
overall best region is returned.
:param disk: the disk
:type disk: :class:`parted.Disk`
:param part_type: the type of partition we want to allocate
:type part_type: one of parted's PARTITION_* constants
:param req_size: the requested size of the partition in MiB
:type req_size: :class:`~.size.Size`
:keyword start: requested start sector for the partition
:type start: int
:keyword boot: whether this will be a bootable partition
:type boot: bool
:keyword best_free: current best free region for this partition
:type best_free: :class:`parted.Geometry`
:keyword grow: indicates whether this is a growable request
:type grow: bool
"""
log.debug("getBestFreeSpaceRegion: disk=%s part_type=%d req_size=%s "
"boot=%s best=%s grow=%s start=%s",
disk.device.path, part_type, req_size, boot, best_free, grow,
start)
extended = disk.getExtendedPartition()
for free_geom in disk.getFreeSpaceRegions():
log.debug("checking %d-%d (%s)", free_geom.start, free_geom.end,
Size(free_geom.getLength(unit="B")))
if start is not None and not free_geom.containsSector(start):
log.debug("free region does not contain requested start sector")
continue
if extended:
in_extended = extended.geometry.contains(free_geom)
if ((in_extended and part_type == parted.PARTITION_NORMAL) or
(not in_extended and part_type == parted.PARTITION_LOGICAL)):
log.debug("free region not suitable for request")
continue
if free_geom.start > disk.maxPartitionStartSector:
log.debug("free range start sector beyond max for new partitions")
continue
if boot:
max_boot = Size("2 TiB")
free_start = Size(free_geom.start * disk.device.sectorSize)
req_end = free_start + req_size
if req_end > max_boot:
log.debug("free range position would place boot req above %s",
max_boot)
continue
log.debug("current free range is %d-%d (%s)", free_geom.start,
free_geom.end,
Size(free_geom.getLength(unit="B")))
free_size = Size(free_geom.getLength(unit="B"))
# For boot partitions, we want the first suitable region we find.
# For growable or extended partitions, we want the largest possible
# free region.
# For all others, we want the smallest suitable free region.
if grow or part_type == parted.PARTITION_EXTENDED:
op = gt
else:
op = lt
if req_size <= free_size:
if not best_free or op(free_geom.length, best_free.length):
best_free = free_geom
if boot:
# if this is a bootable partition we want to
# use the first freespace region large enough
# to satisfy the request
break
return best_free
def sectorsToSize(sectors, sectorSize):
""" Convert length in sectors to size.
:param sectors: sector count
:type sectors: int
:param sectorSize: sector size
:type sectorSize: :class:`~.size.Size`
:returns: the size
:rtype: :class:`~.size.Size`
"""
return Size(sectors * sectorSize)
def sizeToSectors(size, sectorSize):
""" Convert size to length in sectors.
:param size: size
:type size: :class:`~.size.Size`
:param sectorSize: sector size in bytes
:type sectorSize: :class:`~.size.Size`
:returns: sector count
:rtype: int
"""
sectors = int(size / sectorSize)
return sectors
def removeNewPartitions(disks, remove, all_partitions):
""" Remove newly added partitions from disks.
Remove all non-existent partitions from the disks in blivet's model.
:param: disks: list of partitioned disks
:type disks: list of :class:`~.devices.StorageDevice`
:param remove: list of partitions to remove
:type remove: list of :class:`~.devices.PartitionDevice`
:param all_partitions: list of all partitions on the disks
:type all_partitions: list of :class:`~.devices.PartitionDevice`
:returns: None
:rtype: NoneType
"""
log.debug("removing all non-preexisting partitions %s from disk(s) %s",
["%s(id %d)" % (p.name, p.id) for p in remove],
[d.name for d in disks])
for part in remove:
if part.partedPartition and part.disk in disks:
if part.exists:
# we're only removing partitions that don't physically exist
continue
if part.isExtended:
# these get removed last
continue
part.disk.format.partedDisk.removePartition(part.partedPartition)
part.partedPartition = None
part.disk = None
for disk in disks:
# remove empty extended so it doesn't interfere
extended = disk.format.extendedPartition
if extended and not disk.format.logicalPartitions and \
(flags.installer_mode or
extended not in (p.partedPartition for p in all_partitions)):
log.debug("removing empty extended partition from %s", disk.name)
disk.format.partedDisk.removePartition(extended)
def addPartition(disklabel, free, part_type, size, start=None, end=None):
""" Add a new partition to a disk.
:param disklabel: the disklabel to add the partition to
:type disklabel: :class:`~.formats.DiskLabel`
:param free: the free region in which to place the new partition
:type free: :class:`parted.Geometry`
:param part_type: the partition type
:type part_type: a parted.PARTITION_* constant
:param size: size of the new partition
:type size: :class:`~.size.Size`
:keyword start: starting sector for the partition
:type start: int
:keyword end: ending sector for the partition
:type end: int
:raises: :class:`~.errors.PartitioningError`
:returns: the newly added partitions
:rtype: :class:`parted.Partition`
.. note::
The new partition will be aligned using the kernel-provided optimal
alignment unless a start sector is provided.
"""
sectorSize = Size(disklabel.partedDevice.sectorSize)
if start is not None:
if end is None:
end = start + sizeToSectors(size, sectorSize) - 1
else:
start = free.start
if not disklabel.alignment.isAligned(free, start):
start = disklabel.alignment.alignNearest(free, start)
if disklabel.labelType == "sun" and start == 0:
start = disklabel.alignment.alignUp(free, start)
if part_type == parted.PARTITION_LOGICAL:
# make room for logical partition's metadata
start += disklabel.alignment.grainSize
if start != free.start:
log.debug("adjusted start sector from %d to %d", free.start, start)
if part_type == parted.PARTITION_EXTENDED and not size:
end = free.end
length = end - start + 1
else:
length = sizeToSectors(size, sectorSize)
end = start + length - 1
if not disklabel.endAlignment.isAligned(free, end):
end = disklabel.endAlignment.alignUp(free, end)
log.debug("adjusted length from %d to %d", length, end - start + 1)
if start > end:
raise PartitioningError(_("unable to allocate aligned partition"))
new_geom = parted.Geometry(device=disklabel.partedDevice,
start=start,
end=end)
max_length = disklabel.partedDisk.maxPartitionLength
if max_length and new_geom.length > max_length:
raise PartitioningError(_("requested size exceeds maximum allowed"))
# create the partition and add it to the disk
partition = parted.Partition(disk=disklabel.partedDisk,
type=part_type,
geometry=new_geom)
constraint = parted.Constraint(exactGeom=new_geom)
disklabel.partedDisk.addPartition(partition=partition,
constraint=constraint)
return partition
def getFreeRegions(disks):
""" Return a list of free regions on the specified disks.
:param disks: list of disks
:type disks: list of :class:`~.devices.Disk`
:returns: list of free regions
:rtype: list of :class:`parted.Geometry`
Only free regions guaranteed to contain at least one aligned sector for
both the start and end alignments in the
:class:`~.formats.disklabel.DiskLabel` are returned.
"""
free = []
for disk in disks:
for f in disk.format.partedDisk.getFreeSpaceRegions():
if f.length >= disk.format.alignment.grainSize:
free.append(f)
return free
def updateExtendedPartitions(storage, disks):
""" Reconcile extended partition changes with the DeviceTree.
:param storage: the Blivet instance
:type storage: :class:`~.Blivet`
:param disks: list of disks
:type disks: list of :class:`~.devices.StorageDevice`
:returns: :const:`None`
:rtype: NoneType
"""
# XXX hack -- if we created any extended partitions we need to add
# them to the tree now
for disk in disks:
extended = disk.format.extendedPartition
if not extended:
# remove any obsolete extended partitions
for part in storage.partitions:
if part.disk == disk and part.isExtended:
if part.exists:
storage.destroyDevice(part)
else:
storage.devicetree._removeDevice(part, modparent=False)
continue
extendedName = devicePathToName(extended.getDeviceNodeName())
device = storage.devicetree.getDeviceByName(extendedName)
if device:
if not device.exists:
# created by us, update partedPartition
device.partedPartition = extended
# remove any obsolete extended partitions
for part in storage.partitions:
if part.disk == disk and part.isExtended and \
part.partedPartition not in disk.format.partitions:
if part.exists:
storage.destroyDevice(part)
else:
storage.devicetree._removeDevice(part, modparent=False)
if device:
continue
# This is a little odd because normally instantiating a partition
# that does not exist means leaving self.parents empty and instead
# populating self.req_disks. In this case, we need to skip past
# that since this partition is already defined.
device = PartitionDevice(extendedName, parents=disk)
device.parents = [disk]
device.partedPartition = extended
# just add the device for now -- we'll handle actions at the last
# moment to simplify things
storage.devicetree._addDevice(device)
def doPartitioning(storage):
""" Allocate and grow partitions.
When this function returns without error, all PartitionDevice
instances must have their parents set to the disk they are
allocated on, and their partedPartition attribute set to the
appropriate parted.Partition instance from their containing
disk. All req_xxxx attributes must be unchanged.
:param storage: Blivet instance
:type storage: :class:`~.Blivet`
:raises: :class:`~.errors.PartitioningError`
:returns: :const:`None`
"""
disks = [d for d in storage.partitioned if not d.protected]
for disk in disks:
try:
disk.setup()
except DeviceError as e:
log.error("failed to set up disk %s: %s", disk.name, e)
raise PartitioningError(_("disk %s inaccessible") % disk.name)
# Remove any extended partition that does not have an action associated.
#
# XXX This does not remove the extended from the parted.Disk, but it should
# cause removeNewPartitions to remove it since there will no longer be
# a PartitionDevice for it.
for partition in storage.partitions:
if not partition.exists and partition.isExtended and \
not storage.devicetree.findActions(device=partition, action_type="create"):
storage.devicetree._removeDevice(partition, modparent=False, force=True)
partitions = storage.partitions[:]
for part in storage.partitions:
part.req_bootable = False
if not part.exists:
# start over with flexible-size requests
part.req_size = part.req_base_size
try:
storage.bootDevice.req_bootable = True
except AttributeError:
# there's no stage2 device. hopefully it's temporary.
pass
removeNewPartitions(disks, partitions, partitions)
free = getFreeRegions(disks)
try:
allocatePartitions(storage, disks, partitions, free)
growPartitions(disks, partitions, free, size_sets=storage.size_sets)
except Exception:
raise
else:
# Mark all growable requests as no longer growable.
for partition in storage.partitions:
log.debug("fixing size of %s", partition)
partition.req_grow = False
partition.req_base_size = partition.size
partition.req_size = partition.size
finally:
# these are only valid for one allocation run
storage.size_sets = []
# The number and thus the name of partitions may have changed now,
# allocatePartitions() takes care of this for new partitions, but not
# for pre-existing ones, so we update the name of all partitions here
for part in storage.partitions:
# leave extended partitions as-is -- we'll handle them separately
if part.isExtended:
continue
part.updateName()
updateExtendedPartitions(storage, disks)
for part in [p for p in storage.partitions if not p.exists]:
problem = part.checkSize()
if problem < 0:
raise PartitioningError(_("partition is too small for %(format)s formatting "
"(allowable size is %(minSize)s to %(maxSize)s)")
% {"format": part.format.name, "minSize": part.format.minSize,
"maxSize": part.format.maxSize})
elif problem > 0:
raise PartitioningError(_("partition is too large for %(format)s formatting "
"(allowable size is %(minSize)s to %(maxSize)s)")
% {"format": part.format.name, "minSize": part.format.minSize,
"maxSize": part.format.maxSize})
def allocatePartitions(storage, disks, partitions, freespace):
""" Allocate partitions based on requested features.
:param storage: a Blivet instance
:type storage: :class:`~.Blivet`
:param disks: list of usable disks
:type disks: list of :class:`~.devices.StorageDevice`
:param partitions: list of partitions
:type partitions: list of :class:`~.devices.PartitionDevice`
:param freespace: list of free regions on disks
:type freespace: list of :class:`parted.Geometry`
:raises: :class:`~.errors.PartitioningError`
:returns: :const:`None`
Non-existing partitions are sorted according to their requested
attributes, and then allocated.
The basic approach to sorting is that the more specifically-
defined a request is, the earlier it will be allocated. See
:func:`partitionCompare` for details of the sorting criteria.
The :class:`~.devices.PartitionDevice` instances will have their name
and parents attributes set once they have been allocated.
"""
log.debug("allocatePartitions: disks=%s ; partitions=%s",
[d.name for d in disks],
["%s(id %d)" % (p.name, p.id) for p in partitions])