forked from ghostiam/ufw-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker-entrypoint.sh
executable file
·71 lines (62 loc) · 2 KB
/
docker-entrypoint.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/bin/bash
set -euo pipefail
[[ -n "${DEBUG:-}" ]] && set -x
[[ 0 -eq "$#" ]] && set -- start
ufw_docker_agent=ufw-docker-agent
ufw_docker_agent_image="${ufw_docker_agent_image:-chaifeng/${ufw_docker_agent}:181003}"
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
}
function update-ufw-rules() {
declare -p | sed -e '/^declare -x ufw_public_/!d' \
-e 's/^declare -x ufw_public_//' \
-e 's/="/ /' \
-e 's/"$//' |
while read -r id port; do
ufw-allow-or-deny-service "${id}" "${port#*/}"
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}"
-v /var/run/docker.sock:/var/run/docker.sock
-v /etc/ufw:/etc/ufw "${ufw_docker_agent_image}" "$@")
docker "${docker_opts[@]}"
}
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 "^.+\$"
}
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 "^.+\$"
}
function main() {
case "$1" in
start)
update-ufw-rules
while true; do
sleep "$(( 3600 * 24 * 7 ))" || break
done
;;
delete|allow|add-service-rule)
ufw-docker "$@"
;;
update-ufw-rules)
update-ufw-rules
;;
*)
if [[ -f "$1" ]]; then
exec "$@"
else
echo "Unknown parameters:" "$@" >&2
exit 1
fi
esac
}
main "$@"