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