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