bootchartd.c 13 KB

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