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 buf[32];
33  long smpl_period_usec;
34  int proc_accounting;
35  int is_login;
36
37  void *head;
38)
39
40struct pid_list {
41  struct pid_list *next, *prev;
42  int pid;
43};
44
45static int push_pids_in_list(pid_t pid, char *name)
46{
47  struct pid_list *new = xzalloc(sizeof(struct pid_list));
48
49  new->pid = pid;
50  dlist_add_nomalloc((void *)&TT.head, (void *)new);
51
52  return 0;
53}
54
55static void dump_data_in_file(char *fname, int wfd)
56{
57  int rfd = open(fname, O_RDONLY);
58
59  if (rfd != -1) {
60    xwrite(wfd, TT.buf, strlen(TT.buf));
61    xsendfile(rfd, wfd);
62    close(rfd);
63    xwrite(wfd, "\n", 1);
64  }
65}
66
67static int dump_proc_data(FILE *fp)
68{
69  struct dirent *pid_dir;
70  int login_flag = 0;
71  pid_t pid;
72  DIR *proc_dir = opendir("/proc");
73
74  fputs(TT.buf, fp);
75  while ((pid_dir = readdir(proc_dir))) {
76    char filename[64];
77    int fd;
78
79    if (!isdigit(pid_dir->d_name[0])) continue;
80    sscanf(pid_dir->d_name, "%d", &pid);
81    sprintf(filename, "/proc/%d/stat", pid);
82    if ((fd = open(filename, O_RDONLY)) != -1 ) {
83      char *ptr;
84      ssize_t len;
85
86      if ((len = readall(fd, toybuf, sizeof(toybuf)-1)) < 0) {
87        xclose(fd);
88        continue;
89      }
90      toybuf[len] = '\0';
91      close(fd);
92      fputs(toybuf, fp);
93      if (!TT.is_login) continue;
94      if ((ptr = strchr(toybuf, '('))) {
95        char *tmp = strchr(++ptr, ')');
96
97        if (tmp) *tmp = '\0';
98      }
99      // Checks for gdm, kdm or getty
100      if (((ptr[0] == 'g' || ptr[0] == 'k' || ptr[0] == 'x') && ptr[1] == 'd'
101            && ptr[2] == 'm') || strstr(ptr, "getty")) login_flag = 1;
102    }
103  }
104  closedir(proc_dir);
105  fputc('\n', fp);
106  return login_flag;
107}
108
109static int parse_config_file(char *fname)
110{
111  size_t len = 0;
112  char  *line = NULL;
113  FILE *fp = fopen(fname, "r");
114
115  if (!fp) return 0;
116  for (;getline(&line, &len, fp) != -1; line = NULL) {
117    char *ptr = line;
118
119    while (*ptr == ' ' || *ptr == '\t') ptr++;
120    if (!*ptr || *ptr == '#' || *ptr == '\n') continue;
121    if (!strncmp(ptr, "SAMPLE_PERIOD", strlen("SAMPLE_PERIOD"))) {
122      double smpl_val;
123
124      if ((ptr = strchr(ptr, '='))) ptr += 1;
125      else continue;
126      sscanf(ptr, "%lf", &smpl_val);
127      TT.smpl_period_usec = smpl_val * 1000000;
128      if (TT.smpl_period_usec <= 0) TT.smpl_period_usec = 1;
129    }
130    if (!strncmp(ptr, "PROCESS_ACCOUNTING", strlen("PROCESS_ACCOUNTING"))) {
131      if ((ptr = strchr(ptr, '='))) ptr += 1;
132      else continue;
133      sscanf(ptr, "%s", toybuf);  // string will come with double quotes.
134      if (!(strncmp(toybuf+1, "on", strlen("on"))) ||
135          !(strncmp(toybuf+1, "yes", strlen("yes")))) TT.proc_accounting = 1;
136    }
137    free(line);
138  }
139  fclose(fp);
140  return 1;
141}
142
143static char *create_tmp_dir()
144{
145  char *dir_list[] = {"/tmp", "/mnt", "/boot", "/proc"}, **target = dir_list;
146  char *dir, dir_path[] = "/tmp/bootchart.XXXXXX";
147
148  if ((dir = mkdtemp(dir_path))) {
149    xchdir((dir = xstrdup(dir)));
150    return dir;
151  }
152  while (mount("none", *target, "tmpfs", (1<<15), "size=16m")) //MS_SILENT
153    if (!++target) perror_exit("can't mount tmpfs");
154  xchdir(*target);
155  if (umount2(*target, MNT_DETACH)) perror_exit("Can't unmount tmpfs");
156  return *target;
157}
158
159static void start_logging()
160{
161  int proc_stat_fd = xcreate("proc_stat.log",
162      O_WRONLY | O_CREAT | O_TRUNC, 0644);
163  int proc_diskstats_fd = xcreate("proc_diskstats.log",
164      O_WRONLY | O_CREAT | O_TRUNC, 0644);
165  FILE *proc_ps_fp = xfopen("proc_ps.log", "w");
166  long tcnt = 60 * 1000 * 1000 / TT.smpl_period_usec;
167
168  if (tcnt <= 0) tcnt = 1;
169  if (TT.proc_accounting) {
170    int kp_fd = xcreate("kernel_procs_acct", O_WRONLY | O_CREAT | O_TRUNC,0666);
171
172    xclose(kp_fd);
173    acct("kernel_procs_acct");
174  }
175  memset(TT.buf, 0, sizeof(TT.buf));
176  while (--tcnt && !toys.signal) {
177    int i = 0, j = 0, fd = open("/proc/uptime", O_RDONLY);
178    if (fd < 0) goto wait_usec;
179    char *line = get_line(fd);
180
181    if (!line)  goto wait_usec;
182    while (line[i] != ' ') {
183      if (line[i] == '.') {
184        i++;
185        continue;
186      }
187      TT.buf[j++] = line[i++];
188    }
189    TT.buf[j++] = '\n';
190    TT.buf[j] = '\0';
191    free(line);
192    close(fd);
193    dump_data_in_file("/proc/stat", proc_stat_fd);
194    dump_data_in_file("/proc/diskstats", proc_diskstats_fd);
195    // stop proc dumping in 2 secs if getty or gdm, kdm, xdm found
196    if (dump_proc_data(proc_ps_fp))
197      if (tcnt > 2 * 1000 * 1000 / TT.smpl_period_usec)
198        tcnt = 2 * 1000 * 1000 / TT.smpl_period_usec;
199    fflush(NULL);
200wait_usec:
201    usleep(TT.smpl_period_usec);
202  }
203  xclose(proc_stat_fd);
204  xclose(proc_diskstats_fd);
205  fclose(proc_ps_fp);
206}
207
208static void stop_logging(char *tmp_dir, char *prog)
209{
210  char host_name[32];
211  int kcmd_line_fd;
212  time_t t;
213  struct tm st;
214  struct utsname uts;
215  FILE *hdr_fp = xfopen("header", "w");
216
217  if (TT.proc_accounting) acct(NULL);
218  if (prog) fprintf(hdr_fp, "profile.process = %s\n", prog);
219  gethostname(host_name, sizeof(host_name));
220  time(&t);
221  localtime_r(&t, &st);
222  memset(toybuf, 0, sizeof(toybuf));
223  strftime(toybuf, sizeof(toybuf), "%a %b %e %H:%M:%S %Z %Y", &st);
224  fprintf(hdr_fp, "version = TBX_BCHARTD_VER 1.0.0\n");
225  fprintf(hdr_fp, "title = Boot chart for %s (%s)\n", host_name, toybuf);
226  if (uname(&uts) < 0) perror_exit("uname");
227  fprintf(hdr_fp, "system.uname = %s %s %s %s\n", uts.sysname, uts.release,
228      uts.version, uts.machine);
229  memset(toybuf, 0, sizeof(toybuf));
230  if ((kcmd_line_fd = open("/proc/cmdline", O_RDONLY)) != -1) {
231    ssize_t len;
232
233    if ((len = readall(kcmd_line_fd, toybuf, sizeof(toybuf)-1)) > 0) {
234      toybuf[len] = 0;
235      while (--len >= 0 && !toybuf[len]) continue;
236      for (; len > 0; len--) if (toybuf[len] < ' ') toybuf[len] = ' ';
237    } else *toybuf = 0;
238  }
239  fprintf(hdr_fp, "system.kernel.options = %s", toybuf);
240  close(kcmd_line_fd);
241  fclose(hdr_fp);
242  memset(toybuf, 0, sizeof(toybuf));
243  snprintf(toybuf, sizeof(toybuf), "tar -zcf /var/log/bootlog.tgz header %s *.log",
244      TT.proc_accounting ? "kernel_procs_acct" : "");
245  system(toybuf);
246  if (tmp_dir) {
247    unlink("header");
248    unlink("proc_stat.log");
249    unlink("proc_diskstats.log");
250    unlink("proc_ps.log");
251    if (TT.proc_accounting) unlink("kernel_procs_acct");
252    rmdir(tmp_dir);
253  }
254}
255
256void bootchartd_main()
257{
258  pid_t lgr_pid, self_pid = getpid();
259  int bchartd_opt = 0; // 0=PID1, 1=start, 2=stop, 3=init
260  TT.smpl_period_usec = 200 * 1000;
261
262  TT.is_login = (self_pid == 1);
263  if (*toys.optargs) {
264    if (!strcmp("start", *toys.optargs)) bchartd_opt = 1;
265    else if (!strcmp("stop", *toys.optargs)) bchartd_opt = 2;
266    else if (!strcmp("init", *toys.optargs)) bchartd_opt = 3;
267    else error_exit("Unknown option '%s'", *toys.optargs);
268
269    if (bchartd_opt == 2) {
270      struct pid_list *temp;
271      char *process_name[] = {"bootchartd", NULL};
272
273      names_to_pid(process_name, push_pids_in_list);
274      temp = TT.head;
275      if (temp) temp->prev->next = 0;
276      for (; temp; temp = temp->next)
277        if (temp->pid != self_pid) kill(temp->pid, SIGUSR1);
278      llist_traverse(TT.head, free);
279
280      return;
281    }
282  } else if (!TT.is_login) error_exit("not PID 1");
283
284  // Execute the code below for start or init or PID1
285  if (!parse_config_file("bootchartd.conf"))
286    parse_config_file("/etc/bootchartd.conf");
287
288  memset(toybuf, 0, sizeof(toybuf));
289  if (!(lgr_pid = xfork())) {
290    char *tmp_dir = create_tmp_dir();
291
292    sigatexit(generic_signal);
293    raise(SIGSTOP);
294    if (!bchartd_opt && !getenv("PATH"))
295      putenv("PATH=/sbin:/usr/sbin:/bin:/usr/bin");
296    start_logging();
297    stop_logging(tmp_dir, bchartd_opt == 1 ? toys.optargs[1] : NULL);
298    return;
299  }
300  waitpid(lgr_pid, NULL, WUNTRACED);
301  kill(lgr_pid, SIGCONT);
302
303  if (!bchartd_opt) {
304    char *pbchart_init = getenv("bootchart_init");
305
306    if (pbchart_init) execl(pbchart_init, pbchart_init, NULL);
307    execl("/init", "init", (void *)0);
308    execl("/sbin/init", "init", (void *)0);
309  }
310  if (bchartd_opt == 1 && toys.optargs[1]) {
311    pid_t prog_pid;
312
313    if (!(prog_pid = xfork())) xexec(toys.optargs+1);
314    waitpid(prog_pid, NULL, 0);
315    kill(lgr_pid, SIGUSR1);
316  }
317}
318