#!/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, tpool
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, outStream):
  """Get a checker function. Caches imports. Writes output to outfile."""
  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)

  fun = CHECK_CACHE[name].check

  def wrapper(args):
    """Wrapper function."""
    try:
      sys.stdout = outStream
      sys.stderr = outStream
      fun(args)
    except SystemExit:
      pass
    finally:
      sys.stdout = sys.__stdout__
      sys.stderr = sys.__stderr__

  return wrapper


@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."""
  outStream = StringIO()
  try:
    checkFun = checker(name, outStream)
  except KeyError:
    abort(404)

  args = request.args.getlist('arg')
  args.insert(0, 'check_%s' % name)

  tpool.execute(checkFun, args)
  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()

@@ -1110,16 +1110,349 @@
 (int)%0A%0A%0A
+def runChecker(fun, args):%0A  %22%22%22Run a checker function with the given args. Return a string.%22%22%22%0A  outStream = StringIO()%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  return outStream.getvalue()%0A%0A%0A
 def chec
@@ -1459,27 +1459,16 @@
 ker(name
-, outStream
 ):%0A  %22%22%22
@@ -1834,303 +1834,69 @@
 %0A%0A  
-fun = CHECK_CACHE%5Bname%5D.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
+return lambda args: runChecker(CHECK_CACHE%5Bname%5D.check, args)
 %0A%0A%0A@
@@ -2225,33 +2225,8 @@
 %22%22%22%0A
-  outStream = StringIO()%0A
   tr
@@ -2259,19 +2259,8 @@
 name
-, outStream
 )%0A  
@@ -2367,16 +2367,25 @@
 name)%0A%0A 
+ output =
  tpool.e
@@ -2413,24 +2413,205 @@
 )%0A  
-STATS%5Bname%5D += 1
+if not output.strip(): # If thread pool is wack, run in main thread. Also, pylint: disable=E1103%0A    logging.warn('Thread pool hiccup. Running %25s in main thread.', name)%0A    output = checkFun(args)
 %0A  r
@@ -2637,26 +2637,32 @@
 (out
-Stream.getvalue())
+put)%0A  STATS%5Bname%5D += 1%0A
 %0A  r

Refactor a bit and deal with weird thread pool exception wackiness.