Home | History | Annotate | Download | only in tracing
      1 #!/usr/bin/env python
      2 # Copyright (c) PLUMgrid, Inc.
      3 # Licensed under the Apache License, Version 2.0 (the "License")
      4 
      5 # This is an example of tracing an event and printing custom fields.
      6 # run in project examples directory with:
      7 # sudo ./trace_fields.py"
      8 
      9 import atexit
     10 from bcc import BPF
     11 import ctypes as ct
     12 
     13 class Data(ct.Structure):
     14     _fields_ = [("ts", ct.c_ulonglong),
     15                 ("magic", ct.c_ulonglong)]
     16 
     17 counter = 0
     18 def cb(cpu, data, size):
     19     assert size >= ct.sizeof(Data)
     20     event = ct.cast(data, ct.POINTER(Data)).contents
     21     print("[%0d] %f: %x" % (cpu, float(event.ts) / 1000000, event.magic))
     22     global counter
     23     counter += 1
     24 
     25 prog = """
     26 BPF_PERF_OUTPUT(events);
     27 BPF_ARRAY(counters, u64, 10);
     28 int do_sys_clone(void *ctx) {
     29   struct {
     30     u64 ts;
     31     u64 magic;
     32   } data = {bpf_ktime_get_ns(), 0x12345678};
     33   int rc;
     34   if ((rc = events.perf_submit(ctx, &data, sizeof(data))) < 0)
     35     bpf_trace_printk("perf_output failed: %d\\n", rc);
     36   int zero = 0;
     37   u64 *val = counters.lookup(&zero);
     38   if (val) lock_xadd(val, 1);
     39   return 0;
     40 }
     41 """
     42 b = BPF(text=prog)
     43 event_name = b.get_syscall_fnname("clone")
     44 b.attach_kprobe(event=event_name, fn_name="do_sys_clone")
     45 b["events"].open_perf_buffer(cb)
     46 
     47 @atexit.register
     48 def print_counter():
     49     global counter
     50     global b
     51     print("counter = %d vs %d" % (counter, b["counters"][ct.c_int(0)].value))
     52 
     53 print("Tracing " + event_name + ", try `dd if=/dev/zero of=/dev/null`")
     54 print("Tracing... Hit Ctrl-C to end.")
     55 while 1:
     56     b.perf_buffer_poll()
     57