at 24.11-pre 43 kB view raw
1#! @perl@/bin/perl 2 3# Issue #166838 uncovered a situation in which a configuration not suitable 4# for the target architecture caused a cryptic error message instead of 5# a clean failure. Due to this mismatch, the perl interpreter in the shebang 6# line wasn't able to be executed, causing this script to be misinterpreted 7# as a shell script. 8# 9# Let's detect this situation to give a more meaningful error 10# message. The following two lines are carefully written to be both valid Perl 11# and Bash. 12printf "Perl script erroneously interpreted as shell script,\ndoes target platform match nixpkgs.crossSystem platform?\n" && exit 1 13 if 0; 14 15use strict; 16use warnings; 17use Config::IniFiles; 18use File::Path qw(make_path); 19use File::Basename; 20use File::Slurp qw(read_file write_file edit_file); 21use JSON::PP; 22use IPC::Cmd; 23use Sys::Syslog qw(:standard :macros); 24use Cwd qw(abs_path); 25use Fcntl ':flock'; 26 27## no critic(ControlStructures::ProhibitDeepNests) 28## no critic(ErrorHandling::RequireCarping) 29## no critic(CodeLayout::ProhibitParensWithBuiltins) 30## no critic(Variables::ProhibitPunctuationVars, Variables::RequireLocalizedPunctuationVars) 31## no critic(InputOutput::RequireCheckedSyscalls, InputOutput::RequireBracedFileHandleWithPrint, InputOutput::RequireBriefOpen) 32## no critic(ValuesAndExpressions::ProhibitNoisyQuotes, ValuesAndExpressions::ProhibitMagicNumbers, ValuesAndExpressions::ProhibitEmptyQuotes, ValuesAndExpressions::ProhibitInterpolationOfLiterals) 33## no critic(RegularExpressions::ProhibitEscapedMetacharacters) 34 35# Location of activation scripts 36my $out = "@out@"; 37# System closure path to switch to 38my $toplevel = "@toplevel@"; 39# Path to the directory containing systemd tools of the old system 40my $cur_systemd = abs_path("/run/current-system/sw/bin"); 41# Path to the systemd store path of the new system 42my $new_systemd = "@systemd@"; 43 44# To be robust against interruption, record what units need to be started etc. 45# We read these files again every time this script starts to make sure we continue 46# where the old (interrupted) script left off. 47my $start_list_file = "/run/nixos/start-list"; 48my $restart_list_file = "/run/nixos/restart-list"; 49my $reload_list_file = "/run/nixos/reload-list"; 50 51# Parse restart/reload requests by the activation script. 52# Activation scripts may write newline-separated units to the restart 53# file and switch-to-configuration will handle them. While 54# `stopIfChanged = true` is ignored, switch-to-configuration will 55# handle `restartIfChanged = false` and `reloadIfChanged = true`. 56# This is the same as specifying a restart trigger in the NixOS module. 57# 58# The reload file asks the script to reload a unit. This is the same as 59# specifying a reload trigger in the NixOS module and can be ignored if 60# the unit is restarted in this activation. 61my $restart_by_activation_file = "/run/nixos/activation-restart-list"; 62my $reload_by_activation_file = "/run/nixos/activation-reload-list"; 63my $dry_restart_by_activation_file = "/run/nixos/dry-activation-restart-list"; 64my $dry_reload_by_activation_file = "/run/nixos/dry-activation-reload-list"; 65 66# The action that is to be performed (like switch, boot, test, dry-activate) 67# Also exposed via environment variable from now on 68my $action = shift(@ARGV); 69$ENV{NIXOS_ACTION} = $action; 70 71# Expose the locale archive as an environment variable for systemctl and the activation script 72if ("@localeArchive@" ne "") { 73 $ENV{LOCALE_ARCHIVE} = "@localeArchive@"; 74} 75 76if (!defined($action) || ($action ne "switch" && $action ne "boot" && $action ne "test" && $action ne "dry-activate")) { 77 print STDERR <<"EOF"; 78Usage: $0 [switch|boot|test|dry-activate] 79 80switch: make the configuration the boot default and activate now 81boot: make the configuration the boot default 82test: activate the configuration, but don\'t make it the boot default 83dry-activate: show what would be done if this configuration were activated 84EOF 85 exit(1); 86} 87 88# This is a NixOS installation if it has /etc/NIXOS or a proper 89# /etc/os-release. 90if (!-f "/etc/NIXOS" && (read_file("/etc/os-release", err_mode => "quiet") // "") !~ /^ID="?@distroId@"?/msx) { 91 die("This is not a NixOS installation!\n"); 92} 93 94make_path("/run/nixos", { mode => oct(755) }); 95open(my $stc_lock, '>>', '/run/nixos/switch-to-configuration.lock') or die "Could not open lock - $!"; 96flock($stc_lock, LOCK_EX) or die "Could not acquire lock - $!"; 97openlog("nixos", "", LOG_USER); 98 99# Install or update the bootloader. 100if ($action eq "switch" || $action eq "boot") { 101 chomp(my $install_boot_loader = <<'EOFBOOTLOADER'); 102@installBootLoader@ 103EOFBOOTLOADER 104 system("$install_boot_loader $toplevel") == 0 or exit 1; 105} 106 107# Just in case the new configuration hangs the system, do a sync now. 108if (($ENV{"NIXOS_NO_SYNC"} // "") ne "1") { 109 system("@coreutils@/bin/sync", "-f", "/nix/store"); 110} 111 112if ($action eq "boot") { 113 exit(0); 114} 115 116# Check if we can activate the new configuration. 117my $cur_init_interface_version = read_file("/run/current-system/init-interface-version", err_mode => "quiet") // ""; 118my $new_init_interface_version = read_file("$toplevel/init-interface-version"); 119 120if ($new_init_interface_version ne $cur_init_interface_version) { 121 print STDERR <<'EOF'; 122Warning: the new NixOS configuration has an ‘init’ that is 123incompatible with the current configuration. The new configuration 124won't take effect until you reboot the system. 125EOF 126 exit(100); 127} 128 129# Ignore SIGHUP so that we're not killed if we're running on (say) 130# virtual console 1 and we restart the "tty1" unit. 131$SIG{PIPE} = "IGNORE"; 132 133# Replacement for Net::DBus that calls busctl of the current systemd, parses 134# it's json output and returns the response using only core modules to reduce 135# dependencies on perlPackages in baseSystem 136sub busctl_call_systemd1_mgr { 137 my (@args) = @_; 138 my $cmd = [ 139 "$cur_systemd/busctl", "--json=short", "call", "org.freedesktop.systemd1", 140 "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", 141 @args 142 ]; 143 144 my ($ok, $err, undef, $stdout) = IPC::Cmd::run(command => $cmd); 145 die $err unless $ok; 146 147 my $res = decode_json(join "", @$stdout); 148 return $res; 149} 150 151# Asks the currently running systemd instance via dbus which units are active. 152# Returns a hash where the key is the name of each unit and the value a hash 153# of load, state, substate. 154sub get_active_units { 155 my $units = busctl_call_systemd1_mgr("ListUnitsByPatterns", "asas", 0, 0)->{data}->[0]; 156 my $res = {}; 157 for my $item (@{$units}) { 158 my ($id, $description, $load_state, $active_state, $sub_state, 159 $following, $unit_path, $job_id, $job_type, $job_path) = @{$item}; 160 if ($following ne "") { 161 next; 162 } 163 if ($job_id == 0 and $active_state eq "inactive") { 164 next; 165 } 166 $res->{$id} = { load => $load_state, state => $active_state, substate => $sub_state }; 167 } 168 return $res; 169} 170 171# Asks the currently running systemd instance whether a unit is currently active. 172# Takes the name of the unit as an argument and returns a bool whether the unit is active or not. 173sub unit_is_active { 174 my ($unit_name) = @_; 175 my $units = busctl_call_systemd1_mgr("ListUnitsByNames", "as", 1, , "--", $unit_name)->{data}->[0]; 176 if (scalar(@{$units}) == 0) { 177 return 0; 178 } 179 my $active_state = $units->[0]->[3]; 180 return $active_state eq "active" || $active_state eq "activating"; 181} 182 183# Parse a fstab file, given its path. 184# Returns a tuple of filesystems and swaps. 185# 186# Filesystems is a hash of mountpoint and { device, fsType, options } 187# Swaps is a hash of device and { options } 188sub parse_fstab { 189 my ($filename) = @_; 190 my ($fss, $swaps); 191 foreach my $line (read_file($filename, err_mode => "quiet")) { 192 chomp($line); 193 $line =~ s/^\s*\#.*//msx; 194 if ($line =~ /^\s*$/msx) { 195 next; 196 } 197 my @xs = split(/\s+/msx, $line); 198 if ($xs[2] eq "swap") { 199 $swaps->{$xs[0]} = { options => $xs[3] // "" }; 200 } else { 201 $fss->{$xs[1]} = { device => $xs[0], fsType => $xs[2], options => $xs[3] // "" }; 202 } 203 } 204 return ($fss, $swaps); 205} 206 207# This subroutine takes a single ini file that specified systemd configuration 208# like unit configuration and parses it into a hash where the keys are the sections 209# of the unit file and the values are hashes themselves. These hashes have the unit file 210# keys as their keys (left side of =) and an array of all values that were set as their 211# values. If a value is empty (for example `ExecStart=`), then all current definitions are 212# removed. 213# 214# Instead of returning the hash, this subroutine takes a hashref to return the data in. This 215# allows calling the subroutine multiple times with the same hash to parse override files. 216sub parse_systemd_ini { 217 my ($unit_contents, $path) = @_; 218 # Tie the ini file to a hash for easier access 219 tie(my %file_contents, "Config::IniFiles", (-file => $path, -allowempty => 1, -allowcontinue => 1)); ## no critic(Miscellanea::ProhibitTies) 220 221 # Copy over all sections 222 foreach my $section_name (keys(%file_contents)) { 223 if ($section_name eq "Install") { 224 # Skip the [Install] section because it has no relevant keys for us 225 next; 226 } 227 # Copy over all keys 228 foreach my $ini_key (keys(%{$file_contents{$section_name}})) { 229 # Ensure the value is an array so it's easier to work with 230 my $ini_value = $file_contents{$section_name}{$ini_key}; 231 my @ini_values; 232 if (ref($ini_value) eq "ARRAY") { 233 @ini_values = @{$ini_value}; 234 } else { 235 @ini_values = $ini_value; 236 } 237 # Go over all values 238 for my $ini_value (@ini_values) { 239 # If a value is empty, it's an override that tells us to clean the value 240 if ($ini_value eq "") { 241 delete $unit_contents->{$section_name}->{$ini_key}; 242 next; 243 } 244 push(@{$unit_contents->{$section_name}->{$ini_key}}, $ini_value); 245 } 246 } 247 } 248 return; 249} 250 251# This subroutine takes the path to a systemd configuration file (like a unit configuration), 252# parses it, and returns a hash that contains the contents. The contents of this hash are 253# explained in the `parse_systemd_ini` subroutine. Neither the sections nor the keys inside 254# the sections are consistently sorted. 255# 256# If a directory with the same basename ending in .d exists next to the unit file, it will be 257# assumed to contain override files which will be parsed as well and handled properly. 258sub parse_unit { 259 my ($unit_path, $base_unit_path) = @_; 260 261 # Parse the main unit and all overrides 262 my %unit_data; 263 # Replace \ with \\ so glob() still works with units that have a \ in them 264 # Valid characters in unit names are ASCII letters, digits, ":", "-", "_", ".", and "\" 265 $base_unit_path =~ s/\\/\\\\/gmsx; 266 $unit_path =~ s/\\/\\\\/gmsx; 267 268 foreach (glob("${base_unit_path}{,.d/*.conf}")) { 269 parse_systemd_ini(\%unit_data, "$_") 270 } 271 # Handle drop-in template-unit instance overrides 272 if ($unit_path ne $base_unit_path) { 273 foreach (glob("${unit_path}.d/*.conf")) { 274 parse_systemd_ini(\%unit_data, "$_") 275 } 276 } 277 return %unit_data; 278} 279 280# Checks whether a specified boolean in a systemd unit is true 281# or false, with a default that is applied when the value is not set. 282sub parse_systemd_bool { 283 my ($unit_config, $section_name, $bool_name, $default) = @_; 284 285 my @values = @{$unit_config->{$section_name}{$bool_name} // []}; 286 # Return default if value is not set 287 if ((scalar(@values) < 1) || (not defined($values[-1]))) { 288 return $default; 289 } 290 # If value is defined multiple times, use the last definition 291 my $last_value = $values[-1]; 292 # These are valid values as of systemd.syntax(7) 293 return $last_value eq "1" || $last_value eq "yes" || $last_value eq "true" || $last_value eq "on"; 294} 295 296# Writes a unit name into a given file to be more resilient against 297# crashes of the script. Does nothing when the action is dry-activate. 298sub record_unit { 299 my ($fn, $unit) = @_; 300 if ($action ne "dry-activate") { 301 write_file($fn, { append => 1 }, "$unit\n"); 302 } 303 return; 304} 305 306# The opposite of record_unit, removes a unit name from a file 307sub unrecord_unit { 308 my ($fn, $unit) = @_; 309 if ($action ne "dry-activate") { 310 edit_file(sub { s/^$unit\n//msx }, $fn); 311 } 312 return; 313} 314 315# Compare the contents of two unit files and return whether the unit 316# needs to be restarted or reloaded. If the units differ, the service 317# is restarted unless the only difference is `X-Reload-Triggers` in the 318# `Unit` section. If this is the only modification, the unit is reloaded 319# instead of restarted. If the only difference is `Options` in the 320# `[Mount]` section, the unit is reloaded rather than restarted. 321# Returns: 322# - 0 if the units are equal 323# - 1 if the units are different and a restart action is required 324# - 2 if the units are different and a reload action is required 325sub compare_units { ## no critic(Subroutines::ProhibitExcessComplexity) 326 my ($cur_unit, $new_unit) = @_; 327 my $ret = 0; 328 # Keys to ignore in the [Unit] section 329 my %unit_section_ignores = map { $_ => 1 } qw( 330 X-Reload-Triggers 331 Description Documentation 332 OnFailure OnSuccess OnFailureJobMode 333 IgnoreOnIsolate StopWhenUnneeded 334 RefuseManualStart RefuseManualStop 335 AllowIsolate CollectMode 336 SourcePath 337 ); 338 339 my $comp_array = sub { 340 my ($a, $b) = @_; 341 return join("\0", @{$a}) eq join("\0", @{$b}); 342 }; 343 344 # Comparison hash for the sections 345 my %section_cmp = map { $_ => 1 } keys(%{$new_unit}); 346 # Iterate over the sections 347 foreach my $section_name (keys(%{$cur_unit})) { 348 # Missing section in the new unit? 349 if (not exists($section_cmp{$section_name})) { 350 # If the [Unit] section was removed, make sure that only keys 351 # were in it that are ignored 352 if ($section_name eq "Unit") { 353 foreach my $ini_key (keys(%{$cur_unit->{"Unit"}})) { 354 if (not defined($unit_section_ignores{$ini_key})) { 355 return 1; 356 } 357 } 358 next; # check the next section 359 } else { 360 return 1; 361 } 362 if ($section_name eq "Unit" and %{$cur_unit->{"Unit"}} == 1 and defined(%{$cur_unit->{"Unit"}}{"X-Reload-Triggers"})) { 363 # If a new [Unit] section was removed that only contained X-Reload-Triggers, 364 # do nothing. 365 next; 366 } else { 367 return 1; 368 } 369 } 370 delete $section_cmp{$section_name}; 371 # Comparison hash for the section contents 372 my %ini_cmp = map { $_ => 1 } keys(%{$new_unit->{$section_name}}); 373 # Iterate over the keys of the section 374 foreach my $ini_key (keys(%{$cur_unit->{$section_name}})) { 375 delete $ini_cmp{$ini_key}; 376 my @cur_value = @{$cur_unit->{$section_name}{$ini_key}}; 377 # If the key is missing in the new unit, they are different... 378 if (not $new_unit->{$section_name}{$ini_key}) { 379 # ... unless the key that is now missing is one of the ignored keys 380 if ($section_name eq "Unit" and defined($unit_section_ignores{$ini_key})) { 381 next; 382 } 383 return 1; 384 } 385 my @new_value = @{$new_unit->{$section_name}{$ini_key}}; 386 # If the contents are different, the units are different 387 if (not $comp_array->(\@cur_value, \@new_value)) { 388 # Check if only the reload triggers changed or one of the ignored keys 389 if ($section_name eq "Unit") { 390 if ($ini_key eq "X-Reload-Triggers") { 391 $ret = 2; 392 next; 393 } elsif (defined($unit_section_ignores{$ini_key})) { 394 next; 395 } 396 } 397 # If this is a mount unit, check if it was only `Options` 398 if ($section_name eq "Mount" and $ini_key eq "Options") { 399 $ret = 2; 400 next; 401 } 402 return 1; 403 } 404 } 405 # A key was introduced that was missing in the previous unit 406 if (%ini_cmp) { 407 if ($section_name eq "Unit") { 408 foreach my $ini_key (keys(%ini_cmp)) { 409 if ($ini_key eq "X-Reload-Triggers") { 410 $ret = 2; 411 } elsif (defined($unit_section_ignores{$ini_key})) { 412 next; 413 } else { 414 return 1; 415 } 416 } 417 } else { 418 return 1; 419 } 420 }; 421 } 422 # A section was introduced that was missing in the previous unit 423 if (%section_cmp) { 424 if (%section_cmp == 1 and defined($section_cmp{"Unit"})) { 425 foreach my $ini_key (keys(%{$new_unit->{"Unit"}})) { 426 if (not defined($unit_section_ignores{$ini_key})) { 427 return 1; 428 } elsif ($ini_key eq "X-Reload-Triggers") { 429 $ret = 2; 430 } 431 } 432 } else { 433 return 1; 434 } 435 } 436 437 return $ret; 438} 439 440# Called when a unit exists in both the old systemd and the new system and the units 441# differ. This figures out of what units are to be stopped, restarted, reloaded, started, and skipped. 442sub handle_modified_unit { ## no critic(Subroutines::ProhibitManyArgs, Subroutines::ProhibitExcessComplexity) 443 my ($unit, $base_name, $new_unit_file, $new_base_unit_file, $new_unit_info, $active_cur, $units_to_stop, $units_to_start, $units_to_reload, $units_to_restart, $units_to_skip) = @_; 444 445 if ($unit eq "sysinit.target" || $unit eq "basic.target" || $unit eq "multi-user.target" || $unit eq "graphical.target" || $unit =~ /\.path$/msx || $unit =~ /\.slice$/msx) { 446 # Do nothing. These cannot be restarted directly. 447 448 # Slices and Paths don't have to be restarted since 449 # properties (resource limits and inotify watches) 450 # seem to get applied on daemon-reload. 451 } elsif ($unit =~ /\.mount$/msx) { 452 # Just restart the unit. We wouldn't have gotten into this subroutine 453 # if only `Options` was changed, in which case the unit would be reloaded. 454 # The only exception is / and /nix because it's very unlikely we can safely 455 # unmount them so we reload them instead. This means that we may not get 456 # all changes into the running system but it's better than crashing it. 457 if ($unit eq "-.mount" or $unit eq "nix.mount") { 458 $units_to_reload->{$unit} = 1; 459 record_unit($reload_list_file, $unit); 460 } else { 461 $units_to_restart->{$unit} = 1; 462 record_unit($restart_list_file, $unit); 463 } 464 } elsif ($unit =~ /\.socket$/msx) { 465 # FIXME: do something? 466 # Attempt to fix this: https://github.com/NixOS/nixpkgs/pull/141192 467 # Revert of the attempt: https://github.com/NixOS/nixpkgs/pull/147609 468 # More details: https://github.com/NixOS/nixpkgs/issues/74899#issuecomment-981142430 469 } else { 470 my %new_unit_info = $new_unit_info ? %{$new_unit_info} : parse_unit($new_unit_file, $new_base_unit_file); 471 if (parse_systemd_bool(\%new_unit_info, "Service", "X-ReloadIfChanged", 0) and not $units_to_restart->{$unit} and not $units_to_stop->{$unit}) { 472 $units_to_reload->{$unit} = 1; 473 record_unit($reload_list_file, $unit); 474 } 475 elsif ($unit eq "dbus.service" || $unit eq "dbus-broker.service") { 476 # dbus service should only ever be reloaded, not started/stoped/restarted as that would break the system. 477 } 478 elsif (!parse_systemd_bool(\%new_unit_info, "Service", "X-RestartIfChanged", 1) || parse_systemd_bool(\%new_unit_info, "Unit", "RefuseManualStop", 0) || parse_systemd_bool(\%new_unit_info, "Unit", "X-OnlyManualStart", 0)) { 479 $units_to_skip->{$unit} = 1; 480 } else { 481 # It doesn't make sense to stop and start non-services because 482 # they can't have ExecStop= 483 if (!parse_systemd_bool(\%new_unit_info, "Service", "X-StopIfChanged", 1) || $unit !~ /\.service$/msx) { 484 # This unit should be restarted instead of 485 # stopped and started. 486 $units_to_restart->{$unit} = 1; 487 record_unit($restart_list_file, $unit); 488 # Remove from units to reload so we don't restart and reload 489 if ($units_to_reload->{$unit}) { 490 delete $units_to_reload->{$unit}; 491 unrecord_unit($reload_list_file, $unit); 492 } 493 } else { 494 # If this unit is socket-activated, then stop the 495 # socket unit(s) as well, and restart the 496 # socket(s) instead of the service. 497 my $socket_activated = 0; 498 if ($unit =~ /\.service$/msx) { 499 my @sockets = split(/\s+/msx, join(" ", @{$new_unit_info{Service}{Sockets} // []})); 500 if (scalar(@sockets) == 0) { 501 @sockets = ("$base_name.socket"); 502 } 503 foreach my $socket (@sockets) { 504 if (defined($active_cur->{$socket})) { 505 # We can now be sure this is a socket-activate unit 506 507 $units_to_stop->{$socket} = 1; 508 # Only restart sockets that actually 509 # exist in new configuration: 510 if (-e "$toplevel/etc/systemd/system/$socket") { 511 $units_to_start->{$socket} = 1; 512 if ($units_to_start eq $units_to_restart) { 513 record_unit($restart_list_file, $socket); 514 } else { 515 record_unit($start_list_file, $socket); 516 } 517 $socket_activated = 1; 518 } 519 # Remove from units to reload so we don't restart and reload 520 if ($units_to_reload->{$unit}) { 521 delete $units_to_reload->{$unit}; 522 unrecord_unit($reload_list_file, $unit); 523 } 524 } 525 } 526 } 527 528 # If the unit is not socket-activated, record 529 # that this unit needs to be started below. 530 # We write this to a file to ensure that the 531 # service gets restarted if we're interrupted. 532 if (!$socket_activated) { 533 $units_to_start->{$unit} = 1; 534 if ($units_to_start eq $units_to_restart) { 535 record_unit($restart_list_file, $unit); 536 } else { 537 record_unit($start_list_file, $unit); 538 } 539 } 540 541 $units_to_stop->{$unit} = 1; 542 # Remove from units to reload so we don't restart and reload 543 if ($units_to_reload->{$unit}) { 544 delete $units_to_reload->{$unit}; 545 unrecord_unit($reload_list_file, $unit); 546 } 547 } 548 } 549 } 550 return; 551} 552 553# Figure out what units need to be stopped, started, restarted or reloaded. 554my (%units_to_stop, %units_to_skip, %units_to_start, %units_to_restart, %units_to_reload); 555 556my %units_to_filter; # units not shown 557 558%units_to_start = map { $_ => 1 } 559 split(/\n/msx, read_file($start_list_file, err_mode => "quiet") // ""); 560 561%units_to_restart = map { $_ => 1 } 562 split(/\n/msx, read_file($restart_list_file, err_mode => "quiet") // ""); 563 564%units_to_reload = map { $_ => 1 } 565 split(/\n/msx, read_file($reload_list_file, err_mode => "quiet") // ""); 566 567my $active_cur = get_active_units(); 568while (my ($unit, $state) = each(%{$active_cur})) { 569 my $cur_unit_file = "/etc/systemd/system/$unit"; 570 my $new_unit_file = "$toplevel/etc/systemd/system/$unit"; 571 572 my $base_unit = $unit; 573 my $cur_base_unit_file = $cur_unit_file; 574 my $new_base_unit_file = $new_unit_file; 575 576 # Detect template instances. 577 if (!-e $cur_unit_file && !-e $new_unit_file && $unit =~ /^(.*)@[^\.]*\.(.*)$/msx) { 578 $base_unit = "$1\@.$2"; 579 $cur_base_unit_file = "/etc/systemd/system/$base_unit"; 580 $new_base_unit_file = "$toplevel/etc/systemd/system/$base_unit"; 581 } 582 583 my $base_name = $base_unit; 584 $base_name =~ s/\.[[:lower:]]*$//msx; 585 586 if (-e $cur_base_unit_file && ($state->{state} eq "active" || $state->{state} eq "activating")) { 587 if (! -e $new_base_unit_file || abs_path($new_base_unit_file) eq "/dev/null") { 588 my %cur_unit_info = parse_unit($cur_unit_file, $cur_base_unit_file); 589 if (parse_systemd_bool(\%cur_unit_info, "Unit", "X-StopOnRemoval", 1)) { 590 $units_to_stop{$unit} = 1; 591 } 592 } 593 594 elsif ($unit =~ /\.target$/msx) { 595 my %new_unit_info = parse_unit($new_unit_file, $new_base_unit_file); 596 597 # Cause all active target units to be restarted below. 598 # This should start most changed units we stop here as 599 # well as any new dependencies (including new mounts and 600 # swap devices). FIXME: the suspend target is sometimes 601 # active after the system has resumed, which probably 602 # should not be the case. Just ignore it. 603 if ($unit ne "suspend.target" && $unit ne "hibernate.target" && $unit ne "hybrid-sleep.target") { 604 if (!(parse_systemd_bool(\%new_unit_info, "Unit", "RefuseManualStart", 0) || parse_systemd_bool(\%new_unit_info, "Unit", "X-OnlyManualStart", 0))) { 605 $units_to_start{$unit} = 1; 606 record_unit($start_list_file, $unit); 607 # Don't spam the user with target units that always get started. 608 if (($ENV{"STC_DISPLAY_ALL_UNITS"} // "") ne "1") { 609 $units_to_filter{$unit} = 1; 610 } 611 } 612 } 613 614 # Stop targets that have X-StopOnReconfiguration set. 615 # This is necessary to respect dependency orderings 616 # involving targets: if unit X starts after target Y and 617 # target Y starts after unit Z, then if X and Z have both 618 # changed, then X should be restarted after Z. However, 619 # if target Y is in the "active" state, X and Z will be 620 # restarted at the same time because X's dependency on Y 621 # is already satisfied. Thus, we need to stop Y first. 622 # Stopping a target generally has no effect on other units 623 # (unless there is a PartOf dependency), so this is just a 624 # bookkeeping thing to get systemd to do the right thing. 625 if (parse_systemd_bool(\%new_unit_info, "Unit", "X-StopOnReconfiguration", 0)) { 626 $units_to_stop{$unit} = 1; 627 } 628 } 629 630 else { 631 my %cur_unit_info = parse_unit($cur_unit_file, $cur_base_unit_file); 632 my %new_unit_info = parse_unit($new_unit_file, $new_base_unit_file); 633 my $diff = compare_units(\%cur_unit_info, \%new_unit_info); 634 if ($diff == 1) { 635 handle_modified_unit($unit, $base_name, $new_unit_file, $new_base_unit_file, \%new_unit_info, $active_cur, \%units_to_stop, \%units_to_start, \%units_to_reload, \%units_to_restart, \%units_to_skip); 636 } elsif ($diff == 2 and not $units_to_restart{$unit}) { 637 $units_to_reload{$unit} = 1; 638 record_unit($reload_list_file, $unit); 639 } 640 } 641 } 642} 643 644# Converts a path to the name of a systemd mount unit that would be responsible 645# for mounting this path. 646sub path_to_unit_name { 647 my ($path) = @_; 648 # Use current version of systemctl binary before daemon is reexeced. 649 open(my $cmd, "-|", "$cur_systemd/systemd-escape", "--suffix=mount", "-p", $path) 650 or die "Unable to escape $path!\n"; 651 my $escaped = do { local $/ = undef; <$cmd> }; 652 chomp($escaped); 653 close($cmd) or die("Unable to close systemd-escape pipe"); 654 return $escaped; 655} 656 657# Compare the previous and new fstab to figure out which filesystems 658# need a remount or need to be unmounted. New filesystems are mounted 659# automatically by starting local-fs.target. FIXME: might be nicer if 660# we generated units for all mounts; then we could unify this with the 661# unit checking code above. 662my ($cur_fss, $cur_swaps) = parse_fstab("/etc/fstab"); 663my ($new_fss, $new_swaps) = parse_fstab("$toplevel/etc/fstab"); 664foreach my $mount_point (keys(%{$cur_fss})) { 665 my $cur = $cur_fss->{$mount_point}; 666 my $new = $new_fss->{$mount_point}; 667 my $unit = path_to_unit_name($mount_point); 668 if (!defined($new)) { 669 # Filesystem entry disappeared, so unmount it. 670 $units_to_stop{$unit} = 1; 671 } elsif ($cur->{fsType} ne $new->{fsType} || $cur->{device} ne $new->{device}) { 672 if ($mount_point eq '/' or $mount_point eq '/nix') { 673 if ($cur->{options} ne $new->{options}) { 674 # Mount options changed, so remount it. 675 $units_to_reload{$unit} = 1; 676 record_unit($reload_list_file, $unit); 677 } else { 678 # Don't unmount / or /nix if the device changed 679 $units_to_skip{$unit} = 1; 680 } 681 } else { 682 # Filesystem type or device changed, so unmount and mount it. 683 $units_to_restart{$unit} = 1; 684 record_unit($restart_list_file, $unit); 685 } 686 } elsif ($cur->{options} ne $new->{options}) { 687 # Mount options changes, so remount it. 688 $units_to_reload{$unit} = 1; 689 record_unit($reload_list_file, $unit); 690 } 691} 692 693# Also handles swap devices. 694foreach my $device (keys(%{$cur_swaps})) { 695 my $cur = $cur_swaps->{$device}; 696 my $new = $new_swaps->{$device}; 697 if (!defined($new)) { 698 # Swap entry disappeared, so turn it off. Can't use 699 # "systemctl stop" here because systemd has lots of alias 700 # units that prevent a stop from actually calling 701 # "swapoff". 702 if ($action eq "dry-activate") { 703 print STDERR "would stop swap device: $device\n"; 704 } else { 705 print STDERR "stopping swap device: $device\n"; 706 system("@utillinux@/sbin/swapoff", $device); 707 } 708 } 709 # FIXME: update swap options (i.e. its priority). 710} 711 712 713# Should we have systemd re-exec itself? 714my $cur_pid1_path = abs_path("/proc/1/exe") // "/unknown"; 715my $cur_systemd_system_config = abs_path("/etc/systemd/system.conf") // "/unknown"; 716my $new_pid1_path = abs_path("$new_systemd/lib/systemd/systemd") or die; 717my $new_systemd_system_config = abs_path("$toplevel/etc/systemd/system.conf") // "/unknown"; 718 719my $restart_systemd = $cur_pid1_path ne $new_pid1_path; 720if ($cur_systemd_system_config ne $new_systemd_system_config) { 721 $restart_systemd = 1; 722} 723 724# Takes an array of unit names and returns an array with the same elements, 725# except all units that are also in the global variable `unitsToFilter`. 726sub filter_units { 727 my ($units) = @_; 728 my @res; 729 foreach my $unit (sort(keys(%{$units}))) { 730 if (!defined($units_to_filter{$unit})) { 731 push(@res, $unit); 732 } 733 } 734 return @res; 735} 736 737my @units_to_stop_filtered = filter_units(\%units_to_stop); 738 739 740# Show dry-run actions. 741if ($action eq "dry-activate") { 742 if (scalar(@units_to_stop_filtered) > 0) { 743 print STDERR "would stop the following units: ", join(", ", @units_to_stop_filtered), "\n"; 744 } 745 if (scalar(keys(%units_to_skip)) > 0) { 746 print STDERR "would NOT stop the following changed units: ", join(", ", sort(keys(%units_to_skip))), "\n"; 747 } 748 749 print STDERR "would activate the configuration...\n"; 750 system("$out/dry-activate", "$out"); 751 752 # Handle the activation script requesting the restart or reload of a unit. 753 foreach (split(/\n/msx, read_file($dry_restart_by_activation_file, err_mode => "quiet") // "")) { 754 my $unit = $_; 755 my $new_unit_file = "$toplevel/etc/systemd/system/$unit"; 756 my $base_unit = $unit; 757 my $new_base_unit_file = $new_unit_file; 758 759 # Detect template instances. 760 if (!-e $new_unit_file && $unit =~ /^(.*)@[^\.]*\.(.*)$/msx) { 761 $base_unit = "$1\@.$2"; 762 $new_base_unit_file = "$toplevel/etc/systemd/system/$base_unit"; 763 } 764 765 my $base_name = $base_unit; 766 $base_name =~ s/\.[[:lower:]]*$//msx; 767 768 # Start units if they were not active previously 769 if (not defined($active_cur->{$unit})) { 770 $units_to_start{$unit} = 1; 771 next; 772 } 773 774 handle_modified_unit($unit, $base_name, $new_unit_file, $new_base_unit_file, undef, $active_cur, \%units_to_restart, \%units_to_restart, \%units_to_reload, \%units_to_restart, \%units_to_skip); 775 } 776 unlink($dry_restart_by_activation_file); 777 778 foreach (split(/\n/msx, read_file($dry_reload_by_activation_file, err_mode => "quiet") // "")) { 779 my $unit = $_; 780 781 if (defined($active_cur->{$unit}) and not $units_to_restart{$unit} and not $units_to_stop{$unit}) { 782 $units_to_reload{$unit} = 1; 783 record_unit($reload_list_file, $unit); 784 } 785 } 786 unlink($dry_reload_by_activation_file); 787 788 if ($restart_systemd) { 789 print STDERR "would restart systemd\n"; 790 } 791 if (scalar(keys(%units_to_reload)) > 0) { 792 print STDERR "would reload the following units: ", join(", ", sort(keys(%units_to_reload))), "\n"; 793 } 794 if (scalar(keys(%units_to_restart)) > 0) { 795 print STDERR "would restart the following units: ", join(", ", sort(keys(%units_to_restart))), "\n"; 796 } 797 my @units_to_start_filtered = filter_units(\%units_to_start); 798 if (scalar(@units_to_start_filtered)) { 799 print STDERR "would start the following units: ", join(", ", @units_to_start_filtered), "\n"; 800 } 801 exit 0; 802} 803 804 805syslog(LOG_NOTICE, "switching to system configuration $toplevel"); 806 807if (scalar(keys(%units_to_stop)) > 0) { 808 if (scalar(@units_to_stop_filtered)) { 809 print STDERR "stopping the following units: ", join(", ", @units_to_stop_filtered), "\n"; 810 } 811 # Use current version of systemctl binary before daemon is reexeced. 812 system("$cur_systemd/systemctl", "stop", "--", sort(keys(%units_to_stop))); 813} 814 815if (scalar(keys(%units_to_skip)) > 0) { 816 print STDERR "NOT restarting the following changed units: ", join(", ", sort(keys(%units_to_skip))), "\n"; 817} 818 819# Activate the new configuration (i.e., update /etc, make accounts, 820# and so on). 821my $res = 0; 822print STDERR "activating the configuration...\n"; 823system("$out/activate", "$out") == 0 or $res = 2; 824 825# Handle the activation script requesting the restart or reload of a unit. 826foreach (split(/\n/msx, read_file($restart_by_activation_file, err_mode => "quiet") // "")) { 827 my $unit = $_; 828 my $new_unit_file = "$toplevel/etc/systemd/system/$unit"; 829 my $base_unit = $unit; 830 my $new_base_unit_file = $new_unit_file; 831 832 # Detect template instances. 833 if (!-e $new_unit_file && $unit =~ /^(.*)@[^\.]*\.(.*)$/msx) { 834 $base_unit = "$1\@.$2"; 835 $new_base_unit_file = "$toplevel/etc/systemd/system/$base_unit"; 836 } 837 838 my $base_name = $base_unit; 839 $base_name =~ s/\.[[:lower:]]*$//msx; 840 841 # Start units if they were not active previously 842 if (not defined($active_cur->{$unit})) { 843 $units_to_start{$unit} = 1; 844 record_unit($start_list_file, $unit); 845 next; 846 } 847 848 handle_modified_unit($unit, $base_name, $new_unit_file, $new_base_unit_file, undef, $active_cur, \%units_to_restart, \%units_to_restart, \%units_to_reload, \%units_to_restart, \%units_to_skip); 849} 850# We can remove the file now because it has been propagated to the other restart/reload files 851unlink($restart_by_activation_file); 852 853foreach (split(/\n/msx, read_file($reload_by_activation_file, err_mode => "quiet") // "")) { 854 my $unit = $_; 855 856 if (defined($active_cur->{$unit}) and not $units_to_restart{$unit} and not $units_to_stop{$unit}) { 857 $units_to_reload{$unit} = 1; 858 record_unit($reload_list_file, $unit); 859 } 860} 861# We can remove the file now because it has been propagated to the other reload file 862unlink($reload_by_activation_file); 863 864# Restart systemd if necessary. Note that this is done using the 865# current version of systemd, just in case the new one has trouble 866# communicating with the running pid 1. 867if ($restart_systemd) { 868 print STDERR "restarting systemd...\n"; 869 system("$cur_systemd/systemctl", "daemon-reexec") == 0 or $res = 2; 870} 871 872# Forget about previously failed services. 873system("$new_systemd/bin/systemctl", "reset-failed"); 874 875# Make systemd reload its units. 876system("$new_systemd/bin/systemctl", "daemon-reload") == 0 or $res = 3; 877 878# Reload user units 879open(my $list_active_users, "-|", "$new_systemd/bin/loginctl", "list-users", "--no-legend") || die("Unable to call loginctl"); 880while (my $f = <$list_active_users>) { 881 if ($f !~ /^\s*(?<uid>\d+)\s+(?<user>\S+)/msx) { 882 next; 883 } 884 my ($uid, $name) = ($+{uid}, $+{user}); 885 print STDERR "reloading user units for $name...\n"; 886 887 system("@su@", "-s", "@shell@", "-l", $name, "-c", 888 "export XDG_RUNTIME_DIR=/run/user/$uid; " . 889 "$cur_systemd/systemctl --user daemon-reexec; " . 890 "$new_systemd/bin/systemctl --user start nixos-activation.service"); 891} 892 893close($list_active_users) || die("Unable to close the file handle to loginctl"); 894 895# Restart sysinit-reactivation.target. 896# This target only exists to restart services ordered before sysinit.target. We 897# cannot use X-StopOnReconfiguration to restart sysinit.target because then ALL 898# services of the system would be restarted since all normal services have a 899# default dependency on sysinit.target. sysinit-reactivation.target ensures 900# that services ordered BEFORE sysinit.target get re-started in the correct 901# order. Ordering between these services is respected. 902print STDERR "restarting sysinit-reactivation.target\n"; 903system("$new_systemd/bin/systemctl", "restart", "sysinit-reactivation.target") == 0 or $res = 4; 904 905# Before reloading we need to ensure that the units are still active. They may have been 906# deactivated because one of their requirements got stopped. If they are inactive 907# but should have been reloaded, the user probably expects them to be started. 908if (scalar(keys(%units_to_reload)) > 0) { 909 for my $unit (keys(%units_to_reload)) { 910 if (!unit_is_active($unit)) { 911 # Figure out if we need to start the unit 912 my %unit_info = parse_unit("$toplevel/etc/systemd/system/$unit", "$toplevel/etc/systemd/system/$unit"); 913 if (!(parse_systemd_bool(\%unit_info, "Unit", "RefuseManualStart", 0) || parse_systemd_bool(\%unit_info, "Unit", "X-OnlyManualStart", 0))) { 914 $units_to_start{$unit} = 1; 915 record_unit($start_list_file, $unit); 916 } 917 # Don't reload the unit, reloading would fail 918 delete %units_to_reload{$unit}; 919 unrecord_unit($reload_list_file, $unit); 920 } 921 } 922} 923# Reload units that need it. This includes remounting changed mount 924# units. 925if (scalar(keys(%units_to_reload)) > 0) { 926 print STDERR "reloading the following units: ", join(", ", sort(keys(%units_to_reload))), "\n"; 927 system("$new_systemd/bin/systemctl", "reload", "--", sort(keys(%units_to_reload))) == 0 or $res = 4; 928 unlink($reload_list_file); 929} 930 931# Restart changed services (those that have to be restarted rather 932# than stopped and started). 933if (scalar(keys(%units_to_restart)) > 0) { 934 print STDERR "restarting the following units: ", join(", ", sort(keys(%units_to_restart))), "\n"; 935 system("$new_systemd/bin/systemctl", "restart", "--", sort(keys(%units_to_restart))) == 0 or $res = 4; 936 unlink($restart_list_file); 937} 938 939# Start all active targets, as well as changed units we stopped above. 940# The latter is necessary because some may not be dependencies of the 941# targets (i.e., they were manually started). FIXME: detect units 942# that are symlinks to other units. We shouldn't start both at the 943# same time because we'll get a "Failed to add path to set" error from 944# systemd. 945my @units_to_start_filtered = filter_units(\%units_to_start); 946if (scalar(@units_to_start_filtered)) { 947 print STDERR "starting the following units: ", join(", ", @units_to_start_filtered), "\n" 948} 949system("$new_systemd/bin/systemctl", "start", "--", sort(keys(%units_to_start))) == 0 or $res = 4; 950unlink($start_list_file); 951 952 953# Print failed and new units. 954my (@failed, @new); 955my $active_new = get_active_units(); 956while (my ($unit, $state) = each(%{$active_new})) { 957 if ($state->{state} eq "failed") { 958 push(@failed, $unit); 959 next; 960 } 961 962 if ($state->{substate} eq "auto-restart") { 963 # A unit in auto-restart substate is a failure *if* it previously failed to start 964 open(my $main_status_fd, "-|", "$new_systemd/bin/systemctl", "show", "--value", "--property=ExecMainStatus", $unit) || die("Unable to call 'systemctl show'"); 965 my $main_status = do { local $/ = undef; <$main_status_fd> }; 966 close($main_status_fd) || die("Unable to close 'systemctl show' fd"); 967 chomp($main_status); 968 969 if ($main_status ne "0") { 970 push(@failed, $unit); 971 next; 972 } 973 } 974 975 # Ignore scopes since they are not managed by this script but rather 976 # created and managed by third-party services via the systemd dbus API. 977 # This only lists units that are not failed (including ones that are in auto-restart but have not failed previously) 978 if ($state->{state} ne "failed" && !defined($active_cur->{$unit}) && $unit !~ /\.scope$/msx) { 979 push(@new, $unit); 980 } 981} 982 983if (scalar(@new) > 0) { 984 print STDERR "the following new units were started: ", join(", ", sort(@new)), "\n" 985} 986 987if (scalar(@failed) > 0) { 988 my @failed_sorted = sort(@failed); 989 print STDERR "warning: the following units failed: ", join(", ", @failed_sorted), "\n\n"; 990 system("$new_systemd/bin/systemctl status --no-pager --full '" . join("' '", @failed_sorted) . "' >&2"); 991 $res = 4; 992} 993 994if ($res == 0) { 995 syslog(LOG_NOTICE, "finished switching to system configuration $toplevel"); 996} else { 997 syslog(LOG_ERR, "switching to system configuration $toplevel failed (status $res)"); 998} 999 1000close($stc_lock) or die "Could not close lock - $!"; 1001exit($res);