Skip to content

Commit 462aba6

Browse files
author
Shakeel Mohamed
committed
General code cleanup
1 parent aded811 commit 462aba6

File tree

13 files changed

+84
-78
lines changed

13 files changed

+84
-78
lines changed

splunklib/modularinput/argument.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,13 @@ class Argument(object):
4141
)
4242
"""
4343

44-
# Constant values, do not change
44+
# Constant values, do not change.
45+
# These should be used for setting the value of an Argument object's data_type field.
4546
data_type_boolean = "BOOLEAN"
4647
data_type_number = "NUMBER"
4748
data_type_string = "STRING"
4849

49-
def __init__(self, name, description=None, validation=None, \
50+
def __init__(self, name, description=None, validation=None,
5051
data_type=data_type_string, required_on_edit=False, required_on_create=False):
5152
"""
5253
:param name: string, identifier for this argument in Splunk

splunklib/modularinput/event.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class Event(object):
2222
2323
To write an input to a stream, call the write_to function, passing in a stream.
2424
"""
25-
def __init__(self, data=None, stanza=None, time=None, host=None, index=None, source=None,\
25+
def __init__(self, data=None, stanza=None, time=None, host=None, index=None, source=None,
2626
sourceType=None, done=True, unbroken=True):
2727
"""There are no required parameters for constructing an Event
2828
@@ -71,7 +71,8 @@ def __init__(self, data=None, stanza=None, time=None, host=None, index=None, sou
7171
def write_to(self, stream):
7272
"""Write an XML representation of self, an Event object, to the given stream
7373
74-
The Event object will only be written if its data field is defined
74+
The Event object will only be written if its data field is defined,
75+
else a ValueError is raised.
7576
7677
:param stream: stream to write XML to
7778
"""
@@ -96,10 +97,10 @@ def write_to(self, stream):
9697
("data", self.data)
9798
]
9899
for node, value in subelements:
99-
if value:
100+
if value is not None:
100101
ET.SubElement(event, node).text = value
101102

102-
if self.done:
103+
if self.done is not None:
103104
ET.SubElement(event, "done")
104105

105106
stream.write(ET.tostring(event))

splunklib/modularinput/event_writer.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# License for the specific language governing permissions and limitations
1313
# under the License.
1414

15-
from splunklib.modularinput.event import Event, ET
15+
from splunklib.modularinput.event import ET
1616
import sys
1717

1818
try:
@@ -48,9 +48,6 @@ def __init__(self, output = sys.stdout, error = sys.stderr):
4848

4949
def write_event(self, event):
5050
"""Write an Event object to Splunk.
51-
If the opening <stream> tag hasn't been written,
52-
write it & set header_written to True
53-
Then, write the event.
5451
5552
:param event: an Event object
5653
"""

splunklib/modularinput/input_definition.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,13 @@ def __init__ (self):
2929
self.metadata = {}
3030
self.inputs = {}
3131

32-
3332
def __eq__(self, other):
3433
if not isinstance(other, InputDefinition):
3534
return False
3635
return self.metadata == other.metadata and self.inputs == other.inputs
3736

38-
def parse_input_definition(stream):
37+
@staticmethod
38+
def parse_input_definition(stream):
3939
"""Parse a stream containing XML into an InputDefinition.
4040
4141
:param stream: stream containing XML to parse

splunklib/modularinput/scheme.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ class Scheme(object):
2727
"""
2828

2929
# Constant values, do not change
30+
# These should be used for setting the value of a Scheme object's streaming_mode field.
3031
streaming_mode_simple = "SIMPLE"
3132
streaming_mode_xml = "XML"
3233

@@ -50,7 +51,7 @@ def add_argument(self, arg):
5051
"""
5152
self.arguments.append(arg)
5253

53-
def to_XML(self):
54+
def to_xml(self):
5455
"""Creates an ET.Element representing self, then returns it
5556
5657
:return root, an ET.Element representing this scheme
@@ -63,10 +64,14 @@ def to_XML(self):
6364
if self.description is not None:
6465
ET.SubElement(root, "description").text = self.description
6566

66-
# add other subelements
67-
ET.SubElement(root, "use_external_validation").text = str(self.use_external_validation).lower()
68-
ET.SubElement(root, "use_single_instance").text = str(self.use_single_instance).lower()
69-
ET.SubElement(root, "streaming_mode").text = self.streaming_mode.lower()
67+
# add other subelements; represented by (tag, text)
68+
subelements = [
69+
("use_external_validation", str(self.use_external_validation).lower()),
70+
("use_single_instance", str(self.use_single_instance).lower()),
71+
("streaming_mode", self.streaming_mode.lower())
72+
]
73+
for name, value in subelements:
74+
ET.SubElement(root, name).text = value
7075

7176
endpoint = ET.SubElement(root, "endpoint")
7277

splunklib/modularinput/script.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,10 @@
1313
# under the License.
1414

1515
from abc import ABCMeta, abstractmethod
16-
import sys
17-
from splunklib.modularinput.input_definition import InputDefinition, parse_input_definition
18-
from splunklib.modularinput.validation_definition import ValidationDefinition, parse_validation_definition
16+
from splunklib.modularinput.input_definition import InputDefinition
17+
from splunklib.modularinput.validation_definition import ValidationDefinition
1918
from splunklib.modularinput.event_writer import EventWriter
20-
from splunklib.modularinput.scheme import Scheme
19+
import sys
2120

2221
try:
2322
import xml.etree.cElementTree as ET
@@ -28,12 +27,11 @@
2827
class Script(object):
2928
"""An abstract base class for implementing modular inputs.
3029
31-
Subclasses should override getScheme, StreamEvents,
32-
and optional configureValidator if the modular Input uses
30+
Subclasses should override get_scheme, stream_events,
31+
and optional validate_input if the modular Input uses
3332
external validation.
3433
3534
The important function is run, which is used to run modular inputs
36-
3735
"""
3836
__metaclass__ = ABCMeta
3937

@@ -58,7 +56,7 @@ def run_script(self, args, event_writer, input_stream):
5856
if len(args) == 0:
5957
# This script is running as an input. Input definitions will be passed on stdin
6058
# as XML, and the script will write events on stdout and log entries on stderr.
61-
input_definition = parse_input_definition(input_stream)
59+
input_definition = InputDefinition.parse_input_definition(input_stream)
6260
self.stream_events(input_definition, event_writer)
6361
event_writer.close()
6462
return 0
@@ -71,11 +69,11 @@ def run_script(self, args, event_writer, input_stream):
7169
event_writer.log(EventWriter.FATAL, "Modular input script returned a null scheme.")
7270
return 1
7371
else:
74-
event_writer.write_xml_document(scheme.to_XML())
72+
event_writer.write_xml_document(scheme.to_xml())
7573
return 0
7674

7775
elif args[0].lower() == "--validate-arguments":
78-
validation_definition = parse_validation_definition(input_stream)
76+
validation_definition = ValidationDefinition.parse_validation_definition(input_stream)
7977
try:
8078
self.validate_input(validation_definition)
8179
return 0

splunklib/modularinput/utils.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,21 +41,23 @@ def xml_compare(expected, found):
4141
return False
4242

4343
# compare elements, if there is no text node, return True
44-
if (expected.text is None or expected.text.strip() == "") and (found.text is None or found.text.strip() == ""):
44+
if (expected.text is None or expected.text.strip() == "") \
45+
and (found.text is None or found.text.strip() == ""):
4546
return True
4647
else:
47-
return expected.tag == found.tag and expected.text == found.text and expected.attrib == found.attrib
48+
return expected.tag == found.tag and expected.text == found.text \
49+
and expected.attrib == found.attrib
4850

49-
def parse_parameters(paramNode):
50-
if paramNode.tag == "param":
51-
return paramNode.text
52-
elif paramNode.tag == "param_list":
51+
def parse_parameters(param_node):
52+
if param_node.tag == "param":
53+
return param_node.text
54+
elif param_node.tag == "param_list":
5355
parameters = []
54-
for mvp in paramNode:
56+
for mvp in param_node:
5557
parameters.append(mvp.text)
5658
return parameters
5759
else:
58-
raise ValueError("Invalid configuration scheme, %s tag unexpected." % paramNode.tag)
60+
raise ValueError("Invalid configuration scheme, %s tag unexpected." % param_node.tag)
5961

6062
def parse_xml_data(parent_node, child_node_tag):
6163
data = {}

splunklib/modularinput/validation_definition.py

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -35,43 +35,44 @@ def __eq__(self, other):
3535
return False
3636
return self.metadata == other.metadata and self.parameters == other.parameters
3737

38-
def parse_validation_definition(stream):
39-
"""Creates a ValidationDefinition from a provided stream containing XML.
38+
@staticmethod
39+
def parse_validation_definition(stream):
40+
"""Creates a ValidationDefinition from a provided stream containing XML.
4041
41-
The XML typically will look like
42+
The XML typically will look like
4243
43-
<items>
44-
<server_host>myHost</server_host>
45-
<server_uri>https://127.0.0.1:8089</server_uri>
46-
<session_key>123102983109283019283</session_key>
47-
<checkpoint_dir>/opt/splunk/var/lib/splunk/modinputs</checkpoint_dir>
48-
<item name="myScheme">
49-
<param name="param1">value1</param>
50-
<param_list name="param2">
51-
<value>value2</value>
52-
<value>value3</value>
53-
<value>value4</value>
54-
</param_list>
55-
</item>
56-
</items>
44+
<items>
45+
<server_host>myHost</server_host>
46+
<server_uri>https://127.0.0.1:8089</server_uri>
47+
<session_key>123102983109283019283</session_key>
48+
<checkpoint_dir>/opt/splunk/var/lib/splunk/modinputs</checkpoint_dir>
49+
<item name="myScheme">
50+
<param name="param1">value1</param>
51+
<param_list name="param2">
52+
<value>value2</value>
53+
<value>value3</value>
54+
<value>value4</value>
55+
</param_list>
56+
</item>
57+
</items>
5758
58-
:param stream: stream containing XML to parse
59-
:return definition: a ValidationDefinition object
60-
"""
59+
:param stream: stream containing XML to parse
60+
:return definition: a ValidationDefinition object
61+
"""
6162

62-
definition = ValidationDefinition()
63+
definition = ValidationDefinition()
6364

64-
# parse XML from the stream, then get the root node
65-
root = ET.parse(stream).getroot()
65+
# parse XML from the stream, then get the root node
66+
root = ET.parse(stream).getroot()
6667

67-
for node in root:
68-
# lone item node
69-
if node.tag == "item":
70-
# name from item node
71-
definition.metadata["name"] = node.get("name")
72-
definition.parameters = parse_xml_data(node, "")
73-
else:
74-
# Store anything else in metadata
75-
definition.metadata[node.tag] = node.text
68+
for node in root:
69+
# lone item node
70+
if node.tag == "item":
71+
# name from item node
72+
definition.metadata["name"] = node.get("name")
73+
definition.parameters = parse_xml_data(node, "")
74+
else:
75+
# Store anything else in metadata
76+
definition.metadata[node.tag] = node.text
7677

77-
return definition
78+
return definition

tests/modularinput/test_event.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def test_logging_errors_with_event_writer(self):
135135
self.assertEqual("ERROR Something happened!\n", err.getvalue())
136136

137137
def test_write_xml_is_sane(self):
138-
"""Check that EventWriter.writeXmlDocument writes sensible
138+
"""Check that EventWriter.write_xml_document writes sensible
139139
XML to the output stream."""
140140
out = StringIO()
141141
err = StringIO()

tests/modularinput/test_input_definition.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@
1515
# under the License.
1616

1717
from tests.modularinput.modularinput_testlib import unittest
18-
from splunklib.modularinput.input_definition import InputDefinition, parse_input_definition
18+
from splunklib.modularinput.input_definition import InputDefinition
1919

2020
class InputDefinitionTestCase(unittest.TestCase):
2121

2222
def test_parse_inputdef_with_zero_inputs(self):
2323
"""Check parsing of XML that contains only metadata"""
2424

25-
found = parse_input_definition(open("data/conf_with_0_inputs.xml"))
25+
found = InputDefinition.parse_input_definition(open("data/conf_with_0_inputs.xml"))
2626

2727
expectedDefinition = InputDefinition()
2828
expectedDefinition.metadata = {
@@ -37,7 +37,7 @@ def test_parse_inputdef_with_zero_inputs(self):
3737
def test_parse_inputdef_with_two_inputs(self):
3838
"""Check parsing of XML that contains 2 inputs"""
3939

40-
found = parse_input_definition(open("data/conf_with_2_inputs.xml"))
40+
found = InputDefinition.parse_input_definition(open("data/conf_with_2_inputs.xml"))
4141

4242
expectedDefinition = InputDefinition()
4343
expectedDefinition.metadata = {
@@ -67,7 +67,7 @@ def test_attempt_to_parse_malformed_input_definition_will_throw_exception(self):
6767
"""Does malformed XML cause the expected exception."""
6868

6969
with self.assertRaises(ValueError):
70-
found = parse_input_definition(open("data/conf_with_invalid_inputs.xml"))
70+
found = InputDefinition.parse_input_definition(open("data/conf_with_invalid_inputs.xml"))
7171

7272
if __name__ == "__main__":
7373
unittest.main()

0 commit comments

Comments
 (0)