Last active
March 12, 2018 05:29
-
-
Save zintrepid/9a1a9fc309b8e57a1cdfd1efdb71b2a1 to your computer and use it in GitHub Desktop.
Simple systemd upgrade proof-of-concept
This file contains 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/bash | |
# | |
# This script can be daemonized by systemd and shows how to do an in-place upgrade | |
# with service type=fork and pid files. If you watch systemctl status, you will see | |
# that the PID and command line of the service update after 20 seconds to reflect | |
# the script executed with 'type=upgraded-child'. After 5 minutes, the service will | |
# stop itself. | |
# | |
# upgrade-test.service: | |
# | |
# [Unit] | |
# Description=In-place upgrade test | |
# | |
# [Service] | |
# Type=forking | |
# PIDFile=/run/upgrade-test.pid | |
# ExecStart=/bin/bash /root/upgrade-test.sh --type=daemon --pid-file=/run/upgrade-test.pid | |
# | |
SELF="${BASH_SOURCE[0]}" | |
PARSED=$(getopt -o '' --longoptions="type:,pid-file:" --name "$0" -- "$@") | |
if (( $? != 0 )); then | |
echo "Failed to parse command line" | |
exit 2 | |
fi | |
eval set -- "$PARSED" | |
while true; do | |
case "$1" in | |
--type) | |
TYPE="$2" | |
shift 2 | |
;; | |
--pid-file) | |
PID_FILE="$2" | |
shift 2 | |
;; | |
--) | |
shift | |
break | |
;; | |
*) | |
echo "Unprocessed option: $1" | |
exit 3 | |
;; | |
esac | |
done | |
if [[ -z "$PID_FILE" ]]; then | |
echo "Missing required option: --pid-file" | |
exit 2 | |
fi | |
case "$TYPE" in | |
daemon) | |
# Systemd expects a forking process to, well, fork... | |
"$SELF" --type=child --pid-file="$PID_FILE" & | |
echo $! > "$PID_FILE" | |
disown | |
exit 0 | |
;; | |
child) | |
# Simulate process doing some work | |
sleep 10 | |
"$SELF" --type=upgraded-child --pid-file="$PID_FILE" & | |
CHILD_PID=$! | |
# Simulate process cleaning up resources | |
# You'll see during this time that systemd knows of both instances | |
# of the script, and still treats this instance as the main one. | |
sleep 10 | |
echo $CHILD_PID > "$PID_FILE" | |
disown | |
exit 0 | |
;; | |
upgraded-child) | |
sleep 300 | |
exit 0 | |
;; | |
*) | |
echo "Unrecognized type: $TYPE" | |
exit 2 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment