/
blivet.py
1885 lines (1525 loc) · 68.9 KB
/
blivet.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
#
# Copyright (C) 2009-2015 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>
#
import os
import copy
import tempfile
import re
import shelve
import contextlib
import time
import parted
import functools
from pykickstart.constants import AUTOPART_TYPE_LVM, CLEARPART_TYPE_ALL, CLEARPART_TYPE_LINUX, CLEARPART_TYPE_LIST, CLEARPART_TYPE_NONE
from .storage_log import log_method_call, log_exception_info
from .devices import BTRFSDevice, BTRFSSubVolumeDevice, BTRFSVolumeDevice
from .devices import LVMLogicalVolumeDevice, LVMThinLogicalVolumeDevice, LVMThinPoolDevice, LVMVolumeGroupDevice
from .devices import MDRaidArrayDevice, PartitionDevice, TmpFSDevice, devicePathToName
from .deviceaction import ActionCreateDevice, ActionCreateFormat, ActionDestroyDevice
from .deviceaction import ActionDestroyFormat, ActionResizeDevice, ActionResizeFormat
from .devicelibs.edd import get_edd_dict
from .devicelibs.btrfs import MAIN_VOLUME_ID
from .errors import StorageError
from .size import Size
from .devicetree import DeviceTree
from .formats import get_default_filesystem_type
from .flags import flags
from .platform import platform as _platform
from .formats import getFormat
from .osinstall import FSSet, findExistingInstallations
from . import arch
from . import iscsi
from . import fcoe
from . import zfcp
from . import devicefactory
from . import get_bootloader, getSysroot, shortProductName, __version__
from .util import open # pylint: disable=redefined-builtin
from .i18n import _
import logging
log = logging.getLogger("blivet")
def empty_device(device, devicetree):
empty = True
if device.partitioned:
partitions = devicetree.getChildren(device)
empty = all([p.isMagic for p in partitions])
else:
empty = (device.format.type is None)
return empty
class StorageDiscoveryConfig(object):
""" Class to encapsulate various detection/initialization parameters. """
def __init__(self):
# storage configuration variables
self.ignoreDiskInteractive = False
self.ignoredDisks = []
self.exclusiveDisks = []
self.clearPartType = None
self.clearPartDisks = []
self.clearPartDevices = []
self.initializeDisks = False
self.protectedDevSpecs = []
self.diskImages = {}
self.zeroMbr = False
# Whether clearPartitions removes scheduled/non-existent devices and
# disklabels depends on this flag.
self.clearNonExistent = False
def update(self, ksdata):
""" Update configuration from ksdata source.
:param ksdata: kickstart data used as data source
:type ksdata: :class:`pykickstart.Handler`
"""
self.ignoredDisks = ksdata.ignoredisk.ignoredisk[:]
self.exclusiveDisks = ksdata.ignoredisk.onlyuse[:]
self.clearPartType = ksdata.clearpart.type
self.clearPartDisks = ksdata.clearpart.drives[:]
self.clearPartDevices = ksdata.clearpart.devices[:]
self.initializeDisks = ksdata.clearpart.initAll
self.zeroMbr = ksdata.zerombr.zerombr
class Blivet(object):
""" Top-level class for managing storage configuration. """
def __init__(self, ksdata=None):
"""
:keyword ksdata: kickstart data store
:type ksdata: :class:`pykickstart.Handler`
"""
self.ksdata = ksdata
self._bootloader = None
self.config = StorageDiscoveryConfig()
# storage configuration variables
self.doAutoPart = False
self.clearPartChoice = None
self.encryptedAutoPart = False
self.autoPartType = AUTOPART_TYPE_LVM
self.encryptionPassphrase = None
self.encryptionCipher = None
self.escrowCertificates = {}
self.autoPartEscrowCert = None
self.autoPartAddBackupPassphrase = False
self.autoPartitionRequests = []
self.eddDict = {}
self.dasd = []
self.__luksDevs = {}
self.size_sets = []
self.setDefaultFSType(get_default_filesystem_type())
self._defaultBootFSType = None
self.iscsi = iscsi.iscsi()
self.fcoe = fcoe.fcoe()
self.zfcp = zfcp.ZFCP()
self._nextID = 0
self._dumpFile = "%s/storage.state" % tempfile.gettempdir()
# these will both be empty until our reset method gets called
self.devicetree = DeviceTree(conf=self.config,
passphrase=self.encryptionPassphrase,
luksDict=self.__luksDevs,
iscsi=self.iscsi,
dasd=self.dasd)
self.fsset = FSSet(self.devicetree)
self.roots = []
self.services = set()
self._free_space_snapshot = None
def doIt(self, callbacks=None):
"""
Commit queued changes to disk.
:param callbacks: callbacks to be invoked when actions are executed
:type callbacks: return value of the :func:`~.callbacks.create_new_callbacks_register`
"""
self.devicetree.processActions(callbacks=callbacks)
if not flags.installer_mode:
return
# now set the boot partition's flag
if self.bootloader and not self.bootloader.skip_bootloader:
if self.bootloader.stage2_bootable:
boot = self.bootDevice
else:
boot = self.bootLoaderDevice
if boot.type == "mdarray":
bootDevs = boot.parents
else:
bootDevs = [boot]
for dev in bootDevs:
if not hasattr(dev, "bootable"):
log.info("Skipping %s, not bootable", dev)
continue
# Dos labels can only have one partition marked as active
# and unmarking ie the windows partition is not a good idea
skip = False
if dev.disk.format.partedDisk.type == "msdos":
for p in dev.disk.format.partedDisk.partitions:
if p.type == parted.PARTITION_NORMAL and \
p.getFlag(parted.PARTITION_BOOT):
skip = True
break
# GPT labeled disks should only have bootable set on the
# EFI system partition (parted sets the EFI System GUID on
# GPT partitions with the boot flag)
if dev.disk.format.labelType == "gpt" and \
dev.format.type not in ["efi", "macefi"]:
skip = True
if skip:
log.info("Skipping %s", dev.name)
continue
# hfs+ partitions on gpt can't be marked bootable via parted
if dev.disk.format.partedDisk.type != "gpt" or \
dev.format.type not in ["hfs+", "macefi"]:
log.info("setting boot flag on %s", dev.name)
dev.bootable = True
# Set the boot partition's name on disk labels that support it
if dev.partedPartition.disk.supportsFeature(parted.DISK_TYPE_PARTITION_NAME):
ped_partition = dev.partedPartition.getPedPartition()
ped_partition.set_name(dev.format.name)
log.info("Setting label on %s to '%s'", dev, dev.format.name)
dev.disk.setup()
dev.disk.format.commitToDisk()
if flags.installer_mode:
self.dumpState("final")
@property
def nextID(self):
""" Used for creating unique placeholder names. """
newid = self._nextID
self._nextID += 1
return newid
def shutdown(self):
""" Deactivate all devices (installer_mode only). """
if not flags.installer_mode:
return
try:
self.devicetree.teardownAll()
except Exception: # pylint: disable=broad-except
log_exception_info(log.error, "failure tearing down device tree")
def reset(self, cleanupOnly=False):
""" Reset storage configuration to reflect actual system state.
This will cancel any queued actions and rescan from scratch but not
clobber user-obtained information like passphrases, iscsi config, &c
:keyword cleanupOnly: prepare the tree only to deactivate devices
:type cleanupOnly: bool
See :meth:`devicetree.Devicetree.populate` for more information
about the cleanupOnly keyword argument.
"""
log.info("resetting Blivet (version %s) instance %s", __version__, self)
if flags.installer_mode:
# save passphrases for luks devices so we don't have to reprompt
self.encryptionPassphrase = None
for device in self.devices:
if device.format.type == "luks" and device.format.exists:
self.__luksDevs[device.format.uuid] = device.format._LUKS__passphrase
if self.ksdata:
self.config.update(self.ksdata)
if flags.installer_mode and not flags.image_install:
self.iscsi.startup()
self.fcoe.startup()
self.zfcp.startup()
self.dasd = self.devicetree.make_dasd_list(self.dasd, self.devices)
if self.dasd:
# Reset the internal dasd list (823534)
self.dasd = []
self.devicetree.reset(conf=self.config,
passphrase=self.encryptionPassphrase,
luksDict=self.__luksDevs,
iscsi=self.iscsi,
dasd=self.dasd)
self.devicetree.populate(cleanupOnly=cleanupOnly)
self.fsset = FSSet(self.devicetree)
self.eddDict = get_edd_dict(self.partitioned)
if self.bootloader:
# clear out bootloader attributes that refer to devices that are
# no longer in the tree
self.bootloader.reset()
self.roots = []
if flags.installer_mode:
try:
self.roots = findExistingInstallations(self.devicetree)
except Exception: # pylint: disable=broad-except
log_exception_info(log.info, "failure detecting existing installations")
self.dumpState("initial")
if not flags.installer_mode:
self.devicetree.handleNodevFilesystems()
self.updateBootLoaderDiskList()
@property
def unusedDevices(self):
used_devices = []
for root in self.roots:
for device in list(root.mounts.values()) + root.swaps:
if device not in self.devices:
continue
used_devices.extend(device.ancestors)
for new in [d for d in self.devicetree.leaves if not d.format.exists]:
if new.format.mountable and not new.format.mountpoint:
continue
used_devices.extend(new.ancestors)
for device in self.partitions:
if getattr(device, "isLogical", False):
extended = device.disk.format.extendedPartition.path
used_devices.append(self.devicetree.getDeviceByPath(extended))
used = set(used_devices)
_all = set(self.devices)
return list(_all.difference(used))
@property
def devices(self):
""" A list of all the devices in the device tree. """
devices = self.devicetree.devices
devices.sort(key=lambda d: d.name)
return devices
@property
def disks(self):
""" A list of the disks in the device tree.
Ignored disks are excluded, as are disks with no media present.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
disks = []
for device in self.devicetree.devices:
if device.isDisk:
if not device.mediaPresent:
log.info("Skipping disk: %s: No media present", device.name)
continue
disks.append(device)
disks.sort(key=self.compareDisksKey)
return disks
@property
def partitioned(self):
""" A list of the partitioned devices in the device tree.
Ignored devices are not included, nor disks with no media present.
Devices of types for which partitioning is not supported are also
not included.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
partitioned = []
for device in self.devicetree.devices:
if not device.partitioned:
continue
if not device.mediaPresent:
log.info("Skipping device: %s: No media present", device.name)
continue
partitioned.append(device)
partitioned.sort(key=lambda d: d.name)
return partitioned
@property
def partitions(self):
""" A list of the partitions in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
partitions = self.devicetree.getDevicesByInstance(PartitionDevice)
partitions.sort(key=lambda d: d.name)
return partitions
@property
def vgs(self):
""" A list of the LVM Volume Groups in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
vgs = self.devicetree.getDevicesByType("lvmvg")
vgs.sort(key=lambda d: d.name)
return vgs
@property
def lvs(self):
""" A list of the LVM Logical Volumes in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
lvs = (d for d in self.devices if d.type in ("lvmlv", "lvmthinpool", "lvmthinlv"))
return sorted(lvs, key=lambda d: d.name)
@property
def thinlvs(self):
""" A list of the LVM Thin Logical Volumes in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
thin = self.devicetree.getDevicesByType("lvmthinlv")
thin.sort(key=lambda d: d.name)
return thin
@property
def thinpools(self):
""" A list of the LVM Thin Pool Logical Volumes in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
pools = self.devicetree.getDevicesByType("lvmthinpool")
pools.sort(key=lambda d: d.name)
return pools
@property
def pvs(self):
""" A list of the LVM Physical Volumes in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
devices = self.devicetree.devices
pvs = [d for d in devices if d.format.type == "lvmpv"]
pvs.sort(key=lambda d: d.name)
return pvs
@property
def mdarrays(self):
""" A list of the MD arrays in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
arrays = self.devicetree.getDevicesByType("mdarray")
arrays.sort(key=lambda d: d.name)
return arrays
@property
def mdcontainers(self):
""" A list of the MD containers in the device tree. """
arrays = self.devicetree.getDevicesByType("mdcontainer")
arrays.sort(key=lambda d: d.name)
return arrays
@property
def mdmembers(self):
""" A list of the MD member devices in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
devices = self.devicetree.devices
members = [d for d in devices if d.format.type == "mdmember"]
members.sort(key=lambda d: d.name)
return members
@property
def btrfsVolumes(self):
""" A list of the BTRFS volumes in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
return sorted(self.devicetree.getDevicesByType("btrfs volume"),
key=lambda d: d.name)
@property
def swaps(self):
""" A list of the swap devices in the device tree.
This is based on the current state of the device tree and
does not necessarily reflect the actual on-disk state of the
system's disks.
"""
devices = self.devicetree.devices
swaps = [d for d in devices if d.format.type == "swap"]
swaps.sort(key=lambda d: d.name)
return swaps
def shouldClear(self, device, **kwargs):
""" Return True if a clearpart settings say a device should be cleared.
:param device: the device (required)
:type device: :class:`~.devices.StorageDevice`
:keyword clearPartType: overrides :attr:`self.config.clearPartType`
:type clearPartType: int
:keyword clearPartDisks: overrides
:attr:`self.config.clearPartDisks`
:type clearPartDisks: list
:keyword clearPartDevices: overrides
:attr:`self.config.clearPartDevices`
:type clearPartDevices: list
:returns: whether or not clearPartitions should remove this device
:rtype: bool
"""
clearPartType = kwargs.get("clearPartType", self.config.clearPartType)
clearPartDisks = kwargs.get("clearPartDisks",
self.config.clearPartDisks)
clearPartDevices = kwargs.get("clearPartDevices",
self.config.clearPartDevices)
for disk in device.disks:
# this will not include disks with hidden formats like multipath
# and firmware raid member disks
if clearPartDisks and disk.name not in clearPartDisks:
return False
if not self.config.clearNonExistent:
if (device.isDisk and not device.format.exists) or \
(not device.isDisk and not device.exists):
return False
# the only devices we want to clear when clearPartType is
# CLEARPART_TYPE_NONE are uninitialized disks, or disks with no
# partitions, in clearPartDisks, and then only when we have been asked
# to initialize disks as needed
if clearPartType in [CLEARPART_TYPE_NONE, None]:
if not self.config.initializeDisks or not device.isDisk:
return False
if not empty_device(device, self.devicetree):
return False
if isinstance(device, PartitionDevice):
# Never clear the special first partition on a Mac disk label, as
# that holds the partition table itself.
# Something similar for the third partition on a Sun disklabel.
if device.isMagic:
return False
# We don't want to fool with extended partitions, freespace, &c
if not device.isPrimary and not device.isLogical:
return False
if clearPartType == CLEARPART_TYPE_LINUX and \
not device.format.linuxNative and \
not device.getFlag(parted.PARTITION_LVM) and \
not device.getFlag(parted.PARTITION_RAID) and \
not device.getFlag(parted.PARTITION_SWAP):
return False
elif device.isDisk:
if device.partitioned and clearPartType != CLEARPART_TYPE_ALL:
# if clearPartType is not CLEARPART_TYPE_ALL but we'll still be
# removing every partition from the disk, return True since we
# will want to be able to create a new disklabel on this disk
if not empty_device(device, self.devicetree):
return False
# Never clear disks with hidden formats
if device.format.hidden:
return False
# When clearPartType is CLEARPART_TYPE_LINUX and a disk has non-
# linux whole-disk formatting, do not clear it. The exception is
# the case of an uninitialized disk when we've been asked to
# initialize disks as needed
if (clearPartType == CLEARPART_TYPE_LINUX and
not ((self.config.initializeDisks and
empty_device(device, self.devicetree)) or
(not device.partitioned and device.format.linuxNative))):
return False
# Don't clear devices holding install media.
descendants = self.devicetree.getDependentDevices(device)
if device.protected or any(d.protected for d in descendants):
return False
if clearPartType == CLEARPART_TYPE_LIST and \
device.name not in clearPartDevices:
return False
return True
def recursiveRemove(self, device):
""" Remove a device after removing its dependent devices.
If the device is not a leaf, all of its dependents are removed
recursively until it is a leaf device. At that point the device is
removed, unless it is a disk. If the device is a disk, its
formatting is removed by no attempt is made to actually remove the
disk device.
"""
self.devicetree.recursiveRemove(device)
def clearPartitions(self):
""" Clear partitions and dependent devices from disks.
This is also where zerombr is handled.
"""
# Sort partitions by descending partition number to minimize confusing
# things like multiple "destroy sda5" actions due to parted renumbering
# partitions. This can still happen through the UI but it makes sense to
# avoid it where possible.
partitions = sorted(self.partitions,
key=lambda p: p.partedPartition.number,
reverse=True)
for part in partitions:
log.debug("clearpart: looking at %s", part.name)
if not self.shouldClear(part):
continue
self.recursiveRemove(part)
log.debug("partitions: %s", [p.getDeviceNodeName() for p in part.partedPartition.disk.partitions])
# now remove any empty extended partitions
self.removeEmptyExtendedPartitions()
# ensure all disks have appropriate disklabels
for disk in self.disks:
zerombr = (self.config.zeroMbr and disk.format.type is None)
should_clear = self.shouldClear(disk)
if should_clear:
self.recursiveRemove(disk)
if zerombr or should_clear:
log.debug("clearpart: initializing %s", disk.name)
self.initializeDisk(disk)
self.updateBootLoaderDiskList()
def initializeDisk(self, disk):
""" (Re)initialize a disk by creating a disklabel on it.
The disk should not contain any partitions except perhaps for a
magic partitions on mac and sun disklabels. If the disk does contain
partitions other than the disklabel-type-specific "magic" partitions
ValueError will be raised.
:param disk: the disk to initialize
:type disk: :class:`~.devices.StorageDevice`
:returns None:
:raises: ValueError
"""
# first, remove magic mac/sun partitions from the parted Disk
if disk.partitioned:
magic = disk.format.magicPartitionNumber
expected = 0
if magic:
expected = 1
# remove the magic partition
for part in self.devicetree.getChildren(disk):
if part.partedPartition.number == magic:
log.debug("removing %s", part.name)
# We can't schedule the magic partition for removal
# because parted will not allow us to remove it from the
# disk. Still, we need it out of the devicetree.
self.devicetree._removeDevice(part, modparent=False)
if len(disk.format.partitions) > expected:
raise ValueError("cannot initialize a disk that has partitions")
# remove existing formatting from the disk
destroy_action = ActionDestroyFormat(disk)
self.devicetree.registerAction(destroy_action)
labelType = _platform.bestDiskLabelType(disk)
# create a new disklabel on the disk
newLabel = getFormat("disklabel", device=disk.path,
labelType=labelType)
create_action = ActionCreateFormat(disk, fmt=newLabel)
self.devicetree.registerAction(create_action)
def removeEmptyExtendedPartitions(self):
for disk in self.partitioned:
log.debug("checking whether disk %s has an empty extended", disk.name)
extended = disk.format.extendedPartition
logical_parts = disk.format.logicalPartitions
log.debug("extended is %s ; logicals is %s", extended, [p.getDeviceNodeName() for p in logical_parts])
if extended and not logical_parts:
log.debug("removing empty extended partition from %s", disk.name)
extended_name = devicePathToName(extended.getDeviceNodeName())
extended = self.devicetree.getDeviceByName(extended_name)
self.destroyDevice(extended)
def getFreeSpace(self, disks=None, clearPartType=None):
""" Return a dict with free space info for each disk.
The dict values are 2-tuples: (disk_free, fs_free). fs_free is
space available by shrinking filesystems. disk_free is space not
allocated to any partition.
disks and clearPartType allow specifying a set of disks other than
self.disks and a clearPartType value other than
self.config.clearPartType.
:keyword disks: overrides :attr:`disks`
:type disks: list
:keyword clearPartType: overrides :attr:`self.config.clearPartType`
:type clearPartType: int
:returns: dict with disk name keys and tuple (disk, fs) free values
:rtype: dict
.. note::
The free space values are :class:`~.size.Size` instances.
"""
if disks is None:
disks = self.disks
if clearPartType is None:
clearPartType = self.config.clearPartType
free = {}
for disk in disks:
should_clear = self.shouldClear(disk, clearPartType=clearPartType,
clearPartDisks=[disk.name])
if should_clear:
free[disk.name] = (disk.size, Size(0))
continue
disk_free = Size(0)
fs_free = Size(0)
if disk.partitioned:
disk_free = disk.format.free
for partition in [p for p in self.partitions if p.disk == disk]:
# only check actual filesystems since lvm &c require a bunch of
# operations to translate free filesystem space into free disk
# space
should_clear = self.shouldClear(partition,
clearPartType=clearPartType,
clearPartDisks=[disk.name])
if should_clear:
disk_free += partition.size
elif hasattr(partition.format, "free"):
fs_free += partition.format.free
elif hasattr(disk.format, "free"):
fs_free = disk.format.free
elif disk.format.type is None:
disk_free = disk.size
free[disk.name] = (disk_free, fs_free)
return free
@property
def names(self):
""" A list of all of the known in-use device names. """
return self.devicetree.names
def deviceDeps(self, device):
""" Return a list of the devices that depend on the specified device.
:param device: the subtree root device
:type device: :class:`~.devices.StorageDevice`
:returns: list of dependent devices
:rtype: list
"""
return self.devicetree.getDependentDevices(device)
def newPartition(self, *args, **kwargs):
""" Return a new (unallocated) PartitionDevice instance.
:keyword fmt_type: format type
:type fmt_type: str
:keyword fmt_args: arguments for format constructor
:type fmt_args: dict
:keyword mountpoint: mountpoint for format (filesystem)
:type mountpoint: str
All other arguments are passed on to the
:class:`~.devices.PartitionDevice` constructor.
"""
if 'fmt_type' in kwargs:
kwargs["fmt"] = getFormat(kwargs.pop("fmt_type"),
mountpoint=kwargs.pop("mountpoint",
None),
**kwargs.pop("fmt_args", {}))
if 'name' in kwargs:
name = kwargs.pop("name")
else:
name = "req%d" % self.nextID
if "weight" not in kwargs:
fmt = kwargs.get("fmt")
if fmt:
mountpoint = getattr(fmt, "mountpoint", None)
kwargs["weight"] = _platform.weight(mountpoint=mountpoint,
fstype=fmt.type)
return PartitionDevice(name, *args, **kwargs)
def newMDArray(self, *args, **kwargs):
""" Return a new MDRaidArrayDevice instance.
:keyword fmt_type: format type
:type fmt_type: str
:keyword fmt_args: arguments for format constructor
:type fmt_args: dict
:keyword mountpoint: mountpoint for format (filesystem)
:type mountpoint: str
:returns: the new md array device
:rtype: :class:`~.devices.MDRaidArrayDevice`
All other arguments are passed on to the
:class:`~.devices.MDRaidArrayDevice` constructor.
If a name is not specified, one will be generated based on the
format type, mountpoint, hostname, and/or product name.
"""
if 'fmt_type' in kwargs:
kwargs["fmt"] = getFormat(kwargs.pop("fmt_type"),
mountpoint=kwargs.pop("mountpoint",
None),
**kwargs.pop("fmt_args", {}))
name = kwargs.pop("name", None)
if name:
safe_name = self.safeDeviceName(name)
if safe_name != name:
log.warning("using '%s' instead of specified name '%s'",
safe_name, name)
name = safe_name
else:
swap = getattr(kwargs.get("fmt"), "type", None) == "swap"
mountpoint = getattr(kwargs.get("fmt"), "mountpoint", None)
name = self.suggestDeviceName(prefix=shortProductName,
swap=swap,
mountpoint=mountpoint)
return MDRaidArrayDevice(name, *args, **kwargs)
def newVG(self, *args, **kwargs):
""" Return a new LVMVolumeGroupDevice instance.
:returns: the new volume group device
:rtype: :class:`~.devices.LVMVolumeGroupDevice`
All arguments are passed on to the
:class:`~.devices.LVMVolumeGroupDevice` constructor.
If a name is not specified, one will be generated based on the
hostname, and/or product name.
"""
pvs = kwargs.pop("parents", [])
for pv in pvs:
if pv not in self.devices:
raise ValueError("pv is not in the device tree")
name = kwargs.pop("name", None)
if name:
safe_name = self.safeDeviceName(name)
if safe_name != name:
log.warning("using '%s' instead of specified name '%s'",
safe_name, name)
name = safe_name
else:
hostname = ""
if self.ksdata and self.ksdata.network.hostname is not None:
hostname = self.ksdata.network.hostname
name = self.suggestContainerName(hostname=hostname)
if name in self.names:
raise ValueError("name already in use")
return LVMVolumeGroupDevice(name, pvs, *args, **kwargs)
def newLV(self, *args, **kwargs):
""" Return a new LVMLogicalVolumeDevice instance.
:keyword fmt_type: format type
:type fmt_type: str
:keyword fmt_args: arguments for format constructor
:type fmt_args: dict
:keyword mountpoint: mountpoint for format (filesystem)
:type mountpoint: str
:keyword thin_pool: whether to create a thin pool
:type thin_pool: bool
:keyword thin_volume: whether to create a thin volume
:type thin_volume: bool
:returns: the new device
:rtype: :class:`~.devices.LVMLogicalVolumeDevice`
All other arguments are passed on to the appropriate
:class:`~.devices.LVMLogicalVolumeDevice` constructor.
If a name is not specified, one will be generated based on the
format type and/or mountpoint.
.. note::
If you are creating a thin volume, the parents kwarg should
contain the pool -- not the vg.
"""
thin_volume = kwargs.pop("thin_volume", False)
thin_pool = kwargs.pop("thin_pool", False)
parent = kwargs.get("parents", [None])[0]
if thin_volume and parent:
# kwargs["parents"] will contain the pool device, so...
vg = parent.vg
else:
vg = parent
mountpoint = kwargs.pop("mountpoint", None)
if 'fmt_type' in kwargs:
kwargs["fmt"] = getFormat(kwargs.pop("fmt_type"),
mountpoint=mountpoint,
**kwargs.pop("fmt_args", {}))
name = kwargs.pop("name", None)
if name:
# make sure the specified name is sensible
safe_vg_name = self.safeDeviceName(vg.name)
full_name = "%s-%s" % (safe_vg_name, name)
safe_name = self.safeDeviceName(full_name)
if safe_name != full_name:
new_name = safe_name[len(safe_vg_name)+1:]
log.warning("using '%s' instead of specified name '%s'",
new_name, name)
name = new_name
else:
if kwargs.get("fmt") and kwargs["fmt"].type == "swap":
swap = True
else:
swap = False
prefix = ""
if thin_pool:
prefix = "pool"
name = self.suggestDeviceName(parent=vg,
swap=swap,
mountpoint=mountpoint,
prefix=prefix)
if "%s-%s" % (vg.name, name) in self.names:
raise ValueError("name already in use")
if thin_pool:
device_class = LVMThinPoolDevice
elif thin_volume:
device_class = LVMThinLogicalVolumeDevice
else:
device_class = LVMLogicalVolumeDevice
return device_class(name, *args, **kwargs)
def newBTRFS(self, *args, **kwargs):
""" Return a new BTRFSVolumeDevice or BRFSSubVolumeDevice.
:keyword fmt_args: arguments for format constructor
:type fmt_args: dict
:keyword mountpoint: mountpoint for format (filesystem)
:type mountpoint: str
:keyword subvol: whether this is a subvol (as opposed to a volume)
:type subvol: bool
:returns: the new device
:rtype: :class:`~.devices.BTRFSDevice`
All other arguments are passed on to the appropriate
:class:`~.devices.BTRFSDevice` constructor.
For volumes, the label is the same as the name. If a name/label is
not specified, one will be generated based on the hostname and/or
product name.
.. note::
If you are creating a subvolume, the parents kwarg should
contain the volume you want to contain the subvolume.
"""
log.debug("newBTRFS: args = %s ; kwargs = %s", args, kwargs)
name = kwargs.pop("name", None)
if args:
name = args[0]