ufw-docker/docker-entrypoint.sh

87 lines
2.6 KiB
Bash
Raw Normal View History

#!/bin/bash
[[ 0 -eq "$#" ]] && set -- start
2018-10-03 02:36:21 +00:00
ufw_docker_agent=ufw-docker-agent
2018-10-03 04:03:34 +00:00
ufw_docker_agent_image="${ufw_docker_agent_image:-chaifeng/${ufw_docker_agent}:181003}"
2018-10-03 02:36:21 +00:00
2018-10-03 03:09:54 +00:00
function ufw-update-service-instances() {
2018-10-03 04:46:40 +00:00
id="$1"
2018-10-03 02:36:21 +00:00
port="$2"
2018-10-03 04:46:40 +00:00
declare -a opts
2018-10-03 02:36:21 +00:00
[[ "$port" = all ]] || opts+=("$port")
2018-10-03 04:46:40 +00:00
docker ps -qf "label=com.docker.swarm.service.id=${id}" |
2018-10-03 02:36:21 +00:00
while read name; do
2018-10-03 04:46:40 +00:00
echo "$id $name $port"
run-ufw-docker allow "${name}" "${opts[@]}"
2018-10-03 02:36:21 +00:00
done
}
2018-10-03 03:09:54 +00:00
function update-ufw-rules() {
declare -p | sed -e '/^declare -x ufw_public_/!d' \
-e 's/^declare -x ufw_public_//' \
-e 's/="/ /' \
-e 's/"$//' |
2018-10-03 04:46:40 +00:00
while read id port; do
echo "${id}=$port"
ufw-update-service-instances "${id}" "${port}"
2018-10-03 03:09:54 +00:00
done
}
function run-ufw-docker() {
declare -a docker_opts=(run --rm -t --name ufw-docker-agent-tmp-$(date '+%Y%m%d%H%M%S')
--cap-add NET_ADMIN --network host
--env UFW_DOCKER_FORCE_ADD=yes
-v /var/run/docker.sock:/var/run/docker.sock
2018-10-03 04:46:40 +00:00
-v /etc/ufw:/etc/ufw "${ufw_docker_agent_image}" "$@")
echo docker "${docker_opts[@]}"
2018-10-03 03:09:54 +00:00
}
function get-service-name-of() {
docker inspect "$1" --format '{{range $k,$v:=.Config.Labels}}{{ if eq $k "com.docker.swarm.service.name" }}{{$v}}{{end}}{{end}}' | grep -E "^.+\$"
}
2018-10-03 03:22:50 +00:00
function get-service-id-of() {
docker inspect "$1" --format '{{range $k,$v:=.Config.Labels}}{{ if eq $k "com.docker.swarm.service.id" }}{{$v}}{{end}}{{end}}' | grep -E "^.+\$"
}
case "$1" in
start)
2018-10-03 04:46:40 +00:00
update-ufw-rules
2018-10-03 01:18:28 +00:00
docker events --format '{{.Time}} {{.Status}} {{.Actor.Attributes.name}}' --filter 'scope=local' --filter 'type=container' |
while read time status name; do
echo "$time $status $name" >&2
2018-10-03 03:09:54 +00:00
[[ "$status" = @(kill|start) ]] || continue
2018-10-03 03:22:50 +00:00
declare -n env_name="ufw_public_$(get-service-id-of "$name")"
2018-10-03 03:09:54 +00:00
[[ -z "$env_name" ]] && continue
declare -a agent_opts=()
2018-10-03 04:46:40 +00:00
if [[ "$status" = kill ]]; then
agent_opts+=(delete allow "$name")
elif [[ "$status" = start ]]; then
agent_opts+=(allow "$name")
fi
2018-10-03 01:18:28 +00:00
2018-10-03 03:09:54 +00:00
run-ufw-docker "${agent_opts[@]}" >&2
2018-10-03 01:18:28 +00:00
done
sleep 60; exit 1
;;
delete|allow)
ufw-docker "$@"
;;
2018-10-03 03:09:54 +00:00
update-ufw-rules)
update-ufw-rules
;;
*)
if [[ -f "$1" ]]; then
exec "$@"
else
echo "Unknown parameters: $@" >&2
exit 1
fi
esac