xref: /openbsd-src/usr.sbin/sa/main.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: main.c,v 1.10 2005/05/04 09:02:54 jmc Exp $	*/
2 /*
3  * Copyright (c) 1994 Christopher G. Demetriou
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *      This product includes software developed by Christopher G. Demetriou.
17  * 4. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #ifndef LINT
33 static char copright[] =
34 "@(#) Copyright (c) 1994 Christopher G. Demetriou\n\
35  All rights reserved.\n";
36 
37 static char rcsid[] = "$Id: main.c,v 1.10 2005/05/04 09:02:54 jmc Exp $";
38 #endif
39 
40 /*
41  * sa:	system accounting
42  */
43 
44 #include <sys/types.h>
45 #include <sys/acct.h>
46 #include <ctype.h>
47 #include <err.h>
48 #include <fcntl.h>
49 #include <signal.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include "extern.h"
55 #include "pathnames.h"
56 
57 static int	acct_load(char *, int);
58 static u_quad_t	decode_comp_t(comp_t);
59 static int	cmp_comm(const char *, const char *);
60 static int	cmp_usrsys(const DBT *, const DBT *);
61 static int	cmp_avgusrsys(const DBT *, const DBT *);
62 static int	cmp_dkio(const DBT *, const DBT *);
63 static int	cmp_avgdkio(const DBT *, const DBT *);
64 static int	cmp_cpumem(const DBT *, const DBT *);
65 static int	cmp_avgcpumem(const DBT *, const DBT *);
66 static int	cmp_calls(const DBT *, const DBT *);
67 
68 int aflag, bflag, cflag, dflag, Dflag, fflag, iflag, jflag, kflag;
69 int Kflag, lflag, mflag, qflag, rflag, sflag, tflag, uflag, vflag;
70 int cutoff = 1;
71 
72 static char	*dfltargv[] = { _PATH_ACCT };
73 static int	dfltargc = (sizeof(dfltargv)/sizeof(char *));
74 
75 /* default to comparing by sum of user + system time */
76 cmpf_t   sa_cmp = cmp_usrsys;
77 
78 int
79 main(int argc, char **argv)
80 {
81 	int ch;
82 	int error = 0;
83 	extern char *__progname;
84 
85 	while ((ch = getopt(argc, argv, "abcdDfijkKlmnqrstuv:")) != -1)
86 		switch (ch) {
87 		case 'a':
88 			/* print all commands */
89 			aflag = 1;
90 			break;
91 		case 'b':
92 			/* sort by per-call user/system time average */
93 			bflag = 1;
94 			sa_cmp = cmp_avgusrsys;
95 			break;
96 		case 'c':
97 			/* print percentage total time */
98 			cflag = 1;
99 			break;
100 		case 'd':
101 			/* sort by averge number of disk I/O ops */
102 			dflag = 1;
103 			sa_cmp = cmp_avgdkio;
104 			break;
105 		case 'D':
106 			/* print and sort by total disk I/O ops */
107 			Dflag = 1;
108 			sa_cmp = cmp_dkio;
109 			break;
110 		case 'f':
111 			/* force no interactive threshold comprison */
112 			fflag = 1;
113 			break;
114 		case 'i':
115 			/* do not read in summary file */
116 			iflag = 1;
117 			break;
118 		case 'j':
119 			/* instead of total minutes, give sec/call */
120 			jflag = 1;
121 			break;
122 		case 'k':
123 			/* sort by cpu-time average memory usage */
124 			kflag = 1;
125 			sa_cmp = cmp_avgcpumem;
126 			break;
127 		case 'K':
128 			/* print and sort by cpu-storage integral */
129 			sa_cmp = cmp_cpumem;
130 			Kflag = 1;
131 			break;
132 		case 'l':
133 			/* separate system and user time */
134 			lflag = 1;
135 			break;
136 		case 'm':
137 			/* print procs and time per-user */
138 			mflag = 1;
139 			break;
140 		case 'n':
141 			/* sort by number of calls */
142 			sa_cmp = cmp_calls;
143 			break;
144 		case 'q':
145 			/* quiet; error messages only */
146 			qflag = 1;
147 			break;
148 		case 'r':
149 			/* reverse order of sort */
150 			rflag = 1;
151 			break;
152 		case 's':
153 			/* merge accounting file into summaries */
154 			sflag = 1;
155 			break;
156 		case 't':
157 			/* report ratio of user and system times */
158 			tflag = 1;
159 			break;
160 		case 'u':
161 			/* first, print uid and command name */
162 			uflag = 1;
163 			break;
164 		case 'v':
165 			/* cull junk */
166 			vflag = 1;
167 			cutoff = atoi(optarg);
168 			break;
169 		case '?':
170 		default:
171 			(void)fprintf(stderr,
172 			    "usage: %s [-abcDdfijKklmnqrstu] [-v cutoff]"
173 			    " [file ...]\n", __progname);
174 			exit(1);
175 		}
176 
177 	argc -= optind;
178 	argv += optind;
179 
180 	/* various argument checking */
181 	if (fflag && !vflag)
182 		errx(1, "only one of -f requires -v");
183 	if (fflag && aflag)
184 		errx(1, "only one of -a and -v may be specified");
185 	/* XXX need more argument checking */
186 
187 	if (!uflag) {
188 		/* initialize tables */
189 		if ((sflag || (!mflag && !qflag)) && pacct_init() != 0)
190 			errx(1, "process accounting initialization failed");
191 		if ((sflag || (mflag && !qflag)) && usracct_init() != 0)
192 			errx(1, "user accounting initialization failed");
193 	}
194 
195 	if (argc == 0) {
196 		argc = dfltargc;
197 		argv = dfltargv;
198 	}
199 
200 	/* for each file specified */
201 	for (; argc > 0; argc--, argv++) {
202 		int	fd;
203 
204 		/*
205 		 * load the accounting data from the file.
206 		 * if it fails, go on to the next file.
207 		 */
208 		fd = acct_load(argv[0], sflag);
209 		if (fd < 0)
210 			continue;
211 
212 		if (!uflag && sflag) {
213 #ifndef DEBUG
214 			sigset_t nmask, omask;
215 			int unmask = 1;
216 
217 			/*
218 			 * block most signals so we aren't interrupted during
219 			 * the update.
220 			 */
221 			if (sigfillset(&nmask) == -1) {
222 				warn("sigfillset");
223 				unmask = 0;
224 				error = 1;
225 			}
226 			if (unmask &&
227 			    (sigprocmask(SIG_BLOCK, &nmask, &omask) == -1)) {
228 				warn("couldn't set signal mask ");
229 				unmask = 0;
230 				error = 1;
231 			}
232 #endif /* DEBUG */
233 
234 			/*
235 			 * truncate the accounting data file ASAP, to avoid
236 			 * losing data.  don't worry about errors in updating
237 			 * the saved stats; better to underbill than overbill,
238 			 * but we want every accounting record intact.
239 			 */
240 			if (ftruncate(fd, 0) == -1) {
241 				warn("couldn't truncate %s", *argv);
242 				error = 1;
243 			}
244 
245 			/*
246 			 * update saved user and process accounting data.
247 			 * note errors for later.
248 			 */
249 			if (pacct_update() != 0 || usracct_update() != 0)
250 				error = 1;
251 
252 #ifndef DEBUG
253 			/*
254 			 * restore signals
255 			 */
256 			if (unmask &&
257 			    (sigprocmask(SIG_SETMASK, &omask, NULL) == -1)) {
258 				warn("couldn't restore signal mask");
259 				error = 1;
260 			}
261 #endif /* DEBUG */
262 		}
263 
264 		/*
265 		 * close the opened accounting file
266 		 */
267 		if (close(fd) == -1) {
268 			warn("close %s", *argv);
269 			error = 1;
270 		}
271 	}
272 
273 	if (!uflag && !qflag) {
274 		/* print any results we may have obtained. */
275 		if (!mflag)
276 			pacct_print();
277 		else
278 			usracct_print();
279 	}
280 
281 	if (!uflag) {
282 		/* finally, deallocate databases */
283 		if (sflag || (!mflag && !qflag))
284 			pacct_destroy();
285 		if (sflag || (mflag && !qflag))
286 			usracct_destroy();
287 	}
288 
289 	exit(error);
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("%6u %12.2f cpu %12lluk mem %12llu 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