Class: VarnishPipe

Inherits:
Object
  • Object
show all
Defined in:
lib/varnish_pipe.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, regexs) ⇒ VarnishPipe

Returns a new instance of VarnishPipe.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/varnish_pipe.rb', line 6

def initialize(config, regexs)
  @stats = {
    :total_reqs => 0,
    :total_bytes => 0,
    :requests => {},
    :calls => {},
    :hitratio => {},
    :reqps => {},
    :bps => {},
  }

  @semaphore = Mutex.new
  @avg_period = config[:avg_period]
  @host_mode = config[:host_mode]
  @default_key = "other"

  @regexs = regexs
end

Instance Attribute Details

#semaphoreObject

Returns the value of attribute semaphore.



4
5
6
# File 'lib/varnish_pipe.rb', line 4

def semaphore
  @semaphore
end

#start_timeObject

Returns the value of attribute start_time.



4
5
6
# File 'lib/varnish_pipe.rb', line 4

def start_time
  @start_time
end

#statsObject

Returns the value of attribute stats.



4
5
6
# File 'lib/varnish_pipe.rb', line 4

def stats
  @stats
end

Instance Method Details

#startObject



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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/varnish_pipe.rb', line 25

def start
  @stop = false
  @start_time = Time.new.to_f
  @start_ts = @start_time.to_i

  IO.popen("varnishncsa -F '%{Host}i %U %{Varnish:hitmiss}x %b'").each_line do |line|
    if line =~ /^(\S+) (\S+) (\w+) (\d+)$/
      host, url, status, bytes = $1, $2, $3, $4
      key = nil

      if (@host_mode) 
        key = host;
      else
        @regexs.each do |k,v|
          if k.match(url)
            key = v.map{|x| "#{$~[x]}" }.join(":")
            break
          end
        end
        key = @default_key unless key
      end


      @semaphore.synchronize do
        duration = (Time.now.to_i - @start_ts)
        it = duration / @avg_period
        idx = duration % @avg_period

        @stats[:requests][key] ||= {
          :hit => Array.new(@avg_period, 0),
          :miss => Array.new(@avg_period, 0),
          :bytes => Array.new(@avg_period, 0),
          :it => Array.new(@avg_period, 0),
          :last => ""
        }

        cur_req = @stats[:requests][key]
        if cur_req[:it][idx] < it
          cur_req[status.to_sym][idx] = 0
          cur_req[:bytes][idx] = 0
        end
        cur_req[status.to_sym][idx] += 1
        cur_req[:bytes][idx] += bytes.to_i
        cur_req[:it][idx] = it
        cur_req[:last] = url
        @stats[:total_reqs] += 1
        @stats[:total_bytes] += bytes.to_i
      end
    end

    break if @stop
  end
end

#stopObject



79
80
81
# File 'lib/varnish_pipe.rb', line 79

def stop
  @stop = true
end