Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
mvsum for splunk
# put this in $SPLUNK_HOME/etc/apps/search/local/commands.conf
[mvsum]
filename = mvsum.py
streaming = true
retainsevents = true
supports_multivalues = true
supports_getinfo = true
# save this as $SPLUNK_HOME/etc/apps/search/bin/mvsum.py
# make sure to chmod it to be executable
# Sums multi-valued fields within a single result.
# Usage:
# | mvsum response_time as total_response_time
# where "response_time" is a multi-valued numeric field.
import splunk.Intersplunk as si
import sys
import exceptions
def num(s):
try:
return int(s)
except exceptions.ValueError:
return float(s)
isgetinfo, sys.argv = si.isGetInfo(sys.argv)
keywords, options = si.getKeywordsAndOptions()
if len(keywords) != 3 or keywords[1] != "as":
si.parseError("Invalid syntax. Syntax is: mvsum input-field as output-field")
if isgetinfo:
# outputInfo automatically calls sys.exit()
si.outputInfo(True, False, True, False, None, False)
try:
input_field = keywords[0]
output_field = keywords[2]
results, dummyresults, settings = si.getOrganizedResults()
for result in results:
if input_field in result:
field_value = result[input_field]
if field_value:
if isinstance(field_value, list):
nums = [num(x) for x in field_value]
result[output_field] = str(sum(nums))
else:
result[output_field] = int(field_value)
except:
import traceback
stack = traceback.format_exc()
results = si.generateErrorResults("Error : Traceback: " + str(stack))
si.outputResults(results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment