#!/usr/bin/env python
# Copyright 2011 The greplin-nagios-utils Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Server that runs Python checks."""

from eventlet import wsgi
import eventlet
from flask import Flask, request, make_response, jsonify, abort
APP = Flask(__name__)

import imp
import os
import sys
import logging
from optparse import OptionParser
from collections import defaultdict
from cStringIO import StringIO

# Cache mapping check names to checker modules
CHECK_CACHE = {}
# Argparser options
OPTIONS = None
# Stats on how many times each checker has run
STATS = defaultdict(int)


def checker(name):
  """Get a checker function. Caches imports."""
  if name not in CHECK_CACHE:
    filename = os.path.join(os.path.dirname(__file__), OPTIONS.checkdir, 'check_%s.py' % name)
    if os.path.exists(filename):
      CHECK_CACHE[name] = imp.load_source('check_%s' % name, filename)
    else:
      raise KeyError('No such file: %s' % filename)

  return CHECK_CACHE[name].check


@APP.route('/')
def root():
  """Root request handler."""
  return jsonify(STATS)


@APP.route('/update/<name>')
def update(name):
  """Reload a check module."""
  if name in CHECK_CACHE:
    del CHECK_CACHE[name]
    return "Reloaded"
  else:
    abort(404)


@APP.route('/check/<name>')
def check(name):
  """Run a check."""
  try:
    checkFun = checker(name)
  except KeyError:
    abort(404)

  outStream = StringIO()
  args = request.args.getlist('arg')
  args.insert(0, 'check_%s' % name)
  try:
    sys.stdout = outStream
    sys.stderr = outStream
    checkFun(args)
  except SystemExit:
    pass
  finally:
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
    STATS[name] += 1
  resp = make_response(outStream.getvalue())
  resp.headers['Content-Type'] = 'text/plain; charset=UTF-8'
  return resp


def main():
  """Run the server."""
  global OPTIONS                        # pylint: disable=W0603
  parser = OptionParser()
  parser.add_option("-d", "--checkdir", dest="checkdir", metavar="DIR",
                    default="/usr/lib/nagios/plugins", help="directory with check scripts")
  parser.add_option("-l", "--log-level", dest="loglevel", metavar="LEVEL",
                    help="logging level", default='info')
  parser.add_option("-p", "--port", dest="port", metavar="PORT",
                    help="port to listen on", default=8111, type="int")
  OPTIONS = parser.parse_args()[0]

  levelname = {'debug': logging.DEBUG, 'info': logging.INFO, 'warn': logging.WARN, 'error': logging.ERROR}
  logging.basicConfig(level=levelname.get(OPTIONS.loglevel.lower(), logging.WARN))

  wsgi.server(eventlet.listen(('', int(OPTIONS.port))), APP)


if __name__ == '__main__':
  main()

@@ -677,16 +677,23 @@
 ort wsgi
+, tpool
 %0Aimport 
@@ -1122,24 +1122,35 @@
 checker(name
+, outStream
 ):%0A  %22%22%22Get 
@@ -1184,16 +1184,42 @@
 imports.
+ Writes output to outfile.
 %22%22%22%0A  if
@@ -1508,22 +1508,21 @@
 ame)%0A%0A  
-return
+fun =
  CHECK_C
@@ -1539,16 +1539,282 @@
 .check%0A%0A
+  def wrapper(args):%0A    %22%22%22Wrapper function.%22%22%22%0A    try:%0A      sys.stdout = outStream%0A      sys.stderr = outStream%0A      fun(args)%0A    except SystemExit:%0A      pass%0A    finally:%0A      sys.stdout = sys.__stdout__%0A      sys.stderr = sys.__stderr__%0A%0A  return wrapper%0A%0A
 %0A@APP.ro
@@ -2133,16 +2133,41 @@
 eck.%22%22%22%0A
+  outStream = StringIO()%0A
   try:%0A 
@@ -2188,24 +2188,35 @@
 checker(name
+, outStream
 )%0A  except K
@@ -2244,33 +2244,8 @@
 4)%0A%0A
-  outStream = StringIO()%0A
   ar
@@ -2317,81 +2317,33 @@
 me)%0A
-  try:%0A    sys.stdout = outStream%0A    sys.stderr = outStream%0A    
+%0A  tpool.execute(
 checkFun
 (arg
@@ -2342,122 +2342,16 @@
 kFun
-(
+, 
 args)%0A
-  except SystemExit:%0A    pass%0A  finally:%0A    sys.stdout = sys.__stdout__%0A    sys.stderr = sys.__stderr__%0A  
   ST

Make flask server run all checkers in a thread pool.