Create a gist now

Instantly share code, notes, and snippets.

Simple HTTP health-check by abusing systemd socket activation with shell scripts
$ ./status.sh 3>&2 3<&0
GET / HTTP/1.1
Host: foo.bar.com
HTTP/1.0 404 Not Found
Content-Type: text/html
Content-Length: 38
Date: Fri, 05 Dec 2014 17:06:53 +0000
Host: foo.bar.com
<html>
<body>
<h1>WUT</h1>
</html>
</body>
$ curl --dump-header - localhost:12345
HTTP/1.0 404 Not Found
Content-Type: text/html
Content-Length: 43
Date: Fri, 05 Dec 2014 17:48:56 +0000
<html>
<body>
<h1>WUT</h1>
</html>
</body>
$ sudo systemctl start someservice
$ curl --dump-header - localhost:12345
HTTP/1.0 200 OK
Content-Type: text/html
Content-Length: 43
Date: Fri, 05 Dec 2014 17:48:56 +0000
<html>
<body>
<h1>WUT</h1>
</html>
</body>
$
#!/bin/sh
# fd 3 is what systemd gave us
while true ; do
sed -e 's/\r$//' | IFS=":" read header line <&3
[ "$header" == "Host" ] && host="$header:$line"
[ -z "$header" ] && break
done
if /path/to/somecommand >/dev/null 2>&1; then
cat >&3 <<EOF
HTTP/1.0 200 OK
EOF
else
cat >&3 <<EOF
HTTP/1.0 404 Not Found
EOF
fi
cat >&3 <<EOF
Content-Type: text/html
Content-Length: 43
Date: $(date -R)
EOF
[ -n "$host" ] && echo $host | cat >&3
cat >&3 <<EOF
<html>
<body>
<h1>WUT</h1>
</html>
</body>
EOF
[Unit]
Description=Monitor Socket
[Socket]
ListenStream=12345
Backlog=1
MaxConnections=3
Accept=yes
[Install]
WantedBy=sockets.target
[Unit]
Description=monitor service
Requires=status.socket
After=syslog.target network.target
[Service]
Type=forking
ExecStart=/path/to/status.sh
[Install]
WantedBy=multi-user.target
Also=status.socket
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment