Skip to content

Instantly share code, notes, and snippets.

@XavM
Created November 4, 2015 15:48
Show Gist options
  • Save XavM/ea24af7a6aebc58e5820 to your computer and use it in GitHub Desktop.
Save XavM/ea24af7a6aebc58e5820 to your computer and use it in GitHub Desktop.
Containers and Service auto registration through Consul for openVZ CT (via ovz action scripts)
#!/bin/bash
set -eo pipefail
CONSUL_EP="IP:PORT"
main() {
# Exit when required files are not present
[[ -f /etc/vz/vz.conf ]] || exit 1
[[ -f $VE_CONFFILE ]] || exit 1
# Source the CT conf file
. $VE_CONFFILE
# Register CT in consul (Exept for consul server itself : ns1)
[[ "${HOSTNAME}" == "ns1" ]] \
|| curl --noproxy "*" -sS ${CONSUL_EP}/v1/catalog/register \
-d '{
"Node": "'${HOSTNAME}'",
"Address": "'${IP_ADDRESS}'",
"Check": {
"Node": "'${HOSTNAME}'",
"Name": "'${HOSTNAME}' status",
"Status": "passing"
}
}' \
> /dev/null
# Services should be stored in "description" field with the following format :
# vzctl set ${VEID} --description '{
# "services": [
# {
# "name": "graphite",
# "port": "2300",
# "tags": [
# "tag1"
# ]
# },
# {
# "name": "service1"
# },
# {
# "name": "service2"
# }
# ],
# "tags": [],
# "description": ""
# }'
# Get list of services for this CT
SERVICES=$(/usr/sbin/vzlist ${VEID} -o description -H | jq -cr ".services[]" 2>/dev/null)
# Register Services in consul
for SERVICE in $SERVICES; do
echo "Adding ${SERVICE} to service discovery"
# Detect description format
# Must be one of :
# - {"services": [{"name":"graphite","port":"2300","tags":["tag1"]}] }
# - {"services": ["service:port#tag","service","service:port","service#tag"] }
local DETAILED_FORMAT=$(echo "${SERVICE}" | jq . 2>&1>/dev/null && echo "true" || echo "false")
[[ "${DETAILED_FORMAT}" == "true" ]] && {
local NAME="$(echo "${SERVICE}" | jq -r '.name // 0')"
local PORT="$(echo "${SERVICE}" | jq -r '.port // 0')"
local TAGS="$(echo "${SERVICE}" | jq -r '.tags // []')"
local PAYLOAD='{
"Service": "'"${NAME}"'",
"Tags": '"${TAGS}"',
"Port": '"${PORT}"'
}'
} || {
local NAME_PORT="${SERVICE%%#*}"
local NAME="${NAME_PORT%%:*}"
local PORT="${NAME_PORT##*:}"
local TAG="${SERVICE##*#}"
[[ "${PORT}" == "${NAME_PORT}" ]] && PORT=0
[[ "${TAG}" == "${NAME_PORT}" ]] && TAG=""
local PAYLOAD='{
"Service": "'"${NAME}"'",
"Port": '"${PORT}"',
"Tags": ["'"${TAG}"'"]
}'
}
curl --noproxy "*" -sS ${CONSUL_EP}/v1/catalog/register -d '{
"Node": "'${HOSTNAME}'",
"Address": "'${IP_ADDRESS}'",
"Service": '"${PAYLOAD}"'
}' \
> /dev/null
done
}
main &
disown
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment