1/* bootchartd.c - bootchartd is commonly used to profile the boot process.
2 *
3 * Copyright 2014 Bilal Qureshi <bilal.jmi@gmail.com>
4 * Copyright 2014 Kyungwan Han <asura321@gmail.com>
5 *
6 * No Standard
7
8USE_BOOTCHARTD(NEWTOY(bootchartd, 0, TOYFLAG_STAYROOT|TOYFLAG_USR|TOYFLAG_BIN))
9
10config BOOTCHARTD
11  bool "bootchartd"
12  default n
13  depends on TOYBOX_FORK
14  help
15    usage: bootchartd {start [PROG ARGS]}|stop|init
16
17    Create /var/log/bootlog.tgz with boot chart data
18
19    start: start background logging; with PROG, run PROG,
20           then kill logging with USR1
21    stop:  send USR1 to all bootchartd processes
22    init:  start background logging; stop when getty/xdm is seen
23          (for init scripts)
24
25    Under PID 1: as init, then exec $bootchart_init, /init, /sbin/init
26*/
27
28#define FOR_bootchartd
29#include "toys.h"
30
31GLOBALS(
32  char timestamp[32];
33  long msec;
34  int proc_accounting;
35
36  pid_t pid;
37)
38
39static void dump_data_in_file(char *fname, int wfd)
40{
41  int rfd = open(fname, O_RDONLY);
42
43  if (rfd != -1) {
44    xwrite(wfd, TT.timestamp, strlen(TT.timestamp));
45    xsendfile(rfd, wfd);
46    close(rfd);
47    xwrite(wfd, "\n", 1);
48  }
49}
50
51static int dump_proc_data(FILE *fp)
52{
53  struct dirent *pid_dir;
54  int login_flag = 0;
55  pid_t pid;
56  DIR *proc_dir = opendir("/proc");
57
58  fputs(TT.timestamp, fp);
59  while ((pid_dir = readdir(proc_dir))) {
60    char filename[64];
61    int fd;
62
63    if (!isdigit(pid_dir->d_name[0])) continue;
64    sscanf(pid_dir->d_name, "%d", &pid);
65    sprintf(filename, "/proc/%d/stat", pid);
66    if ((fd = open(filename, O_RDONLY)) != -1 ) {
67      char *ptr;
68      ssize_t len;
69
70      if ((len = readall(fd, toybuf, sizeof(toybuf)-1)) < 0) {
71        xclose(fd);
72        continue;
73      }
74      toybuf[len] = '\0';
75      close(fd);
76      fputs(toybuf, fp);
77      if (TT.pid != 1) continue;
78      if ((ptr = strchr(toybuf, '('))) {
79        char *tmp = strchr(++ptr, ')');
80
81        if (tmp) *tmp = '\0';
82      }
83      // Checks for gdm, kdm or getty
84      if (((ptr[0] == 'g' || ptr[0] == 'k' || ptr[0] == 'x') && ptr[1] == 'd'
85            && ptr[2] == 'm') || strstr(ptr, "getty")) login_flag = 1;
86    }
87  }
88  closedir(proc_dir);
89  fputc('\n', fp);
90  return login_flag;
91}
92
93static int parse_config_file(char *fname)
94{
95  size_t len = 0;
96  char  *line = 0;
97  FILE *fp = fopen(fname, "r");
98
99  if (!fp) return 0;
100  for (;getline(&line, &len, fp) != -1; line = 0) {
101    char *ptr = line;
102
103    while (*ptr == ' ' || *ptr == '\t') ptr++;
104    if (!*ptr || *ptr == '#' || *ptr == '\n') continue;
105    if (strstart(&ptr, "SAMPLE_PERIOD=")) {
106      double dd;
107
108      sscanf(ptr, "%lf", &dd);
109      if ((TT.msec = dd*1000)<1) TT.msec = 1;
110    } else if (strstart(&ptr, "PROCESS_ACCOUNTING="))
111      if (strstart(&ptr, "\"on\"") || strstart(&ptr, "\"yes\""))
112        TT.proc_accounting = 1;
113    free(line);
114  }
115  fclose(fp);
116  return 1;
117}
118
119static char *create_tmp_dir()
120{
121  char *dir_list[] = {"/tmp", "/mnt", "/boot", "/proc"}, **target = dir_list;
122  char *dir, dir_path[] = "/tmp/bootchart.XXXXXX";
123
124  if ((dir = mkdtemp(dir_path))) {
125    xchdir((dir = xstrdup(dir)));
126    return dir;
127  }
128  while (mount("none", *target, "tmpfs", (1<<15), "size=16m")) //MS_SILENT
129    if (!++target) perror_exit("can't mount tmpfs");
130  xchdir(*target);
131  if (umount2(*target, MNT_DETACH)) perror_exit("Can't unmount tmpfs");
132  return *target;
133}
134
135static void start_logging()
136{
137  struct timespec ts;
138  int proc_stat_fd = xcreate("proc_stat.log",
139      O_WRONLY | O_CREAT | O_TRUNC, 0644);
140  int proc_diskstats_fd = xcreate("proc_diskstats.log",
141      O_WRONLY | O_CREAT | O_TRUNC, 0644);
142  FILE *proc_ps_fp = xfopen("proc_ps.log", "w");
143  long tcnt = 60 * 1000 / TT.msec;
144
145  if (tcnt <= 0) tcnt = 1;
146  if (TT.proc_accounting) {
147    int kp_fd = xcreate("kernel_procs_acct", O_WRONLY | O_CREAT | O_TRUNC,0666);
148
149    xclose(kp_fd);
150    acct("kernel_procs_acct");
151  }
152  while (--tcnt && !toys.signal) {
153    clock_gettime(CLOCK_BOOTTIME, &ts);
154    sprintf(TT.timestamp, "%ld.%02d\n", (long) ts.tv_sec,
155        (int) (ts.tv_nsec/10000000));
156    dump_data_in_file("/proc/stat", proc_stat_fd);
157    dump_data_in_file("/proc/diskstats", proc_diskstats_fd);
158    // stop proc dumping in 2 secs if getty or gdm, kdm, xdm found
159    if (dump_proc_data(proc_ps_fp))
160      if (tcnt > 2 * 1000 / TT.msec) tcnt = 2 * 1000 / TT.msec;
161    fflush(0);
162    msleep(TT.msec);
163  }
164  xclose(proc_stat_fd);
165  xclose(proc_diskstats_fd);
166  fclose(proc_ps_fp);
167}
168
169static void stop_logging(char *tmp_dir, char *prog)
170{
171  char host_name[32];
172  int kcmd_line_fd;
173  time_t t;
174  struct tm st;
175  struct utsname uts;
176  FILE *hdr_fp = xfopen("header", "w");
177
178  if (TT.proc_accounting) acct(NULL);
179  if (prog) fprintf(hdr_fp, "profile.process = %s\n", prog);
180  gethostname(host_name, sizeof(host_name));
181  time(&t);
182  localtime_r(&t, &st);
183  memset(toybuf, 0, sizeof(toybuf));
184  strftime(toybuf, sizeof(toybuf), "%a %b %e %H:%M:%S %Z %Y", &st);
185  fprintf(hdr_fp, "version = TBX_BCHARTD_VER 1.0.0\n");
186  fprintf(hdr_fp, "title = Boot chart for %s (%s)\n", host_name, toybuf);
187  if (uname(&uts) < 0) perror_exit("uname");
188  fprintf(hdr_fp, "system.uname = %s %s %s %s\n", uts.sysname, uts.release,
189      uts.version, uts.machine);
190  memset(toybuf, 0, sizeof(toybuf));
191  if ((kcmd_line_fd = open("/proc/cmdline", O_RDONLY)) != -1) {
192    ssize_t len;
193
194    if ((len = readall(kcmd_line_fd, toybuf, sizeof(toybuf)-1)) > 0) {
195      toybuf[len] = 0;
196      while (--len >= 0 && !toybuf[len]) continue;
197      for (; len > 0; len--) if (toybuf[len] < ' ') toybuf[len] = ' ';
198    } else *toybuf = 0;
199  }
200  fprintf(hdr_fp, "system.kernel.options = %s", toybuf);
201  close(kcmd_line_fd);
202  fclose(hdr_fp);
203  memset(toybuf, 0, sizeof(toybuf));
204  snprintf(toybuf, sizeof(toybuf), "tar -zcf /var/log/bootlog.tgz header %s *.log",
205      TT.proc_accounting ? "kernel_procs_acct" : "");
206  system(toybuf);
207  if (tmp_dir) {
208    unlink("header");
209    unlink("proc_stat.log");
210    unlink("proc_diskstats.log");
211    unlink("proc_ps.log");
212    if (TT.proc_accounting) unlink("kernel_procs_acct");
213    rmdir(tmp_dir);
214  }
215}
216
217static int signal_pid(pid_t pid, char *name)
218{
219  if (pid != TT.pid) kill(pid, SIGUSR1);
220  return 0;
221}
222
223void bootchartd_main()
224{
225  pid_t lgr_pid;
226  int bchartd_opt = 0; // 0=PID1, 1=start, 2=stop, 3=init
227
228  TT.pid = getpid();
229  TT.msec = 200;
230
231  if (*toys.optargs) {
232    if (!strcmp("start", *toys.optargs)) bchartd_opt = 1;
233    else if (!strcmp("stop", *toys.optargs)) bchartd_opt = 2;
234    else if (!strcmp("init", *toys.optargs)) bchartd_opt = 3;
235    else error_exit("Unknown option '%s'", *toys.optargs);
236
237    if (bchartd_opt == 2) {
238      char *process_name[] = {"bootchartd", NULL};
239
240      names_to_pid(process_name, signal_pid, 0);
241      return;
242    }
243  } else if (TT.pid != 1) error_exit("not PID 1");
244
245  // Execute the code below for start or init or PID1
246  if (!parse_config_file("bootchartd.conf"))
247    parse_config_file("/etc/bootchartd.conf");
248
249  memset(toybuf, 0, sizeof(toybuf));
250  if (!(lgr_pid = xfork())) {
251    char *tmp_dir = create_tmp_dir();
252
253    sigatexit(generic_signal);
254    raise(SIGSTOP);
255    if (!bchartd_opt && !getenv("PATH"))
256      putenv("PATH=/sbin:/usr/sbin:/bin:/usr/bin");
257    start_logging();
258    stop_logging(tmp_dir, bchartd_opt == 1 ? toys.optargs[1] : NULL);
259    return;
260  }
261  waitpid(lgr_pid, NULL, WUNTRACED);
262  kill(lgr_pid, SIGCONT);
263
264  if (!bchartd_opt) {
265    char *pbchart_init = getenv("bootchart_init");
266
267    if (pbchart_init) execl(pbchart_init, pbchart_init, NULL);
268    execl("/init", "init", (void *)0);
269    execl("/sbin/init", "init", (void *)0);
270  }
271  if (bchartd_opt == 1 && toys.optargs[1]) {
272    pid_t prog_pid;
273
274    if (!(prog_pid = xfork())) xexec(toys.optargs+1);
275    waitpid(prog_pid, NULL, 0);
276    kill(lgr_pid, SIGUSR1);
277  }
278}
279