2017-04-20 00:22:31 +02:00
#! @python3@/bin/python3 -B
2013-02-02 00:03:45 -05:00
import argparse
2017-05-09 18:56:26 +01:00
import ctypes
Include date and NixOS version in systemd-boot entries
Grub configs include the NixOS version and date they were built, now
systemd can have fun too:
version Generation 99 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-08-30
version Generation 100 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-08-30
version Generation 101 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-08-31
version Generation 102 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-09-01
version Generation 103 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-09-02
version Generation 104 NixOS 17.09beta41.1b8c7786ee, Linux Kernel 4.9.46, Built on 2017-09-02
version Generation 105 NixOS 17.09.git.1b8c778, Linux Kernel 4.9.46, Built on 2017-09-02
2017-09-02 14:27:36 -04:00
import datetime
2023-08-26 18:30:59 +02:00
import errno
Include date and NixOS version in systemd-boot entries
Grub configs include the NixOS version and date they were built, now
systemd can have fun too:
version Generation 99 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-08-30
version Generation 100 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-08-30
version Generation 101 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-08-31
version Generation 102 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-09-01
version Generation 103 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-09-02
version Generation 104 NixOS 17.09beta41.1b8c7786ee, Linux Kernel 4.9.46, Built on 2017-09-02
version Generation 105 NixOS 17.09.git.1b8c778, Linux Kernel 4.9.46, Built on 2017-09-02
2017-09-02 14:27:36 -04:00
import glob
2023-08-26 18:30:59 +02:00
import os
Include date and NixOS version in systemd-boot entries
Grub configs include the NixOS version and date they were built, now
systemd can have fun too:
version Generation 99 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-08-30
version Generation 100 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-08-30
version Generation 101 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-08-31
version Generation 102 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-09-01
version Generation 103 NixOS 17.03.1700.51a83266d1, Linux Kernel 4.9.43, Built on 2017-09-02
version Generation 104 NixOS 17.09beta41.1b8c7786ee, Linux Kernel 4.9.46, Built on 2017-09-02
version Generation 105 NixOS 17.09.git.1b8c778, Linux Kernel 4.9.46, Built on 2017-09-02
2017-09-02 14:27:36 -04:00
import os . path
2023-08-26 18:30:59 +02:00
import re
import shutil
import subprocess
import sys
import warnings
2023-10-25 10:51:44 +00:00
import json
2024-08-13 21:47:05 -04:00
from typing import NamedTuple , Any
2023-10-25 10:51:44 +00:00
from dataclasses import dataclass
2024-01-17 22:52:27 +01:00
# These values will be replaced with actual values during the package build
EFI_SYS_MOUNT_POINT = " @efiSysMountPoint@ "
2024-01-31 21:51:12 -05:00
BOOT_MOUNT_POINT = " @bootMountPoint@ "
LOADER_CONF = f " { EFI_SYS_MOUNT_POINT } /loader/loader.conf " # Always stored on the ESP
NIXOS_DIR = " @nixosDir@ "
2024-01-17 22:52:27 +01:00
TIMEOUT = " @timeout@ "
2024-06-29 18:37:54 +02:00
EDITOR = " @editor@ " == " 1 " # noqa: PLR0133
2024-01-17 22:52:27 +01:00
CONSOLE_MODE = " @consoleMode@ "
BOOTSPEC_TOOLS = " @bootspecTools@ "
DISTRO_NAME = " @distroName@ "
NIX = " @nix@ "
SYSTEMD = " @systemd@ "
CONFIGURATION_LIMIT = int ( " @configurationLimit@ " )
2023-09-04 14:12:24 +02:00
REBOOT_FOR_BITLOCKER = bool ( " @rebootForBitlocker@ " )
2024-01-17 22:52:27 +01:00
CAN_TOUCH_EFI_VARIABLES = " @canTouchEfiVariables@ "
GRACEFUL = " @graceful@ "
COPY_EXTRA_FILES = " @copyExtraFiles@ "
2024-01-31 21:51:12 -05:00
CHECK_MOUNTPOINTS = " @checkMountpoints@ "
2024-08-20 22:28:24 -07:00
STORE_DIR = " @storeDir@ "
2023-10-25 10:51:44 +00:00
@dataclass
class BootSpec :
init : str
initrd : str
kernel : str
2024-06-29 18:43:00 +02:00
kernelParams : list [ str ] # noqa: N815
2023-10-25 10:51:44 +00:00
label : str
system : str
toplevel : str
2024-06-29 18:43:00 +02:00
specialisations : dict [ str , " BootSpec " ]
2024-06-29 18:37:54 +02:00
sortKey : str # noqa: N815
2024-06-12 17:02:35 -07:00
devicetree : str | None = None # noqa: N815
2024-06-29 18:37:54 +02:00
initrdSecrets : str | None = None # noqa: N815
2023-10-25 10:51:44 +00:00
2023-08-26 18:30:59 +02:00
libc = ctypes . CDLL ( " libc.so.6 " )
2024-06-29 18:22:32 +02:00
FILE = None | int
2024-06-29 18:43:00 +02:00
def run ( cmd : list [ str ] , stdout : FILE = None ) - > subprocess . CompletedProcess [ str ] :
2024-06-29 18:22:32 +02:00
return subprocess . run ( cmd , check = True , text = True , stdout = stdout )
2022-01-23 22:42:54 +01:00
class SystemIdentifier ( NamedTuple ) :
2023-08-26 18:38:26 +02:00
profile : str | None
2022-01-23 22:42:54 +01:00
generation : int
2023-08-26 18:38:26 +02:00
specialisation : str | None
2021-01-03 18:29:34 +00:00
2021-01-10 14:09:07 +01:00
def copy_if_not_exists ( source : str , dest : str ) - > None :
2013-02-02 00:03:45 -05:00
if not os . path . exists ( dest ) :
shutil . copyfile ( source , dest )
2021-01-10 14:09:07 +01:00
2023-08-26 18:38:26 +02:00
def generation_dir ( profile : str | None , generation : int ) - > str :
2017-06-24 21:33:34 +02:00
if profile :
return " /nix/var/nix/profiles/system-profiles/ %s - %d -link " % ( profile , generation )
else :
return " /nix/var/nix/profiles/system- %d -link " % ( generation )
2013-02-02 00:03:45 -05:00
2023-08-26 18:38:26 +02:00
def system_dir ( profile : str | None , generation : int , specialisation : str | None ) - > str :
2021-01-03 18:29:34 +00:00
d = generation_dir ( profile , generation )
if specialisation :
return os . path . join ( d , " specialisation " , specialisation )
else :
return d
2024-08-13 21:47:05 -04:00
BOOT_ENTRY = """ title {title}
sort - key { sort_key }
version Generation { generation } { description }
linux { kernel }
initrd { initrd }
options { kernel_params }
"""
def generation_conf_filename ( profile : str | None , generation : int , specialisation : str | None ) - > str :
pieces = [
" nixos " ,
profile or None ,
" generation " ,
str ( generation ) ,
f " specialisation- { specialisation } " if specialisation else None ,
]
return " - " . join ( p for p in pieces if p ) + " .conf "
def write_loader_conf ( profile : str | None , generation : int , specialisation : str | None ) - > None :
with open ( f " { LOADER_CONF } .tmp " , ' w ' ) as f :
2024-08-05 08:48:54 +00:00
f . write ( f " timeout { TIMEOUT } \n " )
2024-08-13 21:47:05 -04:00
f . write ( " default %s \n " % generation_conf_filename ( profile , generation , specialisation ) )
2024-01-17 22:52:27 +01:00
if not EDITOR :
2023-08-26 18:50:04 +02:00
f . write ( " editor 0 \n " )
2023-09-04 14:12:24 +02:00
if REBOOT_FOR_BITLOCKER :
2024-08-20 22:30:57 -07:00
f . write ( " reboot-for-bitlocker yes \n " )
2024-01-17 22:52:27 +01:00
f . write ( f " console-mode { CONSOLE_MODE } \n " )
2023-10-10 10:53:58 +02:00
f . flush ( )
os . fsync ( f . fileno ( ) )
2024-01-31 21:51:12 -05:00
os . rename ( f " { LOADER_CONF } .tmp " , LOADER_CONF )
2013-02-02 00:03:45 -05:00
2021-01-10 14:09:07 +01:00
2023-10-25 10:51:44 +00:00
def get_bootspec ( profile : str | None , generation : int ) - > BootSpec :
2023-11-16 23:48:19 +00:00
system_directory = system_dir ( profile , generation , None )
boot_json_path = os . path . realpath ( " %s / %s " % ( system_directory , " boot.json " ) )
if os . path . isfile ( boot_json_path ) :
boot_json_f = open ( boot_json_path , ' r ' )
bootspec_json = json . load ( boot_json_f )
else :
2024-06-29 18:22:32 +02:00
boot_json_str = run (
[
f " { BOOTSPEC_TOOLS } /bin/synthesize " ,
" --version " ,
" 1 " ,
system_directory ,
" /dev/stdout " ,
] ,
stdout = subprocess . PIPE ,
) . stdout
2023-11-16 23:48:19 +00:00
bootspec_json = json . loads ( boot_json_str )
2023-10-25 10:51:44 +00:00
return bootspec_from_json ( bootspec_json )
2017-04-02 14:51:09 -04:00
2024-06-29 18:43:00 +02:00
def bootspec_from_json ( bootspec_json : dict [ str , Any ] ) - > BootSpec :
2023-10-25 10:51:44 +00:00
specialisations = bootspec_json [ ' org.nixos.specialisation.v1 ' ]
specialisations = { k : bootspec_from_json ( v ) for k , v in specialisations . items ( ) }
systemd-boot: introduce options to set a sort-key for systemd-boot entries
Without sort-keys specified on entries, the entries are sorted only by
file name (in decreasing order, so starting at the end of the alphabet!),
without taking any other fields into account (see
[the boot loader specification reference][1]).
Moreover, entries without a sort-key are always ordered after all
entries with a sort-key, so by not adding a sort-key to the NixOS ones,
we cannot add a sort-key to any other entry while keeping it below the
NixOS entries.
So currently we have options to set the file names for additional entries like
memtest and netbootxyz.
However, as mentioned above, the sorting by file name is not very intuitive and
actually sorts in the opposite order of what is currently mentioned in the option
descriptions.
With this commit, we set a configurable sort-key on all NixOS entries,
and add options for setting the sort-keys for the memtest and netbootxyz
entries.
The sorting by sort-key is more intuitive (it starts at the start of the
alphabet) and also takes into account the machine-id and version for entries
with identical sort-keys.
We use a bootspec extension to store the sort keys, which allows us to
redefine the sort key for individual specialisations without needing any
special casing.
[1]: https://uapi-group.org/specifications/specs/boot_loader_specification/#sorting
2024-01-24 18:15:28 +01:00
systemdBootExtension = bootspec_json . get ( ' org.nixos.systemd-boot ' , { } )
sortKey = systemdBootExtension . get ( ' sortKey ' , ' nixos ' )
2024-06-12 17:02:35 -07:00
devicetree = systemdBootExtension . get ( ' devicetree ' )
systemd-boot: introduce options to set a sort-key for systemd-boot entries
Without sort-keys specified on entries, the entries are sorted only by
file name (in decreasing order, so starting at the end of the alphabet!),
without taking any other fields into account (see
[the boot loader specification reference][1]).
Moreover, entries without a sort-key are always ordered after all
entries with a sort-key, so by not adding a sort-key to the NixOS ones,
we cannot add a sort-key to any other entry while keeping it below the
NixOS entries.
So currently we have options to set the file names for additional entries like
memtest and netbootxyz.
However, as mentioned above, the sorting by file name is not very intuitive and
actually sorts in the opposite order of what is currently mentioned in the option
descriptions.
With this commit, we set a configurable sort-key on all NixOS entries,
and add options for setting the sort-keys for the memtest and netbootxyz
entries.
The sorting by sort-key is more intuitive (it starts at the start of the
alphabet) and also takes into account the machine-id and version for entries
with identical sort-keys.
We use a bootspec extension to store the sort keys, which allows us to
redefine the sort key for individual specialisations without needing any
special casing.
[1]: https://uapi-group.org/specifications/specs/boot_loader_specification/#sorting
2024-01-24 18:15:28 +01:00
return BootSpec (
* * bootspec_json [ ' org.nixos.bootspec.v1 ' ] ,
specialisations = specialisations ,
2024-06-12 17:02:35 -07:00
sortKey = sortKey ,
devicetree = devicetree ,
systemd-boot: introduce options to set a sort-key for systemd-boot entries
Without sort-keys specified on entries, the entries are sorted only by
file name (in decreasing order, so starting at the end of the alphabet!),
without taking any other fields into account (see
[the boot loader specification reference][1]).
Moreover, entries without a sort-key are always ordered after all
entries with a sort-key, so by not adding a sort-key to the NixOS ones,
we cannot add a sort-key to any other entry while keeping it below the
NixOS entries.
So currently we have options to set the file names for additional entries like
memtest and netbootxyz.
However, as mentioned above, the sorting by file name is not very intuitive and
actually sorts in the opposite order of what is currently mentioned in the option
descriptions.
With this commit, we set a configurable sort-key on all NixOS entries,
and add options for setting the sort-keys for the memtest and netbootxyz
entries.
The sorting by sort-key is more intuitive (it starts at the start of the
alphabet) and also takes into account the machine-id and version for entries
with identical sort-keys.
We use a bootspec extension to store the sort keys, which allows us to
redefine the sort key for individual specialisations without needing any
special casing.
[1]: https://uapi-group.org/specifications/specs/boot_loader_specification/#sorting
2024-01-24 18:15:28 +01:00
)
2021-01-10 14:09:07 +01:00
2023-10-25 10:51:44 +00:00
def copy_from_file ( file : str , dry_run : bool = False ) - > str :
store_file_path = os . path . realpath ( file )
2013-02-02 00:03:45 -05:00
suffix = os . path . basename ( store_file_path )
2024-08-20 22:28:24 -07:00
store_subdir = os . path . relpath ( store_file_path , start = STORE_DIR ) . split ( os . path . sep ) [ 0 ]
efi_file_path = f " { NIXOS_DIR } / { suffix } .efi " if suffix == store_subdir else f " { NIXOS_DIR } / { store_subdir } - { suffix } .efi "
2014-02-03 17:41:06 -05:00
if not dry_run :
2024-01-31 21:51:12 -05:00
copy_if_not_exists ( store_file_path , f " { BOOT_MOUNT_POINT } { efi_file_path } " )
2013-02-02 00:03:45 -05:00
return efi_file_path
2024-08-20 22:28:24 -07:00
2024-08-13 21:47:05 -04:00
def write_entry ( profile : str | None , generation : int , specialisation : str | None ,
2024-10-09 15:07:58 +02:00
machine_id : str | None , bootspec : BootSpec , current : bool ) - > None :
2023-10-25 10:51:44 +00:00
if specialisation :
bootspec = bootspec . specialisations [ specialisation ]
kernel = copy_from_file ( bootspec . kernel )
initrd = copy_from_file ( bootspec . initrd )
2024-06-12 17:02:35 -07:00
devicetree = copy_from_file ( bootspec . devicetree ) if bootspec . devicetree is not None else None
2023-01-19 19:18:19 +01:00
2024-01-17 22:52:27 +01:00
title = " {name} {profile} {specialisation} " . format (
name = DISTRO_NAME ,
2023-01-19 19:18:19 +01:00
profile = " [ " + profile + " ] " if profile else " " ,
specialisation = " ( %s ) " % specialisation if specialisation else " " )
2017-04-02 14:51:09 -04:00
try :
2024-01-04 02:40:41 +01:00
if bootspec . initrdSecrets is not None :
2024-06-29 18:22:32 +02:00
run ( [ bootspec . initrdSecrets , f " { BOOT_MOUNT_POINT } %s " % ( initrd ) ] )
2023-01-19 19:18:19 +01:00
except subprocess . CalledProcessError :
if current :
print ( " failed to create initrd secrets! " , file = sys . stderr )
sys . exit ( 1 )
else :
print ( " warning: failed to create initrd secrets "
f ' for " { title } - Configuration { generation } " , an older generation ' , file = sys . stderr )
print ( " note: this is normal after having removed "
" or renamed a file in `boot.initrd.secrets` " , file = sys . stderr )
2024-08-13 21:47:05 -04:00
entry_file = f " { BOOT_MOUNT_POINT } /loader/entries/%s " % (
generation_conf_filename ( profile , generation , specialisation ) )
tmp_path = " %s .tmp " % ( entry_file )
2023-10-25 10:51:44 +00:00
kernel_params = " init= %s " % bootspec . init
2024-08-13 21:47:05 -04:00
2023-10-25 10:51:44 +00:00
kernel_params = kernel_params + " " . join ( bootspec . kernelParams )
build_time = int ( os . path . getctime ( system_dir ( profile , generation , specialisation ) ) )
build_date = datetime . datetime . fromtimestamp ( build_time ) . strftime ( ' %F ' )
2024-08-13 21:47:05 -04:00
with open ( tmp_path , ' w ' ) as f :
f . write ( BOOT_ENTRY . format ( title = title ,
sort_key = bootspec . sortKey ,
generation = generation ,
kernel = kernel ,
initrd = initrd ,
kernel_params = kernel_params ,
description = f " { bootspec . label } , built on { build_date } " ) )
if machine_id is not None :
f . write ( " machine-id %s \n " % machine_id )
if devicetree is not None :
f . write ( " devicetree %s \n " % devicetree )
f . flush ( )
os . fsync ( f . fileno ( ) )
os . rename ( tmp_path , entry_file )
2021-01-10 14:09:07 +01:00
2023-08-26 18:38:26 +02:00
def get_generations ( profile : str | None = None ) - > list [ SystemIdentifier ] :
2024-06-29 18:22:32 +02:00
gen_list = run (
[
f " { NIX } /bin/nix-env " ,
" --list-generations " ,
" -p " ,
" /nix/var/nix/profiles/ %s "
% ( " system-profiles/ " + profile if profile else " system " ) ,
] ,
stdout = subprocess . PIPE ,
) . stdout
gen_lines = gen_list . split ( " \n " )
2013-02-02 00:03:45 -05:00
gen_lines . pop ( )
2019-06-22 20:10:03 +02:00
2024-01-17 22:52:27 +01:00
configurationLimit = CONFIGURATION_LIMIT
2022-01-23 22:42:54 +01:00
configurations = [
SystemIdentifier (
profile = profile ,
generation = int ( line . split ( ) [ 0 ] ) ,
specialisation = None
)
for line in gen_lines
]
2021-01-03 18:29:34 +00:00
return configurations [ - configurationLimit : ]
2024-08-13 21:47:05 -04:00
def remove_old_entries ( gens : list [ SystemIdentifier ] ) - > None :
rex_profile = re . compile ( r " ^ " + re . escape ( BOOT_MOUNT_POINT ) + r " /loader/entries/nixos-(.*)-generation-.* \ .conf$ " )
rex_generation = re . compile ( r " ^ " + re . escape ( BOOT_MOUNT_POINT ) + r " /loader/entries/nixos.*-generation-([0-9]+)(-specialisation-.*)? \ .conf$ " )
2014-02-03 17:41:06 -05:00
known_paths = [ ]
for gen in gens :
2023-10-25 10:51:44 +00:00
bootspec = get_bootspec ( gen . profile , gen . generation )
known_paths . append ( copy_from_file ( bootspec . kernel , True ) )
known_paths . append ( copy_from_file ( bootspec . initrd , True ) )
2024-08-13 21:47:05 -04:00
for path in glob . iglob ( f " { BOOT_MOUNT_POINT } /loader/entries/nixos*-generation-[1-9]*.conf " ) :
if rex_profile . match ( path ) :
prof = rex_profile . sub ( r " \ 1 " , path )
else :
prof = None
try :
gen_number = int ( rex_generation . sub ( r " \ 1 " , path ) )
except ValueError :
continue
if ( prof , gen_number , None ) not in gens :
os . unlink ( path )
for path in glob . iglob ( f " { BOOT_MOUNT_POINT } / { NIXOS_DIR } /* " ) :
2024-06-29 18:02:14 +02:00
if path not in known_paths and not os . path . isdir ( path ) :
2013-02-02 00:03:45 -05:00
os . unlink ( path )
2024-08-13 21:47:05 -04:00
2024-01-31 21:51:12 -05:00
def cleanup_esp ( ) - > None :
for path in glob . iglob ( f " { EFI_SYS_MOUNT_POINT } /loader/entries/nixos* " ) :
os . unlink ( path )
if os . path . isdir ( f " { EFI_SYS_MOUNT_POINT } / { NIXOS_DIR } " ) :
shutil . rmtree ( f " { EFI_SYS_MOUNT_POINT } / { NIXOS_DIR } " )
2023-08-26 18:38:26 +02:00
def get_profiles ( ) - > list [ str ] :
2017-06-24 21:33:34 +02:00
if os . path . isdir ( " /nix/var/nix/profiles/system-profiles/ " ) :
return [ x
for x in os . listdir ( " /nix/var/nix/profiles/system-profiles/ " )
if not x . endswith ( " -link " ) ]
else :
return [ ]
2023-08-26 18:31:52 +02:00
def install_bootloader ( args : argparse . Namespace ) - > None :
2017-02-20 13:25:08 +01:00
try :
with open ( " /etc/machine-id " ) as machine_file :
2025-01-20 02:18:03 -08:00
machine_id = machine_file . readlines ( ) [ 0 ] . strip ( )
2017-02-20 13:25:08 +01:00
except IOError as e :
if e . errno != errno . ENOENT :
raise
2024-10-09 15:07:58 +02:00
machine_id = None
2017-02-20 13:25:08 +01:00
2016-09-30 13:28:42 +02:00
if os . getenv ( " NIXOS_INSTALL_GRUB " ) == " 1 " :
warnings . warn ( " NIXOS_INSTALL_GRUB env var deprecated, use NIXOS_INSTALL_BOOTLOADER " , DeprecationWarning )
os . environ [ " NIXOS_INSTALL_BOOTLOADER " ] = " 1 "
2023-01-16 15:31:52 -06:00
# flags to pass to bootctl install/update
bootctl_flags = [ ]
2024-01-31 21:51:12 -05:00
if BOOT_MOUNT_POINT != EFI_SYS_MOUNT_POINT :
bootctl_flags . append ( f " --boot-path= { BOOT_MOUNT_POINT } " )
2024-01-17 22:52:27 +01:00
if CAN_TOUCH_EFI_VARIABLES != " 1 " :
2023-01-16 15:31:52 -06:00
bootctl_flags . append ( " --no-variables " )
2024-01-17 22:52:27 +01:00
if GRACEFUL == " 1 " :
2023-01-16 15:31:52 -06:00
bootctl_flags . append ( " --graceful " )
2016-09-30 13:28:42 +02:00
if os . getenv ( " NIXOS_INSTALL_BOOTLOADER " ) == " 1 " :
2017-02-20 14:28:53 +01:00
# bootctl uses fopen() with modes "wxe" and fails if the file exists.
2024-01-31 21:51:12 -05:00
if os . path . exists ( LOADER_CONF ) :
os . unlink ( LOADER_CONF )
2017-02-20 14:28:53 +01:00
2024-06-29 18:22:32 +02:00
run (
[ f " { SYSTEMD } /bin/bootctl " , f " --esp-path= { EFI_SYS_MOUNT_POINT } " ]
+ bootctl_flags
+ [ " install " ]
)
2020-06-14 13:16:30 -04:00
else :
# Update bootloader to latest if needed
2024-06-29 18:22:32 +02:00
available_out = run (
[ f " { SYSTEMD } /bin/bootctl " , " --version " ] , stdout = subprocess . PIPE
) . stdout . split ( ) [ 2 ]
installed_out = run (
[ f " { SYSTEMD } /bin/bootctl " , f " --esp-path= { EFI_SYS_MOUNT_POINT } " , " status " ] ,
stdout = subprocess . PIPE ,
) . stdout
2020-06-14 13:16:30 -04:00
# See status_binaries() in systemd bootctl.c for code which generates this
2024-07-13 11:57:07 +09:00
# Matches
# Available Boot Loaders on ESP:
# ESP: /boot (/dev/disk/by-partuuid/9b39b4c4-c48b-4ebf-bfea-a56b2395b7e0)
# File: └─/EFI/systemd/systemd-bootx64.efi (systemd-boot 255.2)
# But also:
# Available Boot Loaders on ESP:
# ESP: /boot (/dev/disk/by-partuuid/9b39b4c4-c48b-4ebf-bfea-a56b2395b7e0)
# File: ├─/EFI/systemd/HashTool.efi
# └─/EFI/systemd/systemd-bootx64.efi (systemd-boot 255.2)
installed_match = re . search ( r " ^ \ W+.*/EFI/(?:BOOT|systemd)/.* \ .efi \ (systemd-boot ([ \ d.]+[^)]*) \ )$ " ,
nixos/systemd-boot: fix systemd-boot-builder dowgrade to fail
Since, 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c systemd-boot-builder
is broken in two ways:
* if no systemd-boot is currently installed *and* the NIXOS_INSTALL_BOOTLOADER
env variable is not set, it will try to run "bootctl update", which will fail
* if the currently installed systemd-boot version is newer than the version
we're about to install, it will also try to run "bootctl update", which will fail
This patch changes the behaviour,
* for the first case to still fail, but not even bother to try running
"bootctl update" and instead erroring out with an exception
* for the second case to leave the newer version in place, restoring
the pre - 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c behaviour
To do the proper version check a new "should_update" helper function was introduced,
mimicing the compare_product C function from bootctl. If the following systemd
issue gets resolved, we would have a nice way to get rid of this function:
> https://github.com/systemd/systemd/issues/23450
This change allows to again switch to a different NixOS configuration which contains
an older systemd-boot.
Co-authored-by: Martin Weinelt <mweinelt@users.noreply.github.com>
2022-05-13 12:09:25 +02:00
installed_out , re . IGNORECASE | re . MULTILINE )
2021-10-12 09:46:54 -04:00
nixos/systemd-boot: fix systemd-boot-builder dowgrade to fail
Since, 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c systemd-boot-builder
is broken in two ways:
* if no systemd-boot is currently installed *and* the NIXOS_INSTALL_BOOTLOADER
env variable is not set, it will try to run "bootctl update", which will fail
* if the currently installed systemd-boot version is newer than the version
we're about to install, it will also try to run "bootctl update", which will fail
This patch changes the behaviour,
* for the first case to still fail, but not even bother to try running
"bootctl update" and instead erroring out with an exception
* for the second case to leave the newer version in place, restoring
the pre - 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c behaviour
To do the proper version check a new "should_update" helper function was introduced,
mimicing the compare_product C function from bootctl. If the following systemd
issue gets resolved, we would have a nice way to get rid of this function:
> https://github.com/systemd/systemd/issues/23450
This change allows to again switch to a different NixOS configuration which contains
an older systemd-boot.
Co-authored-by: Martin Weinelt <mweinelt@users.noreply.github.com>
2022-05-13 12:09:25 +02:00
available_match = re . search ( r " ^ \ ((.*) \ )$ " , available_out )
2021-10-12 09:46:54 -04:00
nixos/systemd-boot: fix systemd-boot-builder dowgrade to fail
Since, 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c systemd-boot-builder
is broken in two ways:
* if no systemd-boot is currently installed *and* the NIXOS_INSTALL_BOOTLOADER
env variable is not set, it will try to run "bootctl update", which will fail
* if the currently installed systemd-boot version is newer than the version
we're about to install, it will also try to run "bootctl update", which will fail
This patch changes the behaviour,
* for the first case to still fail, but not even bother to try running
"bootctl update" and instead erroring out with an exception
* for the second case to leave the newer version in place, restoring
the pre - 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c behaviour
To do the proper version check a new "should_update" helper function was introduced,
mimicing the compare_product C function from bootctl. If the following systemd
issue gets resolved, we would have a nice way to get rid of this function:
> https://github.com/systemd/systemd/issues/23450
This change allows to again switch to a different NixOS configuration which contains
an older systemd-boot.
Co-authored-by: Martin Weinelt <mweinelt@users.noreply.github.com>
2022-05-13 12:09:25 +02:00
if installed_match is None :
2025-05-20 15:38:57 +02:00
raise Exception ( " Could not find any previously installed systemd-boot. If you are switching to systemd-boot from a different bootloader, you need to run `nixos-rebuild switch --install-bootloader` " )
nixos/systemd-boot: fix systemd-boot-builder dowgrade to fail
Since, 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c systemd-boot-builder
is broken in two ways:
* if no systemd-boot is currently installed *and* the NIXOS_INSTALL_BOOTLOADER
env variable is not set, it will try to run "bootctl update", which will fail
* if the currently installed systemd-boot version is newer than the version
we're about to install, it will also try to run "bootctl update", which will fail
This patch changes the behaviour,
* for the first case to still fail, but not even bother to try running
"bootctl update" and instead erroring out with an exception
* for the second case to leave the newer version in place, restoring
the pre - 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c behaviour
To do the proper version check a new "should_update" helper function was introduced,
mimicing the compare_product C function from bootctl. If the following systemd
issue gets resolved, we would have a nice way to get rid of this function:
> https://github.com/systemd/systemd/issues/23450
This change allows to again switch to a different NixOS configuration which contains
an older systemd-boot.
Co-authored-by: Martin Weinelt <mweinelt@users.noreply.github.com>
2022-05-13 12:09:25 +02:00
if available_match is None :
raise Exception ( " could not determine systemd-boot version " )
2021-10-12 09:46:54 -04:00
2023-10-10 10:12:41 +02:00
installed_version = installed_match . group ( 1 )
available_version = available_match . group ( 1 )
nixos/systemd-boot: fix systemd-boot-builder dowgrade to fail
Since, 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c systemd-boot-builder
is broken in two ways:
* if no systemd-boot is currently installed *and* the NIXOS_INSTALL_BOOTLOADER
env variable is not set, it will try to run "bootctl update", which will fail
* if the currently installed systemd-boot version is newer than the version
we're about to install, it will also try to run "bootctl update", which will fail
This patch changes the behaviour,
* for the first case to still fail, but not even bother to try running
"bootctl update" and instead erroring out with an exception
* for the second case to leave the newer version in place, restoring
the pre - 4ddc78818e4d69605f49f5f8faa22fb4601b0a0c behaviour
To do the proper version check a new "should_update" helper function was introduced,
mimicing the compare_product C function from bootctl. If the following systemd
issue gets resolved, we would have a nice way to get rid of this function:
> https://github.com/systemd/systemd/issues/23450
This change allows to again switch to a different NixOS configuration which contains
an older systemd-boot.
Co-authored-by: Martin Weinelt <mweinelt@users.noreply.github.com>
2022-05-13 12:09:25 +02:00
2022-05-31 16:42:33 +02:00
if installed_version < available_version :
2023-10-10 10:12:41 +02:00
print ( " updating systemd-boot from %s to %s " % ( installed_version , available_version ) )
2024-06-29 18:22:32 +02:00
run (
[ f " { SYSTEMD } /bin/bootctl " , f " --esp-path= { EFI_SYS_MOUNT_POINT } " ]
+ bootctl_flags
+ [ " update " ]
)
2020-06-14 13:16:30 -04:00
2024-01-31 21:51:12 -05:00
os . makedirs ( f " { BOOT_MOUNT_POINT } / { NIXOS_DIR } " , exist_ok = True )
os . makedirs ( f " { BOOT_MOUNT_POINT } /loader/entries " , exist_ok = True )
2016-09-30 13:28:42 +02:00
2017-06-24 21:33:34 +02:00
gens = get_generations ( )
for profile in get_profiles ( ) :
gens + = get_generations ( profile )
2024-08-13 21:47:05 -04:00
remove_old_entries ( gens )
2024-01-31 21:51:12 -05:00
2016-09-30 13:28:42 +02:00
for gen in gens :
2021-02-28 11:45:03 +01:00
try :
2023-10-25 10:51:44 +00:00
bootspec = get_bootspec ( gen . profile , gen . generation )
is_default = os . path . dirname ( bootspec . init ) == args . default_config
2024-08-13 21:47:05 -04:00
write_entry ( * gen , machine_id , bootspec , current = is_default )
2023-10-25 10:51:44 +00:00
for specialisation in bootspec . specialisations . keys ( ) :
2024-08-13 21:47:05 -04:00
write_entry ( gen . profile , gen . generation , specialisation , machine_id , bootspec , current = is_default )
2023-01-19 19:18:19 +01:00
if is_default :
2024-08-13 21:47:05 -04:00
write_loader_conf ( * gen )
2021-02-28 11:45:03 +01:00
except OSError as e :
2022-12-16 20:43:22 +01:00
# See https://github.com/NixOS/nixpkgs/issues/114552
if e . errno == errno . EINVAL :
profile = f " profile ' { gen . profile } ' " if gen . profile else " default profile "
print ( " ignoring {} in the list of boot entries because of the following error: \n {} " . format ( profile , e ) , file = sys . stderr )
else :
raise e
2016-09-30 13:28:42 +02:00
2024-01-31 21:51:12 -05:00
if BOOT_MOUNT_POINT != EFI_SYS_MOUNT_POINT :
# Cleanup any entries in ESP if xbootldrMountPoint is set.
# If the user later unsets xbootldrMountPoint, entries in XBOOTLDR will not be cleaned up
# automatically, as we don't have information about the mount point anymore.
cleanup_esp ( )
for root , _ , files in os . walk ( f " { BOOT_MOUNT_POINT } / { NIXOS_DIR } /.extra-files " , topdown = False ) :
relative_root = root . removeprefix ( f " { BOOT_MOUNT_POINT } / { NIXOS_DIR } /.extra-files " ) . removeprefix ( " / " )
actual_root = os . path . join ( f " { BOOT_MOUNT_POINT } " , relative_root )
2021-12-12 22:44:02 +11:00
for file in files :
actual_file = os . path . join ( actual_root , file )
if os . path . exists ( actual_file ) :
os . unlink ( actual_file )
os . unlink ( os . path . join ( root , file ) )
if not len ( os . listdir ( actual_root ) ) :
os . rmdir ( actual_root )
os . rmdir ( root )
2024-01-31 21:51:12 -05:00
os . makedirs ( f " { BOOT_MOUNT_POINT } / { NIXOS_DIR } /.extra-files " , exist_ok = True )
2019-05-05 20:16:19 +09:00
2024-06-29 18:22:32 +02:00
run ( [ COPY_EXTRA_FILES ] )
2019-05-05 20:16:19 +09:00
2023-08-26 18:31:52 +02:00
def main ( ) - > None :
2024-01-17 22:52:27 +01:00
parser = argparse . ArgumentParser ( description = f " Update { DISTRO_NAME } -related systemd-boot files " )
parser . add_argument ( ' default_config ' , metavar = ' DEFAULT-CONFIG ' , help = f " The default { DISTRO_NAME } config to boot " )
2023-08-26 18:31:52 +02:00
args = parser . parse_args ( )
2024-06-29 18:22:32 +02:00
run ( [ CHECK_MOUNTPOINTS ] )
2024-01-31 21:51:12 -05:00
2023-08-26 18:31:52 +02:00
try :
install_bootloader ( args )
finally :
# Since fat32 provides little recovery facilities after a crash,
# it can leave the system in an unbootable state, when a crash/outage
# happens shortly after an update. To decrease the likelihood of this
# event sync the efi filesystem after each update.
2024-01-31 21:51:12 -05:00
rc = libc . syncfs ( os . open ( f " { BOOT_MOUNT_POINT } " , os . O_RDONLY ) )
2023-08-26 18:31:52 +02:00
if rc != 0 :
2024-01-31 21:51:12 -05:00
print ( f " could not sync { BOOT_MOUNT_POINT } : { os . strerror ( rc ) } " , file = sys . stderr )
if BOOT_MOUNT_POINT != EFI_SYS_MOUNT_POINT :
rc = libc . syncfs ( os . open ( EFI_SYS_MOUNT_POINT , os . O_RDONLY ) )
if rc != 0 :
print ( f " could not sync { EFI_SYS_MOUNT_POINT } : { os . strerror ( rc ) } " , file = sys . stderr )
2017-05-09 18:56:26 +01:00
2021-01-10 14:09:07 +01:00
2016-09-30 13:28:42 +02:00
if __name__ == ' __main__ ' :
main ( )