2016-09-16 10:11:08 +02:00
#!/bin/bash
2018-11-14 11:40:26 +01:00
# Create and start a persistent systemd unit that survives reboots. Use as:
2020-11-06 09:30:35 -03:00
# systemd_create_and_start_unit "name" "my-service --args"
2018-11-14 11:40:26 +01:00
# The third arg supports "overrides" which allow to customize the service
# as needed, e.g.:
2020-11-06 09:30:35 -03:00
# systemd_create_and_start_unit "name" "start" "[Unit]\nAfter=foo"
systemd_create_and_start_unit( ) {
2018-11-19 12:18:12 +01:00
printf '[Unit]\nDescription=Support for test %s\n[Service]\nType=simple\nExecStart=%s\n[Install]\nWantedBy=multi-user.target\n' " ${ SPREAD_JOB :- unknown } " " $2 " > " /etc/systemd/system/ $1 .service "
2018-11-14 11:40:26 +01:00
if [ -n " ${ 3 :- } " ] ; then
mkdir -p " /etc/systemd/system/ $1 .service.d "
2018-11-16 12:49:07 +01:00
# shellcheck disable=SC2059
printf " $3 " >> " /etc/systemd/system/ $1 .service.d/override.conf "
2018-11-14 11:40:26 +01:00
fi
systemctl daemon-reload
systemctl enable " $1 "
systemctl start " $1 "
2023-03-13 07:32:57 -03:00
wait_for_service " $1 " active 30
2018-11-14 11:40:26 +01:00
}
2020-11-06 09:30:35 -03:00
systemd_stop_and_remove_unit( ) {
2018-11-14 11:40:26 +01:00
systemctl stop " $1 " || true
systemctl disable " $1 " || true
rm -f " /etc/systemd/system/ $1 .service "
rm -rf " /etc/systemd/system/ $1 .service.d "
2016-09-16 10:11:08 +02:00
systemctl daemon-reload
}
2017-08-29 17:51:23 +02:00
wait_for_service( ) {
local service_name = " $1 "
local state = " ${ 2 :- active } "
2023-03-13 07:32:57 -03:00
local attempts = " ${ 3 :- 60 } "
for i in $( seq " $attempts " ) ; do
2017-08-30 14:54:45 +02:00
if systemctl show -p ActiveState " $service_name " | grep -q " ActiveState= $state " ; then
return
fi
# show debug output every 1min
2019-08-21 12:23:50 +02:00
if [ " $i " -gt 0 ] && [ $(( i % 60 )) = 0 ] ; then
2017-08-30 14:54:45 +02:00
systemctl status " $service_name " || true;
fi
sleep 1;
2017-08-29 17:51:23 +02:00
done
2017-08-30 14:54:45 +02:00
echo " service $service_name did not start "
exit 1
2017-08-29 17:51:23 +02:00
}
2018-03-15 17:16:03 -03:00
systemd_stop_units( ) {
for unit in " $@ " ; do
if systemctl is-active " $unit " ; then
echo "Ensure the service is active before stopping it"
retries = 20
2019-08-21 11:36:16 +02:00
while systemctl status " $unit " | grep -q "Active: activating" ; do
2018-03-15 17:16:03 -03:00
if [ $retries -eq 0 ] ; then
echo " $unit unit not active "
2019-08-21 11:36:16 +02:00
systemctl status " $unit " || true
2018-03-15 17:16:03 -03:00
exit 1
fi
2018-04-24 12:48:08 +02:00
retries = $(( retries - 1 ))
2018-03-15 17:16:03 -03:00
sleep 1
done
systemctl stop " $unit "
fi
done
}