-
Notifications
You must be signed in to change notification settings - Fork 345
/
custom_storage.py
1890 lines (1508 loc) · 71.9 KB
/
custom_storage.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
#
# Custom partitioning classes.
#
# Copyright (C) 2012-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.
#
# TODO:
# - Deleting an LV is not reflected in available space in the bottom left.
# - this is only true for preexisting LVs
# - Device descriptions, suggested sizes, etc. should be moved out into a support file.
# - Tabbing behavior in the accordion is weird.
# - Implement striping and mirroring for LVM.
# - Activating reformat should always enable resize for existing devices.
import copy
from dasbus.client.proxy import get_object_path
from dasbus.structure import compare_data
from dasbus.typing import unwrap_variant
from pyanaconda.anaconda_loggers import get_module_logger
from pyanaconda.core.configuration.anaconda import conf
from pyanaconda.core.constants import THREAD_EXECUTE_STORAGE, THREAD_STORAGE, \
SIZE_UNITS_DEFAULT, PARTITIONING_METHOD_INTERACTIVE
from pyanaconda.core.i18n import _, N_, CP_, C_
from pyanaconda.modules.common.constants.objects import BOOTLOADER, DISK_SELECTION
from pyanaconda.modules.common.constants.services import STORAGE
from pyanaconda.modules.common.structures.storage import OSData, DeviceFormatData, DeviceData
from pyanaconda.modules.common.structures.validation import ValidationReport
from pyanaconda.modules.common.task import sync_run_task
from pyanaconda.modules.common.errors.configuration import BootloaderConfigurationError, \
StorageConfigurationError
from pyanaconda.modules.common.structures.partitioning import PartitioningRequest
from pyanaconda.modules.common.structures.device_factory import DeviceFactoryRequest, \
DeviceFactoryPermissions
from pyanaconda.product import productName, productVersion
from pyanaconda.ui.lib.storage import reset_bootloader, create_partitioning, filter_disks_by_names
from pyanaconda.core.storage import DEVICE_TYPE_UNSUPPORTED, DEVICE_TEXT_MAP, \
MOUNTPOINT_DESCRIPTIONS, NAMED_DEVICE_TYPES, CONTAINER_DEVICE_TYPES, device_type_from_autopart, \
PROTECTED_FORMAT_TYPES, DEVICE_TYPE_BTRFS, DEVICE_TYPE_MD, Size
from pyanaconda.threading import threadMgr
from pyanaconda.ui.categories.system import SystemCategory
from pyanaconda.ui.communication import hubQ
from pyanaconda.ui.gui.spokes import NormalSpoke
from pyanaconda.ui.gui.spokes.lib.accordion import MountPointSelector, Accordion, Page, \
CreateNewPage, UnknownPage
from pyanaconda.ui.gui.spokes.lib.cart import SelectedDisksDialog
from pyanaconda.ui.gui.spokes.lib.custom_storage_helpers import get_size_from_entry, \
get_selected_raid_level, get_default_raid_level, get_container_type, AddDialog,\
ConfirmDeleteDialog, DisksDialog, ContainerDialog, NOTEBOOK_LABEL_PAGE, NOTEBOOK_DETAILS_PAGE,\
NOTEBOOK_LUKS_PAGE, NOTEBOOK_UNEDITABLE_PAGE, NOTEBOOK_INCOMPLETE_PAGE, NEW_CONTAINER_TEXT,\
CONTAINER_TOOLTIP, get_supported_device_raid_levels, generate_request_description
from pyanaconda.ui.gui.spokes.lib.passphrase import PassphraseDialog
from pyanaconda.ui.gui.spokes.lib.refresh import RefreshDialog
from pyanaconda.ui.gui.spokes.lib.summary import ActionSummaryDialog
from pyanaconda.ui.gui.utils import setViewportBackground, fancy_set_sensitive, ignoreEscape, \
really_hide, really_show, timed_action, escape_markup
from pyanaconda.ui.helpers import StorageCheckHandler
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk, Gtk
log = get_module_logger(__name__)
__all__ = ["CustomPartitioningSpoke"]
class CustomPartitioningSpoke(NormalSpoke, StorageCheckHandler):
"""
.. inheritance-diagram:: CustomPartitioningSpoke
:parts: 3
"""
builderObjects = ["customStorageWindow", "containerStore", "deviceTypeStore",
"partitionStore", "raidStoreFiltered", "raidLevelStore",
"addImage", "removeImage", "settingsImage",
"mountPointCompletion", "mountPointStore", "fileSystemStore",
"luksVersionStore"]
mainWidgetName = "customStorageWindow"
uiFile = "spokes/custom_storage.glade"
helpFile = "CustomSpoke.xml"
category = SystemCategory
title = N_("MANUAL PARTITIONING")
# The maximum number of places to show when displaying a size
MAX_SIZE_PLACES = 2
# If the user enters a smaller size, the GUI changes it to this value
MIN_SIZE_ENTRY = Size("1 MiB")
def __init__(self, data, storage, payload):
StorageCheckHandler.__init__(self)
NormalSpoke.__init__(self, data, storage, payload)
self._back_already_clicked = False
self._initialized = False
self._error = None
self._accordion = None
self._partitioning_scheme = conf.storage.default_scheme
self._default_file_system = ""
self._selected_disks = []
self._passphrase = ""
self._os_name = ""
self._supported_raid_levels = {}
self._partitioning = None
self._device_tree = None
self._request = DeviceFactoryRequest()
self._original_request = DeviceFactoryRequest()
self._permissions = DeviceFactoryPermissions()
self._storage_module = STORAGE.get_proxy()
self._boot_loader = STORAGE.get_proxy(BOOTLOADER)
self._disk_selection = STORAGE.get_proxy(DISK_SELECTION)
def apply(self):
self.clear_errors()
hubQ.send_ready("StorageSpoke", True)
@property
def indirect(self):
return True
@property
def status(self):
return None
def _grab_objects(self):
self._partitionsViewport = self.builder.get_object("partitionsViewport")
self._partitionsNotebook = self.builder.get_object("partitionsNotebook")
# Connect partitionsNotebook focus events to scrolling in the parent viewport
partitions_notebook_viewport = self.builder.get_object("partitionsNotebookViewport")
self._partitionsNotebook.set_focus_vadjustment(
Gtk.Scrollable.get_vadjustment(partitions_notebook_viewport))
self._pageLabel = self.builder.get_object("pageLabel")
self._availableSpaceLabel = self.builder.get_object("availableSpaceLabel")
self._totalSpaceLabel = self.builder.get_object("totalSpaceLabel")
self._summaryLabel = self.builder.get_object("summary_label")
# Buttons
self._addButton = self.builder.get_object("addButton")
self._applyButton = self.builder.get_object("applyButton")
self._configButton = self.builder.get_object("configureButton")
self._removeButton = self.builder.get_object("removeButton")
self._resetButton = self.builder.get_object("resetButton")
# Detailed configuration stuff
self._encryptCheckbox = self.builder.get_object("encryptCheckbox")
self._fsCombo = self.builder.get_object("fileSystemTypeCombo")
self._fsStore = self.builder.get_object("fileSystemStore")
self._luksCombo = self.builder.get_object("luksVersionCombo")
self._luksStore = self.builder.get_object("luksVersionStore")
self._luksLabel = self.builder.get_object("luksVersionLabel")
self._labelEntry = self.builder.get_object("labelEntry")
self._mountPointEntry = self.builder.get_object("mountPointEntry")
self._nameEntry = self.builder.get_object("nameEntry")
self._raidLevelCombo = self.builder.get_object("raidLevelCombo")
self._raidLevelLabel = self.builder.get_object("raidLevelLabel")
self._reformatCheckbox = self.builder.get_object("reformatCheckbox")
self._sizeEntry = self.builder.get_object("sizeEntry")
self._typeStore = self.builder.get_object("deviceTypeStore")
self._typeCombo = self.builder.get_object("deviceTypeCombo")
self._modifyContainerButton = self.builder.get_object("modifyContainerButton")
self._containerCombo = self.builder.get_object("containerCombo")
self._containerStore = self.builder.get_object("containerStore")
self._deviceDescLabel = self.builder.get_object("deviceDescLabel")
# Set the fixed-size properties on the volume group ComboBox renderers to
# False so that the "Create a new..." row can overlap with the free space
# on the other rows. These properties are not accessible from glade.
cell_area = self._containerCombo.get_area()
desc_renderer = self.builder.get_object("descRenderer")
free_space_renderer = self.builder.get_object("freeSpaceRenderer")
cell_area.cell_set_property(desc_renderer, "fixed-size", False)
cell_area.cell_set_property(free_space_renderer, "fixed-size", False)
self._passphraseEntry = self.builder.get_object("passphraseEntry")
# Stores
self._raidStoreFilter = self.builder.get_object("raidStoreFiltered")
# Labels
self._selectedDeviceLabel = self.builder.get_object("selectedDeviceLabel")
self._selectedDeviceDescLabel = self.builder.get_object("selectedDeviceDescLabel")
self._encryptedDeviceLabel = self.builder.get_object("encryptedDeviceLabel")
self._encryptedDeviceDescLabel = self.builder.get_object("encryptedDeviceDescriptionLabel")
self._incompleteDeviceLabel = self.builder.get_object("incompleteDeviceLabel")
self._incompleteDeviceDescLabel = self.builder.get_object(
"incompleteDeviceDescriptionLabel")
self._incompleteDeviceOptionsLabel = self.builder.get_object(
"incompleteDeviceOptionsLabel")
self._uneditableDeviceLabel = self.builder.get_object("uneditableDeviceLabel")
self._uneditableDeviceDescLabel = self.builder.get_object(
"uneditableDeviceDescriptionLabel")
self._containerLabel = self.builder.get_object("containerLabel")
def initialize(self):
NormalSpoke.initialize(self)
self.initialize_start()
self._grab_objects()
setViewportBackground(self.builder.get_object("availableSpaceViewport"), "#db3279")
setViewportBackground(self.builder.get_object("totalSpaceViewport"), "#60605b")
self._raidStoreFilter.set_visible_func(self._raid_level_visible)
self._accordion = Accordion()
self._partitionsViewport.add(self._accordion)
# Connect viewport scrolling with accordion focus events
self._accordion.set_focus_hadjustment(
Gtk.Scrollable.get_hadjustment(self._partitionsViewport))
self._accordion.set_focus_vadjustment(
Gtk.Scrollable.get_vadjustment(self._partitionsViewport))
self.initialize_done()
def _get_unused_devices(self):
return self._device_tree.CollectUnusedDevices()
@property
def _boot_drive(self):
return self._boot_loader.Drive
def _get_new_devices(self):
return self._device_tree.CollectNewDevices(self._boot_drive)
def _get_all_devices(self):
return self._device_tree.GetDevices()
def _update_permissions(self):
self._permissions = self._get_permissions(self._request)
def _get_permissions(self, request):
return DeviceFactoryPermissions.from_structure(
self._device_tree.GenerateDeviceFactoryPermissions(
DeviceFactoryRequest.to_structure(request)
)
)
def _update_space_display(self):
# Set up the free space/available space displays in the bottom left.
disks = self._selected_disks
free_space = Size(self._device_tree.GetDiskFreeSpace(disks))
total_space = Size(self._device_tree.GetDiskTotalSpace(disks))
self._availableSpaceLabel.set_text(str(free_space))
self._totalSpaceLabel.set_text(str(total_space))
count = len(disks)
summary = CP_("GUI|Custom Partitioning",
"%d _storage device selected",
"%d _storage devices selected",
count) % count
self._summaryLabel.set_text(summary)
self._summaryLabel.set_use_underline(True)
def _reset_storage(self):
# FIXME: Reset only the current partitioning module.
self._storage_module.ResetPartitioning()
def refresh(self):
self.reset_state()
NormalSpoke.refresh(self)
# Make sure the storage spoke execute method has finished before we
# copy the storage instance.
for thread_name in [THREAD_EXECUTE_STORAGE, THREAD_STORAGE]:
threadMgr.wait(thread_name)
if not self._partitioning:
# Create the partitioning now. It cannot by done earlier, because
# the storage spoke would use it as a default partitioning.
self._partitioning = create_partitioning(PARTITIONING_METHOD_INTERACTIVE)
self._device_tree = STORAGE.get_proxy(self._partitioning.GetDeviceTree())
# Get the name of the new installation.
self._os_name = self._device_tree.GenerateSystemName()
# Get the default file system type.
self._default_file_system = self._device_tree.GetDefaultFileSystem()
# Initialize the selected disks.
selected_disks = self._disk_selection.SelectedDisks
partitioned_devices = self._device_tree.GetPartitioned()
self._selected_disks = filter_disks_by_names(partitioned_devices, selected_disks)
# Update the UI elements.
self._do_refresh(init_expanded_pages=True)
self._applyButton.set_sensitive(False)
def _get_file_system_type(self):
itr = self._fsCombo.get_active_iter()
if not itr:
return None
model = self._fsCombo.get_model()
return model[itr][1]
def _change_autopart_type(self, autopart_type_combo):
"""
This is called when the autopart type combo on the left hand side of
custom partitioning is changed. We already know how to handle the case
where the user changes the type and then clicks the autopart link
button. This handles the case where the user changes the type and then
clicks the '+' button.
"""
itr = autopart_type_combo.get_active_iter()
if not itr:
return
model = autopart_type_combo.get_model()
self._partitioning_scheme = model[itr][1]
def _set_page_label_text(self):
if self._accordion.is_multiselection:
select_tmpl = _("%(items_selected)s of %(items_total)s mount points in %(page_name)s")
span_tmpl = "<span size='large' weight='bold' fgcolor='%s'>%s</span>"
pages_count = ""
for page in self._accordion.all_pages:
if not page.members:
continue
if page.selected_members:
highlight_color = "black"
page_text_tmpl = select_tmpl
else:
highlight_color = "gray"
page_text_tmpl = "<span fgcolor='gray'>%s</span>" % escape_markup(select_tmpl)
selected_str = span_tmpl % (escape_markup(highlight_color),
escape_markup(str(len(page.selected_members))))
total_str = span_tmpl % (escape_markup(highlight_color),
escape_markup(str(len(page.members))))
page_name = span_tmpl % (escape_markup(highlight_color),
escape_markup(page.page_title))
page_line = page_text_tmpl % {"items_selected": selected_str,
"items_total": total_str,
"page_name": page_name}
pages_count += page_line + "\n"
self._pageLabel.set_markup(
_("Please select a single mount point to edit properties.\n\n"
"You have currently selected:\n"
"%s") % pages_count)
else:
self._pageLabel.set_text(
_("When you create mount points for your %(name)s %(version)s "
"installation, you'll be able to view their details here.")
% {"name": productName, "version": productVersion})
def _populate_accordion(self):
# Make sure we start with a clean state.
self._accordion.remove_all_pages()
new_devices = self._get_new_devices()
all_devices = self._get_all_devices()
unused_devices = self._get_unused_devices()
# Collect the existing roots.
ui_roots = OSData.from_structure_list(
self._device_tree.CollectSupportedSystems()
)
# Now it's time to populate the accordion.
log.debug("Populating accordion for devices %s (unused %s, new %s).",
all_devices, unused_devices, new_devices)
# Add the initial page.
if not new_devices:
self._add_initial_page(reuse_existing=bool(ui_roots or unused_devices))
else:
new_root = OSData.from_structure(
self._device_tree.GenerateSystemData(self._boot_drive)
)
ui_roots.insert(0, new_root)
# Add root pages.
for root in ui_roots:
self._add_root_page(root)
# Add the unknown page.
if unused_devices:
self._add_unknown_page(unused_devices)
def _add_initial_page(self, reuse_existing=False):
page = CreateNewPage(
self._os_name,
self.on_create_clicked,
self._change_autopart_type,
default_scheme=self._partitioning_scheme,
partitions_to_reuse=reuse_existing
)
self._accordion.add_page(page, cb=self.on_page_clicked)
self._partitionsNotebook.set_current_page(NOTEBOOK_LABEL_PAGE)
self._set_page_label_text()
def _add_root_page(self, root: OSData):
page = Page(root.os_name)
self._accordion.add_page(page, cb=self.on_page_clicked)
for mount_point, device_name in root.mount_points.items():
selector = MountPointSelector()
self._update_selector(
selector,
device_name=device_name,
root_name=root.os_name,
mount_point=mount_point
)
page.add_selector(selector, self.on_selector_clicked)
for device_name in root.swap_devices:
selector = MountPointSelector()
self._update_selector(
selector,
device_name=device_name,
root_name=root.os_name
)
page.add_selector(selector, self.on_selector_clicked)
page.show_all()
def _add_unknown_page(self, devices):
page = UnknownPage(_("Unknown"))
self._accordion.add_page(page, cb=self.on_page_clicked)
for device_name in sorted(devices):
selector = MountPointSelector()
self._update_selector(selector, device_name)
page.add_selector(selector, self.on_selector_clicked)
page.show_all()
def _update_selector(self, selector, device_name="", root_name="", mount_point=""):
if not selector:
return
if not device_name:
device_name = selector.device_name
if not root_name:
root_name = selector.root_name
device_data = DeviceData.from_structure(
self._device_tree.GetDeviceData(device_name)
)
format_data = DeviceFormatData.from_structure(
self._device_tree.GetFormatData(device_name)
)
mount_point = self._get_mount_point_description(
mount_point, format_data
)
selector.props.name = device_name
selector.props.size = str(Size(device_data.size))
selector.props.mountpoint = mount_point
selector.root_name = root_name
def _get_mount_point_description(self, mount_point, format_data):
"""Generate the selector's mount point description."""
return \
format_data.attrs.get("mount-point", "") or \
mount_point or \
format_data.description or \
_("Unknown")
def _get_mount_point_description_for_request(self, request):
"""Generate the selector's mount point description from a request."""
mount_point = request.mount_point
format_type = request.format_type
format_data = DeviceFormatData.from_structure(
self._device_tree.GetFormatTypeData(format_type)
)
return self._get_mount_point_description(
mount_point, format_data
)
def _do_refresh(self, mountpoint_to_show=None, init_expanded_pages=False):
# block mountpoint selector signal handler for now
self._initialized = False
expanded_pages = self._accordion.get_expanded_pages()
self._accordion.clear_current_selector()
# Start with buttons disabled, since nothing is selected.
self._removeButton.set_sensitive(False)
self._configButton.set_sensitive(False)
# populate the accorion with roots and mount points
self._populate_accordion()
# And then open the first page by default. Most of the time, this will
# be fine since it'll be the new installation page.
self._initialized = True
first_page = self._accordion.all_pages[0]
if init_expanded_pages:
expanded_pages = [first_page.page_title]
self._accordion.expand_pages(expanded_pages)
self._show_mountpoint(page=first_page, mountpoint=mountpoint_to_show)
self._applyButton.set_sensitive(False)
self._resetButton.set_sensitive(bool(self._device_tree.GetActions()))
# Set up the free space/available space labels.
self._update_space_display()
###
### RIGHT HAND SIDE METHODS
###
def _save_right_side(self, selector):
""" Save settings from RHS and apply changes to the device.
This method must never trigger a call to self._do_refresh.
"""
# check if initialized and have something to operate on
if not self._initialized or not selector:
return
# only call _save_right_side if on the right page and some changes need
# to be saved (sensitivity of the Update Settings button reflects that)
if self._partitionsNotebook.get_current_page() != NOTEBOOK_DETAILS_PAGE or \
not self._applyButton.get_sensitive():
return
device_name = selector.device_name
if device_name not in self._device_tree.GetDevices():
# just-removed device
return
self.reset_state()
log.debug("Saving the right side for device: %s", device_name)
# Get the device factory request.
old_request = self._original_request
new_request = self._request
if compare_data(old_request, new_request):
log.debug("Nothing to do.")
return
# Log the results.
description = generate_request_description(new_request, old_request)
log.debug("Device request: %s", description)
# Validate the device info.
report = ValidationReport.from_structure(
self._device_tree.ValidateDeviceFactoryRequest(
DeviceFactoryRequest.to_structure(new_request)
)
)
if not report.is_valid():
log.debug("Validation has failed: %s", report)
self.set_warning(" ".join(report.get_messages()))
self._populate_right_side(selector)
return
# Apply the changes.
try:
self._device_tree.ChangeDevice(
DeviceFactoryRequest.to_structure(new_request),
DeviceFactoryRequest.to_structure(old_request)
)
except StorageConfigurationError as e:
log.error("Failed to reconfigure the device: %s", e)
self.set_detailed_error(_("Device reconfiguration failed."), e)
self._reset_storage()
self._do_refresh()
return
# Update UI.
log.debug("The device request changes are applied.")
mount_point = self._get_mount_point_description_for_request(new_request)
self._do_refresh(mountpoint_to_show=mount_point)
def _raid_level_visible(self, model, itr, user_data):
raid_level = model[itr][1]
return raid_level in self._supported_raid_levels
def _populate_raid(self, raid_level=""):
"""Set up the raid-specific portion of the device details.
:param str raid_level: RAID level name or an empty string
"""
self._supported_raid_levels = get_supported_device_raid_levels(
self._device_tree, self._get_current_device_type()
)
self._raidStoreFilter.refilter()
if not self._supported_raid_levels:
for widget in [self._raidLevelLabel, self._raidLevelCombo]:
really_hide(widget)
return
device_type = self._get_current_device_type()
raid_level = raid_level or get_default_raid_level(device_type)
# Set a default RAID level in the combo.
index = self._raidLevelCombo.get_active()
for (i, row) in enumerate(self._raidLevelCombo.get_model()):
if row[1] == raid_level:
index = i
break
for widget in [self._raidLevelLabel, self._raidLevelCombo]:
really_show(widget)
self._raidLevelCombo.set_active(index)
def _populate_luks(self, luks_version):
"""Set up the LUKS version combo box.
:param luks_version: a LUKS version or None
"""
# Add the values.
self._luksStore.clear()
for version in ["luks1", "luks2"]:
self._luksStore.append([version])
# Get the selected value.
luks_version = luks_version or self._device_tree.GetDefaultLUKSVersion()
# Set the selected value.
idx = next(
i for i, data in enumerate(self._luksCombo.get_model())
if data[0] == luks_version
)
self._luksCombo.set_active(idx)
self._update_luks_combo()
def _get_current_device_type(self):
""" Return integer for type combo selection.
:returns: the corresponding integer code, a constant in
blivet.devicefactory.
:rtype: int or NoneType
"""
itr = self._typeCombo.get_active_iter()
if not itr:
return None
device_type = self._typeStore[itr][1]
if device_type == DEVICE_TYPE_UNSUPPORTED:
return None
return device_type
def _setup_fstype_combo(self, device_type, device_format_type, format_types):
"""Setup the filesystem combo box."""
default_type = device_format_type
if default_type not in format_types:
format_types.append(default_type)
# Add all desired fileystem type names to the box, sorted alphabetically
self._fsStore.clear()
for fs_type in format_types:
fmt = DeviceFormatData.from_structure(
self._device_tree.GetFormatTypeData(fs_type)
)
self._fsStore.append([fmt.description, fmt.type])
# set the active filesystem type
model = self._fsCombo.get_model()
idx = next(i for i, data in enumerate(model) if data[1] == default_type)
self._fsCombo.set_active(idx)
# do additional updating handled by other method
self._update_fstype_combo(device_type)
def _setup_device_type_combo(self, device_type, device_types):
"""Set up device type combo."""
# Include md only if there are two or more disks.
if len(self._selected_disks) <= 1:
device_types.remove(DEVICE_TYPE_MD)
# For existing unsupported device add the information in the UI.
if device_type not in device_types:
log.debug("Existing device with unsupported type %s found.", device_type)
device_type = DEVICE_TYPE_UNSUPPORTED
device_types.append(device_type)
# Add values.
self._typeStore.clear()
for dt in device_types:
self._typeStore.append([_(DEVICE_TEXT_MAP[dt]), dt])
# Set the selected value.
idx = next(
i for i, data in enumerate(self._typeCombo.get_model())
if data[1] == device_type
)
self._typeCombo.set_active(idx)
def _get_device_name(self, device_type):
"""Update the dictionary of device names."""
if device_type == self._original_request.device_type:
return self._original_request.device_name
if device_type in NAMED_DEVICE_TYPES:
return self._device_tree.GenerateDeviceName(
self._request.mount_point,
self._request.format_type
)
return ""
def _set_devices_label(self):
disks = self._request.disks
if not disks:
description = _("No disks assigned")
else:
device_data = DeviceData.from_structure(
self._device_tree.GetDeviceData(disks[0])
)
description = "{} ({})".format(
device_data.description,
device_data.name
)
num_disks = len(disks)
if num_disks > 1:
description += CP_(
"GUI|Custom Partitioning|Devices",
" and {} other", " and {} others",
num_disks - 1
).format(num_disks - 1)
self._deviceDescLabel.set_text(description)
def _populate_right_side(self, selector):
device_name = selector.device_name
self._request = DeviceFactoryRequest.from_structure(
self._device_tree.GenerateDeviceFactoryRequest(device_name)
)
self._original_request = copy.deepcopy(self._request)
self._update_permissions()
description = generate_request_description(self._request)
log.debug("Populating the right side for device %s: %s", device_name, description)
self._selectedDeviceLabel.set_text(device_name)
self._selectedDeviceDescLabel.set_text(
_(MOUNTPOINT_DESCRIPTIONS.get(device_name, ""))
)
self._set_devices_label()
self._mountPointEntry.set_text(self._request.mount_point)
fancy_set_sensitive(self._mountPointEntry, self._permissions.mount_point)
self._labelEntry.set_text(self._request.label)
fancy_set_sensitive(self._labelEntry, self._permissions.label)
self._sizeEntry.set_text(
Size(self._request.device_size).human_readable(max_places=self.MAX_SIZE_PLACES)
)
self._reformatCheckbox.set_active(self._request.reformat)
fancy_set_sensitive(self._reformatCheckbox, self._permissions.reformat)
# Set up the encryption.
self._encryptCheckbox.set_active(self._request.device_encrypted)
fancy_set_sensitive(self._encryptCheckbox, self._permissions.device_encrypted)
self._encryptCheckbox.set_inconsistent(self._request.container_encrypted)
text = _("The container is encrypted.") if self._request.container_encrypted else ""
self._encryptCheckbox.set_tooltip_text(text)
self._update_luks_combo()
# Set up the filesystem type combo.
format_types = self._device_tree.GetFileSystemsForDevice(device_name)
self._setup_fstype_combo(self._request.device_type, self._request.format_type, format_types)
fancy_set_sensitive(self._fsCombo, self._permissions.format_type)
# Set up the device type combo.
device_types = self._device_tree.GetDeviceTypesForDevice(device_name)
self._setup_device_type_combo(self._request.device_type, device_types)
fancy_set_sensitive(self._typeCombo, self._permissions.device_type)
# FIXME: device encryption should be mutually exclusive with container
# encryption
# FIXME: device raid should be mutually exclusive with container raid
# The size entry is only sensitive for resizable existing devices and
# new devices that are not btrfs subvolumes.
# Do this after the device type combo is set since
# on_device_type_changed doesn't account for device existence.
fancy_set_sensitive(self._sizeEntry, self._permissions.device_size)
if self._permissions.device_size:
self._sizeEntry.props.has_tooltip = False
elif self._request.format_type == "btrfs":
self._sizeEntry.set_tooltip_text(_(
"The space available to this mount point can "
"be changed by modifying the volume below."
))
else:
self._sizeEntry.set_tooltip_text(_(
"This file system may not be resized."
))
self._populate_raid(self._request.device_raid_level)
fancy_set_sensitive(self._raidLevelCombo, self._permissions.device_raid_level)
self._populate_container()
self._populate_luks(self._request.luks_version)
self._nameEntry.set_text(self._request.device_name)
fancy_set_sensitive(self._nameEntry, self._permissions.device_name)
self._configButton.set_sensitive(self._permissions.disks)
###
### SIGNAL HANDLERS
###
def on_key_pressed(self, widget, event, *args):
if not event or event and event.type != Gdk.EventType.KEY_RELEASE:
return
if event.keyval in [Gdk.KEY_Delete, Gdk.KEY_minus]:
# But we only want delete to work if you have focused a MountPointSelector,
# and not just any random widget. For those, it's likely the user wants
# to delete a character.
if isinstance(self.main_window.get_focus(), MountPointSelector):
self._removeButton.emit("clicked")
elif event.keyval == Gdk.KEY_plus:
# And we only want '+' to work if you don't have a text entry focused, since
# the user might be entering some free-form text that can include a plus.
if not isinstance(self.main_window.get_focus(), Gtk.Entry):
self._addButton.emit("clicked")
def _setup_passphrase(self):
# Find new LUKS devices without a passphrase.
devices = self._device_tree.FindUnconfiguredLUKS()
if not devices:
return True
# Ask for a passphrase.
dialog = PassphraseDialog(self.data, default_passphrase=self._passphrase)
with self.main_window.enlightbox(dialog.window):
rc = dialog.run()
# Cancel. Leave the old passphrase set if there was one.
if rc != 1:
return False
# Set the new passphrase.
self._passphrase = dialog.passphrase
# Configure the devices.
for device_name in devices:
self._device_tree.SetDevicePassphrase(device_name, self._passphrase)
return True
def _do_check(self):
self.clear_errors()
StorageCheckHandler.errors = []
StorageCheckHandler.warnings = []
try:
log.debug("Generating updated storage configuration")
task_path = self._partitioning.ConfigureWithTask()
task_proxy = STORAGE.get_proxy(task_path)
sync_run_task(task_proxy)
except BootloaderConfigurationError as e:
log.error("Storage configuration failed: %s", e)
StorageCheckHandler.errors = [str(e)]
reset_bootloader()
else:
log.debug("Checking storage configuration...")
task_path = self._partitioning.ValidateWithTask()
task_proxy = STORAGE.get_proxy(task_path)
sync_run_task(task_proxy)
result = unwrap_variant(task_proxy.GetResult())
report = ValidationReport.from_structure(result)
log.debug("Validation has been completed: %s", report)
StorageCheckHandler.errors = report.error_messages
StorageCheckHandler.warnings = report.warning_messages
if report.is_valid():
self._storage_module.ApplyPartitioning(
get_object_path(self._partitioning)
)
if self.errors:
self.set_warning(_(
"Error checking storage configuration. <a href=\"\">Click for details</a> "
"or press Done again to continue."))
elif self.warnings:
self.set_warning(_(
"Warning checking storage configuration. <a href=\"\">Click for details</a> "
"or press Done again to continue."))
# on_info_bar_clicked requires self._error to be set, so set it to the
# list of all errors and warnings that storage checking found.
self._error = "\n".join(self.errors + self.warnings)
return self._error == ""
def on_back_clicked(self, button):
# Clear any existing errors
self.clear_errors()
# Save anything from the currently displayed mount point.
self._save_right_side(self._accordion.current_selector)
self._applyButton.set_sensitive(False)
# And then display the summary screen. From there, the user will either
# head back to the hub, or stay on the custom screen.
# If back has been clicked on once already and no other changes made on the screen,
# run the storage check now. This handles displaying any errors in the info bar.
if not self._back_already_clicked:
self._back_already_clicked = True
# If we hit any errors while saving things above, stop and let the
# user think about what they have done
if self._error is not None:
return
if not self._setup_passphrase():
return
if not self._do_check():
return
dialog = ActionSummaryDialog(self.data, self._device_tree)
dialog.refresh()
if dialog.actions:
with self.main_window.enlightbox(dialog.window):
rc = dialog.run()
if rc != 1:
# Cancel. Stay on the custom screen.
return
NormalSpoke.on_back_clicked(self, button)
def on_add_clicked(self, button):
# Clear any existing errors
self.reset_state()
# Save anything from the currently displayed mount point.
self._save_right_side(self._accordion.current_selector)
# Initialize and run the AddDialog.
dialog = AddDialog(self.data, self._device_tree)
dialog.refresh()
with self.main_window.enlightbox(dialog.window):
rc = dialog.run()
if rc != 1:
# user cancel
dialog.window.destroy()
return
# Gather data about the added mount point.
request = DeviceFactoryRequest()
request.mount_point = dialog.mount_point