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