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