File: load.c

package info (click to toggle)
rtpengine 13.5.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,676 kB
  • sloc: ansic: 86,764; perl: 59,422; python: 3,193; sh: 1,030; makefile: 693; asm: 211
file content (57 lines) | stat: -rw-r--r-- 1,397 bytes parent folder | download | duplicates (2)
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
#include "load.h"

#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#include "helpers.h"
#include "log.h"
#include "main.h"

int load_average; // times 100
int cpu_usage; // percent times 100 (0 - 9999)

static long used_last, idle_last;

enum thread_looper_action load_thread(void) {
	// anything to do?
	if (!rtpe_config.load_limit && !rtpe_config.cpu_limit)
		return TLA_BREAK;

	if (rtpe_config.load_limit) {
		double loadavg;
		if (getloadavg(&loadavg, 1) >= 1)
			g_atomic_int_set(&load_average, (int) (loadavg * 100.0));
		else
			ilog(LOG_WARN, "Failed to obtain load average: %s", strerror(errno));
	}

	if (rtpe_config.cpu_limit) {
		FILE *f;
		f = fopen("/proc/stat", "r");
		if (f) {
			long user_now, nice_now, system_now, idle_now;
			if (fscanf(f, "cpu  %li %li %li %li",
						&user_now, &nice_now, &system_now, &idle_now) == 4)
			{
				long used_now = user_now + nice_now + system_now;
				long used_secs = used_now - used_last;
				long idle_secs = idle_now - idle_last;
				long total_secs = used_secs + idle_secs;
				if (total_secs > 0 && used_last && idle_last)
					g_atomic_int_set(&cpu_usage, (int) (used_secs
								* 10000 / total_secs));
				used_last = used_now;
				idle_last = idle_now;
			}
			else
				ilog(LOG_WARN, "Failed to obtain CPU usage");
			fclose(f);
		}
	}

	return TLA_CONTINUE;
}