-
Notifications
You must be signed in to change notification settings - Fork 25
/
blivet_utils.py
1571 lines (1207 loc) · 65.4 KB
/
blivet_utils.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
# utils.py
# Classes working directly with blivet instance
#
# Copyright (C) 2014 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): Vojtech Trefny <vtrefny@redhat.com>
#
# ---------------------------------------------------------------------------- #
import blivet
from blivet.devices import PartitionDevice, LUKSDevice, LVMVolumeGroupDevice, BTRFSVolumeDevice, BTRFSSubVolumeDevice, MDRaidArrayDevice
from blivet.formats import DeviceFormat
from blivet.size import Size
from blivet.devicelibs.crypto import LUKS_METADATA_SIZE
from .communication.proxy_utils import ProxyDataContainer
import traceback
import parted
import subprocess
from .logs import set_logging, log_utils_call
from .i18n import _
from . import __version__
# ---------------------------------------------------------------------------- #
PARTITION_TYPE = {"primary": parted.PARTITION_NORMAL,
"logical": parted.PARTITION_LOGICAL,
"extended": parted.PARTITION_EXTENDED}
# ---------------------------------------------------------------------------- #
def lsblk():
p = subprocess.run(["lsblk", "-a", "-o", "+FSTYPE,LABEL,UUID,MOUNTPOINT"],
stdout=subprocess.PIPE, check=False)
return p.stdout.decode()
class FreeSpaceDevice(object):
""" Special class to represent free space on disk (device)
(blivet doesn't have class/device to represent free space)
"""
def __init__(self, free_size, dev_id, start, end, parents, logical=False):
"""
:param free_size: size of free space
:type free_size: blivet.size.Size
:param start: start block
:type end: int
:param end: end block
:type end: int
:param parents: list of parent devices
:type parents: blivet.devices.lib.ParentList
:param logical: is this free space inside extended partition
:type logical: bool
"""
self.name = _("free space")
self.size = free_size
self.id = dev_id
self.start = start
self.end = end
self.is_logical = logical
self.is_extended = False
self.is_primary = not logical
self.is_free_space = True
self.is_disk = False
self.direct = False
self._resizable = False
self.format_immutable = False
self.format = DeviceFormat(exists=True)
self.type = "free space"
self.children = []
self.parents = blivet.devices.lib.ParentList(items=parents)
self.disk = self._get_disk()
def _get_disk(self):
parents = self.parents
while parents:
if parents[0].is_disk:
return parents[0]
parents = parents[0].parents
return None
@property
def protected(self):
return self.parents[0].protected
@property
def is_empty_disk(self):
return len(self.parents) == 1 and self.parents[0].type in ("disk", "nvdimm") and \
not self.parents[0].children and self.parents[0].format.type and \
self.parents[0].format.type not in ("iso9660",)
@property
def is_uninitialized_disk(self):
return len(self.parents) == 1 and self.parents[0].type in ("disk", "nvdimm") and \
not self.parents[0].children and not self.parents[0].format.type
@property
def is_free_region(self):
return not (self.is_empty_disk or self.is_uninitialized_disk)
def __str__(self):
return "existing " + str(self.size) + " free space"
class BlivetUtils(object):
""" Class with utils directly working with blivet itselves
"""
installer_mode = False
def __init__(self, ignored_disks=None, exclusive_disks=None, flags=None):
self.ignored_disks = ignored_disks
self.exclusive_disks = exclusive_disks
self._resizable_filesystems = None
# create our log now, creating blivet.Blivet instance may fail
# and log some basic information -- version and lsblk output
_log_file, self.log = set_logging(component="blivet-gui-utils")
self.log.info("BlivetUtils, version: %s", __version__)
self.log.info("lsblk output:\n%s", lsblk())
self.storage = blivet.Blivet()
# logging
set_logging(component="blivet")
set_logging(component="program")
# ignore zram devices
blivet.udev.ignored_device_names.append(r"^zram")
# set blivet flags
if flags:
self._set_blivet_flags(flags)
blivet.flags.flags.allow_online_fs_resize = True
self.blivet_reset()
self._update_min_sizes_info()
def _set_blivet_flags(self, flags):
for flag, value in flags.items():
self.log.info("setting blivet flag '%s' to '%s'", flag, value)
setattr(blivet.flags.flags, flag, value)
@property
def resizable_filesystems(self):
if self._resizable_filesystems is None:
self._resizable_filesystems = []
for cls in blivet.formats.device_formats.values():
if cls._resizable:
self._resizable_filesystems.append(cls._type)
return self._resizable_filesystems
def log_debug(self, message, user_input):
""" Log message to the blivet-gui-utils log
"""
log_utils_call(log=self.log, message=message, user_input=user_input)
def get_disks(self):
""" Return list of all disk devices on current system
:returns: list of all "disk" devices
:rtype: list
"""
return [device for device in self.storage.disks if device.type != "mdarray"]
def get_group_devices(self):
""" Return list of LVM2 Volume Group devices
:returns: list of LVM2 VG devices
:rtype: list
"""
devices = {}
devices["lvm"] = self.storage.vgs
devices["raid"] = self.storage.mdarrays
devices["btrfs"] = self.storage.btrfs_volumes
return devices
def get_free_info(self):
""" Get list of free 'devices' (PVs and disk regions) that can be used
as parents for newly added devices
"""
free_devices = []
# free pvs
for pv in self.storage.pvs:
if not pv.children:
free_devices.append(("lvmpv", FreeSpaceDevice(pv.size, self.storage.next_id, None, None, [pv])))
# free disks and disk regions
for disk in self.storage.disks:
if disk.format.type not in ("disklabel",):
continue
free_space = blivet.partitioning.get_free_regions([disk], align=True)
for free in free_space:
free_size = blivet.size.Size(free.length * free.device.sectorSize)
if free_size > blivet.size.Size("2 MiB"): # skip very small free regions
free_devices.append(("free", FreeSpaceDevice(free_size, self.storage.next_id, free.start, free.end, [disk])))
return free_devices
def get_group_device(self, blivet_device):
""" Get 'group' device based on underlying device (lvmpv/btrfs/mdmember/luks partition)
"""
# already a group device
if blivet_device.type in ("btrfs volume", "lvmvg", "mdarray"):
return blivet_device
# encrypted group device -> get the luks device instead
if blivet_device.format.type in ("luks", "integrity"):
blivet_device = self.get_luks_device(blivet_device)
if not blivet_device.format or blivet_device.format.type not in ("lvmpv", "btrfs", "mdmember", "luks"):
return None
if len(blivet_device.children) != 1:
return None
group_device = blivet_device.children[0]
return group_device
def get_luks_device(self, blivet_device):
""" Get luks or integrity device based on underlying partition
"""
if not blivet_device.format or blivet_device.format.type not in ("luks", "integrity"):
return None
if len(blivet_device.children) != 1:
return None
if blivet_device.children[0].type == "integrity/dm-crypt" and blivet_device.children[0].children:
# LUKS + integrity
luks_device = blivet_device.children[0].children[0]
else:
# only integrity device
luks_device = blivet_device.children[0]
return luks_device
def get_children(self, blivet_device):
""" Get partitions (children) of selected device
:param blivet_device: blivet device
:type blivet_device: blivet.device.Device
:returns: list of child devices
:rtype: list of blivet.device.Device
"""
if not blivet_device:
return []
childs = blivet_device.children
if blivet_device.type == "lvmvg" and blivet_device.free_space > blivet.size.Size(0):
childs.append(FreeSpaceDevice(blivet_device.free_space, self.storage.next_id, None, None, [blivet_device]))
return childs
def get_disk_children(self, blivet_device):
if not blivet_device.is_disk:
raise TypeError("device %s is not a disk" % blivet_device.name)
if blivet_device.is_disk and not blivet_device.format.type:
if blivet_device.format.name != "Unknown":
# disk with unsupported format
return ProxyDataContainer(partitions=[blivet_device], extended=None, logicals=None)
else:
# empty disk without disk label
partitions = [FreeSpaceDevice(blivet_device.size, self.storage.next_id, 0, blivet_device.current_size, [blivet_device], False)]
return ProxyDataContainer(partitions=partitions, extended=None, logicals=None)
if blivet_device.format and blivet_device.format.type not in ("disklabel", "btrfs", "luks", None):
# special occasion -- raw device format
return ProxyDataContainer(partitions=[blivet_device], extended=None, logicals=None)
if blivet_device.format and blivet_device.format.type == "btrfs" and blivet_device.children:
# btrfs volume on raw device
btrfs_volume = blivet_device.children[0]
return ProxyDataContainer(partitions=[btrfs_volume], extended=None, logicals=None)
if blivet_device.format and blivet_device.format.type in ("luks", "integrity"):
if blivet_device.children:
luks = self.get_luks_device(blivet_device)
else:
luks = blivet_device
return ProxyDataContainer(partitions=[luks], extended=None, logicals=None)
partitions = blivet_device.children
# extended partition
extended = self._get_extended_partition(blivet_device, partitions)
# logical partitions + 'logical' free space
logicals = self._get_logical_partitions(blivet_device, partitions) + self._get_free_logical(blivet_device)
# primary partitions + 'primary' free space
primaries = self._get_primary_partitions(blivet_device, partitions) + self._get_free_primary(blivet_device)
def _sort_partitions(part): # FIXME: move to separate 'utils' file
if part.type not in ("free space", "partition"):
raise ValueError
if part.type == "free space":
return part.start
else:
return part.parted_partition.geometry.start
if extended:
partitions = sorted(primaries + [extended], key=_sort_partitions)
else:
partitions = sorted(primaries, key=_sort_partitions)
logicals = sorted(logicals, key=_sort_partitions)
return ProxyDataContainer(partitions=partitions, extended=extended, logicals=logicals)
def _get_extended_partition(self, blivet_device, partitions=None):
if not blivet_device.is_disk or not blivet_device.format or blivet_device.format.type != "disklabel":
return None
extended = None
if partitions is None:
partitions = blivet_device.children
for part in partitions:
if part.type == "partition" and part.is_extended:
extended = part
break # only one extended partition
return extended
def _get_logical_partitions(self, blivet_device, partitions=None):
if not blivet_device.is_disk or not blivet_device.format or blivet_device.format.type != "disklabel":
return []
logicals = []
if partitions is None:
partitions = blivet_device.children
for part in partitions:
if part.type == "partition" and part.is_logical:
logicals.append(part)
return logicals
def _get_primary_partitions(self, blivet_device, partitions=None):
if not blivet_device.is_disk or not blivet_device.format or blivet_device.format.type != "disklabel":
return []
primaries = []
if partitions is None:
partitions = blivet_device.children
for part in partitions:
if part.type == "partition" and part.is_primary:
primaries.append(part)
return primaries
def _get_free_logical(self, blivet_device):
if not blivet_device.is_disk or not blivet_device.format or blivet_device.format.type != "disklabel":
return []
extended = blivet_device.format.extended_partition
if not extended:
return []
free_logical = []
free_regions = blivet.partitioning.get_free_regions([blivet_device], align=True)
for region in free_regions:
region_size = blivet.size.Size(region.length * region.device.sectorSize)
if region_size < blivet.size.Size("4 MiB"):
continue
if region.start >= extended.geometry.start and \
region.end <= extended.geometry.end:
free_logical.append(FreeSpaceDevice(region_size, self.storage.next_id, region.start, region.end, [blivet_device], True))
return free_logical
def _get_free_primary(self, blivet_device):
if not blivet_device.is_disk or not blivet_device.format or blivet_device.format.type != "disklabel":
return []
free_primary = []
extended = blivet_device.format.extended_partition
free_regions = blivet.partitioning.get_free_regions([blivet_device], align=True)
for region in free_regions:
region_size = blivet.size.Size(region.length * region.device.sectorSize)
if region_size < blivet.size.Size("4 MiB"):
continue
if extended and not (region.start >= extended.geometry.start and
region.end <= extended.geometry.end):
free_primary.append(FreeSpaceDevice(region_size, self.storage.next_id, region.start, region.end, [blivet_device], False))
elif not extended:
free_primary.append(FreeSpaceDevice(region_size, self.storage.next_id, region.start, region.end, [blivet_device], False))
return free_primary
def get_roots(self, blivet_device):
""" Get list of parents for selected device with its structure """
roots = set([])
if blivet_device.type == "lvmvg":
for pv in blivet_device.pvs:
roots.add(self._get_root_device(pv))
elif blivet_device.type in ("mdarray", "btrfs volume"):
for member in blivet_device.members:
roots.add(self._get_root_device(member))
elif blivet_device.type in ("luks/dm-crypt", "integrity/dm-crypt"):
roots.add(self._get_root_device(blivet_device.raw_device))
return roots
def _get_root_device(self, blivet_device):
if blivet_device.is_disk:
return blivet_device
elif blivet_device.type in ("mdarray",):
return blivet_device
elif blivet_device.type in ("lvmlv", "lvmthinlv"):
return blivet_device.vg
elif blivet_device.parents and blivet_device.parents[0].type in ("mdarray", "mdmember"):
return blivet_device.parents[0]
elif blivet_device.type in ("luks/dm-crypt", "integrity/dm-crypt"):
return self._get_root_device(blivet_device.raw_device)
# loop devices don't have the "disk" property so just return its
# parent (FileDevice instance)
elif blivet_device.type == "loop":
return blivet_device.parents[0]
else:
return blivet_device.disk
def get_free_device(self, blivet_device):
""" Get FreeSpaceDevice object for selected device (e.g. VG) """
# VG -- just get free space in it
if blivet_device.type == "lvmvg":
return FreeSpaceDevice(free_size=blivet_device.free_space,
dev_id=self.storage.next_id,
start=None, end=None,
parents=[blivet_device])
# LV -- we are adding a snapshot --> we need free space in the VG
elif blivet_device.type == "lvmlv":
return FreeSpaceDevice(free_size=blivet_device.vg.free_space,
dev_id=self.storage.next_id,
start=None, end=None,
parents=[blivet_device])
# Thin Pool -- size of the thin LVs/snapshots is limited by the size of the pool
elif blivet_device.type == "lvmthinpool":
return FreeSpaceDevice(free_size=blivet_device.size,
dev_id=self.storage.next_id,
start=None, end=None,
parents=[blivet_device])
# Btrfs Volume -- size of the subvolumes/snapshots is limited by the size of the volume
elif blivet_device.type == "btrfs volume":
return FreeSpaceDevice(free_size=blivet_device.size,
dev_id=self.storage.next_id,
start=None, end=None,
parents=[blivet_device])
# something else, just return size of the device and hope for the best
else:
return FreeSpaceDevice(free_size=blivet_device.size,
dev_id=self.storage.next_id,
start=None, end=None,
parents=[blivet_device])
def _delete_disk_label(self, disk_device):
""" Delete current disk label
:param disk_device: blivet device
:type disk_device: blivet.Device
"""
try:
if disk_device.format.exists:
disk_device.format.teardown()
action = blivet.deviceaction.ActionDestroyFormat(disk_device)
self.storage.devicetree.actions.add(action)
except Exception as e: # pylint: disable=broad-except
return ProxyDataContainer(success=False, actions=None, message=None, exception=e,
traceback=traceback.format_exc())
return ProxyDataContainer(success=True, actions=[action], message=None, exception=None, traceback=None)
def _delete_format(self, blivet_device):
actions = []
try:
if not blivet_device.format_immutable:
ac_fmt = blivet.deviceaction.ActionDestroyFormat(blivet_device)
self.storage.devicetree.actions.add(ac_fmt)
actions.append(ac_fmt)
except Exception as e: # pylint: disable=broad-except
return ProxyDataContainer(success=False, actions=None, message=None, exception=e,
traceback=traceback.format_exc())
return ProxyDataContainer(success=True, actions=actions, message=None, exception=None,
traceback=None)
def _delete_device(self, blivet_device):
actions = []
if blivet_device.children:
for device in blivet_device.children:
res = self._delete_device(device)
if not res.success:
return res
else:
actions.extend(res.actions)
try:
if not blivet_device.format_immutable:
ac_fmt = blivet.deviceaction.ActionDestroyFormat(blivet_device)
self.storage.devicetree.actions.add(ac_fmt)
actions.append(ac_fmt)
ac_dev = blivet.deviceaction.ActionDestroyDevice(blivet_device)
self.storage.devicetree.actions.add(ac_dev)
actions.append(ac_dev)
except Exception as e: # pylint: disable=broad-except
return ProxyDataContainer(success=False, actions=None, message=None, exception=e,
traceback=traceback.format_exc())
return ProxyDataContainer(success=True, actions=actions, message=None, exception=None,
traceback=None)
def delete_device(self, blivet_device, delete_parents):
""" Delete device
:param blivet_device: blivet device
:type blivet_device: blivet.Device
:param delete_parents: delete parent devices too?
:type delete_parents: bool
"""
log_msg = "Deleting device '%s':\n" % blivet_device.name
log_utils_call(log=self.log, message=log_msg,
user_input={"device": blivet_device, "delete_parents": delete_parents})
actions = []
if blivet_device.is_disk:
result = self._delete_disk_label(blivet_device)
return result
result = self._delete_device(blivet_device)
if not result.success:
return result
else:
actions.extend(result.actions)
# for encrypted partitions/lvms delete the luks-formatted partition too
if blivet_device.type in ("luks/dm-crypt", "integrity/dm-crypt"):
for parent in blivet_device.parents:
result = self._delete_device(parent)
if not result.success:
return result
else:
actions.extend(result.actions)
# destroy action for MD array is no-op, the array is destroyed by removing
# the mdmember format from the parents
if blivet_device.type == "mdarray":
for parent in blivet_device.parents:
if parent.format.exists:
try:
parent.format.teardown()
except Exception as e: # pylint: disable=broad-except
return ProxyDataContainer(success=False, actions=None, message=None, exception=e,
traceback=traceback.format_exc())
result = self._delete_format(parent)
if not result.success:
return result
else:
actions.extend(result.actions)
# for btrfs volumes delete parents partition after deleting volume
if blivet_device.type in ("btrfs volume", "mdarray", "lvmvg") and delete_parents:
for parent in blivet_device.parents:
result = self.delete_device(parent, delete_parents=False)
if not result.success:
return result
else:
actions.extend(result.actions)
return ProxyDataContainer(success=True, actions=actions, message=None, exception=None, traceback=None)
def _has_snapshots(self, blivet_device):
for lvs in blivet_device.vg.children:
if lvs.is_snapshot_lv and lvs.origin == blivet_device:
return True
return False
def _update_min_sizes_info(self):
""" Update information of minimal size for resizable devices
"""
for device in self.storage.devices:
if device.type in ("partition", "lvmlv", "lvmpv", "luks/dm-crypt"):
# skip mounted devices
if hasattr(device.format, "system_mountpoint") and device.format.system_mountpoint:
continue
if device.format.type and hasattr(device.format, "update_size_info"):
try:
device.format.update_size_info()
except blivet.errors.FSError:
pass
def device_resizable(self, blivet_device):
""" Is given device resizable
:param blivet_device: blivet device
:type blivet_device: blivet.Device
:returns: device resizable, min_size, max_size, size
:rtype: tuple
"""
if not blivet_device._resizable:
msg = _("Resizing of {type} devices is currently not supported").format(type=blivet_device.type)
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif blivet_device.protected:
msg = _("Protected devices cannot be resized")
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif blivet_device.format_immutable:
msg = _("Immutable formats cannot be resized")
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif blivet_device.children:
msg = _("Devices with children cannot be resized")
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif not blivet_device.format.type:
# unformatted devices are not resizable (except extended partitions)
if (blivet_device.type == "partition" and blivet_device.is_extended and (blivet_device.max_size > blivet_device.size or
blivet_device.min_size < blivet_device.size)):
return ProxyDataContainer(resizable=True, error=None, min_size=blivet_device.min_size,
max_size=blivet_device.max_size)
else:
msg = _("Unformatted devices are not resizable")
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif blivet_device.format.type not in self.resizable_filesystems:
# unfortunately we can't use format._resizable here because blivet uses it to both mark
# formats as not resizable and force users to call update_size_info on resizable formats
msg = _("Resizing of {type} format is currently not supported").format(type=blivet_device.format.type)
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif not blivet_device.format._resize.available:
msg = _("Tools for resizing format {type} are not available.").format(type=blivet_device.format.type)
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif not blivet_device.format.exists:
# TODO: we could support this by simply changing formats target size but we'd need
# a workaround for the missing action
msg = _("Formats scheduled to be created cannot be resized")
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif blivet_device.format.type and not hasattr(blivet_device.format, "update_size_info"):
msg = _("Format {type} doesn't support updating its size limit information").format(format_type=blivet_device.format.type)
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif hasattr(blivet_device.format, "system_mountpoint") and blivet_device.format.system_mountpoint and \
not (blivet_device.format._resize_support & blivet.formats.fslib.FSResize.ONLINE_GROW or
blivet_device.format._resize_support & blivet.formats.fslib.FSResize.ONLINE_SHRINK):
msg = _("Mounted devices cannot be resized")
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif blivet_device.type in ("lvmlv",) and self._has_snapshots(blivet_device):
msg = _("Logical Volumes with snapshots cannot be resized.")
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
elif blivet_device.type == "luks/dm-crypt" and blivet_device.raw_device.format.luks_version == "luks2":
msg = _("Resizing of LUKS2 devices is currently not supported.")
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
if not self.installer_mode:
try:
blivet_device.format.update_size_info()
if blivet_device.type == "luks/dm-crypt":
blivet_device.raw_device.format.update_size_info()
except blivet.errors.FSError as e:
msg = _("Failed to update filesystem size info: {error}").format(error=str(e))
return ProxyDataContainer(resizable=False, error=msg,
min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
if blivet_device.resizable and blivet_device.format.resizable:
if blivet_device.type == "luks/dm-crypt":
min_size = blivet_device.min_size
max_size = blivet_device.raw_device.max_size - LUKS_METADATA_SIZE
else:
min_size = blivet_device.min_size
max_size = blivet_device.max_size
return ProxyDataContainer(resizable=True, error=None, min_size=min_size,
max_size=max_size)
else:
if not blivet_device.resizable:
msg = _("Device is not resizable.")
elif not blivet_device.format.resizable:
msg = _("Format is not resizable after updating its size limit information.")
return ProxyDataContainer(resizable=False, error=msg, min_size=blivet.size.Size("1 MiB"),
max_size=blivet_device.size)
def format_device(self, user_input):
log_msg = "Formatting device '%s'\n" % user_input.edit_device.name
log_utils_call(log=self.log, message=log_msg,
user_input=user_input)
fmt_actions = []
fmt_actions.append(blivet.deviceaction.ActionDestroyFormat(user_input.edit_device))
if user_input.filesystem:
fmt_actions.extend(self._create_format(user_input, user_input.edit_device))
try:
for ac in fmt_actions:
self.storage.devicetree.actions.add(ac)
return ProxyDataContainer(success=True, actions=fmt_actions, message=None, exception=None, traceback=None)
except Exception as e: # pylint: disable=broad-except
return ProxyDataContainer(success=False, actions=None, message=None, exception=e,
traceback=traceback.format_exc())
def resize_device(self, user_input):
device = user_input.edit_device
log_msg = "Resizing device '%s'\n" % device.name
log_utils_call(log=self.log, message=log_msg,
user_input=user_input)
if not user_input.resize or user_input.size == device.size:
return ProxyDataContainer(success=True, actions=None, message=None, exception=None, traceback=None)
resize_actions = []
# align size first
if device.type == "partition":
aligned_size = device.align_target_size(user_input.size)
elif device.type == "luks/dm-crypt":
aligned_size = device.raw_device.align_target_size(user_input.size)
else:
aligned_size = user_input.size
# resize format
if device.format.resizable:
resize_actions.append(blivet.deviceaction.ActionResizeFormat(device, aligned_size))
# resize device
if device.type == "luks/dm-crypt":
resize_actions.append(blivet.deviceaction.ActionResizeDevice(device, aligned_size))
resize_actions.append(blivet.deviceaction.ActionResizeFormat(device.raw_device, aligned_size))
resize_actions.append(blivet.deviceaction.ActionResizeDevice(device.raw_device, aligned_size + LUKS_METADATA_SIZE))
else:
resize_actions.append(blivet.deviceaction.ActionResizeDevice(device, aligned_size))
# reverse order if grow
if aligned_size > device.current_size:
resize_actions.reverse()
try:
for ac in resize_actions:
self.storage.devicetree.actions.add(ac)
blivet.partitioning.do_partitioning(self.storage)
return ProxyDataContainer(success=True, actions=resize_actions, message=None, exception=None, traceback=None)
except Exception as e: # pylint: disable=broad-except
return ProxyDataContainer(success=False, actions=None, message=None, exception=e,
traceback=traceback.format_exc())
def relabel_format(self, user_input):
log_msg = "Setting format label for '%s'\n" % user_input.edit_device.name
log_utils_call(log=self.log, message=log_msg,
user_input=user_input)
label_ac = blivet.deviceaction.ActionConfigureFormat(device=user_input.edit_device,
attr="label",
new_value=user_input.label)
try:
self.storage.devicetree.actions.add(label_ac)
except Exception as e: # pylint: disable=broad-except
return ProxyDataContainer(success=False, actions=None, message=None, exception=e,
traceback=traceback.format_exc())
else:
return ProxyDataContainer(success=True, actions=[label_ac], message=None,
exception=None, traceback=None)
def edit_lvmvg_device(self, user_input):
""" Edit LVM Volume group
"""
log_msg = "Editing parents for LVM volume group '%s'\n" % user_input.edit_device.name
log_utils_call(log=self.log, message=log_msg,
user_input=user_input)
actions = []
if user_input.action_type == "add":
for parent in user_input.parents_list:
result = self._add_lvmvg_parent(user_input.edit_device, parent)
if result.success:
actions.extend(result.actions)
else:
return result
elif user_input.action_type == "remove":
for parent in user_input.parents_list:
result = self._remove_lvmvg_parent(user_input.edit_device, parent)
if result.success:
actions.extend(result.actions)
else:
return result
return ProxyDataContainer(success=True, actions=actions, message=None, exception=None, traceback=None)
def _pick_device_name(self, name, parent_device=None, snapshot=False):
""" Pick name for device.
If user chose a name, check it and (if necessary) change it
:param name: name selected by user
:type name: str
:param parent_device: parent device
:type parent_device: blivet.Device
:returns: new (valid) name
:rtype: str
"""
if not name:
if parent_device:
# parent name is part of the child name only on LVM
if parent_device.type == "lvmvg":
name = self.storage.suggest_device_name(parent=parent_device, swap=False)
else:
name = self.storage.suggest_device_name(swap=False)
elif snapshot:
name = self.storage.suggest_device_name(parent=parent_device, swap=False, prefix="snapshot")
else:
name = self.storage.suggest_container_name()
else:
# if name exists add -XX suffix
if name in self.storage.names or (parent_device and parent_device.name + "-" + name in self.storage.names):
for i in range(100):
if name + "-" + str(i) not in self.storage.names:
name = name + "-" + str(i)
break
# if still exists let blivet pick it
if name in self.storage.names:
name = self._pick_device_name(name=None, parent_device=parent_device)
return name
def _create_format(self, user_input, device):
fmt_type = user_input.filesystem
if fmt_type == "btrfs":
actions = self._create_btrfs_format(user_input, device)
return actions
if fmt_type is not None:
if fmt_type == "ntfs":
fmt_options = "-f"
else:
fmt_options = ""
new_fmt = blivet.formats.get_format(fmt_type=user_input.filesystem,
label=user_input.label,
mountpoint=user_input.mountpoint,
create_options=fmt_options)
return [blivet.deviceaction.ActionCreateFormat(device, new_fmt)]
def _create_btrfs_format(self, user_input, device):
actions = []
# format the device to btrfs
btrfs_fmt = blivet.formats.get_format(fmt_type="btrfs")
actions.append(blivet.deviceaction.ActionCreateFormat(device, btrfs_fmt))
if getattr(user_input, "create_volume", True):
device.format = btrfs_fmt
new_btrfs = BTRFSVolumeDevice(parents=[device])
new_btrfs.format = blivet.formats.get_format("btrfs", label=user_input.label, mountpoint=user_input.mountpoint)
actions.append(blivet.deviceaction.ActionCreateDevice(new_btrfs))
return actions
def _align_partition(self, user_input):
if hasattr(user_input, "advanced"):
partition_type = user_input.advanced["parttype"] or "primary"
else:
partition_type = "primary"
start = user_input.size_selection.parents[0].free_space.start
end = user_input.size_selection.parents[0].free_space.end
size = user_input.size_selection.total_size
disk = user_input.size_selection.parents[0].parent_device
size_sectors = size // disk.format.sector_size
if partition_type == "logical":
extended = disk.format.extended_partition
if not extended:
# this should never happen
raise ValueError("Trying to add a logical partition to a disk without extended partition.")
if disk.format.logical_partitions:
# start 1 MiB after last logical partition
last_logical = sorted(disk.format.logical_partitions, key=lambda x: x.geometry.start)[-1]
start = int((last_logical.geometry.end) + (Size("1 MiB") / disk.format.sector_size))
else:
# first logical partition -- start 1 MiB after extended partition start
start = int((extended.geometry.start) + (Size("1 MiB") / disk.format.sector_size))
# align the start sector up
constraint = disk.format.parted_device.optimalAlignedConstraint
start = constraint.startAlign.alignUp(constraint.startRange, start)
# we moved start of the partition, it's possible we don't have enough free space now
if start + size_sectors > end:
size_sectors -= ((start + size_sectors) - end)
size = size_sectors * disk.format.sector_size
# align total size for the disklabel