bootchartd.c 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  4. */
  5. #include "libbb.h"
  6. #include <sys/mount.h>
  7. #ifndef MS_SILENT
  8. # define MS_SILENT (1 << 15)
  9. #endif
  10. #ifndef MNT_DETACH
  11. # define MNT_DETACH 0x00000002
  12. #endif
  13. #define BC_VERSION_STR "0.8"
  14. /* For debugging, set to 0:
  15. * strace won't work with DO_SIGNAL_SYNC set to 1.
  16. */
  17. #define DO_SIGNAL_SYNC 1
  18. //Not supported: $PWD/bootchartd.conf and /etc/bootchartd.conf
  19. //# tmpfs size
  20. //# (32 MB should suffice for ~20 minutes worth of log data, but YMMV)
  21. //TMPFS_SIZE=32m
  22. //
  23. //# Sampling period (in seconds)
  24. //SAMPLE_PERIOD=0.2
  25. //
  26. //# Whether to enable and store BSD process accounting information. The
  27. //# kernel needs to be configured to enable v3 accounting
  28. //# (CONFIG_BSD_PROCESS_ACCT_V3). accton from the GNU accounting utilities
  29. //# is also required.
  30. //PROCESS_ACCOUNTING="no"
  31. //
  32. //# Tarball for the various boot log files
  33. //BOOTLOG_DEST=/var/log/bootchart.tgz
  34. //
  35. //# Whether to automatically stop logging as the boot process completes.
  36. //# The logger will look for known processes that indicate bootup completion
  37. //# at a specific runlevel (e.g. gdm-binary, mingetty, etc.).
  38. //AUTO_STOP_LOGGER="yes"
  39. //
  40. //# Whether to automatically generate the boot chart once the boot logger
  41. //# completes. The boot chart will be generated in $AUTO_RENDER_DIR.
  42. //# Note that the bootchart package must be installed.
  43. //AUTO_RENDER="no"
  44. //
  45. //# Image format to use for the auto-generated boot chart
  46. //# (choose between png, svg and eps).
  47. //AUTO_RENDER_FORMAT="png"
  48. //
  49. //# Output directory for auto-generated boot charts
  50. //AUTO_RENDER_DIR="/var/log"
  51. /* Globals */
  52. struct globals {
  53. char jiffy_line[sizeof(bb_common_bufsiz1)];
  54. } FIX_ALIASING;
  55. #define G (*(struct globals*)&bb_common_bufsiz1)
  56. #define INIT_G() do { } while (0)
  57. static void dump_file(FILE *fp, const char *filename)
  58. {
  59. int fd = open(filename, O_RDONLY);
  60. if (fd >= 0) {
  61. fputs(G.jiffy_line, fp);
  62. fflush(fp);
  63. bb_copyfd_eof(fd, fileno(fp));
  64. close(fd);
  65. fputc('\n', fp);
  66. }
  67. }
  68. static int dump_procs(FILE *fp, int look_for_login_process)
  69. {
  70. struct dirent *entry;
  71. DIR *dir = opendir("/proc");
  72. int found_login_process = 0;
  73. fputs(G.jiffy_line, fp);
  74. while ((entry = readdir(dir)) != NULL) {
  75. char name[sizeof("/proc/%u/cmdline") + sizeof(int)*3];
  76. int stat_fd;
  77. unsigned pid = bb_strtou(entry->d_name, NULL, 10);
  78. if (errno)
  79. continue;
  80. /* Android's version reads /proc/PID/cmdline and extracts
  81. * non-truncated process name. Do we want to do that? */
  82. sprintf(name, "/proc/%u/stat", pid);
  83. stat_fd = open(name, O_RDONLY);
  84. if (stat_fd >= 0) {
  85. char *p;
  86. char stat_line[4*1024];
  87. int rd = safe_read(stat_fd, stat_line, sizeof(stat_line)-2);
  88. close(stat_fd);
  89. if (rd < 0)
  90. continue;
  91. stat_line[rd] = '\0';
  92. p = strchrnul(stat_line, '\n');
  93. *p++ = '\n';
  94. *p = '\0';
  95. fputs(stat_line, fp);
  96. if (!look_for_login_process)
  97. continue;
  98. p = strchr(stat_line, '(');
  99. if (!p)
  100. continue;
  101. p++;
  102. strchrnul(p, ')')[0] = '\0';
  103. /* If is gdm, kdm or a getty? */
  104. if (((p[0] == 'g' || p[0] == 'k' || p[0] == 'x') && p[1] == 'd' && p[2] == 'm')
  105. || strstr(p, "getty")
  106. ) {
  107. found_login_process = 1;
  108. }
  109. }
  110. }
  111. closedir(dir);
  112. fputc('\n', fp);
  113. return found_login_process;
  114. }
  115. static char *make_tempdir(const char *prog)
  116. {
  117. char template[] = "/tmp/bootchart.XXXXXX";
  118. char *tempdir = xstrdup(mkdtemp(template));
  119. if (!tempdir) {
  120. /* /tmp is not writable (happens when we are used as init).
  121. * Try to mount a tmpfs, them cd and lazily unmount it.
  122. * Since we unmount it at once, we can mount it anywhere.
  123. * Try a few locations which are likely ti exist.
  124. */
  125. static const char dirs[] = "/mnt\0""/tmp\0""/boot\0""/proc\0";
  126. const char *try_dir = dirs;
  127. while (mount("none", try_dir, "tmpfs", MS_SILENT, "size=16m") != 0) {
  128. try_dir += strlen(try_dir) + 1;
  129. if (!try_dir[0])
  130. bb_perror_msg_and_die("can't %smount tmpfs", "");
  131. }
  132. //bb_error_msg("mounted tmpfs on %s", try_dir);
  133. xchdir(try_dir);
  134. if (umount2(try_dir, MNT_DETACH) != 0) {
  135. bb_perror_msg_and_die("can't %smount tmpfs", "un");
  136. }
  137. } else {
  138. xchdir(tempdir);
  139. }
  140. {
  141. FILE *header_fp = xfopen("header", "w");
  142. if (prog)
  143. fprintf(header_fp, "profile.process = %s\n", prog);
  144. fputs("version = "BC_VERSION_STR"\n", header_fp);
  145. fclose(header_fp);
  146. }
  147. return tempdir;
  148. }
  149. static void do_logging(void)
  150. {
  151. //# Enable process accounting if configured
  152. //if [ "$PROCESS_ACCOUNTING" = "yes" ]; then
  153. // [ -e kernel_pacct ] || : > kernel_pacct
  154. // accton kernel_pacct
  155. //fi
  156. FILE *proc_stat = xfopen("proc_stat.log", "w");
  157. FILE *proc_diskstats = xfopen("proc_diskstats.log", "w");
  158. //FILE *proc_netdev = xfopen("proc_netdev.log", "w");
  159. FILE *proc_ps = xfopen("proc_ps.log", "w");
  160. int look_for_login_process = (getppid() == 1);
  161. unsigned count = 60*1000*1000 / (200*1000); /* ~1 minute */
  162. while (--count && !bb_got_signal) {
  163. char *p;
  164. int len = open_read_close("/proc/uptime", G.jiffy_line, sizeof(G.jiffy_line)-2);
  165. if (len < 0)
  166. goto wait_more;
  167. /* /proc/uptime has format "NNNNNN.MM NNNNNNN.MM" */
  168. /* we convert it to "NNNNNNMM\n" (using first value) */
  169. G.jiffy_line[len] = '\0';
  170. p = strchr(G.jiffy_line, '.');
  171. if (!p)
  172. goto wait_more;
  173. while (isdigit(*++p))
  174. p[-1] = *p;
  175. p[-1] = '\n';
  176. p[0] = '\0';
  177. dump_file(proc_stat, "/proc/stat");
  178. dump_file(proc_diskstats, "/proc/diskstats");
  179. //dump_file(proc_netdev, "/proc/net/dev");
  180. if (dump_procs(proc_ps, look_for_login_process)) {
  181. /* dump_procs saw a getty or {g,k,x}dm
  182. * stop logging in 2 seconds:
  183. */
  184. if (count > 2*1000*1000 / (200*1000))
  185. count = 2*1000*1000 / (200*1000);
  186. }
  187. fflush_all();
  188. wait_more:
  189. usleep(200*1000);
  190. }
  191. // [ -e kernel_pacct ] && accton off
  192. }
  193. static void finalize(char *tempdir)
  194. {
  195. //# Stop process accounting if configured
  196. //local pacct=
  197. //[ -e kernel_pacct ] && pacct=kernel_pacct
  198. //(
  199. // echo "version = $VERSION"
  200. // echo "title = Boot chart for $( hostname | sed q ) ($( date ))"
  201. // echo "system.uname = $( uname -srvm | sed q )"
  202. // echo "system.release = $( sed q /etc/SuSE-release )"
  203. // echo "system.cpu = $( grep '^model name' /proc/cpuinfo | sed q ) ($cpucount)"
  204. // echo "system.kernel.options = $( sed q /proc/cmdline )"
  205. //) >> header
  206. /* Package log files */
  207. system("tar -zcf /var/log/bootchart.tgz header *.log"); // + $pacct
  208. /* Clean up (if we are not in detached tmpfs) */
  209. if (tempdir) {
  210. unlink("header");
  211. unlink("proc_stat.log");
  212. unlink("proc_diskstats.log");
  213. //unlink("proc_netdev.log");
  214. unlink("proc_ps.log");
  215. rmdir(tempdir);
  216. }
  217. /* shell-based bootchartd tries to run /usr/bin/bootchart if $AUTO_RENDER=yes:
  218. * /usr/bin/bootchart -o "$AUTO_RENDER_DIR" -f $AUTO_RENDER_FORMAT "$BOOTLOG_DEST"
  219. */
  220. }
  221. /* Usage:
  222. * bootchartd start [PROG ARGS]: start logging in background, USR1 stops it.
  223. * With PROG, runs PROG, then kills background logging.
  224. * bootchartd stop: same as "killall -USR1 bootchartd"
  225. * bootchartd init: start logging in background
  226. * Stop when getty/gdm is seen (if AUTO_STOP_LOGGER = yes).
  227. * Meant to be used from init scripts.
  228. * bootchartd (pid==1): as init, but then execs $bootchart_init, /init, /sbin/init
  229. * Meant to be used as kernel's init process.
  230. */
  231. int bootchartd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  232. int bootchartd_main(int argc UNUSED_PARAM, char **argv)
  233. {
  234. pid_t parent_pid, logger_pid;
  235. smallint cmd;
  236. enum {
  237. CMD_STOP = 0,
  238. CMD_START,
  239. CMD_INIT,
  240. CMD_PID1, /* used to mark pid 1 case */
  241. };
  242. INIT_G();
  243. parent_pid = getpid();
  244. if (argv[1]) {
  245. cmd = index_in_strings("stop\0""start\0""init\0", argv[1]);
  246. if (cmd < 0)
  247. bb_show_usage();
  248. if (cmd == CMD_STOP) {
  249. pid_t *pidList = find_pid_by_name("bootchartd");
  250. while (*pidList != 0) {
  251. if (*pidList != parent_pid)
  252. kill(*pidList, SIGUSR1);
  253. pidList++;
  254. }
  255. return EXIT_SUCCESS;
  256. }
  257. } else {
  258. if (parent_pid != 1)
  259. bb_show_usage();
  260. cmd = CMD_PID1;
  261. }
  262. /* Here we are in START or INIT state. Create logger child: */
  263. logger_pid = fork_or_rexec(argv);
  264. if (logger_pid == 0) { /* child */
  265. char *tempdir;
  266. bb_signals(0
  267. + (1 << SIGUSR1)
  268. + (1 << SIGUSR2)
  269. + (1 << SIGTERM)
  270. + (1 << SIGQUIT)
  271. + (1 << SIGINT)
  272. + (1 << SIGHUP)
  273. , record_signo);
  274. if (DO_SIGNAL_SYNC)
  275. /* Inform parent that we are ready */
  276. raise(SIGSTOP);
  277. /* If we are started by kernel, PATH might be unset.
  278. * In order to find "tar", let's set some sane PATH:
  279. */
  280. if (cmd == CMD_PID1 && !getenv("PATH"))
  281. putenv((char*)bb_PATH_root_path);
  282. tempdir = make_tempdir(cmd == CMD_START ? argv[2] : NULL);
  283. do_logging();
  284. finalize(tempdir);
  285. return EXIT_SUCCESS;
  286. }
  287. /* parent */
  288. if (DO_SIGNAL_SYNC) {
  289. /* Wait for logger child to set handlers, then unpause it.
  290. * Otherwise with short-lived PROG (e.g. "bootchartd start true")
  291. * we might send SIGUSR1 before logger sets its handler.
  292. */
  293. waitpid(logger_pid, NULL, WUNTRACED);
  294. kill(logger_pid, SIGCONT);
  295. }
  296. if (cmd == CMD_PID1) {
  297. char *bootchart_init = getenv("bootchart_init");
  298. if (bootchart_init)
  299. execl(bootchart_init, bootchart_init, NULL);
  300. execl("/init", "init", NULL);
  301. execl("/sbin/init", "init", NULL);
  302. bb_perror_msg_and_die("can't exec '%s'", "/sbin/init");
  303. }
  304. if (cmd == CMD_START && argv[2]) { /* "start PROG ARGS" */
  305. pid_t pid = vfork();
  306. if (pid < 0)
  307. bb_perror_msg_and_die("vfork");
  308. if (pid == 0) { /* child */
  309. argv += 2;
  310. execvp(argv[0], argv);
  311. bb_perror_msg_and_die("can't exec '%s'", argv[0]);
  312. }
  313. /* parent */
  314. waitpid(pid, NULL, 0);
  315. kill(logger_pid, SIGUSR1);
  316. }
  317. return EXIT_SUCCESS;
  318. }