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