Last active
December 20, 2016 14:12
-
-
Save yukirii/aca9d536dbbd4ab1ab752711383422bd to your computer and use it in GitHub Desktop.
CyberAgent Developers Advent Calendar 2016 - https://developers.cyberagent.co.jp/blog/archives/3572/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
-- Lua の HTTP module を使用しているため lua-socket パッケージが必要 | |
-- | |
http = require("socket.http") | |
ltn12 = require("ltn12") | |
-- | |
-- cache サーバの一覧 | |
-- | |
varnishHosts = { | |
"stat100-cache01.example.com", | |
"stat100-cache02.example.com", | |
} | |
-- | |
-- /data ディレクトリの変更を監視し、何らかの変更があった場合に purgeHandler を呼ぶ | |
-- | |
sync { | |
purgeHandler, | |
source = "/data" | |
} | |
-- | |
-- purgeHandler | |
-- | |
purgeHandler = { | |
maxDelays = 1, | |
maxProcesses = 8, | |
action = function(inlet) | |
local event = inlet.getEvent() | |
-- | |
-- 隠しファイルの場合は PURGE を送らないようにする | |
-- ハマリポイント2 で解説 | |
-- | |
log("Normal", string.format("Event Name: %s %s", event.etype, event.path)) | |
if event.etype ~= "Attrib" and not string.find(event.path, "%/%.") then | |
sendPurge(event) | |
end | |
inlet.discardEvent(event) | |
end | |
} | |
-- | |
-- sendPurge funciton | |
-- | |
sendPurge = function(event) | |
for i, varnishHost in pairs(varnishHosts) do | |
local targetUrl = "http://" .. varnishHost .. event.path | |
local httpMethod = "PURGE" | |
-- | |
-- 対象がディレクトリの場合かつ削除イベントの場合は | |
-- BAN リクエストでディレクトリ配下のキャッシュを一括削除 | |
-- ハマリポイント1 で解説 | |
-- | |
if event.isdir and event.etype == "Delete" then | |
targetUrl = targetUrl .. "*" | |
httpMethod = "BAN" | |
end | |
-- | |
-- HTTP リクエストの送信 | |
-- | |
local resp = {} | |
local r, c, h = http.request{ | |
method = httpMethod, | |
url = targetUrl, | |
headers = { | |
["Host"] = varnishHost | |
}, | |
sink = ltn12.sink.table( resp ) | |
} | |
-- | |
-- lsyncd.log への出力 | |
-- | |
if not next(resp) then | |
log("Error", string.format("Failed to %s request to %s", httpMethod, targetUrl)) | |
else | |
local respBody = table.concat(resp) | |
local title = string.match(respBody, "<title>(.+)</title>") | |
local xid = string.match(respBody, "XID:%s(%d+)") | |
log("Normal", string.format("req %s %s", httpMethod, targetUrl)) | |
log("Normal", string.format("recv %s %s - %s XID:%s", httpMethod, targetUrl, title, xid)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment