Skip to content

Instantly share code, notes, and snippets.

@cirocosta
Last active November 23, 2019 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cirocosta/d28c90fac0008710db834f3d18327e3a to your computer and use it in GitHub Desktop.
Save cirocosta/d28c90fac0008710db834f3d18327e3a to your computer and use it in GitHub Desktop.
counts quick uses of `sync` - modified version from `iovisor/bcc` to keep track of statistics
#!/usr/bin/python
# hello-sync.py Detect quick uses of `sync`
#
# The program detects when two `sync()` calls get issued within a 1s delta.
#
# For instance, `sync; sleep 2; sync` will count `quick` as 0, but `sync;sync;sync`
# will.
#
# Example output:
#
# TOTAL QUICK
# 0 0
# 1 0
# 1 0
# 1 0
# 3 1
# 3 1
from __future__ import print_function
from bcc import BPF
from collections import defaultdict
from ctypes import c_int
from pprint import pprint
from time import sleep
b = BPF(text=r"""
// store the last time a sync occurred.
//
BPF_HASH(last);
enum stat_types
{
S_TOTAL = 1,
S_QUICK,
S_MAXSTAT
};
BPF_ARRAY(stats, u64, S_MAXSTAT);
int
do_trace(void* ctx)
{
u64* tsp = 0;
u64 ts, delta, KEY_LAST = 0;
u64 SECOND = 1000000000;
stats.increment(S_TOTAL);
tsp = last.lookup(&KEY_LAST);
if (tsp != 0) {
delta = bpf_ktime_get_ns() - *tsp;
if (delta < SECOND) {
stats.increment(S_QUICK);
}
}
ts = bpf_ktime_get_ns();
last.update(&KEY_LAST, &ts);
return 0;
}
""")
b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="do_trace")
print("Tracing... Hit Ctrl-C to end.")
print("%-8s %-8s" % ("TOTAL", "QUICK"))
stats = b["stats"]
S_TOTAL = c_int(1)
S_QUICK = c_int(2)
exiting = False
while not exiting:
try:
sleep(1)
except KeyboardInterrupt:
exiting = True
print("%-8d %-8d" % (stats[S_TOTAL].value, stats[S_QUICK].value))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment