Advertisement
phoenixdigital

Splunk Single Instance Modular Input

Oct 15th, 2014
508
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.32 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2013 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. import random, sys, time
  18. import datetime
  19.  
  20. from splunklib.modularinput import *
  21.  
  22. class MyScript(Script):
  23.     """All modular inputs should inherit from the abstract base class Script
  24.     from splunklib.modularinput.script.
  25.     They must override the get_scheme and stream_events functions, and,
  26.     if the scheme returned by get_scheme has Scheme.use_external_validation
  27.     set to True, the validate_input function.
  28.     """
  29.     def get_scheme(self):
  30.         """When Splunk starts, it looks for all the modular inputs defined by
  31.         its configuration, and tries to run them with the argument --scheme.
  32.         Splunkd expects the modular inputs to print a description of the
  33.         input in XML on stdout. The modular input framework takes care of all
  34.         the details of formatting XML and printing it. The user need only
  35.         override get_scheme and return a new Scheme object.
  36.  
  37.         :return: scheme, a Scheme object
  38.         """
  39.         # "random_numbers" is the name Splunk will display to users for this input.
  40.         scheme = Scheme("Random Numbers")
  41.  
  42.         scheme.description = "Streams events containing a random number."
  43.         # If you set external validation to True, without overriding validate_input,
  44.         # the script will accept anything as valid. Generally you only need external
  45.         # validation if there are relationships you must maintain among the
  46.         # parameters, such as requiring min to be less than max in this example,
  47.         # or you need to check that some resource is reachable or valid.
  48.         # Otherwise, Splunk lets you specify a validation string for each argument
  49.         # and will run validation internally using that string.
  50.         scheme.use_external_validation = True
  51.         scheme.use_single_instance = True
  52.  
  53.         min_argument = Argument("min")
  54.         min_argument.data_type = Argument.data_type_number
  55.         min_argument.description = "Minimum random number to be produced by this input."
  56.         min_argument.required_on_create = True
  57.         # If you are not using external validation, you would add something like:
  58.         #
  59.         # scheme.validation = "min > 0"
  60.         scheme.add_argument(min_argument)
  61.  
  62.         max_argument = Argument("max")
  63.         max_argument.data_type = Argument.data_type_number
  64.         max_argument.description = "Maximum random number to be produced by this input."
  65.         max_argument.required_on_create = True
  66.         scheme.add_argument(max_argument)
  67.  
  68.         interval_argument = Argument("interval")
  69.         interval_argument.data_type = Argument.data_type_number
  70.         interval_argument.description = "Number of seconds between random number generations."
  71.         interval_argument.required_on_create = True
  72.         scheme.add_argument(interval_argument)     
  73.  
  74.         return scheme
  75.  
  76.     def validate_input(self, validation_definition):
  77.         """In this example we are using external validation to verify that min is
  78.         less than max. If validate_input does not raise an Exception, the input is
  79.         assumed to be valid. Otherwise it prints the exception as an error message
  80.         when telling splunkd that the configuration is invalid.
  81.  
  82.         When using external validation, after splunkd calls the modular input with
  83.         --scheme to get a scheme, it calls it again with --validate-arguments for
  84.         each instance of the modular input in its configuration files, feeding XML
  85.         on stdin to the modular input to do validation. It is called the same way
  86.         whenever a modular input's configuration is edited.
  87.  
  88.         :param validation_definition: a ValidationDefinition object
  89.         """
  90.         # Get the parameters from the ValidationDefinition object,
  91.         # then typecast the values as floats
  92.         minimum = float(validation_definition.parameters["min"])
  93.         maximum = float(validation_definition.parameters["max"])
  94.  
  95.         if minimum >= maximum:
  96.             raise ValueError("min must be less than max; found min=%f, max=%f" % minimum, maximum)
  97.  
  98.     def stream_events(self, inputs, ew):
  99.         """This function handles all the action: splunk calls this modular input
  100.         without arguments, streams XML describing the inputs to stdin, and waits
  101.         for XML on stdout describing events.
  102.  
  103.         If you set use_single_instance to True on the scheme in get_scheme, it
  104.         will pass all the instances of this input to a single instance of this
  105.         script.
  106.  
  107.         :param inputs: an InputDefinition object
  108.         :param ew: an EventWriter object
  109.         """
  110.  
  111.         # Keep track of when each input was last polled
  112.         time_of_last_poll = {}
  113.  
  114.         # Loop indefinitely
  115.         while 1:
  116.             time.sleep(1)
  117.  
  118.             # Keep count for debugging purposes
  119.             loopCount = 0
  120.  
  121.  
  122.             # Go through each input for this modular input
  123.             for input_name, input_item in inputs.inputs.iteritems():
  124.                
  125.                 # Check if this input has ever been polled before
  126.                 if not time_of_last_poll.has_key(input_name):
  127.                     # mark as not polled
  128.                     time_of_last_poll[input_name] = None
  129.  
  130.                 # Get the current time
  131.                 currenttime = datetime.datetime.now()
  132.                
  133.                 # Check if this input was never polled or if interval in seconds has passed since last poll of this input
  134.                 if (time_of_last_poll[input_name] == None or (currenttime - time_of_last_poll[input_name]) >= datetime.timedelta(seconds=int(input_item["interval"]))):
  135.                    
  136.                     # Get the values, for this input cast them as floats
  137.                     minimum = float(input_item["min"])
  138.                     maximum = float(input_item["max"])
  139.                     interval = float(input_item["interval"])
  140.  
  141.                     # Create an Event object, and set its data fields
  142.                     event = Event()
  143.                     event.stanza = input_name
  144.                     event.data = "number=\"%s\",interval=%d,loopCount=%d" % (str(random.uniform(minimum, maximum)),interval,loopCount)
  145.  
  146.                     # Tell the EventWriter to write this event
  147.                     ew.write_event(event)
  148. #                   ew.log('randomlog','Poll completed for input \'%s\'' % input_name)
  149.  
  150.                     # Set latest poll time for this input
  151.                     time_of_last_poll[input_name] = currenttime
  152.                
  153.                 # increment input counter
  154.                 loopCount = loopCount + 1
  155.  
  156. if __name__ == "__main__":
  157.     sys.exit(MyScript().run(sys.argv))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement