85 lines
1.9 KiB
Bash

#!/bin/sh
pingSentinel() {
resp=$(timeout -s 15 $1 \
valkey-cli \
-h ${VALKEY_SERVICE} \
-p ${VALKEY_SENTINEL_PORT} \
ping)
ret=${?}
echo $resp
return ${ret}
}
getPrimaryInfo() {
valkey-cli --csv -h ${VALKEY_SERVICE} -p ${VALKEY_SENTINEL_PORT} sentinel get-primary-addr-by-name "mymaster"| \
awk -F ',' '{ gsub(/"/,"",$0); print $1 " " $2 }'
return ${?}
}
waitFroSentinel() {
tout=60
while true; do
response=$(pingSentinel 5)
if [ "${response}" = "PONG" ]; then
echo "Sentinel is responding"
break
return 0
fi
echo "Sentinel is not responding [${response}]"
sleep 1
tout=$((tout - 1))
if [ "${tout}" -le 0 ]; then
echo "Sentinel ping timed out"
return 124
fi
done
}
startValkey() {
# Start Valkey
echo "Running : [valkey-server ${@}]"
valkey-server ${@}
ret=${?}
if [ "${ret}" -ne 0 ]; then
echo "Failed to start Valkey"
exit ${ret}
fi
}
setupPrimary=0
primaryHost=""
primaryPort=""
waitFroSentinel
ret=${?}
if [ "${ret}" -ne 0 ]; then
exit ${ret}
fi
primaryInfo=$(getPrimaryInfo)
if [ "${?}" -ne 0 ]; then
echo "No primary found, seting up node as primary"
setupPrimary=1
else
primaryHost=$(echo ${primaryInfo} | awk -F ' ' '{print $1}')
primaryPort=$(echo ${primaryInfo} | awk -F ' ' '{print $2}')
currentHost=$(hostname -f)
if [ "${primaryHost}" != "${currentHost}" ]; then
echo "Not the primary, setting up as replica"
setupPrimary=0
else
echo "This is the primary"
setupPrimary=1
fi
fi
if [ "${setupPrimary}" -eq 1 ]; then
echo "Starting Valkey as primary"
cat $1
startValkey ${@}
else
echo "Starting Valkey as replica"
startValkey ${@} "--replicaof" "${primaryHost}" "${primaryPort}"
fi