bootchartd.c 13 KB

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