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