-
Notifications
You must be signed in to change notification settings - Fork 84
/
devicefactory.py
1781 lines (1439 loc) · 66.5 KB
/
devicefactory.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
# devicefactory.py
# Creation of devices based on a top-down specification.
#
# Copyright (C) 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): David Lehman <dlehman@redhat.com>
#
from .storage_log import log_method_call
from .errors import DeviceFactoryError, StorageError
from .devices import BTRFSDevice, DiskDevice
from .devices import LUKSDevice, LVMLogicalVolumeDevice, LVMThinPoolDevice
from .devices import PartitionDevice, MDRaidArrayDevice
from .formats import get_format
from .devicelibs import btrfs
from .devicelibs import mdraid
from .devicelibs import lvm
from .devicelibs import raid
from .partitioning import SameSizeSet
from .partitioning import TotalSizeSet
from .partitioning import do_partitioning
from .size import Size
import gi
gi.require_version("BlockDev", "1.0")
from gi.repository import BlockDev as blockdev
import logging
log = logging.getLogger("blivet")
# policy value of >0 is a fixed size request
SIZE_POLICY_MAX = -1
SIZE_POLICY_AUTO = 0
DEVICE_TYPE_LVM = 0
DEVICE_TYPE_MD = 1
DEVICE_TYPE_PARTITION = 2
DEVICE_TYPE_BTRFS = 3
DEVICE_TYPE_DISK = 4
DEVICE_TYPE_LVM_THINP = 5
def is_supported_device_type(device_type):
""" Return True if blivet supports this device type.
:param device_type: an enumeration indicating the device type
:type device_type: int
:returns: True if this device type is supported
:rtype: bool
"""
devices = []
if device_type == DEVICE_TYPE_BTRFS:
devices = [BTRFSDevice]
elif device_type == DEVICE_TYPE_DISK:
devices = [DiskDevice]
elif device_type in (DEVICE_TYPE_LVM, DEVICE_TYPE_LVM_THINP):
devices = [LVMLogicalVolumeDevice, LVMThinPoolDevice]
elif device_type == DEVICE_TYPE_PARTITION:
devices = [PartitionDevice]
elif device_type == DEVICE_TYPE_MD:
devices = [MDRaidArrayDevice]
return not any(c.unavailable_type_dependencies() for c in devices)
def get_supported_raid_levels(device_type):
""" Return the supported raid levels for this device type.
:param device_type: an enumeration indicating the device type
:type device_type: int
:returns: a set of supported raid levels for this device type
:rtype: set of :class:`~.devicelibs.raid.RAIDLevel`
"""
pkg = None
if device_type == DEVICE_TYPE_BTRFS:
pkg = btrfs
elif device_type in (DEVICE_TYPE_LVM, DEVICE_TYPE_LVM_THINP):
pkg = lvm
elif device_type == DEVICE_TYPE_MD:
pkg = mdraid
if pkg and all(d.available for d in pkg.EXTERNAL_DEPENDENCIES):
return set(pkg.raid_levels)
else:
return set()
def get_device_type(device):
# the only time we should ever get a thin pool here is when we're removing
# an empty pool after removing the last thin lv, so the only thing we'll be
# doing with the factory is adjusting the vg to account for the pool's
# removal
device_types = {"partition": DEVICE_TYPE_PARTITION,
"lvmlv": DEVICE_TYPE_LVM,
"lvmthinlv": DEVICE_TYPE_LVM_THINP,
"lvmthinpool": DEVICE_TYPE_LVM,
"btrfs subvolume": DEVICE_TYPE_BTRFS,
"btrfs volume": DEVICE_TYPE_BTRFS,
"mdarray": DEVICE_TYPE_MD}
use_dev = device.raw_device
if use_dev.is_disk:
device_type = DEVICE_TYPE_DISK
else:
device_type = device_types.get(use_dev.type)
return device_type
def get_device_factory(blivet, device_type, size, **kwargs):
""" Return a suitable DeviceFactory instance for device_type. """
disks = kwargs.pop("disks", [])
class_table = {DEVICE_TYPE_LVM: LVMFactory,
DEVICE_TYPE_BTRFS: BTRFSFactory,
DEVICE_TYPE_PARTITION: PartitionFactory,
DEVICE_TYPE_MD: MDFactory,
DEVICE_TYPE_LVM_THINP: LVMThinPFactory,
DEVICE_TYPE_DISK: DeviceFactory}
factory_class = class_table[device_type]
log.debug("instantiating %s: %s, %s, %s, %s", factory_class,
blivet, size, [d.name for d in disks], kwargs)
return factory_class(blivet, size, disks, **kwargs)
class DeviceFactory(object):
""" Class for creation of devices based on a top-down specification
DeviceFactory instances can be combined/stacked to create more complex
device stacks like lvm with md pvs.
Simplified call trace for creation of a new LV in a new VG with
partition PVs::
LVMFactory.configure
PartitionSetFactory.configure # set up PVs on partitions
LVMFactory._create_container # create container device (VG)
LVMFactory._create_device # create leaf device (LV)
Simplified call trace for creation of a new LV in a new VG with a single
MD PV with member partitions on multiple disks::
LVMOnMDFactory.configure
MDFactory.configure
PartitionSetFactory.configure # create md partitions
MDFactory._create_device # create PV on MD array
LVMFactory._create_container # create VG
LVMFactory._create_device # create LV
The code below will create a volume group with the name "data" just
large enough to contain a new logical volume named "music" with a size
of 10000 MB. It will make one physical volume partition on each disk in
"disks" that has space. If the resulting volume group is not large
enough to contain a logical volume of the specified size, the logical
volume will be created with a size that is as close as possible to the
requested size. If there is already a non-existent volume group named
"data" in the Blivet instance's device tree, that volume group will be
used instead of creating a new one. If the already-defined "data" volume
group exists on disk its size will not be changed, but if it has not
been written to disk it will be adjusted to hold the new logical volume::
import blivet
_blivet = blivet.Blivet()
_blivet.reset()
disks = _blivet.partitioned
# Create a new LV "music" to a VG named "data", which may or may not
# exist. If the VG exists, the LV will be allocated from free space
# in the VG. If the VG does not exist, one will be created using new
# PVs on each of the specified disks. No free space is maintained in
# new VGs by default.
factory = blivet.devicefactory.LVMFactory(_blivet,
Size("10000 MB"),
disks,
fstype="xfs",
label="music",
name="music",
container_name="data")
factory.configure()
music_lv = factory.device
# Now add another LV to the "data" VG, adjusting the size of a non-
# existent "data" VG so that it can contain the new LV.
factory = blivet.devicefactory.LVMFactory(_blivet,
Size("20000 MB"),
disks,
fstype="xfs",
label="videos",
name="videos",
container_name="data")
factory.configure()
# Now change the size of the "music" LV and adjust the size of the
# "data" VG accordingly.
factory = blivet.devicefactory.LVMFactory(_blivet,
Size("15000 MB"),
disks,
device=music_lv)
factory.configure()
# Write the new devices to disk and create the filesystems they
# contain.
_blivet.do_it()
Some operations (on non-existent devices) these classes do support:
- create a device and a container to hold it
- create a device within a defined container
- create a device within an existing (on disk) container
- change the set of disks from which partitions used by a factory
can be allocated
- change the size of a defined (but non-existent) device
- toggle encryption of a leaf device or container member devices
Some operations these classes do not support:
- any modification to an existing leaf device
- change an existing container's member device set
- resize or rename an existing container
- move a device from one container to another
- change the type of a defined device
- change the container member device type of a defined device
"""
child_factory_class = None
child_factory_fstype = None
size_set_class = TotalSizeSet
def __init__(self, storage, size, disks, fstype=None, mountpoint=None,
label=None, raid_level=None, encrypted=False,
container_encrypted=False, container_name=None,
container_raid_level=None, container_size=SIZE_POLICY_AUTO,
name=None, device=None, min_luks_entropy=0):
"""
:param storage: a Blivet instance
:type storage: :class:`~.Blivet`
:param size: the desired size for the device
:type size: :class:`~.size.Size`
:param disks: the set of disks to use
:type disks: list of :class:`~.devices.StorageDevice`
:keyword fstype: filesystem type
:type fstype: str
:keyword mountpoint: filesystem mount point
:type mountpoint: str
:keyword label: filesystem label text
:type label: str
:keyword raid_level: raid level descriptor
:type raid_level: any valid RAID level descriptor
:keyword encrypted: whether to encrypt (boolean)
:type encrypted: bool
:keyword name: name of requested device
:type name: str
:keyword device: an already-defined but non-existent device to
adjust instead of creating a new device
:type device: :class:`~.devices.StorageDevice`
.. note::
any device passed must be of the appropriate type for the
factory class it is passed to
:keyword container_name: name of requested container
:type container_name: str
:keyword container_raid_level: raid level for container
:type container_raid_level: any valid RAID level descriptor
:keyword container_encrypted: whether to encrypt the container
:type container_encrypted: bool
:keyword container_size: requested container size
:type container_size: :class:`~.size.Size`
:keyword min_luks_entropy: minimum entropy in bits required for
LUKS format creation
:type min_luks_entropy: int
"""
if encrypted and size:
# encrypted, bump size up with LUKS metadata size
size += get_format("luks").min_size
self.storage = storage # a Blivet instance
self.size = size # the requested size for this device
self.disks = disks # the set of disks to allocate from
self.original_size = size
self.original_disks = disks[:]
self.fstype = fstype
self.mountpoint = mountpoint
self.label = label
self.raid_level = raid_level
self.container_raid_level = container_raid_level
self.encrypted = encrypted
self.container_encrypted = container_encrypted
self.container_name = container_name
self.device_name = name
self.container_size = container_size
self.container = None
self.device = device
if not self.fstype:
self.fstype = self.storage.get_fstype(mountpoint=self.mountpoint)
if fstype == "swap":
self.mountpoint = None
self.child_factory = None
self.parent_factory = None
self.min_luks_entropy = min_luks_entropy
# used for error recovery
self.__devices = []
self.__actions = []
self.__names = []
self.__roots = []
@property
def raid_level(self):
return self._raid_level
@raid_level.setter
def raid_level(self, value):
""" Sets the RAID level for the factory.
:param value: new RAID level
:param type: a valid RAID level descriptor
:returns: None
"""
# pylint: disable=attribute-defined-outside-init
if value is None:
self._raid_level = None
else:
self._raid_level = raid.get_raid_level(value)
@property
def container_raid_level(self):
return self._container_raid_level
@container_raid_level.setter
def container_raid_level(self, value):
""" Sets the RAID level for the factory.
:param value: new RAID level
:param type: a valid RAID level descriptor
:returns: None
"""
# pylint: disable=attribute-defined-outside-init
if value is None:
self._container_raid_level = None
else:
self._container_raid_level = raid.get_raid_level(value)
#
# methods related to device size and disk space requirements
#
def _get_free_disk_space(self):
free_info = self.storage.get_free_space(disks=self.disks)
return sum(d[0] for d in free_info.values())
def _normalize_size(self):
if self.size is None:
self._handle_no_size()
size = self.size
fmt = get_format(self.fstype)
if size < fmt.min_size:
size = fmt.min_size
elif fmt.max_size and size > fmt.max_size:
size = fmt.max_size
if self.size != size:
log.debug("adjusted size from %s to %s to honor format limits",
self.size, size)
self.size = size
def _handle_no_size(self):
""" Set device size so that it grows to the largest size possible. """
if self.size is not None:
return
self.size = self._get_free_disk_space()
if self.device:
self.size += self.device.size
if self.container_size > 0:
self.size = min(self.container_size, self.size)
def _get_total_space(self):
""" Return the total space need for this factory's device/container.
This is used for the size argument to the child factory constructor
and also to construct the size set in PartitionSetFactory.configure.
"""
size = self._get_device_space()
if self.container:
size += self.container.size
if self.device:
size -= self.device.size
return size
def _get_device_space(self):
""" The total disk space required for this device. """
return self.size
def _get_device_size(self):
""" Return the factory device size including container limitations. """
return self.size
def _set_device_size(self):
""" Set the size of a defined factory device. """
pass
#
# methods related to container/parent devices
#
def _get_parent_devices(self):
""" Return the list of parent devices for this factory's device. """
# TODO: maintain something like a state machine to ensure context for
# methods like this one
if self.container:
parents = [self.container]
elif self.child_factory:
parents = self.child_factory.devices
else:
parents = []
return parents
def _get_member_devices(self):
""" Return a list of member devices.
This is only used by classes like lvm and md where there is a set of
member devices, the length of which can affect disk space
requirements (per-member metadata).
We want this to be as up-to-date as is possible.
Our container's parent list is not used here. Prior to configuring
the child factory it is no more accurate than our disk list.
Afterwards, it is no more accurate than the child factory's device
list.
"""
members = self.disks # fallback/default if we're called very early
if self.child_factory:
# the child factory's device list what our container's is based on
members = self.child_factory.devices
return members
@property
def container_list(self):
""" List of containers of the appropriate type for this class. """
return []
# FIXME: This is nuts. Move specifics into the appropriate classes.
def get_container(self, device=None, name=None, allow_existing=False):
""" Return the best choice of container for this factory.
Keyword arguments:
device -- a defined factory device
name -- a specific container name to look for
allow_existing -- whether to allow selection of preexisting
containers
"""
# XXX would it be useful to implement this as a series of fallbacks
# instead of mutually exclusive branches?
if self.device and not device:
device = self.device
if self.container_name and not name:
name = self.container_name
container = None
if device:
if hasattr(device, "vg"):
container = device.vg
elif hasattr(device, "volume"):
container = device.volume
elif hasattr(device, "subvolumes"):
container = device
elif name:
for c in self.storage.devices:
if c.name == name and c in self.container_list:
container = c
break
else:
containers = [c for c in self.container_list
if allow_existing or not c.exists]
if containers:
# XXX All containers should have a "free" attribute
containers.sort(key=lambda c: getattr(c, "freeSpace", c.size),
reverse=True)
container = containers[0]
return container
def _set_container(self):
""" Set this factory's container device. """
self.container = self.get_container(device=self.raw_device,
name=self.container_name)
def _create_container(self):
""" Create the container device required by this factory device. """
parents = self._get_parent_devices()
self.container = self._get_new_container(name=self.container_name,
parents=parents)
self.storage.create_device(self.container)
if self.container_name is None:
self.container_name = self.container.name
def _get_new_container(self, *args, **kwargs):
""" Type-specific container device instantiation. """
pass
def _check_container_size(self):
""" Raise an exception if the container cannot hold its devices. """
pass
def _reconfigure_container(self):
""" Reconfigure a defined container required by this factory device. """
if getattr(self.container, "exists", False):
return
self._set_container_members()
self._set_container_raid_level()
# check that the container is still large enough to contain whatever
# other devices it previously contained
if self.size > 0:
# only do this check if we're not doing post-removal cleanup
self._check_container_size()
def _set_container_members(self):
if not self.child_factory:
return
members = self.child_factory.devices
log.debug("new member set: %s", [d.name for d in members])
log.debug("old member set: %s", [d.name for d in self.container.parents])
for member in self.container.parents[:]:
if member not in members:
self.container.parents.remove(member)
for member in members:
if member not in self.container.parents:
self.container.parents.append(member)
def _set_container_raid_level(self):
pass
#
# properties and methods related to the factory device
#
@property
def raw_device(self):
""" If self.device is encrypted, this is its backing device. """
return self.device.raw_device if self.device else None
@property
def devices(self):
""" A list of this factory's product devices. """
return [self.device]
#
# methods to configure the factory device(s)
#
def _create_device(self):
""" Create the factory device. """
if self.size == Size(0):
# A factory with a size of zero means you're adjusting a container
# after removing a device from it.
return
fmt_args = {}
if self.encrypted:
fstype = "luks"
mountpoint = None
else:
fstype = self.fstype
mountpoint = self.mountpoint
fmt_args = {}
if self.label:
fmt_args["label"] = self.label
if self.device_name:
kwa = {"name": self.device_name}
else:
kwa = {}
# this gets us a size value that takes into account the actual size of
# the container
size = self._get_device_size()
if size <= Size(0):
raise DeviceFactoryError("not enough free space for new device")
parents = self._get_parent_devices()
try:
device = self._get_new_device(parents=parents,
size=size,
fmt_type=fstype,
mountpoint=mountpoint,
fmt_args=fmt_args,
**kwa)
except (StorageError, ValueError) as e:
log.error("device instance creation failed: %s", e)
raise
self.storage.create_device(device)
e = None
try:
self._post_create()
except (StorageError, blockdev.BlockDevError) as e:
log.error("device post-create method failed: %s", e)
else:
if not device.size:
e = StorageError("failed to create device")
if e:
self.storage.destroy_device(device)
raise StorageError(e)
ret = device
if self.encrypted:
fmt_args = {}
if self.label:
fmt_args["label"] = self.label
fmt = get_format(self.fstype,
mountpoint=self.mountpoint,
min_luks_entropy=self.min_luks_entropy,
**fmt_args)
luks_device = LUKSDevice("luks-" + device.name,
parents=[device], fmt=fmt)
self.storage.create_device(luks_device)
ret = luks_device
self.device = ret
def _get_new_device(self, *args, **kwargs):
""" Type-specific device instantiation. """
pass
def _reconfigure_device(self):
""" Reconfigure a defined factory device. """
# We are adjusting a defined device: size, disk set, container
# member encryption, container raid level. The StorageDevice
# instance exists, but the underlying device does not.
self._set_disks()
self._set_raid_level()
self._set_size()
self._set_encryption()
self._set_format()
self._set_name()
def _set_disks(self):
pass
def _set_raid_level(self):
pass
def _set_size(self):
# reset the device's format before allocating partitions, &c
if self.device.format.type != self.fstype:
self.device.format = None
# this is setting the device size based on the factory size and the
# current size of the container
self._set_device_size()
try:
self._post_create()
except (StorageError, blockdev.BlockDevError) as e:
log.error("device post-create method failed: %s", e)
raise
else:
if (self.device.size < self.device.format.min_size or
(self.device.size == self.device.format.min_size and
self.size > self.device.format.min_size)):
raise StorageError("failed to adjust device -- not enough free space in specified disks?")
def _set_format(self):
current_format = self.device.format
if current_format.type != self.fstype:
new_format = get_format(self.fstype,
mountpoint=self.mountpoint,
label=self.label,
exists=False)
self.storage.format_device(self.device, new_format)
else:
if (hasattr(current_format, "mountpoint") and
current_format.mountpoint != self.mountpoint):
current_format.mountpoint = self.mountpoint
if (hasattr(current_format, "label") and
current_format.label != self.label):
current_format.label = self.label
def _set_encryption(self):
# toggle encryption of the leaf device as needed
parent_container = getattr(self.parent_factory, "container", None)
if isinstance(self.device, LUKSDevice) and not self.encrypted:
orig_device = self.device
raw_device = self.raw_device
leaf_format = self.device.format
if parent_container:
parent_container.parents.remove(orig_device)
self.storage.destroy_device(self.device)
self.storage.format_device(self.raw_device, leaf_format)
self.device = raw_device
if parent_container:
parent_container.parents.append(self.device)
elif self.encrypted and not isinstance(self.device, LUKSDevice):
orig_device = self.device
leaf_format = self.device.format
self.storage.format_device(self.device, get_format("luks",
min_luks_entropy=self.min_luks_entropy))
luks_device = LUKSDevice("luks-%s" % self.device.name,
fmt=leaf_format,
parents=self.device)
self.storage.create_device(luks_device)
self.device = luks_device
if parent_container:
parent_container.parents.replace(orig_device, self.device)
def _set_name(self):
if not self.device_name:
self.device_name = self.storage.suggest_device_name(
parent=self.container,
swap=(self.fstype == "swap"),
mountpoint=self.mountpoint)
safe_new_name = self.storage.safe_device_name(self.device_name)
if self.device.name != safe_new_name:
if safe_new_name in self.storage.names:
log.error("not renaming '%s' to in-use name '%s'",
self.device.name, safe_new_name)
return
log.debug("renaming device '%s' to '%s'",
self.device.name, safe_new_name)
self.device.name = safe_new_name
def _post_create(self):
""" Hook for post-creation operations. """
pass
def _get_child_factory_args(self):
return [self.storage, self._get_total_space(), self.disks]
def _get_child_factory_kwargs(self):
return {"fstype": self.child_factory_fstype}
def _set_up_child_factory(self):
if self.child_factory or not self.child_factory_class or \
self.container and self.container.exists:
return
args = self._get_child_factory_args()
kwargs = self._get_child_factory_kwargs()
log.debug("child factory class: %s", self.child_factory_class)
log.debug("child factory args: %s", args)
log.debug("child factory kwargs: %s", kwargs)
factory = self.child_factory_class(*args, **kwargs) # pylint: disable=not-callable
self.child_factory = factory
factory.parent_factory = self
def configure(self):
""" Configure the factory's device(s).
Keyword arguments:
An example of the parent_factory is the LVMOnMDFactory creating and
then using an MDFactory to manage the volume group's single MD PV.
Another example is the MDFactory creating and then using a
PartitionSetFactory to manage the set of member partitions.
"""
log_method_call(self, parent_factory=self.parent_factory)
if self.parent_factory is None:
# only do the backup/restore error handling in the top-level factory
self._save_devicetree()
try:
self._configure()
except Exception as e:
log.error("failed to configure device factory: %s", e)
if self.parent_factory is None:
# only do the backup/restore error handling at the top-level
self._revert_devicetree()
if not isinstance(e, (StorageError, OverflowError)):
e = DeviceFactoryError(str(e))
raise(e)
def _configure(self):
self._set_container()
if self.container and self.container.exists:
self.disks = self.container.disks
self._normalize_size()
self._set_up_child_factory()
# Configure any devices this device will use as building blocks, except
# for type-specific container devices. In the LVM example, this will
# configure the PVs.
if self.child_factory:
self.child_factory.configure()
# Make sure that there are enough disks involved for any specified
# device or container raid level.
for level_attr in ["raid_level", "container_raid_level"]:
level = getattr(self, level_attr, None)
if level is None:
continue
disks = set(d for m in self._get_member_devices() for d in m.disks)
if len(disks) < level.min_members:
raise DeviceFactoryError("Not enough disks for %s" % level)
# Configure any type-specific container device. The obvious example of
# this is the LVMFactory, which will configure its VG in this step.
if self.container:
self._reconfigure_container()
else:
self._create_container()
if self.container and hasattr(self.container, "size_policy") and \
not self.container.exists:
self.container.size_policy = self.container_size
# Configure this factory's leaf device, eg, for LVMFactory: the LV.
if self.device:
self._reconfigure_device()
else:
self._create_device()
#
# methods for error recovery
#
def _save_devicetree(self):
_blivet_copy = self.storage.copy()
self.__devices = _blivet_copy.devicetree._devices
self.__actions = _blivet_copy.devicetree._actions
self.__names = _blivet_copy.devicetree.names
self.__roots = _blivet_copy.roots
def _revert_devicetree(self):
self.storage.devicetree._devices = self.__devices
self.storage.devicetree._actions = self.__actions
self.storage.devicetree.names = self.__names
self.storage.roots = self.__roots
class PartitionFactory(DeviceFactory):
""" Factory class for creating a partition. """
#
# methods related to device size and disk space requirements
#
def _get_base_size(self):
if self.device:
min_format_size = self.device.format.min_size
else:
min_format_size = get_format(self.fstype).min_size
# min_format_size may be None here, make sure it is a number
min_format_size = min_format_size or 0
if self.encrypted:
min_format_size += get_format("luks").min_size
return max(Size("1MiB"), min_format_size)
def _get_device_size(self):
""" Return the factory device size including container limitations. """
return max(self._get_base_size(), self.size)
def _set_device_size(self):
""" Set the size of a defined factory device. """
if self.raw_device and self.size != self.raw_device.size:
log.info("adjusting device size from %s to %s",
self.raw_device.size, self.size)
base_size = self._get_base_size()
size = self._get_device_size()
self.raw_device.req_base_size = base_size
self.raw_device.req_size = base_size
self.raw_device.req_max_size = size
self.raw_device.req_grow = size > base_size
#
# methods related to container/parent devices
#
def get_container(self, device=None, name=None, allow_existing=False):
return None
def _create_container(self):
pass
def _get_parent_devices(self):
""" Return the list of parent devices for this factory's device. """
return self.disks
#
# methods to configure the factory device
#
def _get_new_device(self, *args, **kwargs):
""" Create and return the factory device as a StorageDevice. """
max_size = kwargs.pop("size")
kwargs["size"] = self._get_base_size()
device = self.storage.new_partition(*args,
grow=True, maxsize=max_size,
**kwargs)
return device
def _set_disks(self):
self.raw_device.req_disks = self.disks[:]
def _set_name(self):
pass
def _post_create(self):
try:
do_partitioning(self.storage)
except (StorageError, blockdev.BlockDevError) as e:
log.error("failed to allocate partitions: %s", e)
raise
class PartitionSetFactory(PartitionFactory):
""" Factory for creating a set of related partitions. """
def __init__(self, storage, size, disks, fstype=None, encrypted=False,
devices=None):
""" Create a new DeviceFactory instance.
Arguments:
storage a Blivet instance
size the desired size for the device
disks the set of disks to use
Keyword args:
fstype filesystem type
encrypted whether to encrypt (boolean)
devices an initial set of devices
"""
super(PartitionSetFactory, self).__init__(storage, size, disks,
fstype=fstype,
encrypted=encrypted)
self._devices = []
if devices:
self._devices = devices
@property
def devices(self):
return self._devices