Table des matières

Version : 2024.01

Dernière mise-à-jour : 2024/09/26 13:19

RH12412 - Gestion des Services et des Démons

Contenu du Module

Systemd

Les systèmes de démarrage antérieurs à Systemd, SysVinit et Upstart, étaient des systèmes de démarrage séquentiels.

Systemd essaie, par contre, de démarrer autant de services en parallèle que possible. Ceci est rendu possible car la majorité d'architectures matérielles modernes sont multi-cœurs. Si un service dépend d'un autre qui n'est pas encore démarré ce premier est mis en attente dans une mémoire tampon. Qui plus est, les services qui ne sont pas nécessaires au démarrage de la machine, tel cups, ne sont démarrés ultérieurement que si nécessaire. Lors de démarrage, les partitions sont montées en parallèle. Dernièrement, Systemd remplace les scripts de démarrage traditionnels avec des binaires compilés, beaucoup plus rapides que leur prédécesseurs.

Au lieu de parler de scripts de démarrage et de niveaux d'exécution, Systemd utilise la terminologie Unités (Units) et Cibles (Targets). Une Unité peut être :

Une Cible est en quelque sorte une grande étape dans le démarrage du système :

Systemd utilise des Cibles d'une manière similaire à ce que SysVinit utilise des niveaux d'exécution. Pour rendre la transition plus facile, il existe des Cibles qui “simulent” les niveaux d'exécution de SysVinit :

[root@redhat9 ~]# ls -l /usr/lib/systemd/system/runlevel*
lrwxrwxrwx. 1 root root 15 Jul 18 13:00 /usr/lib/systemd/system/runlevel0.target -> poweroff.target
lrwxrwxrwx. 1 root root 13 Jul 18 13:00 /usr/lib/systemd/system/runlevel1.target -> rescue.target
lrwxrwxrwx. 1 root root 17 Jul 18 13:00 /usr/lib/systemd/system/runlevel2.target -> multi-user.target
lrwxrwxrwx. 1 root root 17 Jul 18 13:00 /usr/lib/systemd/system/runlevel3.target -> multi-user.target
lrwxrwxrwx. 1 root root 17 Jul 18 13:00 /usr/lib/systemd/system/runlevel4.target -> multi-user.target
lrwxrwxrwx. 1 root root 16 Jul 18 13:00 /usr/lib/systemd/system/runlevel5.target -> graphical.target
lrwxrwxrwx. 1 root root 13 Jul 18 13:00 /usr/lib/systemd/system/runlevel6.target -> reboot.target

/usr/lib/systemd/system/runlevel1.target.wants:
total 0

/usr/lib/systemd/system/runlevel2.target.wants:
total 0

/usr/lib/systemd/system/runlevel3.target.wants:
total 0

/usr/lib/systemd/system/runlevel4.target.wants:
total 0

/usr/lib/systemd/system/runlevel5.target.wants:
total 0

LAB #1 - La Commande systemctl

Pour visualiser la liste des Unités, il convient d'utiliser la commande systemctl avec l'option list-units :

[root@redhat9 ~]# systemctl list-units
  UNIT                                                                                                     LOAD   ACTIVE SUB       DESCRIPTION                                >
  proc-sys-fs-binfmt_misc.automount                                                                        loaded active running   Arbitrary Executable File Formats File Syst>
  sys-devices-pci0000:00-0000:00:01.1-ata2-host2-target2:0:0-2:0:0:0-block-sr0.device                      loaded active plugged   QEMU_DVD-ROM
  sys-devices-pci0000:00-0000:00:05.0-0000:01:01.0-virtio2-host0-target0:0:0-0:0:0:0-block-sda-sda1.device loaded active plugged   QEMU_HARDDISK 1
  sys-devices-pci0000:00-0000:00:05.0-0000:01:01.0-virtio2-host0-target0:0:0-0:0:0:0-block-sda-sda2.device loaded active plugged   QEMU_HARDDISK 2
  sys-devices-pci0000:00-0000:00:05.0-0000:01:01.0-virtio2-host0-target0:0:0-0:0:0:0-block-sda.device      loaded active plugged   QEMU_HARDDISK
  sys-devices-pci0000:00-0000:00:12.0-virtio1-net-ens18.device                                             loaded active plugged   Virtio network device
  sys-devices-platform-serial8250-tty-ttyS0.device                                                         loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS0
  sys-devices-platform-serial8250-tty-ttyS1.device                                                         loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS1
  sys-devices-platform-serial8250-tty-ttyS2.device                                                         loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS2
  sys-devices-platform-serial8250-tty-ttyS3.device                                                         loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS3
  sys-devices-virtual-block-dm\x2d0.device                                                                 loaded active plugged   /sys/devices/virtual/block/dm-0
  sys-devices-virtual-block-dm\x2d1.device                                                                 loaded active plugged   /sys/devices/virtual/block/dm-1
  sys-devices-virtual-misc-rfkill.device                                                                   loaded active plugged   /sys/devices/virtual/misc/rfkill
  sys-module-configfs.device                                                                               loaded active plugged   /sys/module/configfs
  sys-module-fuse.device                                                                                   loaded active plugged   /sys/module/fuse
  sys-subsystem-net-devices-ens18.device                                                                   loaded active plugged   Virtio network device                      >
  -.mount                                                                                                  loaded active mounted   Root Mount
  boot.mount                                                                                               loaded active mounted   /boot
  dev-hugepages.mount                                                                                      loaded active mounted   Huge Pages File System
  dev-mqueue.mount                                                                                         loaded active mounted   POSIX Message Queue File System
  proc-sys-fs-binfmt_misc.mount                                                                            loaded active mounted   Arbitrary Executable File Formats File Syst>
  run-credentials-systemd\x2dsysctl.service.mount                                                          loaded active mounted   /run/credentials/systemd-sysctl.service
  run-credentials-systemd\x2dtmpfiles\x2dsetup.service.mount                                               loaded active mounted   /run/credentials/systemd-tmpfiles-setup.ser>
  run-credentials-systemd\x2dtmpfiles\x2dsetup\x2ddev.service.mount                                        loaded active mounted   /run/credentials/systemd-tmpfiles-setup-dev>
  run-user-1000.mount                                                                                      loaded active mounted   /run/user/1000
  run-user-42.mount                                                                                        loaded active mounted   /run/user/42
  sys-fs-fuse-connections.mount                                                                            loaded active mounted   FUSE Control File System
  sys-kernel-config.mount                                                                                  loaded active mounted   Kernel Configuration File System
  sys-kernel-debug-tracing.mount                                                                           loaded active mounted   /sys/kernel/debug/tracing
  sys-kernel-debug.mount                                                                                   loaded active mounted   Kernel Debug File System
  sys-kernel-tracing.mount                                                                                 loaded active mounted   Kernel Trace File System                   >
  cups.path                                                                                                loaded active running   CUPS Scheduler
  systemd-ask-password-plymouth.path                                                                       loaded active waiting   Forward Password Requests to Plymouth Direc>
  systemd-ask-password-wall.path                                                                           loaded active waiting   Forward Password Requests to Wall Directory>
  init.scope                                                                                               loaded active running   System and Service Manager
  session-4.scope                                                                                          loaded active running   Session 4 of User trainee
lines 1-37...skipping...
  UNIT                                                                                                     LOAD   ACTIVE SUB       DESCRIPTION                                                                  
  proc-sys-fs-binfmt_misc.automount                                                                        loaded active running   Arbitrary Executable File Formats File System Automount Point                
  sys-devices-pci0000:00-0000:00:01.1-ata2-host2-target2:0:0-2:0:0:0-block-sr0.device                      loaded active plugged   QEMU_DVD-ROM
  sys-devices-pci0000:00-0000:00:05.0-0000:01:01.0-virtio2-host0-target0:0:0-0:0:0:0-block-sda-sda1.device loaded active plugged   QEMU_HARDDISK 1
  sys-devices-pci0000:00-0000:00:05.0-0000:01:01.0-virtio2-host0-target0:0:0-0:0:0:0-block-sda-sda2.device loaded active plugged   QEMU_HARDDISK 2
  sys-devices-pci0000:00-0000:00:05.0-0000:01:01.0-virtio2-host0-target0:0:0-0:0:0:0-block-sda.device      loaded active plugged   QEMU_HARDDISK
  sys-devices-pci0000:00-0000:00:12.0-virtio1-net-ens18.device                                             loaded active plugged   Virtio network device
  sys-devices-platform-serial8250-tty-ttyS0.device                                                         loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS0
  sys-devices-platform-serial8250-tty-ttyS1.device                                                         loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS1
  sys-devices-platform-serial8250-tty-ttyS2.device                                                         loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS2
  sys-devices-platform-serial8250-tty-ttyS3.device                                                         loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS3
  sys-devices-virtual-block-dm\x2d0.device                                                                 loaded active plugged   /sys/devices/virtual/block/dm-0
  sys-devices-virtual-block-dm\x2d1.device                                                                 loaded active plugged   /sys/devices/virtual/block/dm-1
  sys-devices-virtual-misc-rfkill.device                                                                   loaded active plugged   /sys/devices/virtual/misc/rfkill
  sys-module-configfs.device                                                                               loaded active plugged   /sys/module/configfs
  sys-module-fuse.device                                                                                   loaded active plugged   /sys/module/fuse
  sys-subsystem-net-devices-ens18.device                                                                   loaded active plugged   Virtio network device                                                        
  -.mount                                                                                                  loaded active mounted   Root Mount
  boot.mount                                                                                               loaded active mounted   /boot
  dev-hugepages.mount                                                                                      loaded active mounted   Huge Pages File System
  dev-mqueue.mount                                                                                         loaded active mounted   POSIX Message Queue File System
  proc-sys-fs-binfmt_misc.mount                                                                            loaded active mounted   Arbitrary Executable File Formats File System
  run-credentials-systemd\x2dsysctl.service.mount                                                          loaded active mounted   /run/credentials/systemd-sysctl.service
  run-credentials-systemd\x2dtmpfiles\x2dsetup.service.mount                                               loaded active mounted   /run/credentials/systemd-tmpfiles-setup.service
  run-credentials-systemd\x2dtmpfiles\x2dsetup\x2ddev.service.mount                                        loaded active mounted   /run/credentials/systemd-tmpfiles-setup-dev.service
  run-user-1000.mount                                                                                      loaded active mounted   /run/user/1000
  run-user-42.mount                                                                                        loaded active mounted   /run/user/42
  sys-fs-fuse-connections.mount                                                                            loaded active mounted   FUSE Control File System
  sys-kernel-config.mount                                                                                  loaded active mounted   Kernel Configuration File System
  sys-kernel-debug-tracing.mount                                                                           loaded active mounted   /sys/kernel/debug/tracing
  sys-kernel-debug.mount                                                                                   loaded active mounted   Kernel Debug File System
  sys-kernel-tracing.mount                                                                                 loaded active mounted   Kernel Trace File System                                                     
  cups.path                                                                                                loaded active running   CUPS Scheduler
  systemd-ask-password-plymouth.path                                                                       loaded active waiting   Forward Password Requests to Plymouth Directory Watch
  systemd-ask-password-wall.path                                                                           loaded active waiting   Forward Password Requests to Wall Directory Watch                            
  init.scope                                                                                               loaded active running   System and Service Manager
  session-4.scope                                                                                          loaded active running   Session 4 of User trainee
  session-c1.scope                                                                                         loaded active running   Session c1 of User gdm                                                       
  accounts-daemon.service                                                                                  loaded active running   Accounts Service
  atd.service                                                                                              loaded active running   Deferred execution scheduler
  auditd.service                                                                                           loaded active running   Security Auditing Service
  avahi-daemon.service                                                                                     loaded active running   Avahi mDNS/DNS-SD Stack
  colord.service                                                                                           loaded active running   Manage, Install and Generate Color Profiles
  crond.service                                                                                            loaded active running   Command Scheduler
  cups.service                                                                                             loaded active running   CUPS Scheduler
  dbus-broker.service                                                                                      loaded active running   D-Bus System Message Bus
  dracut-shutdown.service                                                                                  loaded active exited    Restore /run/initramfs on shutdown
  firewalld.service                                                                                        loaded active running   firewalld - dynamic firewall daemon
  gdm.service                                                                                              loaded active running   GNOME Display Manager
  irqbalance.service                                                                                       loaded active running   irqbalance daemon
  iscsi.service                                                                                            loaded active exited    Login and scanning of iSCSI devices
  kdump.service                                                                                            loaded active exited    Crash recovery kernel arming
  kmod-static-nodes.service                                                                                loaded active exited    Create List of Static Device Nodes
  libstoragemgmt.service                                                                                   loaded active running   libstoragemgmt plug-in server daemon
  lvm2-monitor.service                                                                                     loaded active exited    Monitoring of LVM2 mirrors, snapshots etc. using dmeventd or progress polling
lines 1-55

Pour consulter la liste des Unités inactifs, utilisez la commande suivante :

[root@redhat9 ~]# systemctl list-units --all | grep inactive | more
● boot.automount                                                                                                 not-found inactive dead      boot.automount
● home.mount                                                                                                     not-found inactive dead      home.mount
● sysroot.mount                                                                                                  not-found inactive dead      sysroot.mount
  tmp.mount                                                                                                      loaded    inactive dead      Temporary Directory /tmp
● var.mount                                                                                                      not-found inactive dead      var.mount
  systemd-ask-password-console.path                                                                              loaded    inactive dead      Dispatch Password Requests to Console Directory Watch
  alsa-restore.service                                                                                           loaded    inactive dead      Save/Restore Sound Card State
  alsa-state.service                                                                                             loaded    inactive dead      Manage Sound Card State (restore and store)
● auto-cpufreq.service                                                                                           not-found inactive dead      auto-cpufreq.service
● autofs.service                                                                                                 not-found inactive dead      autofs.service
  blk-availability.service                                                                                       loaded    inactive dead      Availability of block devices
  cpupower.service                                                                                               loaded    inactive dead      Configure CPU power related settings
  dm-event.service                                                                                               loaded    inactive dead      Device-mapper event daemon
  dnf-makecache.service                                                                                          loaded    inactive dead      dnf makecache
  dracut-cmdline.service                                                                                         loaded    inactive dead      dracut cmdline hook
  dracut-initqueue.service                                                                                       loaded    inactive dead      dracut initqueue hook
  dracut-mount.service                                                                                           loaded    inactive dead      dracut mount hook
  dracut-pre-mount.service                                                                                       loaded    inactive dead      dracut pre-mount hook
  dracut-pre-pivot.service                                                                                       loaded    inactive dead      dracut pre-pivot and cleanup hook
  dracut-pre-trigger.service                                                                                     loaded    inactive dead      dracut pre-trigger hook
  dracut-pre-udev.service                                                                                        loaded    inactive dead      dracut pre-udev hook
  dracut-shutdown-onfailure.service                                                                              loaded    inactive dead      Service executing upon dracut-shutdown failure to perform cleanup
● ebtables.service                                                                                               not-found inactive dead      ebtables.service
  emergency.service                                                                                              loaded    inactive dead      Emergency Shell
● fcoe.service                                                                                                   not-found inactive dead      fcoe.service
  getty@tty1.service                                                                                             loaded    inactive dead      Getty on tty1
  initrd-cleanup.service                                                                                         loaded    inactive dead      Cleaning Up and Shutting Down Daemons
  initrd-parse-etc.service                                                                                       loaded    inactive dead      Mountpoints Configured in the Real Root
  initrd-switch-root.service                                                                                     loaded    inactive dead      Switch Root
  initrd-udevadm-cleanup-db.service                                                                              loaded    inactive dead      Cleanup udev Database
  insights-client-boot.service                                                                                   loaded    inactive dead      Run Insights Client at boot
● ip6tables.service                                                                                              not-found inactive dead      ip6tables.service
● ipset.service                                                                                                  not-found inactive dead      ipset.service
● iptables.service                                                                                               not-found inactive dead      iptables.service
  iscsi-init.service                                                                                             loaded    inactive dead      One time configuration for iscsi.service
  iscsi-onboot.service                                                                                           loaded    inactive dead      Special handling of early boot iSCSI sessions
  iscsi-shutdown.service                                                                                         loaded    inactive dead      Logout off all iSCSI sessions on shutdown
  iscsi-starter.service                                                                                          loaded    inactive dead      iscsi-starter.service
  iscsid.service                                                                                                 loaded    inactive dead      Open-iSCSI
  iscsiuio.service                                                                                               loaded    inactive dead      iSCSI UserSpace I/O driver
  ldconfig.service                                                                                               loaded    inactive dead      Rebuild Dynamic Linker Cache
  logrotate.service                                                                                              loaded    inactive dead      Rotate log files
  low-memory-monitor.service                                                                                     loaded    inactive dead      Low Memory Monitor
● lvm2-activation-early.service                                                                                  not-found inactive dead      lvm2-activation-early.service
  lvm2-lvmpolld.service                                                                                          loaded    inactive dead      LVM2 poll daemon
  mdmonitor.service                                                                                              loaded    inactive dead      Software RAID monitoring and management
  microcode.service                                                                                              loaded    inactive dead      Load CPU microcode update
  mlocate-updatedb.service                                                                                       loaded    inactive dead      Update a database for mlocate
  modprobe@configfs.service                                                                                      loaded    inactive dead      Load Kernel Module configfs
  modprobe@drm.service                                                                                           loaded    inactive dead      Load Kernel Module drm
  modprobe@fuse.service                                                                                          loaded    inactive dead      Load Kernel Module fuse
  multipathd.service                                                                                             loaded    inactive dead      Device-Mapper Multipath Device Controller
● network.service                                                                                                not-found inactive dead      network.service
  nftables.service                                                                                               loaded    inactive dead      Netfilter Tables
● nslcd.service                                                                                                  not-found inactive dead      nslcd.service
--More--
[q]

Les points noirs au début de certaines lignes dans la sortie ci-dessus sont en réalité des points blancs à l'écran. Ces points impliquent que le service, la cible ou l'unité spécifié n'a pas été trouvé sur le système. Par exemple :

[root@redhat9 ~]# systemctl status network
Unit network.service could not be found.

Pour consulter la liste des Unités ainsi que leurs statuts, utilisez la commande suivante :

[root@redhat9 ~]# systemctl list-unit-files | more
UNIT FILE                                  STATE           PRESET
proc-sys-fs-binfmt_misc.automount          static          -
-.mount                                    generated       -
boot.mount                                 generated       -
dev-hugepages.mount                        static          -
dev-mqueue.mount                           static          -
proc-sys-fs-binfmt_misc.mount              disabled        disabled
run-vmblock\x2dfuse.mount                  disabled        disabled
sys-fs-fuse-connections.mount              static          -
sys-kernel-config.mount                    static          -
sys-kernel-debug.mount                     static          -
sys-kernel-tracing.mount                   static          -
tmp.mount                                  disabled        disabled
cups.path                                  enabled         enabled
insights-client-results.path               disabled        disabled
ostree-finalize-staged.path                disabled        disabled
systemd-ask-password-console.path          static          -
systemd-ask-password-plymouth.path         static          -
systemd-ask-password-wall.path             static          -
session-4.scope                            transient       -
session-c1.scope                           transient       -
accounts-daemon.service                    enabled         enabled
alsa-restore.service                       static          -
alsa-state.service                         static          -
arp-ethers.service                         disabled        disabled
atd.service                                enabled         enabled
auditd.service                             enabled         enabled
autovt@.service                            alias           -
avahi-daemon.service                       enabled         enabled
blk-availability.service                   disabled        disabled
bluetooth.service                          enabled         enabled
bolt.service                               static          -
brltty.service                             disabled        disabled
canberra-system-bootup.service             disabled        disabled
canberra-system-shutdown-reboot.service    disabled        disabled
canberra-system-shutdown.service           disabled        disabled
chrony-wait.service                        disabled        disabled
chronyd-restricted.service                 disabled        disabled
chronyd.service                            disabled        enabled
cni-dhcp.service                           disabled        disabled
cockpit-motd.service                       static          -
cockpit-wsinstance-http.service            static          -
cockpit-wsinstance-https-factory@.service  static          -
cockpit-wsinstance-https@.service          static          -
cockpit.service                            static          -
colord.service                             static          -
configure-printer@.service                 static          -
console-getty.service                      disabled        disabled
container-getty@.service                   static          -
cpupower.service                           disabled        disabled
crond.service                              enabled         enabled
cups-browsed.service                       disabled        disabled
cups.service                               enabled         enabled
dbus-broker.service                        enabled         enabled
dbus-daemon.service                        disabled        disabled
--More--
[q]

Pour visualiser les Unités d'un type spécifique, il convient d'utiliser l'option -t :

[root@redhat9 ~]# systemctl list-unit-files -t mount
UNIT FILE                     STATE     PRESET  
-.mount                       generated -       
boot.mount                    generated -       
dev-hugepages.mount           static    -       
dev-mqueue.mount              static    -       
proc-sys-fs-binfmt_misc.mount disabled  disabled
run-vmblock\x2dfuse.mount     disabled  disabled
sys-fs-fuse-connections.mount static    -       
sys-kernel-config.mount       static    -       
sys-kernel-debug.mount        static    -       
sys-kernel-tracing.mount      static    -       
tmp.mount                     disabled  disabled

11 unit files listed.

Dans la colonne STATE on voit les mots static et generated.

[root@redhat9 ~]# ls -l /lib/systemd/system-generators/systemd-fstab-generator
-rwxr-xr-x. 1 root root 57696 Jul 18 13:01 /lib/systemd/system-generators/systemd-fstab-generator

Il existe aussi d'autres exécutables responsables de la génération d'autres fichiers :

[root@redhat9 ~]# ls -l /lib/systemd/system-generators
total 396
-rwxr-xr-x. 1 root root   541 Jul 24 06:08 kdump-dep-generator.sh
-rwxr-xr-x. 1 root root 15832 May 17 18:27 ostree-system-generator
lrwxrwxrwx. 1 root root    31 Aug  8 10:54 podman-system-generator -> ../../../libexec/podman/quadlet
-rwxr-xr-x. 1 root root  1005 Feb 19  2024 selinux-autorelabel-generator.sh
-rwxr-xr-x. 1 root root 15624 Jul 18 13:01 systemd-bless-boot-generator
-rwxr-xr-x. 1 root root 40920 Jul 18 13:01 systemd-cryptsetup-generator
-rwxr-xr-x. 1 root root 24312 Jul 18 13:01 systemd-debug-generator
-rwxr-xr-x. 1 root root 57696 Jul 18 13:01 systemd-fstab-generator
-rwxr-xr-x. 1 root root 24096 Jul 18 13:01 systemd-getty-generator
-rwxr-xr-x. 1 root root 36496 Jul 18 13:01 systemd-gpt-auto-generator
-rwxr-xr-x. 1 root root 16096 Jul 18 13:01 systemd-hibernate-resume-generator
-rwxr-xr-x. 1 root root 24240 Jul 18 13:01 systemd-integritysetup-generator
-rwxr-xr-x. 1 root root 15632 Jul 18 13:01 systemd-rc-local-generator
-rwxr-xr-x. 1 root root 24296 Jul 18 13:01 systemd-run-generator
-rwxr-xr-x. 1 root root 15824 Jul 18 13:01 systemd-system-update-generator
-rwxr-xr-x. 1 root root 36424 Jul 18 13:01 systemd-sysv-generator
-rwxr-xr-x. 1 root root 36872 Jul 18 13:01 systemd-veritysetup-generator

Les options de la commande systemctl sont :

[root@redhat9 ~]# systemctl --help
systemctl [OPTIONS...] COMMAND ...

Query or send control commands to the system manager.

Unit Commands:
  list-units [PATTERN...]             List units currently in memory
  list-automounts [PATTERN...]        List automount units currently in memory,
                                      ordered by path
  list-sockets [PATTERN...]           List socket units currently in memory,
                                      ordered by address
  list-timers [PATTERN...]            List timer units currently in memory,
                                      ordered by next elapse
  is-active PATTERN...                Check whether units are active
  is-failed PATTERN...                Check whether units are failed
  status [PATTERN...|PID...]          Show runtime status of one or more units
  show [PATTERN...|JOB...]            Show properties of one or more
                                      units/jobs or the manager
  cat PATTERN...                      Show files and drop-ins of specified units
  help PATTERN...|PID...              Show manual for one or more units
  list-dependencies [UNIT...]         Recursively show units which are required
                                      or wanted by the units or by which those
                                      units are required or wanted
  start UNIT...                       Start (activate) one or more units
  stop UNIT...                        Stop (deactivate) one or more units
  reload UNIT...                      Reload one or more units
  restart UNIT...                     Start or restart one or more units
  try-restart UNIT...                 Restart one or more units if active
  reload-or-restart UNIT...           Reload one or more units if possible,
                                      otherwise start or restart
  try-reload-or-restart UNIT...       If active, reload one or more units,
                                      if supported, otherwise restart
  isolate UNIT                        Start one unit and stop all others
  kill UNIT...                        Send signal to processes of a unit
  clean UNIT...                       Clean runtime, cache, state, logs or
                                      configuration of unit
  freeze PATTERN...                   Freeze execution of unit processes
  thaw PATTERN...                     Resume execution of a frozen unit
  set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit
  bind UNIT PATH [PATH]               Bind-mount a path from the host into a
                                      unit's namespace
  mount-image UNIT PATH [PATH [OPTS]] Mount an image from the host into a
                                      unit's namespace
  service-log-level SERVICE [LEVEL]   Get/set logging threshold for service
  service-log-target SERVICE [TARGET] Get/set logging target for service
  reset-failed [PATTERN...]           Reset failed state for all, one, or more
                                      units
Unit File Commands:
  list-unit-files [PATTERN...]        List installed unit files
  enable [UNIT...|PATH...]            Enable one or more unit files
  disable UNIT...                     Disable one or more unit files
  reenable UNIT...                    Reenable one or more unit files
  preset UNIT...                      Enable/disable one or more unit files
                                      based on preset configuration
  preset-all                          Enable/disable all unit files based on
                                      preset configuration
lines 1-55

LAB #2 - Fichiers de Configuration

2.1 - Fichiers de Configuration par Défaut

Les fichiers de configuration des Cibles et fichiers de configuration des Unités installés par des paquets se trouvent dans le répertoire /usr/lib/systemd/system :

[root@redhat9 ~]# pkg-config systemd --variable=systemdsystemunitdir
/usr/lib/systemd/system
[root@redhat9 ~]# ls -l /usr/lib/systemd/system | more
total 1584
-rw-r--r--. 1 root root  729 Feb 24  2022 accounts-daemon.service
-rw-r--r--. 1 root root  480 Jan 16  2024 alsa-restore.service
-rw-r--r--. 1 root root  465 Jan 16  2024 alsa-state.service
-rw-r--r--. 1 root root  275 Aug 10  2021 arp-ethers.service
-rw-r--r--. 1 root root  274 Apr  4  2022 atd.service
-rw-r--r--. 1 root root 1771 Nov  8  2023 auditd.service
lrwxrwxrwx. 1 root root   14 Jul 18 13:00 autovt@.service -> getty@.service
-rw-r--r--. 1 root root 1044 Nov  8  2023 avahi-daemon.service
-rw-r--r--. 1 root root  870 Nov  8  2023 avahi-daemon.socket
-rw-r--r--. 1 root root  964 Jul 18 13:00 basic.target
drwxr-xr-x. 2 root root    6 Jul 18 13:00 basic.target.wants
-r--r--r--. 1 root root  384 Feb  3  2024 blk-availability.service
-rw-r--r--. 1 root root  449 Oct 31  2022 blockdev@.target
-rw-r--r--. 1 root root  707 Jun 14  2022 bluetooth.service
-rw-r--r--. 1 root root  435 Oct 31  2022 bluetooth.target
-rw-r--r--. 1 root root  642 Jan 16  2023 bolt.service
-rw-r--r--. 1 root root  463 Oct 31  2022 boot-complete.target
-rw-r--r--. 1 root root  217 Aug  9  2021 brltty.service
-rw-r--r--. 1 root root  491 Jul 13  2023 canberra-system-bootup.service
-rw-r--r--. 1 root root  509 Jul 13  2023 canberra-system-shutdown-reboot.service
-rw-r--r--. 1 root root  466 Jul 13  2023 canberra-system-shutdown.service
-rw-r--r--. 1 root root 1811 Jan 23  2024 chronyd-restricted.service
-rw-r--r--. 1 root root 1468 Jan 23  2024 chronyd.service
-rw-r--r--. 1 root root 1082 Jan 23  2024 chrony-wait.service
-rw-r--r--. 1 root root  277 Jul 23 09:37 cni-dhcp.service
-rw-r--r--. 1 root root  302 Dec  4  2023 cni-dhcp.socket
-rw-r--r--. 1 root root  222 Apr  2 05:45 cockpit-motd.service
-rw-r--r--. 1 root root  720 Apr  2 05:45 cockpit.service
-rw-r--r--. 1 root root  349 Apr  2 05:45 cockpit.socket
-rw-r--r--. 1 root root  221 Apr  2 05:45 cockpit-wsinstance-http.service
-rw-r--r--. 1 root root  165 Apr  2 05:45 cockpit-wsinstance-https-factory@.service
-rw-r--r--. 1 root root  244 Apr  2 05:45 cockpit-wsinstance-https-factory.socket
-rw-r--r--. 1 root root  215 Apr  2 05:45 cockpit-wsinstance-http.socket
-rw-r--r--. 1 root root  264 Apr  2 05:45 cockpit-wsinstance-https@.service
-rw-r--r--. 1 root root  478 Apr  2 05:45 cockpit-wsinstance-https@.socket
-rw-r--r--. 1 root root  295 Aug  9  2021 colord.service
-rw-r--r--. 1 root root  154 Aug 11  2021 configure-printer@.service
-rw-r--r--. 1 root root 1102 Jul 18 13:00 console-getty.service
-rw-r--r--. 1 root root 1254 Jul 18 13:00 container-getty@.service
-rw-r--r--. 1 root root  294 Sep 13 18:49 cpupower.service
-rw-r--r--. 1 root root  371 Nov 30  2023 crond.service
-rw-r--r--. 1 root root  473 Oct 31  2022 cryptsetup-pre.target
-rw-r--r--. 1 root root  420 Oct 31  2022 cryptsetup.target
lrwxrwxrwx. 1 root root   13 Jul 18 13:00 ctrl-alt-del.target -> reboot.target
-rw-r--r--. 1 root root  234 Jan  7  2021 cups-browsed.service
-rw-r--r--. 1 root root  142 Jun 19 11:00 cups.path
-rw-r--r--. 1 root root  298 Jun 19 11:00 cups.service
drwxr-xr-x. 2 root root   25 Sep 25 12:03 cups.service.d
-rw-r--r--. 1 root root  148 Jun 19 11:00 cups.socket
-rw-r--r--. 1 root root  529 Aug 23  2022 dbus-broker.service
-rw-r--r--. 1 root root  560 Jun 12  2023 dbus-daemon.service
lrwxrwxrwx. 1 root root   25 Jul 18 13:00 dbus-org.freedesktop.hostname1.service -> systemd-hostnamed.service
lrwxrwxrwx. 1 root root   23 Jul 18 13:00 dbus-org.freedesktop.locale1.service -> systemd-localed.service
lrwxrwxrwx. 1 root root   22 Jul 18 13:00 dbus-org.freedesktop.login1.service -> systemd-logind.service
--More--
[q]

Certains fichiers de configuration sont créés à la volée dans le répertoire /run/systemd/system lors du runtime puis ils sont détruits quand le système n'en a plus besoin :

[root@redhat9 ~]# ls -l /run/systemd/system/
total 0

Les fichiers de configuration des Unités crées par les utilisateurs doivent être mis dans le répertoire /usr/lib/systemd/user :

[root@redhat9 ~]# pkg-config systemd --variable=systemduserunitdir
/usr/lib/systemd/user

Important : De cette façon les fichiers dans /usr/lib/systemd/user surchargent les fichiers dans le répertoire /run/systemd/system qui surchargent les fichiers dans le répertoire /usr/lib/systemd/system.

Prenons le cas du service sshd qui est configuré par le fichier /usr/lib/systemd/system/sshd.service :

[root@redhat9 ~]# cat /usr/lib/systemd/system/sshd.service
[Unit]
Description=OpenSSH server daemon
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target sshd-keygen.target
Wants=sshd-keygen.target

[Service]
Type=notify
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

Dans le fichier on peut noter la présence des lignes suivantes dans la section [Unit] :

Dans le fichier on peut aussi noter la présence des lignes suivantes dans la section [Service] :

Dernièrement on note la présence de la ligne suivante dans la section [Install] :

Pour consulter l'ensemble des directives de configuration ainsi que leurs valeurs d'une Unité, il convient d'utiliser la commande systemctl show en spécifiant l'Unité concernée :

[root@redhat9 ~]# systemctl show sshd
Type=notify
ExitType=main
Restart=on-failure
NotifyAccess=main
RestartUSec=42s
TimeoutStartUSec=1min 30s
TimeoutStopUSec=1min 30s
TimeoutAbortUSec=1min 30s
TimeoutStartFailureMode=terminate
TimeoutStopFailureMode=terminate
RuntimeMaxUSec=infinity
RuntimeRandomizedExtraUSec=0
WatchdogUSec=0
WatchdogTimestampMonotonic=0
RootDirectoryStartOnly=no
RemainAfterExit=no
GuessMainPID=yes
MainPID=875
ControlPID=0
FileDescriptorStoreMax=0
NFileDescriptorStore=0
StatusErrno=0
Result=success
ReloadResult=success
CleanResult=success
UID=[not set]
GID=[not set]
NRestarts=0
OOMPolicy=stop
ReloadSignal=1
ExecMainStartTimestamp=Wed 2024-09-25 12:44:53 CEST
ExecMainStartTimestampMonotonic=18089127
ExecMainExitTimestampMonotonic=0
ExecMainPID=875
ExecMainCode=0
ExecMainStatus=0
ExecStart={ path=/usr/sbin/sshd ; argv[]=/usr/sbin/sshd -D $OPTIONS ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }
ExecStartEx={ path=/usr/sbin/sshd ; argv[]=/usr/sbin/sshd -D $OPTIONS ; flags= ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }
ExecReload={ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }
ExecReloadEx={ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; flags= ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }
Slice=system.slice
ControlGroup=/system.slice/sshd.service
ControlGroupId=3690
MemoryCurrent=5275648
MemoryAvailable=infinity
CPUUsageNSec=122370000
TasksCurrent=1
IPIngressBytes=[no data]
IPIngressPackets=[no data]
IPEgressBytes=[no data]
IPEgressPackets=[no data]
IOReadBytes=18446744073709551615
IOReadOperations=18446744073709551615
IOWriteBytes=18446744073709551615
IOWriteOperations=18446744073709551615
lines 1-55

Pour consulter la liste des dépendances d'une Unité, il convient d'utiliser systemctl list-dependancies en spécifiant l'Unité concernée :

[root@redhat9 ~]# systemctl list-dependencies sshd.service
sshd.service
● ├─system.slice
● ├─sshd-keygen.target
○ │ ├─sshd-keygen@ecdsa.service
○ │ ├─sshd-keygen@ed25519.service
○ │ └─sshd-keygen@rsa.service
● └─sysinit.target
●   ├─dev-hugepages.mount
●   ├─dev-mqueue.mount
●   ├─dracut-shutdown.service
○   ├─iscsi-onboot.service
○   ├─iscsi-starter.service
●   ├─kmod-static-nodes.service
○   ├─ldconfig.service
●   ├─lvm2-lvmpolld.socket
●   ├─lvm2-monitor.service
○   ├─multipathd.service
●   ├─nis-domainname.service
●   ├─plymouth-read-write.service
●   ├─plymouth-start.service
●   ├─proc-sys-fs-binfmt_misc.automount
○   ├─selinux-autorelabel-mark.service
●   ├─sys-fs-fuse-connections.mount
●   ├─sys-kernel-config.mount
●   ├─sys-kernel-debug.mount
●   ├─sys-kernel-tracing.mount
○   ├─systemd-ask-password-console.path
○   ├─systemd-binfmt.service
○   ├─systemd-boot-random-seed.service
●   ├─systemd-boot-update.service
○   ├─systemd-firstboot.service
○   ├─systemd-hwdb-update.service
○   ├─systemd-journal-catalog-update.service
●   ├─systemd-journal-flush.service
●   ├─systemd-journald.service
○   ├─systemd-machine-id-commit.service
●   ├─systemd-modules-load.service
●   ├─systemd-network-generator.service
○   ├─systemd-pcrmachine.service
○   ├─systemd-pcrphase-sysinit.service
○   ├─systemd-pcrphase.service
●   ├─systemd-random-seed.service
○   ├─systemd-repart.service
●   ├─systemd-sysctl.service
○   ├─systemd-sysusers.service
●   ├─systemd-tmpfiles-setup-dev.service
●   ├─systemd-tmpfiles-setup.service
●   ├─systemd-udev-trigger.service
●   ├─systemd-udevd.service
○   ├─systemd-update-done.service
●   ├─systemd-update-utmp.service
●   ├─cryptsetup.target
●   ├─integritysetup.target
●   ├─local-fs.target
●   │ ├─-.mount
lines 1-55

2.2 - Surchargement des Fichiers de Configuration par Défaut

Les fichiers de configuration par défaut peuvent aussi être surchargés par des fichiers dans d'autres répertoires :

[root@redhat9 ~]# pkg-config systemd --variable=systemdsystemunitpath
/etc/systemd/system:/etc/systemd/system:/run/systemd/system:/usr/local/lib/systemd/system:/usr/lib/systemd/system:/usr/lib/systemd/system:/lib/systemd/system
[root@redhat9 ~]# ls -l /etc/systemd/system
total 8
drwxr-xr-x. 2 root root   65 Oct 19  2023  basic.target.wants
drwxr-xr-x. 2 root root   31 Oct 19  2023  bluetooth.target.wants
lrwxrwxrwx. 1 root root   37 Oct 19  2023  ctrl-alt-del.target -> /usr/lib/systemd/system/reboot.target
lrwxrwxrwx. 1 root root   41 Oct 19  2023  dbus-org.bluez.service -> /usr/lib/systemd/system/bluetooth.service
lrwxrwxrwx. 1 root root   41 Oct 19  2023  dbus-org.fedoraproject.FirewallD1.service -> /usr/lib/systemd/system/firewalld.service
lrwxrwxrwx. 1 root root   44 Oct 19  2023  dbus-org.freedesktop.Avahi.service -> /usr/lib/systemd/system/avahi-daemon.service
lrwxrwxrwx. 1 root root   44 Oct 19  2023  dbus-org.freedesktop.ModemManager1.service -> /usr/lib/systemd/system/ModemManager.service
lrwxrwxrwx. 1 root root   57 Oct 19  2023  dbus-org.freedesktop.nm-dispatcher.service -> /usr/lib/systemd/system/NetworkManager-dispatcher.service
lrwxrwxrwx. 1 root root   43 Oct 19  2023  dbus.service -> /usr/lib/systemd/system/dbus-broker.service
lrwxrwxrwx. 1 root root   40 Oct 19  2023  default.target -> /usr/lib/systemd/system/graphical.target
drwxr-xr-x. 2 root root   45 Oct 19  2023  default.target.wants
drwxr-xr-x. 2 root root   38 Oct 19  2023 'dev-virtio\x2dports-org.qemu.guest_agent.0.device.wants'
lrwxrwxrwx. 1 root root   35 Oct 19  2023  display-manager.service -> /usr/lib/systemd/system/gdm.service
drwxr-xr-x. 2 root root   32 Oct 19  2023  getty.target.wants
drwxr-xr-x. 2 root root  181 Oct 19  2023  graphical.target.wants
drwxr-xr-x. 2 root root   36 Oct 19  2023  local-fs.target.wants
drwxr-xr-x. 2 root root 4096 Oct 19  2023  multi-user.target.wants
drwxr-xr-x. 2 root root   48 Oct 19  2023  network-online.target.wants
drwxr-xr-x. 2 root root   26 Oct 19  2023  printer.target.wants
drwxr-xr-x. 2 root root   27 Oct 19  2023  remote-fs.target.wants
drwxr-xr-x. 2 root root  186 Oct 19  2023  sockets.target.wants
drwxr-xr-x. 2 root root 4096 Sep 25 12:08  sysinit.target.wants
drwxr-xr-x. 2 root root   86 Oct 19  2023  timers.target.wants
drwxr-xr-x. 2 root root   29 Oct 19  2023  vmtoolsd.service.requires

LAB #3 - La Commande systemd-analyze

Pour avoir une évaluation du temps de démarrage, il convient d'utiliser la commande suivante :

[root@redhat9 ~]# systemd-analyze
Startup finished in 1.309s (kernel) + 4.384s (initrd) + 29.375s (userspace) = 35.069s 
graphical.target reached after 29.358s in userspace.

L'option blame de la commande systemd-analyze permet de voir le temps de démarrage de chaque Unité afin de pourvoir se concentrer sur les plus lentes :

[root@redhat9 ~]# systemd-analyze blame
15.289s plymouth-quit-wait.service
 8.760s dev-disk-by\x2dpartuuid-d00dfc8a\x2d02.device
 8.760s dev-disk-by\x2did-scsi\x2d0QEMU_QEMU_HARDDISK_drive\x2dscsi0\x2dpart2.device
 8.760s sys-devices-pci0000:00-0000:00:05.0-0000:01:01.0-virtio2-host0-target0:0:0-0:0:0:0-block-sda-sda2.device
 8.760s dev-disk-by\x2dpath-pci\x2d0000:01:01.0\x2dscsi\x2d0:0:0:0\x2dpart2.device
 8.760s dev-sda2.device
 8.662s sys-devices-pci0000:00-0000:00:05.0-0000:01:01.0-virtio2-host0-target0:0:0-0:0:0:0-block-sda-sda1.device
 8.662s dev-disk-by\x2did-scsi\x2d0QEMU_QEMU_HARDDISK_drive\x2dscsi0\x2dpart1.device
 8.662s dev-sda1.device
 8.662s dev-disk-by\x2dpath-pci\x2d0000:01:01.0\x2dscsi\x2d0:0:0:0\x2dpart1.device
 8.662s dev-disk-by\x2duuid-6f6c5bb9\x2d30be\x2d4734\x2dbc23\x2d03fed8541616.device
 8.662s dev-disk-by\x2dpartuuid-d00dfc8a\x2d01.device
 8.629s dev-sda.device
 8.629s dev-disk-by\x2dpath-pci\x2d0000:01:01.0\x2dscsi\x2d0:0:0:0.device
 8.629s dev-disk-by\x2did-scsi\x2d0QEMU_QEMU_HARDDISK_drive\x2dscsi0.device
 8.629s sys-devices-pci0000:00-0000:00:05.0-0000:01:01.0-virtio2-host0-target0:0:0-0:0:0:0-block-sda.device
 8.629s dev-disk-by\x2ddiskseq-1.device
 8.589s sys-module-fuse.device
 8.578s sys-devices-pci0000:00-0000:00:12.0-virtio1-net-ens18.device
 8.578s sys-subsystem-net-devices-ens18.device
 8.560s sys-devices-platform-serial8250-tty-ttyS0.device
 8.560s dev-ttyS0.device
 8.559s sys-devices-platform-serial8250-tty-ttyS2.device
 8.559s dev-ttyS2.device
 8.558s dev-ttyS1.device
 8.558s sys-devices-platform-serial8250-tty-ttyS1.device
 8.557s dev-ttyS3.device
 8.557s sys-devices-platform-serial8250-tty-ttyS3.device
 8.510s sys-module-configfs.device
 4.024s initrd-switch-root.service
 2.468s firewalld.service
 2.157s kdump.service
 1.944s systemd-udev-settle.service
 1.548s dnf-makecache.service
 1.454s NetworkManager-wait-online.service
 1.309s udisks2.service
 1.294s NetworkManager.service
 1.112s power-profiles-daemon.service
 1.091s polkit.service
 1.015s accounts-daemon.service
  953ms ModemManager.service
  900ms user@42.service
  888ms dracut-initqueue.service
  671ms dbus-broker.service
  661ms systemd-tmpfiles-setup-dev.service
  658ms systemd-udevd.service
  561ms lvm2-monitor.service
  547ms boot.mount
  506ms cups.service
  464ms sshd.service
  446ms logrotate.service
  382ms systemd-random-seed.service
  376ms auditd.service
  371ms systemd-tmpfiles-setup.service
  324ms systemd-sysctl.service
lines 1-55

L'option critical-chain de la commande systemd-analyze permet de voir l'enchaînement des événements qui amènent au chargement de l'Unité qui est passée en argument :

[root@redhat9 ~]# systemd-analyze critical-chain sshd.service
The time when unit became active or started is printed after the "@" character.
The time the unit took to start is printed after the "+" character.

sshd.service +464ms
└─network.target @12.377s
  └─wpa_supplicant.service @25.556s +119ms
    └─basic.target @7.432s
      └─dbus-broker.service @6.758s +671ms
        └─dbus.socket @6.741s
          └─sysinit.target @6.737s
            └─systemd-update-utmp.service @6.721s +15ms
              └─auditd.service @6.333s +376ms
                └─systemd-tmpfiles-setup.service @5.951s +371ms
                  └─local-fs.target @5.939s
                    └─run-user-42.mount @14.616s
                      └─local-fs-pre.target @5.379s
                        └─systemd-tmpfiles-setup-dev.service @3.398s +661ms
                          └─kmod-static-nodes.service @3.243s +49ms
                            └─systemd-journald.socket
                              └─system.slice
                                └─-.slice

Les options de la commande systemd-analyze sont :

[root@redhat9 ~]# systemd-analyze --help
systemd-analyze [OPTIONS...] COMMAND ...

Profile systemd, show unit dependencies, check unit files.

Commands:
  [time]                     Print time required to boot the machine
  blame                      Print list of running units ordered by
                             time to init
  critical-chain [UNIT...]   Print a tree of the time critical chain
                             of units
  plot                       Output SVG graphic showing service
                             initialization
  dot [UNIT...]              Output dependency graph in dot(1) format
  dump [PATTERN...]          Output state serialization of service
                             manager
  cat-config                 Show configuration file and drop-ins
  unit-files                 List files and symlinks for units
  unit-paths                 List load directories for units
  exit-status [STATUS...]    List exit status definitions
  capability [CAP...]        List capability definitions
  syscall-filter [NAME...]   List syscalls in seccomp filters
  filesystems [NAME...]      List known filesystems
  condition CONDITION...     Evaluate conditions and asserts
  compare-versions VERSION1 [OP] VERSION2
                             Compare two version strings
  verify FILE...             Check unit files for correctness
  calendar SPEC...           Validate repetitive calendar time
                             events
  timestamp TIMESTAMP...     Validate a timestamp
  timespan SPAN...           Validate a time span
  security [UNIT...]         Analyze security of unit
  inspect-elf FILE...        Parse and print ELF package metadata

Options:
     --recursive-errors=MODE Control which units are verified
     --offline=BOOL          Perform a security review on unit file(s)
     --threshold=N           Exit with a non-zero status when overall
                             exposure level is over threshold value
     --security-policy=PATH  Use custom JSON security policy instead
                             of built-in one
     --json=pretty|short|off Generate JSON output of the security
                             analysis table, or plot's raw time data
     --no-pager              Do not pipe output into a pager
     --no-legend             Disable column headers and hints in plot
                             with either --table or --json=
     --system                Operate on system systemd instance
     --user                  Operate on user systemd instance
     --global                Operate on global user configuration
  -H --host=[USER@]HOST      Operate on remote host
  -M --machine=CONTAINER     Operate on local container
     --order                 Show only order in the graph
     --require               Show only requirement in the graph
     --from-pattern=GLOB     Show only origins in the graph
     --to-pattern=GLOB       Show only destinations in the graph
     --fuzz=SECONDS          Also print services which finished SECONDS
lines 1-55

LAB #4 - Les Cibles Systemd

Chaque Cible est décrite par un fichier de configuration :

[root@redhat9 ~]# cat /usr/lib/systemd/system/graphical.target
#  SPDX-License-Identifier: LGPL-2.1-or-later
#
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

[Unit]
Description=Graphical Interface
Documentation=man:systemd.special(7)
Requires=multi-user.target
Wants=display-manager.service
Conflicts=rescue.service rescue.target
After=multi-user.target rescue.service rescue.target display-manager.service
AllowIsolate=yes

Dans ce fichier on peut noter la présence des lignes suivantes :

4.1 - Contrôler les dépendances d'une Cible

Les dépendances d'une Cible peuvent être consultées en utilisant la commande systemctl list-dependencies :

[root@redhat9 ~]# systemctl list-dependencies multi-user.target
multi-user.target
● ├─atd.service
● ├─auditd.service
● ├─avahi-daemon.service
● ├─crond.service
● ├─cups.path
● ├─cups.service
● ├─firewalld.service
○ ├─insights-client-boot.service
● ├─irqbalance.service
● ├─kdump.service
● ├─libstoragemgmt.service
● ├─mcelog.service
○ ├─mdmonitor.service
● ├─ModemManager.service
● ├─NetworkManager.service
○ ├─ostree-readonly-sysroot-migration.service
● ├─plymouth-quit-wait.service
○ ├─plymouth-quit.service
● ├─rhsmcertd.service
● ├─rsyslog.service
○ ├─smartd.service
● ├─sshd.service
○ ├─sssd.service
● ├─systemd-ask-password-wall.path
● ├─systemd-logind.service
○ ├─systemd-update-utmp-runlevel.service
● ├─systemd-user-sessions.service
○ ├─tuned.service
○ ├─vmtoolsd.service
● ├─basic.target
● │ ├─-.mount
○ │ ├─low-memory-monitor.service
○ │ ├─microcode.service
● │ ├─paths.target
● │ ├─slices.target
● │ │ ├─-.slice
● │ │ └─system.slice
● │ ├─sockets.target
● │ │ ├─avahi-daemon.socket
● │ │ ├─cups.socket
● │ │ ├─dbus.socket
● │ │ ├─dm-event.socket
● │ │ ├─iscsid.socket
● │ │ ├─iscsiuio.socket
○ │ │ ├─multipathd.socket
● │ │ ├─sssd-kcm.socket
● │ │ ├─systemd-coredump.socket
● │ │ ├─systemd-initctl.socket
● │ │ ├─systemd-journald-dev-log.socket
● │ │ ├─systemd-journald.socket
● │ │ ├─systemd-udevd-control.socket
● │ │ └─systemd-udevd-kernel.socket
● │ ├─sysinit.target
● │ │ ├─dev-hugepages.mount
lines 1-55

Les points noirs au début de chaque ligne dans la sortie ci-dessus peuvent être de trois couleurs différentes :

Pour visualiser les Unités en état d'erreur fatale, utilisez la commande systemctl –failed :

[root@redhat9 ~]# systemctl --failed
  UNIT LOAD ACTIVE SUB DESCRIPTION
0 loaded units listed.

Les dépendances sont créés sous la forme de liens symboliques dans les répertoires /etc/systemd/system/multi-user.target.wants et /usr/lib/systemd/system/multi-user.target.wants :

[root@redhat9 ~]# ls -l /etc/systemd/system/multi-user.target.wants
total 0
lrwxrwxrwx. 1 root root 35 Oct 19  2023 atd.service -> /usr/lib/systemd/system/atd.service
lrwxrwxrwx. 1 root root 38 Oct 19  2023 auditd.service -> /usr/lib/systemd/system/auditd.service
lrwxrwxrwx. 1 root root 44 Oct 19  2023 avahi-daemon.service -> /usr/lib/systemd/system/avahi-daemon.service
lrwxrwxrwx. 1 root root 37 Oct 19  2023 crond.service -> /usr/lib/systemd/system/crond.service
lrwxrwxrwx. 1 root root 33 Oct 19  2023 cups.path -> /usr/lib/systemd/system/cups.path
lrwxrwxrwx. 1 root root 36 Oct 19  2023 cups.service -> /usr/lib/systemd/system/cups.service
lrwxrwxrwx. 1 root root 41 Oct 19  2023 firewalld.service -> /usr/lib/systemd/system/firewalld.service
lrwxrwxrwx. 1 root root 52 Oct 19  2023 insights-client-boot.service -> /usr/lib/systemd/system/insights-client-boot.service
lrwxrwxrwx. 1 root root 42 Oct 19  2023 irqbalance.service -> /usr/lib/systemd/system/irqbalance.service
lrwxrwxrwx. 1 root root 37 Oct 19  2023 kdump.service -> /usr/lib/systemd/system/kdump.service
lrwxrwxrwx. 1 root root 46 Oct 19  2023 libstoragemgmt.service -> /usr/lib/systemd/system/libstoragemgmt.service
lrwxrwxrwx. 1 root root 38 Oct 19  2023 mcelog.service -> /usr/lib/systemd/system/mcelog.service
lrwxrwxrwx. 1 root root 41 Oct 19  2023 mdmonitor.service -> /usr/lib/systemd/system/mdmonitor.service
lrwxrwxrwx. 1 root root 44 Oct 19  2023 ModemManager.service -> /usr/lib/systemd/system/ModemManager.service
lrwxrwxrwx. 1 root root 46 Oct 19  2023 NetworkManager.service -> /usr/lib/systemd/system/NetworkManager.service
lrwxrwxrwx. 1 root root 40 Oct 19  2023 remote-fs.target -> /usr/lib/systemd/system/remote-fs.target
lrwxrwxrwx. 1 root root 41 Oct 19  2023 rhsmcertd.service -> /usr/lib/systemd/system/rhsmcertd.service
lrwxrwxrwx. 1 root root 39 Oct 19  2023 rsyslog.service -> /usr/lib/systemd/system/rsyslog.service
lrwxrwxrwx. 1 root root 38 Oct 19  2023 smartd.service -> /usr/lib/systemd/system/smartd.service
lrwxrwxrwx. 1 root root 36 Oct 19  2023 sshd.service -> /usr/lib/systemd/system/sshd.service
lrwxrwxrwx. 1 root root 36 Oct 19  2023 sssd.service -> /usr/lib/systemd/system/sssd.service
lrwxrwxrwx. 1 root root 37 Oct 19  2023 tuned.service -> /usr/lib/systemd/system/tuned.service
lrwxrwxrwx. 1 root root 40 Oct 19  2023 vmtoolsd.service -> /usr/lib/systemd/system/vmtoolsd.service

[root@redhat9 ~]# ls -l /usr/lib/systemd/system/multi-user.target.wants
total 0
lrwxrwxrwx. 1 root root 15 Jul 18 13:00 getty.target -> ../getty.target
lrwxrwxrwx. 1 root root 44 May 17 18:27 ostree-readonly-sysroot-migration.service -> ../ostree-readonly-sysroot-migration.service
lrwxrwxrwx. 1 root root 24 Jul 14  2023 plymouth-quit.service -> ../plymouth-quit.service
lrwxrwxrwx. 1 root root 29 Jul 14  2023 plymouth-quit-wait.service -> ../plymouth-quit-wait.service
lrwxrwxrwx. 1 root root 33 Jul 18 13:00 systemd-ask-password-wall.path -> ../systemd-ask-password-wall.path
lrwxrwxrwx. 1 root root 25 Jul 18 13:00 systemd-logind.service -> ../systemd-logind.service
lrwxrwxrwx. 1 root root 39 Jul 18 13:00 systemd-update-utmp-runlevel.service -> ../systemd-update-utmp-runlevel.service
lrwxrwxrwx. 1 root root 32 Jul 18 13:00 systemd-user-sessions.service -> ../systemd-user-sessions.service

4.2 - La Cible par Défaut

Consulter la Cible par Défaut

Pour consulter la cible par défaut, il convient d'utiliser la commande systemctl get-default :

[root@redhat9 ~]# systemctl get-default
graphical.target

La Cible par défaut est représentée par le lien symbolique /etc/systemd/system/default.target :

[root@redhat9 ~]# ls -l /etc/systemd/system/default.target
lrwxrwxrwx. 1 root root 40 Oct 19  2023 /etc/systemd/system/default.target -> /usr/lib/systemd/system/graphical.target
Modifier la Cible par Défaut

Pour modifier la Cible par défaut avec une prise en compte lors du prochain démarrage, il convient d'utiliser la commande systemctl set-default :

[root@redhat9 ~]# systemctl set-default multi-user.target
Removed "/etc/systemd/system/default.target".
Created symlink /etc/systemd/system/default.target → /usr/lib/systemd/system/multi-user.target.

[root@redhat9 ~]# ls -l /etc/systemd/system/default.target
lrwxrwxrwx. 1 root root 41 Sep 26 14:50 /etc/systemd/system/default.target -> /usr/lib/systemd/system/multi-user.target

[root@redhat9 ~]# systemctl set-default graphical.target
Removed "/etc/systemd/system/default.target".
Created symlink /etc/systemd/system/default.target → /usr/lib/systemd/system/graphical.target.

[root@redhat9 ~]# ls -l /etc/systemd/system/default.target
lrwxrwxrwx. 1 root root 40 Sep 26 14:51 /etc/systemd/system/default.target -> /usr/lib/systemd/system/graphical.target
Modifier la Cible en Cours

Il est possible de modifier la cible actuellement en cours en utilisant la commande systemctl isolate :

[root@redhat9 ~]# systemctl isolate rescue

[root@redhat9 ~]# systemctl list-units --type target | egrep "eme|res|gra|mul" | head -1
  rescue.target         loaded active active Rescue Mode
            
[root@redhat9 ~]# runlevel
5 1

[root@redhat9 ~]# who -r
         run-level 1  2024-09-26 14:52                   last=5
[root@redhat9 ~]# systemctl isolate graphical

[root@redhat9 ~]# systemctl list-units --type target | egrep "eme|res|gra|mul" | head -1
  graphical.target       loaded active active Graphical Interface

[root@redhat9 ~]# runlevel
1 5

[root@redhat9 ~]# who -r
         run-level 5  2024-09-26 14:55                   last=1

LAB #5 - Gestion des Services

5.1 - Gestion des Instances Uniques

Commencez par installer le paquet httpd :

[root@redhat9 ~]# dnf install httpd
Updating Subscription Management repositories.
Last metadata expiration check: 1:59:56 ago on Thu 26 Sep 2024 12:57:02 PM CEST.
Dependencies resolved.
==================================================================================================================================================================================================================
 Package                                           Architecture                          Version                                            Repository                                                       Size
==================================================================================================================================================================================================================
Installing:
 httpd                                             x86_64                                2.4.57-11.el9_4.1                                  rhel-9-for-x86_64-appstream-rpms                                 51 k
Installing dependencies:
 apr                                               x86_64                                1.7.0-12.el9_3                                     rhel-9-for-x86_64-appstream-rpms                                126 k
 apr-util                                          x86_64                                1.6.1-23.el9                                       rhel-9-for-x86_64-appstream-rpms                                 97 k
 apr-util-bdb                                      x86_64                                1.6.1-23.el9                                       rhel-9-for-x86_64-appstream-rpms                                 14 k
 httpd-core                                        x86_64                                2.4.57-11.el9_4.1                                  rhel-9-for-x86_64-appstream-rpms                                1.5 M
 httpd-filesystem                                  noarch                                2.4.57-11.el9_4.1                                  rhel-9-for-x86_64-appstream-rpms                                 14 k
 httpd-tools                                       x86_64                                2.4.57-11.el9_4.1                                  rhel-9-for-x86_64-appstream-rpms                                 86 k
 redhat-logos-httpd                                noarch                                90.4-2.el9                                         rhel-9-for-x86_64-appstream-rpms                                 18 k
Installing weak dependencies:
 apr-util-openssl                                  x86_64                                1.6.1-23.el9                                       rhel-9-for-x86_64-appstream-rpms                                 17 k
 mod_http2                                         x86_64                                2.0.26-2.el9_4                                     rhel-9-for-x86_64-appstream-rpms                                167 k
 mod_lua                                           x86_64                                2.4.57-11.el9_4.1                                  rhel-9-for-x86_64-appstream-rpms                                 60 k

Transaction Summary
==================================================================================================================================================================================================================
Install  11 Packages

Total download size: 2.2 M
Installed size: 6.0 M
Is this ok [y/N]: y
Downloading Packages:
(1/11): apr-util-bdb-1.6.1-23.el9.x86_64.rpm                                                                                                                                       28 kB/s |  14 kB     00:00    
(2/11): apr-util-openssl-1.6.1-23.el9.x86_64.rpm                                                                                                                                   31 kB/s |  17 kB     00:00    
(3/11): apr-util-1.6.1-23.el9.x86_64.rpm                                                                                                                                          165 kB/s |  97 kB     00:00    
(4/11): redhat-logos-httpd-90.4-2.el9.noarch.rpm                                                                                                                                   69 kB/s |  18 kB     00:00    
(5/11): apr-1.7.0-12.el9_3.x86_64.rpm                                                                                                                                             374 kB/s | 126 kB     00:00    
(6/11): mod_http2-2.0.26-2.el9_4.x86_64.rpm                                                                                                                                       435 kB/s | 167 kB     00:00    
(7/11): httpd-core-2.4.57-11.el9_4.1.x86_64.rpm                                                                                                                                   2.9 MB/s | 1.5 MB     00:00    
(8/11): httpd-filesystem-2.4.57-11.el9_4.1.noarch.rpm                                                                                                                              31 kB/s |  14 kB     00:00    
(9/11): httpd-2.4.57-11.el9_4.1.x86_64.rpm                                                                                                                                         63 kB/s |  51 kB     00:00    
(10/11): httpd-tools-2.4.57-11.el9_4.1.x86_64.rpm                                                                                                                                 297 kB/s |  86 kB     00:00    
(11/11): mod_lua-2.4.57-11.el9_4.1.x86_64.rpm                                                                                                                                     154 kB/s |  60 kB     00:00    
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                             1.2 MB/s | 2.2 MB     00:01     
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                                                                                                          1/1 
  Installing       : apr-1.7.0-12.el9_3.x86_64                                                                                                                                                               1/11 
  Installing       : apr-util-bdb-1.6.1-23.el9.x86_64                                                                                                                                                        2/11 
  Installing       : apr-util-openssl-1.6.1-23.el9.x86_64                                                                                                                                                    3/11 
  Installing       : apr-util-1.6.1-23.el9.x86_64                                                                                                                                                            4/11 
  Installing       : httpd-tools-2.4.57-11.el9_4.1.x86_64                                                                                                                                                    5/11 
  Running scriptlet: httpd-filesystem-2.4.57-11.el9_4.1.noarch                                                                                                                                               6/11 
  Installing       : httpd-filesystem-2.4.57-11.el9_4.1.noarch                                                                                                                                               6/11 
  Installing       : httpd-core-2.4.57-11.el9_4.1.x86_64                                                                                                                                                     7/11 
  Installing       : mod_lua-2.4.57-11.el9_4.1.x86_64                                                                                                                                                        8/11 
  Installing       : redhat-logos-httpd-90.4-2.el9.noarch                                                                                                                                                    9/11 
  Installing       : mod_http2-2.0.26-2.el9_4.x86_64                                                                                                                                                        10/11 
  Installing       : httpd-2.4.57-11.el9_4.1.x86_64                                                                                                                                                         11/11 
  Running scriptlet: httpd-2.4.57-11.el9_4.1.x86_64                                                                                                                                                         11/11 
  Verifying        : apr-util-1.6.1-23.el9.x86_64                                                                                                                                                            1/11 
  Verifying        : apr-util-bdb-1.6.1-23.el9.x86_64                                                                                                                                                        2/11 
  Verifying        : apr-util-openssl-1.6.1-23.el9.x86_64                                                                                                                                                    3/11 
  Verifying        : redhat-logos-httpd-90.4-2.el9.noarch                                                                                                                                                    4/11 
  Verifying        : apr-1.7.0-12.el9_3.x86_64                                                                                                                                                               5/11 
  Verifying        : mod_http2-2.0.26-2.el9_4.x86_64                                                                                                                                                         6/11 
  Verifying        : httpd-2.4.57-11.el9_4.1.x86_64                                                                                                                                                          7/11 
  Verifying        : httpd-core-2.4.57-11.el9_4.1.x86_64                                                                                                                                                     8/11 
  Verifying        : httpd-filesystem-2.4.57-11.el9_4.1.noarch                                                                                                                                               9/11 
  Verifying        : httpd-tools-2.4.57-11.el9_4.1.x86_64                                                                                                                                                   10/11 
  Verifying        : mod_lua-2.4.57-11.el9_4.1.x86_64                                                                                                                                                       11/11 
Installed products updated.

Installed:
  apr-1.7.0-12.el9_3.x86_64                apr-util-1.6.1-23.el9.x86_64                  apr-util-bdb-1.6.1-23.el9.x86_64         apr-util-openssl-1.6.1-23.el9.x86_64     httpd-2.4.57-11.el9_4.1.x86_64      
  httpd-core-2.4.57-11.el9_4.1.x86_64      httpd-filesystem-2.4.57-11.el9_4.1.noarch     httpd-tools-2.4.57-11.el9_4.1.x86_64     mod_http2-2.0.26-2.el9_4.x86_64          mod_lua-2.4.57-11.el9_4.1.x86_64    
  redhat-logos-httpd-90.4-2.el9.noarch    

Complete!

Pour obtenir le détail sur un service donné, il convient d'utiliser la commande systemctl status :

[root@redhat9 ~]# systemctl status httpd.service
○ httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; preset: disabled)
     Active: inactive (dead)
       Docs: man:httpd.service(8)

Dans le cas du service httpd ci-dessus, on peut constater que le statut est disabled. Le statut peut être une de 2 valeurs :

Il est possible de vérifier le statut en utilisant le commande systemctl is-enabled :

[root@redhat9 ~]# systemctl is-enabled httpd.service
disabled

Pour rendre le statut enabled, il convient d'utiliser la commande systemctl enable :

[root@redhat9 ~]# systemctl enable httpd.service
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.

[root@redhat9 ~]# systemctl is-enabled httpd.service
enabled

[root@redhat9 ~]# systemctl status httpd.service
○ httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; preset: disabled)
     Active: inactive (dead)
       Docs: man:httpd.service(8)

Dans le cas du service httpd ci-dessus, on peut maintenant constater que l'état est inactive (dead). L'état peut être une de 7 valeurs :

Il est possible de vérifier l'état en utilisant le commande systemctl is-active :

[root@redhat9 ~]# systemctl is-active httpd.service
inactive

Pour rendre l'état active(running), utilisez la commande suivante :

[root@redhat9 ~]# systemctl start httpd.service

Vérifiez ensuite l'état du service :

[root@redhat9 ~]# systemctl is-active httpd.service
active

[root@redhat9 ~]# systemctl status httpd.service
● httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; preset: disabled)
     Active: active (running) since Thu 2024-09-26 15:01:28 CEST; 43s ago
       Docs: man:httpd.service(8)
   Main PID: 7187 (httpd)
     Status: "Total requests: 0; Idle/Busy workers 100/0;Requests/sec: 0; Bytes served/sec:   0 B/sec"
      Tasks: 177 (limit: 48800)
     Memory: 40.5M
        CPU: 128ms
     CGroup: /system.slice/httpd.service
             ├─7187 /usr/sbin/httpd -DFOREGROUND
             ├─7188 /usr/sbin/httpd -DFOREGROUND
             ├─7189 /usr/sbin/httpd -DFOREGROUND
             ├─7190 /usr/sbin/httpd -DFOREGROUND
             └─7191 /usr/sbin/httpd -DFOREGROUND

Sep 26 15:01:28 redhat9.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Sep 26 15:01:28 redhat9.ittraining.loc httpd[7187]: Server configured, listening on: port 80
Sep 26 15:01:28 redhat9.ittraining.loc systemd[1]: Started The Apache HTTP Server.

Pour arrêter une Unité de service, utilisez la commande suivante :

[root@redhat9 ~]# systemctl stop httpd.service

[root@redhat9 ~]# systemctl status httpd.service
○ httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; preset: disabled)
     Active: inactive (dead) since Thu 2024-09-26 15:02:55 CEST; 2s ago
   Duration: 1min 26.084s
       Docs: man:httpd.service(8)
    Process: 7187 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=0/SUCCESS)
   Main PID: 7187 (code=exited, status=0/SUCCESS)
     Status: "Total requests: 0; Idle/Busy workers 100/0;Requests/sec: 0; Bytes served/sec:   0 B/sec"
        CPU: 178ms

Sep 26 15:01:28 redhat9.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Sep 26 15:01:28 redhat9.ittraining.loc httpd[7187]: Server configured, listening on: port 80
Sep 26 15:01:28 redhat9.ittraining.loc systemd[1]: Started The Apache HTTP Server.
Sep 26 15:02:54 redhat9.ittraining.loc systemd[1]: Stopping The Apache HTTP Server...
Sep 26 15:02:55 redhat9.ittraining.loc systemd[1]: httpd.service: Deactivated successfully.
Sep 26 15:02:55 redhat9.ittraining.loc systemd[1]: Stopped The Apache HTTP Server.

Pour désactiver un service au prochain démarrage du système, utilisez l'option disable :

[root@redhat9 ~]# systemctl disable httpd.service
Removed "/etc/systemd/system/multi-user.target.wants/httpd.service".

[root@redhat9 ~]# systemctl status httpd.service
○ httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; preset: disabled)
     Active: inactive (dead)
       Docs: man:httpd.service(8)

Sep 26 15:01:28 redhat9.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Sep 26 15:01:28 redhat9.ittraining.loc httpd[7187]: Server configured, listening on: port 80
Sep 26 15:01:28 redhat9.ittraining.loc systemd[1]: Started The Apache HTTP Server.
Sep 26 15:02:54 redhat9.ittraining.loc systemd[1]: Stopping The Apache HTTP Server...
Sep 26 15:02:55 redhat9.ittraining.loc systemd[1]: httpd.service: Deactivated successfully.
Sep 26 15:02:55 redhat9.ittraining.loc systemd[1]: Stopped The Apache HTTP Server.

5.2 - Gestion d'Instances Multiples

Systemd permet l'utilisation des gabarits (templates) des fichiers de configuration des Unités. De cette façon il est possible de faire coexister deux ou plusieurs instances du même service. Un gabarit est reconnaissable par le caractère @ qui est placé juste avant le point dans le nom du fichier :

[root@redhat9 ~]# cat /usr/lib/systemd/system/httpd@.service
# This is a template for httpd instances.
# See httpd@.service(8) for more information.

[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd@.service(8)

[Service]
Type=notify
Environment=LANG=C
Environment=HTTPD_INSTANCE=%i
ExecStartPre=/bin/mkdir -m 710 -p /run/httpd/instance-%i
ExecStartPre=/bin/chown root.apache /run/httpd/instance-%i
ExecStartPre=/bin/mkdir -m 700 -p /var/lib/httpd/instance-%i
ExecStartPre=/bin/chown apache.apache /var/lib/httpd/instance-%i
ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND -f conf/%i.conf
ExecReload=/usr/sbin/httpd $OPTIONS -k graceful -f conf/%i.conf
# Send SIGWINCH for graceful stop
KillSignal=SIGWINCH
KillMode=mixed
PrivateTmp=true
OOMPolicy=continue

[Install]
WantedBy=multi-user.target

Une instance créée à partir de ce gabarit devrait avoir un nom sous la forme suivante :

httpd@<nom_instance>.service

Dans ce fichier on peut constater l'utilisation d'un identifier sous la forme de %i. Les identifiers sont de deux types - un dit échappé où les caractères non-ASCII alphanumérique sont remplacés par escapes de type langage C et l'autre non-échappé :

Créez maintenant deux copies du fichier /usr/lib/systemd/system/httpd@.service :

[root@redhat9 ~]# cp /usr/lib/systemd/system/httpd@.service /usr/lib/systemd/system/httpd@instance01.service

[root@redhat9 ~]# cp /usr/lib/systemd/system/httpd@.service /usr/lib/systemd/system/httpd@instance02.service

Créez deux copies du fichier /etc/httpd/conf/httpd.conf :

[root@redhat9 ~]# cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/instance01.conf

[root@redhat9 ~]# cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/instance02.conf

Editez la directive Listen du fichier /etc/httpd/conf/instance01.conf et ajoutez la directive PidFile :

[root@redhat9 ~]# vi /etc/httpd/conf/instance01.conf 

[root@redhat9 ~]# more /etc/httpd/conf/instance01.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see 
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# See the httpd.conf(5) man page for more information on this configuration,
# and httpd.service(8) on using and configuring the httpd service.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.  
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on a specific IP address, but note that if
# httpd.service is enabled to run at boot time, the address may not be
# available when the service starts.  See the httpd.service(8) man
# page for more information.
#
#Listen 12.34.56.78:80
Listen 8008
PidFile /var/run/httpd/instance01.pid
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
--More--(19%)
[q]

Editez la directive Listen du fichier /etc/httpd/conf/instance02.conf et ajoutez la directive PidFile :

[root@redhat9 ~]# vi /etc/httpd/conf/instance02.conf 

[root@redhat9 ~]# more /etc/httpd/conf/instance02.conf 
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see 
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# See the httpd.conf(5) man page for more information on this configuration,
# and httpd.service(8) on using and configuring the httpd service.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.  
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on a specific IP address, but note that if
# httpd.service is enabled to run at boot time, the address may not be
# available when the service starts.  See the httpd.service(8) man
# page for more information.
#
#Listen 12.34.56.78:80
Listen 8009
PidFile /var/run/httpd/instance02.pid

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
--More--(19%)
[q]

Démarrez les deux services :

[root@redhat9 ~]# systemctl start httpd@instance01.service

[root@redhat9 ~]# systemctl status httpd@instance01.service
● httpd@instance01.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd@instance01.service; disabled; preset: disabled)
     Active: active (running) since Thu 2024-09-26 15:14:25 CEST; 9s ago
       Docs: man:httpd@.service(8)
    Process: 7424 ExecStartPre=/bin/mkdir -m 710 -p /run/httpd/instance-instance01 (code=exited, status=0/SUCCESS)
    Process: 7425 ExecStartPre=/bin/chown root.apache /run/httpd/instance-instance01 (code=exited, status=0/SUCCESS)
    Process: 7426 ExecStartPre=/bin/mkdir -m 700 -p /var/lib/httpd/instance-instance01 (code=exited, status=0/SUCCESS)
    Process: 7427 ExecStartPre=/bin/chown apache.apache /var/lib/httpd/instance-instance01 (code=exited, status=0/SUCCESS)
   Main PID: 7429 (httpd)
     Status: "Total requests: 0; Idle/Busy workers 100/0;Requests/sec: 0; Bytes served/sec:   0 B/sec"
      Tasks: 177 (limit: 48800)
     Memory: 42.1M
        CPU: 122ms
     CGroup: /system.slice/system-httpd.slice/httpd@instance01.service
             ├─7429 /usr/sbin/httpd -DFOREGROUND -f conf/instance01.conf
             ├─7430 /usr/sbin/httpd -DFOREGROUND -f conf/instance01.conf
             ├─7431 /usr/sbin/httpd -DFOREGROUND -f conf/instance01.conf
             ├─7432 /usr/sbin/httpd -DFOREGROUND -f conf/instance01.conf
             └─7433 /usr/sbin/httpd -DFOREGROUND -f conf/instance01.conf

Sep 26 15:14:24 redhat9.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Sep 26 15:14:25 redhat9.ittraining.loc httpd[7429]: Server configured, listening on: port 8008
Sep 26 15:14:25 redhat9.ittraining.loc systemd[1]: Started The Apache HTTP Server.

[root@redhat9 ~]# systemctl start httpd@instance02.service

[root@redhat9 ~]# systemctl status httpd@instance02.service
● httpd@instance02.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd@instance02.service; disabled; preset: disabled)
     Active: active (running) since Thu 2024-09-26 15:14:43 CEST; 7s ago
       Docs: man:httpd@.service(8)
    Process: 7614 ExecStartPre=/bin/mkdir -m 710 -p /run/httpd/instance-instance02 (code=exited, status=0/SUCCESS)
    Process: 7615 ExecStartPre=/bin/chown root.apache /run/httpd/instance-instance02 (code=exited, status=0/SUCCESS)
    Process: 7616 ExecStartPre=/bin/mkdir -m 700 -p /var/lib/httpd/instance-instance02 (code=exited, status=0/SUCCESS)
    Process: 7617 ExecStartPre=/bin/chown apache.apache /var/lib/httpd/instance-instance02 (code=exited, status=0/SUCCESS)
   Main PID: 7618 (httpd)
     Status: "Started, listening on: port 8009"
      Tasks: 177 (limit: 48800)
     Memory: 42.1M
        CPU: 113ms
     CGroup: /system.slice/system-httpd.slice/httpd@instance02.service
             ├─7618 /usr/sbin/httpd -DFOREGROUND -f conf/instance02.conf
             ├─7619 /usr/sbin/httpd -DFOREGROUND -f conf/instance02.conf
             ├─7620 /usr/sbin/httpd -DFOREGROUND -f conf/instance02.conf
             ├─7621 /usr/sbin/httpd -DFOREGROUND -f conf/instance02.conf
             └─7622 /usr/sbin/httpd -DFOREGROUND -f conf/instance02.conf

Sep 26 15:14:43 redhat9.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Sep 26 15:14:43 redhat9.ittraining.loc httpd[7618]: Server configured, listening on: port 8009
Sep 26 15:14:43 redhat9.ittraining.loc systemd[1]: Started The Apache HTTP Server.

5.3 - Interdire la Modification du Statut d'un Service

Il est possible d'interdire la modification en utilisant la commande systemctl mask:

[root@redhat9 ~]# systemctl status httpd.service
○ httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; preset: disabled)
     Active: inactive (dead)
       Docs: man:httpd.service(8)

Sep 26 15:01:28 redhat9.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Sep 26 15:01:28 redhat9.ittraining.loc httpd[7187]: Server configured, listening on: port 80
Sep 26 15:01:28 redhat9.ittraining.loc systemd[1]: Started The Apache HTTP Server.
Sep 26 15:02:54 redhat9.ittraining.loc systemd[1]: Stopping The Apache HTTP Server...
Sep 26 15:02:55 redhat9.ittraining.loc systemd[1]: httpd.service: Deactivated successfully.
Sep 26 15:02:55 redhat9.ittraining.loc systemd[1]: Stopped The Apache HTTP Server.

[root@redhat9 ~]# systemctl mask httpd.service
Created symlink /etc/systemd/system/httpd.service → /dev/null.

[root@redhat9 ~]# systemctl enable httpd.service
Failed to enable unit: Unit file /etc/systemd/system/httpd.service is masked.

[root@redhat9 ~]# systemctl start httpd.service
Failed to start httpd.service: Unit httpd.service is masked.

Pour autoriser de nouveau les modifications, il convient d'utiliser la commande systemctl unmask :

[root@redhat9 ~]# systemctl unmask httpd.service
Removed "/etc/systemd/system/httpd.service".

[root@redhat9 ~]# systemctl enable httpd.service
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.

[root@redhat9 ~]# systemctl start httpd.service

[root@redhat9 ~]# systemctl status httpd.service
● httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; preset: disabled)
     Active: active (running) since Thu 2024-09-26 15:17:38 CEST; 18s ago
       Docs: man:httpd.service(8)
   Main PID: 7896 (httpd)
     Status: "Total requests: 0; Idle/Busy workers 100/0;Requests/sec: 0; Bytes served/sec:   0 B/sec"
      Tasks: 177 (limit: 48800)
     Memory: 40.1M
        CPU: 99ms
     CGroup: /system.slice/httpd.service
             ├─7896 /usr/sbin/httpd -DFOREGROUND
             ├─7897 /usr/sbin/httpd -DFOREGROUND
             ├─7898 /usr/sbin/httpd -DFOREGROUND
             ├─7899 /usr/sbin/httpd -DFOREGROUND
             └─7900 /usr/sbin/httpd -DFOREGROUND

Sep 26 15:17:38 redhat9.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Sep 26 15:17:38 redhat9.ittraining.loc httpd[7896]: Server configured, listening on: port 80
Sep 26 15:17:38 redhat9.ittraining.loc systemd[1]: Started The Apache HTTP Server.

Copyright © 2024 Hugh Norris.