linux systemd - ghdrako/doc_snipets GitHub Wiki
systemctl stop [servicename]
systemctl disable [servicename]
rm /etc/systemd/system/[servicename]
rm /etc/systemd/system/[servicename] # and symlinks that might be related
rm /usr/lib/systemd/system/[servicename]
rm /usr/lib/systemd/system/[servicename] # and symlinks that might be related
systemctl daemon-reload
systemctl reset-failed
- https://docs.fedoraproject.org/en-US/quick-docs/understanding-and-administering-systemd/
- https://www.computernetworkingnotes.com/linux-tutorials/systemd-units-explained-with-types-and-states.html
Systemd is a suite of basic building blocks for a Linux system. It provides a system and service manager that runs as PID 1 and starts the rest of the system.
The advantages of systemd:
- simplicity - simpler script, we have a much cleaner way of killing processes - all processes that are associated with that service will also get terminated.
- consistency - same commands on all Linux distros.
- performance - can start services in parallel,
- security
/etc/systemd/system.conf
- sets the configuration for the systemd init process. Information man systemd-system.conf
, apropos systemd
or man -k systemd
-find all pages that match the systemd string
Each service is stored in a .service file under the /lib/systemd/system
or /etc/systemd/system
directory. The services found in /lib
are
definitions for system startup services and those in /etc
are for the services that start during system runtime.
/etc/systemd/system/
- tu wrzucamy *.service np cloud-sql-proxy.service
stunnel.service
itd
/etc/systemd/system/
directory chock-full of symlinks to files in usr/lib/systemd/system/
. /usr/lib/systemd/system/
contains init scripts; to start a service at boot it must be linked to /etc/systemd/system/
. The systemctl command does this for you when you enable a new service
-
/usr/lib/systemd/system/
Systemd unit files distributed with installed RPM packages. -
/run/systemd/system/
Systemd unit files created at run time. This directory takes precedence over the directory with installed service unit files. -
/etc/systemd/system/
Systemd unit files created by systemctl enable as well as unit files added for extending a service. This directory takes precedence over the directory with runtime unit files.
The two tools is use to interact with systemd are:
-
systemctl
: Controls services (called ‘units’ in systemd nomenclature) -
journalctl
: Lets you work with system logs
The systemctl utility is for controlling systemd
-
systemctl start <service>
: starts a service. -
systemctl stop <service>
: stops a service. -
systemctl restart <service>
: restarts a service. -
systemctl status <service>
: displays the current status of a service. -
enable
- start automatically on boot (when the system enters multi-user mode). Creates a symbolic link from our unit file to/etc/systemd/system/multi-user.target.wants/my-daemon.service
.multi-user.target
was the target we specified in the unit file. So when the system reaches the multi-user level, systemd will start all services in that directory. Its define in configuration:
[Install]
WantedBy=multi-user.target
sudo systemctl enable my-daemon
-
start
- when the daemon start create/var/run/my-daemon.pid
file - this is how systemd keeps track of forking daemons.
sudo systemctl start my-daemon
systemctl list-units # list the active units that systemd currently has in memory
systemctl list-units --all # list all units either not active
systemctl list-units -t service # list the active units specific type
systemctl list-units -t service --state=dead # see the services that are dead
sudo systemctl --failed # List failed services on boot
systemctl --state=help # see a list of all of the different states that you can view for the different unit types
systemctl is-enabled systemd-timesyncd
systemctl is-active systemd-timesyncd
systemctl is-enabled NetworkManager
systemctl list-unit-files -t swap
systemctl show # see the actual running configuration
systemctl show --property=DefaultLimitSIGPENDING
systemctl start name.service
systemctl stop name.service
systemctl restart name.service
systemctl try-restart name.service # Restarts a service only if it is running.
systemctl reload name.service # Reloads configuration.
systemctl status name.service
systemctl is-active name.service
systemctl is-enabled name.service
systemctl list-units --type service --all # Displays the status of all services.
systemctl enable name.service
systemctl disable name.service
systemctl list-dependencies --after
systemctl list-dependencies --before
systemctl list-units --type service # list all currently loaded service units - see which services are available and their status
systemctl list-units --type service --all
systemctl mask name.service # Prevent a service from starting dynamically or even manually unless unmasked
systemctl edit httpd.service
systemctl daemon-reload # To make systemd aware of the new service, reload its service files
systemctl kill SERVICE.service # Kill SERVICE (all processes) with SIGTERM
systemctl kill -s SIGKILL SERVICE.service # Kill SERVICE (all processes) with SIGKILL
Action | Command |
---|---|
Go to single user mode | systemctl rescue |
Go to multi-user mode | systemctl isolate multi-user.target |
(= old runlevel 3) | systemctl isolate runlevel3.target |
Go to graphical level | systemctl isolate graphical.target |
Get default runlevel | systemctl get-default |
Set default runlevel | systemctl set-default graphical.target |
Shutdown | systemctl poweroff |
Reboot, suspend, hibernate | systemctl STATE |
[Unit]
Description=My custom service
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/sleep infinity
[Install]
WantedBy=multi-user.target
$ cat greeter.service
[Unit]
Description=My custom service
After=network.target
[Service]
Type=oneshot
ExecStart=/home/ak/greeter.sh
$cat greeter.timer
[Unit]
Description=Uruchamianie co godzine uslugi
[Timer]
OnCalendar=hourly
Oba pliki do /run/systemd/system
Dystrybucje Debian automatycznie rozpoznaja i wlaczaja nowe uslugi. W Redhat trzeba wyraznie wskazac:
sudo systemctl start greeter.timer
To samo tyczy sie wlaczenia uslugi do rozruchu w Redhat:
sudo systemctl enable greeter.timer
Status:
sudo systemctl status greeter.timer
journalctl -f greeter.service # -f wyswietla nowo pojawiajace sie wpisy
The systemd init system controls system and service operations with various types of unit files. Each unit file has a filename with a filename extension that describes which type of unit it is.
The /lib/systemd/system/
directory is the default location for unit files that either come with the operating system or come with any packages that you might install.
When you'll either need to modify some of these unit files or even create your own ou'll do that in the /etc/systemd/system/
directory. Any unit files in this directory that have the same name as unit files in /lib/systemd/system/
take precedence.
man systemd.unit
systemctl -t help # list all available unit types
systemctl --all list-units | grep .[unit-type]
systemctl --all list-units | grep .service # lists all available units in the type service
Unit type | Description |
---|---|
Target | A group of units that defines a synchronization point. The synchronization point is used at boot time to start the system in a particular state. |
Service | A unit of this type starts, stops, restarts or reloads a service daemon such as Apache webserver. |
Socket | A unit of this type activates a service when the service receives incoming traffic on a listening socket. |
Device | A unit of this type implements device-based activation such as a device driver. |
Mount | A unit of this type controls the file-system mount point. |
Automount | A unit of this type provides and controls on-demand mounting of file systems. |
Swap | A unit of this type encapsulates/activates/deactivates swap partition. |
Path | A unit of this type monitors files/directories and activates/deactivates a service if the specified file or directory is accessed. |
Timer | A unit of this type activates/deactivates specified service based on a timer or when the set time is elapsed. |
Snapshot | A unit that creates and saves the current state of all running units. This state can be used to restore the system later. |
Slice | A group of units that manages system resources such as CPU, and memory. |
Scope | A unit that organizes and manages foreign processes. |
busname | A unit that controls DBus system. |
systemctl --all list-units | grep active | grep .service
Status | Description |
---|---|
loaded | The unit's configuration file has been successfully read and processed. |
Active (exited) | Successfully executed the one-time configuration and after execution, the unit is neither running an active process nor waiting for an event. |
Active (running) | Successfully executed the one-time configuration and after execution, the unit is running one or more active processes. |
Active (waiting) | Successfully executed the one-time configuration and after execution, the unit is waiting for an event. |
Inactive (dead) | Either the one-time configuration failed to execute or not executed yet. |
-
service
: These are the configuration files for services. -
socket
: Sockets can either enable communication between different system services or they can automatically wake up a sleeping service when it receives a connection request. -
slice
: Slice units are used when configuring cgroups. -
mount
andautomount
: These contain mount point information for filesystems that are controlled by systemd. Normally, they get created automatically, so you shouldn't have to do too much with them. -
target
: Target units are used during system startup, for grouping units and for providing well-known synchronization points. -
timer
: Timer units are for scheduling jobs that run on a schedule. They replace the old cron system. -
path
: Path units are for services that can be started via path-based activation. -
swap
: Swap units contain information about your swap partitions.
Most of the systemd executables are found instead in the /lib/systemd/
directory. Rest in /bin
and /sbin
-
bootctl
-pozwala sprawdzicstan programu rozruchowego i zarzadza programami tego typu -
timedatectl
- definiowanie i wyswietlanie info o dacie/czasie -
coredumpctl
- pozwala przetwarzac zapisane zrzuty wygenerowane przez jadro -
journalctl
- przegladanie dziennikow zdarzen ktorymi zarzadza systemd
Systemd timer units are newer versions of cron daemon jobs. They can do everything that cron can. However, they offer some additional capabilities:
- You can specify the job to run at some time after a system boots.
- You can specify that the job has to run at some interval after some other job has run.
- The dependency on the timer unit can even be a service unit – the normal system service task.
- The granularity is much better. Cron jobs only go down to every minute. Systemd timers can trigger with accuracy defined to a second.
Timers are systemd unit files whose name ends in .timer that control .service files or events.
Timers have built-in support for calendar time events, monotonic time events, and can be run asynchronously.
- list timers
$ systemctl list-timers
$ systemctl list-timers --all # list all timers (including inactive)
$ systemctl status *timer
Example
$ loginctl enable-linger # run once - makes sure that the user mode systemd is launched on boot
$ systemctl --user edit --full --force mpop.service # does a daemon-reload in manual editing you have to remember
[Service]
Type=oneshot
ExecStart=mpop --quiet
$ systemctl --user start mpop
$ systemctl --user status mpop
$ journalctl --user -u mpop # full output of past runs
$ systemctl --user edit --full --force mpop.timer
[Timer]
OnCalendar=*-*-* 14,21:30:00
[Install]
WantedBy=timers.target
$ systemctl --user enable mpop.timer # hooks it into the timers.target
$ systemctl --user start timers.target # or systemctl --user start mpop.timer
Package systemd-cron
(at least on Debian) serves you systemd timers with a cron user interface: it translates the crontab line transparently for you and the command line tools are the same.
Time spans can be used to specify the desired accuracy as well as to define time spans for repeating or one-time events. It recognizes the following units:
- usec, us, µs
- msec, ms
- seconds, second, sec, s
- minutes, minute, min, m
- hours, hour, hr, h
- days, day, d
- weeks, week, w
- months, month, M (defined as 30.44 days)
- years, year, y (defined as 365.25 days)
AccuracySec=1us
grep Accur /usr/lib/systemd/system/*timer
See the man pages for systemd.timer and systemd.time for more information about timer accuracy, event-time specifications, and trigger events.
Systemd timers can be configured to trigger based on status changes in other systemd units. For example, a timer might be configured to trigger a specific elapsed time after system boot, after startup, or after a defined service unit activates. These are called monotonic timers. Monotonic refers to a count or sequence that continually increases. These timers are not persistent because they reset after each boot.
Timer | Monotonic | Definition |
---|---|---|
OnActiveSec= |
X | This defines a timer relative to the moment the timer is activated. |
OnBootSec= |
X | This defines a timer relative to when the machine boots up. |
OnStartupSec= |
X | This defines a timer relative to when the service manager first starts. For system timer units, this is very similar to OnBootSec= , as the system service manager generally starts very early at boot. It's primarily useful when configured in units running in the per-user service manager, as the user service manager generally starts on first login only, not during boot. |
OnUnitActiveSec= |
X | This defines a timer relative to when the timer that is to be activated was last activated. |
OnUnitInactiveSec= |
X | This defines a timer relative to when the timer that is to be activated was last deactivated. |
OnCalendar= |
This defines real-time (i.e., wall clock) timers with calendar event expressions. See systemd.time(7) for more information on the syntax of calendar event expressions. Otherwise, the semantics are similar to OnActiveSec= and related settings. This timer is the one most like those used with the cron service. |
Example Monotonic timer - will start 15 minutes after boot and again every week while the system is running
/etc/systemd/system/foo.timer
[Unit]
Description=Run foo weekly and on boot
[Timer]
OnBootSec=15min
OnUnitActiveSec=1w
[Install]
WantedBy=timers.target
systemd and its timers use a different style for time and date specifications than the format used in crontab.
The basic format for systemd timers using OnCalendar=
is DOW YYYY-MM-DD HH:MM:SS
. DOW (day of week) is optional, and other fields can use an asterisk (*
) to match any value for that position. All calendar time forms are converted to a normalized form. If the time is not specified, it is assumed to be 00:00:00. If the date is not specified but the time is, the next match might be today or tomorrow, depending upon the current time. Names or numbers can be used for the month and day of the week. Comma-separated lists of each unit can be specified. Unit ranges can be specified with ..
between the beginning and ending values.
There are a couple interesting options for specifying dates. The Tilde (~
) can be used to specify the last day of the month or a specified number of days prior to the last day of the month. The /
can be used to specify a day of the week as a modifier.
Calendar event specification | Description |
---|---|
DOW YYYY-MM-DD HH:MM:SS |
format |
*-*-* 00:15:30 |
Every day of every month of every year at 15 minutes and 30 seconds after midnight |
Weekly |
Every Monday at 00:00:00 |
Mon *-*-* 00:00:00 |
Same as weekly |
Mon |
Same as weekly |
Wed 2020-*-* |
Every Wednesday in 2020 at 00:00:00 |
Mon..Fri 2021-*-* |
Every weekday in 2021 at 00:00:00 |
2022-6,7,8-1,15 01:15:00 |
The 1st and 15th of June, July, and August of 2022 at 01:15:00am |
Mon *-05~03 |
The next occurrence of a Monday in May of any year which is also the 3rd day from the end of the month. |
Mon..Fri *-08~04 |
The 4th day preceding the end of August for any years in which it also falls on a weekday. |
*-05~03/2 |
The 3rd day from the end of the month of May and then again two days later. Repeats every year. Note that this expression uses the Tilde (~ ). |
systemd provides an excellent tool for validating and examining calendar time event specifications in a timer. The systemd-analyze calendar
tool parses a calendar time event specification and provides the normalized form as well as other interesting information such as the date and time of the next "elapse," i.e., match, and the approximate amount of time before the trigger time is reached.
*-05-03/2 | The third day of the month of may and then every 2nd day for the rest of May. Repeats every year. Note that this expression uses the dash (-).
In this example, the date and time are analyzed separately as non-related entities:
[root@testvm1 system]# systemd-analyze calendar 2030-06-17 15:21:16
Original form: 2030-06-17
Normalized form: 2030-06-17 00:00:00
Next elapse: Mon 2030-06-17 00:00:00 EDT
(in UTC): Mon 2030-06-17 04:00:00 UTC
From now: 10 years 0 months left
Original form: 15:21:16
Normalized form: *-*-* 15:21:16
Next elapse: Mon 2020-06-15 15:21:16 EDT
(in UTC): Mon 2020-06-15 19:21:16 UTC
From now: 3h 55min left
To analyze the date and time as a single unit, enclose them together in quotes. Be sure to remove the quotes when using them in the OnCalendar= event specification in a timer unit or you will get errors:
[root@testvm1 system]# systemd-analyze calendar "2030-06-17 15:21:16"
Normalized form: 2030-06-17 15:21:16
Next elapse: Mon 2030-06-17 15:21:16 EDT
(in UTC): Mon 2030-06-17 19:21:16 UTC
From now: 10 years 0 months left
list the next five elapses for the timestamp expression.
[root@testvm1 ~]# systemd-analyze calendar --iterations=5 "Mon *-05~3"
Original form: Mon *-05~3
Normalized form: Mon *-05~03 00:00:00
Next elapse: Mon 2023-05-29 00:00:00 EDT
(in UTC): Mon 2023-05-29 04:00:00 UTC
From now: 2 years 11 months left
Iter. #2: Mon 2028-05-29 00:00:00 EDT
(in UTC): Mon 2028-05-29 04:00:00 UTC
From now: 7 years 11 months left
Iter. #3: Mon 2034-05-29 00:00:00 EDT
(in UTC): Mon 2034-05-29 04:00:00 UTC
From now: 13 years 11 months left
Iter. #4: Mon 2045-05-29 00:00:00 EDT
(in UTC): Mon 2045-05-29 04:00:00 UTC
From now: 24 years 11 months left
Iter. #5: Mon 2051-05-29 00:00:00 EDT
(in UTC): Mon 2051-05-29 04:00:00 UTC
From now: 30 years 11 months left
The journal is systemd's logging facility. All messages that a daemon prints to either stdout or stderr gets added to the journal. There's also the system's boot messages, among other things.
-
-u
unit
sudo journalctl -u new-style-daemon
-
-f
follow
sudo journalctl -u new-style-daemon -f
--since and --until
sudo journalctl -u new-style-daemon \
> --since "2020-12-06 20:32:00" \
> --until "2020-12-06 20:33:00"
-
lines <n>
- show last n lines
sudo journalctl -u new-style-daemon --lines 5
Example service that will have the purpose of monitoring whether a given file is being modified.
- create file to monitor
$ touch /etc/test_config/config
- prepare a script that describes the procedure we require to be executed when the file is changed.
$ cat ~/sniff_printer.sh
echo "File /etc/test_config/config changed!"
- define our new service through the required unit – myservice_test.service – implementing the following script:
[Unit]
Description=This service is triggered through a file change
[Service]
Type=oneshot
ExecStart=bash /home/oem/sniff_printer.sh
[Install]
WantedBy=multi-user.target
- file path we’re monitoring through another unit called myservice_test.path, implemented via the following code:
[Unit]
Description=Path unit for watching for changes in "config"
[Path]
PathModified=/etc/test_config/config
Unit=myservice_test.service
[Install]
WantedBy=multi-user.target
- As we are adding a new file to the service directory, we must execute a reload:
$ systemctl daemon-reload
- enable and start the service:
$ systemctl enable myservice_test
$ systemctl start myservice_test
- Change file and observe effect
$ echo test >> /etc/test_config/config
$ systemctl status myservice_test
Apr 06 15:37:12 oem-virtual-machine bash[5340]: File /etc/
But the process is no longer active as the service unit is of type oneshot, therefore only another file update will retrigger it.