Skip to content

Commit e7b001e

Browse files
author
Shakeel Mohamed
committed
Added Event & EventWriter classes, their unit test & test data
Also updated modularinput_testlib with an XML comparing function
1 parent b8f505b commit e7b001e

8 files changed

Lines changed: 380 additions & 1 deletion

File tree

‎splunklib/modularinput/event.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# Copyright 2011-2013 Splunk, Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License"): you may
4+
# not use this file except in compliance with the License. You may obtain
5+
# a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12+
# License for the specific language governing permissions and limitations
13+
# under the License.
14+
15+
import sys, time
16+
17+
try:
18+
import xml.etree.cElementTree as ET
19+
except ImportError as ie:
20+
import xml.etree.ElementTree as ET
21+
22+
try:
23+
import cStringIO as StringIO
24+
except ImportError as ie:
25+
import StringIO
26+
27+
class Event(object):
28+
"""Represents an event or fragment of an event to be written by this modular input to Splunk."""
29+
def __init__(self):
30+
self.data = None
31+
self.done = True
32+
self.host = None
33+
self.index = None
34+
self.source = None
35+
self.sourceType = None
36+
self.stanza = None
37+
self.time = None
38+
self.unbroken = True
39+
40+
def write_to(self, stream):
41+
"""Write an XML representation of self, an Event, to the given stream
42+
43+
:param stream: stream to write XML to
44+
"""
45+
if not self.data:
46+
raise ValueError("Events must have at least the data field set to be written to XML.")
47+
48+
event = ET.Element("event")
49+
if self.stanza:
50+
event.set("stanza", self.stanza)
51+
event.set("unbroken", str(int(self.unbroken)))
52+
53+
if(self.time):
54+
epoch_time = self.time
55+
else:
56+
epoch_time = time.time()
57+
58+
create_subelement(event, "time", str(epoch_time))
59+
create_subelement(event, "source", self.source)
60+
create_subelement(event, "sourceType", self.sourceType)
61+
create_subelement(event, "index", self.index)
62+
create_subelement(event, "host", self.host)
63+
create_subelement(event, "data", self.data)
64+
65+
if not self.unbroken and self.done:
66+
done = ET.SubElement(event, "done")
67+
68+
stream.write(ET.tostring(event))
69+
sys.stdout.flush()
70+
71+
def create_subelement(parent, name, text):
72+
"""Create an XML subelement with tag and text specified
73+
74+
:param parent: parent XML element
75+
:param name: name of XML node tag
76+
:param text: text to go inside <name>
77+
"""
78+
if not text:
79+
return
80+
subelement = ET.SubElement(parent, name)
81+
subelement.text = text
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Copyright 2011-2013 Splunk, Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License"): you may
4+
# not use this file except in compliance with the License. You may obtain
5+
# a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12+
# License for the specific language governing permissions and limitations
13+
# under the License.
14+
15+
from splunklib.modularinput.event import Event, ET, StringIO
16+
import sys
17+
18+
class EventWriter(object):
19+
"""EventWriter writes events and error messages to Splunk from a modular input."""
20+
def __init__(self, output = sys.stdout, error = sys.stderr):
21+
"""
22+
:param output: where to write the output, defaults to sys.stdout
23+
:param error:
24+
"""
25+
# The severities that Splunk understands for log messages from modular inputs.
26+
self.DEBUG = "DEBUG"
27+
self.INFO = "INFO"
28+
self.WARN = "WARN"
29+
self.ERROR = "ERROR"
30+
self.FATAL = "FATAL"
31+
32+
self.output_writer = output
33+
self.error_writer = error
34+
35+
self.header_written = False
36+
37+
def write_event(self, event):
38+
"""Write an Event object to Splunk.
39+
40+
:param event: an Event object
41+
"""
42+
43+
if not self.header_written:
44+
self.output_writer.write("<stream>")
45+
self.header_written = True
46+
#try:
47+
event.write_to(self.output_writer)
48+
#except ValueError as ve:
49+
#self.log(self.WARN, ve.message)
50+
51+
def log(self, severity, message):
52+
"""Log messages about the state of this modular input to Splunk. These messages will show up in Splunk's
53+
internal logs
54+
55+
:param severity: string, severity of message, see severites in __init__
56+
:param message: message to log
57+
"""
58+
59+
self.error_writer.write("%s %s\n" % (severity, message))
60+
self.error_writer.flush()
61+
62+
def write_xml_document(self, document):
63+
"""Write an ElementTree to the output stream
64+
65+
:param document: an ElementTree object
66+
"""
67+
stream = StringIO.StringIO()
68+
stream.write(ET.tostring(document, "us-ascii", "xml"))
69+
stream.flush()
70+
self.output_writer.write(stream.getvalue())
71+
self.output_writer.flush()
72+
73+
def close(self):
74+
"""Write the closing </stream> tag to make this XML well formed."""
75+
self.output_writer.write("</stream>")

‎splunklib/modularinput/modularinput_testlib.py‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,43 @@ def parse_xml_data(parentNode, childNodeTag):
4747
data[child.get("name")][param.get("name")] = parse_parameters(param)
4848
elif "item" == parentNode.tag:
4949
data[child.get("name")] = parse_parameters(child)
50-
return data
50+
return data
51+
52+
def xml_compare(expected, found):
53+
"""Checks equality of two ElementTrees
54+
55+
:param expected: an ElementTree object
56+
:param found: an ElementTree object
57+
:return: boolean, equality of expected and found
58+
"""
59+
#TODO: error handling & exception throwing
60+
61+
try:
62+
import xml.etree.cElementTree as ET
63+
except ImportError:
64+
import xml.etree.ElementTree as ET
65+
66+
# if comparing the same ET object
67+
if expected == found:
68+
return True
69+
70+
# compare element attributes, ignoring order
71+
if not set(expected.items()) == set(found.items()):
72+
return False
73+
expectedChildren = list(expected)
74+
foundChildren = list(found)
75+
if len(expectedChildren) != len(foundChildren):
76+
return False
77+
78+
# compare children
79+
for i, child in enumerate(expectedChildren):
80+
if not xml_compare(child, foundChildren[i]):
81+
return False
82+
# compare element text if it exists, else elements are equal
83+
if expected.text and expected.text.strip() != "":
84+
if expected.tag == found.tag and expected.text == found.text:
85+
return True
86+
else:
87+
return False
88+
else:
89+
return True
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<event stanza="fubar" unbroken="1">
2+
<time>1372274622.493</time>
3+
<source>hilda</source>
4+
<sourceType>misc</sourceType>
5+
<index>main</index>
6+
<host>localhost</host>
7+
<data>This is a test of the emergency broadcast system.</data>
8+
</event>
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<event stanza="fubar" unbroken="1">
2+
<time>1372187084.000</time>
3+
<data>This is a test of the emergency broadcast system.</data>
4+
</event>
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<stream>
2+
<event stanza="fubar" unbroken="1">
3+
<time>1372275124.466</time>
4+
<source>hilda</source>
5+
<sourceType>misc</sourceType>
6+
<index>main</index>
7+
<host>localhost</host>
8+
<data>This is a test of the emergency broadcast system.</data>
9+
</event>
10+
</stream>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<stream>
2+
<event stanza="fubar" unbroken="1">
3+
<time>1372275124.466</time>
4+
<source>hilda</source>
5+
<sourceType>misc</sourceType>
6+
<index>main</index>
7+
<host>localhost</host>
8+
<data>This is a test of the emergency broadcast system.</data>
9+
</event>
10+
<event stanza="fubar" unbroken="1">
11+
<time>1372275124.466</time>
12+
<source>hilda</source>
13+
<sourceType>misc</sourceType>
14+
<index>main</index>
15+
<host>localhost</host>
16+
<data>This is a test of the emergency broadcast system.</data>
17+
</event>
18+
</stream>

0 commit comments

Comments
 (0)