ufw-docker/docker-entrypoint.sh

98 lines
2.9 KiB
Bash
Raw Normal View History

#!/bin/bash
set -euo pipefail
2018-10-03 07:43:44 +00:00
[[ -n "${DEBUG:-}" ]] && set -x
[[ 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 07:02:50 +00:00
function ufw-update-rule-for-instance() {
name="$1"
2018-10-03 02:36:21 +00:00
port="$2"
2018-10-03 04:46:40 +00:00
declare -a opts
[[ "$port" = deny ]] && opts+=(delete)
opts+=(allow)
[[ "$port" = @(all|deny) ]] && port=""
2018-10-03 02:36:21 +00:00
2018-10-03 07:02:50 +00:00
run-ufw-docker "${opts[@]}" "${name}" "$port"
}
function ufw-update-service-instances() {
id="$1"
port="$2"
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 07:02:50 +00:00
ufw-update-rule-for-instance "${name}" "$port"
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
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-"${RANDOM}"-$(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}" "$@")
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 "^.+\$"
}
2018-10-05 05:39:57 +00:00
function main() {
case "$1" in
start)
update-ufw-rules
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
[[ -z "$name" ]] && continue
[[ "$status" = @(kill|start) ]] || continue
declare -n env_name="ufw_public_$(get-service-id-of "$name")"
[[ -z "${env_name:-}" ]] && continue
declare port="${env_name:-deny}"
if [[ "$status" = kill ]]; then
port=deny
fi
echo ufw-update-rule-for-instance "$name" "$port"
done
sleep 60; exit 1
;;
delete|allow)
ufw-docker "$@"
;;
update-ufw-rules)
update-ufw-rules
;;
*)
if [[ -f "$1" ]]; then
exec "$@"
else
echo "Unknown parameters: $@" >&2
exit 1
fi
esac
}
main "$@"