From 683d265b2fdf0f51160f5e9c26b3553f12a6c81b Mon Sep 17 00:00:00 2001 From: david Date: Sat, 22 Jan 2022 00:24:45 +0100 Subject: [PATCH] added watch_containers.sh --- watch_containers.sh | 90 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100755 watch_containers.sh diff --git a/watch_containers.sh b/watch_containers.sh new file mode 100755 index 0000000..8cf3a19 --- /dev/null +++ b/watch_containers.sh @@ -0,0 +1,90 @@ +#!/bin/bash + +# name: watch_containers.sh +# author: david@socialnerds.org +# version: 0.1 +# license: GPLv3 +# description: Checks if the running container count +# matches a number provided as $1 and optionally +# reports results to a healthchecks endpoint. + +# usage: ./watch_containers.sh + +# **** function definitions **** +function usage { + echo "usage: ./watch_containers.sh " +} + +function get_container_count { + local CNT=$(docker ps -q | wc -l) + if is_int "$CNT"; then + echo $CNT + fi +} + +function is_int { + local INT_EXPR='^[0-9]+$' + if [[ $1 =~ $INT_EXPR ]]; then + return 0 + else + return 1 + fi +} + +function is_url { + local URL_EXPR='^https?://.+$' + if [[ $1 =~ $URL_EXPR ]]; then + return 0 + else + return 1 + fi +} + +# **** start **** + +#exit if no options +if [ -z "$1" ]; then + usage + exit 1 +fi + +#exit if $1 is no intager +if ! is_int "$1"; then + usage + exit 1 +fi + +#set expected running containers +NUM=$1 + +#get running container count +CNT=$(get_container_count) + +#set healthchecks url if not empty +URL="" +if [ -n "$2" ]; then + #exit if $2 is no valid url + if ! is_url "$2"; then + usage + exit 1 + fi + URL="$2" +fi + +MSG="Running containers: $CNT +Expected containers: $NUM" + +echo "$MSG" + +#report to healthchecks +if [ -n "$URL" ]; then + if [ $NUM -eq $CNT ]; then + curl -m 10 --retry 5 --data-raw "$MSG" "$URL" + else + curl -m 10 --retry 5 --data-raw "$MSG" "$URL/fail" + fi +fi + +# **** end **** +exit 0 +