-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdummyprobe.py
369 lines (332 loc) · 14.3 KB
/
dummyprobe.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
from __future__ import with_statement
import os.path
import threading
from java.lang import Thread as JThread
import sys
import logging
from logging.config import fileConfig
import time
import datetime
import re
from java.util.concurrent import Callable
import org.joda.time.DateTime as DateTime
import com.xhaus.jyson.JysonCodec as json
import traceback
logger = logging.getLogger(__name__)
class DummyProbe(Callable):
def __init__(self, input, output):
self.regexTransform = re.compile("(?P<token>\$[A-Za-z]+\.[a-zA-Z0-9_]+)")
self.input = input
self.output = output
self.openfiles = {}
self.outplugin = {}
self.runtime = {}
self.started = None
self.completed = None
self.result = None
self.thread_used = None
self.exception = None
self.datasource = None
self.running = False
try:
self.interval = int(input["interval"])
except:
self.interval = 60
self.runtime["jodaStart"] = DateTime()
self.runtime["jodaEnd"] = DateTime()
self.cycle = {
"start": self.runtime["jodaStart"].getMillis(),
"laststart": self.runtime["jodaStart"].getMillis(),
"laststartdt": str(self.runtime["jodaEnd"]),
"end": self.runtime["jodaStart"].getMillis(),
"elapsed": 0,
"startdt": str(self.runtime["jodaEnd"]),
"enddt": str(self.runtime["jodaEnd"]),
"numCycles": 0,
"badCycles": 0,
"goodCycles": 0,
}
def __str__(self):
if self.exception:
return "[%s] %s DummyProbe error %s in %.2fs" % \
(self.thread_used, self.input, self.exception,
self.completed - self.started, ) #, self.result)
elif self.completed:
return "[%s] executed" % \
(self.thread_used) #, self.result)
elif self.started:
return "[%s] %s started at %s" % \
(self.thread_used, self.input, self.started)
else:
return "[%s] %s not yet scheduled" % \
(self.thread_used, self.input)
def getClassByName(self, 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)
def outputInitialize(self, output):
if output not in self.outplugin: #It's been initialized
configuration = self.output[output].copy()
self.outplugin[output] = {}
self.outplugin[output]["config"] = configuration
module = configuration['outputmodule']['module']
name = configuration['outputmodule']['name']
outputmodule = __import__(module, globals(), locals(), [''], -1)
outputclass = self.getClassByName(outputmodule, name)
self.outplugin[output]["object"] = outputclass
outputInstance = self.outplugin[output]["object"](configuration)
self.outplugin[output]["instance"] = outputInstance
if "codec" not in configuration:
self.outplugin[output]["codec"] = "plain"
else:
logger.debug("Already initialized output %s", output)
return True
def outputWriteDocument(self, output, data, force):
if self.getInputProperty("transform") != None:
matches = re.findall(self.regexTransform, self.getInputProperty("transform"))
if matches:
out = self.getInputProperty("transform")
for match in matches:
substitution = None
(dictionary,key) = match.split(".")
if dictionary == "$cycle":
substitution = self.getCycleProperty(key)
if dictionary == "$config":
substitution = self.getInputProperty(key)
if dictionary == "$data":
if key in data:
substitution = data[key]
else:
logger.warning("Found no key named \"%s\" in %s, your data was discarded", key, dictionary)
logger.warning(data)
return None
if substitution == None:
logger.warning("Found no value for %s.%s, your data was discarded", dictionary, key)
logger.warning(data)
return None
out = out.replace(str(match), str(substitution))
data = out
if "codec" in self.outplugin[output]["config"]:
codec = self.outplugin[output]["config"]["codec"]
if codec == "json_lines":
data = json.dumps(data).encode('UTF-8')
return self.outplugin[output]["instance"].writeDocument(data, force)
def evaluateCycleExpression(self, expression, data):
matches = re.findall(self.regexTransform, expression)
out = expression
if matches:
for match in matches:
substitution = None
(dictionary,key) = match.split(".")
if dictionary == "$cycle":
substitution = self.getCycleProperty(key)
if dictionary == "$config":
substitution = self.getInputProperty(key)
if dictionary == "$data":
if key in data:
substitution = data[key]
if substitution != None:
out = out.replace(str(match), str(substitution))
return out
def outputFlush(self, output):
return self.outplugin[output]["instance"].flush()
def outputCleanup(self, output):
self.outplugin[output]["instance"].cleanup()
self.outplugin[output] = {}
return True
def startOutput(self):
for output in self.output:
if "outputmodule" in self.output[output]:
outputType = "plugin"
else:
logger.warning("No \"outputmodule\" configured. If you're not using stdout or file outputs, you may have a bad configuration.")
outputType = self.output[output]["class"]
if outputType == "plugin":
return self.outputInitialize(output)
if outputType == "file":
filename = self.output[output]["filename"]
self.openfiles[filename] = open(filename, 'ab')
def stopOutput(self):
for output in self.output:
if "outputmodule" in self.output[output]:
outputType = "plugin"
else:
outputType = self.output[output]["class"]
#TODO: review this, decoupling messed this class somewhat
if outputType == "plugin":
self.outputFlush(output)
if outputType == "file":
filename = self.output[output]["filename"]
self.openfiles[filename].close()
def processData(self, data):
logger.debug(data)
if (self.getInputProperty("messageTemplate") != None):
template = self.getInputProperty("messageTemplate")
for key in template:
data[key] = self.evaluateCycleExpression(template[key], data)
for output in self.output:
if (self.getOutputProperty(output, "messageTemplate") != None):
template = self.getOutputProperty(output, "messageTemplate")
for key in template:
data[key] = self.evaluateCycleExpression(template[key], data)
if "outputmodule" in self.output[output]:
outputType = "plugin"
else:
outputType = self.output[output]["class"]
#TODO: deal with ommited fields
if outputType == "plugin":
self.outputWriteDocument(output, data, False)
if outputType == "stdout":
codec = self.output[output]["codec"]
if codec == "json_lines":
print(json.dumps(data))
else:
print(data)
if outputType == "file":
codec = self.output[output]["codec"]
if codec == "json_lines":
filename = self.output[output]["filename"]
self.openfiles[filename].write(json.dumps(data).encode('UTF-8'))
self.openfiles[filename].write("\n")
def startCycle(self):
self.cycle["numCycles"] += 1
self.runtime["jodaStart"] = DateTime()
self.cycle["start"] = self.runtime["jodaStart"].getMillis()
self.cycle["startdt"] = str(self.runtime["jodaStart"])
logger.info("Started cycle at %s", self.cycle["startdt"])
def now(self):
return DateTime().getMillis()
def nowDt(self):
return str(DateTime())
def finishCycle(self):
self.runtime["jodaEnd"] = DateTime()
self.cycle["end"] = self.runtime["jodaEnd"].getMillis()
self.cycle["enddt"] = str(self.runtime["jodaEnd"])
self.cycle["laststart"] = self.cycle["start"]
self.cycle["laststartdt"] = self.cycle["startdt"]
self.cycle["elapsed"] = self.runtime["jodaEnd"].getMillis() - self.cycle["start"]
logger.info("Finished cycle at %s", self.cycle["enddt"])
def tick(self):
self.processData({ "time": time.time() })
def initialize(self):
logger.info("Initializing probe before cycling")
def cleanup(self):
logger.info("Cleaning up after cycling")
for output in self.output:
if "outputmodule" in self.output[output]:
outputType = "plugin"
else:
outputType = self.output[output]["class"]
if outputType == "plugin":
self.outputCleanup(output)
def getCycleProperty(self, name):
if name in self.cycle:
return self.cycle[name]
else:
return None
def getInputProperty(self, name):
if name in self.input:
return self.input[name]
else:
return None
def setInputProperty(self, name, value):
self.input[name] = value
def getOutputProperty(self, output, name):
if name in self.output[output]:
return self.output[output][name]
else:
return None
def setOutputProperty(self, output, name, value):
self.output[output][name] = value
def getRuntimeProperty(self, name):
if name in self.runtime:
return self.runtime[name]
else:
return None
def setRuntimeProperty(self, name, value):
self.runtime[name] = value
def saveCycleState(self):
storeCycleState = self.getInputProperty("storeCycleState")
if storeCycleState == None:
return False
elif "enabled" in storeCycleState and storeCycleState["enabled"] == True:
if "filename" in storeCycleState:
configurationFile = storeCycleState["filename"]
else:
configurationFile = "probespawnerDB.json"
logger.info("Saving cycle state to file %s", configurationFile)
json_data = json.dumps(self.cycle)
try:
with open(configurationFile, "w") as data_file:
data_file.write(json_data)
except Exception, ex:
logger.warning("Unable to write cycle state to file %s", configurationFile)
return True
def loadCycleState(self):
storeCycleState = self.getInputProperty("storeCycleState")
if storeCycleState != None and "enabled" in storeCycleState and storeCycleState["enabled"] == True:
if "filename" in storeCycleState:
configurationFile = storeCycleState["filename"]
else:
configurationFile = "probespawnerDB.json"
logger.info("Loading cycle state from file %s", configurationFile)
try:
with open(configurationFile) as data_file:
json_string = data_file.read()
self.cycle = json.loads(json_string)
self.cycle["numCycles"] = 0
except Exception, ex:
logger.warning("Unable to read cycle state from file %s", configurationFile)
# needed to implement the Callable interface;
# any exceptions will be wrapped as either ExecutionException
# or InterruptedException
def call(self):
if self.getInputProperty("description"):
JThread.currentThread().setName(self.getInputProperty("description"))
else:
JThread.currentThread().setName(__name__)
self.thread_used = threading.currentThread().getName()
self.started = time.time()
self.running = True
self.initialize()
self.loadCycleState()
while self.running:
try:
self.startCycle()
self.startOutput()
self.tick()
self.stopOutput()
# cycle catcher
except Exception, ex:
traceback.print_exc()
self.exception = ex
logger.error(ex)
self.running = False
self.completed = time.time()
#TODO: remember finally
self.finishCycle()
self.saveCycleState()
sleepTime = self.interval - self.cycle["elapsed"] / 1000
if "maxCycles" in self.input and self.cycle["numCycles"] >= self.input["maxCycles"]:
logger.info("Max cycles reached %d", self.cycle["numCycles"])
sleepTime = 0
self.running = False
if (sleepTime < 0):
sleepTime = 0
logger.info("End of cycle: sleeping for %d seconds", sleepTime)
time.sleep(sleepTime);
#TODO: cleanup, make sure outputs have closed and whatnot
self.cleanup()
self.completed = time.time()
return self