1#!/usr/bin/env 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 13from __future__ import print_function 14from bcc import BPF, USDT 15import sys 16 17if len(sys.argv) < 2: 18 print("USAGE: mysqld_latency PID") 19 exit() 20pid = sys.argv[1] 21debug = 0 22 23# load BPF program 24bpf_text = """ 25#include <uapi/linux/ptrace.h> 26int 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 42u = USDT(pid=int(pid)) 43u.enable_probe(probe="query__start", fn_name="do_trace") 44if debug: 45 print(u.get_text()) 46 print(bpf_text) 47 48# initialize BPF 49b = BPF(text=bpf_text, usdt_contexts=[u]) 50 51# header 52print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "QUERY")) 53 54# format output 55while 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)) 62