• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env bcc-lua
2--[[
3Copyright 2016 Marek Vavrusa <mvavrusa@cloudflare.com>
4
5Licensed under the Apache License, Version 2.0 (the "License");
6you may not use this file except in compliance with the License.
7You may obtain a copy of the License at
8
9http://www.apache.org/licenses/LICENSE-2.0
10
11Unless required by applicable law or agreed to in writing, software
12distributed under the License is distributed on an "AS IS" BASIS,
13WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14See the License for the specific language governing permissions and
15limitations under the License.
16]]
17-- Trace operations on keys matching given pattern in KyotoTycoon daemon.
18-- This can show you if certain keys were modified or read during the lifetime
19-- even if KT doesn't support this. It also shows how to attach to C++ mangled symbols.
20local ffi = require('ffi')
21local bpf = require('bpf')
22local S = require('syscall')
23local function help(err)
24	print(string.format('%s [get|set] [key]', arg[0]))
25	if err then print('error: '..err) end
26	os.exit(1)
27end
28-- Accept the same format as ktremotemgr for clarity: <get|set> <key>
29local writeable, watch_key, klen = 'any', arg[2] or '*', 80
30if     arg[1] == 'get' then writeable = 0
31elseif arg[1] == 'set' then writeable = 1
32elseif arg[1] == '-h' or arg[1] == '--help' then help()
33elseif arg[1] and arg[1] ~= 'any' then
34	help(string.format('bad cmd: "%s"', arg[1]))
35end
36if watch_key ~= '*' then klen = #watch_key end
37
38-- Find a good entrypoint that has both key and differentiates read/write in KT
39-- That is going to serve as an attachment point for BPF program
40-- ABI: bool accept(void *this, const char* kbuf, size_t ksiz, Visitor* visitor, bool writable)
41local key_type = string.format('char [%d]', klen)
42local probe = bpf.uprobe('/usr/local/bin/ktserver:kyotocabinet::StashDB::accept',
43function (ptregs)
44	-- Watch either get/set or both
45	if writeable ~= 'any' then
46		if ptregs.parm5 ~= writeable then return end
47	end
48	local line = ffi.new(key_type)
49	ffi.copy(line, ffi.cast('char *', ptregs.parm2))
50	-- Check if we're looking for specific key
51	if watch_key ~= '*' then
52		if ptregs.parm3 ~= klen then return false end
53		if line ~= watch_key then return false end
54	end
55	print('%s write:%d\n', line, ptregs.parm5)
56end, false, -1, 0)
57-- User-space part of the program
58local ok, err = pcall(function()
59	local log = bpf.tracelog()
60	print('            TASK-PID   CPU#         TIMESTAMP  FUNCTION')
61	print('               | |      |               |         |')
62	while true do
63		print(log:read())
64	end
65end)
66