blob: c7388c99e3d82bbfdb3ac36473362bc5b6a2bf9f
1 | /* vi: set sw=4 ts=4: */ |
2 | /* |
3 | * Licensed under GPLv2 or later, see file LICENSE in this source tree. |
4 | */ |
5 | |
6 | //applet:IF_BOOTCHARTD(APPLET(bootchartd, BB_DIR_SBIN, BB_SUID_DROP)) |
7 | |
8 | //kbuild:lib-$(CONFIG_BOOTCHARTD) += bootchartd.o |
9 | |
10 | //config:config BOOTCHARTD |
11 | //config: bool "bootchartd" |
12 | //config: default y |
13 | //config: help |
14 | //config: bootchartd is commonly used to profile the boot process |
15 | //config: for the purpose of speeding it up. In this case, it is started |
16 | //config: by the kernel as the init process. This is configured by adding |
17 | //config: the init=/sbin/bootchartd option to the kernel command line. |
18 | //config: |
19 | //config: It can also be used to monitor the resource usage of a specific |
20 | //config: application or the running system in general. In this case, |
21 | //config: bootchartd is started interactively by running bootchartd start |
22 | //config: and stopped using bootchartd stop. |
23 | //config: |
24 | //config:config FEATURE_BOOTCHARTD_BLOATED_HEADER |
25 | //config: bool "Compatible, bloated header" |
26 | //config: default y |
27 | //config: depends on BOOTCHARTD |
28 | //config: help |
29 | //config: Create extended header file compatible with "big" bootchartd. |
30 | //config: "Big" bootchartd is a shell script and it dumps some |
31 | //config: "convenient" info int the header, such as: |
32 | //config: title = Boot chart for `hostname` (`date`) |
33 | //config: system.uname = `uname -srvm` |
34 | //config: system.release = `cat /etc/DISTRO-release` |
35 | //config: system.cpu = `grep '^model name' /proc/cpuinfo | head -1` ($cpucount) |
36 | //config: system.kernel.options = `cat /proc/cmdline` |
37 | //config: This data is not mandatory for bootchart graph generation, |
38 | //config: and is considered bloat. Nevertheless, this option |
39 | //config: makes bootchartd applet to dump a subset of it. |
40 | //config: |
41 | //config:config FEATURE_BOOTCHARTD_CONFIG_FILE |
42 | //config: bool "Support bootchartd.conf" |
43 | //config: default y |
44 | //config: depends on BOOTCHARTD |
45 | //config: help |
46 | //config: Enable reading and parsing of $PWD/bootchartd.conf |
47 | //config: and /etc/bootchartd.conf files. |
48 | |
49 | #include "libbb.h" |
50 | /* After libbb.h, since it needs sys/types.h on some systems */ |
51 | #include <sys/utsname.h> |
52 | |
53 | #ifdef __linux__ |
54 | # include <sys/mount.h> |
55 | # ifndef MS_SILENT |
56 | # define MS_SILENT (1 << 15) |
57 | # endif |
58 | # ifndef MNT_DETACH |
59 | # define MNT_DETACH 0x00000002 |
60 | # endif |
61 | #endif |
62 | |
63 | #if !ENABLE_TAR && !ENABLE_WERROR |
64 | # warning Note: bootchartd requires tar command, but you did not select it. |
65 | #elif !ENABLE_FEATURE_SEAMLESS_GZ && !ENABLE_WERROR |
66 | # warning Note: bootchartd requires tar -z support, but you did not select it. |
67 | #endif |
68 | |
69 | #define BC_VERSION_STR "0.8" |
70 | |
71 | /* For debugging, set to 0: |
72 | * strace won't work with DO_SIGNAL_SYNC set to 1. |
73 | */ |
74 | #define DO_SIGNAL_SYNC 1 |
75 | |
76 | |
77 | //$PWD/bootchartd.conf and /etc/bootchartd.conf: |
78 | //supported options: |
79 | //# Sampling period (in seconds) |
80 | //SAMPLE_PERIOD=0.2 |
81 | // |
82 | //not yet supported: |
83 | //# tmpfs size |
84 | //# (32 MB should suffice for ~20 minutes worth of log data, but YMMV) |
85 | //TMPFS_SIZE=32m |
86 | // |
87 | //# Whether to enable and store BSD process accounting information. The |
88 | //# kernel needs to be configured to enable v3 accounting |
89 | //# (CONFIG_BSD_PROCESS_ACCT_V3). accton from the GNU accounting utilities |
90 | //# is also required. |
91 | //PROCESS_ACCOUNTING="no" |
92 | // |
93 | //# Tarball for the various boot log files |
94 | //BOOTLOG_DEST=/var/log/bootchart.tgz |
95 | // |
96 | //# Whether to automatically stop logging as the boot process completes. |
97 | //# The logger will look for known processes that indicate bootup completion |
98 | //# at a specific runlevel (e.g. gdm-binary, mingetty, etc.). |
99 | //AUTO_STOP_LOGGER="yes" |
100 | // |
101 | //# Whether to automatically generate the boot chart once the boot logger |
102 | //# completes. The boot chart will be generated in $AUTO_RENDER_DIR. |
103 | //# Note that the bootchart package must be installed. |
104 | //AUTO_RENDER="no" |
105 | // |
106 | //# Image format to use for the auto-generated boot chart |
107 | //# (choose between png, svg and eps). |
108 | //AUTO_RENDER_FORMAT="png" |
109 | // |
110 | //# Output directory for auto-generated boot charts |
111 | //AUTO_RENDER_DIR="/var/log" |
112 | |
113 | |
114 | /* Globals */ |
115 | struct globals { |
116 | char jiffy_line[COMMON_BUFSIZE]; |
117 | } FIX_ALIASING; |
118 | #define G (*(struct globals*)&bb_common_bufsiz1) |
119 | #define INIT_G() do { } while (0) |
120 | |
121 | static void dump_file(FILE *fp, const char *filename) |
122 | { |
123 | int fd = open(filename, O_RDONLY); |
124 | if (fd >= 0) { |
125 | fputs(G.jiffy_line, fp); |
126 | fflush(fp); |
127 | bb_copyfd_eof(fd, fileno(fp)); |
128 | close(fd); |
129 | fputc('\n', fp); |
130 | } |
131 | } |
132 | |
133 | static int dump_procs(FILE *fp, int look_for_login_process) |
134 | { |
135 | struct dirent *entry; |
136 | DIR *dir = opendir("/proc"); |
137 | int found_login_process = 0; |
138 | |
139 | fputs(G.jiffy_line, fp); |
140 | while ((entry = readdir(dir)) != NULL) { |
141 | char name[sizeof("/proc/%u/cmdline") + sizeof(int)*3]; |
142 | int stat_fd; |
143 | unsigned pid = bb_strtou(entry->d_name, NULL, 10); |
144 | if (errno) |
145 | continue; |
146 | |
147 | /* Android's version reads /proc/PID/cmdline and extracts |
148 | * non-truncated process name. Do we want to do that? */ |
149 | |
150 | sprintf(name, "/proc/%u/stat", pid); |
151 | stat_fd = open(name, O_RDONLY); |
152 | if (stat_fd >= 0) { |
153 | char *p; |
154 | char stat_line[4*1024]; |
155 | int rd = safe_read(stat_fd, stat_line, sizeof(stat_line)-2); |
156 | |
157 | close(stat_fd); |
158 | if (rd < 0) |
159 | continue; |
160 | stat_line[rd] = '\0'; |
161 | p = strchrnul(stat_line, '\n'); |
162 | *p++ = '\n'; |
163 | *p = '\0'; |
164 | fputs(stat_line, fp); |
165 | if (!look_for_login_process) |
166 | continue; |
167 | p = strchr(stat_line, '('); |
168 | if (!p) |
169 | continue; |
170 | p++; |
171 | strchrnul(p, ')')[0] = '\0'; |
172 | /* Is it gdm, kdm or a getty? */ |
173 | if (((p[0] == 'g' || p[0] == 'k' || p[0] == 'x') && p[1] == 'd' && p[2] == 'm') |
174 | || strstr(p, "getty") |
175 | ) { |
176 | found_login_process = 1; |
177 | } |
178 | } |
179 | } |
180 | closedir(dir); |
181 | fputc('\n', fp); |
182 | return found_login_process; |
183 | } |
184 | |
185 | static char *make_tempdir(void) |
186 | { |
187 | char template[] = "/tmp/bootchart.XXXXXX"; |
188 | char *tempdir = xstrdup(mkdtemp(template)); |
189 | if (!tempdir) { |
190 | #ifdef __linux__ |
191 | /* /tmp is not writable (happens when we are used as init). |
192 | * Try to mount a tmpfs, them cd and lazily unmount it. |
193 | * Since we unmount it at once, we can mount it anywhere. |
194 | * Try a few locations which are likely ti exist. |
195 | */ |
196 | static const char dirs[] = "/mnt\0""/tmp\0""/boot\0""/proc\0"; |
197 | const char *try_dir = dirs; |
198 | while (mount("none", try_dir, "tmpfs", MS_SILENT, "size=16m") != 0) { |
199 | try_dir += strlen(try_dir) + 1; |
200 | if (!try_dir[0]) |
201 | bb_perror_msg_and_die("can't %smount tmpfs", ""); |
202 | } |
203 | //bb_error_msg("mounted tmpfs on %s", try_dir); |
204 | xchdir(try_dir); |
205 | if (umount2(try_dir, MNT_DETACH) != 0) { |
206 | bb_perror_msg_and_die("can't %smount tmpfs", "un"); |
207 | } |
208 | #else |
209 | bb_perror_msg_and_die("can't create temporary directory"); |
210 | #endif |
211 | } else { |
212 | xchdir(tempdir); |
213 | } |
214 | return tempdir; |
215 | } |
216 | |
217 | static void do_logging(unsigned sample_period_us, int process_accounting) |
218 | { |
219 | FILE *proc_stat = xfopen("proc_stat.log", "w"); |
220 | FILE *proc_diskstats = xfopen("proc_diskstats.log", "w"); |
221 | //FILE *proc_netdev = xfopen("proc_netdev.log", "w"); |
222 | FILE *proc_ps = xfopen("proc_ps.log", "w"); |
223 | int look_for_login_process = (getppid() == 1); |
224 | unsigned count = 60*1000*1000 / sample_period_us; /* ~1 minute */ |
225 | |
226 | if (process_accounting) { |
227 | close(xopen("kernel_pacct", O_WRONLY | O_CREAT | O_TRUNC)); |
228 | acct("kernel_pacct"); |
229 | } |
230 | |
231 | while (--count && !bb_got_signal) { |
232 | char *p; |
233 | int len = open_read_close("/proc/uptime", G.jiffy_line, sizeof(G.jiffy_line)-2); |
234 | if (len < 0) |
235 | goto wait_more; |
236 | /* /proc/uptime has format "NNNNNN.MM NNNNNNN.MM" */ |
237 | /* we convert it to "NNNNNNMM\n" (using first value) */ |
238 | G.jiffy_line[len] = '\0'; |
239 | p = strchr(G.jiffy_line, '.'); |
240 | if (!p) |
241 | goto wait_more; |
242 | while (isdigit(*++p)) |
243 | p[-1] = *p; |
244 | p[-1] = '\n'; |
245 | p[0] = '\0'; |
246 | |
247 | dump_file(proc_stat, "/proc/stat"); |
248 | dump_file(proc_diskstats, "/proc/diskstats"); |
249 | //dump_file(proc_netdev, "/proc/net/dev"); |
250 | if (dump_procs(proc_ps, look_for_login_process)) { |
251 | /* dump_procs saw a getty or {g,k,x}dm |
252 | * stop logging in 2 seconds: |
253 | */ |
254 | if (count > 2*1000*1000 / sample_period_us) |
255 | count = 2*1000*1000 / sample_period_us; |
256 | } |
257 | fflush_all(); |
258 | wait_more: |
259 | usleep(sample_period_us); |
260 | } |
261 | } |
262 | |
263 | static void finalize(char *tempdir, const char *prog, int process_accounting) |
264 | { |
265 | //# Stop process accounting if configured |
266 | //local pacct= |
267 | //[ -e kernel_pacct ] && pacct=kernel_pacct |
268 | |
269 | FILE *header_fp = xfopen("header", "w"); |
270 | |
271 | if (process_accounting) |
272 | acct(NULL); |
273 | |
274 | if (prog) |
275 | fprintf(header_fp, "profile.process = %s\n", prog); |
276 | |
277 | fputs("version = "BC_VERSION_STR"\n", header_fp); |
278 | if (ENABLE_FEATURE_BOOTCHARTD_BLOATED_HEADER) { |
279 | char *hostname; |
280 | char *kcmdline; |
281 | time_t t; |
282 | struct tm tm_time; |
283 | /* x2 for possible localized weekday/month names */ |
284 | char date_buf[sizeof("Mon Jun 21 05:29:03 CEST 2010") * 2]; |
285 | struct utsname unamebuf; |
286 | |
287 | hostname = safe_gethostname(); |
288 | time(&t); |
289 | localtime_r(&t, &tm_time); |
290 | strftime(date_buf, sizeof(date_buf), "%a %b %e %H:%M:%S %Z %Y", &tm_time); |
291 | fprintf(header_fp, "title = Boot chart for %s (%s)\n", hostname, date_buf); |
292 | if (ENABLE_FEATURE_CLEAN_UP) |
293 | free(hostname); |
294 | |
295 | uname(&unamebuf); /* never fails */ |
296 | /* same as uname -srvm */ |
297 | fprintf(header_fp, "system.uname = %s %s %s %s\n", |
298 | unamebuf.sysname, |
299 | unamebuf.release, |
300 | unamebuf.version, |
301 | unamebuf.machine |
302 | ); |
303 | |
304 | //system.release = `cat /etc/DISTRO-release` |
305 | //system.cpu = `grep '^model name' /proc/cpuinfo | head -1` ($cpucount) |
306 | |
307 | kcmdline = xmalloc_open_read_close("/proc/cmdline", NULL); |
308 | /* kcmdline includes trailing "\n" */ |
309 | fprintf(header_fp, "system.kernel.options = %s", kcmdline); |
310 | if (ENABLE_FEATURE_CLEAN_UP) |
311 | free(kcmdline); |
312 | } |
313 | fclose(header_fp); |
314 | |
315 | /* Package log files */ |
316 | system(xasprintf("tar -zcf /var/log/bootlog.tgz header %s *.log", process_accounting ? "kernel_pacct" : "")); |
317 | /* Clean up (if we are not in detached tmpfs) */ |
318 | if (tempdir) { |
319 | unlink("header"); |
320 | unlink("proc_stat.log"); |
321 | unlink("proc_diskstats.log"); |
322 | //unlink("proc_netdev.log"); |
323 | unlink("proc_ps.log"); |
324 | if (process_accounting) |
325 | unlink("kernel_pacct"); |
326 | rmdir(tempdir); |
327 | } |
328 | |
329 | /* shell-based bootchartd tries to run /usr/bin/bootchart if $AUTO_RENDER=yes: |
330 | * /usr/bin/bootchart -o "$AUTO_RENDER_DIR" -f $AUTO_RENDER_FORMAT "$BOOTLOG_DEST" |
331 | */ |
332 | } |
333 | |
334 | //usage:#define bootchartd_trivial_usage |
335 | //usage: "start [PROG ARGS]|stop|init" |
336 | //usage:#define bootchartd_full_usage "\n\n" |
337 | //usage: "Create /var/log/bootchart.tgz with boot chart data\n" |
338 | //usage: "\nstart: start background logging; with PROG, run PROG, then kill logging with USR1" |
339 | //usage: "\nstop: send USR1 to all bootchartd processes" |
340 | //usage: "\ninit: start background logging; stop when getty/xdm is seen (for init scripts)" |
341 | //usage: "\nUnder PID 1: as init, then exec $bootchart_init, /init, /sbin/init" |
342 | |
343 | int bootchartd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; |
344 | int bootchartd_main(int argc UNUSED_PARAM, char **argv) |
345 | { |
346 | unsigned sample_period_us; |
347 | pid_t parent_pid, logger_pid; |
348 | smallint cmd; |
349 | int process_accounting; |
350 | enum { |
351 | CMD_STOP = 0, |
352 | CMD_START, |
353 | CMD_INIT, |
354 | CMD_PID1, /* used to mark pid 1 case */ |
355 | }; |
356 | |
357 | INIT_G(); |
358 | |
359 | parent_pid = getpid(); |
360 | if (argv[1]) { |
361 | cmd = index_in_strings("stop\0""start\0""init\0", argv[1]); |
362 | if (cmd < 0) |
363 | bb_show_usage(); |
364 | if (cmd == CMD_STOP) { |
365 | pid_t *pidList = find_pid_by_name("bootchartd"); |
366 | while (*pidList != 0) { |
367 | if (*pidList != parent_pid) |
368 | kill(*pidList, SIGUSR1); |
369 | pidList++; |
370 | } |
371 | return EXIT_SUCCESS; |
372 | } |
373 | } else { |
374 | if (parent_pid != 1) |
375 | bb_show_usage(); |
376 | cmd = CMD_PID1; |
377 | } |
378 | |
379 | /* Here we are in START, INIT or CMD_PID1 state */ |
380 | |
381 | /* Read config file: */ |
382 | sample_period_us = 200 * 1000; |
383 | process_accounting = 0; |
384 | if (ENABLE_FEATURE_BOOTCHARTD_CONFIG_FILE) { |
385 | char* token[2]; |
386 | parser_t *parser = config_open2("/etc/bootchartd.conf" + 5, fopen_for_read); |
387 | if (!parser) |
388 | parser = config_open2("/etc/bootchartd.conf", fopen_for_read); |
389 | while (config_read(parser, token, 2, 0, "#=", PARSE_NORMAL & ~PARSE_COLLAPSE)) { |
390 | if (strcmp(token[0], "SAMPLE_PERIOD") == 0 && token[1]) |
391 | sample_period_us = atof(token[1]) * 1000000; |
392 | if (strcmp(token[0], "PROCESS_ACCOUNTING") == 0 && token[1] |
393 | && (strcmp(token[1], "on") == 0 || strcmp(token[1], "yes") == 0) |
394 | ) { |
395 | process_accounting = 1; |
396 | } |
397 | } |
398 | config_close(parser); |
399 | if ((int)sample_period_us <= 0) |
400 | sample_period_us = 1; /* prevent division by 0 */ |
401 | } |
402 | |
403 | /* Create logger child: */ |
404 | logger_pid = fork_or_rexec(argv); |
405 | |
406 | if (logger_pid == 0) { /* child */ |
407 | char *tempdir; |
408 | |
409 | bb_signals(0 |
410 | + (1 << SIGUSR1) |
411 | + (1 << SIGUSR2) |
412 | + (1 << SIGTERM) |
413 | + (1 << SIGQUIT) |
414 | + (1 << SIGINT) |
415 | + (1 << SIGHUP) |
416 | , record_signo); |
417 | |
418 | if (DO_SIGNAL_SYNC) |
419 | /* Inform parent that we are ready */ |
420 | raise(SIGSTOP); |
421 | |
422 | /* If we are started by kernel, PATH might be unset. |
423 | * In order to find "tar", let's set some sane PATH: |
424 | */ |
425 | if (cmd == CMD_PID1 && !getenv("PATH")) |
426 | putenv((char*)bb_PATH_root_path); |
427 | |
428 | tempdir = make_tempdir(); |
429 | do_logging(sample_period_us, process_accounting); |
430 | finalize(tempdir, cmd == CMD_START ? argv[2] : NULL, process_accounting); |
431 | return EXIT_SUCCESS; |
432 | } |
433 | |
434 | /* parent */ |
435 | |
436 | USE_FOR_NOMMU(argv[0][0] &= 0x7f); /* undo fork_or_rexec() damage */ |
437 | |
438 | if (DO_SIGNAL_SYNC) { |
439 | /* Wait for logger child to set handlers, then unpause it. |
440 | * Otherwise with short-lived PROG (e.g. "bootchartd start true") |
441 | * we might send SIGUSR1 before logger sets its handler. |
442 | */ |
443 | waitpid(logger_pid, NULL, WUNTRACED); |
444 | kill(logger_pid, SIGCONT); |
445 | } |
446 | |
447 | if (cmd == CMD_PID1) { |
448 | char *bootchart_init = getenv("bootchart_init"); |
449 | if (bootchart_init) |
450 | execl(bootchart_init, bootchart_init, NULL); |
451 | execl("/init", "init", NULL); |
452 | execl("/sbin/init", "init", NULL); |
453 | bb_perror_msg_and_die("can't execute '%s'", "/sbin/init"); |
454 | } |
455 | |
456 | if (cmd == CMD_START && argv[2]) { /* "start PROG ARGS" */ |
457 | pid_t pid = xvfork(); |
458 | if (pid == 0) { /* child */ |
459 | argv += 2; |
460 | BB_EXECVP_or_die(argv); |
461 | } |
462 | /* parent */ |
463 | waitpid(pid, NULL, 0); |
464 | kill(logger_pid, SIGUSR1); |
465 | } |
466 | |
467 | return EXIT_SUCCESS; |
468 | } |
469 |