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