2022-11-04 13:01:36 +01:00
|
|
|
#!/usr/bin/env sh
|
|
|
|
# Configurable Variables
|
2022-11-11 15:39:33 +01:00
|
|
|
[ -z $DOCKER_SOCK_PATH ] && DOCKER_SOCK_PATH="/tmp/docker.sock"
|
|
|
|
[ -z $NETWORK_NAME ] && NETWORK_NAME="proxy"
|
|
|
|
[ -z $RESOLVE_DOCKERHOST ] && RESOLVE_DOCKERHOST=false
|
|
|
|
[ -z $HOST_CONF_PATH ] && HOST_CONF_PATH="/tmp/hosts"
|
|
|
|
[ -z $DOCKER_HOSTNAME_VAR ] && DOCKER_HOSTNAME_VAR="VIRTUAL_HOST"
|
2022-11-04 13:01:36 +01:00
|
|
|
|
|
|
|
query_docker () {
|
2022-11-17 14:51:49 +01:00
|
|
|
curl --unix-socket $DOCKER_SOCK_PATH --silent -g http://v1.41/$1$2
|
2022-11-04 13:01:36 +01:00
|
|
|
}
|
|
|
|
|
2022-11-11 15:39:33 +01:00
|
|
|
get_host_list() {
|
2022-11-04 13:01:36 +01:00
|
|
|
PROXY_HOST_CONF=""
|
2022-11-17 14:51:49 +01:00
|
|
|
CONTAINER_LIST=$(query_docker "containers/json" "?filters={%22network%22:[%22${NETWORK_NAME}%22],%22status%22:[%22running%22]}" | jq -cr '.[].Id')
|
2022-11-04 13:01:36 +01:00
|
|
|
|
|
|
|
for id in $CONTAINER_LIST
|
|
|
|
do
|
2022-11-11 15:39:33 +01:00
|
|
|
# Query individual container to access relevant data
|
2022-11-17 14:51:49 +01:00
|
|
|
CONTAINER_DATA=$(query_docker "containers/${id}/json")
|
2022-11-18 09:45:24 +01:00
|
|
|
if $RESOLVE_DOCKERHOST
|
2022-11-11 15:39:33 +01:00
|
|
|
then
|
|
|
|
HOST_IP=$(echo $CONTAINER_DATA | jq -cr '.NetworkSettings.Networks.proxy.IPAddress')
|
|
|
|
else
|
|
|
|
HOST_IP="127.0.0.1"
|
|
|
|
fi
|
2022-11-04 13:01:36 +01:00
|
|
|
# Filter Env for HOSTNAME, remove list parenthesis and split/only keep values
|
2022-11-11 15:39:33 +01:00
|
|
|
HOST_NAMES=$(echo $CONTAINER_DATA | jq -cr ".Config.Env[] | select(contains(\"$DOCKER_HOSTNAME_VAR=\")) | split(\"=\")[1]")
|
2022-11-04 13:01:36 +01:00
|
|
|
|
|
|
|
for hostname in $HOST_NAMES
|
|
|
|
do
|
2022-11-11 15:39:33 +01:00
|
|
|
PROXY_HOST_CONF="$PROXY_HOST_CONF\n$HOST_IP $hostname # Added by hostman"
|
2022-11-04 13:01:36 +01:00
|
|
|
done
|
|
|
|
done
|
2022-11-11 15:39:33 +01:00
|
|
|
echo $PROXY_HOST_CONF
|
|
|
|
}
|
2022-11-04 13:01:36 +01:00
|
|
|
|
2022-11-17 14:51:49 +01:00
|
|
|
update_host_list() {
|
2022-11-04 13:01:36 +01:00
|
|
|
FILTERED_HOSTS=$(grep -ve "# Added by hostman$" $HOST_CONF_PATH)
|
2022-11-11 15:39:33 +01:00
|
|
|
echo -e "$FILTERED_HOSTS$(get_host_list)" > $HOST_CONF_PATH
|
2022-11-17 14:51:49 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
update_host_list
|
|
|
|
# cannot filter because reailine no longer recognized lines otherwise (check how IFS changes)
|
|
|
|
query_docker "events" | while true
|
|
|
|
do
|
|
|
|
read -r;
|
|
|
|
# wait for related events to finish
|
|
|
|
while [ $? -eq 0 ]
|
|
|
|
do
|
|
|
|
read -t 5 -r;
|
|
|
|
done
|
|
|
|
update_host_list
|
2022-11-04 13:01:36 +01:00
|
|
|
done
|