ufw-docker/docker-entrypoint.sh

73 lines
2.0 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
function ufw-allow-or-deny-service() {
declare id="$1"
declare port="$2"
if [[ "$port" = deny ]]; then
run-ufw-docker delete allow "$id"
else
run-ufw-docker add-service-rule "$id" "$port"
fi
2018-10-03 02:36:21 +00:00
}
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
2018-10-05 10:05:20 +00:00
ufw-allow-or-deny-service "${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 DEBUG="$DEBUG"
--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
2018-10-05 10:11:33 +00:00
while true; do
sleep "$(( 3600 * 24 * 7 ))" || break
done
2018-10-05 05:39:57 +00:00
;;
2018-10-05 08:25:44 +00:00
delete|allow|add-service-rule)
2018-10-05 05:39:57 +00:00
ufw-docker "$@"
;;
update-ufw-rules)
update-ufw-rules
;;
*)
if [[ -f "$1" ]]; then
exec "$@"
else
echo "Unknown parameters: $@" >&2
exit 1
fi
esac
}
main "$@"