bitesize.py 1.64 KB
Newer Older
mcaleavya's avatar
mcaleavya committed
1 2 3 4 5 6 7
#!/usr/bin/python
#
# bitehist.py   Block I/O size histogram.
#               For Linux, uses BCC, eBPF. See .c file.
#
# USAGE: bitesize
#
Brendan Gregg's avatar
Brendan Gregg committed
8
# Ctrl-C will print the partially gathered histogram then exit.
mcaleavya's avatar
mcaleavya committed
9 10 11 12 13 14 15 16 17 18 19 20 21
#
# Copyright (c) 2016 Allan McAleavy
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 05-Feb-2016 Allan McAleavy ran pep8 against file

from bcc import BPF
from time import sleep

bpf_text = """
#include <uapi/linux/ptrace.h>
#include <linux/blkdev.h>

Brendan Gregg's avatar
nits  
Brendan Gregg committed
22
struct proc_key_t {
mcaleavya's avatar
mcaleavya committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    char name[TASK_COMM_LEN];
    u64 slot;
};

struct val_t {
    char name[TASK_COMM_LEN];
};

BPF_HISTOGRAM(dist, struct proc_key_t);
BPF_HASH(commbyreq, struct request *, struct val_t);

int trace_pid_start(struct pt_regs *ctx, struct request *req)
{
    struct val_t val = {};

    if (bpf_get_current_comm(&val.name, sizeof(val.name)) == 0) {
        commbyreq.update(&req, &val);
    }
    return 0;
}

Brendan Gregg's avatar
nits  
Brendan Gregg committed
44
int do_count(struct pt_regs *ctx, struct request *req)
mcaleavya's avatar
mcaleavya committed
45 46 47 48
{
    struct val_t *valp;

    valp = commbyreq.lookup(&req);
Brendan Gregg's avatar
nits  
Brendan Gregg committed
49
    if (valp == 0) {
mcaleavya's avatar
mcaleavya committed
50 51 52 53 54 55 56 57
       return 0;
    }

    if (req->__data_len > 0) {
        struct proc_key_t key = {.slot = bpf_log2l(req->__data_len / 1024)};
        bpf_probe_read(&key.name, sizeof(key.name),valp->name);
        dist.increment(key);
    }
Brendan Gregg's avatar
Brendan Gregg committed
58
    return 0;
mcaleavya's avatar
mcaleavya committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
}
"""

# load BPF program
b = BPF(text=bpf_text)
b.attach_kprobe(event="blk_account_io_start", fn_name="trace_pid_start")
b.attach_kprobe(event="blk_account_io_completion", fn_name="do_count")

print("Tracing... Hit Ctrl-C to end.")

# trace until Ctrl-C
dist = b.get_table("dist")

try:
    sleep(99999999)
except KeyboardInterrupt:
Brendan Gregg's avatar
Brendan Gregg committed
75
    dist.print_log2_hist("Kbytes", "Process Name")