-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvarnish_bust.rb
73 lines (61 loc) · 1.64 KB
/
varnish_bust.rb
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
get '/bust' do
if ['host', 'path', 'paths'].all? { |key| params[key].nil? || params[key].length == 0 }
halt 400, "ERROR: you must provide a 'host' param and a 'path' or comma-delimited 'paths' key"
end
host = params['host']
if params['paths']
paths = params['paths'].split(',')
else
paths = [params['path']]
end
# Make sure each path begins with '/'
paths.map! do |p|
p.strip!
p.insert(0,'/') if p[0,1] != '/'
p
end
purge_cmds = paths.collect do |p|
"req.http.host ~ #{host} && req.url ~ ^#{p}"
end
servers = varnish_hosts(params['server'])
servers.each do |server|
run_purges(server, purge_cmds)
end
"OK. Objects purged from #{servers.join(',')}."
end
private
def run_purges(server,purge_cmds)
begin
varnish = Varnish::Client.new(server)
Timeout::timeout(3) do
purge_cmds.each do |cmd|
puts "purging '#{cmd}' on #{server}..."
varnish.purge(cmd)
end
end
rescue Timeout::Error
halt 500, "ERROR: Request to #{server} timed out."
rescue Exception => e
halt 500, "ERROR: #{e.message}"
end
end
def varnish_hosts(server_name)
# retrive data
if defined?(VARNISH_SERVERS)
if server_name.nil? || server_name.empty?
addr = VARNISH_SERVERS['default']
else
addr = VARNISH_SERVERS[server_name]
end
else # for backwards-compatibility with config files
addr = VARNISH_SERVER
end
halt 500, "ERROR: varnish server #{server_name} unknown." if addr.nil? || addr.empty?
# Turn data into an array if it isn't already
if addr.is_a?(Array)
servers = addr
else
servers = [addr]
end
return servers
end