#!/bin/bash
#
# Author  Pierre Fumet <pfumet@easter-eggs.com>
# Date    Fri, 21 Oct 2022 16:19:48 +0200
# Desc    Check existing rbd-nbd mounts, #89071

# defaults
defwtime=900
defctime=3600

usage () {
	echo "
Check for rbd-nbd mounts :
	$0 [-w warn_seconds] [-c crit_seconds]
Returns :
- warning if has more than warn_seconds (def. $defwtime) but less than critl_seconds (def. $defctime)
- critical if more than crit_seconds"
}

while getopts ":w:c:h" opt
do
	case $opt in
		h) usage; exit 0 ;;
		w) wtime=$OPTARG ;;
		c) ctime=$OPTARG ;;
		:) echo "Missing value for option -$OPTARG"; usage; exit 2 ;;
		?) echo "$OPTARG : bad option"; usage; exit 2 ;;
	esac
done

# pre
WTIME=${wtime:-$defwtime}
CTIME=${ctime:-$defctime}
[[ $WTIME -lt $CTIME ]] || { echo "warn_seconds ($WTIME) MUST be less than crit_seconds ($CTIME) !"; exit 1; }

# main
RES=$(ps -C rbd-nbd -o pid,lstart | grep -v STARTED)

if [[ -n "$RES" ]]
then
	mapped=$(rbd-nbd list-mapped | grep -v ^pid)
	crit=0
	warn=0

	while read pid psdate
	do
		mapdate=$(date -d "$psdate" +%s)
		date=$(date +%s)
		pool=$(echo "$mapped" | awk '/'$pid'/ {print $2}')
		img=$(echo "$mapped" | awk '/'$pid'/ {print $3}')
		dev=$(echo "$mapped" | awk '/'$pid'/ {print $5}')
		if [[ $(( date - mapdate )) -ge $CTIME ]]; then crit=1
		elif [[ $(( date - mapdate )) -ge $WTIME ]]; then warn=1
		fi
		msg="$msg\n$pool/$img -> $dev, since $psdate"
	done < <(echo "$RES")

	if [[ $crit -eq 1 ]]
	then
		msg="CRITICAL - map older than $CTIME seconds\n$msg"; out=2
	elif [[ $warn -eq 1 ]]
	then
		msg="WARNING - map older than $WTIME seconds\n$msg"; out=1
	else
		msg="OK\n$msg"; out=0
	fi
else
	msg="OK - no mounts"; out=0
fi

# notify
echo -e "$msg"
exit $out
