#!/usr/bin/python3
# coding=utf-8
# Copyright (C) 2021:
#     Linexos, info@linexos.fr
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# By JTA (04/2021)

import os, sys, time, redis
from datetime import datetime
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-H', '--host', help='Redis Host, default=localhost', default='localhost')
parser.add_argument('-P', '--port', help='Port number, default=6379', default='6379')
parser.add_argument('-K', '--key', help='Key to check in Redis', default=None, type=str, required=True)
parser.add_argument('-W', '--warning', help='Warning threshold', default=3, type=float)
parser.add_argument('-C', '--critical', help='Critical theshold', default=15, type=float)
parser.add_argument('-T', '--timeout', help='Socket timeout', default=5, type=float)

args = parser.parse_args()

if (args.critical and args.critical < 0):
	print("Error: -C Critical cannot be negative")
	sys.exit(3)
elif (args.warning and args.warning < 0):
	print("Error: -W Warning cannot be negative")
	sys.exit(3)


red = redis.Redis(host=args.host, port=args.port, socket_timeout=args.timeout)
try:
	KEYLEN = int(red.llen(args.key))	
except redis.exceptions.ConnectionError as r:
	print("CRITICAL : %s " % r)
	sys.exit(2)
except redis.exceptions.InvalidResponse as r:
	print("UNKNOWN : %s " % r)
	sys.exit(3)
except redis.exceptions.TimeoutError as r:
	print("CRITICAL : %s " % r)
	sys.exit(2)
except redis.exceptions.DataError as r:
	print("UNKNOWN : %s " % r)
	sys.exit(3)
except:
	print("UNKNOWN : %s" % sys.exc_info()[0])
	sys.exit(3)

# Test the value
if (KEYLEN >= args.critical):
	print("CRITICAL : Stack of %i in key %s" % (KEYLEN, args.key))
	status_code = 2
elif (KEYLEN >= args.warning):
	print("WARNING : Stack of %i in key %s" % (KEYLEN, args.key))
	status_code = 1
else:
	print("OK : Stack of %i in key %s | %s=%i" % (KEYLEN, args.key, args.key, KEYLEN))
	status_code = 0

sys.exit(status_code)