source: calamares/trunk/fuentes/src/modules/grubcfg/main.py @ 7538

Last change on this file since 7538 was 7538, checked in by kbut, 17 months ago

sync with github

File size: 7.8 KB
Line 
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#
4# === This file is part of Calamares - <https://github.com/calamares> ===
5#
6#   Copyright 2014-2015, Philip Müller <philm@manjaro.org>
7#   Copyright 2015-2017, Teo Mrnjavac <teo@kde.org>
8#   Copyright 2017, Alf Gaida <agaida@siduction.org>
9#   Copyright 2017, Adriaan de Groot <groot@kde.org>
10#   Copyright 2017, Gabriel Craciunescu <crazy@frugalware.org>
11#
12#   Calamares is free software: you can redistribute it and/or modify
13#   it under the terms of the GNU General Public License as published by
14#   the Free Software Foundation, either version 3 of the License, or
15#   (at your option) any later version.
16#
17#   Calamares is distributed in the hope that it will be useful,
18#   but WITHOUT ANY WARRANTY; without even the implied warranty of
19#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20#   GNU General Public License for more details.
21#
22#   You should have received a copy of the GNU General Public License
23#   along with Calamares. If not, see <http://www.gnu.org/licenses/>.
24
25import libcalamares
26import os
27import re
28
29
30def modify_grub_default(partitions, root_mount_point, distributor):
31    """
32    Configures '/etc/default/grub' for hibernation and plymouth.
33
34    @see bootloader/main.py, for similar handling of kernel parameters
35
36    :param partitions:
37    :param root_mount_point:
38    :param distributor:
39    :return:
40    """
41    default_dir = os.path.join(root_mount_point, "etc/default")
42    default_grub = os.path.join(default_dir, "grub")
43    distributor_replace = distributor.replace("'", "'\\''")
44    dracut_bin = libcalamares.utils.target_env_call(
45        ["sh", "-c", "which dracut"]
46        )
47    plymouth_bin = libcalamares.utils.target_env_call(
48        ["sh", "-c", "which plymouth"]
49        )
50
51    # Shell exit value 0 means success
52    have_plymouth = plymouth_bin == 0
53    have_dracut = dracut_bin == 0
54
55    use_splash = ""
56    swap_uuid = ""
57    swap_outer_uuid = ""
58    swap_outer_mappername = None
59
60    if have_plymouth:
61        use_splash = "splash"
62
63    cryptdevice_params = []
64
65    if have_dracut:
66        for partition in partitions:
67            has_luks = "luksMapperName" in partition
68            if partition["fs"] == "linuxswap" and not has_luks:
69                swap_uuid = partition["uuid"]
70
71            if (partition["fs"] == "linuxswap" and has_luks):
72                swap_outer_uuid = partition["luksUuid"]
73                swap_outer_mappername = partition["luksMapperName"]
74
75            if (partition["mountPoint"] == "/" and has_luks):
76                cryptdevice_params = [
77                    "rd.luks.uuid={!s}".format(partition["luksUuid"])
78                    ]
79    else:
80        for partition in partitions:
81            has_luks = "luksMapperName" in partition
82            if partition["fs"] == "linuxswap" and not has_luks:
83                swap_uuid = partition["uuid"]
84
85            if (partition["mountPoint"] == "/" and has_luks):
86                cryptdevice_params = [
87                    "cryptdevice=UUID={!s}:{!s}".format(
88                        partition["luksUuid"], partition["luksMapperName"]
89                        ),
90                    "root=/dev/mapper/{!s}".format(
91                        partition["luksMapperName"]
92                        ),
93                    "resume=/dev/mapper/{!s}".format(
94                        partition["luksMapperName"]
95                        )
96                ]
97
98    kernel_params = ["quiet"]
99
100    if cryptdevice_params:
101        kernel_params.extend(cryptdevice_params)
102
103    if use_splash:
104        kernel_params.append(use_splash)
105
106    if swap_uuid:
107        kernel_params.append("resume=UUID={!s}".format(swap_uuid))
108
109    if have_dracut and swap_outer_uuid:
110        kernel_params.append("rd.luks.uuid={!s}".format(swap_outer_uuid))
111    if have_dracut and swap_outer_mappername:
112        kernel_params.append("resume=/dev/mapper/{!s}".format(
113            swap_outer_mappername))
114
115    distributor_line = "GRUB_DISTRIBUTOR='{!s}'".format(distributor_replace)
116
117    if not os.path.exists(default_dir):
118        os.mkdir(default_dir)
119
120    have_kernel_cmd = False
121    have_distributor_line = False
122
123    if "overwrite" in libcalamares.job.configuration:
124        overwrite = libcalamares.job.configuration["overwrite"]
125    else:
126        overwrite = False
127
128    if os.path.exists(default_grub) and not overwrite:
129        with open(default_grub, 'r') as grub_file:
130            lines = [x.strip() for x in grub_file.readlines()]
131
132        for i in range(len(lines)):
133            if lines[i].startswith("#GRUB_CMDLINE_LINUX_DEFAULT"):
134                kernel_cmd = "GRUB_CMDLINE_LINUX_DEFAULT=\"{!s}\"".format(
135                    " ".join(kernel_params)
136                    )
137                lines[i] = kernel_cmd
138                have_kernel_cmd = True
139            elif lines[i].startswith("GRUB_CMDLINE_LINUX_DEFAULT"):
140                regex = re.compile(r"^GRUB_CMDLINE_LINUX_DEFAULT\s*=\s*")
141                line = regex.sub("", lines[i])
142                line = line.lstrip()
143                line = line.lstrip("\"")
144                line = line.lstrip("'")
145                line = line.rstrip()
146                line = line.rstrip("\"")
147                line = line.rstrip("'")
148                existing_params = line.split()
149
150                for existing_param in existing_params:
151                    existing_param_name = existing_param.split("=")[0]
152
153                    # the only ones we ever add
154                    if existing_param_name not in [
155                            "quiet", "resume", "splash"]:
156                        kernel_params.append(existing_param)
157
158                kernel_cmd = "GRUB_CMDLINE_LINUX_DEFAULT=\"{!s}\"".format(
159                    " ".join(kernel_params)
160                    )
161                lines[i] = kernel_cmd
162                have_kernel_cmd = True
163            elif (lines[i].startswith("#GRUB_DISTRIBUTOR")
164                  or lines[i].startswith("GRUB_DISTRIBUTOR")):
165                lines[i] = distributor_line
166                have_distributor_line = True
167    else:
168        lines = []
169
170        if "defaults" in libcalamares.job.configuration:
171            for key, value in libcalamares.job.configuration[
172                    "defaults"].items():
173                if value.__class__.__name__ == "bool":
174                    if value:
175                        escaped_value = "true"
176                    else:
177                        escaped_value = "false"
178                else:
179                    escaped_value = str(value).replace("'", "'\\''")
180
181                lines.append("{!s}='{!s}'".format(key, escaped_value))
182
183    if not have_kernel_cmd:
184        kernel_cmd = "GRUB_CMDLINE_LINUX_DEFAULT=\"{!s}\"".format(
185            " ".join(kernel_params)
186            )
187        lines.append(kernel_cmd)
188
189    if not have_distributor_line:
190        lines.append(distributor_line)
191
192    if cryptdevice_params:
193        lines.append("GRUB_ENABLE_CRYPTODISK=y")
194
195    with open(default_grub, 'w') as grub_file:
196        grub_file.write("\n".join(lines) + "\n")
197
198    return None
199
200
201def run():
202    """
203    Calls routine with given parameters to modify '/etc/default/grub'.
204
205    :return:
206    """
207
208    fw_type = libcalamares.globalstorage.value("firmwareType")
209
210    if (libcalamares.globalstorage.value("bootLoader") is None
211            and fw_type != "efi"):
212        return None
213
214    partitions = libcalamares.globalstorage.value("partitions")
215
216    if fw_type == "efi":
217        esp_found = False
218
219        for partition in partitions:
220            if (partition["mountPoint"]
221                    == libcalamares.globalstorage.value("efiSystemPartition")):
222                esp_found = True
223
224        if not esp_found:
225            return None
226
227    root_mount_point = libcalamares.globalstorage.value("rootMountPoint")
228    branding = libcalamares.globalstorage.value("branding")
229    distributor = branding["bootloaderEntryName"]
230
231    return modify_grub_default(partitions, root_mount_point, distributor)
Note: See TracBrowser for help on using the repository browser.