-
Notifications
You must be signed in to change notification settings - Fork 3
/
varnish_statsd_send.py
executable file
·178 lines (143 loc) · 6.53 KB
/
varnish_statsd_send.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python
#
# Charlie Schluting <[email protected]>
#
### Running: ./varnish_statsd_send.py /path/to/logfile [--stdin] [--cluster] [--environment]
###
### Use inotify to tail logfile (argv[1]) for varnish data which we'll
### assume has the following format:
# varnishncsa -F '%U %{Varnish:time_firstbyte}x %{X-Request-Backend}o %{Varnish:hitmiss}x'
### e.g. "/path/foo.gif 0.000345 foo hit"
###
### Can also be used to log HTTP response codes, but we currently do that by other means.
import sys
import os
import pyinotify
import kruxstatsd
from optparse import OptionParser
from pprint import PrettyPrinter
# function to take input from varnish, and parse into request_time and
# /path (top-level only)
def convert_input_to_keys(data):
# checking for malformed data
if len(data) < 4:
sys.stderr.write("malformed line: %s\n" % data)
return(None)
# unpack the data
path, request_time, backend, hitmiss = data
# we set X-Request-Backend to 'nonematch' if there was no backend (or synthetic response) to send it to
# this avoids creating infinite metrics in graphite for /randomURIs that hit us.
if 'nonematch' in backend:
path = 'catchall'
# clean up the path
path = path.rstrip('/').lstrip('/').replace('.', '_')
if '/' in path:
parts = path.split('/')
endpoint_top_level = parts[0]
else:
endpoint_top_level = path
request_time = int(float(request_time) * 1000000)
return request_time, endpoint_top_level, hitmiss
# function to call, which shoves the stat in statsd via the kruxstatsd library.
def run(varnish_says, k):
data = None
if not varnish_says:
sys.stdout.write("got to run(), with no data!\n")
else:
data = convert_input_to_keys(varnish_says.split())
if not data:
return
request_time, endpoint_top_level, hitmiss = data
k.timing(endpoint_top_level + '.request_time', request_time)
k.incr(endpoint_top_level + '.' + hitmiss) # log a counter for req/s, too
k.incr("_total_cluster_requests") # also, log a hit for cluster-level req/s!
return
if __name__ == '__main__':
# parse some options!
parser = OptionParser()
parser.add_option( "--cluster", dest="cluster_name", default="ungrouped",
help="The cluster_name stats will be grouped in" ),
parser.add_option( "--environment", dest="environment",
default=os.environ.get('KRUX_ENVIRONMENT', 'prototype'),
help="The (krux) environment the script is running in" ),
parser.add_option("--stdin", dest="stdin", action="store_true",
help="Instead of tailing a log file, read from stdin",)
(options, args) = parser.parse_args()
# this defines the graphite metric. e.g. timers.httpd.logger-b....
stat_name = 'httpd.' + options.cluster_name
k = kruxstatsd.StatsClient(stat_name, env=options.environment)
# now, read what varnish sent from stdin, forever:
if options.stdin:
for varnish_says in sys.stdin:
run(varnish_says, k)
# else, from a file using inotify, if --stdin wasn't used.
else:
myfile = args[0]
print "I am totally watching " + myfile
wm = pyinotify.WatchManager()
# watched events on the directory, and parse $path for file_of_interest:
dirmask = pyinotify.IN_MODIFY | pyinotify.IN_DELETE | pyinotify.IN_MOVE_SELF | pyinotify.IN_CREATE
# open file, skip to end.. global, because we need it within the below
# class, every time it's triggered.
global fh
try:
fh = open(myfile, 'r')
except:
sys.stderr.write("unable to open file %s" % myfile)
fh.seek(0,2)
# the event handlers:
class EventHandler(pyinotify.ProcessEvent):
def __init__(self):
self.last_position_in_file = 0
pyinotify.ProcessEvent.__init__(self)
def process_IN_MODIFY(self, event):
if myfile != os.path.join(event.path, event.name):
return
else:
line = None
# first, check if the file was truncated:
curr_size = os.fstat(fh.fileno()).st_size
if curr_size < self.last_position_in_file:
sys.stdout.write("File was truncated! re-seeking to position 0..\n")
self.last_position_in_file = 0
fh.seek(0) # always behind - need catch-up code here too! (see below in IN_CREATE)
try:
line = fh.readline()
self.last_position_in_file = fh.tell()
except:
sys.stderr.write("error reading line from file!\n")
return
run(line, k)
def process_IN_DELETE(self, event):
return
def process_IN_CREATE(self, event):
if myfile in os.path.join(event.path, event.name):
# yay, I exist again!
global fh
fh.close()
fh = open(myfile, 'r')
# catch up: /!\ disabled, due to spikes in graphs, and resources consumed. Will re-enable, maybe, later, when it can
# send metrics it missed with the timestamp they occurred. a tiny gap is better for now.
# Requires: unix epoch time formatting via strftime() in varnish (varnishncsa -F %{%s}t, which won't work
# until commit # (varnish/varnish-cache@0471b9b) is a stable/released version. (currently in varnish/master)
#print "My file was removed, then re-created! I'm now catching up with lines in the newly created file."
#for line in fh.readlines():
# run(line, k)
fh.seek(0,2)
self.last_position_in_file = fh.tell()
return
notifier = pyinotify.Notifier(wm, EventHandler())
# watch the directory, so we can get IN_CREATE events and re-open
# the file when logrotate comes along.
index = myfile.rfind('/')
try:
wm.add_watch(myfile[:index], dirmask)
except:
sys.stderr.write("unable to watch file: %s" % myfile)
try:
notifier.loop()
except KeyboardInterrupt:
None
finally:
notifier.stop()
fh.close()