WIP: update all services rules

This commit is contained in:
Chai Feng 2018-10-03 11:09:54 +08:00
parent 0ce7e710f5
commit 9767d9e5e1
No known key found for this signature in database
GPG Key ID: 2DCD9A24E523FFD2

View File

@ -4,7 +4,7 @@
ufw_docker_agent=ufw-docker-agent ufw_docker_agent=ufw-docker-agent
function ufw_update_service_instances() { function ufw-update-service-instances() {
name="$1" name="$1"
port="$2" port="$2"
@ -13,35 +13,55 @@ function ufw_update_service_instances() {
docker ps -qf "label=com.docker.swarm.service.name=${name}" | docker ps -qf "label=com.docker.swarm.service.name=${name}" |
while read name; do while read name; do
echo ufw-docker allow "${opts[@]}" ufw-docker allow "${opts[@]}"
done done
} }
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 name port; do
echo "${name}=$port"
ufw-update-service-instances "${name}" "${port}"
done
}
function run-ufw-docker() {
echo docker run --rm --cap-add NET_ADMIN --network host -v /etc/ufw:/etc/ufw "${ufw_docker_agent}" "$@"
}
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 "^.+\$"
}
case "$1" in case "$1" in
start) start)
declare -p | sed -e '/^declare -x ufw_public_/!d' \ run-ufw-docker update-ufw-rules
-e 's/^declare -x ufw_public_//' \
-e 's/="/ /' \
-e 's/"$//' |
while read name port; do
echo "${name}=$port"
ufw_update_service_instances "${name}" "${port}"
done
docker events --format '{{.Time}} {{.Status}} {{.Actor.Attributes.name}}' --filter 'scope=local' --filter 'type=container' | docker events --format '{{.Time}} {{.Status}} {{.Actor.Attributes.name}}' --filter 'scope=local' --filter 'type=container' |
while read time status name; do while read time status name; do
echo "$time $status $name" >&2 echo "$time $status $name" >&2
declare -a agent_opts=(run --rm --cap-add NET_ADMIN --network host -v /etc/ufw:/etc/ufw "${ufw_docker_agent_image}") [[ "$status" = @(kill|start) ]] || continue
declare -n env_name="ufw_public_$(get-service-name-of "$name")"
[[ -z "$env_name" ]] && continue
declare -a agent_opts=()
[[ "status" = start ]] && agent_opts+=(allow "$name") [[ "status" = start ]] && agent_opts+=(allow "$name")
[[ "status" = stop ]] && agent_opts+=(delete allow "$name") [[ "status" = stop ]] && agent_opts+=(delete allow "$name")
echo docker "${agent_opts[@]}" run-ufw-docker "${agent_opts[@]}" >&2
done done
sleep 60; exit 1 sleep 60; exit 1
;; ;;
delete|allow) delete|allow)
ufw-docker "$@" ufw-docker "$@"
;; ;;
update-ufw-rules)
update-ufw-rules
;;
*) *)
if [[ -f "$1" ]]; then if [[ -f "$1" ]]; then
exec "$@" exec "$@"