-
Notifications
You must be signed in to change notification settings - Fork 1
/
probespawner.py
137 lines (121 loc) · 4.15 KB
/
probespawner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
from __future__ import with_statement
from pprint import pprint
#from databaseprobe import DatabaseProbe
from threading import Thread
from java.lang import Thread as JThread, InterruptedException
from java.util.concurrent import ExecutionException
from java.util.concurrent import Executors, TimeUnit
from java.util.concurrent import Executors, ExecutorCompletionService
from time import sleep
import time
import datetime
import getopt, sys
import traceback
import com.xhaus.jyson.JysonCodec as json
import sys
import logging
from logging.config import fileConfig
fileConfig('probespawner.ini')
logger = logging.getLogger(__name__)
configurationLiterals = ["verbose", "help", "configuration="];
configurationHelp = ["Increase verbosity of messages", "Display help", "JSON configuration file"];
configurationFile = "some.feeder.config.json";
probeListStr = "databaseprobe.py,jmxprobe.py";
json_string = "theres is no JSON"
def usage():
print "USAGE:"
for index in range(len(configurationLiterals)):
print " --" + configurationLiterals[index] + " : " + configurationHelp[index];
def shutdown_and_await_termination(pool, timeout):
pool.shutdown()
try:
if not pool.awaitTermination(timeout, TimeUnit.SECONDS):
pool.shutdownNow()
if (not pool.awaitTermination(timeout, TimeUnit.SECONDS)):
print >> sys.stderr, "Pool did not terminate"
except InterruptedException, ex:
# (Re-)Cancel if current thread also interrupted
pool.shutdownNow()
# Preserve interrupt status
Thread.currentThread().interrupt()
try:
opts, args = getopt.getopt(sys.argv[1:], "vhc:", configurationLiterals)
except getopt.GetoptError, err:
print str(err)
usage()
sys.exit(2)
for o, a in opts:
if o == "-v":
verbose = True
if o in ("-h", "--help"):
usage()
elif o in ("-c", "--configuration"):
configurationFile = a
#TODO: split and load libs
else:
assert False, "Unknown option"
try:
with open(configurationFile) as data_file:
json_string = data_file.read()
except EnvironmentError, err:
print str(err)
usage()
sys.exit(3)
try:
config = json.loads(json_string.decode('utf-8'))
except:
print "JSON from file '" + configurationFile + "' is malformed."
e = sys.exc_info()[0]
print str(e)
sys.exit(4)
pool = Executors.newFixedThreadPool(len(config["input"]))
ecs = ExecutorCompletionService(pool)
def scheduler(roots):
for inputConfig in roots:
yield inputConfig
def getClassByName(module, className):
if not module:
if className.startswith("services."):
className = className.split("services.")[1]
l = className.split(".")
m = __services__[l[0]]
return getClassByName(m, ".".join(l[1:]))
elif "." in className:
l = className.split(".")
m = getattr(module, l[0])
return getClassByName(m, ".".join(l[1:]))
else:
return getattr(module, className)
for inputConfig in scheduler(config["input"]):
outputs = {}
for output in config[inputConfig]["output"]:
outputs[output] = config[output]
module = config[inputConfig]['probemodule']['module']
name = config[inputConfig]['probemodule']['name']
#TODO: consider input singletons
#from config[inputConfig]['probemodule']['module'] import config[inputConfig]['probemodule']['name']
probemodule = __import__(module, globals(), locals(), [''], -1)
probeclass = getClassByName(probemodule, name)
config[inputConfig]["__inputname__"] = inputConfig
obj = probeclass(config[inputConfig], outputs)
ecs.submit(obj)
workingProbes = len(config["input"])
#TODO: handle signals for stopping, thread exits, etc.
while workingProbes > 0:
result = "No result"
try:
result = ecs.take().get()
except InterruptedException, ex:
traceback.print_exc()
pprint(ex)
except ExecutionException, ex:
traceback.print_exc()
pprint(ex)
print result
workingProbes -= 1
print "shutting threadpool down..."
shutdown_and_await_termination(pool, 5)
print "done"
sys.exit(1)