etc: Allow init.d/ashd to handle remaining connections more gracefully.
[ashd.git] / etc / debian / init.d-ashd
CommitLineData
9f61b28a
FT
1#!/bin/sh
2### BEGIN INIT INFO
3# Provides: ashd
4# Required-Start: $local_fs $remote_fs $network $syslog
5# Required-Stop: $local_fs $remote_fs $network $syslog
6# Default-Start: 2 3 4 5
7# Default-Stop: 0 1 6
8# Short-Description: The ashd HTTP server
9### END INIT INFO
10
11set -e
12
13. /lib/lsb/init-functions
14
15PATH=/usr/local/bin:/usr/local/sbin:$PATH
16HTPARSER="$(which htparser || true)"
17PIDFILE=/var/run/ashd.pid
4b7750b4
FT
18GRACE_PERIOD=10
19USER=nobody
20CHROOT=/var/tmp
9f61b28a 21PORTSPEC="plain"
c6b5fb27 22ROOTSPEC="dirplex /srv/www"
9f61b28a
FT
23[ -r /etc/default/locale ] && . /etc/default/locale
24[ -r /etc/default/ashd ] && . /etc/default/ashd
25[ -x "$HTPARSER" ] || exit 0
26
27start() {
28 export LANG
29 log_daemon_msg "Starting HTTP server" "ashd"
4b7750b4
FT
30 if start-stop-daemon -S -p "$PIDFILE" -qa "$HTPARSER" -- -Sf -p "$PIDFILE" -u "$USER" -r "$CHROOT" $PORTSPEC -- $ROOTSPEC; then
31 log_success_msg
32 else
33 log_end_msg $?
34 fi
9f61b28a
FT
35}
36
4b7750b4
FT
37kill_wholly() {
38 start-stop-daemon -K -p "$PIDFILE" -qx "$HTPARSER"
39}
40
41kill_listen() {
42 pid=$(cat "$PIDFILE" 2>/dev/null || true)
43 if [ -z "$pid" ]; then
44 log_failure_msg "no pid file"
45 return 1
46 fi
47 if ! kill -0 "$pid"; then
48 log_failure_msg "invalid saved pid"
49 return 1
50 fi
51 log_progress_msg "listen"
52 kill -TERM "$pid"
53 for try in 0 1 2 3 4 5; do
54 sleep $try
55 case "$(wc -l <"$PIDFILE")" in
56 1) continue ;;
57 0|2) return 0 ;;
58 *)
59 log_failure_msg "could not parse pid file"
60 return 1
61 ;;
62 esac
63 done
64 log_failure_msg "htparser did not stop listening, killing it completely"
65 kill_wholly
9f61b28a 66 start-stop-daemon -K -p "$PIDFILE" -qx "$HTPARSER"
4b7750b4
FT
67 return 1
68}
69
70stop_listen() {
71 log_daemon_msg "Stopping HTTP server" "ashd"
72 kill_listen
9f61b28a
FT
73 log_end_msg $?
74}
75
4b7750b4
FT
76stop_gracefully() {
77 log_daemon_msg "Stopping HTTP server" "ashd"
78 if ! kill_listen ; then
79 log_end_msg $?
80 return 1
81 fi
82 pid=$(cat "$PIDFILE" 2>/dev/null || true)
83 if kill -0 "$pid" 2>/dev/null; then
84 log_progress_msg "waiting for remaining connections..."
85 for try in $(seq "$GRACE_PERIOD"); do
86 sleep 1
87 if ! kill -0 "$pid" 2>/dev/null; then
88 log_success_msg
89 return 0
90 fi
91 done
92 else
93 log_success_msg
94 return 0
95 fi
96 log_progress_msg "terminating remaining connections"
97 if kill_wholly; then
98 log_success_msg
99 else
100 log_end_msg $?
101 fi
102}
103
9f61b28a
FT
104case "$1" in
105 start)
106 start
107 ;;
108 stop)
4b7750b4 109 stop_gracefully
9f61b28a
FT
110 ;;
111 restart)
4b7750b4
FT
112 stop_listen
113 # Truncate PID file to allow start-stop-daemon to work despite remaining connections.
114 >"$PIDFILE"
9f61b28a
FT
115 start
116 ;;
117esac
118
119exit 0