import logging
log = logging.getLogger(__name__)

# Events, for Task
import event

# Subprocess, for NagiosTask
import subprocess
import shlex

# Multiprocessing, for PythonTask
import multiprocessing

import time

class Task():
	def __init__(self, name, ttl):
		log.info("Creating task: '%s' with TTL of %ss" % (name, ttl))
		self.events = event.Events()
		self.name = name
		self.ttl = ttl
		self.tags = []
		self.timings = [0]

	def add_timing(self, value, limit=5):
		self.timings.append(value)
		del self.timings[:-limit]

	def skew(self):
		return sum(self.timings)/len(self.timings)

	def start(self):
		log.info("Starting task: '%s' with TTL of %ss" % (self.name, self.ttl))
		self.start_time = time.time()
		self.run()

	def get_events(self):
		self.join()
		self.end_time = time.time()
		self.add_timing(self.end_time - self.start_time)

		return self.events


class PythonTask(Task):
	def __init__(self, name, ttl, module):
		Task.__init__(self, name, ttl)
		self.module = module

	def run(self):
		pass

	def join(self):
		self.events.add(service=self.name, state=state, description=description, ttl=self.ttl, tags=self.tags)


class NagiosTask(Task):
	exitcodes = {
		0: 'ok',
		1: 'warn',
		2: 'error',
		3: 'unknown'
	}

	def __init__(self, name, ttl, command, shell=False):
		Task.__init__(self, name, ttl)
		self.raw_command = command
		self.command = shlex.split(command)
		self.use_shell = shell

	def run(self):
		try:
			self.process = subprocess.Popen(self.command, stdout=subprocess.PIPE, shell=self.use_shell)
		except Exception as e:
			log.error("Exception running task '%s':\n%s" % (self.name, str(e)))

	def join(self):
		stdout, sterr = self.process.communicate()
		description = self.raw_command + "\n" + stdout
		returncode = self.process.returncode

		if returncode in self.exitcodes:
			state = self.exitcodes[returncode]
		else:
			state = 'unknown'

		self.events.add(service=self.name, state=state, description=description, ttl=self.ttl, tags=self.tags)

@@ -195,16 +195,61 @@
 essing%0A%0A
+# Requests, for JSONWebTask%0Aimport requests%0A%0A
 import t
@@ -964,22 +964,19 @@
 e, ttl, 
-module
+arg
 ):%0A%09%09Tas
@@ -1019,22 +1019,19 @@
 odule = 
-module
+arg
 %0A%0A%09def r
@@ -1040,16 +1040,76 @@
 (self):%0A
+%09%09# TODO: Not yet built. Needs dynamic module/class loading%0A
 %09%09pass%0A%0A
@@ -1232,16 +1232,834 @@
 tags)%0A%0A%0A
+class JSONWebTask(Task):%0A%09def __init__(self, name, ttl, arg):%0A%09%09Task.__init__(self, name, ttl)%0A%09%09self.url = arg%0A%0A%09def request(self, url, q):%0A%09%09log.debug(%22Starting web request to '%25s'%22 %25 (url))%0A%09%09resp = requests.get(url)%0A%09%09log.debug(%22Response: %25s%22 %25 (resp))%0A%09%09q.put(resp.json())%0A%0A%09def run(self):%0A%09%09self.q = multiprocessing.Queue()%0A%09%09self.proc = multiprocessing.Process(target=self.request, args=(self.url, self.q))%0A%09%09self.proc.start()%0A%0A%09def join(self):%0A%09%09log.info('JSONWebTask: reading queue...')%0A%09%09json_result = self.q.get()%0A%0A%09%09log.info('JSONWebTask: Joining process...')%0A%09%09self.proc.join()%0A%0A%09%09log.info('JSONWebTask: Processing events...')%0A%09%09for metric in json_result%5B'metrics'%5D:%0A%09%09%09self.events.add(service=metric%5B'name'%5D,%0A%09%09%09%09state=metric%5B'state'%5D,%0A%09%09%09%09metric=metric%5B'value'%5D,%0A%09%09%09%09description=%22%22,%0A%09%09%09%09ttl=self.ttl)%0A%0A%0A
 class Na
@@ -2177,23 +2177,19 @@
 e, ttl, 
-command
+arg
 , shell=
@@ -2250,23 +2250,19 @@
 mmand = 
-command
+arg
 %0A%09%09self.
@@ -2283,23 +2283,19 @@
 x.split(
-command
+arg
 )%0A%09%09self

Add JSONWebTask for requesting JSON documents in CloudKick format, and processing the results.