Advertisement
phoenixdigital

Systemd Modular Input

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