0% found this document useful (0 votes)
95 views

Linux - Admin Local - Systemd

Systemd takes the place of initd as the first process of the Linux system. It manages all system resources through units like services, targets, devices, mounts etc. Some key systemctl commands to control services include status, start, stop, restart, reload. Services can be enabled to start at boot or masked to prevent starting. Systemd visualizes the relationships between processes and services using control groups and the startup sequence.

Uploaded by

irudimena
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views

Linux - Admin Local - Systemd

Systemd takes the place of initd as the first process of the Linux system. It manages all system resources through units like services, targets, devices, mounts etc. Some key systemctl commands to control services include status, start, stop, restart, reload. Services can be enabled to start at boot or masked to prevent starting. Systemd visualizes the relationships between processes and services using control groups and the startup sequence.

Uploaded by

irudimena
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 12

SYSTEMD – Administración de servicios con systemctl

https://www.freedesktop.org/wiki/Software/systemd/

systemd

• Systemd takes the place of initd, and it becomes the first process of the system (PID is 1), and other processes are its child processes
• In systemd all services are exposed at runtime in a kernel file system, the cgroupfs.
• Systemd gestiona todos los recursos del sistema a través de Unidades. Systemd has 12 unit types. service is system services, and
when you're running any of the above commands you can leave off the .service extension, because systemd assumes a service unit if
you don't specify something else. The other unit types are:

Service unit: system service


Target unit: A group of multiple units
Device Unit: Hardware device
Mount Unit: Mount point of the file system
Automount Unit: Auto Mount Point
Path Unit: file or path
Scope Unit: An external process that is not started by Systemd
Slice Unit: Process Group
Snapshot Unit: Systemd snapshot; you can switch back to a certain snapshot
Socket Unit: Socket for interprocess communication
Swap Unit: swap file
Timer Unit: Timer

Comandos administrativos

ystemctl timedatectl localectl bootctl machinectl


loginctl hostnamectl systemctl journalctl

systemctl
sudo systemctl reboot
sudo systemctl poweroff
sudo systemctl halt
sudo systemctl suspend
sudo systemctl hibernate
sudo systemctl hybrid-sleep
sudo systemctl rescue

systemd-analyze
systemd-analyze # View the startup time
systemd-analyze blame # View the startup time of each service
systemd-analyze critical-chain # Show the startup process flow
systemd-analyze critical-chain atd.service # Show the startup flow of the specified service

localectl
localectl # View localization settings
localectl set-locale LANG=en_GB.utf8 # Set localization parameters
localectl set-keymap en_GB

hostnamectl
hostnamectl # Show the information about the current host
hostnamectl set-hostname rhel7 # Set the host name

timedatectl
timedatectl # View the current time zone settings
timedatectl list-timezones # Show all the available time zones
timedatectl set-timezone America/New_York # Set the current time zone
timedatectl set-time YYYY-MM-DD
timedatectl set-time HH:MM:SS

loginctl
# List the current sessions
$ loginctl list-sessions

# List the currently logged-in users


$ loginctl list-users

# List the information showing the specified user


$ loginctl show-user ruanyf

Unidades y servicios

Los ficheros de unidades pueden albergarse en diferentes ubicaciones por orden de prioridad

System Wide: /etc/systemd/system > /run/systemd/system > /usr/lib/systemd/system


User side: /etc/systemd/user > /run/systemd/user > /usr/lib/systemd/user

ln -s /bin/systemctl /usr/local/bin/sc

sc list-units # List the running Unit


sc list-units –all # List all the Units, including w/o configuration file or fails to start
sc list-units --all –state=inactive # List all the Units that doesn't run
sc list-units –failed # List all the Units that fails to load
sc list-units --type=service # List all the running Units of which type is service
sc ; Lista todos los servicios en ejecución
sc (list-units) ; Todas las unidades cargadas o intentadas de cargar en memoria que estan activas
sc (list-units) –all ; Todas las unidades cargadas o intentadas de cargar en memoria aunque no estan activas
sc (list-units-files) ; Todas las unidades que haya intentado cargar o no en el arranque
sc list-unit-files (--type=service) ; Muestra ficheros de configuración
sc list-units --type service --all
sc --type=service ; Muestra estado servicios
systemctl is-system-running ; Comprueba si el arranque ha finalizado del todo
systemctl show -p "Wants" multi-user.target # Qué servicios carga un target
systemd --test --system --unit=foobar.target # Simula qué transacción inicial se ejecutará en el arranque

Otros: “WantedBy", "Requires", "RequiredBy", "Conflicts", "ConflictedBy", "Before", "After"

Estado de una unidad/servicio

• Enabled means it has a symlink in a .wants directory. It has been established the enabled link
• Disabled means it does not. It has not established the enabled link
• Static means the service is missing the [Install] section in its init script, so you cannot enable or disable it. Static services are usually
dependencies of other services, and are controlled automatically.
• Masked: The configuration file is forbidden to establish an enabled link

systemctl status # Display the system status


sysystemctl status bluetooth.service # Display the status of a single unit
systemctl -H [email protected] status httpd.service # Display the status of a unit on the remote host
systemctl is-active application.service # Show whether a Unit is running
systemctl is-failed application.service # Show whether a Unit is in a boot failure state
systemctl is-enabled application.service # Show whether a Unit service has established an enabled link
systemctl cat atd.service # Muestra contenido de un fichero de configuración

Reinicio/recarga/detención/estado

systemctl status [name.service]


systemctl is-active [name.service]
systemctl start [name.service]
systemctl --user start A.service
systemctl stop [name.service]
systemctl restart [name.service]
systemctl reload [name.service]
systemctl --user daemon-reload ; Relanza todos los servicios
systemctl start apache.service # Start a service
systemctl stop apache.service # Stop a service
systemctl restart apache.service # Restart a service
systemctl kill apache.service # Kill all the child processes of a service
systemctl reload apache.service # Reload the configuration files of a service
systemctl daemon-reload # reload all the modified configuration files
systemctl show httpd.service # Show all the underlying parameters of a Unit
systemctl show -p CPUShares httpd.service # Show the value of the specified property of a Unit
systemctl set-property httpd.service CPUShares=500 # Set the specified property of a Unit

Activacion/desactivación

systemctl status firewalld.service


systemctl stop|status <servicio>
systemctl enable [email protected] ; Activa arranque servicio
systemctl disable system.slice

ln -s '/usr/lib/systemd/system/[email protected]' '/etc/systemd/system/multi-user.target.wants/[email protected]

• También se puede crear un vínculo simbólico en el directorio multi-user.target.wants (runlevel 3) que también se ejecuta para el
graphical.target (runlevel 5)
• Deshabilitar una unidad de la que depende otra unidad que no esta deshabilitada, hará que la primera se inicie aunque esté
deshabilitada

ln -sf /usr/lib/systemd/system/foobar.service /etc/systemd/system/multi-user.target.wants/foobar.service


systemctl daemon-reload

Enmascaramiento de unidades (deshabilitación total de unidades)

El enmascaramiento de una unidad permite la deshabilitación total de la unidad aun cuando existan unidades activas que depedan de la
unidad deshabilitada.

systemctl mask httpd.service # Created symlink from /etc/systemd/system/httpd.service to /dev/null.


# (ln -s /dev/null /etc/systemd/system/httpd.service)
systemctl start httpd.service # Now attempt to start the web server manually:
Failed to start httpd.service: Unit httpd.service is masked
systemctl unmask httpd.service

Procesos pertenecientes a servicios / Dependencias de unidades

systemd-cgls ; Muestra árbol de dependencia de servicios


alias psc='ps xawf -eo pid,user,cgroup,args'
psc
systemctl list-dependencies # Muestra todas las dependencias de cada unidad
systemctl list-dependencies nginx.service
systemctl list-dependencies --all nginx.service # Some dependencies of the output for the above command are of the type Target

Grupos de control (cgroup)

Permiten gestionar algunos servicios en conjunto


TARGETS (runlevels)

Un Target es un grupo de unidades que suelen ser iniciadas conjuntamente al arrancar el equipo-

; Muestra el entorno de ejecución por defecto (puede haber mas de un target activo)

systemctl get-default
ls -lrt /etc/systemd/system/default.target
lrwxrwxrwx. 1 root root 36 Sep 23 20:01 /etc/systemd/system/default.target -> /lib/systemd/system/graphical.target

; Establece el entorno de ejecución por defecto a multiusuario pero sin interfaz gráfico

systemctl set-default multi-user.target


ln -sf /usr/lib/systemd/system/multi-user.target /etc/systemd/system/default.target

; Establece el entorno de ejecución por defecto a multiusuario con interfaz gráfico

ln -sf /usr/lib/systemd/system/graphical.target /etc/systemd/system/default.target

; Muestra dependencias de un target

systemctl list-dependencies graphical.target

● ├─accounts-daemon.service
● ├─apache2.service
● ├─apport.service
● ├─display-manager.service

; Cambia el runlevel actual (no afecta al arranque)

systemctl isolate runlevel5.target ≡ systemctl isolate graphical.target

; Muestra todos los runlevels (targets) activos

sc list-units --type=target

Comparativa targets vs. runlevels

A diferencia de los runlevels, pueden ejecutarse multiples targets a la vez.

0 Halt poweroff.target (runlevel0.target) Shuts down system


1 Single-User Mode rescue.target (runlevel1.target) No network, no daemons, no non-root logins
2 M-User Mode No network, no daemons
3 M-User Mode+Net multi-user.target (runlevel3.target) Starts the system normally
4 Undefined
5 X11 graphical.target (runlevel5.target) As runlevel 3 + display manager(X)
6 Reboot reboot.target (runlevel6.target) Reboots the system
Emergency emergency.target
Ctrl-Alt-Delete /etc/systemd/system/ctrl-alt-del.target

Targets habituales

sc list-units --type=target

UNIT LOAD ACTIVE SUB DESCRIPTION


basic.target loaded active active Basic System
cryptsetup.target loaded active active Local Encrypted Volumes
getty.target loaded active active Login Prompts
graphical.target loaded active active Graphical Interface
local-fs-pre.target loaded active active Local File Systems (Pre)
local-fs.target loaded active active Local File Systems
multi-user.target loaded active active Multi-User System
network.target loaded active active Network
nss-user-lookup.target loaded active active User and Group Name Lookups
paths.target loaded active active Paths
remote-fs.target loaded active active Remote File Systems
slices.target loaded active active Slices
sockets.target loaded active active Sockets
sound.target loaded active active Sound Card
swap.target loaded active active Swap
sysinit.target loaded active active System Initialization
system-update-pre.target loaded active active Offline System Update (Pre)
timers.target loaded active active Timers

LOAD = Reflects whether the unit definition was properly loaded.


ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB = The low-level unit activation state, values depend on unit type.

18 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.
CREACIÓN DE UN SERVICIO

cd /etc/systemd/system o /etc/systemd/system/custom.target.wants
nano configsistema.service

[Unit]
Description = Configuracion sistema ETSINF
After=multi-user.target
Before=display-manager.service

[Service]
Type=simple
Type=oneshot ; systemd waits for the process to exit before it starts any follow-up units
Type=idle ; actual execution of the service binary is delayed until all jobs are dispatched.

RemainAfterExit=false ; if true, systemd keeps the process as “active”

ExecStart = /root/configura
ExecStart=/usr/bin/myinitscript.sh start
ExecStop=/usr/bin/myinitscript.sh stop

[Install]
WantedBy=multi-user.target

nano /root/scripts/configurasistema
chmod +x configurasistema
systemctl start configurasistema.service

[Unit]

The [Unit] block is usually the first block of the configuration file, and it's used to define the metadata for the Unit and configure the
relationship to other Units. Its main fields are as follows.

Description
Documentation: Document Address
Requires: Other Units that the current Unit depends on. If they are not running, the current Unit will fail to start.
Wants: Other Units that work with the current Unit. If they are not running, the current Unit will not fail to start.
BindsTo: Similar to Requires. If the Unit specified by it exits, it will cause the current Unit to stop running.
Before: If the Unit specified by this field is also to be started, it must be started after the current Unit.
After: If the Unit specified by this field is also to be started, it must be started before the current Unit.
Conflicts: The Unit specified here cannot be run simultaneously with the current Unit.
Condition...: The condition that the current Unit must satisfy, otherwise it will not run.
Assert...: The condition that the current Unit must satisfy, otherwise it will fail to start.

Description=Configuracion sistema ETSINF


After=network.target
After=B.service
IgnoreOnIsolate=yes

[Install]

[Install] is usually the last block of the configuration file, and it's used to define how to start, and whether it starts up automatically. Its main
fields are as follows.

WantedBy: Its value is one or more Targets. When the current Unit is enabled, the symbolic link will be placed in the subdirectory
consisting of the Target name + .wants suffix which is under the /etc/systemd/system directory.
RequiredBy: Its value is one or more Targets. When the current Unit is enabled, the symbolic link will be placed in the subdirectory
consisting of the Target name + .required suffix. which is the /etc/systemd/system directory.
Alias: The alias that the current Unit can be used to start
Also: Other Units that will be enabled at the same time when the current Unit is enabled.

WantedBy=multi-user.target

Configuraciones

After declares ordering, and describes that network.target and sshd-keygen.service should run first.

Wants describes that sshd-keygen should be run in order for this service to start. Note the subtle difference from ordering. systemd
considers order and dependencies orthogonal, meaning just because sshd-keygen comes first doesn’t mean it is a dependency of sshd — although
in this case it is. Wants means systemd should run sshd-keygen.service, but if that doesn’t complete successfully (for instance, if SSH
server keys already exist), sshd will still run. If sshd-keygen.service needed to complete successfully, you’d use Requires instead.

EnvironmentFile, similar to SysVinit, is a configuration file with options for sshd. It contains a set of key=value pairs that will be
passed to sshd.
ExecStart is the command that runs to start sshd. This replaces the entire start function in the old initscript. The $OPTIONS variable here
is what is specified in EnvironmentFile for the variable OPTIONS.

ExecReload is the command that runs if the sysadmin reloads the sshd daemon. This replaces the entire reload function in the old
initscript.

KillMode sets how systemd will stop the service. In this case, systemd will stop the main sshd process only. Any additional sshd child
processes will continue to manage their open SSH sessions. This is not an option used often, but it is important here. For instance, it
stops you from killing your own SSH session when you run systemctl!

Restart determines how systemd manages the service if it stops unexpectedly. In this case, on-failure means virtually any unexpected
failure will cause systemd to restart sshd. If sshd stops normally, though, such as with a systemctl stop command, it will not be restarted.

RestartSec allows 42 seconds of sleep time before sshd is restarted due to an unexpected stop.

WantedBy means when the command systemctl enable sshd.service is run, a link is placed in the multi-user.target.wants directory by default.
This is one of the mechanisms systemd uses to determine units to run for specific targets. So multi-user.target and any target that depends
on it, will include running sshd.service.

[Service]

The [Service] block is used for the configuration of the Service. Only the Unit of the type Service has this block. Its main fields are as
follows.

Type: Define the behavior of the process at startup. Its values are as follows.
Type=simple: The default value. It executes the command specified by ExecStart, and starts the main process.
Type=forking: Create a child process from the parent process in the fork mode. After the creation, the parent process will exit immediately.
Type=oneshot: One-time process. Systemd will wait for the current service to exit, and then move on executing.
Type=dbus: The current service is started by D-Bus.
Type=notify: After the current service finishes starting, it will notify Systemd, and then go on executing.
Type=idle: The current service will run only after other tasks have finished executing.
ExecStart: The command to start the current service.
ExecStartPre: The command executed before starting the current service.
ExecStartPost: The command executed after starting the current service.
ExecReload: The command executed when restarting the current service.
ExecStop: The command executed when stopping the current service.
ExecStopPost: The command executed after stopping the current service.
RestartSec: The number of seconds of the interval for restarting the current service automatically.
Restart: Define the circumstances on which Systemd will restart the current service automatically, and its possible values include always,
on-success, on-failure, on-abnormal, on-abort, on-watchdog.
TimeoutSec: Define the number of seconds Systemd waits before stopping the current service.
Environment: Specify the environment variables.

Type=oneshot
ReamainAfterExit=true
ExecStart=/root/configura
ExecStart=/usr/bin/echo 'A starts' ; /usr/bin/sleep 10 ; /usr/bin/echo 'A ends'
ExecStart=/usr/bin/echo 'prog1 starts' ; /usr/bin/sleep 10 ; /usr/bin/echo 'prog1 ends'

Type: oneshot
RemainAfterExit=true/false
ExecStart=/usr/bin/script

Modificación de un servicio

Copy the service file from /usr/lib/systemd/system to /etc/systemd/system and edit it there. The latter directory takes precedence over the
former, and rpm will never overwrite it. If you want to use the distributed service file again you can simply delete (or rename) the service file
in /etc/systemd/system again.

Require/Wants/After

After: Solo comprueba que la unidad especificada esté activa pero no la activa (se esperará y retrasara su propia activación)
Requires: Comprueba y activa las unidades especificadas antes de poder activar la unidad.

• Es posible usar Wants= sin After= si no se quiere esperar al arranque de las demás unidades
• Que una unidad especifique otra unidad en Wants= no asegura que dicha unidad se llegue a ejecutar (solo se solicitará su ejecución)
• Si una unidad especifica a otra en Requires=, la primera no se ejecutará si la segunda no se ejectua con éxito
• Before/After es independiente de las dependencias.

Requires (DEPENDENCIA9
Configures requirement dependencies on other units. If this unit gets activated, the units listed here will be activated as well. If one of
the other units gets deactivated or its activation fails, this unit will be deactivated. This option may be specified more than once or
multiple space-separated units may be specified in one option in which case requirement dependencies for all listed names will be created.
Note that requirement dependencies do not influence the order in which services are started or stopped. This has to be configured
independently with the After= or Before= options. If a unit foo.service requires a unit bar.service as configured with Requires= and no
ordering is configured with After= or Before=, then both units will be started simultaneously and without any delay between them if
foo.service is activated. Often, it is a better choice to use Wants= instead of Requires= in order to achieve a system that is more robust
when dealing with failing services.
Wants
A weaker version of Requires=. Units listed in this option will be started if the configuring unit is. However, if the listed units fail to
start or cannot be added to the transaction, this has no impact on the validity of the transaction as a whole. This is the recommended way
to hook start-up of one unit to the start-up of another unit.
Before=, After= (ORDENACIÓN DE DEPENDENCIAS)
A space-separated list of unit names. Configures ordering dependencies between units. If a unit foo.service contains a setting
Before=bar.service and both units are being started, bar.service's start-up is delayed until foo.service is started up. Note that this
setting is independent of and orthogonal to the requirement dependencies as configured by Requires=. It is a common pattern to include a
unit name in both the After= and Requires= option, in which case the unit listed will be started before the unit that is configured with
these options. This option may be specified more than once, in which case ordering dependencies for all listed names are created. After= is
the inverse of Before=, i.e. while After= ensures that the configured unit is started after the listed unit finished starting up, Before=
ensures the opposite, i.e. that the configured unit is fully started up before the listed unit is started. Note that when two units with an
ordering dependency between them are shut down, the inverse of the start-up order is applied. i.e. if a unit is configured with After= on
another unit, the former is stopped before the latter if both are shut down. Given two units with any ordering dependency between them, if
one unit is shut down and the other is started up, the shutdown is ordered before the start-up. It doesn't matter if the ordering dependency
is After= or Before=. It also doesn't matter which of the two is shut down, as long as one is shut down and the other is started up. The
shutdown is ordered before the start-up in all cases. If two units have no ordering dependencies between them, they are shut down or started
up simultaneously, and no ordering takes place.

Ejemplos

Wants=sshd-keygen.service
After=network.target sshd-keygen.service
UNIT TEMPLATES

Los template units permiten gestionar varias unidades/instancias desde un único fichero de configuración. Se pueden pasar parámetros a la
unidad para poderse referir a cada de las unidades del fichero de configuración.

%i passes the argument, specially formatted (escaped)


%I passes the argument verbatim without escaping

Ejemplo

[Unit]
Description=OpenVPN Robust And Highly Flexible Tunneling Application On %I
After=network.target

[Service]
PrivateTmp=true
Type=forking
PIDFile=/var/run/openvpn/%i.pid
ExecStart=/usr/sbin/openvpn --daemon --writepid /var/run/openvpn/%i.pid --cd /etc/openvpn/ --config %i.conf

[Install]
WantedBy=multi-user.target

# fancy-web-server.service
[Unit]
Description=My HTTP server
AssertPathExists=/srv/webserver

[Service]
Type=notify
ExecStart=/usr/sbin/some-fancy-httpd-server %i.conf
Nice=5

[Install]
WantedBy=multi-user.target
systemctl start [email protected]
systemctl start [email protected]
/usr/sbin/some-fancy-httpd-server config1.conf
/usr/sbin/some-fancy-httpd-server config2.conf

Referencias

• Systemd Template Units


https://fedoramagazine.org/systemd-template-unit-files/
ANALISIS DE TIEMPOS

Analisis de tiempo de arranque

sc status bluetooth.service

system-analyze blame (analiza hasta la ventana de login)


system-analyze plot > g.svg

daemon-reload

systemd-sysv-generator → /run/systemd/generator.late/ConfigLab.service

journalctl -b -e --user | tail -n 13

REGISTRO DE EVENTOS

Systemd manages the startup logs for all Units. So you can view all the logs (kernel logs and application logs) with just one command of
journalctl. The configuration file for the log is /etc/systemd/journald.conf.

# View all the logs (Only the logs started this time are saved by default.)
$ sudo journalctl

# View the kernel logs (The application logs are not displayed.)
$ sudo journalctl -k

# View the logs that are started this time. (solo desde último arranque)
$ sudo journalctl -b
$ sudo journalctl -b -0

# View the logs that were last started (you need to change the settings).
$ sudo journalctl -b -1

# View the logs for the specified time.


$ sudo journalctl --since="2012-10-30 18:17:16"
$ sudo journalctl --since "20 min ago"
$ sudo journalctl --since yesterday
$ sudo journalctl --since "2015-01-10" --until "2015-01-11 03:00"
$ sudo journalctl --since 09:00 --until "1 hour ago"

# Show the logs of the last 10 lines.


$ sudo journalctl -n

# Show the logs of the last specified lines.


$ sudo journalctl -n 20

# Show the latest logs in real time.


$ sudo journalctl -f

# View the logs of the specified service


$ sudo journalctl /usr/lib/systemd/systemd

# View the logs of the specified process


$ sudo journalctl _PID=1

# View the logs of a script for a path


$ sudo journalctl /usr/bin/bash

# View the logs of the specified user


$ sudo journalctl _UID=33 --since today

# View the logs of a Unit (filtrado específico)


$ sudo journalctl -u nginx.service
$ sudo journalctl -u nginx.service --since today

# Show the latest logs of a Unit in real time.


$ sudo journalctl -u nginx.service -f

# Merge and show the logs of multiple Units.


$ journalctl -u nginx.service -u php-fpm.service --since today

# View the logs of the specified priority level (and above), and there are 8 levels.
# 0: emerg, 1: alert, 2: crit, 3: err, 4: warning, 5: notice, 6: info, 7: debug
$ sudo journalctl -p err -b

# The output for logs is paging by default. You can use --no-pager to change it to normal standard output.
$ sudo journalctl --no-pager

# Salida de en formato extenso


$ journalctl -b -u NetworkManager --since='yesterday' -o verbose

# Output in the JSON format (a single line).


$ sudo journalctl -b -u nginx.service -o json

# Output in the JSON format (multiple lines), which is more readable.


$ sudo journalctl -b -u nginx.serviceqq
-o json-pretty
# Show the hard disk space occupied by the logs.
$ sudo journalctl --disk-usage

# Specify the maximum space that can be occupied by the log file
$ sudo journalctl --vacuum-size=1G

# Specify how long the log file will be saved.


$ sudo journalctl --vacuum-time=1years

# Filtrado por campos


$ journalctl --list-boots
$ journalctl _BOOT_ID=1c677fd72e82413bb68fe95f10524aef -u NetworkManager
$ journalctl _COMM=dhclient --since='2 hours ago'
$ journalctl -F _BOOT_ID
$ mind.journalctl -F _SYSTEMD_UNIT

[Unit]

[Service]
RemainsAfterExit=no
TimeoutSec=0min (stop timeout)
StandardOutput=journal+console
StandardError=journal+console

FICHEROS DE CONFIGURACIÓN ADICIONALES

• /etc/hostname: the host name for the system. One of the most basic and trivial system settings. Nonetheless previously all
distributions used different files for this. Fedora used /etc/sysconfig/network, OpenSUSE /etc/HOSTNAME. We chose to standardize on
the Debian configuration file /etc/hostname.
• /etc/vconsole.conf: configuration of the default keyboard mapping and console font.
• /etc/locale.conf: configuration of the system-wide locale.
• /etc/modules-load.d/*.conf: a drop-in directory for kernel modules to statically load at boot (for the very few that still need
this).
• /etc/sysctl.d/*.conf: a drop-in directory for kernel sysctl parameters, extending what you can already do with /etc/sysctl.conf.
• /etc/tmpfiles.d/*.conf: a drop-in directory for configuration of runtime files that need to be removed/created/cleaned up at boot
and during uptime.
• /etc/binfmt.d/*.conf: a drop-in directory for registration of additional binary formats for systems like Java, Mono and WINE.
• /etc/os-release: a standardization of the various distribution ID files like /etc/fedora-release and similar. Really every
distribution introduced their own file here; writing a simple tool that just prints out the name of the local distribution usually
means including a database of release files to check. The LSB tried to standardize something like this with the lsb_release tool,
but quite frankly the idea of employing a shell script in this is not the best choice the LSB folks ever made. To rectify this we
just decided to generalize this, so that everybody can use the same file here.
• /etc/machine-id: a machine ID file, superseding D-Bus' machine ID file. This file is guaranteed to be existing and valid on a
systemd system, covering also stateless boots. By moving this out of the D-Bus logic it is hopefully interesting for a lot of
additional uses as a unique and stable machine identifier.
• /etc/machine-info: a new information file encoding meta data about a host, like a pretty host name and an icon name, replacing
stuff like /etc/favicon.png and suchlike. This is maintained by systemd-hostnamed.

COMPATIBILIDAD SYSVINIT

Another notable feature of systemd, though, is that it doesn’t abandon compatibility for SysVinit. Some administrators have created their
own custom startup scripts such as /etc/rc.d/rc.local. If you’re not prepared to convert it, don’t worry — systemd will honor it, using the rc-
local.service file already included.

Remember, if you are building custom system services for your Fedora, it’s best to place them into /etc/systemd/system. Typically /etc/ is
where all system configuration or customization is kept. This allows you to avoid putting customizations in /usr/lib/systemd/system which is
managed by Fedora’s package system.

AYUDA

man systemd.unit

REFERENCIAS

• https://www.linux.com/learn/understanding-and-using-systemd
• https://www.freedesktop.org/wiki/Software/systemd/
• https://www.tutorialdocs.com/article/learn-systemd-commands-in-20-minutes.html
• https://fedoramagazine.org/what-is-an-init-system/

CASO PRÁCTICO: EJECUTAR SERVICIOS CUANDO LA RED ESTÉ ACTIVADA
https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/

$network es una característica de arranque especificada en el estandar LSB para poder especificar dependencias en el sistema de scripts de
inicialización en el estilo System V.

En systemd existen 3 target units que asumen el rol de $network

network.target = Pila de gestión de red activa

No tiene mucho uso en el arranque. Es una unidad pasiva (no se puede invocar ni manualmente si no solo desde el servicio de gestion de red
directamente y se han de evitar las referencias tipo Wants=network.target o Requires=network.target). Solo indica que la pila de gestión de
red está activa. No implica que los interfaces de red estén preparados y activos. Solo se emplea para desactivar ordenadamente la red al
apagar el equipo. El uso correcto, por tanto, en scripts que empleen la red sería:

[Unit]
After=network.target

network-online.target = Interfaz de red enrutable IP configurado y activo

Indica que la red está activa y el interfaz tiene asignado correctamente su IP. Es una unidad activa por lo que puede ser solicitada por otros
servicios que dependan de este.

network-pre.target

Se usa generalmente por firewalls que desean establecer un firewall antes de activar un interfaz de red. Es una unidad pasiva que no puede
ser invocada directamente que no es invocada por el servicio de gestión de red sino por el servicio que se ha de ejecutar antes de el. Este
servicio de gestión se configuraría pues asi: After=network-pre.target, pero evitaría cualquier Wants=network-pre.target o incluso
Requires=network-pre.target

Los servicios que se hayan de ejecutar antes de que la red esté configurada deberían indicar: Before=network-pre.target y también
Wants=network-pre.target para solicitar su ejecución.

Ejemplo

[Unit]
After=network-online.target
Wants=network-online.target

Referencias

Linux Standard Base


https://en.wikipedia.org/wiki/Linux_Standard_Base

Facility Names
http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/facilname.html
EJEMPLOS DE UNIDADES/SERVICIOS

sshd.service
[Unit]
Description=OpenSSH server daemon
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target sshd-keygen.service
Wants=sshd-keygen.service

[Service]
EnvironmentFile=/etc/sysconfig/sshd
ExecStart=/usr/sbin/sshd -D $OPTIONS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target

You might also like