#!/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 ${?} } waitForSentinel() { 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 sleep 10 } 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="" if [[ -f /etc/valkey/sentinel.conf ]]; then primaryHost="$(awk '/monitor/ {print $4}' /etc/valkey/sentinel.conf)" primaryPort="$(awk '/monitor/ {print $5}' /etc/valkey/sentinel.conf)" echo "Found previous primary ${primaryHost}:${primaryPort}" fi if [[ ! -f /etc/valkey/replication.conf ]]; then cp /etc/valkey/replication.conf.orig /etc/valkey/replication.conf fi waitForSentinel ret=${?} if [ "${ret}" -ne 0 ]; then exit ${ret} fi primaryInfo=$(getPrimaryInfo) if [ "${?}" -ne 0 ]; then echo "No primary found, seting up node as primary" startPrimary=1 else primaryHost=$(echo ${primaryInfo} | awk -F ' ' '{print $1}') primaryPort=$(echo ${primaryInfo} | awk -F ' ' '{print $2}') echo "Primary host is : ${primaryHost}, port: ${primaryPort}" currentHost=$(hostname -f) echo "Current host is : ${currentHost}" if [ "${primaryHost}" != "${currentHost}" ]; then echo "Not the primary, setting up as replica" startPrimary=0 else echo "This is the primary" startPrimary=1 fi fi if [ "${startPrimary}" -eq 1 ]; then echo "Starting Valkey as primary" cat $1 startValkey ${@} else echo "Starting Valkey as replica" startValkey ${@} "--replicaof" "${primaryHost}" "${primaryPort}" fi