Collectd patch to collect cpu average on linux
06 Jan 2012
I'm using collectd to collectd data at work -> http://www.collectd.org The cpu plugin don't collectd average cpu usage, I have create a patch to work this around. Here it is diff -Nurp collectd-5.0.1/src/cpu.c collectd-5.0.1-new/src/cpu.c --- collectd-5.0.1/src/cpu.c 2011-10-14 17:49:49.000000000 -0300 +++ collectd-5.0.1-new/src/cpu.c 2012-01-03 17:48:22.000000000 -0200 @@ -252,7 +252,11 @@ static void submit (int cpu_num, const c vl.values_len = 1; sstrncpy (vl.host, hostname_g, sizeof (vl.host)); sstrncpy (vl.plugin, "cpu", sizeof (vl.plugin)); - ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance), + if (cpu_num < 0) + ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance), + "avg"); + else + ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance), "%i", cpu_num); sstrncpy (vl.type, "cpu", sizeof (vl.type)); sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); @@ -359,6 +363,7 @@ static int cpu_read (void) char *fields[9]; int numfields; + int coren = sysconf(_SC_NPROCESSORS_ONLN); /* number of cores */ if ((fh = fopen ("/proc/stat", "r")) == NULL) { @@ -372,18 +377,24 @@ static int cpu_read (void) { if (strncmp (buf, "cpu", 3)) continue; - if ((buf[3] < '0') || (buf[3] > '9')) - continue; numfields = strsplit (buf, fields, 9); if (numfields < 5) continue; - cpu = atoi (fields[0] + 3); - user = atoll (fields[1]); - nice = atoll (fields[2]); - syst = atoll (fields[3]); - idle = atoll (fields[4]); + if (!isdigit(fields[0][3])) { + cpu = -1; + user = atoll (fields[1]) / coren; + nice = atoll (fields[2]) / coren; + syst = atoll (fields[3]) / coren; + idle = atoll (fields[4]) / coren; + } else { + cpu = atoi (fields[0] + 3); + user = atoll (fields[1]); + nice = atoll (fields[2]); + syst = atoll (fields[3]); + idle = atoll (fields[4]); + } submit (cpu, "user", user); submit (cpu, "nice", nice); @@ -392,9 +403,15 @@ static int cpu_read (void) if (numfields >= 8) { - wait = atoll (fields[5]); - intr = atoll (fields[6]); - sitr = atoll (fields[7]); + if (cpu < 0) { + wait = atoll (fields[5]) / coren; + intr = atoll (fields[6]) / coren; + sitr = atoll (fields[7]) / coren; + } else { + wait = atoll (fields[5]); + intr = atoll (fields[6]); + sitr = atoll (fields[7]); + } submit (cpu, "wait", wait); submit (cpu, "interrupt", intr);