1# What happens during a system switch? {#sec-switching-systems} 2 3Running `nixos-rebuild switch` is one of the more common tasks under NixOS. 4This chapter explains some of the internals of this command to make it simpler 5for new module developers to configure their units correctly and to make it 6easier to understand what is happening and why for curious administrators. 7 8`nixos-rebuild`, like many deployment solutions, calls `switch-to-configuration` 9which resides in a NixOS system at `$out/bin/switch-to-configuration`. The 10script is called with the action that is to be performed like `switch`, `test`, 11`boot`. There is also the `dry-activate` action which does not really perform 12the actions but rather prints what it would do if you called it with `test`. 13This feature can be used to check what service states would be changed if the 14configuration was switched to. 15 16If the action is `switch` or `boot`, the bootloader is updated first so the 17configuration will be the next one to boot. Unless `NIXOS_NO_SYNC` is set to 18`1`, `/nix/store` is synced to disk. 19 20If the action is `switch` or `test`, the currently running system is inspected 21and the actions to switch to the new system are calculated. This process takes 22two data sources into account: `/etc/fstab` and the current systemd status. 23Mounts and swaps are read from `/etc/fstab` and the corresponding actions are 24generated. If a new mount is added, for example, the proper `.mount` unit is 25marked to be started. The current systemd state is inspected, the difference 26between the current system and the desired configuration is calculated and 27actions are generated to get to this state. There are a lot of nuances that can 28be controlled by the units which are explained here. 29 30After calculating what should be done, the actions are carried out. The order 31of actions is always the same: 32- Stop units (`systemctl stop`) 33- Run activation script (`$out/activate`) 34- See if the activation script requested more units to restart 35- Restart systemd if needed (`systemd daemon-reexec`) 36- Forget about the failed state of units (`systemctl reset-failed`) 37- Reload systemd (`systemctl daemon-reload`) 38- Reload systemd user instances (`systemctl --user daemon-reload`) 39- Set up tmpfiles (`systemd-tmpfiles --create`) 40- Reload units (`systemctl reload`) 41- Restart units (`systemctl restart`) 42- Start units (`systemctl start`) 43- Inspect what changed during these actions and print units that failed and 44 that were newly started 45 46Most of these actions are either self-explaining but some of them have to do 47with our units or the activation script. For this reason, these topics are 48explained in the next sections. 49 50```{=docbook} 51<xi:include href="unit-handling.section.xml" /> 52<xi:include href="activation-script.section.xml" /> 53```