|
| 1 | +#!/bin/sh |
| 2 | +# shellcheck shell=dash |
| 3 | + |
| 4 | +# |
| 5 | +# Waits for the given host(s) to be available via TCP before executing a given |
| 6 | +# command. |
| 7 | +# |
| 8 | +# Usage: ./wait.sh [-t timeout] host:port [host:port] [...] [-- command args...] |
| 9 | +# |
| 10 | +# It accepts a number of `host:port` combinations to connect to via netcat. |
| 11 | +# The command to execute after each host is reachable can be supplied after the |
| 12 | +# `--` argument. |
| 13 | +# The default timeout of 10 seconds can be changed via `-t timeout` argument. |
| 14 | +# |
| 15 | +# Copyright 2016, Sebastian Tschan |
| 16 | +# https://blueimp.net |
| 17 | +# |
| 18 | +# Licensed under the MIT license: |
| 19 | +# https://opensource.org/licenses/MIT |
| 20 | +# |
| 21 | + |
| 22 | +set -e |
| 23 | + |
| 24 | +TIMEOUT=10 |
| 25 | + |
| 26 | +is_integer() { |
| 27 | + test "1ドル" -eq "1ドル" 2> /dev/null |
| 28 | +} |
| 29 | + |
| 30 | +connect_to_service() { |
| 31 | + nc -w 1 -z "1ドル" "2ドル" |
| 32 | +} |
| 33 | + |
| 34 | +wait_for_service() { |
| 35 | + local host="${1%:*}" |
| 36 | + local port="${1#*:}" |
| 37 | + local output |
| 38 | + if ! is_integer "$port"; then |
| 39 | + printf 'Error: "%s" is not a valid host:port combination.\n' "1ドル" >&2 |
| 40 | + return 1 |
| 41 | + fi |
| 42 | + printf 'Waiting for %s to become available ... ' "1ドル" >&2 |
| 43 | + # shellcheck disable=SC2155 |
| 44 | + local timeout=$(($(date +%s)+TIMEOUT)) |
| 45 | + while ! output="$(connect_to_service "$host" "$port" 2>&1)"; do |
| 46 | + if [ "$(date +%s)" -gt "$timeout" ]; then |
| 47 | + echo 'timeout' >&2 |
| 48 | + if [ ! -z "$output" ]; then |
| 49 | + echo "$output" >&2 |
| 50 | + fi |
| 51 | + return 1 |
| 52 | + fi |
| 53 | + sleep 1 |
| 54 | + done |
| 55 | + echo 'done' >&2 |
| 56 | +} |
| 57 | + |
| 58 | +while [ $# != 0 ]; do |
| 59 | + if [ "1ドル" = '-t' ] || [ "1ドル" = '--timeout' ]; then |
| 60 | + if ! is_integer "2ドル"; then |
| 61 | + printf 'Error: "%s" is not a timeout integer.\n' "2ドル" >&2 |
| 62 | + exit 1 |
| 63 | + fi |
| 64 | + TIMEOUT="2ドル" |
| 65 | + shift 2 |
| 66 | + fi |
| 67 | + if [ "1ドル" = '--' ]; then |
| 68 | + shift |
| 69 | + exec "$@" |
| 70 | + fi |
| 71 | + wait_for_service "1ドル" |
| 72 | + shift |
| 73 | +done |
0 commit comments