xref: /netbsd-src/usr.sbin/sa/main.c (revision 4e6df137e8e14049b5a701d249962c480449c141)
1 /* $NetBSD: main.c,v 1.25 2009/11/17 18:37:45 drochner Exp $ */
2 
3 /*
4  * Copyright (c) 1994 Christopher G. Demetriou
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *          This product includes software developed for the
18  *          NetBSD Project.  See http://www.NetBSD.org/ for
19  *          information about NetBSD.
20  * 4. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  *
34  * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
35  */
36 
37 #include <sys/cdefs.h>
38 #ifndef lint
39 __COPYRIGHT("@(#) Copyright (c) 1994\
40  Christopher G. Demetriou.  All rights reserved.");
41 
42 __RCSID("$NetBSD: main.c,v 1.25 2009/11/17 18:37:45 drochner Exp $");
43 #endif
44 
45 /*
46  * sa:	system accounting
47  */
48 
49 #include <sys/types.h>
50 #include <sys/acct.h>
51 #include <ctype.h>
52 #include <err.h>
53 #include <vis.h>
54 #include <fcntl.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 #include "extern.h"
61 #include "pathnames.h"
62 
63 static int	acct_load	__P((char *, int));
64 static u_quad_t	decode_comp_t	__P((comp_t));
65 static int	cmp_comm	__P((const char *, const char *));
66 static int	cmp_usrsys	__P((const DBT *, const DBT *));
67 static int	cmp_avgusrsys	__P((const DBT *, const DBT *));
68 static int	cmp_dkio	__P((const DBT *, const DBT *));
69 static int	cmp_avgdkio	__P((const DBT *, const DBT *));
70 static int	cmp_cpumem	__P((const DBT *, const DBT *));
71 static int	cmp_avgcpumem	__P((const DBT *, const DBT *));
72 static int	cmp_calls	__P((const DBT *, const DBT *));
73 static void	usage		__P((void)) __dead;
74 
75 int aflag, bflag, cflag, dflag, Dflag, fflag, iflag, jflag, kflag;
76 int Kflag, lflag, mflag, qflag, rflag, sflag, tflag, uflag, vflag;
77 int cutoff = 1;
78 
79 static const char	*dfltargv[] = { _PATH_ACCT };
80 static const int	dfltargc = (sizeof(dfltargv)/sizeof(char *));
81 
82 /* default to comparing by sum of user + system time */
83 cmpf_t   sa_cmp = cmp_usrsys;
84 
85 int
86 main(argc, argv)
87 	int argc;
88 	char **argv;
89 {
90 	int ch;
91 	int error;
92 
93 	error = 0;
94 	while ((ch = getopt(argc, argv, "abcdDfijkKlmnqrstuv:")) != -1)
95 		switch (ch) {
96 		case 'a':
97 			/* print all commands */
98 			aflag = 1;
99 			break;
100 		case 'b':
101 			/* sort by per-call user/system time average */
102 			bflag = 1;
103 			sa_cmp = cmp_avgusrsys;
104 			break;
105 		case 'c':
106 			/* print percentage total time */
107 			cflag = 1;
108 			break;
109 		case 'd':
110 			/* sort by averge number of disk I/O ops */
111 			dflag = 1;
112 			sa_cmp = cmp_avgdkio;
113 			break;
114 		case 'D':
115 			/* print and sort by total disk I/O ops */
116 			Dflag = 1;
117 			sa_cmp = cmp_dkio;
118 			break;
119 		case 'f':
120 			/* force no interactive threshold comprison */
121 			fflag = 1;
122 			break;
123 		case 'i':
124 			/* do not read in summary file */
125 			iflag = 1;
126 			break;
127 		case 'j':
128 			/* instead of total minutes, give sec/call */
129 			jflag = 1;
130 			break;
131 		case 'k':
132 			/* sort by CPU-time average memory usage */
133 			kflag = 1;
134 			sa_cmp = cmp_avgcpumem;
135 			break;
136 		case 'K':
137 			/* print and sort by CPU-storage integral */
138 			sa_cmp = cmp_cpumem;
139 			Kflag = 1;
140 			break;
141 		case 'l':
142 			/* separate system and user time */
143 			lflag = 1;
144 			break;
145 		case 'm':
146 			/* print procs and time per-user */
147 			mflag = 1;
148 			break;
149 		case 'n':
150 			/* sort by number of calls */
151 			sa_cmp = cmp_calls;
152 			break;
153 		case 'q':
154 			/* quiet; error messages only */
155 			qflag = 1;
156 			break;
157 		case 'r':
158 			/* reverse order of sort */
159 			rflag = 1;
160 			break;
161 		case 's':
162 			/* merge accounting file into summaries */
163 			sflag = 1;
164 			break;
165 		case 't':
166 			/* report ratio of user and system times */
167 			tflag = 1;
168 			break;
169 		case 'u':
170 			/* first, print uid and command name */
171 			uflag = 1;
172 			break;
173 		case 'v':
174 			/* cull junk */
175 			vflag = 1;
176 			cutoff = atoi(optarg);
177 			break;
178 		case '?':
179 		default:
180 			usage();
181 			/*NOTREACHED*/
182 		}
183 
184 	argc -= optind;
185 	argv += optind;
186 
187 	/* various argument checking */
188 	if (fflag && !vflag)
189 		errx(1, "only one of -f requires -v");
190 	if (fflag && aflag)
191 		errx(1, "only one of -a and -v may be specified");
192 	/* XXX need more argument checking */
193 
194 	if (!uflag) {
195 		/* initialize tables */
196 		if ((sflag || (!mflag && !qflag)) && pacct_init() != 0)
197 			errx(1, "process accounting initialization failed");
198 		if ((sflag || (mflag && !qflag)) && usracct_init() != 0)
199 			errx(1, "user accounting initialization failed");
200 	}
201 
202 	if (argc == 0) {
203 		argc = dfltargc;
204 		argv = __UNCONST(dfltargv);
205 	}
206 
207 	/* for each file specified */
208 	for (; argc > 0; argc--, argv++) {
209 		int	fd;
210 
211 		/*
212 		 * load the accounting data from the file.
213 		 * if it fails, go on to the next file.
214 		 */
215 		fd = acct_load(argv[0], sflag);
216 		if (fd < 0)
217 			continue;
218 
219 		if (!uflag && sflag) {
220 #ifndef DEBUG
221 			sigset_t nmask, omask;
222 			int unmask = 1;
223 
224 			/*
225 			 * block most signals so we aren't interrupted during
226 			 * the update.
227 			 */
228 			if (sigfillset(&nmask) == -1) {
229 				warn("sigfillset");
230 				unmask = 0;
231 				error = 1;
232 			}
233 			if (unmask &&
234 			    (sigprocmask(SIG_BLOCK, &nmask, &omask) == -1)) {
235 				warn("couldn't set signal mask ");
236 				unmask = 0;
237 				error = 1;
238 			}
239 #endif /* DEBUG */
240 
241 			/*
242 			 * truncate the accounting data file ASAP, to avoid
243 			 * losing data.  don't worry about errors in updating
244 			 * the saved stats; better to underbill than overbill,
245 			 * but we want every accounting record intact.
246 			 */
247 			if (ftruncate(fd, 0) == -1) {
248 				warn("couldn't truncate %s", *argv);
249 				error = 1;
250 			}
251 
252 			/*
253 			 * update saved user and process accounting data.
254 			 * note errors for later.
255 			 */
256 			if (pacct_update() != 0 || usracct_update() != 0)
257 				error = 1;
258 
259 #ifndef DEBUG
260 			/*
261 			 * restore signals
262 			 */
263 			if (unmask &&
264 			    (sigprocmask(SIG_SETMASK, &omask, NULL) == -1)) {
265 				warn("couldn't restore signal mask");
266 				error = 1;
267 			}
268 #endif /* DEBUG */
269 		}
270 
271 		/*
272 		 * close the opened accounting file
273 		 */
274 		if (close(fd) == -1) {
275 			warn("close %s", *argv);
276 			error = 1;
277 		}
278 	}
279 
280 	if (!uflag && !qflag) {
281 		/* print any results we may have obtained. */
282 		if (!mflag)
283 			pacct_print();
284 		else
285 			usracct_print();
286 	}
287 
288 	if (!uflag) {
289 		/* finally, deallocate databases */
290 		if (sflag || (!mflag && !qflag))
291 			pacct_destroy();
292 		if (sflag || (mflag && !qflag))
293 			usracct_destroy();
294 	}
295 
296 	exit(error);
297 }
298 
299 static int
300 acct_load(pn, wr)
301 	char *pn;
302 	int wr;
303 {
304 	struct acct ac;
305 	struct cmdinfo ci;
306 	size_t i;
307 	FILE *fp;
308 
309 	/*
310 	 * open the file
311 	 */
312 	fp = fopen(pn, wr ? "r+" : "r");
313 	if (fp == NULL) {
314 		warn("open %s %s", pn, wr ? "for read/write" : "read-only");
315 		return (-1);
316 	}
317 
318 	/*
319 	 * read all we can; don't stat and open because more processes
320 	 * could exit, and we'd miss them
321 	 */
322 	for (;;) {
323 		/* get one accounting entry and punt if there's an error */
324 		if (fread(&ac, sizeof(struct acct), 1, fp) != 1) {
325 			if (feof(fp))
326 				break;
327 			if (ferror(fp))
328 				warn("error reading %s", pn);
329 			else
330 				warnx("short read of accounting data in %s",
331 				    pn);
332 			break;
333 		}
334 
335 		/* decode it */
336 		ci.ci_calls = 1;
337 		for (i = 0; i < sizeof(ac.ac_comm) && ac.ac_comm[i] != '\0';
338 		    i++) {
339 			char c = ac.ac_comm[i];
340 
341 			if (!isascii(c) || iscntrl((unsigned char)c)) {
342 				ci.ci_comm[i] = '?';
343 				ci.ci_flags |= CI_UNPRINTABLE;
344 			} else
345 				ci.ci_comm[i] = c;
346 		}
347 		if (ac.ac_flag & AFORK)
348 			ci.ci_comm[i++] = '*';
349 		ci.ci_comm[i++] = '\0';
350 		ci.ci_etime = decode_comp_t(ac.ac_etime);
351 		ci.ci_utime = decode_comp_t(ac.ac_utime);
352 		ci.ci_stime = decode_comp_t(ac.ac_stime);
353 		ci.ci_uid = ac.ac_uid;
354 		ci.ci_mem = ac.ac_mem;
355 		ci.ci_io = decode_comp_t(ac.ac_io) / AHZ;
356 
357 		if (!uflag) {
358 			/* and enter it into the usracct and pacct databases */
359 			if (sflag || (!mflag && !qflag))
360 				pacct_add(&ci);
361 			if (sflag || (mflag && !qflag))
362 				usracct_add(&ci);
363 		} else if (!qflag)
364 			printf("%6u %12.2f CPU %12lluk mem %12llu io %s\n",
365 			    ci.ci_uid,
366 			    (ci.ci_utime + ci.ci_stime) / (double) AHZ,
367 			    (unsigned long long)ci.ci_mem,
368 			    (unsigned long long)ci.ci_io, ci.ci_comm);
369 	}
370 
371 	/* finally, return the file descriptor for possible truncation */
372 	return (fileno(fp));
373 }
374 
375 static u_quad_t
376 decode_comp_t(comp_t comp)
377 {
378 	u_quad_t rv;
379 
380 	/*
381 	 * for more info on the comp_t format, see:
382 	 *	/usr/src/sys/kern/kern_acct.c
383 	 *	/usr/src/sys/sys/acct.h
384 	 *	/usr/src/usr.bin/lastcomm/lastcomm.c
385 	 */
386 	rv = comp & 0x1fff;	/* 13 bit fraction */
387 	comp >>= 13;		/* 3 bit base-8 exponent */
388 	while (comp--)
389 		rv <<= 3;
390 
391 	return (rv);
392 }
393 
394 /* sort commands, doing the right thing in terms of reversals */
395 static int
396 cmp_comm(s1, s2)
397 	const char *s1, *s2;
398 {
399 	int rv;
400 
401 	rv = strcmp(s1, s2);
402 	if (rv == 0)
403 		rv = -1;
404 	return (rflag ? rv : -rv);
405 }
406 
407 /* sort by total user and system time */
408 static int
409 cmp_usrsys(d1, d2)
410 	const DBT *d1, *d2;
411 {
412 	struct cmdinfo c1, c2;
413 	u_quad_t t1, t2;
414 
415 	memcpy(&c1, d1->data, sizeof(c1));
416 	memcpy(&c2, d2->data, sizeof(c2));
417 
418 	t1 = c1.ci_utime + c1.ci_stime;
419 	t2 = c2.ci_utime + c2.ci_stime;
420 
421 	if (t1 < t2)
422 		return -1;
423 	else if (t1 == t2)
424 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
425 	else
426 		return 1;
427 }
428 
429 /* sort by average user and system time */
430 static int
431 cmp_avgusrsys(d1, d2)
432 	const DBT *d1, *d2;
433 {
434 	struct cmdinfo c1, c2;
435 	double t1, t2;
436 
437 	memcpy(&c1, d1->data, sizeof(c1));
438 	memcpy(&c2, d2->data, sizeof(c2));
439 
440 	t1 = c1.ci_utime + c1.ci_stime;
441 	t1 /= (double) (c1.ci_calls ? c1.ci_calls : 1);
442 
443 	t2 = c2.ci_utime + c2.ci_stime;
444 	t2 /= (double) (c2.ci_calls ? c2.ci_calls : 1);
445 
446 	if (t1 < t2)
447 		return -1;
448 	else if (t1 == t2)
449 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
450 	else
451 		return 1;
452 }
453 
454 /* sort by total number of disk I/O operations */
455 static int
456 cmp_dkio(d1, d2)
457 	const DBT *d1, *d2;
458 {
459 	struct cmdinfo c1, c2;
460 
461 	memcpy(&c1, d1->data, sizeof(c1));
462 	memcpy(&c2, d2->data, sizeof(c2));
463 
464 	if (c1.ci_io < c2.ci_io)
465 		return -1;
466 	else if (c1.ci_io == c2.ci_io)
467 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
468 	else
469 		return 1;
470 }
471 
472 /* sort by average number of disk I/O operations */
473 static int
474 cmp_avgdkio(d1, d2)
475 	const DBT *d1, *d2;
476 {
477 	struct cmdinfo c1, c2;
478 	double n1, n2;
479 
480 	memcpy(&c1, d1->data, sizeof(c1));
481 	memcpy(&c2, d2->data, sizeof(c2));
482 
483 	n1 = (double) c1.ci_io / (double) (c1.ci_calls ? c1.ci_calls : 1);
484 	n2 = (double) c2.ci_io / (double) (c2.ci_calls ? c2.ci_calls : 1);
485 
486 	if (n1 < n2)
487 		return -1;
488 	else if (n1 == n2)
489 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
490 	else
491 		return 1;
492 }
493 
494 /* sort by the CPU-storage integral */
495 static int
496 cmp_cpumem(d1, d2)
497 	const DBT *d1, *d2;
498 {
499 	struct cmdinfo c1, c2;
500 
501 	memcpy(&c1, d1->data, sizeof(c1));
502 	memcpy(&c2, d2->data, sizeof(c2));
503 
504 	if (c1.ci_mem < c2.ci_mem)
505 		return -1;
506 	else if (c1.ci_mem == c2.ci_mem)
507 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
508 	else
509 		return 1;
510 }
511 
512 /* sort by the CPU-time average memory usage */
513 static int
514 cmp_avgcpumem(d1, d2)
515 	const DBT *d1, *d2;
516 {
517 	struct cmdinfo c1, c2;
518 	u_quad_t t1, t2;
519 	double n1, n2;
520 
521 	memcpy(&c1, d1->data, sizeof(c1));
522 	memcpy(&c2, d2->data, sizeof(c2));
523 
524 	t1 = c1.ci_utime + c1.ci_stime;
525 	t2 = c2.ci_utime + c2.ci_stime;
526 
527 	n1 = (double) c1.ci_mem / (double) (t1 ? t1 : 1);
528 	n2 = (double) c2.ci_mem / (double) (t2 ? t2 : 1);
529 
530 	if (n1 < n2)
531 		return -1;
532 	else if (n1 == n2)
533 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
534 	else
535 		return 1;
536 }
537 
538 /* sort by the number of invocations */
539 static int
540 cmp_calls(d1, d2)
541 	const DBT *d1, *d2;
542 {
543 	struct cmdinfo c1, c2;
544 
545 	memcpy(&c1, d1->data, sizeof(c1));
546 	memcpy(&c2, d2->data, sizeof(c2));
547 
548 	if (c1.ci_calls < c2.ci_calls)
549 		return -1;
550 	else if (c1.ci_calls == c2.ci_calls)
551 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
552 	else
553 		return 1;
554 }
555 
556 static void
557 usage()
558 {
559 
560 	(void)fprintf(stderr,
561 	    "usage: %s [-abcdDfijkKlmnqrstu] [-v cutoff] [file ...]\n",
562 	    getprogname());
563 	exit(0);
564 }
565 
566 const char *
567 fmt(key)
568 	const DBT *key;
569 {
570 	static char *buf = NULL;
571 	static size_t len = 0;
572 	char *nbuf;
573 
574 	if (len < key->size * 4 + 1) {
575 		nbuf = realloc(buf, key->size * 4 + 1);
576 		if (!nbuf)
577 			err(1, "realloc");
578 		buf = nbuf;
579 		len = key->size * 4 + 1;
580 	}
581 	(void)strvisx(buf, key->data, key->size, 0);
582 	return buf;
583 }
584