iovisor / bcc

BCC - Tools for BPF-based Linux IO analysis, networking, monitoring, and more
Apache License 2.0
20.59k stars 3.88k forks source link

Is there some mechanism for "sampling" tables at a periodic rate? #4930

Open pontaoski opened 8 months ago

pontaoski commented 8 months ago

usecase: writing BPF programs that track how many of an event happens per second over time

I started down this path (code incomplete as i realised that this probably isn't the best way partway through):

#include <uapi/linux/ptrace.h>
#include <linux/sched.h>

BPF_HASH(counts, u32);
BPF_ARRAY_OF_MAPS(last_ten_counts, "counts", 10);

BPF_ARRAY(probing_start_time, u64, 1);
BPF_ARRAY(current_count, u64, 1);

static int count_wakeup(struct bpf_raw_tracepoint_args *ctx, struct task_struct *process) {
    int key = 0;
    u64* pst = probing_start_time.lookup(&key);
    u64* cc = current_count.lookup(&key);
    if (pst == 0 || cc == 0) {
        return 0;
    }
    if (process->flags & PF_KTHREAD) {
        return 0;
    }
    u32 taskID = process->tgid;
    counts.atomic_increment(taskID);
    u64 now = bpf_ktime_get_ns();
    if (*pst == -1) {
        *pst = now;
    } else {
        if ((now - *pst) >= 1000000000) {
            *pst = now;

            // copy counts to last_ten_counts[*cc]

            *cc++;
            if (cc >= 10) {
                *cc = 0;
            }
        }
    }
    return 0;
}

RAW_TRACEPOINT_PROBE(sched_wakeup)
{
    struct task_struct *p = (struct task_struct *)ctx->args[0];
    return count_wakeup(ctx, p);
}

but then realised that this Seems rather unwieldy for what is seemingly a pretty basic profiling thing

is there some obvious solution i'm missing to track "rates" of stuff over time?