summaryrefslogtreecommitdiffstats
path: root/pyanaconda/bootloader.py
blob: a8c969e5152c909bcba776812430dbf661383ae1 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
# 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>
#

import collections
import sys
import os
import re
import struct

from pyanaconda import iutil
from pyanaconda.storage.devicelibs import mdraid
from pyanaconda.isys import sync, getMacAddress
from pyanaconda.product import productName
from pyanaconda.flags import flags
from pyanaconda.constants import *
from pyanaconda.storage.errors import StorageError
from pyanaconda.storage.fcoe import fcoe
import pyanaconda.network

import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)
N_ = lambda x: x

import logging
log = logging.getLogger("storage")


def get_boot_block(device, seek_blocks=0):
    status = device.status
    if not status:
        try:
            device.setup()
        except StorageError:
            return ""
    block_size = device.partedDevice.sectorSize
    fd = os.open(device.path, os.O_RDONLY)
    if seek_blocks:
        os.lseek(fd, seek_blocks * block_size, 0)
    block = os.read(fd, 512)
    os.close(fd)
    if not status:
        try:
            device.teardown(recursive=True)
        except StorageError:
            pass

    return block

def is_windows_boot_block(block):
    try:
        windows = (len(block) >= 512 and
                   struct.unpack("H", block[0x1fe: 0x200]) == (0xaa55,))
    except struct.error:
        windows = False
    return windows

def has_windows_boot_block(device):
    return is_windows_boot_block(get_boot_block(device))

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.

    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"""
    opts = serial_opts()
    m = re.match('\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

class BootLoaderError(Exception):
    pass

class Arguments(set):
    ordering_dict = {
        "rhgb" : 99,
        "quiet" : 100
        }

    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 = set(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()
        # sort the elements according to their values in ordering_dict. The
        # higher the number the closer to the final string the argument
        # gets. The default is 50.
        lst = sorted(self, key=lambda s: self.ordering_dict.get(s, 50))

        return " ".join(lst)

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 = []
    obsoletes = []
    config_file = None
    config_file_mode = 0600
    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_types = []
    stage2_raid_levels = []
    stage2_raid_metadata = []
    stage2_raid_member_types = []
    stage2_format_types = ["ext4", "ext3", "ext2"]
    stage2_mountpoints = ["/boot", "/"]
    stage2_bootable = False
    stage2_must_be_primary = True
    stage2_description = N_("/boot filesystem")
    stage2_max_end_mb = 2 * 1024 * 1024

    # this is so stupid...
    global_preserve_args = ["speakup_synth", "apic", "noapic", "apm", "ide",
                            "noht", "acpi", "video", "pci", "nodmraid",
                            "nompath", "nomodeset", "noiswmd", "fips"]
    preserve_args = []

    _trusted_boot = False

    def __init__(self, platform=None):
        # pyanaconda.platform.Platform instance
        self.platform = platform

        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

        # 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._update_only = False
        self.skip_bootloader = False

        self.stage2_is_preferred_stage1 = False

        self.errors = []
        self.warnings = []

    #
    # disk list access
    #
    # pylint: disable-msg=E0202
    @property
    def disk_order(self):
        """Potentially partial order for disks."""
        return self._disk_order

    # pylint: disable-msg=E0102,E0202,E1101
    @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
    #
    # pylint: disable-msg=E0202
    @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

    # pylint: disable-msg=E0102,E0202,E1101
    @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 self.platform._disklabel_types

    @property
    def device_descriptions(self):
        return self.platform.bootStage1ConstraintDict["descriptions"]

    #
    # constraint checking for target devices
    #
    def _is_valid_md(self, device, device_types=None, 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("RAID%d" % l for l in raid_levels)
            self.errors.append(_("RAID sets that contain '%s' must have one "
                                 "of the following raid levels: %s.")
                               % (desc, 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 '%s' must have one "
                                 "of the following metadata versions: %s.")
                               % (desc, ",".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 '%s' must "
                                         "have one of the following device "
                                         "types: %s.")
                                       % (desc, ",".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, desc=""):
        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(_("%s must have one of the following "
                                         "disklabel types: %s.")
                                       % (device.name, 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(_("%s cannot be of type %s.")
                               % (desc, device.format.type))
            ret = False

        if mountpoints and hasattr(device.format, "mountpoint") \
           and device.format.mountpoint not in mountpoints:
            self.errors.append(_("%s must be mounted on one of %s.")
                               % (desc, ", ".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 = (_("%s must be between %d and %d MB in size")
                   % (desc, device.format.minSize, device.format.maxSize))

        if device.format.minSize and device.size < device.format.minSize:
            if msg is None:
                errors.append(_("%s must not be smaller than %dMB.")
                              % (desc, 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(_("%s must not be larger than %dMB.")
                              % (desc, 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_mb=None, desc=""):
        ret = True
        if max_mb and device.type == "partition" and device.partedPartition:
            end_sector = device.partedPartition.geometry.end
            sector_size = device.partedPartition.disk.device.sectorSize
            end_mb = (sector_size * end_sector) / (1024.0 * 1024.0)
            if end_mb > max_mb:
                self.errors.append(_("%s must be within the first %dMB of "
                                     "the disk.") % (desc, max_mb))
                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 = 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):
        """ 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. """
        self.errors = []
        self.warnings = []
        valid = True
        constraint = self.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

        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,
                                        desc=description):
            valid = False

        if not self._is_valid_size(device, desc=description):
            valid = False

        if not self._is_valid_location(device,
                                       max_mb=constraint["max_end_mb"],
                                       desc=description):
            valid = False

        if not self._is_valid_md(device,
                                 device_types=constraint["device_types"],
                                 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 not self._is_valid_format(device,
                                     format_types=constraint["format_types"],
                                     mountpoints=constraint["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:
            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):
                self.stage1_device = device
                break

        if not self.stage1_device:
            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 not self._device_type_match(device, self.stage2_device_types):
            self.errors.append(_("%s cannot be of type %s")
                               % (self.stage2_description, device.type))
            valid = False

        if not self._is_valid_disklabel(device,
                                        disklabel_types=self.disklabel_types,
                                        desc=self.stage2_description):
            valid = False

        if not self._is_valid_size(device, desc=self.stage2_description):
            valid = False

        if not self._is_valid_location(device,
                                       max_mb=self.stage2_max_end_mb,
                                       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, device_types=self.stage2_device_types,
                                 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 = self.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

    # pylint: disable-msg=E0202
    @property
    def timeout(self):
        """Bootloader timeout in seconds."""
        if self._timeout is not None:
            t = self._timeout
        else:
            t = 5

        return t

    # pylint: disable-msg=E0102,E0202,E1101
    @timeout.setter
    def timeout(self, seconds):
        self._timeout = seconds

    # pylint: disable-msg=E0202
    @property
    def update_only(self):
        return self._update_only

    # pylint: disable-msg=E0102,E0202,E1101
    @update_only.setter
    def update_only(self, value):
        if value and not self.can_update:
            raise ValueError("this bootloader 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 pyanaconda.storage.Storage instance

            All other arguments are expected to have a dracutSetupArgs()
            method.
        """
        storage = kwargs.pop("storage", None)

        #
        # FIPS
        #
        if flags.cmdline.get("fips") == "1":
            self.boot_args.add("boot=%s" % self.stage2_device.fstabSpec)

        #
        # dracut
        #

        # storage
        from pyanaconda.storage.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])

        done = []
        # When we see a device whose setup string starts with a key in this
        # dict we pop that pair from the dict. When we're done looking at
        # devices we are left with the values that belong in the boot args.
        dracut_storage = {"rd.luks.uuid": "rd.luks=0",
                          "rd.lvm.lv": "rd.lvm=0",
                          "rd.md.uuid": "rd.md=0",
                          "rd.dm.uuid": "rd.dm=0"}
        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)
                for setup_arg in setup_args:
                    dracut_storage.pop(setup_arg.split("=")[0], None)

                # 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)

        self.boot_args.update(dracut_storage.values())
        self.dracut_args.update(dracut_storage.values())

        # passed-in objects
        for cfg_obj in list(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:
            hwaddr = getMacAddress(nic)
            self.boot_args.add("ifname=%s:%s" % (nic, hwaddr.lower()))

        #
        # preservation of some of our boot args
        # FIXME: this is stupid.
        #
        for opt in self.global_preserve_args + self.preserve_args:
            if opt not in flags.cmdline:
                continue

            arg = flags.cmdline.get(opt)
            new_arg = opt
            if arg:
                new_arg += "=%s" % arg

            self.boot_args.add(new_arg)

    #
    # 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. """
        if flags.serial:
            console = flags.cmdline.get("console", "ttyS0").split(",", 1)
            self.console = console[0]
            if len(console) > 1:
                self.console_options = console[1]
        elif flags.virtpconsole:
            self.console = re.sub("^/dev/", "", flags.virtpconsole)

    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."""
        # XXX might this be identical for yaboot and silo?
        raise NotImplementedError()

    def write_config_post(self):
        try:
            os.chmod(ROOT_PATH + self.config_file, self.config_file_mode)
        except OSError as e:
            log.error("failed to set config file permissions: %s" % e)

    def write_config(self):
        """ Write the bootloader configuration. """
        if not self.config_file:
            raise BootLoaderError("no config file defined for this bootloader")

        config_path = os.path.normpath(ROOT_PATH + self.config_file)
        if os.access(config_path, os.R_OK):
            os.rename(config_path, config_path + ".anacbak")

        config = open(config_path, "w")
        self.write_config_header(config)
        self.write_config_images(config)
        config.close()
        self.write_config_post()

    def read(self):
        """ Read an existing bootloader configuration. """
        raise NotImplementedError()

    @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.update_only:
            self.update()
            return

        self.write_config()
        sync()
        self.stage2_device.format.sync(root=ROOT_PATH)
        self.install()

    def install(self):
        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 = [mdraid.RAID1]
    stage2_raid_member_types = ["partition"]
    stage2_raid_metadata = ["0", "0.90", "1.0"]

    packages = ["grub"]

    def __init__(self, platform=None):
        super(GRUB, self).__init__(platform=platform)
        self.encrypted_password = ""

    #
    # grub-related conveniences
    #

    def grub_device_name(self, device):
        """ Return a grub-friendly representation of device. """
        disk = getattr(device, "disk", device)
        name = "(hd%d" % self.disks.index(disk)
        if hasattr(device, "disk"):
            name += ",%d" % (device.partedPartition.number - 1,)
        name += ")"
        return name

    @property
    def grub_config_dir(self):
        """ Config dir, adjusted for grub's view of the world. """
        return self.boot_prefix + self._config_dir

    #
    # configuration
    #

    @property
    def config_dir(self):
        """ Full path to configuration directory. """
        return "/boot/" + self._config_dir

    @property
    def config_file(self):
        """ Full path to configuration file. """
        return "%s/%s" % (self.config_dir, self._config_file)

    @property
    def device_map_file(self):
        """ Full path to device.map file. """
        return "%s/%s" % (self.config_dir, self._device_map_file)

    @property
    def grub_conf_device_line(self):
        return ""

    @property
    def splash_dir(self):
        """ relative path to splash image directory."""
        return GRUB._config_dir

    @property
    def serial_command(self):
        command = ""
        if self.console and self.console.startswith("ttyS"):
            unit = self.console[-1]
            command = ["serial"]
            s = parse_serial_opt(self.console_options)
            if unit and unit != '0':
                command.append("--unit=%s" % unit)
            if s.speed and s.speed != '9600':
                command.append("--speed=%s" % s.speed)
            if s.parity:
                if s.parity == 'o':
                    command.append("--parity=odd")
                elif s.parity == 'e':
                    command.append("--parity=even")
            if s.word and s.word != '8':
                command.append("--word=%s" % s.word)
            if s.stop and s.stop != '1':
                command.append("--stop=%s" % s.stop)
            command = " ".join(command)
        return command

    def write_config_console(self, config):
        """ Write console-related configuration. """
        if not self.console:
            return

        if self.console.startswith("ttyS"):
            config.write("%s\n" % self.serial_command)
            config.write("terminal --timeout=%s serial console\n"
                         % self.timeout)

        console_arg = "console=%s" % self.console
        if self.console_options:
            console_arg += ",%s" % self.console_options
        self.boot_args.add(console_arg)

    def _encrypt_password(self):
        """ Make sure self.encrypted_password is set up correctly. """
        if self.encrypted_password:
            return

        if not self.password:
            raise BootLoaderError("cannot encrypt empty password")

        import string
        import crypt
        import random
        salt = "$6$"
        salt_len = 16
        salt_chars = string.letters + string.digits + './'

        rand_gen = random.SystemRandom()
        salt += "".join([rand_gen.choice(salt_chars) for i in range(salt_len)])
        self.encrypted_password = crypt.crypt(self.password, salt)

    def write_config_password(self, config):
        """ Write password-related configuration. """
        if not self.password and not self.encrypted_password:
            return

        self._encrypt_password()
        password_line = "--encrypted " + self.encrypted_password
        config.write("password %s\n" % password_line)

    def write_config_header(self, config):
        """Write global configuration information. """
        if self.boot_prefix:
            have_boot = "do not "
        else:
            have_boot = ""

        s = """# grub.conf generated by anaconda
# Note that you do not have to rerun grub after making changes to this file.
# NOTICE:  You %(do)shave a /boot partition. This means that all kernel and
#          initrd paths are relative to %(boot)s, eg.
#          root %(grub_target)s
#          kernel %(prefix)s/vmlinuz-version ro root=%(root_device)s
#          initrd %(prefix)s/initrd-[generic-]version.img
""" % {"do": have_boot, "boot": self.stage2_device.format.mountpoint,
       "root_device": self.stage2_device.path,
       "grub_target": self.grub_device_name(self.stage1_device),
       "prefix": self.boot_prefix}

        config.write(s)
        config.write("boot=%s\n" % self.stage1_device.path)
        config.write(self.grub_conf_device_line)

        # find the index of the default image
        try:
            default_index = self.images.index(self.default)
        except ValueError:
            e = "Failed to find default image (%s)" % self.default.label
            raise BootLoaderError(e)

        config.write("default=%d\n" % default_index)
        config.write("timeout=%d\n" % self.timeout)

        self.write_config_console(config)

        if not flags.serial:
            splash = "splash.xpm.gz"
            splash_path = os.path.normpath("%s/boot/%s/%s" % (ROOT_PATH,
                                                        self.splash_dir,
                                                        splash))
            if os.access(splash_path, os.R_OK):
                grub_root_grub_name = self.grub_device_name(self.stage2_device)
                config.write("splashimage=%s/%s/%s\n" % (grub_root_grub_name,
                                                         self.splash_dir,
                                                         splash))
                config.write("hiddenmenu\n")

        self.write_config_password(config)

    def write_config_images(self, config):
        """ Write image entries into configuration file. """
        for image in self.images:
            args = Arguments()
            if isinstance(image, LinuxBootLoaderImage):
                grub_root = self.grub_device_name(self.stage2_device)
                args.update(["ro", "root=%s" % image.device.fstabSpec])
                args.update(self.boot_args)
                if isinstance(image, TbootLinuxBootLoaderImage):
                    args.update(image.args)
                    snippet = ("\tkernel %(prefix)s/%(multiboot)s %(mbargs)s\n"
                               "\tmodule %(prefix)s/%(kernel)s %(args)s\n"
                               "\tmodule %(prefix)s/%(initrd)s\n"
                               % {"prefix": self.boot_prefix,
                                  "multiboot": image.multiboot,
                                  "mbargs": image.mbargs,
                                  "kernel": image.kernel, "args": args,
                                  "initrd": image.initrd})
                else:
                    snippet = ("\tkernel %(prefix)s/%(kernel)s %(args)s\n"
                               "\tinitrd %(prefix)s/%(initrd)s\n"
                               % {"prefix": self.boot_prefix,
                                  "kernel": image.kernel, "args": args,
                                  "initrd": image.initrd})
                stanza = ("title %(label)s (%(version)s)\n"
                          "\troot %(grub_root)s\n"
                          "%(snippet)s"
                          % {"label": image.label, "version": image.version,
                             "grub_root": grub_root, "snippet": snippet})
            else:
                stanza = ("title %(label)s\n"
                          "\trootnoverify %(grub_root)s\n"
                          "\tchainloader +1\n"
                          % {"label": image.label,
                             "grub_root": self.grub_device_name(image.device)})

            log.info("bootloader.py: used boot args: %s " % args)
            config.write(stanza)

    def write_device_map(self):
        """ Write out a device map containing all supported devices. """
        map_path = os.path.normpath(ROOT_PATH + self.device_map_file)
        if os.access(map_path, os.R_OK):
            os.rename(map_path, map_path + ".anacbak")

        dev_map = open(map_path, "w")
        dev_map.write("# this device map was generated by anaconda\n")
        for disk in self.disks:
            dev_map.write("%s      %s\n" % (self.grub_device_name(disk),
                                            disk.path))
        dev_map.close()

    def write_config_post(self):
        """ Perform additional configuration after writing config file(s). """
        super(GRUB, self).write_config_post()

        # make symlink for menu.lst (grub's default config file name)
        menu_lst = "%s%s/menu.lst" % (ROOT_PATH, self.config_dir)
        if os.access(menu_lst, os.R_OK):
            try:
                os.rename(menu_lst, menu_lst + '.anacbak')
            except OSError as e:
                log.error("failed to back up %s: %s" % (menu_lst, e))

        try:
            os.symlink(self._config_file, menu_lst)
        except OSError as e:
            log.error("failed to create grub menu.lst symlink: %s" % e)

        # make symlink to grub.conf in /etc since that's where configs belong
        etc_grub = "%s/etc/%s" % (ROOT_PATH, self._config_file)
        if os.access(etc_grub, os.R_OK):
            try:
                os.unlink(etc_grub)
            except OSError as e:
                log.error("failed to remove %s: %s" % (etc_grub, e))

        try:
            os.symlink("..%s" % self.config_file, etc_grub)
        except OSError as e:
            log.error("failed to create /etc/grub.conf symlink: %s" % e)

    def write_config(self):
        """ Write bootloader configuration to disk. """
        # write device.map
        self.write_device_map()

        # this writes the actual configuration file
        super(GRUB, self).write_config()

    #
    # installation
    #

    @property
    def install_targets(self):
        """ List of (stage1, stage2) tuples representing install targets. """
        targets = []
        if self.stage2_device.type == "mdarray" and \
           self.stage2_device.level == 1:
            # make sure we have stage1 and stage2 installed with redundancy
            # so that boot can succeed even in the event of failure or removal
            # of some of the disks containing the member partitions of the
            # /boot array
            for stage2dev in self.stage2_device.parents:
                if self.stage1_device.isDisk:
                    # install to mbr
                    if self.stage2_device.dependsOn(self.stage1_device):
                        # if target disk contains any of /boot array's member
                        # partitions, set up stage1 on each member's disk
                        # and stage2 on each member partition
                        stage1dev = stage2dev.disk
                    else:
                        # if target disk does not contain any of /boot array's
                        # member partitions, install stage1 to the target disk
                        # and stage2 to each of the member partitions
                        stage1dev = self.stage1_device
                else:
                    # target is /boot device and /boot is raid, so install
                    # grub to each of /boot member partitions
                    stage1dev = stage2dev

                targets.append((stage1dev, stage2dev))
        else:
            targets.append((self.stage1_device, self.stage2_device))

        return targets

    def install(self):
        rc = iutil.execWithRedirect("grub-install", ["--just-copy"],
                                    stdout="/dev/tty5", stderr="/dev/tty5",
                                    root=ROOT_PATH)
        if rc:
            raise BootLoaderError("bootloader install failed")

        for (stage1dev, stage2dev) in self.install_targets:
            cmd = ("root %(stage2dev)s\n"
                   "install --stage2=%(config_dir)s/stage2"
                   " /%(grub_config_dir)s/stage1 d %(stage1dev)s"
                   " /%(grub_config_dir)s/stage2 p"
                   " %(stage2dev)s/%(grub_config_dir)s/%(config_basename)s\n"
                   % {"grub_config_dir": self.grub_config_dir,
                      "config_dir": self.config_dir,
                      "config_basename": self._config_file,
                      "stage1dev": self.grub_device_name(self.stage1_device),
                      "stage2dev": self.grub_device_name(self.stage2_device)})
            (pread, pwrite) = os.pipe()
            os.write(pwrite, cmd)
            os.close(pwrite)
            args = ["--batch", "--no-floppy",
                    "--device-map=%s" % self.device_map_file]
            rc = iutil.execWithRedirect("grub", args,
                                        stdout="/dev/tty5", stderr="/dev/tty5",
                                        stdin=pread, root=ROOT_PATH)
            os.close(pread)
            if rc:
                raise BootLoaderError("bootloader install failed")

    def update(self):
        self.install()

    #
    # miscellaneous
    #

    def has_windows(self, devices):
        """ Potential boot devices containing non-linux operating systems. """
        # make sure we don't clobber error/warning lists
        errors = self.errors[:]
        warnings = self.warnings[:]
        ret = [d for d in devices if self.is_valid_stage2_device(d, linux=False, non_linux=True)]
        self.errors = errors
        self.warnings = warnings
        return ret

class GRUB2(GRUB):
    """ GRUBv2

        - configuration
            - password (insecure), password_pbkdf2
                - http://www.gnu.org/software/grub/manual/grub.html#Invoking-grub_002dmkpasswd_002dpbkdf2
            - --users per-entry specifies which users can access, otherwise
              entry is unrestricted
            - /etc/grub/custom.cfg

        - how does grub resolve names of md arrays?

        - disable automatic use of grub-mkconfig?
            - on upgrades?

        - BIOS boot partition (GPT)
            - parted /dev/sda set <partition_number> bios_grub on
            - can't contain a filesystem
            - 31KiB min, 1MiB recommended

    """
    name = "GRUB2"
    packages = ["grub2"]
    obsoletes = ["grub"]
    _config_file = "grub.cfg"
    _config_dir = "grub2"
    config_file_mode = 0600
    defaults_file = "/etc/default/grub"
    can_dual_boot = True
    can_update = True

    # requirements for boot devices
    stage2_format_types = ["ext4", "ext3", "ext2", "btrfs", "xfs"]
    stage2_device_types = ["partition", "mdarray", "lvmlv", "btrfs volume"]
    stage2_raid_levels = [mdraid.RAID0, mdraid.RAID1, mdraid.RAID4,
                          mdraid.RAID5, mdraid.RAID6, mdraid.RAID10]

    def __init__(self, platform=None):
        super(GRUB2, self).__init__(platform=platform)
        self.boot_args.add("$([ -x /usr/sbin/rhcrashkernel-param ] && "\
                           "/usr/sbin/rhcrashkernel-param || :)")

    # XXX we probably need special handling for raid stage1 w/ gpt disklabel
    #     since it's unlikely there'll be a bios boot partition on each disk

    #
    # grub-related conveniences
    #

    def grub_device_name(self, device):
        """ Return a grub-friendly representation of device.

            Disks and partitions use the (hdX,Y) notation, while lvm and
            md devices just use their names.
        """
        disk = None
        name = "(%s)" % device.name

        if device.isDisk:
            disk = device
        elif hasattr(device, "disk"):
            disk = device.disk

        if disk is not None:
            name = "(hd%d" % self.disks.index(disk)
            if hasattr(device, "disk"):
                lt = device.disk.format.labelType
                name += ",%s%d" % (lt, device.partedPartition.number)
            name += ")"
        return name

    def write_config_console(self, config):
        if not self.console:
            return

        console_arg = "console=%s" % self.console
        if self.console_options:
            console_arg += ",%s" % self.console_options
        self.boot_args.add(console_arg)

    def write_device_map(self):
        """ Write out a device map containing all supported devices. """
        map_path = os.path.normpath(ROOT_PATH + self.device_map_file)
        if os.access(map_path, os.R_OK):
            os.rename(map_path, map_path + ".anacbak")

        devices = self.disks
        if self.stage1_device not in devices:
            devices.append(self.stage1_device)

        for disk in self.stage2_device.disks:
            if disk not in devices:
                devices.append(disk)

        devices = [d for d in devices if d.isDisk]

        if len(devices) == 0:
            return

        dev_map = open(map_path, "w")
        dev_map.write("# this device map was generated by anaconda\n")
        for drive in devices:
            dev_map.write("%s      %s\n" % (self.grub_device_name(drive),
                                            drive.path))
        dev_map.close()

    def write_defaults(self):
        defaults_file = "%s%s" % (ROOT_PATH, self.defaults_file)
        defaults = open(defaults_file, "w+")
        defaults.write("GRUB_TIMEOUT=%d\n" % self.timeout)
        defaults.write("GRUB_DISTRIBUTOR=\"$(sed 's, release .*$,,g' /etc/system-release)\"\n")
        defaults.write("GRUB_DEFAULT=saved\n")
        if self.console and self.console.startswith("ttyS"):
            defaults.write("GRUB_TERMINAL=\"serial console\"\n")
            defaults.write("GRUB_SERIAL_COMMAND=\"%s\"\n" % self.serial_command)

        # this is going to cause problems for systems containing multiple
        # linux installations or even multiple boot entries with different
        # boot arguments
        log.info("bootloader.py: used boot args: %s " % self.boot_args)
        defaults.write("GRUB_CMDLINE_LINUX=\"%s\"\n" % self.boot_args)
        defaults.write("GRUB_DISABLE_RECOVERY=\"true\"\n")
        defaults.write("GRUB_THEME=\"/boot/grub2/themes/system/theme.txt\"\n")
        defaults.close()

    def _encrypt_password(self):
        """ Make sure self.encrypted_password is set up properly. """
        if self.encrypted_password:
            return

        if not self.password:
            raise RuntimeError("cannot encrypt empty password")

        (pread, pwrite) = os.pipe()
        os.write(pwrite, "%s\n%s\n" % (self.password, self.password))
        os.close(pwrite)
        buf = iutil.execWithCapture("grub2-mkpasswd-pbkdf2", [],
                                    stdin=pread,
                                    stderr="/dev/tty5",
                                    root=ROOT_PATH)
        os.close(pread)
        self.encrypted_password = buf.split()[-1].strip()
        if not self.encrypted_password.startswith("grub.pbkdf2."):
            raise BootLoaderError("failed to encrypt bootloader password")

    def write_password_config(self):
        if not self.password and not self.encrypted_password:
            return

        users_file = ROOT_PATH + "/etc/grub.d/01_users"
        header = open(users_file, "w")
        header.write("#!/bin/sh -e\n\n")
        header.write("cat << EOF\n")
        # XXX FIXME: document somewhere that the username is "root"
        header.write("set superusers=\"root\"\n")
        header.write("export superusers\n")
        self._encrypt_password()
        password_line = "password_pbkdf2 root " + self.encrypted_password
        header.write("%s\n" % password_line)
        header.write("EOF\n")
        header.close()
        os.chmod(users_file, 0700)

    def write_config(self):
        self.write_config_console(None)
        # See if we have a password and if so update the boot args before we
        # write out the defaults file.
        if self.password or self.encrypted_password:
            self.boot_args.add("rd.shell=0")
        self.write_defaults()

        # if we fail to setup password auth we should complete the
        # installation so the system is at least bootable
        try:
            self.write_password_config()
        except (BootLoaderError, OSError, RuntimeError) as e:
            log.error("bootloader password setup failed: %s" % e)

        # make sure the default entry is the OS we are installing
        entry_title = "%s Linux, with Linux %s" % (productName,
                                                   self.default.version)
        rc = iutil.execWithRedirect("grub2-set-default",
                                    [entry_title],
                                    root=ROOT_PATH,
                                    stdout="/dev/tty5", stderr="/dev/tty5")
        if rc:
            log.error("failed to set default menu entry to %s" % productName)

        # now tell grub2 to generate the main configuration file
        rc = iutil.execWithRedirect("grub2-mkconfig",
                                    ["-o", self.config_file],
                                    root=ROOT_PATH,
                                    stdout="/dev/tty5", stderr="/dev/tty5")
        if rc:
            raise BootLoaderError("failed to write bootloader configuration")

    #
    # installation
    #

    def install(self, args=None):
        if args is None:
            args = []

        # XXX will installing to multiple drives work as expected with GRUBv2?
        for (stage1dev, stage2dev) in self.install_targets:
            grub_args = args + ["--no-floppy", stage1dev.path]
            if stage1dev == stage2dev:
                # This is hopefully a temporary hack. GRUB2 currently refuses
                # to install to a partition's boot block without --force.
                grub_args.insert(0, '--force')

            rc = iutil.execWithRedirect("grub2-install", grub_args,
                                        stdout="/dev/tty5", stderr="/dev/tty5",
                                        root=ROOT_PATH,
                                        env_prune=['MALLOC_PERTURB_'])
            if rc:
                raise BootLoaderError("bootloader install failed")

    def write(self):
        """ Write the bootloader configuration and install the bootloader. """
        if self.update_only:
            self.update()
            return

        self.write_device_map()
        self.stage2_device.format.sync(root=ROOT_PATH)
        sync()
        self.install()
        sync()
        self.stage2_device.format.sync(root=ROOT_PATH)
        self.write_config()
        sync()
        self.stage2_device.format.sync(root=ROOT_PATH)

class EFIGRUB(GRUB2):
    packages = ["grub2-efi", "efibootmgr", "shim"]
    can_dual_boot = False

    @property
    def _config_dir(self):
        return "efi/EFI/%s" % (self.efi_dir,)

    def __init__(self, platform=None):
        super(EFIGRUB, self).__init__(platform=platform)
        self.efi_dir = 'BOOT'

    def efibootmgr(self, *args, **kwargs):
        if kwargs.pop("capture", False):
            exec_func = iutil.execWithCapture
        else:
            exec_func = iutil.execWithRedirect

        return exec_func("efibootmgr", list(args), **kwargs)

    #
    # installation
    #

    def remove_efi_boot_target(self):
        buf = self.efibootmgr(capture=True)
        for line in buf.splitlines():
            try:
                (slot, _product) = line.split(None, 1)
            except ValueError:
                continue

            if _product == productName:
                slot_id = slot[4:8]
                # slot_id is hex, we can't use .isint and use this regex:
                if not re.match("^[0-9a-fA-F]+$", slot_id):
                    log.warning("failed to parse efi boot slot (%s)" % slot)
                    continue

                rc = self.efibootmgr("-b", slot_id, "-B",
                                     root=ROOT_PATH,
                                     stdout="/dev/tty5", stderr="/dev/tty5")
                if rc:
                    raise BootLoaderError("failed to remove old efi boot entry")

    @property
    def efi_dir_as_efifs_dir(self):
        ret = self._config_dir.replace('efi/', '')
        return "\\" + ret.replace('/', '\\')

    def add_efi_boot_target(self):
        if self.stage1_device.type == "partition":
            boot_disk = self.stage1_device.disk
            boot_part_num = self.stage1_device.partedPartition.number
        elif self.stage1_device.type == "mdarray":
            # FIXME: I'm just guessing here. This probably needs the full
            #        treatment, ie: multiple targets for each member.
            boot_disk = self.stage1_device.parents[0].disk
            boot_part_num = self.stage1_device.parents[0].partedPartition.number
        boot_part_num = str(boot_part_num)

        rc = self.efibootmgr("-c", "-w", "-L", productName,
                             "-d", boot_disk.path, "-p", boot_part_num,
                             "-l",
                             self.efi_dir_as_efifs_dir + "\\shim.efi",
                             root=ROOT_PATH,
                             stdout="/dev/tty5", stderr="/dev/tty5")
        if rc:
            raise BootLoaderError("failed to set new efi boot target")

    def install(self):
        if not flags.leavebootorder:
            self.remove_efi_boot_target()
        self.add_efi_boot_target()

    def update(self):
        self.install()

    #
    # installation
    #
    def write(self):
        """ Write the bootloader configuration and install the bootloader. """
        if self.update_only:
            self.update()
            return

        sync()
        self.stage2_device.format.sync(root=ROOT_PATH)
        self.install()
        self.write_config()


class MacEFIGRUB(EFIGRUB):
    def mactel_config(self):
        if os.path.exists(ROOT_PATH + "/usr/libexec/mactel-boot-setup"):
            rc = iutil.execWithRedirect("/usr/libexec/mactel-boot-setup", [],
                                        root=ROOT_PATH,
                                        stdout="/dev/tty5", stderr="/dev/tty5")
            if rc:
                log.error("failed to configure Mac bootloader")

    def install(self):
        super(MacEFIGRUB, self).install()
        self.mactel_config()


class YabootSILOBase(BootLoader):
    def write_config_password(self, config):
        if self.password:
            config.write("password=%s\n" % self.password)
            config.write("restricted\n")

    def write_config_images(self, config):
        for image in self.images:
            if not isinstance(image, LinuxBootLoaderImage):
                # mac os images are handled specially in the header on mac
                continue

            args = Arguments()
            if self.password or self.encrypted_password:
                args.add("rd.shell=0")
            if image.initrd:
                initrd_line = "\tinitrd=%s/%s\n" % (self.boot_prefix,
                                                    image.initrd)
            else:
                initrd_line = ""

            root_device_spec = image.device.fstabSpec
            if root_device_spec.startswith("/"):
                root_line = "\troot=%s\n" % root_device_spec
            else:
                args.add("root=%s" % root_device_spec)
                root_line = ""

            args.update(self.boot_args)
            log.info("bootloader.py: used boot args: %s " % args)

            stanza = ("image=%(boot_prefix)s%(kernel)s\n"
                      "\tlabel=%(label)s\n"
                      "\tread-only\n"
                      "%(initrd_line)s"
                      "%(root_line)s"
                      "\tappend=\"%(args)s\"\n\n"
                      % {"kernel": image.kernel,  "initrd_line": initrd_line,
                         "label": self.image_label(image),
                         "root_line": root_line, "args": args,
                         "boot_prefix": self.boot_prefix})
            config.write(stanza)


class Yaboot(YabootSILOBase):
    name = "Yaboot"
    _config_file = "yaboot.conf"
    prog = "ybin"
    image_label_attr = "short_label"
    packages = ["yaboot"]

    # stage2 device requirements
    stage2_device_types = ["partition", "mdarray"]
    stage2_device_raid_levels = [mdraid.RAID1]

    #
    # configuration
    #

    @property
    def config_dir(self):
        conf_dir = "/etc"
        if self.stage2_device.format.mountpoint == "/boot":
            conf_dir = "/boot/etc"
        return conf_dir

    @property
    def config_file(self):
        return "%s/%s" % (self.config_dir, self._config_file)

    def write_config_header(self, config):
        if self.stage2_device.type == "mdarray":
            boot_part_num = self.stage2_device.parents[0].partedPartition.number
        else:
            boot_part_num = self.stage2_device.partedPartition.number

        # yaboot.conf timeout is in tenths of a second. Brilliant.
        header = ("# yaboot.conf generated by anaconda\n\n"
                  "boot=%(stage1dev)s\n"
                  "init-message=\"Welcome to %(product)s!\\nHit <TAB> for "
                  "boot options\"\n\n"
                  "partition=%(part_num)d\n"
                  "timeout=%(timeout)d\n"
                  "install=/usr/lib/yaboot/yaboot\n"
                  "delay=5\n"
                  "enablecdboot\n"
                  "enableofboot\n"
                  "enablenetboot\n"
                  % {"stage1dev": self.stage1_device.path,
                     "product": productName, "part_num": boot_part_num,
                     "timeout": self.timeout * 10})
        config.write(header)
        self.write_config_variant_header(config)
        self.write_config_password(config)
        config.write("\n")

    def write_config_variant_header(self, config):
        config.write("nonvram\n")
        config.write("mntpoint=/boot/yaboot\n")
        config.write("usemount\n")

    def write_config_post(self):
        super(Yaboot, self).write_config_post()

        # make symlink in /etc to yaboot.conf if config is in /boot/etc
        etc_yaboot_conf = ROOT_PATH + "/etc/yaboot.conf"
        if not os.access(etc_yaboot_conf, os.R_OK):
            try:
                os.symlink("../boot/etc/yaboot.conf", etc_yaboot_conf)
            except OSError as e:
                log.error("failed to create /etc/yaboot.conf symlink: %s" % e)

    def write_config(self):
        if not os.path.isdir(ROOT_PATH + self.config_dir):
            os.mkdir(ROOT_PATH + self.config_dir)

        # this writes the config
        super(Yaboot, self).write_config()

    #
    # installation
    #

    def install(self):
        args = ["-f", "-C", self.config_file]
        rc = iutil.execWithRedirect(self.prog, args,
                                    stdout="/dev/tty5", stderr="/dev/tty5",
                                    root=ROOT_PATH)
        if rc:
            raise BootLoaderError("bootloader installation failed")


class IPSeriesYaboot(Yaboot):
    prog = "mkofboot"

    #
    # configuration
    #

    def write_config_variant_header(self, config):
        config.write("nonvram\n")   # only on pSeries?
        config.write("fstype=raw\n")

    #
    # installation
    #

    def install(self):
        self.updatePowerPCBootList()

        super(IPSeriesYaboot, self).install()

    def updatePowerPCBootList(self):

        log.debug("updatePowerPCBootList: self.stage1_device.path = %s" % self.stage1_device.path)

        buf = iutil.execWithCapture("nvram",
                                    ["--print-config=boot-device"],
                                    stderr="/dev/tty5")

        if len(buf) == 0:
            log.error ("FAIL: nvram --print-config=boot-device")
            return

        boot_list = buf.strip().split()
        log.debug("updatePowerPCBootList: boot_list = %s" % boot_list)

        buf = iutil.execWithCapture("ofpathname",
                                    [self.stage1_device.path],
                                    stderr="/dev/tty5")

        if len(buf) > 0:
            boot_disk = buf.strip()
            log.debug("updatePowerPCBootList: boot_disk = %s" % boot_disk)
        else:
            log.error("FAIL: ofpathname %s" % self.stage1_device.path)
            return

        # Place the disk containing the PReP partition first.
        # Remove all other occurances of it.
        boot_list = [boot_disk] + filter(lambda x: x != boot_disk, boot_list)

        log.debug("updatePowerPCBootList: updated boot_list = %s" % boot_list)

        update_value = "boot-device=%s" % " ".join(boot_list)

        rc = iutil.execWithRedirect("nvram", ["--update-config", update_value],
                                    stdout="/dev/tty5", stderr="/dev/tty5")
        if rc:
            log.error("FAIL: nvram --update-config %s" % update_value)
        else:
            log.info("Updated PPC boot list with the command: nvram --update-config %s" % update_value)


class IPSeriesGRUB2(GRUB2):

    # GRUB2 sets /boot bootable and not the PReP partition.  This causes the Open Firmware BIOS not
    # to present the disk as a bootable target.  If stage2_bootable is False, then the PReP partition
    # will be marked bootable. Confusing.
    stage2_bootable = False

    #
    # installation
    #

    def install(self):
        if flags.leavebootorder:
            log.info("leavebootorder passed as an option. Will not update the NVRAM boot list.")
        else:
            self.updateNVRAMBootList()

        super(IPSeriesGRUB2, self).install(args=["--no-nvram"])

    # This will update the PowerPC's (ppc) bios boot devive order list
    def updateNVRAMBootList(self):

        log.debug("updateNVRAMBootList: self.stage1_device.path = %s" % self.stage1_device.path)

        buf = iutil.execWithCapture("nvram",
                                    ["--print-config=boot-device"],
                                    stderr="/dev/tty5")

        if len(buf) == 0:
            log.error ("Failed to determine nvram boot device")
            return

        boot_list = buf.strip().replace("\"", "").split()
        log.debug("updateNVRAMBootList: boot_list = %s" % boot_list)

        buf = iutil.execWithCapture("ofpathname",
                                    [self.stage1_device.path],
                                    stderr="/dev/tty5")

        if len(buf) > 0:
            boot_disk = buf.strip()
        else:
            log.error("Failed to translate boot path into device name")
            return

        # Place the disk containing the PReP partition first.
        # Remove all other occurances of it.
        boot_list = [boot_disk] + filter(lambda x: x != boot_disk, boot_list)

        update_value = "boot-device=%s" % " ".join(boot_list)

        rc = iutil.execWithRedirect("nvram", ["--update-config", update_value],
                                    stdout="/dev/tty5", stderr="/dev/tty5")
        if rc:
            log.error("Failed to update new boot device order")

    #
    # In addition to the normal grub configuration variable, add one more to set the size of the
    # console's window to a standard 80x24
    #
    def write_defaults(self):
        super(IPSeriesGRUB2, self).write_defaults()

        defaults_file = "%s%s" % (ROOT_PATH, self.defaults_file)
        defaults = open(defaults_file, "a+")
        # The terminfo's X and Y size, and output location could change in the future
        defaults.write("GRUB_TERMINFO=\"terminfo -g 80x24 console\"\n")
        defaults.close()


class MacYaboot(Yaboot):
    prog = "mkofboot"
    can_dual_boot = True

    #
    # configuration
    #

    def write_config_variant_header(self, config):
        try:
            mac_os = [i for i in self.chain_images if i.label][0]
        except IndexError:
            pass
        else:
            config.write("macosx=%s\n" % mac_os.device.path)

        config.write("magicboot=/usr/lib/yaboot/ofboot\n")


class ZIPL(BootLoader):
    name = "ZIPL"
    config_file = "/etc/zipl.conf"
    packages = ["s390utils-base"]

    # stage2 device requirements
    stage2_device_types = ["partition", "mdarray", "lvmlv"]
    stage2_device_raid_levels = [mdraid.RAID1]

    image_label_attr = "short_label"
    preserve_args = ["cio_ignore"]

    def __init__(self, platform=None):
        super(ZIPL, self).__init__(platform=platform)
        self.stage1_name = None

    #
    # configuration
    #

    @property
    def boot_dir(self):
        return "/boot"

    def write_config_images(self, config):
        for image in self.images:
            args = Arguments()
            if image.initrd:
                initrd_line = "\tramdisk=%s/%s\n" % (self.boot_dir,
                                                     image.initrd)
            else:
                initrd_line = ""
            args.add("root=%s" % image.device.fstabSpec)
            args.update(self.boot_args)
            log.info("bootloader.py: used boot args: %s " % args)
            stanza = ("[%(label)s]\n"
                      "\timage=%(boot_dir)s/%(kernel)s\n"
                      "%(initrd_line)s"
                      "\tparameters=\"%(args)s\"\n"
                      % {"label": self.image_label(image),
                         "kernel": image.kernel, "initrd_line": initrd_line,
                         "args": args,
                         "boot_dir": self.boot_dir})
            config.write(stanza)

    def write_config_header(self, config):
        header = ("[defaultboot]\n"
                  "defaultauto\n"
                  "prompt=1\n"
                  "timeout=%(timeout)d\n"
                  "default=%(default)s\n"
                  "target=/boot\n"
                  % {"timeout": self.timeout,
                     "default": self.image_label(self.default)})
        config.write(header)

    #
    # installation
    #

    def install(self):
        buf = iutil.execWithCapture("zipl", [],
                                    stderr="/dev/tty5",
                                    root=ROOT_PATH,
                                    fatal=True)
        for line in buf.splitlines():
            if line.startswith("Preparing boot device: "):
                # Output here may look like:
                #     Preparing boot device: dasdb (0200).
                #     Preparing boot device: dasdl.
                # We want to extract the device name and pass that.
                name = re.sub(".+?: ", "", line)
                self.stage1_name = re.sub("(\s\(.+\))?\.$", "", name)

        if not self.stage1_name:
            raise BootLoaderError("could not find IPL device")

        # do the reipl
        message = iutil.reIPL(self.stage1_name)
        log.info(message)

class SILO(YabootSILOBase):
    name = "SILO"
    _config_file = "silo.conf"
    message_file = "/etc/silo.message"

    # stage1 device requirements
    stage1_device_types = ["disk"]

    # stage2 device requirements
    stage2_device_types = ["partition"]

    packages = ["silo"]

    image_label_attr = "short_label"

    #
    # configuration
    #

    @property
    def config_dir(self):
        if self.stage2_device.format.mountpoint == "/boot":
            return "/boot"
        else:
            return "/etc"

    @property
    def config_file(self):
        return "%s/%s" % (self.config_dir, self._config_file)

    def write_message_file(self):
        message_file = os.path.normpath(ROOT_PATH + self.message_file)
        f = open(message_file, "w")
        f.write("Welcome to %s!\nHit <TAB> for boot options\n\n" % productName)
        f.close()
        os.chmod(message_file, 0600)

    def write_config_header(self, config):
        header = ("# silo.conf generated by anaconda\n\n"
                  "#boot=%(stage1dev)s\n"
                  "message=%(message)s\n"
                  "timeout=%(timeout)d\n"
                  "partition=%(boot_part_num)d\n"
                  "default=%(default)s\n"
                  % {"stage1dev": self.stage1_device.path,
                     "message": self.message_file, "timeout": self.timeout,
                     "boot_part_num": self.stage1_device.partedPartition.number,
                     "default": self.image_label(self.default)})
        config.write(header)
        self.write_config_password(config)

    def write_config_post(self):
        etc_silo = os.path.normpath(ROOT_PATH + "/etc/" + self._config_file)
        if not os.access(etc_silo, os.R_OK):
            try:
                os.symlink("../boot/%s" % self._config_file, etc_silo)
            except OSError as e:
                log.warning("failed to create /etc/silo.conf symlink: %s" % e)

    def write_config(self):
        self.write_message_file()
        super(SILO, self).write_config()

    #
    # installation
    #

    def install(self):
        backup = "%s/backup.b" % self.config_dir
        args = ["-f", "-C", self.config_file, "-S", backup]
        variant = iutil.getSparcMachine()
        if variant in ("sun4u", "sun4v"):
            args.append("-u")
        else:
            args.append("-U")

        rc = iutil.execWithRedirect("silo", args,
                                    stdout="/dev/tty5", stderr="/dev/tty5",
                                    root=ROOT_PATH)

        if rc:
            raise BootLoaderError("bootloader install failed")


# anaconda-specific functions

def writeSysconfigKernel(storage, version):
    # get the name of the default kernel package based on the version
    kernel_basename = "vmlinuz-" + version
    kernel_file = "/boot/%s" % kernel_basename
    if not os.path.isfile(ROOT_PATH + kernel_file):
        kernel_file = "/boot/efi/EFI/redhat/%s" % kernel_basename
        if not os.path.isfile(ROOT_PATH + kernel_file):
            log.error("failed to recreate path to default kernel image")
            return

    try:
        import rpm
    except ImportError:
        log.error("failed to import rpm python module")
        return

    ts = rpm.TransactionSet(ROOT_PATH)
    mi = ts.dbMatch('basenames', kernel_file)
    try:
        h = mi.next()
    except StopIteration:
        log.error("failed to get package name for default kernel")
        return

    kernel = h.name

    f = open(ROOT_PATH + "/etc/sysconfig/kernel", "w+")
    f.write("# UPDATEDEFAULT specifies if new-kernel-pkg should make\n"
            "# new kernels the default\n")
    # only update the default if we're setting the default to linux (#156678)
    if storage.bootloader.default.device == storage.rootDevice:
        f.write("UPDATEDEFAULT=yes\n")
    else:
        f.write("UPDATEDEFAULT=no\n")
    f.write("\n")
    f.write("# DEFAULTKERNEL specifies the default kernel package type\n")
    f.write("DEFAULTKERNEL=%s\n" % kernel)
    f.close()

def writeBootLoader(storage, payload, instClass):
    """ Write bootloader configuration to disk.

        When we get here, the bootloader will already have a default linux
        image. We only have to add images for the non-default kernels and
        adjust the default to reflect whatever the default variant is.
    """
    from pyanaconda.errors import errorHandler, ERROR_RAISE

    stage1_device = storage.bootloader.stage1_device
    log.info("bootloader stage1 target device is %s" % stage1_device.name)
    stage2_device = storage.bootloader.stage2_device
    log.info("bootloader stage2 target device is %s" % stage2_device.name)

    # get a list of installed kernel packages
    kernel_versions = payload.kernelVersionList
    if not kernel_versions:
        log.warning("no kernel was installed -- bootloader config unchanged")
        return

    # all the linux images' labels are based on the default image's
    base_label = productName
    base_short_label = "linux"

    # The first one is the default kernel. Update the bootloader's default
    # entry to reflect the details of the default kernel.
    version = kernel_versions.pop(0)
    default_image = LinuxBootLoaderImage(device=storage.rootDevice,
                                         version=version,
                                         label=base_label,
                                         short=base_short_label)
    storage.bootloader.add_image(default_image)
    storage.bootloader.default = default_image
    if hasattr(storage.bootloader, 'efi_dir'):
        storage.bootloader.efi_dir = instClass.efi_dir

    # write out /etc/sysconfig/kernel
    writeSysconfigKernel(storage, version)

    # now add an image for each of the other kernels
    for version in kernel_versions:
        label = "%s-%s" % (base_label, version)
        short = "%s-%s" % (base_short_label, version)
        if storage.bootloader.trusted_boot:
            image = TbootLinuxBootLoaderImage(
                                         device=storage.rootDevice,
                                         version=version,
                                         label=label, short=short)
        else:
            image = LinuxBootLoaderImage(device=storage.rootDevice,
                                         version=version,
                                         label=label, short=short)
        storage.bootloader.add_image(image)

    # set up dracut/fips boot args
    # XXX FIXME: do this from elsewhere?
    #storage.bootloader.set_boot_args(keyboard=anaconda.keyboard,
    #                                 storage=anaconda.storage,
    #                                 language=anaconda.instLanguage,
    #                                 network=anaconda.network)
    storage.bootloader.set_boot_args(storage=storage,
                                     payload=payload)

    try:
        storage.bootloader.write()
    except BootLoaderError as e:
        if errorHandler.cb(e) == ERROR_RAISE:
            raise