summaryrefslogtreecommitdiff
path: root/lavg/lavg.c
blob: ee5b1a2a7e363105b47fa832a3c239564f00d009 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* $Id$ */
/*
 * Copyright (c) 2005 Dimitri Sokolyuk <demon@dim13.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifndef lint
static const char rcsid[] = "$Id$";
#endif /* not lint */

#include <sys/param.h>
#include <sys/sysctl.h>
#include <err.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

static const struct {
	char *name;
	char *color;
} status[] = {
	{"low",      "#00A650"},
	{"guarded",  "#1B62B7"},
	{"elevated", "#FEDD03"},
	{"high",     "#F57215"},
	{"severe",   "#ED192D"}
};

int	factor[3] = { 2, 1, 1 };

int
ncpu(void)
{
	int mib[2], n;
	size_t len;

	mib[0] = CTL_HW;
	mib[1] = HW_NCPU;
	len = sizeof(n);

	if (sysctl(mib, 2, &n, &len, NULL, 0) == -1)
		err(1, "sysctl");

	return n;
}

int
main(void)
{
	double avg[3], threshold;
	int i, n, cpu;

	cpu = ncpu();
	threshold = log(cpu) + 1;
	
	printf("Content-Type: text/html\n\n<html>\n");

	if (getloadavg(avg, 3) == -1)
		printf("no load average information available\n");
	else {
		for (n = 0, i = 0; i < 3; i++) {
			if (avg[i] > threshold)
				n += factor[i];
		}

		printf("<head>\n");
		printf("<title>load %.2f %s</title>\n",
		    avg[0], status[n].name);
		printf("<meta http-equiv=\"refresh\" content=\"5\">\n");
		printf("</head>\n");

		printf("<body>\n<table>\n");
		printf("<tr><td>cpu</td><td>%d</td></tr>\n", cpu);
		printf("<tr><td>threshold</td><td>%.2f</td></tr>\n", threshold);

		printf("<tr><td>averages</td><td>");
		for (i = 0; i < 3; i++) {
			printf("%.2f", avg[i]);
			if (i < 2)
				printf(", ");
		}
		printf("</td></tr>\n");

		printf("<tr><td>status</td><td><font color=\"%s\">%s</font></td></tr>\n",
		    status[n].color, status[n].name);
		printf("</table>\n</body>\n");
	}
	printf("</html>\n");

	exit(0);
}