Skip to content

Commit

Permalink
replace optparse with argparse and fix linting
Browse files Browse the repository at this point in the history
  • Loading branch information
stdevel committed Mar 21, 2021
1 parent 8ef26ac commit 5df177e
Showing 1 changed file with 57 additions and 43 deletions.
100 changes: 57 additions & 43 deletions check_omd.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@
https://github.com/stdevel/check_omd
"""

from optparse import OptionParser
import argparse
import subprocess
import io
import sys
import logging

__version__ = "1.1.1"
__version__ = "1.3.0"
"""
str: Program version
"""
Expand All @@ -26,40 +26,46 @@
"""



def get_site_status():
"""
Retrieves a particular site's status
"""
#get username
# get username
proc = subprocess.Popen("whoami", stdout=subprocess.PIPE)
site = proc.stdout.read().rstrip().decode("utf-8")
LOGGER.debug("It seems like I'm OMD site '%s'", site)

#get OMD site status
# get OMD site status
cmd = ['omd', 'status', '-b']
LOGGER.debug("running command '%s'", cmd)
proc = subprocess.Popen(
cmd, stderr=subprocess.PIPE, stdin=subprocess.PIPE, stdout=subprocess.PIPE
cmd,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
res, err = proc.communicate()
err = err.decode('utf-8')

if err:
if "no such site" in err:
print("UNKNOWN: unable to check site: '{0}' - did you miss " \
"running this plugin as OMD site user?".format(err.rstrip()))
print(
"UNKNOWN: unable to check site: '{0}' - did you miss "
"running this plugin as OMD site user?".format(err.rstrip())
)
else:
print("UNKNOWN: unable to check site: '{0}'".format(err.rstrip()))
sys.exit(3)
if res:
#try to find out whether omd was executed as root
# try to find out whether omd was executed as root
if res.count(bytes("OVERALL", "utf-8")) > 1:
print("UNKOWN: unable to check site, it seems this plugin is " \
"executed as root (use OMD site context!)")
print(
"UNKOWN: unable to check site, it seems this plugin is "
"executed as root (use OMD site context!)"
)
sys.exit(3)

#check all services
# check all services
fail_srvs = []
warn_srvs = []
restarted_srvs = []
Expand All @@ -69,11 +75,11 @@ def get_site_status():
service = line.rstrip().split(" ")[0]
status = line.rstrip().split(" ")[1]
if service not in OPTIONS.exclude:
#check service
# check service
if status != "0":
if service in OPTIONS.warning:
LOGGER.debug(
"%s service marked for warning has failed" \
"%s service marked for warning has failed"
" state (%s)", service, status
)
warn_srvs.append(service)
Expand All @@ -93,7 +99,7 @@ def get_site_status():
else:
fail_srvs.append(service)
LOGGER.debug(
"%s service has failed state " \
"%s service has failed state "
"(%s)", service, status
)
else:
Expand All @@ -114,56 +120,64 @@ def get_site_status():
print("OK: OMD site '{0}' services are running.".format(site))
sys.exit(0)
elif len(fail_srvs) > 0:
print("CRITICAL: OMD site '{0}' has failed service(s): " \
"'{1}'".format(site, ' '.join(fail_srvs)))
print(
"CRITICAL: OMD site '{0}' has failed service(s): "
"'{1}'".format(site, ' '.join(fail_srvs))
)
sys.exit(2)
else:
print("WARNING: OMD site '{0}' has service(s) in warning state: " \
"'{1}'".format(site, ' '.join(warn_srvs)))
print(
"WARNING: OMD site '{0}' has service(s) in warning state: "
"'{1}'".format(site, ' '.join(warn_srvs))
)
sys.exit(1)



if __name__ == "__main__":
#define description, version and load parser
# define description, version and load parser
DESC = '''%prog is used to check a particular OMD site status. By default,
the script only checks a site's overall status. It is also possible to exclude
particular services and only check the remaining services (e.g. rrdcached,
npcd, icinga, apache, crontab).
npcd, icinga, apache, crontab).'''
EPILOG = 'See also: https://github.com/stdevel/check_omd'
PARSER = argparse.ArgumentParser(description=DESC, epilog=EPILOG)
PARSER.add_argument('--version', action='version', version=__version__)

Checkout the GitHub page for updates: https://github.com/stdevel/check_omd'''
PARSER = OptionParser(description=DESC, version=__version__)
# define option groups
GEN_OPTS = PARSER.add_argument_group("generic arguments")
FILTER_OPTS = PARSER.add_argument_group("filter arguments")

#-d / --debug
PARSER.add_option(
# -d / --debug
GEN_OPTS.add_argument(
"-d", "--debug", dest="debug", default=False, action="store_true",
help="enable debugging outputs (default: no)"
)

#-e / --exclude
PARSER.add_option(
# -H / --heal
FILTER_OPTS.add_argument(
"-H", "--heal", dest="heal", default=False, action="store_true",
help="automatically restarts failed services (default: no)"
)

# -e / --exclude
FILTER_OPTS.add_argument(
"-x", "--exclude", dest="exclude", default=["OVERALL"],
action="append", metavar="SERVICE", help="defines one or more " \
"services that should be excluded (default: none)"
action="append", metavar="SERVICE", help="defines one or more "
"services that should be excluded (default: none)"
)

#-w / --warning
PARSER.add_option(
# -w / --warning
FILTER_OPTS.add_argument(
"-w", "--warning", dest="warning", default=[""], action="append",
metavar="SERVICE", help="defines one or more services that only " \
"should throw a warning if not running (useful for fragile stuff " \
metavar="SERVICE", help="defines one or more services that only "
"should throw a warning if not running (useful for fragile stuff "
"like npcd, default: none)"
)
#-H/ --heal
PARSER.add_option(
"-H", "--heal", dest="heal", default=False, action="store_true",
help="automatically restarts the services that are not running (default: no)"
)

#parse arguments
(OPTIONS, ARGS) = PARSER.parse_args()
# parse arguments
OPTIONS = PARSER.parse_args()

#set logging level
# set logging level
logging.basicConfig()
if OPTIONS.debug:
LOGGER.setLevel(logging.DEBUG)
Expand All @@ -172,5 +186,5 @@ def get_site_status():

LOGGER.debug("OPTIONS: %s", OPTIONS)

#check site status
# check site status
get_site_status()

0 comments on commit 5df177e

Please sign in to comment.