systemd: Riavviare un servizio al variare dello script avviato

Systemd path unit consentono di monitorare file e directory per diversi tipi di eventi. Una volta che l’evento si attiva, systemd può eseguire uno script tramite system unit.

Facciamo un esempio completo.

Vogliamo creare un servizio che avvii uno script python con uvicorn. Il servizio si chiamerà chatserv.

Per gestire solo il servizio, ci basterebbe creare un file chiamato /etc/systemd/system/chatserv.service con all’interno:

[Unit]
Description=Start uvicorn service fastapi
After=network.target

[Service]
Type=simple
User=web1
Group=web1
DynamicUser=true

WorkingDirectory=/var/www/web1/python/f24-online
PrivateTmp=true

ExecStart=/var/www/web1/python/bin/uvicorn --app-dir /var/www/web1/python/chatserv chatserv:app --host 127.0.0.1 --port 8000 --reload

ExecReload=/bin/kill -HUP ${MAINPID}
RestartPreventExitStatus = 255
RestartSec=1
Restart=always

[Install]
WantedBy=multi-user.target

Per abilitare il servizio ci basterà:

systemctl daemon-reload
systemctl enable chatserv.service
systemctl start chatserv.service

Se volessimo aggiungere un monitoraggio su eventuali cambiamenti all’interno della cartella /var/www/web1/python/chatserv dovremmo creare due file.

Il file del servizio di monitoraggio /etc/systemd/system/chatserv-watcher.service:

[Unit]
Description=chatserv.service restarter on script change
After=network.target
StartLimitIntervalSec=10
StartLimitBurst=5

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl restart chatserv.service
RestartSec=5s

[Install]
WantedBy=multi-user.target

dove StartLimitIntervalSec=10 e StartLimitBurst=5 indicano che non è consentito che il sistema si riavvii più di 5 volte in 10 secondi e RestartSec=5s indica che il riavvio avverrà dopo 5 secondi.

Infine il file del path unit service/etc/systemd/system/chatserv-watcher.path:

[Path]
Unit=chatserv-watcher.service
PathChanged=/var/www/web1/python/chatserv

[Install]
WantedBy=multi-user.target

Abilitiamo anche il servizio di monitoraggio:

systemctl enable chatserv-watcher.{path,service}
systemctl start chatserv-watcher.{path,service}

Fatto, possiamo ora provare a modificare lo script e poi controllare che il servizio venga riavviato con:

journalctl -r -u chatserv

enjoy!

Ti interessa acquistare un dominio a prezzi ultraconvenienti? clicca qui

Se hai trovato utili le informazioni su questo blog,
Fai una donazione!
Clicca sul bottone qui sotto o almeno clicca sul banner pubblicitario 🙂



Commenta