forked from QubesOS/qubes-installer-qubes-os
-
Notifications
You must be signed in to change notification settings - Fork 4
/
bootloader.py
2539 lines (2074 loc) · 90.9 KB
/
bootloader.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
# bootloader.py
# Anaconda's bootloader configuration module.
#
# Copyright (C) 2011 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>
# Matthew Miller <mattdm@redhat.com> (extlinux portion)
#
import collections
import os
import re
import shutil
import blivet
from parted import PARTITION_BIOS_GRUB
from glob import glob
from itertools import chain
from pyanaconda import iutil
from pyanaconda.iutil import open # pylint: disable=redefined-builtin
from blivet.devicelibs import raid
from pyanaconda.product import productName
from pyanaconda.flags import flags, can_touch_runtime_system
from blivet.fcoe import fcoe
import pyanaconda.network
from pyanaconda.errors import errorHandler, ERROR_RAISE, ZIPLError
from pyanaconda.packaging.rpmostreepayload import RPMOSTreePayload
from pyanaconda.nm import nm_device_hwaddress
from blivet import platform
from blivet.size import Size
from pyanaconda.i18n import _, N_
from pyanaconda.orderedset import OrderedSet
import logging
import subprocess
log = logging.getLogger("anaconda")
class serial_opts(object):
def __init__(self):
self.speed = None
self.parity = None
self.word = None
self.stop = None
self.flow = None
def parse_serial_opt(arg):
"""
Parse and split serial console options.
.. NOTE::
Documentation/kernel-parameters.txt says:
ttyS<n>[,options]
Use the specified serial port. The options are of
the form "bbbbpnf", where "bbbb" is the baud rate,
"p" is parity ("n", "o", or "e"), "n" is number of
bits, and "f" is flow control ("r" for RTS or
omit it). Default is "9600n8".
but note that everything after the baud rate is optional, so these are
all valid: 9600, 19200n, 38400n8, 9600e7r.
Also note that the kernel assumes 1 stop bit; this can't be changed.
"""
opts = serial_opts()
m = re.match(r'\d+', arg)
if m is None:
return opts
opts.speed = m.group()
idx = len(opts.speed)
try:
opts.parity = arg[idx+0]
opts.word = arg[idx+1]
opts.flow = arg[idx+2]
except IndexError:
pass
return opts
def _is_on_iscsi(device):
"""Tells whether a given device is on an iSCSI disk or not."""
return all(isinstance(disk, blivet.devices.iScsiDiskDevice)
for disk in device.disks)
def _is_on_ibft(device):
"""Tells whether a given device is ibft disk or not."""
return all(getattr(disk, "ibft", False) for disk in device.disks)
class BootLoaderError(Exception):
pass
class Arguments(OrderedSet):
def _merge_ip(self):
"""
Find ip= arguments targetting the same interface and merge them.
"""
# partition the input
def partition_p(arg):
# we are only interested in ip= parameters that use some kind of
# automatic network setup:
return arg.startswith("ip=") and arg.count(":") == 1
ip_params = filter(partition_p, self)
rest = OrderedSet(filter(lambda p: not partition_p(p), self))
# split at the colon:
ip_params = map(lambda p: p.split(":"), ip_params)
# create mapping from nics to their configurations
config = collections.defaultdict(list)
for (nic, cfg) in ip_params:
config[nic].append(cfg)
# generate the new parameters:
ip_params = set()
for nic in config:
ip_params.add("%s:%s" % (nic, ",".join(sorted(config[nic]))))
# update the set
self.clear()
self.update(rest)
self.update(ip_params)
return self
def __str__(self):
self._merge_ip()
return " ".join(list(self))
def add(self, key):
self.discard(key)
super(Arguments, self).add(key)
def update(self, other):
for key in other:
self.discard(key)
self.add(key)
class BootLoaderImage(object):
""" Base class for bootloader images. Suitable for non-linux OS images. """
def __init__(self, device=None, label=None, short=None):
self.label = label
self.short_label = short
self.device = device
class LinuxBootLoaderImage(BootLoaderImage):
def __init__(self, device=None, label=None, short=None, version=None):
super(LinuxBootLoaderImage, self).__init__(device=device, label=label)
self.label = label # label string
self.short_label = short # shorter label string
self.device = device # StorageDevice instance
self.version = version # kernel version string
self._kernel = None # filename string
self._initrd = None # filename string
@property
def kernel(self):
filename = self._kernel
if self.version and not filename:
filename = "vmlinuz-%s" % self.version
return filename
@property
def initrd(self):
filename = self._initrd
if self.version and not filename:
filename = "initramfs-%s.img" % self.version
return filename
class TbootLinuxBootLoaderImage(LinuxBootLoaderImage):
_multiboot = "tboot.gz" # filename string
_mbargs = ["logging=vga,serial,memory"]
_args = ["intel_iommu=on"]
def __init__(self, device=None, label=None, short=None, version=None):
super(TbootLinuxBootLoaderImage, self).__init__(
device=device, label=label,
short=short, version=version)
@property
def multiboot(self):
return self._multiboot
@property
def mbargs(self):
return self._mbargs
@property
def args(self):
return self._args
class BootLoader(object):
name = "Generic Bootloader"
packages = []
config_file = None
config_file_mode = 0o600
can_dual_boot = False
can_update = False
image_label_attr = "label"
encryption_support = False
stage2_is_valid_stage1 = False
# requirements for stage2 devices
stage2_device = None
stage2_device_types = []
stage2_raid_levels = []
stage2_raid_metadata = []
stage2_raid_member_types = []
stage2_mountpoints = ["/boot", "/"]
stage2_bootable = False
stage2_must_be_primary = True
stage2_description = N_("/boot file system")
stage2_max_end = Size("2 TiB")
@property
def stage2_format_types(self):
return ["ext4", "ext3", "ext2"]
preserve_args = []
global_no_preserve_args = ["stage2", "root", "rescue",
"rd.live.check", "ip", "repo", "ks",
"rd.lvm", "rd.md", "rd.luks", "rd.dm",
"rd.lvm.lv"]
_trusted_boot = False
def __init__(self):
self.boot_args = Arguments()
self.dracut_args = Arguments()
self.disks = []
self._disk_order = []
# timeout in seconds
self._timeout = None
self.password = None
# console/serial stuff
self.console = ""
self.console_options = ""
self._set_console()
# list of BootLoaderImage instances representing bootable OSs
self.linux_images = []
self.chain_images = []
# default image
self._default_image = None
self._update_only = False
self.skip_bootloader = False
self.errors = []
self.warnings = []
self.reset()
def reset(self):
""" Reset stage1 and stage2 values """
# the device the bootloader will be installed on
self.stage1_device = None
# the "boot disk", meaning the disk stage1 _will_ go on
self.stage1_disk = None
self.stage2_device = None
self.stage2_is_preferred_stage1 = False
self.errors = []
self.problems = []
self.warnings = []
#
# disk list access
#
@property
def disk_order(self):
"""Potentially partial order for disks."""
return self._disk_order
@disk_order.setter
def disk_order(self, order):
log.debug("new disk order: %s", order)
self._disk_order = order
if self.disks:
self._sort_disks()
def _sort_disks(self):
"""Sort the internal disk list. """
for name in reversed(self.disk_order):
try:
idx = [d.name for d in self.disks].index(name)
except ValueError:
log.error("bios order specified unknown disk %s", name)
continue
self.disks.insert(0, self.disks.pop(idx))
def set_disk_list(self, disks):
self.disks = disks[:]
self._sort_disks()
#
# image list access
#
@property
def default(self):
"""The default image."""
if not self._default_image and self.linux_images:
self._default_image = self.linux_images[0]
return self._default_image
@default.setter
def default(self, image):
if image not in self.images:
raise ValueError("new default image not in image list")
log.debug("new default image: %s", image)
self._default_image = image
@property
def images(self):
""" List of OS images that will be included in the configuration. """
all_images = self.linux_images
all_images.extend(i for i in self.chain_images if i.label)
return all_images
def clear_images(self):
"""Empty out the image list."""
self.linux_images = []
self.chain_images = []
def add_image(self, image):
"""Add a BootLoaderImage instance to the image list."""
if isinstance(image, LinuxBootLoaderImage):
self.linux_images.append(image)
else:
self.chain_images.append(image)
def image_label(self, image):
"""Return the appropriate image label for this bootloader."""
return getattr(image, self.image_label_attr)
#
# platform-specific data access
#
@property
def disklabel_types(self):
return platform.platform._disklabel_types
@property
def device_descriptions(self):
return platform.platform.bootStage1ConstraintDict["descriptions"]
#
# constraint checking for target devices
#
def _is_valid_md(self, device, raid_levels=None,
metadata=None, member_types=None, desc=""):
ret = True
if device.type != "mdarray":
return ret
if raid_levels and device.level not in raid_levels:
levels_str = ",".join("%s" % l for l in raid_levels)
self.errors.append(_("RAID sets that contain '%(desc)s' must have one "
"of the following raid levels: %(raid_level)s.")
% {"desc" : desc, "raid_level" : levels_str})
ret = False
# new arrays will be created with an appropriate metadata format
if device.exists and \
metadata and device.metadataVersion not in metadata:
self.errors.append(_("RAID sets that contain '%(desc)s' must have one "
"of the following metadata versions: %(metadata_versions)s.")
% {"desc": desc, "metadata_versions": ",".join(metadata)})
ret = False
if member_types:
for member in device.devices:
if not self._device_type_match(member, member_types):
self.errors.append(_("RAID sets that contain '%(desc)s' must "
"have one of the following device "
"types: %(types)s.")
% {"desc" : desc, "types" : ",".join(member_types)})
ret = False
log.debug("_is_valid_md(%s) returning %s", device.name, ret)
return ret
def _is_valid_disklabel(self, device, disklabel_types=None):
ret = True
if self.disklabel_types:
for disk in device.disks:
label_type = getattr(disk.format, "labelType", None)
if not label_type or label_type not in self.disklabel_types:
types_str = ",".join(disklabel_types)
self.errors.append(_("%(name)s must have one of the following "
"disklabel types: %(types)s.")
% {"name" : device.name, "types" : types_str})
ret = False
log.debug("_is_valid_disklabel(%s) returning %s", device.name, ret)
return ret
def _is_valid_format(self, device, format_types=None, mountpoints=None,
desc=""):
ret = True
if format_types and device.format.type not in format_types:
self.errors.append(_("%(desc)s cannot be of type %(type)s.")
% {"desc" : desc, "type" : device.format.type})
ret = False
if mountpoints and hasattr(device.format, "mountpoint") \
and device.format.mountpoint not in mountpoints:
self.errors.append(_("%(desc)s must be mounted on one of %(mountpoints)s.")
% {"desc" : desc, "mountpoints" : ", ".join(mountpoints)})
ret = False
log.debug("_is_valid_format(%s) returning %s", device.name, ret)
return ret
def _is_valid_size(self, device, desc=""):
ret = True
msg = None
errors = []
if device.format.minSize and device.format.maxSize:
msg = (_("%(desc)s must be between %(min)d and %(max)d MB in size")
% {"desc" : desc, "min" : device.format.minSize,
"max" : device.format.maxSize})
if device.format.minSize and device.size < device.format.minSize:
if msg is None:
errors.append(_("%(desc)s must not be smaller than %(min)dMB.")
% {"desc" : desc, "min" : device.format.minSize})
else:
errors.append(msg)
ret = False
if device.format.maxSize and device.size > device.format.maxSize:
if msg is None:
errors.append(_("%(desc)s must not be larger than %(max)dMB.")
% {"desc" : desc, "max" : device.format.maxSize})
elif msg not in errors:
# don't add the same error string twice
errors.append(msg)
ret = False
log.debug("_is_valid_size(%s) returning %s", device.name, ret)
return ret
def _is_valid_location(self, device, max_end=None, desc=""):
ret = True
if max_end and device.type == "partition" and device.partedPartition:
end_sector = device.partedPartition.geometry.end
sector_size = device.partedPartition.disk.device.sectorSize
end = Size(sector_size * end_sector)
if end > max_end:
self.errors.append(_("%(desc)s must be within the first %(max_end)s of "
"the disk.") % {"desc": desc, "max_end": max_end})
ret = False
log.debug("_is_valid_location(%s) returning %s", device.name, ret)
return ret
def _is_valid_partition(self, device, primary=None, desc=""):
ret = True
if device.type == "partition" and primary and not device.isPrimary:
self.errors.append(_("%s must be on a primary partition.") % desc)
ret = False
log.debug("_is_valid_partition(%s) returning %s", device.name, ret)
return ret
#
# target/stage1 device access
#
def _device_type_index(self, device, types):
""" Return the index of the matching type in types to device's type.
Return None if no match is found. """
index = None
try:
index = types.index(device.type)
except ValueError:
if "disk" in types and device.isDisk:
index = types.index("disk")
return index
def _device_type_match(self, device, types):
""" Return True if device is of one of the types in the list types. """
return self._device_type_index(device, types) is not None
def device_description(self, device):
device_types = list(self.device_descriptions.keys())
idx = self._device_type_index(device, device_types)
if idx is None:
raise ValueError("No description available for %s" % device.type)
# this looks unnecessarily complicated, but it handles the various
# device types that we treat as disks
return self.device_descriptions[device_types[idx]]
def set_preferred_stage1_type(self, preferred):
""" Set a preferred type of stage1 device. """
if not self.stage2_is_valid_stage1:
# "partition" means first sector of stage2 and is only meaningful
# for bootloaders that can use stage2 as stage1
return
if preferred == "mbr":
# "mbr" is already the default
return
# partition means "use the stage2 device for a stage1 device"
self.stage2_is_preferred_stage1 = True
def is_valid_stage1_device(self, device, early=False):
""" Return True if the device is a valid stage1 target device.
Also collect lists of errors and warnings.
The criteria for being a valid stage1 target device vary from
platform to platform. On some platforms a disk with an msdos
disklabel is a valid stage1 target, while some platforms require
a special device. Some examples of these special devices are EFI
system partitions on EFI machines, PReP boot partitions on
iSeries, and Apple bootstrap partitions on Mac.
The 'early' keyword argument is a boolean flag indicating whether
or not this check is being performed at a point where the mountpoint
cannot be expected to be set for things like EFI system partitions.
"""
self.errors = []
self.warnings = []
valid = True
constraint = platform.platform.bootStage1ConstraintDict
if device is None:
return False
if not self._device_type_match(device, constraint["device_types"]):
log.debug("stage1 device cannot be of type %s", device.type)
return False
if _is_on_iscsi(device) and not _is_on_ibft(device):
log.debug("stage1 device cannot be on an iSCSI disk")
return False
description = self.device_description(device)
if self.stage2_is_valid_stage1 and device == self.stage2_device:
# special case
valid = (self.stage2_is_preferred_stage1 and
self.is_valid_stage2_device(device))
# we'll be checking stage2 separately so don't duplicate messages
self.problems = []
self.warnings = []
return valid
if device.protected:
valid = False
if not self._is_valid_disklabel(device,
disklabel_types=self.disklabel_types):
valid = False
if not self._is_valid_size(device, desc=description):
valid = False
if not self._is_valid_location(device,
max_end=constraint["max_end"],
desc=description):
valid = False
if not self._is_valid_md(device,
raid_levels=constraint["raid_levels"],
metadata=constraint["raid_metadata"],
member_types=constraint["raid_member_types"],
desc=description):
valid = False
if not self.stage2_bootable and not getattr(device, "bootable", True):
log.warning("%s not bootable", device.name)
# XXX does this need to be here?
if getattr(device.format, "label", None) in ("ANACONDA", "LIVE"):
log.info("ignoring anaconda boot disk")
valid = False
if early:
mountpoints = []
else:
mountpoints = constraint["mountpoints"]
if not self._is_valid_format(device,
format_types=constraint["format_types"],
mountpoints=mountpoints,
desc=description):
valid = False
if not self.encryption_support and device.encrypted:
self.errors.append(_("%s cannot be on an encrypted block "
"device.") % description)
valid = False
log.debug("is_valid_stage1_device(%s) returning %s", device.name, valid)
return valid
def set_stage1_device(self, devices):
self.stage1_device = None
if not self.stage1_disk:
self.reset()
raise BootLoaderError("need stage1 disk to set stage1 device")
if self.stage2_is_preferred_stage1:
self.stage1_device = self.stage2_device
return
for device in devices:
if self.stage1_disk not in device.disks:
continue
if self.is_valid_stage1_device(device):
if flags.imageInstall and device.isDisk:
# GRUB2 will install to /dev/loop0 but not to
# /dev/mapper/<image_name>
self.stage1_device = device.parents[0]
else:
self.stage1_device = device
break
if not self.stage1_device:
self.reset()
raise BootLoaderError("failed to find a suitable stage1 device")
#
# boot/stage2 device access
#
def is_valid_stage2_device(self, device, linux=True, non_linux=False):
""" Return True if the device is suitable as a stage2 target device.
Also collect lists of errors and warnings.
"""
self.errors = []
self.warnings = []
valid = True
if device is None:
return False
if device.protected:
valid = False
if _is_on_iscsi(device) and not _is_on_ibft(device):
self.errors.append(_("%s cannot be on an iSCSI disk") % self.stage2_description)
valid = False
if not self._device_type_match(device, self.stage2_device_types):
self.errors.append(_("%(desc)s cannot be of type %(type)s")
% {"desc" : _(self.stage2_description), "type" : device.type})
valid = False
if not self._is_valid_disklabel(device,
disklabel_types=self.disklabel_types):
valid = False
if not self._is_valid_size(device, desc=_(self.stage2_description)):
valid = False
if self.stage2_max_end and not self._is_valid_location(device,
max_end=self.stage2_max_end,
desc=_(self.stage2_description)):
valid = False
if not self._is_valid_partition(device,
primary=self.stage2_must_be_primary):
valid = False
if not self._is_valid_md(device,
raid_levels=self.stage2_raid_levels,
metadata=self.stage2_raid_metadata,
member_types=self.stage2_raid_member_types,
desc=_(self.stage2_description)):
valid = False
if linux and \
not self._is_valid_format(device,
format_types=self.stage2_format_types,
mountpoints=self.stage2_mountpoints,
desc=_(self.stage2_description)):
valid = False
non_linux_format_types = platform.platform._non_linux_format_types
if non_linux and \
not self._is_valid_format(device,
format_types=non_linux_format_types):
valid = False
if not self.encryption_support and device.encrypted:
self.errors.append(_("%s cannot be on an encrypted block "
"device.") % _(self.stage2_description))
valid = False
log.debug("is_valid_stage2_device(%s) returning %s", device.name, valid)
return valid
#
# miscellaneous
#
def has_windows(self, devices):
return False
@property
def timeout(self):
"""Bootloader timeout in seconds."""
if self._timeout is not None:
t = self._timeout
else:
t = 5
return t
def check(self):
""" Run additional bootloader checks """
return True
@timeout.setter
def timeout(self, seconds):
self._timeout = seconds
@property
def update_only(self):
return self._update_only
@update_only.setter
def update_only(self, value):
if value and not self.can_update:
raise ValueError("this boot loader does not support updates")
elif self.can_update:
self._update_only = value
def set_boot_args(self, *args, **kwargs):
""" Set up the boot command line.
Keyword Arguments:
storage - a blivet.Storage instance
All other arguments are expected to have a dracutSetupArgs()
method.
"""
storage = kwargs.pop("storage", None)
#
# FIPS
#
boot_device = storage.mountpoints.get("/boot")
if flags.cmdline.get("fips") == "1" and boot_device:
self.boot_args.add("boot=%s" % self.stage2_device.fstabSpec)
#
# dracut
#
# storage
from blivet.devices import NetworkStorageDevice
dracut_devices = [storage.rootDevice]
if self.stage2_device != storage.rootDevice:
dracut_devices.append(self.stage2_device)
dracut_devices.extend(storage.fsset.swapDevices)
# Does /usr have its own device? If so, we need to tell dracut
usr_device = storage.mountpoints.get("/usr")
if usr_device:
dracut_devices.extend([usr_device])
netdevs = storage.devicetree.getDevicesByInstance(NetworkStorageDevice)
rootdev = storage.rootDevice
if any(rootdev.dependsOn(netdev) for netdev in netdevs):
dracut_devices = set(dracut_devices)
# By this time this thread should be the only one running, and also
# mountpoints is a property function that returns a new dict every
# time, so iterating over the values is safe.
for dev in storage.mountpoints.values():
if any(dev.dependsOn(netdev) for netdev in netdevs):
dracut_devices.add(dev)
done = []
for device in dracut_devices:
for dep in storage.devices:
if dep in done:
continue
if device != dep and not device.dependsOn(dep):
continue
setup_args = dep.dracutSetupArgs()
if not setup_args:
continue
self.boot_args.update(setup_args)
self.dracut_args.update(setup_args)
done.append(dep)
# network storage
# XXX this is nothing to be proud of
if isinstance(dep, NetworkStorageDevice):
setup_args = pyanaconda.network.dracutSetupArgs(dep)
self.boot_args.update(setup_args)
self.dracut_args.update(setup_args)
# passed-in objects
for cfg_obj in chain(args, kwargs.values()):
if hasattr(cfg_obj, "dracutSetupArgs"):
setup_args = cfg_obj.dracutSetupArgs()
self.boot_args.update(setup_args)
self.dracut_args.update(setup_args)
else:
setup_string = cfg_obj.dracutSetupString()
self.boot_args.add(setup_string)
self.dracut_args.add(setup_string)
# This is needed for FCoE, bug #743784. The case:
# We discover LUN on an iface which is part of multipath setup.
# If the iface is disconnected after discovery anaconda doesn't
# write dracut ifname argument for the disconnected iface path
# (in Network.dracutSetupArgs).
# Dracut needs the explicit ifname= because biosdevname
# fails to rename the iface (because of BFS booting from it).
for nic, _dcb, _auto_vlan in fcoe().nics:
try:
hwaddr = nm_device_hwaddress(nic)
except ValueError:
continue
self.boot_args.add("ifname=%s:%s" % (nic, hwaddr.lower()))
# Add iscsi_firmware to trigger dracut running iscsistart
# See rhbz#1099603 and rhbz#1185792
if len(glob("/sys/firmware/iscsi_boot*")) > 0:
self.boot_args.add("iscsi_firmware")
#
# preservation of most of our boot args
#
for opt in flags.cmdline.keys():
if opt in self.global_no_preserve_args:
continue
arg = flags.cmdline.get(opt)
new_arg = opt
if arg:
new_arg += "=%s" % arg
self.boot_args.add(new_arg)
# passed-in objects
for cfg_obj in chain(args, kwargs.values()):
if hasattr(cfg_obj, "dracutSetupArgs"):
setup_args = cfg_obj.dracutSetupArgs()
self.boot_args.update(setup_args)
self.dracut_args.update(setup_args)
else:
setup_string = cfg_obj.dracutSetupString()
self.boot_args.add(setup_string)
self.dracut_args.add(setup_string)
#
# configuration
#
@property
def boot_prefix(self):
""" Prefix, if any, to paths in /boot. """
if self.stage2_device.format.mountpoint == "/":
prefix = "/boot"
else:
prefix = ""
return prefix
def _set_console(self):
""" Set console options based on boot arguments. """
console = flags.cmdline.get("console", "")
console = os.path.basename(console)
self.console, _x, self.console_options = console.partition(",")
def write_config_console(self, config):
"""Write console-related configuration lines."""
pass
def write_config_password(self, config):
"""Write password-related configuration lines."""
pass
def write_config_header(self, config):
"""Write global configuration lines."""
self.write_config_console(config)
self.write_config_password(config)
def write_config_images(self, config):
"""Write image configuration entries."""
raise NotImplementedError()
def write_config_post(self):
pass
def write_config(self):
""" Write the bootloader configuration. """
if not self.config_file:
raise BootLoaderError("no config file defined for this boot loader")
config_path = os.path.normpath(iutil.getSysroot() + self.config_file)
if os.access(config_path, os.R_OK):
os.rename(config_path, config_path + ".anacbak")
config = iutil.open_with_perm(config_path, "w", self.config_file_mode)
self.write_config_header(config)
self.write_config_images(config)
config.close()
self.write_config_post()
@property
def trusted_boot(self):
return self._trusted_boot
@trusted_boot.setter
def trusted_boot(self, trusted_boot):
self._trusted_boot = trusted_boot
#
# installation
#
def write(self):
""" Write the bootloader configuration and install the bootloader. """
if self.skip_bootloader:
return
if self.update_only:
self.update()
return
self.write_config()
os.sync()
self.stage2_device.format.sync(root=iutil.getTargetPhysicalRoot())
self.install()
def install(self, args=None):
raise NotImplementedError()
def update(self):
""" Update an existing bootloader configuration. """
pass
class GRUB(BootLoader):
name = "GRUB"
_config_dir = "grub"
_config_file = "grub.conf"
_device_map_file = "device.map"
can_dual_boot = True
can_update = True
stage2_is_valid_stage1 = True
stage2_bootable = True
stage2_must_be_primary = False
# list of strings representing options for boot device types
stage2_device_types = ["partition", "mdarray"]
stage2_raid_levels = [raid.RAID1]
stage2_raid_member_types = ["partition"]
stage2_raid_metadata = ["0", "0.90", "1.0"]