2 This file is part of GNUnet.
3 Copyright (C) 2008--2013 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file testbed/gnunet-service-testbed_cpustatus.c
23 * @brief calls to determine current CPU load
24 * @author Tzvetan Horozov
25 * @author Christian Grothoff
26 * @author Igor Wronsky
27 * @author Alex Harper (OS X portion)
28 * @author Sree Harsha Totakura
32 #include "gnunet_util_lib.h"
33 #include "gnunet-service-testbed_meminfo.h"
39 #if HAVE_SYS_SYSINFO_H
40 #include <sys/sysinfo.h>
53 #include <mach/mach.h>
55 static processor_cpu_load_info_t prev_cpu_load;
58 #define DEBUG_STATUSCALLS GNUNET_NO
61 static FILE *proc_stat;
65 * Current CPU load, as percentage of CPU cycles not idle or
68 static int currentCPULoad;
70 static double agedCPULoad = -1;
73 * Current IO load, as percentage of CPU cycles blocked on IO.
75 static int currentIOLoad;
77 static double agedIOLoad = -1;
81 * hanlde to the file to write the load statistics to
83 struct GNUNET_BIO_WriteHandle *bw;
85 struct GNUNET_SCHEDULER_Task *sample_load_task_id;
92 unsigned int cpu_count;
93 processor_cpu_load_info_t cpu_load;
94 mach_msg_type_number_t cpu_msg_count;
98 kret = host_processor_info (mach_host_self (),
99 PROCESSOR_CPU_LOAD_INFO,
101 (processor_info_array_t *) &cpu_load,
103 if (kret != KERN_SUCCESS)
105 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "host_processor_info failed.");
106 return GNUNET_SYSERR;
108 prev_cpu_load = GNUNET_malloc (cpu_count * sizeof(*prev_cpu_load));
109 for (i = 0; i < cpu_count; i++)
111 for (j = 0; j < CPU_STATE_MAX; j++)
113 prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
116 vm_deallocate (mach_task_self (),
117 (vm_address_t) cpu_load,
118 (vm_size_t) (cpu_msg_count * sizeof(*cpu_load)));
126 * Update the currentCPU and currentIO load (and on Linux, memory) values.
128 * Before its first invocation the method initStatusCalls() must be called.
129 * If there is an error the method returns -1.
137 /* under linux, first try %idle/usage using /proc/stat;
138 if that does not work, disable /proc/stat for the future
139 by closing the file and use the next-best method. */
140 if (proc_stat != NULL)
142 static unsigned long long last_cpu_results[5] = { 0, 0, 0, 0, 0 };
143 static int have_last_cpu = GNUNET_NO;
146 unsigned long long user_read, system_read, nice_read, idle_read,
148 unsigned long long user, system, nice, idle, iowait;
149 unsigned long long usage_time = 0, total_time = 1;
151 /* Get the first line with the data */
154 if (NULL == fgets (line, 256, proc_stat))
156 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
157 "fgets", "/proc/stat");
158 proc_stat = NULL; /* don't try again */
163 ret = sscanf (line, "%*s %llu %llu %llu %llu %llu",
165 &system_read, &nice_read, &idle_read, &iowait_read);
168 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
169 "fgets-sscanf", "/proc/stat");
171 proc_stat = NULL; /* don't try again */
172 have_last_cpu = GNUNET_NO;
176 /* Store the current usage */
177 user = user_read - last_cpu_results[0];
178 system = system_read - last_cpu_results[1];
179 nice = nice_read - last_cpu_results[2];
180 idle = idle_read - last_cpu_results[3];
181 iowait = iowait_read - last_cpu_results[4];
182 /* Calculate the % usage */
183 usage_time = user + system + nice;
184 total_time = usage_time + idle + iowait;
185 if ((total_time > 0) && (have_last_cpu == GNUNET_YES))
187 currentCPULoad = (int) (100L * usage_time / total_time);
189 currentIOLoad = (int) (100L * iowait / total_time);
191 currentIOLoad = -1; /* 2.4 kernel */
193 /* Store the values for the next calculation */
194 last_cpu_results[0] = user_read;
195 last_cpu_results[1] = system_read;
196 last_cpu_results[2] = nice_read;
197 last_cpu_results[3] = idle_read;
198 last_cpu_results[4] = iowait_read;
199 have_last_cpu = GNUNET_YES;
208 unsigned int cpu_count;
209 processor_cpu_load_info_t cpu_load;
210 mach_msg_type_number_t cpu_msg_count;
211 unsigned long long t_sys, t_user, t_nice, t_idle, t_total;
212 unsigned long long t_idle_all, t_total_all;
216 t_idle_all = t_total_all = 0;
217 kret = host_processor_info (mach_host_self (), PROCESSOR_CPU_LOAD_INFO,
219 (processor_info_array_t *) &cpu_load,
221 if (kret == KERN_SUCCESS)
223 for (i = 0; i < cpu_count; i++)
225 if (cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] >=
226 prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM])
228 t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM]
229 - prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM];
233 t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM]
234 + (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM]
238 if (cpu_load[i].cpu_ticks[CPU_STATE_USER] >=
239 prev_cpu_load[i].cpu_ticks[CPU_STATE_USER])
241 t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER]
242 - prev_cpu_load[i].cpu_ticks[CPU_STATE_USER];
246 t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER]
247 + (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_USER]
251 if (cpu_load[i].cpu_ticks[CPU_STATE_NICE] >=
252 prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE])
254 t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE]
255 - prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE];
259 t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE]
260 + (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE]
264 if (cpu_load[i].cpu_ticks[CPU_STATE_IDLE] >=
265 prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE])
267 t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE]
268 - prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE];
272 t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE]
273 + (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE]
276 t_total = t_sys + t_user + t_nice + t_idle;
277 t_idle_all += t_idle;
278 t_total_all += t_total;
280 for (i = 0; i < cpu_count; i++)
282 for (j = 0; j < CPU_STATE_MAX; j++)
284 prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
288 currentCPULoad = 100 - (100 * t_idle_all) / t_total_all;
291 vm_deallocate (mach_task_self (),
292 (vm_address_t) cpu_load,
293 (vm_size_t) (cpu_msg_count * sizeof(*cpu_load)));
294 currentIOLoad = -1; /* FIXME-OSX! */
299 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "host_processor_info failed.");
300 return GNUNET_SYSERR;
304 /* try kstat (Solaris only) */
305 #if SOLARIS && HAVE_KSTAT_H && HAVE_SYS_SYSINFO_H
307 static long long last_idlecount;
308 static long long last_totalcount;
309 static int kstat_once; /* if open fails, don't keep
314 long long totalcount;
316 long long deltatotal;
323 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kstat_close");
329 for (khelper = kc->kc_chain; khelper != NULL; khelper = khelper->ks_next)
333 if (0 != strncmp (khelper->ks_name, "cpu_stat", strlen ("cpu_stat")))
335 if (khelper->ks_data_size > sizeof(cpu_stat_t))
336 continue; /* better save then sorry! */
337 if (-1 != kstat_read (kc, khelper, &stats))
339 idlecount += stats.cpu_sysinfo.cpu[CPU_IDLE];
341 += stats.cpu_sysinfo.cpu[CPU_IDLE]
342 + stats.cpu_sysinfo.cpu[CPU_USER]
343 + stats.cpu_sysinfo.cpu[CPU_KERNEL]
344 + stats.cpu_sysinfo.cpu[CPU_WAIT];
347 if (0 != kstat_close (kc))
348 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kstat_close");
349 if ((idlecount == 0) && (totalcount == 0))
350 goto ABORT_KSTAT; /* no stats found => abort */
351 deltaidle = idlecount - last_idlecount;
352 deltatotal = totalcount - last_totalcount;
353 if ((deltatotal > 0) && (last_totalcount > 0))
355 currentCPULoad = (unsigned int) (100.0 * deltaidle / deltatotal);
356 if (currentCPULoad > 100)
357 currentCPULoad = 100; /* odd */
358 if (currentCPULoad < 0)
359 currentCPULoad = 0; /* odd */
360 currentCPULoad = 100 - currentCPULoad; /* computed idle-load before! */
364 currentIOLoad = -1; /* FIXME-SOLARIS! */
365 last_idlecount = idlecount;
366 last_totalcount = totalcount;
369 kstat_once = 1; /* failed, don't try again */
370 return GNUNET_SYSERR;
374 /* insert methods better than getloadavg for
375 other platforms HERE! */
377 /* ok, maybe we have getloadavg on this platform */
380 static int warnOnce = 0;
382 if (1 != getloadavg (&loadavg, 1))
384 /* only warn once, if there is a problem with
385 getloadavg, we're going to hit it frequently... */
389 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "getloadavg");
391 return GNUNET_SYSERR;
395 /* success with getloadavg */
396 currentCPULoad = (int) (100 * loadavg);
397 currentIOLoad = -1; /* FIXME */
403 /* loadaverage not defined and no platform
404 specific alternative defined
407 return GNUNET_SYSERR;
412 * Update load values (if enough time has expired),
413 * including computation of averages. Code assumes
414 * that lock has already been obtained.
419 static struct GNUNET_TIME_Absolute lastCall;
420 struct GNUNET_TIME_Relative age;
422 age = GNUNET_TIME_absolute_get_duration (lastCall);
423 if ((agedCPULoad == -1)
424 || (age.rel_value_us > 500000))
426 /* use smoothing, but do NOT update lastRet at frequencies higher
427 than 500ms; this makes the smoothing (mostly) independent from
428 the frequency at which getCPULoad is called (and we don't spend
429 more time measuring CPU than actually computing something). */
430 lastCall = GNUNET_TIME_absolute_get ();
432 if (currentCPULoad == -1)
438 if (agedCPULoad == -1)
440 agedCPULoad = currentCPULoad;
444 /* for CPU, we don't do the 'fast increase' since CPU is much
445 more jitterish to begin with */
446 agedCPULoad = (agedCPULoad * 31 + currentCPULoad) / 32;
449 if (currentIOLoad == -1)
455 if (agedIOLoad == -1)
457 agedIOLoad = currentIOLoad;
461 /* for IO, we don't do the 'fast increase' since IO is much
462 more jitterish to begin with */
463 agedIOLoad = (agedIOLoad * 31 + currentIOLoad) / 32;
471 * Get the load of the CPU relative to what is allowed.
472 * @return the CPU load as a percentage of allowed
473 * (100 is equivalent to full load)
479 return (int) agedCPULoad;
484 * Get the load of the CPU relative to what is allowed.
485 * @return the CPU load as a percentage of allowed
486 * (100 is equivalent to full load)
492 return (int) agedIOLoad;
497 * Get the percentage of memory used
499 * @return the percentage of memory used
507 percentage = (((double) kb_main_used) / ((double) kb_main_total) * 100.0);
508 return (unsigned int) percentage;
515 * Returns the number of processes
517 * @return the number of processes
526 dir = opendir ("/proc");
530 while (NULL != (ent = readdir (dir)))
532 if ((*ent->d_name > '0') && (*ent->d_name <= '9'))
544 sample_load_task (void *cls)
546 struct GNUNET_TIME_Absolute now;
551 unsigned int mem_usage;
554 sample_load_task_id = NULL;
555 ld_cpu = cpu_get_load ();
556 ld_disk = disk_get_load ();
557 if ((-1 == ld_cpu) || (-1 == ld_disk))
559 mem_usage = mem_get_usage ();
561 nproc = get_nproc ();
565 now = GNUNET_TIME_absolute_get ();
566 nbs = GNUNET_asprintf (&str, "%llu %d %d %u %u\n", now.abs_value_us / 1000LL
568 ld_cpu, ld_disk, mem_usage, nproc);
571 GNUNET_BIO_write (bw, str, nbs);
578 sample_load_task_id =
579 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
580 &sample_load_task, NULL);
585 * Initialize logging CPU and IO statisticfs. Checks the configuration for
586 * "STATS_DIR" and logs to a file in that directory. The file is name is
587 * generated from the hostname and the process's PID.
590 GST_stats_init (const struct GNUNET_CONFIGURATION_Handle *cfg)
598 GNUNET_CONFIGURATION_get_value_filename (cfg, "testbed",
599 "STATS_DIR", &stats_dir))
601 len = GNUNET_OS_get_hostname_max_length ();
602 hostname = GNUNET_malloc (len);
603 if (0 != gethostname (hostname, len))
605 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "gethostname");
606 GNUNET_free (stats_dir);
607 GNUNET_free (hostname);
611 (void) GNUNET_asprintf (&fn, "%s/%.*s-%jd.dat", stats_dir, len,
612 hostname, (intmax_t) getpid ());
613 GNUNET_free (stats_dir);
614 GNUNET_free (hostname);
615 if (NULL == (bw = GNUNET_BIO_write_open (fn)))
617 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
618 _ ("Cannot open %s for writing load statistics. "
619 "Not logging load statistics\n"), fn);
624 sample_load_task_id = GNUNET_SCHEDULER_add_now (&sample_load_task, NULL);
626 proc_stat = fopen ("/proc/stat", "r");
627 if (NULL == proc_stat)
628 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
629 "fopen", "/proc/stat");
633 updateUsage (); /* initialize */
638 * Shutdown the status calls module.
646 if (proc_stat != NULL)
652 GNUNET_free_non_null (prev_cpu_load);
654 if (NULL != sample_load_task_id)
656 GNUNET_SCHEDULER_cancel (sample_load_task_id);
657 sample_load_task_id = NULL;
659 GNUNET_break (GNUNET_OK == GNUNET_BIO_write_close (bw));
664 /* end of cpustatus.c */