Skip to content

Commit cf45cd4

Browse files
author
Shakeel Mohamed
committed
Added modular input parsing classes, unit tests & unit test data
Classes: validation_definition & input_definition Tests: test_validation_definition & test_input_definition
1 parent 8a5a2ef commit cf45cd4

13 files changed

Lines changed: 658 additions & 0 deletions

‎splunklib/modularinput/__init__.py‎

Whitespace-only changes.
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# Licensed under the Apache License, Version 2.0 (the "License"): you may
2+
# not use this file except in compliance with the License. You may obtain
3+
# a copy of the License at
4+
#
5+
# http://www.apache.org/licenses/LICENSE-2.0
6+
#
7+
# Unless required by applicable law or agreed to in writing, software
8+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10+
# License for the specific language governing permissions and limitations
11+
# under the License.
12+
13+
try:
14+
import xml.etree.cElementTree as ET
15+
except ImportError as ie:
16+
import xml.etree.ElementTree as ET
17+
from malformed_data_exception import MalformedDataException
18+
19+
class InputDefinition:
20+
""" InputDefinition encodes the XML defining inputs that Splunk passes to
21+
a modular input script
22+
23+
``InputDefinition`` takes no arguments.
24+
25+
**Example**::
26+
27+
i = InputDefinition()
28+
29+
"""
30+
def __init__ (self):
31+
self.metadata = {}
32+
self.inputs = {}
33+
34+
def parseDefinition(self, stream):
35+
""" Parse a stream containing XML into an InputDefinition.
36+
37+
:param stream: stream containing XML to parse
38+
:return: definition: a InputDefinition object
39+
"""
40+
if not isinstance(stream, file):
41+
raise ValueError("Stream is invalid, cannot be parsed")
42+
try:
43+
definition = InputDefinition()
44+
45+
# read everything from the stream
46+
config_str = stream.read()
47+
48+
# parse the configuration XML
49+
root = ET.fromstring(config_str)
50+
for node in root:
51+
if node.tag == "configuration":
52+
# get config for each stanza
53+
for config_stanza in node:
54+
if config_stanza.tag == "stanza":
55+
definition.inputs[config_stanza.get("name")] = {}
56+
57+
for param in config_stanza:
58+
definition.parseParameters(param, config_stanza.get("name"))
59+
else:
60+
raise MalformedDataException, "Invalid configuration scheme, "+config_stanza.tag+" tag unexpected."
61+
else:
62+
definition.metadata[node.tag] = node.text
63+
return definition
64+
except MalformedDataException:
65+
raise
66+
except Exception, e:
67+
raise Exception, "Error getting configuration: %s" % str(e)
68+
69+
def parseParameters(self, paramNode, stanzaName):
70+
"""A helper function to clean up the code for parsing XML parameters
71+
72+
:param paramNode: XML node, it should have param or param_list tag
73+
:param stanzaName: string of the stanza name containing the node
74+
"""
75+
if paramNode.tag == "param":
76+
self.inputs[stanzaName][paramNode.get("name")] = paramNode.text
77+
elif paramNode.tag == "param_list":
78+
self.inputs[stanzaName][paramNode.get("name")] = []
79+
# multi-value parameters
80+
for mvp in paramNode:
81+
self.inputs[stanzaName][paramNode.get("name")].append(mvp.text)
82+
else:
83+
raise MalformedDataException, "Invalid configuration scheme, "+paramNode.tag+" tag unexpected."
84+
85+
86+
def __eq__(self,other):
87+
if not isinstance(other, InputDefinition):
88+
return False
89+
return self.metadata == other.metadata and self.inputs == other.inputs
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
class MalformedDataException(Exception):
16+
pass
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
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+
16+
try:
17+
import xml.etree.cElementTree as ET
18+
except ImportError as ie:
19+
import xml.etree.ElementTree as ET
20+
from malformed_data_exception import MalformedDataException
21+
22+
class ValidationDefinition(object):
23+
"""This class represents the XML sent by Splunk for external validation of a new modular input.
24+
25+
``ValidationDefinition`` takes no arguments.
26+
27+
**Example**::
28+
29+
v = ValidationDefinition()
30+
"""
31+
def __init__(self):
32+
self.metadata = {}
33+
self.parameters = {}
34+
35+
def parseDefintion(self, stream):
36+
"""Create a ValidationDefinition from a provided stream containing XML. The XML typically will look like
37+
38+
<items>
39+
<server_host>myHost</server_host>
40+
<server_uri>https://127.0.0.1:8089</server_uri>
41+
<session_key>123102983109283019283</session_key>
42+
<checkpoint_dir>/opt/splunk/var/lib/splunk/modinputs</checkpoint_dir>
43+
<item name="myScheme">
44+
<param name="param1">value1</param>
45+
<param_list name="param2">
46+
<value>value2</value>
47+
<value>value3</value>
48+
<value>value4</value>
49+
</param_list>
50+
</item>
51+
</items>
52+
:param stream: stream containing XML to parse
53+
:return definition: a ValidationDefinition object
54+
"""
55+
56+
if not isinstance(stream, file):
57+
raise ValueError("Stream is invalid, cannot be parsed")
58+
try:
59+
definition = ValidationDefinition()
60+
61+
# read everything from the stream
62+
validation_str = stream.read()
63+
64+
# parse the validation XML
65+
root = ET.fromstring(validation_str)
66+
for node in root:
67+
# lone item node
68+
if node.tag == "item":
69+
# name from item node
70+
definition.metadata["name"] = node.get("name")
71+
for param_node in node:
72+
# single value params
73+
if param_node.tag == "param":
74+
definition.parameters[param_node.get("name")] = param_node.text
75+
# multi-value params
76+
elif param_node.tag == "param_list":
77+
definition.parameters[param_node.get("name")] = []
78+
for multi_val_param in param_node:
79+
definition.parameters[param_node.get("name")].append(multi_val_param.text)
80+
else:
81+
raise MalformedDataException, "Invalid configuration scheme, "+param_node.tag+" tag unexpected."
82+
else:
83+
# Store anything else in metadata
84+
definition.metadata[node.tag] = node.text
85+
return definition
86+
except Exception, e:
87+
raise Exception, "Error getting validation definition: %s" % str(e)
88+
89+
def __eq__(self, other):
90+
"""Test the equality of self, and other by comparing metadata and parameters
91+
92+
:param other: a ValidationDefinition object
93+
:return boolean: True for equality, else False
94+
"""
95+
if not isinstance(other, ValidationDefinition):
96+
return False
97+
return self.metadata == other.metadata and self.parameters == other.parameters

‎tests/modularinput/__init__.py‎

Whitespace-only changes.
730 Bytes
Binary file not shown.
2.28 KB
Binary file not shown.
1.3 KB
Binary file not shown.
1.77 KB
Binary file not shown.
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#!/usr/bin/env python
2+
#
3+
# Copyright 2011-2012 Splunk, Inc.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License"): you may
6+
# not use this file except in compliance with the License. You may obtain
7+
# a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14+
# License for the specific language governing permissions and limitations
15+
# under the License.
16+
17+
try:
18+
import unittest
19+
except ImportError:
20+
import unittest2 as unittest
21+
import sys
22+
from splunklib.modularinput.input_definition import InputDefinition
23+
from splunklib.modularinput.malformed_data_exception import MalformedDataException
24+
sys.path.insert(0, "../..")
25+
26+
class InputDefinitionTestCase(unittest.TestCase):
27+
28+
def setUp(self):
29+
super(InputDefinitionTestCase, self).setUp()
30+
31+
def test_parse_zero_inputs(self):
32+
"""Check equality of parsed InputDefinition object from known XML
33+
with 1 input defined with manually initialized Input Definition object."""
34+
found = InputDefinition().parseDefinition(open("data/conf_with_0_inputs.xml"))
35+
36+
expectedDefinition = InputDefinition()
37+
expectedDefinition.metadata = {
38+
"server_host": "tiny",
39+
"server_uri": "https://127.0.0.1:8089",
40+
"checkpoint_dir": "/some/dir",
41+
"session_key": "123102983109283019283"
42+
}
43+
44+
self.assertEqual(found, expectedDefinition)
45+
46+
def test_parse_two_inputs(self):
47+
"""Check equality of parsed InputDefinition object from known XML
48+
with 2 inputs definedwith manually initialized Input Definition object."""
49+
found = InputDefinition().parseDefinition(open("data/conf_with_2_inputs.xml"))
50+
51+
expectedDefinition = InputDefinition()
52+
expectedDefinition.metadata = {
53+
"server_host": "tiny",
54+
"server_uri": "https://127.0.0.1:8089",
55+
"checkpoint_dir": "/some/dir",
56+
"session_key": "123102983109283019283"
57+
}
58+
expectedDefinition.inputs["foobar://aaa"] = {
59+
"param1": "value1",
60+
"param2": "value2",
61+
"disabled": "0",
62+
"index": "default"
63+
}
64+
expectedDefinition.inputs["foobar://bbb"] = {
65+
"param1": "value11",
66+
"param2": "value22",
67+
"disabled": "0",
68+
"index": "default",
69+
"multiValue": ["value1", "value2"],
70+
"multiValue2": ["value3", "value4"]
71+
}
72+
73+
self.assertEqual(expectedDefinition, found)
74+
75+
76+
def test_parse_malformed_input_definition(self):
77+
"""Check that parsing an InputDefinition from malformed XML produces the expected exception."""
78+
with self.assertRaises(MalformedDataException):
79+
found = InputDefinition().parseDefinition(open("data/conf_with_invalid_inputs.xml"))
80+
81+
82+
if __name__ == "__main__":
83+
try:
84+
import unittest2 as unittest
85+
except ImportError:
86+
import unittest
87+
unittest.main()

0 commit comments

Comments
 (0)