Skip to content
This repository was archived by the owner on Jun 30, 2021. It is now read-only.

Commit 49bf4fb

Browse files
committed
Kill all ssh tunnels gracefully at expose_ports.sh
1 parent da39980 commit 49bf4fb

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

host-scripts/expose_ports.sh

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,25 @@ die () {
1616
exit $errnum
1717
}
1818

19+
# ensures supervisord dies too
20+
shutdown () {
21+
echo "Trapped SIGTERM/SIGINT/SIGKILL so shutting down expose gracefully..."
22+
kill -SIGTERM $(jobs -p)
23+
exit 0
24+
}
25+
1926
# Required params
2027
[ -z "${1}" ] && die "Need at least 1 port number argument!"
2128
MYAPP_PORTS=$@
2229

2330
[ -z "${CONTAINER_IP}" ] && die "Need environment variable \$CONTAINER_IP set!"
2431
[ -z "${SSHD_PORT}" ] && die "Need environment variable \$SSHD_PORT set!"
2532
[ -z "${KNOWN_HOSTS_PATH}" ] && die "Need env var \$KNOWN_HOSTS_PATH set!"
26-
BASE_SSH_CMD="-p ${SSHD_PORT} -o StrictHostKeyChecking=no -N -fn application@${CONTAINER_IP}"
33+
# -f Requests ssh to go to background just before command execution
34+
# -n Redirects stdin from /dev/null (actually, prevents reading from stdin).
35+
# This must be used when ssh is run in the background
36+
# -N Do not execute a remote command. This is useful for just forwarding ports
37+
BASE_SSH_CMD="-p ${SSHD_PORT} -o StrictHostKeyChecking=no -N -n application@${CONTAINER_IP}"
2738

2839
## convert space separated string into a bash array
2940
IFS=' ' read -a MYAPP_PORTS <<< "${MYAPP_PORTS}"
@@ -32,7 +43,13 @@ declare -a MYAPP_PORTS=${MYAPP_PORTS}
3243
# to setup tunnels first kill existing tunnels if any
3344
# then set them up in the background
3445
for i in "${MYAPP_PORTS[@]}"; do
35-
kill $(lsof -i tcp:${i} -F p | cut -b 2-) >/dev/null 2>&1 || true
36-
ssh-keygen -f "${KNOWN_HOSTS_PATH}" -R [${CONTAINER_IP}]:${SSHD_PORT} >/dev/null 2>&1 || true
46+
(kill $(lsof -i tcp:${i} -F p | cut -b 2-) >/dev/null 2>&1) || true
47+
(ssh-keygen -f "${KNOWN_HOSTS_PATH}" -R [${CONTAINER_IP}]:${SSHD_PORT} >/dev/null 2>&1) || true
3748
ssh ${BASE_SSH_CMD} -R localhost:${i}:localhost:${i} &
3849
done
50+
51+
# Run function shutdown() when this process a killer signal
52+
trap shutdown SIGTERM SIGINT SIGKILL
53+
54+
# tells bash to wait until child processes have exited
55+
wait

0 commit comments

Comments
 (0)