change wait-for-multiply.sh

This commit is contained in:
2026-03-27 16:56:26 +06:00
parent eec582c66b
commit cf80aade19

View File

@@ -1,49 +1,62 @@
#!/bin/sh #!/usr/bin/env bash
# wait-for-multiple.sh (POSIX / sh version) # wait-for-multiply.sh
# Wait for multiple TCP hosts/ports in parallel before executing a command
set -e set -e
HOSTS="" WAIT_FOR_SCRIPT="/usr/local/bin/wait-for.sh"
CMD=""
while [ $# -gt 0 ]; do HOSTS=()
case "$1" in CMD=()
--)
shift # Parse arguments: everything until -- is host:port, rest is command
CMD="$*" while [[ $# -gt 0 ]]; do
break case "$1" in
;; --)
*) shift
HOSTS="$HOSTS $1" CMD=("$@")
shift break
;; ;;
esac *)
HOSTS+=("$1")
shift
;;
esac
done done
if [ -z "$HOSTS" ]; then if [[ ${#HOSTS[@]} -eq 0 ]]; then
echo "Usage: $0 host1:port1 host2:port2 ... -- command args" echo "Error: specify at least one host:port"
exit 1 exit 1
fi fi
wait_host() { if [[ ${#CMD[@]} -eq 0 ]]; then
hostport="$1" echo "Error: specify command to run after hosts are ready"
/usr/bin/wait-for-it.sh "$hostport" --timeout=30 --strict exit 1
fi
# Function to wait for a single host
wait_one() {
local hostport=$1
"$WAIT_FOR_SCRIPT" "$hostport" --strict
} }
PIDS="" # Start all waits in parallel
for h in $HOSTS; do PIDS=()
wait_host "$h" & for HOSTPORT in "${HOSTS[@]}"; do
PIDS="$PIDS $!" wait_one "$HOSTPORT" &
PIDS+=($!)
done done
FAIL=0 # Wait for all to finish and check exit codes
for pid in $PIDS; do EXIT_CODE=0
wait $pid || FAIL=1 for PID in "${PIDS[@]}"; do
wait $PID || EXIT_CODE=$?
done done
if [ $FAIL -ne 0 ]; then if [[ $EXIT_CODE -ne 0 ]]; then
echo "One or more hosts failed to become available" echo "Error: One or more services failed to become available"
exit 1 exit $EXIT_CODE
fi fi
exec $CMD # Execute the final command
exec "${CMD[@]}"