postgres/templates/update_tags.sh.tpl

53 lines
2.7 KiB
Smarty

#!/bin/sh
# vim: syntax=sh
set -eo pipefail
EVENT=$1
NEW_ROLE=$2
if [ -z "${NEW_ROLE}" ]; then
# If new role is not given as argument, fetch it from patroni
NEW_ROLE=$(curl --silent --insecure https://localhost:${NOMAD_PORT_patroni}/health | jq -r .role)
fi
# Source env file to get our consul token
source /secrets/pg.env
# translate promoted = master and demoted = recplica
if [ "${NEW_ROLE}" = "promoted" ]; then
NEW_ROLE="master"
elif [ "${NEW_ROLE}" = "demoted" ]; then
NEW_ROLE="replica"
fi
CURL_OPTS="--connect-timeout 5 --max-time 10 --retry 5 --retry-delay 1 --retry-max-time 40 --retry-connrefused --silent"
# Update tags on the main service
SERVICE_HAS_TAG=$(curl ${CURL_OPTS} \
-H "X-Consul-Token: ${CONSUL_HTTP_TOKEN}" \
http://{{ sockaddr "GetInterfaceIP \"nomad\"" }}:8500/v1/catalog/service/[[ .instance ]][[ .consul.suffix ]] |\
jq ".[] | select( .ServiceTags as \$tags | \"postgres-{{ env "NOMAD_ALLOC_INDEX" }}\" | IN(\$tags[]) ) | .ServiceTags | any(.==\"${NEW_ROLE}\")")
if [ "${SERVICE_HAS_TAG}" = "false" ]; then
echo "Updating tags for the main service"
curl ${CURL_OPTS} -H "X-Consul-Token: ${CONSUL_HTTP_TOKEN}" http://{{ sockaddr "GetInterfaceIP \"nomad\"" }}:8500/v1/catalog/service/[[ .instance ]][[ .consul.suffix ]] |\
jq --from-file /local/serviceformat.jq --arg role "${NEW_ROLE}" --arg mytag postgres-{{ env "NOMAD_ALLOC_INDEX" }} |\
curl ${CORL_OPTS} -H "X-Consul-Token: ${CONSUL_HTTP_TOKEN}" -X PUT -d @- http://{{ sockaddr "GetInterfaceIP \"nomad\"" }}:8500/v1/txn > /dev/null
else
echo "Main service already has the expected ${NEW_ROLE} tag"
fi
# Update tags on the sidecar service (connect-proxy)
SIDECAR_HAS_TAG=$(curl ${CURL_OPTS} \
-H "X-Consul-Token: ${CONSUL_HTTP_TOKEN}" \
http://{{ sockaddr "GetInterfaceIP \"nomad\"" }}:8500/v1/catalog/service/[[ .instance ]][[ .consul.suffix ]]-sidecar-proxy |\
jq ".[] | select( .ServiceTags as \$tags | \"postgres-{{ env "NOMAD_ALLOC_INDEX" }}\" | IN(\$tags[]) ) | .ServiceTags | any(.==\"${NEW_ROLE}\")")
if [ "${SIDECAR_HAS_TAG}" = "false" ]; then
echo "Updating tags for the sidecar"
curl ${CURL_OPTS} -H "X-Consul-Token: ${CONSUL_HTTP_TOKEN}" http://{{ sockaddr "GetInterfaceIP \"nomad\"" }}:8500/v1/catalog/service/[[ .instance ]][[ .consul.suffix ]]-sidecar-proxy |\
jq --from-file /local/serviceformat.jq --arg role "${NEW_ROLE}" --arg mytag postgres-{{ env "NOMAD_ALLOC_INDEX" }} |\
curl ${CURL_OPTS} -H "X-Consul-Token: ${CONSUL_HTTP_TOKEN}" -X PUT -d @- http://{{ sockaddr "GetInterfaceIP \"nomad\"" }}:8500/v1/txn > /dev/null
else
echo "Sidecar service already has the expected ${NEW_ROLE} tag"
fi