Module: Nagios::TimedParse

Included in:
Config, Objects, Status
Defined in:
lib/nagira/timed_parse.rb

Overview

Keep track of last parsed time and last changed time of the status/cache file to avoid parsing on each HTTP request.

Constant Summary collapse

TTL =

Set some minimum interval for re-parsing of the status file: even if file changes often, we do not want to parse it more often, then this number of seconds.

::DEFAULT[:ttl] || 0

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#last_parsedObject

Returns the value of attribute last_parsed.



58
59
60
# File 'lib/nagira/timed_parse.rb', line 58

def last_parsed
  @last_parsed
end

#parse_intervalObject

Returns the value of attribute parse_interval.



58
59
60
# File 'lib/nagira/timed_parse.rb', line 58

def parse_interval
  @parse_interval
end

Class Method Details

.included(base) ⇒ Object

Override constructor and parse method from ::Nagios::Objects or ::Nagios::Status classes, add instance variables to handle modification and parseing times of status file. Original methods are aliased:

  • initialize -> constructor

  • parse -> parse!

See also www.ruby-forum.com/topic/969161



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/nagira/timed_parse.rb', line 22

def self.included(base)
  base.class_eval do
    alias_method :parse!, :parse
    alias_method :constructor, :initialize

    # @method initialize
    # Extend current constructor with some additional data to
    # track file change time
    #
    # @param [String] file Path to status file
    # @param [Fixnum] parse_interval Number of seconds between
    #     re-parsing of the file
    def initialize(file, parse_interval=TTL)
      constructor(file)

      # Time when status file was last time parsed, set it to 0 secs
      # epoch to make sure it will be parsed
      @last_parsed = Time.at(0)

      # Last time file was changed
      @last_changed = File.mtime(@path)
      @parse_interval = parse_interval
    end


    # Extend original parse method: parse file only if it needs
    # parsing and set time of parser run to current time.
    def parse
      if need_parsing?
        parse!
        @last_parsed = Time.now
      end
    end
  end
end

Instance Method Details

#changed?Boolean

Return true if file is changed since it was parsed last time

Returns:

  • (Boolean)


65
66
67
# File 'lib/nagira/timed_parse.rb', line 65

def changed?
  self.last_changed > self.last_parsed
end

#last_changedObject



60
61
62
# File 'lib/nagira/timed_parse.rb', line 60

def last_changed
  @last_changed = File.mtime(@path)
end

#need_parsing?Boolean

Check if:

  • file changed?

  • was it parsed recently?

Returns:

  • (Boolean)


72
73
74
# File 'lib/nagira/timed_parse.rb', line 72

def need_parsing?
  changed? && ((Time.now - self.last_parsed) > @parse_interval)
end