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