|
1 | 1 | #!/bin/sh |
2 | 2 |
|
| 3 | +OLD_TIMEOUT=$TIMEOUT |
| 4 | +OLD_QUIET=$QUIET |
| 5 | +OLD_PORT=$PORT |
| 6 | +OLD_HOST=$HOST |
| 7 | +OLD_LOOSE=$LOOSE |
| 8 | + |
3 | 9 | TIMEOUT=15 |
4 | 10 | QUIET=0 |
| 11 | +LOOSE=0 |
| 12 | + |
| 13 | +if ! which nc >/dev/null; then |
| 14 | + echo "Netcat is not installed. This script requires netcat to work correctly." |
| 15 | + exit 1 |
| 16 | +fi |
5 | 17 |
|
6 | 18 | echoerr() { |
7 | 19 | if [ "$QUIET" -ne 1 ]; then printf "%s\n" "$*" 1>&2; fi |
8 | 20 | } |
9 | 21 |
|
| 22 | +conditionally_output() { |
| 23 | + if [ "$QUIET" -ne 1 ]; then |
| 24 | + "$@" |
| 25 | + else |
| 26 | + "$@" > /dev/null 2>&1 |
| 27 | + fi |
| 28 | +} |
| 29 | + |
10 | 30 | usage() { |
11 | 31 | exitcode="$1" |
12 | 32 | cat << USAGE >&2 |
13 | 33 | Usage: |
14 | | - $cmdname host:port [-t timeout] [-- command args] |
| 34 | + $(basename $0) host:port [-t timeout] [-- command args] |
15 | 35 | -q | --quiet Do not output any status messages |
| 36 | + -l | --loose Execute subcommand even if the test times out |
16 | 37 | -t TIMEOUT | --timeout=timeout Timeout in seconds, zero for no timeout |
17 | 38 | -- COMMAND ARGS Execute command with args after the test finishes |
18 | 39 | USAGE |
19 | 40 | exit "$exitcode" |
20 | 41 | } |
21 | 42 |
|
| 43 | +test_connection() { |
| 44 | + conditionally_output echo "Testing connection to $1:$2..." |
| 45 | + |
| 46 | + # force a 1-second timeout on darwin (https://stackoverflow.com/a/20460402/2063546) |
| 47 | + # POSIX-compliant string inclusion test https://stackoverflow.com/a/8811800/2063546 |
| 48 | + if [ "${OSTYPE#*darwin*}" != "$OSTYPE" ] ; then |
| 49 | + conditionally_output nc -z -w 1 -G 1 "$1" "$2" |
| 50 | + else |
| 51 | + conditionally_output nc -z -w 1 "$1" "$2" |
| 52 | + fi |
| 53 | +} |
| 54 | + |
22 | 55 | wait_for() { |
| 56 | + local result |
23 | 57 | for i in `seq $TIMEOUT` ; do |
24 | | - nc -z "$HOST" "$PORT" > /dev/null 2>&1 |
25 | | - |
| 58 | + # use a 1-second timeout, but still sleep 0.1 seconds after just to be safe |
| 59 | + test_connection "$HOST" "$PORT" |
26 | 60 | result=$? |
27 | | - if [ $result -eq 0 ] ; then |
28 | | - if [ $# -gt 0 ] ; then |
29 | | - exec "$@" |
30 | | - fi |
31 | | - exit 0 |
32 | | - fi |
| 61 | + if [ $result -eq 0 ] ; then break ; fi |
33 | 62 | sleep 1 |
34 | 63 | done |
35 | | - echo "Operation timed out" >&2 |
36 | | - exit 1 |
| 64 | + [ $result -ne 0 ] && echoerr "Operation timed out" |
| 65 | + if [ $result -eq 0 -o $LOOSE -eq 1 -a $# -gt 0 ] ; then |
| 66 | + TIMEOUT=$OLD_TIMEOUT QUIET=$OLD_QUIET PORT=$OLD_PORT HOST=$OLD_HOST LOOSE=$OLD_LOOSE exec "$@" |
| 67 | + fi |
| 68 | + exit $result |
37 | 69 | } |
38 | 70 |
|
39 | 71 | while [ $# -gt 0 ] |
|
48 | 80 | QUIET=1 |
49 | 81 | shift 1 |
50 | 82 | ;; |
| 83 | + -l | --loose) |
| 84 | + LOOSE=1 |
| 85 | + shift 1 |
| 86 | + ;; |
51 | 87 | -t) |
52 | 88 | TIMEOUT="$2" |
53 | 89 | if [ "$TIMEOUT" = "" ]; then break; fi |
|
0 commit comments