Skip to content

Commit

Permalink
Merge pull request #3 from iLert/feature/add-proxy-and-tls-flags
Browse files Browse the repository at this point in the history
[FEATURE] add proxy and tls skip flags
  • Loading branch information
yacut committed Mar 4, 2021
2 parents 6bc76f9 + 92f95e2 commit 19bf806
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 12 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ FROM centos:8
ARG NAGIOS_VERSION=4.0.8
ARG NAGION_PREFIX=4.x
ARG NAGIOS_PLUGINS_VERSION=2.0.3
ARG ILERT_PLUGIN_VERSION=1.5
ARG ILERT_PLUGIN_VERSION=1.6

RUN set -ex; \
yum -y update; \
Expand Down
44 changes: 33 additions & 11 deletions ilert_nagios.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
from urllib2 import HTTPError
from urllib2 import URLError
import uuid
import ssl
from xml.sax.saxutils import escape
from xml.sax.saxutils import quoteattr
import argparse
import io

PLUGIN_VERSION = "1.4"
PLUGIN_VERSION = "1.6"


def persist_event(api_key, directory, payload):
Expand Down Expand Up @@ -51,20 +52,20 @@ def persist_event(api_key, directory, payload):
exit(1)


def lock_and_flush(endpoint, directory, port):
def lock_and_flush(endpoint, directory, port, insecure):
"""Lock event directory and call flush"""
lock_filename = "%s/lockfile" % directory

lockfile = open(lock_filename, "w")

try:
fcntl.flock(lockfile.fileno(), fcntl.LOCK_EX)
flush(endpoint, directory, port)
flush(endpoint, directory, port, insecure)
finally:
lockfile.close()


def flush(endpoint, directory, port):
def flush(endpoint, directory, port, insecure):
"""Send all events in event directory to iLert"""
headers = {"Content-type": "application/xml", "Accept": "application/xml"}
url = "%s:%s/api/v1/events/nagios" % (endpoint, port)
Expand All @@ -84,8 +85,12 @@ def flush(endpoint, directory, port):
syslog.syslog('sending event %s to iLert...' % event)

try:
ctx = ssl.create_default_context()
if insecure == True:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
req = urllib2.Request(url, xml_doc, headers)
urllib2.urlopen(req, timeout=60)
urllib2.urlopen(req, timeout=60, context=ctx)
except HTTPError as e:
if e.code == 429:
syslog.syslog(syslog.LOG_WARNING, "too many requests, will try later. Server response: %s" % e.read())
Expand Down Expand Up @@ -120,20 +125,33 @@ def create_xml(apikey, payload):
return xml_doc


def str_to_bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')

def main():
parser = argparse.ArgumentParser(description='send events from Nagios (and its forks, such as Icinga) to iLert')
parser.add_argument('-m', '--mode', choices=['nagios', 'save', 'cron', 'send'], required=True,
help='Execution mode: "save" persists an event to disk and "send" submits all saved events '
'to iLert. Note that after every "save" "send" will also be called.')
parser.add_argument('-a', '--apikey', help='API key for the alert source in iLert')
parser.add_argument('-e', '--endpoint', default='https://ilertnow.com',
parser.add_argument('-e', '--endpoint', default='https://api.ilert.com',
help='iLert API endpoint (default: %(default)s)')
parser.add_argument('-p', '--port', type=int, default=443, help='endpoint port (default: %(default)s)')
parser.add_argument('-p', '--port', type=int, default=443, help='Endpoint port (default: %(default)s)')
parser.add_argument('-d', '--dir', default='/tmp/ilert_nagios',
help='event directory where events are stored (default: %(default)s)')
help='Event directory where events are stored (default: %(default)s)')
parser.add_argument('--version', action='version', version=PLUGIN_VERSION)
parser.add_argument('-k', '--insecure', type=str_to_bool, nargs='?', const=True, default=False,
help='Disable SSL certification validation (e.g. to use self-signed certificates) (default: %(default)s)')
parser.add_argument('-x', '--proxy', help='Use proxy for the outbound traffic')
parser.add_argument('payload', nargs=argparse.REMAINDER,
help='event payload as key value pairs in the format key1=value1 key2=value2 ...')
help='Event payload as key value pairs in the format key1=value1 key2=value2 ...')
args = parser.parse_args()

# populate payload data from environment variables
Expand All @@ -159,16 +177,20 @@ def main():
if not os.path.exists(args.dir):
os.makedirs(args.dir)

if args.proxy is not None:
os.environ['http_proxy'] = args.proxy
os.environ['https_proxy'] = args.proxy

if args.mode == "nagios" or args.mode == "save":
if apikey is None:
error_msg = "parameter apikey is required in save mode and must be provided either via command line or in " \
"the pager field of the contact definition in Nagios/Icinga"
syslog.syslog(syslog.LOG_ERR, error_msg)
parser.error(error_msg)
persist_event(apikey, args.dir, payload)
lock_and_flush(args.endpoint, args.dir, args.port)
lock_and_flush(args.endpoint, args.dir, args.port, args.insecure)
elif args.mode == "cron" or args.mode == "send":
lock_and_flush(args.endpoint, args.dir, args.port)
lock_and_flush(args.endpoint, args.dir, args.port, args.insecure)

exit(0)

Expand Down

0 comments on commit 19bf806

Please sign in to comment.