xref: /freebsd/usr.sbin/sa/main.c (revision d056fa046c6a91b90cd98165face0e42a33a5173)
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 #if 0
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1994 Christopher G. Demetriou\n\
35  All rights reserved.\n";
36 #endif
37 #endif
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 /*
42  * sa:	system accounting
43  */
44 
45 #include <sys/types.h>
46 #include <sys/acct.h>
47 #include <ctype.h>
48 #include <err.h>
49 #include <fcntl.h>
50 #include <signal.h>
51 #include <stdint.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(const char *, int);
60 static u_quad_t	decode_comp_t(comp_t);
61 static int	cmp_comm(const char *, const char *);
62 static int	cmp_usrsys(const DBT *, const DBT *);
63 static int	cmp_avgusrsys(const DBT *, const DBT *);
64 static int	cmp_dkio(const DBT *, const DBT *);
65 static int	cmp_avgdkio(const DBT *, const DBT *);
66 static int	cmp_cpumem(const DBT *, const DBT *);
67 static int	cmp_avgcpumem(const DBT *, const DBT *);
68 static int	cmp_calls(const DBT *, const DBT *);
69 static void	usage(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 u_quad_t cutoff = 1;
74 
75 static char	*dfltargv[] = { NULL };
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(int argc, char **argv)
83 {
84 	char pathacct[] = _PATH_ACCT;
85 	int ch, error = 0;
86 
87 	dfltargv[0] = pathacct;
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 				/* separate 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(const char *pn, int wr)
303 {
304 	struct acct ac;
305 	struct cmdinfo ci;
306 	ssize_t rv;
307 	int fd, i;
308 
309 	/*
310 	 * open the file
311 	 */
312 	fd = open(pn, wr ? O_RDWR : O_RDONLY, 0);
313 	if (fd == -1) {
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 	while (1) {
323 		/* get one accounting entry and punt if there's an error */
324 		rv = read(fd, &ac, sizeof(struct acct));
325 		if (rv == -1)
326 			warn("error reading %s", pn);
327 		else if (rv > 0 && rv < (int)sizeof(struct acct))
328 			warnx("short read of accounting data in %s", pn);
329 		if (rv != sizeof(struct acct))
330 			break;
331 
332 		/* decode it */
333 		ci.ci_calls = 1;
334 		for (i = 0; i < (int)sizeof ac.ac_comm && ac.ac_comm[i] != '\0';
335 		    i++) {
336 			char c = ac.ac_comm[i];
337 
338 			if (!isascii(c) || iscntrl(c)) {
339 				ci.ci_comm[i] = '?';
340 				ci.ci_flags |= CI_UNPRINTABLE;
341 			} else
342 				ci.ci_comm[i] = c;
343 		}
344 		if (ac.ac_flag & AFORK)
345 			ci.ci_comm[i++] = '*';
346 		ci.ci_comm[i++] = '\0';
347 		ci.ci_etime = decode_comp_t(ac.ac_etime);
348 		ci.ci_utime = decode_comp_t(ac.ac_utime);
349 		ci.ci_stime = decode_comp_t(ac.ac_stime);
350 		ci.ci_uid = ac.ac_uid;
351 		ci.ci_mem = ac.ac_mem;
352 		ci.ci_io = decode_comp_t(ac.ac_io) / AHZ;
353 
354 		if (!uflag) {
355 			/* and enter it into the usracct and pacct databases */
356 			if (sflag || (!mflag && !qflag))
357 				pacct_add(&ci);
358 			if (sflag || (mflag && !qflag))
359 				usracct_add(&ci);
360 		} else if (!qflag)
361 			printf("%6lu %12.2f cpu %12juk mem %12ju io %s\n",
362 			    ci.ci_uid,
363 			    (ci.ci_utime + ci.ci_stime) / (double) AHZ,
364 			    (uintmax_t)ci.ci_mem, (uintmax_t)ci.ci_io,
365 			    ci.ci_comm);
366 	}
367 
368 	/* finally, return the file descriptor for possible truncation */
369 	return (fd);
370 }
371 
372 static u_quad_t
373 decode_comp_t(comp_t comp)
374 {
375 	u_quad_t rv;
376 
377 	/*
378 	 * for more info on the comp_t format, see:
379 	 *	/usr/src/sys/kern/kern_acct.c
380 	 *	/usr/src/sys/sys/acct.h
381 	 *	/usr/src/usr.bin/lastcomm/lastcomm.c
382 	 */
383 	rv = comp & 0x1fff;	/* 13 bit fraction */
384 	comp >>= 13;		/* 3 bit base-8 exponent */
385 	while (comp--)
386 		rv <<= 3;
387 
388 	return (rv);
389 }
390 
391 /* sort commands, doing the right thing in terms of reversals */
392 static int
393 cmp_comm(const char *s1, const char *s2)
394 {
395 	int rv;
396 
397 	rv = strcmp(s1, s2);
398 	if (rv == 0)
399 		rv = -1;
400 	return (rflag ? rv : -rv);
401 }
402 
403 /* sort by total user and system time */
404 static int
405 cmp_usrsys(const DBT *d1, const DBT *d2)
406 {
407 	struct cmdinfo c1, c2;
408 	u_quad_t t1, t2;
409 
410 	memcpy(&c1, d1->data, sizeof(c1));
411 	memcpy(&c2, d2->data, sizeof(c2));
412 
413 	t1 = c1.ci_utime + c1.ci_stime;
414 	t2 = c2.ci_utime + c2.ci_stime;
415 
416 	if (t1 < t2)
417 		return -1;
418 	else if (t1 == t2)
419 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
420 	else
421 		return 1;
422 }
423 
424 /* sort by average user and system time */
425 static int
426 cmp_avgusrsys(const DBT *d1, const DBT *d2)
427 {
428 	struct cmdinfo c1, c2;
429 	double t1, t2;
430 
431 	memcpy(&c1, d1->data, sizeof(c1));
432 	memcpy(&c2, d2->data, sizeof(c2));
433 
434 	t1 = c1.ci_utime + c1.ci_stime;
435 	t1 /= (double) (c1.ci_calls ? c1.ci_calls : 1);
436 
437 	t2 = c2.ci_utime + c2.ci_stime;
438 	t2 /= (double) (c2.ci_calls ? c2.ci_calls : 1);
439 
440 	if (t1 < t2)
441 		return -1;
442 	else if (t1 == t2)
443 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
444 	else
445 		return 1;
446 }
447 
448 /* sort by total number of disk I/O operations */
449 static int
450 cmp_dkio(const DBT *d1, const DBT *d2)
451 {
452 	struct cmdinfo c1, c2;
453 
454 	memcpy(&c1, d1->data, sizeof(c1));
455 	memcpy(&c2, d2->data, sizeof(c2));
456 
457 	if (c1.ci_io < c2.ci_io)
458 		return -1;
459 	else if (c1.ci_io == c2.ci_io)
460 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
461 	else
462 		return 1;
463 }
464 
465 /* sort by average number of disk I/O operations */
466 static int
467 cmp_avgdkio(const DBT *d1, const DBT *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(const DBT *d1, const DBT *d2)
489 {
490 	struct cmdinfo c1, c2;
491 
492 	memcpy(&c1, d1->data, sizeof(c1));
493 	memcpy(&c2, d2->data, sizeof(c2));
494 
495 	if (c1.ci_mem < c2.ci_mem)
496 		return -1;
497 	else if (c1.ci_mem == c2.ci_mem)
498 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
499 	else
500 		return 1;
501 }
502 
503 /* sort by the cpu-time average memory usage */
504 static int
505 cmp_avgcpumem(const DBT *d1, const DBT *d2)
506 {
507 	struct cmdinfo c1, c2;
508 	u_quad_t t1, t2;
509 	double n1, n2;
510 
511 	memcpy(&c1, d1->data, sizeof(c1));
512 	memcpy(&c2, d2->data, sizeof(c2));
513 
514 	t1 = c1.ci_utime + c1.ci_stime;
515 	t2 = c2.ci_utime + c2.ci_stime;
516 
517 	n1 = (double) c1.ci_mem / (double) (t1 ? t1 : 1);
518 	n2 = (double) c2.ci_mem / (double) (t2 ? t2 : 1);
519 
520 	if (n1 < n2)
521 		return -1;
522 	else if (n1 == n2)
523 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
524 	else
525 		return 1;
526 }
527 
528 /* sort by the number of invocations */
529 static int
530 cmp_calls(const DBT *d1, const DBT *d2)
531 {
532 	struct cmdinfo c1, c2;
533 
534 	memcpy(&c1, d1->data, sizeof(c1));
535 	memcpy(&c2, d2->data, sizeof(c2));
536 
537 	if (c1.ci_calls < c2.ci_calls)
538 		return -1;
539 	else if (c1.ci_calls == c2.ci_calls)
540 		return (cmp_comm(c1.ci_comm, c2.ci_comm));
541 	else
542 		return 1;
543 }
544