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