forked from osbuild/osbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
org.osbuild.grub2.legacy
executable file
·354 lines (284 loc) · 10.2 KB
/
org.osbuild.grub2.legacy
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
#!/usr/bin/python3
import os
import shutil
import string
import sys
import osbuild.api
# The main grub2 configuration file template. Used for UEFI and legacy
GRUB_CFG_TEMPLATE = """
# Created by osbuild
set timeout=${timeout}
# load the grubenv file
load_env
# selection of the next boot entry
if [ "${next_entry}" ] ; then
set default="${next_entry}"
set next_entry=
save_env next_entry
set boot_once=true
else
set default="${saved_entry}"
fi
if [ "${prev_saved_entry}" ]; then
set saved_entry="${prev_saved_entry}"
save_env saved_entry
set prev_saved_entry=
save_env prev_saved_entry
set boot_once=true
fi
function savedefault {
if [ -z "${boot_once}" ]; then
saved_entry="${chosen}"
save_env saved_entry
fi
}
${serial}${terminal_input}${terminal_output}
"""
GRUB_ENTRY_TEMPLATE = """
menuentry '${title}' --class red --class gnu-linux --class gnu --class os --unrestricted --id 'gnulinux-${kernel}-advanced-${id}' {
insmod all_video
set gfxpayload=keep
search --no-floppy --set=root ${search}
linux${loader} ${grub_home}vmlinuz-${kernel} ${cmdline}
initrd${loader} ${grub_home}initramfs-${kernel}.img
}
"""
def fs_spec_decode(spec):
for key in ["uuid", "label", "device"]:
val = spec.get(key)
if not val:
continue
if key == "device":
return None, val
return key.upper(), val
raise ValueError("unknown filesystem type")
def copy_modules(tree, platform):
"""Copy all modules from the build image to /boot"""
target = f"{tree}/boot/grub2/{platform}"
source = f"/usr/lib/grub/{platform}"
os.makedirs(target, exist_ok=True)
for dirent in os.scandir(source):
(_, ext) = os.path.splitext(dirent.name)
if ext not in ('.mod', '.lst'):
continue
if dirent.name == "fdt.lst":
continue
shutil.copy2(f"/{source}/{dirent.name}", target)
def copy_font(tree):
"""Copy a unicode font into /boot"""
os.makedirs(f"{tree}/boot/grub2/fonts", exist_ok=True)
shutil.copy2("/usr/share/grub/unicode.pf2", f"{tree}/boot/grub2/fonts/")
def copy_efi_data(tree, vendor):
"""Copy the EFI binaries & data into /boot/efi"""
for d in ['BOOT', vendor]:
source = f"/boot/efi/EFI/{d}"
target = f"{tree}/boot/efi/EFI/{d}/"
shutil.copytree(source, target,
symlinks=False)
class GrubEntry:
class Product:
def __init__(self, name, version, nick=None):
self.name = name
self.nick = nick
self.version = version
@classmethod
def from_json(cls, data):
name = data["name"]
version = data["version"]
nick = data.get("nick")
return cls(name, version, nick)
def __init__(self, uid, product, kernel):
self.id = uid
self.product = product
self.kernel = kernel
self.default = False
@property
def title(self):
p = self.product
res = f"{p.name} ({self.kernel}) {p.version}"
if p.nick:
res += f" ({p.nick})"
return res
@property
def menu_id(self):
return f"gnulinux-${self.kernel}-advanced-{self.id}"
@classmethod
def from_json(cls, data):
uid = data["id"]
product = cls.Product.from_json(data["product"])
kernel = data["kernel"]
entry = cls(uid, product, kernel)
entry.default = data.get("default", False)
return entry
# pylint: disable=too-many-instance-attributes
class GrubConfig:
def __init__(self, bios, rootfs, bootfs):
self.bios = bios
self.rootfs = rootfs
self.bootfs = bootfs
self.entries = []
self.cmdline = ""
self.default_entry = "saved"
self.disable_recovery = True
self.disable_submenu = True
self.distributor = ""
self.serial = ""
self.terminal = None
self.terminal_input = None
self.terminal_output = None
self.timeout = 0
self.timeout_style = "countdown"
@property
def grubfs(self):
"""The filesystem containing the grub files,
This is either a separate partition (self.bootfs if set) or
the root file system (self.rootfs)
"""
return self.bootfs or self.rootfs
@property
def separate_boot(self):
return self.bootfs is not None
@property
def grub_home(self):
return "/" if self.separate_boot else "/boot/"
def make_terminal_config(self, terminal):
config = getattr(self, terminal)
if not config:
return {}
val = (
"\n" +
terminal +
" " +
" ".join(config)
)
return {terminal: val}
def write(self, tree, path, uefi):
"""Write the grub config to `tree` at `path`"""
path = os.path.join(tree, path)
fs_type, fs_id = fs_spec_decode(self.grubfs)
type2opt = {
"UUID": "--fs-uuid",
"LABEL": "--label"
}
search = type2opt[fs_type] + " " + fs_id if fs_type else fs_id
fs_type, fs_id = fs_spec_decode(self.rootfs)
rootfs = f"{fs_type}={fs_id}" if fs_type else fs_id
loader = "" # default to `linux`, i.e. no suffix
if self.bios.get("platform", "") == "i386-pc":
loader = "efi" if uefi else "16"
# configuration options for the main template
config = {
"timeout": self.timeout,
"cmdline": f"root={rootfs} {self.cmdline}",
"search": search,
"loader": loader,
"grub_home": self.grub_home
}
if self.serial:
config["serial"] = "\n" + self.serial
config.update(self.make_terminal_config("terminal_input"))
config.update(self.make_terminal_config("terminal_output"))
tplt = string.Template(GRUB_CFG_TEMPLATE)
data = tplt.safe_substitute(config)
for entry in self.entries:
config.update({
"id": entry.id,
"title": entry.title,
"kernel": entry.kernel,
})
tplt = string.Template(GRUB_ENTRY_TEMPLATE)
data += "\n" + tplt.safe_substitute(config).lstrip("\n")
data += "\n"
with open(path, "w", encoding="utf8") as cfg:
print(data)
cfg.write(data)
def defaults(self):
# NB: The "GRUB_CMDLINE_LINUX" variable contains the kernel command
# line but without the `root=` part, thus we just use `cmdline`.
data = (
f"GRUB_TIMEOUT={self.timeout}\n"
f'GRUB_CMDLINE_LINUX="{self.cmdline}"\n'
f"GRUB_DISABLE_SUBMENU={str(self.disable_submenu).lower()}\n"
f"GRUB_DISABLE_RECOVERY={str(self.disable_recovery).lower()}\n"
f"GRUB_TIMEOUT_STYLE={self.timeout_style}\n"
f"GRUB_DEFAULT={self.default_entry}\n"
)
if self.distributor:
data += f'GRUB_DISTRIBUTOR="{self.distributor}"\n'
if self.serial:
data += f'GRUB_SERIAL_COMMAND="{self.serial}"\n'
if self.terminal:
val = " ".join(self.terminal)
data += f'GRUB_TERMINAL="{val}"\n'
if self.terminal_input:
val = " ".join(self.terminal_input)
data += f'GRUB_TERMINAL_INPUT="{val}"\n'
if self.terminal_output:
val = " ".join(self.terminal_output)
data += f'GRUB_TERMINAL_OUTPUT="{val}"\n'
return data
# pylint: disable=too-many-statements
def main(tree, options):
root_fs = options["rootfs"]
boot_fs = options.get("bootfs")
bios = options.get("bios")
uefi = options.get("uefi", None)
write_defaults = options.get("write_defaults", True)
# Prepare the actual grub configuration file, will be written further down
cfg = options.get("config", {})
config = GrubConfig(bios, root_fs, boot_fs)
config.cmdline = cfg.get("cmdline", "")
config.default_entry = cfg.get("default", "saved")
config.disable_recovery = cfg.get("disable_recovery", True)
config.disable_submenu = cfg.get("disable_submenu", True)
config.distributor = cfg.get("distributor")
config.serial = cfg.get("serial")
config.terminal = cfg.get("terminal")
config.terminal_input = cfg.get("terminal_input")
config.terminal_output = cfg.get("terminal_output")
config.timeout = cfg.get("timeout", 0)
config.timeout_style = cfg.get("timeout_style", "countdown")
config.entries = [GrubEntry.from_json(e) for e in options["entries"]]
# Create the configuration file that determines how grub.cfg is generated.
if write_defaults:
os.makedirs(f"{tree}/etc/default", exist_ok=True)
with open(f"{tree}/etc/default/grub", "w", encoding="utf8") as default:
default.write(config.defaults())
os.makedirs(f"{tree}/boot/grub2", exist_ok=True)
grubenv = f"{tree}/boot/grub2/grubenv"
with open(grubenv, "w", encoding="utf8") as env:
data = (
"# GRUB Environment Block\n"
)
saved_entry = [
e for e in config.entries if e.default
]
assert len(saved_entry) <= 1, "Multiple default entries"
if saved_entry:
data += f"saved_entry={saved_entry[0].menu_id}\n"
# The 'grubenv' file is, according to the documentation,
# a 'preallocated 1024-byte file'. The empty space is
# needs to be filled with '#' as padding
data += '#' * (1024 - len(data))
assert len(data) == 1024
print(data)
env.write(data)
if uefi is not None:
# UEFI support:
vendor = uefi["vendor"]
# EFI binaries and accompanying data can be installed from
# the build root instead of using an rpm package
if uefi.get('install', False):
copy_efi_data(tree, vendor)
grubcfg = f"boot/efi/EFI/{vendor}/grub.cfg"
config.write(tree, grubcfg, True)
if bios:
# Now actually write the main grub.cfg file
config.write(tree, "boot/grub2/grub.cfg", False)
copy_modules(tree, bios["platform"])
copy_font(tree)
return 0
if __name__ == '__main__':
args = osbuild.api.arguments()
r = main(args["tree"], args["options"])
sys.exit(r)