|
| 1 | +#!/usr/bin/env sh |
| 2 | + |
| 3 | +# assume the following environment variables, all of which may be null |
| 4 | +# HEALTHCHECK_PORT |
| 5 | +# HEALTHCHECK_USER |
| 6 | +# HEALTHCHECK_PASSWORD |
| 7 | +# HEALTHCHECK_TOPIC |
| 8 | + |
| 9 | +# set a default for the port |
| 10 | +HEALTHCHECK_PORT="${HEALTHCHECK_PORT:-1883}" |
| 11 | + |
| 12 | +# strip any quotes from username and password |
| 13 | +HEALTHCHECK_USER="$(eval echo $HEALTHCHECK_USER)" |
| 14 | +HEALTHCHECK_PASSWORD="$(eval echo $HEALTHCHECK_PASSWORD)" |
| 15 | + |
| 16 | +# set a default for the topic |
| 17 | +HEALTHCHECK_TOPIC="${HEALTHCHECK_TOPIC:-iotstack/mosquitto/healthcheck}" |
| 18 | +HEALTHCHECK_TOPIC="$(eval echo $HEALTHCHECK_TOPIC)" |
| 19 | + |
| 20 | +# record the current date and time for the test payload |
| 21 | +PUBLISH=$(date) |
| 22 | + |
| 23 | +# publish a retained message containing the timestamp |
| 24 | +mosquitto_pub \ |
| 25 | + -h localhost \ |
| 26 | + -p "$HEALTHCHECK_PORT" \ |
| 27 | + -t "$HEALTHCHECK_TOPIC" \ |
| 28 | + -m "$PUBLISH" \ |
| 29 | + -u "$HEALTHCHECK_USER" \ |
| 30 | + -P "$HEALTHCHECK_PASSWORD" \ |
| 31 | + -r |
| 32 | + |
| 33 | +# did that succeed? |
| 34 | +if [ $? -eq 0 ] ; then |
| 35 | + |
| 36 | + # yes! now, subscribe to that same topic with a 2-second timeout |
| 37 | + # plus returning on the first message |
| 38 | + SUBSCRIBE=$(mosquitto_sub \ |
| 39 | + -h localhost \ |
| 40 | + -p "$HEALTHCHECK_PORT" \ |
| 41 | + -t "$HEALTHCHECK_TOPIC" \ |
| 42 | + -u "$HEALTHCHECK_USER" \ |
| 43 | + -P "$HEALTHCHECK_PASSWORD" \ |
| 44 | + -W 2 \ |
| 45 | + -C 1 \ |
| 46 | + ) |
| 47 | + |
| 48 | + # did the subscribe succeed? |
| 49 | + if [ $? -eq 0 ] ; then |
| 50 | + |
| 51 | + # yes! do the publish and subscribe payloads compare equal? |
| 52 | + if [ "$PUBLISH" = "$SUBSCRIBE" ] ; then |
| 53 | + |
| 54 | + # yes! return success |
| 55 | + exit 0 |
| 56 | + |
| 57 | + fi |
| 58 | + |
| 59 | + fi |
| 60 | + |
| 61 | +fi |
| 62 | + |
| 63 | +# otherwise, return failure |
| 64 | +exit 1 |
0 commit comments