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