Last active
August 29, 2015 14:06
-
-
Save mostlygeek/3a6bb75ce3238bd1eaa8 to your computer and use it in GitHub Desktop.
setup-systemd-test-shutdown.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
rm /tmp/process-log-shutdown.txt | |
rm /tmp/last-shutdown.txt | |
cat > "//usr/local/bin/fake-daemon.sh" << 'EOF' | |
#!/bin/sh | |
OUTFILE=/tmp/process-log-shutdown.txt | |
SLEEP_PID= | |
MYPID=$$ | |
function logshutdown { | |
printf "$(date) PID: $MYPID: " >> $OUTFILE | |
for i in $(seq 1 5); do printf "$i " >> $OUTFILE; sleep 1; done | |
echo " ... done" >> $OUTFILE | |
} | |
trap "echo SIGHUP >> $OUTFILE; logshutdown" SIGHUP | |
trap "echo SIGTERM >> $OUTFILE; logshutdown; exit" SIGTERM | |
trap '[[ $SLEEP_PID ]] && kill $SLEEP_PID' EXIT | |
echo "MY PID: $MYPID" | |
while true; | |
do | |
echo "$(date) PID: $MYPID" | |
# when a SIGHUP or SIGINT comes in we don't want to wait | |
# for `sleep` to finish. So we use this and trap / kill SLEEP | |
# when we need to, ref: http://mywiki.wooledge.org/SignalTrap | |
sleep 10 & SLEEP_PID=$! | |
wait | |
SLEEP_PID= | |
done | |
EOF | |
cat > "/usr/local/bin/log-shutdown.sh" << 'EOF' | |
#!/bin/sh | |
/bin/date "+shutdown: %Y-%m-%d-%H:%M:%S" >> /tmp/last-shutdown.txt | |
for i in $(seq 1 5); do printf "$i " >> /tmp/last-shutdown.txt; sleep 1; done | |
printf "\n" >> /tmp/last-shutdown.txt | |
EOF | |
chmod +x /usr/local/bin/log-shutdown.sh | |
cat > "/usr/lib/systemd/system/test-shutdown.service" << EOF | |
[Unit] | |
Description=test systemd shutdown | |
After=syslog.target network-online.target | |
[Service] | |
Type=oneshot | |
RemainAfterExit=true | |
WorkingDirectory=/tmp | |
ExecStart=/bin/true | |
ExecStop=/usr/local/bin/log-shutdown.sh | |
[Install] | |
WantedBy=multi-user.target | |
EOF | |
cat > "/usr/lib/systemd/system/fake-daemon.service" << 'EOF' | |
[Unit] | |
Description=test systemd shutdown | |
After=syslog.target network-online.target | |
[Service] | |
Type=simple | |
WorkingDirectory=/tmp | |
ExecStart=/usr/local/bin/fake-daemon.sh | |
ExecStop=/usr/bin/sh -c "/bin/kill --signal SIGTERM $MAINPID; while ps -p $MAINPID > /dev/null; do sleep 1; done" | |
[Install] | |
WantedBy=multi-user.target | |
EOF | |
systemctl daemon-reload | |
systemctl enable test-shutdown.service | |
systemctl enable fake-daemon.service | |
systemctl restart test-shutdown.service | |
systemctl restart fake-daemon.service |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment