Brendan Gregg | d602d6b | 2016-08-01 16:18:40 -0700 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # |
| 3 | # mysqld_query Trace MySQL server queries. Example of USDT tracing. |
| 4 | # For Linux, uses BCC, BPF. Embedded C. |
| 5 | # |
| 6 | # USAGE: mysqld_query PID |
| 7 | # |
| 8 | # This uses USDT probes, and needs a MySQL server with -DENABLE_DTRACE=1. |
| 9 | # |
| 10 | # Copyright 2016 Netflix, Inc. |
| 11 | # Licensed under the Apache License, Version 2.0 (the "License") |
| 12 | |
| 13 | from __future__ import print_function |
| 14 | from bcc import BPF, USDT |
| 15 | import sys |
| 16 | |
| 17 | if len(sys.argv) < 2: |
| 18 | print("USAGE: mysqld_latency PID") |
| 19 | exit() |
| 20 | pid = sys.argv[1] |
| 21 | debug = 0 |
| 22 | |
| 23 | # load BPF program |
| 24 | bpf_text = """ |
| 25 | #include <uapi/linux/ptrace.h> |
| 26 | int do_trace(struct pt_regs *ctx) { |
| 27 | uint64_t addr; |
| 28 | char query[128]; |
| 29 | /* |
| 30 | * Read the first argument from the query-start probe, which is the query. |
| 31 | * The format of this probe is: |
| 32 | * query-start(query, connectionid, database, user, host) |
| 33 | * see: https://dev.mysql.com/doc/refman/5.7/en/dba-dtrace-ref-query.html |
| 34 | */ |
| 35 | bpf_usdt_readarg(1, ctx, &addr); |
| 36 | bpf_trace_printk("%s\\n", addr); |
| 37 | return 0; |
| 38 | }; |
| 39 | """ |
| 40 | |
| 41 | # enable USDT probe from given PID |
| 42 | u = USDT(pid=int(pid)) |
| 43 | u.enable_probe(probe="query__start", fn_name="do_trace") |
| 44 | if debug: |
| 45 | print(u.get_text()) |
| 46 | print(bpf_text) |
| 47 | |
| 48 | # initialize BPF |
Sasha Goldshtein | a2370ab | 2016-10-06 17:52:09 -0700 | [diff] [blame] | 49 | b = BPF(text=bpf_text, usdt_contexts=[u]) |
Brendan Gregg | d602d6b | 2016-08-01 16:18:40 -0700 | [diff] [blame] | 50 | |
| 51 | # header |
| 52 | print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "QUERY")) |
| 53 | |
| 54 | # format output |
| 55 | while 1: |
| 56 | try: |
| 57 | (task, pid, cpu, flags, ts, msg) = b.trace_fields() |
| 58 | except ValueError: |
| 59 | print("value error") |
| 60 | continue |
| 61 | print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg)) |