• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 
3 /*
4  * gethostlatency  Show latency for getaddrinfo/gethostbyname[2] calls.
5  *
6  * Copyright (c) 2021 Hengqi Chen
7  *
8  * Based on gethostlatency(8) from BCC by Brendan Gregg.
9  * 24-Mar-2021   Hengqi Chen   Created this.
10  */
11 #include <argp.h>
12 #include <errno.h>
13 #include <signal.h>
14 #include <time.h>
15 
16 #include <bpf/libbpf.h>
17 #include <bpf/bpf.h>
18 #include "gethostlatency.h"
19 #include "gethostlatency.skel.h"
20 #include "trace_helpers.h"
21 #include "uprobe_helpers.h"
22 
23 #define PERF_BUFFER_PAGES	16
24 #define PERF_POLL_TIMEOUT_MS	100
25 #define warn(...) fprintf(stderr, __VA_ARGS__)
26 
27 static volatile sig_atomic_t exiting = 0;
28 
29 static pid_t target_pid = 0;
30 static const char *libc_path = NULL;
31 static bool verbose = false;
32 
33 const char *argp_program_version = "gethostlatency 0.1";
34 const char *argp_program_bug_address =
35 	"https://github.com/iovisor/bcc/tree/master/libbpf-tools";
36 const char argp_program_doc[] =
37 "Show latency for getaddrinfo/gethostbyname[2] calls.\n"
38 "\n"
39 "USAGE: gethostlatency [-h] [-p PID] [-l LIBC]\n"
40 "\n"
41 "EXAMPLES:\n"
42 "    gethostlatency             # time getaddrinfo/gethostbyname[2] calls\n"
43 "    gethostlatency -p 1216     # only trace PID 1216\n";
44 
45 static const struct argp_option opts[] = {
46 	{ "pid", 'p', "PID", 0, "Process ID to trace" },
47 	{ "libc", 'l', "LIBC", 0, "Specify which libc.so to use" },
48 	{ "verbose", 'v', NULL, 0, "Verbose debug output" },
49 	{ NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
50 	{},
51 };
52 
parse_arg(int key,char * arg,struct argp_state * state)53 static error_t parse_arg(int key, char *arg, struct argp_state *state)
54 {
55 	long pid;
56 
57 	switch (key) {
58 	case 'p':
59 		errno = 0;
60 		pid = strtol(arg, NULL, 10);
61 		if (errno || pid <= 0) {
62 			warn("Invalid PID: %s\n", arg);
63 			argp_usage(state);
64 		}
65 		target_pid = pid;
66 		break;
67 	case 'l':
68 		libc_path = strdup(arg);
69 		if (access(libc_path, F_OK)) {
70 			warn("Invalid libc: %s\n", arg);
71 			argp_usage(state);
72 		}
73 		break;
74 	case 'v':
75 		verbose = true;
76 		break;
77 	case 'h':
78 		argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
79 		break;
80 	default:
81 		return ARGP_ERR_UNKNOWN;
82 	}
83 	return 0;
84 }
85 
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)86 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
87 {
88 	if (level == LIBBPF_DEBUG && !verbose)
89 		return 0;
90 	return vfprintf(stderr, format, args);
91 }
92 
sig_int(int signo)93 static void sig_int(int signo)
94 {
95 	exiting = 1;
96 }
97 
handle_event(void * ctx,int cpu,void * data,__u32 data_sz)98 static void handle_event(void *ctx, int cpu, void *data, __u32 data_sz)
99 {
100 	const struct event *e = data;
101 	struct tm *tm;
102 	char ts[16];
103 	time_t t;
104 
105 	time(&t);
106 	tm = localtime(&t);
107 	strftime(ts, sizeof(ts), "%H:%M:%S", tm);
108 	printf("%-8s %-7d %-16s %-10.3f %-s\n",
109 	       ts, e->pid, e->comm, (double)e->time/1000000, e->host);
110 }
111 
handle_lost_events(void * ctx,int cpu,__u64 lost_cnt)112 static void handle_lost_events(void *ctx, int cpu, __u64 lost_cnt)
113 {
114 	warn("lost %llu events on CPU #%d\n", lost_cnt, cpu);
115 }
116 
get_libc_path(char * path)117 static int get_libc_path(char *path)
118 {
119 	FILE *f;
120 	char buf[PATH_MAX] = {};
121 	char *filename;
122 	float version;
123 
124 	if (libc_path) {
125 		memcpy(path, libc_path, strlen(libc_path));
126 		return 0;
127 	}
128 
129 	f = fopen("/proc/self/maps", "r");
130 	if (!f)
131 		return -errno;
132 
133 	while (fscanf(f, "%*x-%*x %*s %*s %*s %*s %[^\n]\n", buf) != EOF) {
134 		if (strchr(buf, '/') != buf)
135 			continue;
136 		filename = strrchr(buf, '/') + 1;
137 		if (sscanf(filename, "libc-%f.so", &version) == 1) {
138 			memcpy(path, buf, strlen(buf));
139 			fclose(f);
140 			return 0;
141 		}
142 	}
143 
144 	fclose(f);
145 	return -1;
146 }
147 
attach_uprobes(struct gethostlatency_bpf * obj,struct bpf_link * links[])148 static int attach_uprobes(struct gethostlatency_bpf *obj, struct bpf_link *links[])
149 {
150 	int err;
151 	char libc_path[PATH_MAX] = {};
152 	off_t func_off;
153 
154 	err = get_libc_path(libc_path);
155 	if (err) {
156 		warn("could not find libc.so\n");
157 		return -1;
158 	}
159 
160 	func_off = get_elf_func_offset(libc_path, "getaddrinfo");
161 	if (func_off < 0) {
162 		warn("could not find getaddrinfo in %s\n", libc_path);
163 		return -1;
164 	}
165 	links[0] = bpf_program__attach_uprobe(obj->progs.handle_entry, false,
166 					      target_pid ?: -1, libc_path, func_off);
167 	if (!links[0]) {
168 		warn("failed to attach getaddrinfo: %d\n", -errno);
169 		return -1;
170 	}
171 	links[1] = bpf_program__attach_uprobe(obj->progs.handle_return, true,
172 					      target_pid ?: -1, libc_path, func_off);
173 	if (!links[1]) {
174 		warn("failed to attach getaddrinfo: %d\n", -errno);
175 		return -1;
176 	}
177 
178 	func_off = get_elf_func_offset(libc_path, "gethostbyname");
179 	if (func_off < 0) {
180 		warn("could not find gethostbyname in %s\n", libc_path);
181 		return -1;
182 	}
183 	links[2] = bpf_program__attach_uprobe(obj->progs.handle_entry, false,
184 					      target_pid ?: -1, libc_path, func_off);
185 	if (!links[2]) {
186 		warn("failed to attach gethostbyname: %d\n", -errno);
187 		return -1;
188 	}
189 	links[3] = bpf_program__attach_uprobe(obj->progs.handle_return, true,
190 					      target_pid ?: -1, libc_path, func_off);
191 	if (!links[3]) {
192 		warn("failed to attach gethostbyname: %d\n", -errno);
193 		return -1;
194 	}
195 
196 	func_off = get_elf_func_offset(libc_path, "gethostbyname2");
197 	if (func_off < 0) {
198 		warn("could not find gethostbyname2 in %s\n", libc_path);
199 		return -1;
200 	}
201 	links[4] = bpf_program__attach_uprobe(obj->progs.handle_entry, false,
202 					      target_pid ?: -1, libc_path, func_off);
203 	if (!links[4]) {
204 		warn("failed to attach gethostbyname2: %d\n", -errno);
205 		return -1;
206 	}
207 	links[5] = bpf_program__attach_uprobe(obj->progs.handle_return, true,
208 					      target_pid ?: -1, libc_path, func_off);
209 	if (!links[5]) {
210 		warn("failed to attach gethostbyname2: %d\n", -errno);
211 		return -1;
212 	}
213 
214 	return 0;
215 }
216 
main(int argc,char ** argv)217 int main(int argc, char **argv)
218 {
219 	static const struct argp argp = {
220 		.options = opts,
221 		.parser = parse_arg,
222 		.doc = argp_program_doc,
223 	};
224 	struct perf_buffer *pb = NULL;
225 	struct bpf_link *links[6] = {};
226 	struct gethostlatency_bpf *obj;
227 	int i, err;
228 
229 	err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
230 	if (err)
231 		return err;
232 
233 	libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
234 	libbpf_set_print(libbpf_print_fn);
235 
236 	obj = gethostlatency_bpf__open();
237 	if (!obj) {
238 		warn("failed to open BPF object\n");
239 		return 1;
240 	}
241 
242 	obj->rodata->target_pid = target_pid;
243 
244 	err = gethostlatency_bpf__load(obj);
245 	if (err) {
246 		warn("failed to load BPF object: %d\n", err);
247 		goto cleanup;
248 	}
249 
250 	err = attach_uprobes(obj, links);
251 	if (err)
252 		goto cleanup;
253 
254 	pb = perf_buffer__new(bpf_map__fd(obj->maps.events), PERF_BUFFER_PAGES,
255 			      handle_event, handle_lost_events, NULL, NULL);
256 	if (!pb) {
257 		err = -errno;
258 		warn("failed to open perf buffer: %d\n", err);
259 		goto cleanup;
260 	}
261 
262 	if (signal(SIGINT, sig_int) == SIG_ERR) {
263 		warn("can't set signal handler: %s\n", strerror(errno));
264 		err = 1;
265 		goto cleanup;
266 	}
267 
268 	printf("%-8s %-7s %-16s %-10s %-s\n",
269 	       "TIME", "PID", "COMM", "LATms", "HOST");
270 
271 	while (!exiting) {
272 		err = perf_buffer__poll(pb, PERF_POLL_TIMEOUT_MS);
273 		if (err < 0 && err != -EINTR) {
274 			warn("error polling perf buffer: %s\n", strerror(-err));
275 			goto cleanup;
276 		}
277 		/* reset err to return 0 if exiting */
278 		err = 0;
279 	}
280 
281 cleanup:
282 	perf_buffer__free(pb);
283 	for (i = 0; i < 6; i++)
284 		bpf_link__destroy(links[i]);
285 	gethostlatency_bpf__destroy(obj);
286 
287 	return err != 0;
288 }
289