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