aboutsummaryrefslogtreecommitdiffstats
path: root/coreupdown.c
blob: ab3d4e971c956fe76297116e8176e18354796ff6 (plain) (blame)
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/* See LICENSE file for copyright and license details. */
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

static const char *argv0;
static volatile sig_atomic_t caught_sighup = 0;

#define coreup() coreupdown(ULONG_MAX)
#define coredown() coreupdown(1)

static int
coreupdown(unsigned long int count)
{
	char path[sizeof("/sys/devices/system/cpu/cpu/online") + 3 * sizeof(count)];
	unsigned long int i;
	int fd, ret = 0;

	for (i = 1; i; i++) {
		sprintf(path, "/sys/devices/system/cpu/cpu%zu/online", i);
		fd = open(path, O_WRONLY);
		if (fd < 0) {
			if (errno == ENOENT)
				break;
			fprintf(stderr, "%s: open %s O_WRONLY\n", argv0, path);
			return -1;
		}
		if (write(fd, i < count ? "1\n" : "0\n", 2) < 0) {
			fprintf(stderr, "%s: write %s\n", argv0, path);
			ret = -1;
		}
		close(fd);
	}
	return ret;
}

static int
oneshot_main(int argc, char **argv, unsigned long int count)
{
	if (argc && !strcmp(argv[0], "--")) {
		argv++;
		argc--;
	}

	if (argc > 1) {
	usage:
		fprintf(stderr, "usage: %s [count]\n", argv0);
		return 1;
	}

	if (argc) {
		char *end;
		errno = 0;
		if (!isdigit(**argv))
			goto usage;
		count = strtoul(*argv, &end, 10);
		if (!count || errno || *end)
			goto usage;
		argv++;
		argc--;
	}

	return -coreupdown(count);
}

static int
getusage(uintmax_t *total_out, uintmax_t *idle_out, size_t *cpus_out)
{
#define IDLE_FIELD 3

	static uintmax_t last_total = 0, last_idle = 0;
	uintmax_t cur_total, cur_idle;
	char buf[512];
	int fd;
	size_t off, len, field;
	ssize_t r;
	int line_incomplete = 0, beginning_of_line = 1;
	uintmax_t amount[] = {0, 0}, value;

	*cpus_out = 0;

	fd = open("/proc/stat", O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "%s: open /proc/stat O_RDONLY\n", argv0);
		return -1;
	}

	len = 0;
	for (;;) {
		r = read(fd, &buf[len], sizeof(buf) - len);
		if (!r) {
			fprintf(stderr, "%s: /proc/stat did not contain \"cpu\" line\n", argv0);
			close(fd);
			return -1;
		} else if (r < 0) {
			if (errno == EINTR)
				continue;
			fprintf(stderr, "%s: read /proc/stat: %s\n", argv0, strerror(errno));
			close(fd);
			return -1;
		}
		len += (size_t)r;

		if (line_incomplete)
			goto skip_line;

		for (off = 0; off < len;) {
			if (len - off < 4) {
				memmove(&buf[0], &buf[off], len -= off);
				break;
			} else if (!strncmp(&buf[off], "cpu", 3)) {
				if (isspace(buf[off + 3]))
					goto cpu_line_found;
				else if (isdigit(buf[off + 3]))
					*cpus_out += 1;
			}

		skip_line:
			while (off < len && buf[off] != '\n')
				off++;
			if (off == len) {
				line_incomplete = 0;
				break;
			} else {
				off++;
				line_incomplete = 1;
			}
		}
	}
cpu_line_found:

	off += 4;
	field = 0;
	value = 0;
	for (;;) {
		if (off == len) {
			off = len = 0;
			r = read(fd, buf, sizeof(buf));
			if (!r) {
				goto line_done;
			} else if (r < 0) {
				if (errno == EINTR)
					continue;
				fprintf(stderr, "%s: read /proc/stat: %s\n", argv0, strerror(errno));
				close(fd);
				return -1;
			}
			len = (size_t)r;
		}
		while (off < len && isspace(buf[off]))
			off++;
		if (off == len)
			continue;
		while (off < len) {
			if (buf[off] == '\n') {
				amount[field++ == IDLE_FIELD] += value;
				off++;
				goto line_done;
			} else if (isspace(buf[off])) {
				amount[field++ == IDLE_FIELD] += value;
				value = 0;
				off++;
				break;
			} else {
				value *= 10;
				value += buf[off] & 15;
				off++;
			}
		}
	}
line_done:

	for (;;) {
		if (off == len) {
			off = len = 0;
		read_more:
			r = read(fd, &buf[len], sizeof(buf) - len);
			if (!r) {
				break;
			} else if (r < 0) {
				if (errno == EINTR)
					continue;
				fprintf(stderr, "%s: read /proc/stat: %s\n", argv0, strerror(errno));
				close(fd);
				return -1;
			}
			len = (size_t)r;
		}
		for (; off < len; off++) {
			if (beginning_of_line) {
				if (len - off < 5) {
					memmove(&buf[0], &buf[off], len -= off);
					goto read_more;
				}
				if (!strncmp(&buf[off], "cpu", 3) && isdigit(buf[off + 3]))
					*cpus_out += 1;
				beginning_of_line = 0;
			}
			if (buf[off] == '\n')
				beginning_of_line = 1;
		}
	}

	close(fd);

	if (field < IDLE_FIELD) {
		fprintf(stderr, "%s: /proc/stat did not contain CPU idle time\n", argv0);
		close(fd);
		return -1;
	}

	cur_total = amount[0] + amount[1];
	cur_idle = amount[1];
	*total_out = cur_total - last_total;
	*idle_out = cur_idle - last_idle;
	last_total = cur_total;
	last_idle = cur_idle;
	return 0;

#undef IDLE_FIELD
}

static void
sighup_handler(int signo)
{
	(void) signo;
	caught_sighup = 1;
}

static int
daemon_main(int argc, char **argv, int orig_argc, char **orig_argv, int reexeced)
{
	uintmax_t total, idle;
	size_t cpus;
	int up_time = 0, down_time = 0, cooldown = 0, err;
	struct timespec interval, rem;
	uintmax_t coreup_threshold_cpu, coredown_threshold_cpu;
	int coreup_threshold_time, coredown_threshold_time;
	int coreup_cooldown, coredown_cooldown;
	time_t daemon_interval_sec;
	long int daemon_interval_nsec;

restart:
	coreup_threshold_cpu = COREUP_THRESHOLD_CPU;
	coreup_threshold_time = COREUP_THRESHOLD_TIME;
	coreup_cooldown = COREUP_COOLDOWN;
	coredown_threshold_cpu = COREDOWN_THRESHOLD_CPU;
	coredown_threshold_time = COREDOWN_THRESHOLD_TIME;
	coredown_cooldown = COREDOWN_COOLDOWN;
	daemon_interval_sec = DAEMON_INTERVAL_SEC;
	daemon_interval_nsec = DAEMON_INTERVAL_NSEC;

	if (reexeced)
		argv[0] = "coreupdownd";

	if (argc && !strcmp(argv[0], "--")) {
		argv++;
		argc--;
	}

	if (argc > 0) {
		fprintf(stderr, "usage: %s\n", argv0);
		return 1;
	}

	if (!reexeced) {
		/* TODO add proper daemonisation */
	}

	/* TODO configurations should be configurable */

	if (signal(SIGHUP, sighup_handler) == SIG_ERR)
		fprintf(stderr, "%s: signal SIGHUP <function>: %s\n", argv0, strerror(errno));

	interval.tv_sec = daemon_interval_sec;
	interval.tv_nsec = daemon_interval_nsec;

	if (getusage(&total, &idle, &cpus))
		return 1;

	close(STDIN_FILENO);
	close(STDOUT_FILENO);

	for (;;) {
		if (caught_sighup) {
			caught_sighup = 0;
			orig_argv[0] = "coreupdownd ";
			execv(DAEMON_PATH, orig_argv);
			fprintf(stderr, "%s: execv %s: %s\n", argv0, DAEMON_PATH, strerror(errno));
			reexeced = 1;
			argv = &orig_argv[1];
			argc = orig_argc - 1;
			goto restart;
		}

		if ((err = clock_nanosleep(CLOCK_REALTIME /* = monotonic */, 0, &interval, &rem))) {
			do {
				if (err != EINTR) {
					fprintf(stderr, "%s: clock_nanosleep CLOCK_REALTIME: %s\n",
					        argv0, strerror(errno));
					return 1;
				}
			} while ((err = clock_nanosleep(CLOCK_REALTIME, 0, &rem, &rem)));
		}
		if (getusage(&total, &idle, &cpus))
			return 1;
		if (cooldown) {
			cooldown--;
			continue;
		}

		if (cpus == 1 && 100 * (total - idle) > coreup_threshold_cpu * total) {
			down_time = 0;
			if (up_time++ >= coreup_threshold_time) {
				cooldown = coreup_cooldown;
				coreup();
				up_time = 0;
			}
		} else if (cpus > 1 && 100 * (total - idle) < coredown_threshold_cpu * total * cpus) {
			up_time = 0;
			if (down_time++ >= coredown_threshold_time) {
				cooldown = coredown_cooldown;
				coredown();
				down_time = 0;
			}
		} else {
			up_time = 0;
			down_time = 0;
		}
	}

	return 0;
}

int
main(int argc, char **argv)
{
	const char *command;

	if (argc--) {
		command = strrchr(argv0 = *argv++, '/');
		command = command ? &command[1] : argv0;
		if (!strcmp(command, "coreup"))
			return oneshot_main(argc, argv, ULONG_MAX);
		if (!strcmp(command, "coredown"))
			return oneshot_main(argc, argv, 1);
		if (!strcmp(command, "coreupdownd"))
			return daemon_main(argc, argv, argc + 1, &argv[-1], 0);
		if (!strcmp(command, "coreupdownd "))
			return daemon_main(argc, argv, argc + 1, &argv[-1], 1);
	}

	fprintf(stderr, "usage: coreup [count]\n"
	                "usage: coredown [count]\n"
	                "usage: coreupdownd\n");

	return 1;
}