blob: 11926543428b90957d8f4b7ef3515bce62de99da [file] [log] [blame]
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +01001#!/usr/bin/env python
2#
Sasha Goldshteinf41ae862016-10-19 01:14:30 +03003# solisten Trace TCP listen events
4# For Linux, uses BCC, eBPF. Embedded C.
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +01005#
6# USAGE: solisten.py [-h] [-p PID] [--show-netns]
7#
8# This is provided as a basic example of TCP connection & socket tracing.
9# It could be usefull in scenarios where load balancers needs to be updated
10# dynamically as application is fully initialized.
11#
12# All IPv4 listen attempts are traced, even if they ultimately fail or the
13# the listening program is not willing to accept().
14#
15# Copyright (c) 2016 Jean-Tiare Le Bigot.
16# Licensed under the Apache License, Version 2.0 (the "License")
17#
18# 04-Mar-2016 Jean-Tiare Le Bigot Created this.
19
20import os
21import socket
22import netaddr
23import argparse
24from bcc import BPF
25import ctypes as ct
26
27# Arguments
28examples = """Examples:
29 ./solisten.py # Stream socket listen
30 ./solisten.py -p 1234 # Stream socket listen for specified PID only
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030031 ./solisten.py --netns 4242 # " for the specified network namespace ID only
32 ./solisten.py --show-netns # Show network ns ID (useful for containers)
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +010033"""
34
35parser = argparse.ArgumentParser(
36 description="Stream sockets listen",
37 formatter_class=argparse.RawDescriptionHelpFormatter,
38 epilog=examples)
39parser.add_argument("--show-netns", action="store_true",
40 help="show network namespace")
41parser.add_argument("-p", "--pid", default=0, type=int,
42 help="trace this PID only")
43parser.add_argument("-n", "--netns", default=0, type=int,
44 help="trace this Network Namespace only")
45
46
47# BPF Program
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030048bpf_text = """
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +010049#include <net/sock.h>
50#include <net/inet_sock.h>
51#include <net/net_namespace.h>
52#include <bcc/proto.h>
53
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +010054// Common structure for UDP/TCP IPv4/IPv6
55struct listen_evt_t {
56 u64 ts_us;
57 u64 pid_tgid;
58 u64 backlog;
59 u64 netns;
60 u64 proto; // familiy << 16 | type
61 u64 lport; // use only 16 bits
62 u64 laddr[2]; // IPv4: store in laddr[0]
63 char task[TASK_COMM_LEN];
64};
65BPF_PERF_OUTPUT(listen_evt);
66
67// Send an event for each IPv4 listen with PID, bound address and port
68int kprobe__inet_listen(struct pt_regs *ctx, struct socket *sock, int backlog)
69{
70 // cast types. Intermediate cast not needed, kept for readability
71 struct sock *sk = sock->sk;
72 struct inet_sock *inet = inet_sk(sk);
73
74 // Built event for userland
75 struct listen_evt_t evt = {
76 .ts_us = bpf_ktime_get_ns() / 1000,
77 .backlog = backlog,
78 };
79
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030080 // Get process comm. Needs LLVM >= 3.7.1
81 // see https://github.com/iovisor/bcc/issues/393
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +010082 bpf_get_current_comm(evt.task, TASK_COMM_LEN);
83
84 // Get socket IP family
85 u16 family = sk->__sk_common.skc_family;
86 evt.proto = family << 16 | SOCK_STREAM;
87
88 // Get PID
89 evt.pid_tgid = bpf_get_current_pid_tgid();
90
91 ##FILTER_PID##
92
93 // Get port
94 bpf_probe_read(&evt.lport, sizeof(u16), &(inet->inet_sport));
95 evt.lport = ntohs(evt.lport);
96
97 // Get network namespace id, if kernel supports it
98#ifdef CONFIG_NET_NS
99 evt.netns = sk->__sk_common.skc_net.net->ns.inum;
100#else
101 evt.netns = 0;
102#endif
103
104 ##FILTER_NETNS##
105
106 // Get IP
107 if (family == AF_INET) {
108 bpf_probe_read(evt.laddr, sizeof(u32), &(inet->inet_rcv_saddr));
Jean-Tiare Le Bigotbf330142016-03-28 15:14:12 +0000109 evt.laddr[0] = be32_to_cpu(evt.laddr[0]);
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +0100110 } else if (family == AF_INET6) {
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300111 bpf_probe_read(evt.laddr, sizeof(evt.laddr),
112 sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
Jean-Tiare Le Bigotbf330142016-03-28 15:14:12 +0000113 evt.laddr[0] = be64_to_cpu(evt.laddr[0]);
114 evt.laddr[1] = be64_to_cpu(evt.laddr[1]);
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +0100115 }
116
117 // Send event to userland
118 listen_evt.perf_submit(ctx, &evt, sizeof(evt));
119
120 return 0;
121};
122"""
123
124# event data
125TASK_COMM_LEN = 16 # linux/sched.h
126class ListenEvt(ct.Structure):
127 _fields_ = [
128 ("ts_us", ct.c_ulonglong),
129 ("pid_tgid", ct.c_ulonglong),
130 ("backlog", ct.c_ulonglong),
131 ("netns", ct.c_ulonglong),
132 ("proto", ct.c_ulonglong),
133 ("lport", ct.c_ulonglong),
134 ("laddr", ct.c_ulonglong * 2),
135 ("task", ct.c_char * TASK_COMM_LEN)
136 ]
137
138 # TODO: properties to unpack protocol / ip / pid / tgid ...
139
140# Format output
141def event_printer(show_netns):
142 def print_event(cpu, data, size):
143 # Decode event
144 event = ct.cast(data, ct.POINTER(ListenEvt)).contents
145
146 pid = event.pid_tgid & 0xffffffff
147 proto_family = event.proto & 0xff
148 proto_type = event.proto >> 16 & 0xff
149
150 if proto_family == socket.SOCK_STREAM:
151 protocol = "TCP"
152 elif proto_family == socket.SOCK_DGRAM:
153 protocol = "UDP"
154 else:
155 protocol = "UNK"
156
157 address = ""
158 if proto_type == socket.AF_INET:
159 protocol += "v4"
160 address = netaddr.IPAddress(event.laddr[0])
161 elif proto_type == socket.AF_INET6:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300162 address = netaddr.IPAddress(event.laddr[0] << 64 | event.laddr[1],
163 version=6)
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +0100164 protocol += "v6"
165
166 # Display
167 if show_netns:
168 print("%-6d %-12.12s %-12s %-6s %-8s %-5s %-39s" % (
169 pid, event.task, event.netns, protocol, event.backlog,
170 event.lport, address,
171 ))
172 else:
173 print("%-6d %-12.12s %-6s %-8s %-5s %-39s" % (
174 pid, event.task, protocol, event.backlog,
175 event.lport, address,
176 ))
177
178 return print_event
179
180if __name__ == "__main__":
181 # Parse arguments
182 args = parser.parse_args()
183
184 pid_filter = ""
185 netns_filter = ""
186
187 if args.pid:
188 pid_filter = "if (evt.pid_tgid != %d) return 0;" % args.pid
189 if args.netns:
190 netns_filter = "if (evt.netns != %d) return 0;" % args.netns
191
192 bpf_text = bpf_text.replace("##FILTER_PID##", pid_filter)
193 bpf_text = bpf_text.replace("##FILTER_NETNS##", netns_filter)
194
195 # Initialize BPF
196 b = BPF(text=bpf_text)
197 b["listen_evt"].open_perf_buffer(event_printer(args.show_netns))
198
199 # Print headers
200 if args.show_netns:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300201 print("%-6s %-12s %-12s %-6s %-8s %-5s %-39s" %
202 ("PID", "COMM", "NETNS", "PROTO", "BACKLOG", "PORT", "ADDR"))
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +0100203 else:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300204 print("%-6s %-12s %-6s %-8s %-5s %-39s" %
205 ("PID", "COMM", "PROTO", "BACKLOG", "PORT", "ADDR"))
Jean-Tiare Le Bigota1ac2f92016-03-04 21:45:32 +0100206
207 # Read events
208 while 1:
209 b.kprobe_poll()