Format BSD constrained sysctl usage
[collectd.git] / src / memory.c
1 /**
2  * collectd - src/memory.c
3  * Copyright (C) 2005-2014  Florian octo Forster
4  * Copyright (C) 2009       Simon Kuhnle
5  * Copyright (C) 2009       Manuel Sanmartin
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; only version 2 of the License is applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Florian octo Forster <octo at collectd.org>
22  *   Simon Kuhnle <simon at blarzwurst.de>
23  *   Manuel Sanmartin
24  **/
25
26 #include "collectd.h"
27
28 #include "plugin.h"
29 #include "utils/common/common.h"
30
31 #if (defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTLBYNAME)) ||              \
32     defined(__OpenBSD__)
33 /* Implies BSD variant */
34 #include <sys/sysctl.h>
35 #endif
36 #ifdef HAVE_SYS_VMMETER_H
37 #include <sys/vmmeter.h>
38 #endif
39
40 #ifdef HAVE_MACH_KERN_RETURN_H
41 #include <mach/kern_return.h>
42 #endif
43 #ifdef HAVE_MACH_MACH_INIT_H
44 #include <mach/mach_init.h>
45 #endif
46 #ifdef HAVE_MACH_MACH_HOST_H
47 #include <mach/mach_host.h>
48 #endif
49 #ifdef HAVE_MACH_HOST_PRIV_H
50 #include <mach/host_priv.h>
51 #endif
52 #ifdef HAVE_MACH_VM_STATISTICS_H
53 #include <mach/vm_statistics.h>
54 #endif
55
56 #if HAVE_STATGRAB_H
57 #include <statgrab.h>
58 #endif
59
60 #if HAVE_PERFSTAT
61 #include <libperfstat.h>
62 #include <sys/protosw.h>
63 #endif /* HAVE_PERFSTAT */
64
65 /* vm_statistics_data_t */
66 #if HAVE_HOST_STATISTICS
67 static mach_port_t port_host;
68 static vm_size_t pagesize;
69 /* #endif HAVE_HOST_STATISTICS */
70
71 #elif HAVE_SYSCTLBYNAME
72 /* no global variables */
73 /* #endif HAVE_SYSCTLBYNAME */
74
75 #elif KERNEL_LINUX
76 /* no global variables */
77 /* #endif KERNEL_LINUX */
78
79 #elif HAVE_LIBKSTAT
80 static int pagesize;
81 static kstat_t *ksp;
82 static kstat_t *ksz;
83 /* #endif HAVE_LIBKSTAT */
84
85 #elif HAVE_SYSCTL && __OpenBSD__
86 /* OpenBSD variant does not have sysctlbyname */
87 static int pagesize;
88 /* #endif HAVE_SYSCTL && __OpenBSD__ */
89
90 #elif HAVE_LIBSTATGRAB
91 /* no global variables */
92 /* endif HAVE_LIBSTATGRAB */
93 #elif HAVE_PERFSTAT
94 static int pagesize;
95 /* endif HAVE_PERFSTAT */
96 #else
97 #error "No applicable input method."
98 #endif
99
100 static bool values_absolute = true;
101 static bool values_percentage;
102
103 static int memory_config(oconfig_item_t *ci) /* {{{ */
104 {
105   for (int i = 0; i < ci->children_num; i++) {
106     oconfig_item_t *child = ci->children + i;
107     if (strcasecmp("ValuesAbsolute", child->key) == 0)
108       cf_util_get_boolean(child, &values_absolute);
109     else if (strcasecmp("ValuesPercentage", child->key) == 0)
110       cf_util_get_boolean(child, &values_percentage);
111     else
112       ERROR("memory plugin: Invalid configuration option: "
113             "\"%s\".",
114             child->key);
115   }
116
117   return 0;
118 } /* }}} int memory_config */
119
120 static int memory_init(void) {
121 #if HAVE_HOST_STATISTICS
122   port_host = mach_host_self();
123   host_page_size(port_host, &pagesize);
124   /* #endif HAVE_HOST_STATISTICS */
125
126 #elif HAVE_SYSCTLBYNAME
127 /* no init stuff */
128 /* #endif HAVE_SYSCTLBYNAME */
129
130 #elif defined(KERNEL_LINUX)
131 /* no init stuff */
132 /* #endif KERNEL_LINUX */
133
134 #elif defined(HAVE_LIBKSTAT)
135   /* getpagesize(3C) tells me this does not fail.. */
136   pagesize = getpagesize();
137   if (get_kstat(&ksp, "unix", 0, "system_pages") != 0) {
138     ksp = NULL;
139     return -1;
140   }
141   if (get_kstat(&ksz, "zfs", 0, "arcstats") != 0) {
142     ksz = NULL;
143     return -1;
144   }
145
146     /* #endif HAVE_LIBKSTAT */
147
148 #elif HAVE_SYSCTL && __OpenBSD__
149   /* OpenBSD variant does not have sysctlbyname */
150   pagesize = getpagesize();
151   if (pagesize <= 0) {
152     ERROR("memory plugin: Invalid pagesize: %i", pagesize);
153     return -1;
154   }
155     /* #endif HAVE_SYSCTL && __OpenBSD__ */
156
157 #elif HAVE_LIBSTATGRAB
158 /* no init stuff */
159 /* #endif HAVE_LIBSTATGRAB */
160
161 #elif HAVE_PERFSTAT
162   pagesize = getpagesize();
163 #endif /* HAVE_PERFSTAT */
164   return 0;
165 } /* int memory_init */
166
167 #define MEMORY_SUBMIT(...)                                                     \
168   do {                                                                         \
169     if (values_absolute)                                                       \
170       plugin_dispatch_multivalue(vl, false, DS_TYPE_GAUGE, __VA_ARGS__, NULL); \
171     if (values_percentage)                                                     \
172       plugin_dispatch_multivalue(vl, true, DS_TYPE_GAUGE, __VA_ARGS__, NULL);  \
173   } while (0)
174
175 static int memory_read_internal(value_list_t *vl) {
176 #if HAVE_HOST_STATISTICS
177   kern_return_t status;
178   vm_statistics_data_t vm_data;
179   mach_msg_type_number_t vm_data_len;
180
181   gauge_t wired;
182   gauge_t active;
183   gauge_t inactive;
184   gauge_t free;
185
186   if (!port_host || !pagesize)
187     return -1;
188
189   vm_data_len = sizeof(vm_data) / sizeof(natural_t);
190   if ((status = host_statistics(port_host, HOST_VM_INFO, (host_info_t)&vm_data,
191                                 &vm_data_len)) != KERN_SUCCESS) {
192     ERROR("memory-plugin: host_statistics failed and returned the value %i",
193           (int)status);
194     return -1;
195   }
196
197   /*
198    * From <http://docs.info.apple.com/article.html?artnum=107918>:
199    *
200    * Wired memory
201    *   This information can't be cached to disk, so it must stay in RAM.
202    *   The amount depends on what applications you are using.
203    *
204    * Active memory
205    *   This information is currently in RAM and actively being used.
206    *
207    * Inactive memory
208    *   This information is no longer being used and has been cached to
209    *   disk, but it will remain in RAM until another application needs
210    *   the space. Leaving this information in RAM is to your advantage if
211    *   you (or a client of your computer) come back to it later.
212    *
213    * Free memory
214    *   This memory is not being used.
215    */
216
217   wired = (gauge_t)(((uint64_t)vm_data.wire_count) * ((uint64_t)pagesize));
218   active = (gauge_t)(((uint64_t)vm_data.active_count) * ((uint64_t)pagesize));
219   inactive =
220       (gauge_t)(((uint64_t)vm_data.inactive_count) * ((uint64_t)pagesize));
221   free = (gauge_t)(((uint64_t)vm_data.free_count) * ((uint64_t)pagesize));
222
223   MEMORY_SUBMIT("wired", wired, "active", active, "inactive", inactive, "free",
224                 free);
225   /* #endif HAVE_HOST_STATISTICS */
226
227 #elif HAVE_SYSCTLBYNAME
228   /*
229    * vm.stats.vm.v_page_size: 4096
230    * vm.stats.vm.v_page_count: 246178
231    * vm.stats.vm.v_free_count: 28760
232    * vm.stats.vm.v_wire_count: 37526
233    * vm.stats.vm.v_active_count: 55239
234    * vm.stats.vm.v_inactive_count: 113730
235    * vm.stats.vm.v_cache_count: 10809
236    */
237   const char *sysctl_keys[8] = {
238       "vm.stats.vm.v_page_size",    "vm.stats.vm.v_page_count",
239       "vm.stats.vm.v_free_count",   "vm.stats.vm.v_wire_count",
240       "vm.stats.vm.v_active_count", "vm.stats.vm.v_inactive_count",
241       "vm.stats.vm.v_cache_count",  NULL};
242   double sysctl_vals[8];
243
244   for (int i = 0; sysctl_keys[i] != NULL; i++) {
245     int value;
246     size_t value_len = sizeof(value);
247
248     if (sysctlbyname(sysctl_keys[i], (void *)&value, &value_len, NULL, 0) ==
249         0) {
250       sysctl_vals[i] = value;
251       DEBUG("memory plugin: %26s: %g", sysctl_keys[i], sysctl_vals[i]);
252     } else {
253       sysctl_vals[i] = NAN;
254     }
255   } /* for (sysctl_keys) */
256
257   /* multiply all all page counts with the pagesize */
258   for (int i = 1; sysctl_keys[i] != NULL; i++)
259     if (!isnan(sysctl_vals[i]))
260       sysctl_vals[i] *= sysctl_vals[0];
261
262   MEMORY_SUBMIT("free", (gauge_t)sysctl_vals[2], "wired",
263                 (gauge_t)sysctl_vals[3], "active", (gauge_t)sysctl_vals[4],
264                 "inactive", (gauge_t)sysctl_vals[5], "cache",
265                 (gauge_t)sysctl_vals[6]);
266   /* #endif HAVE_SYSCTLBYNAME */
267
268 #elif KERNEL_LINUX
269   FILE *fh;
270   char buffer[1024];
271
272   char *fields[8];
273   int numfields;
274
275   bool detailed_slab_info = false;
276
277   gauge_t mem_total = 0;
278   gauge_t mem_used = 0;
279   gauge_t mem_buffered = 0;
280   gauge_t mem_cached = 0;
281   gauge_t mem_free = 0;
282   gauge_t mem_slab_total = 0;
283   gauge_t mem_slab_reclaimable = 0;
284   gauge_t mem_slab_unreclaimable = 0;
285
286   if ((fh = fopen("/proc/meminfo", "r")) == NULL) {
287     WARNING("memory: fopen: %s", STRERRNO);
288     return -1;
289   }
290
291   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
292     gauge_t *val = NULL;
293
294     if (strncasecmp(buffer, "MemTotal:", 9) == 0)
295       val = &mem_total;
296     else if (strncasecmp(buffer, "MemFree:", 8) == 0)
297       val = &mem_free;
298     else if (strncasecmp(buffer, "Buffers:", 8) == 0)
299       val = &mem_buffered;
300     else if (strncasecmp(buffer, "Cached:", 7) == 0)
301       val = &mem_cached;
302     else if (strncasecmp(buffer, "Slab:", 5) == 0)
303       val = &mem_slab_total;
304     else if (strncasecmp(buffer, "SReclaimable:", 13) == 0) {
305       val = &mem_slab_reclaimable;
306       detailed_slab_info = true;
307     } else if (strncasecmp(buffer, "SUnreclaim:", 11) == 0) {
308       val = &mem_slab_unreclaimable;
309       detailed_slab_info = true;
310     } else
311       continue;
312
313     numfields = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
314     if (numfields < 2)
315       continue;
316
317     *val = 1024.0 * atof(fields[1]);
318   }
319
320   if (fclose(fh)) {
321     WARNING("memory: fclose: %s", STRERRNO);
322   }
323
324   if (mem_total < (mem_free + mem_buffered + mem_cached + mem_slab_total))
325     return -1;
326
327   mem_used =
328       mem_total - (mem_free + mem_buffered + mem_cached + mem_slab_total);
329
330   /* SReclaimable and SUnreclaim were introduced in kernel 2.6.19
331    * They sum up to the value of Slab, which is available on older & newer
332    * kernels. So SReclaimable/SUnreclaim are submitted if available, and Slab
333    * if not. */
334   if (detailed_slab_info)
335     MEMORY_SUBMIT("used", mem_used, "buffered", mem_buffered, "cached",
336                   mem_cached, "free", mem_free, "slab_unrecl",
337                   mem_slab_unreclaimable, "slab_recl", mem_slab_reclaimable);
338   else
339     MEMORY_SUBMIT("used", mem_used, "buffered", mem_buffered, "cached",
340                   mem_cached, "free", mem_free, "slab", mem_slab_total);
341     /* #endif KERNEL_LINUX */
342
343 #elif HAVE_LIBKSTAT
344   /* Most of the additions here were taken as-is from the k9toolkit from
345    * Brendan Gregg and are subject to change I guess */
346   long long mem_used;
347   long long mem_free;
348   long long mem_lock;
349   long long mem_kern;
350   long long mem_unus;
351   long long arcsize;
352
353   long long pp_kernel;
354   long long physmem;
355   long long availrmem;
356
357   if (ksp == NULL)
358     return -1;
359   if (ksz == NULL)
360     return -1;
361
362   mem_used = get_kstat_value(ksp, "pagestotal");
363   mem_free = get_kstat_value(ksp, "pagesfree");
364   mem_lock = get_kstat_value(ksp, "pageslocked");
365   arcsize = get_kstat_value(ksz, "size");
366   pp_kernel = get_kstat_value(ksp, "pp_kernel");
367   physmem = get_kstat_value(ksp, "physmem");
368   availrmem = get_kstat_value(ksp, "availrmem");
369
370   mem_kern = 0;
371   mem_unus = 0;
372
373   if ((mem_used < 0LL) || (mem_free < 0LL) || (mem_lock < 0LL)) {
374     WARNING("memory plugin: one of used, free or locked is negative.");
375     return -1;
376   }
377
378   mem_unus = physmem - mem_used;
379
380   if (mem_used < (mem_free + mem_lock)) {
381     /* source: http://wesunsolve.net/bugid/id/4909199
382      * this seems to happen when swap space is small, e.g. 2G on a 32G system
383      * we will make some assumptions here
384      * educated solaris internals help welcome here */
385     DEBUG("memory plugin: pages total is smaller than \"free\" "
386           "+ \"locked\". This is probably due to small "
387           "swap space");
388     mem_free = availrmem;
389     mem_used = 0;
390   } else {
391     mem_used -= mem_free + mem_lock;
392   }
393
394   /* mem_kern is accounted for in mem_lock */
395   if (pp_kernel < mem_lock) {
396     mem_kern = pp_kernel;
397     mem_lock -= pp_kernel;
398   } else {
399     mem_kern = mem_lock;
400     mem_lock = 0;
401   }
402
403   mem_used *= pagesize; /* If this overflows you have some serious */
404   mem_free *= pagesize; /* memory.. Why not call me up and give me */
405   mem_lock *= pagesize; /* some? ;) */
406   mem_kern *= pagesize; /* it's 2011 RAM is cheap */
407   mem_unus *= pagesize;
408   mem_kern -= arcsize;
409
410   MEMORY_SUBMIT("used", (gauge_t)mem_used, "free", (gauge_t)mem_free, "locked",
411                 (gauge_t)mem_lock, "kernel", (gauge_t)mem_kern, "arc",
412                 (gauge_t)arcsize, "unusable", (gauge_t)mem_unus);
413   /* #endif HAVE_LIBKSTAT */
414
415 #elif HAVE_SYSCTL && __OpenBSD__
416   /* OpenBSD variant does not have HAVE_SYSCTLBYNAME */
417   int mib[] = {CTL_VM, VM_METER};
418   struct vmtotal vmtotal = {0};
419   gauge_t mem_active;
420   gauge_t mem_inactive;
421   gauge_t mem_free;
422   size_t size;
423
424   size = sizeof(vmtotal);
425
426   if (sysctl(mib, 2, &vmtotal, &size, NULL, 0) < 0) {
427     WARNING("memory plugin: sysctl failed: %s", STRERRNO);
428     return -1;
429   }
430
431   assert(pagesize > 0);
432   mem_active = (gauge_t)(vmtotal.t_arm * pagesize);
433   mem_inactive = (gauge_t)((vmtotal.t_rm - vmtotal.t_arm) * pagesize);
434   mem_free = (gauge_t)(vmtotal.t_free * pagesize);
435
436   MEMORY_SUBMIT("active", mem_active, "inactive", mem_inactive, "free",
437                 mem_free);
438   /* #endif HAVE_SYSCTL && __OpenBSD__ */
439
440 #elif HAVE_LIBSTATGRAB
441   sg_mem_stats *ios;
442
443   ios = sg_get_mem_stats();
444   if (ios == NULL)
445     return -1;
446
447   MEMORY_SUBMIT("used", (gauge_t)ios->used, "cached", (gauge_t)ios->cache,
448                 "free", (gauge_t)ios->free);
449   /* #endif HAVE_LIBSTATGRAB */
450
451 #elif HAVE_PERFSTAT
452   perfstat_memory_total_t pmemory = {0};
453
454   if (perfstat_memory_total(NULL, &pmemory, sizeof(pmemory), 1) < 0) {
455     WARNING("memory plugin: perfstat_memory_total failed: %s", STRERRNO);
456     return -1;
457   }
458
459   /* Unfortunately, the AIX documentation is not very clear on how these
460    * numbers relate to one another. The only thing is states explcitly
461    * is:
462    *   real_total = real_process + real_free + numperm + real_system
463    *
464    * Another segmentation, which would be closer to the numbers reported
465    * by the "svmon" utility, would be:
466    *   real_total = real_free + real_inuse
467    *   real_inuse = "active" + real_pinned + numperm
468    */
469   MEMORY_SUBMIT("free", (gauge_t)(pmemory.real_free * pagesize), "cached",
470                 (gauge_t)(pmemory.numperm * pagesize), "system",
471                 (gauge_t)(pmemory.real_system * pagesize), "user",
472                 (gauge_t)(pmemory.real_process * pagesize));
473 #endif /* HAVE_PERFSTAT */
474
475   return 0;
476 } /* }}} int memory_read_internal */
477
478 static int memory_read(void) /* {{{ */
479 {
480   value_t v[1];
481   value_list_t vl = VALUE_LIST_INIT;
482
483   vl.values = v;
484   vl.values_len = STATIC_ARRAY_SIZE(v);
485   sstrncpy(vl.plugin, "memory", sizeof(vl.plugin));
486   sstrncpy(vl.type, "memory", sizeof(vl.type));
487   vl.time = cdtime();
488
489   return memory_read_internal(&vl);
490 } /* }}} int memory_read */
491
492 void module_register(void) {
493   plugin_register_complex_config("memory", memory_config);
494   plugin_register_init("memory", memory_init);
495   plugin_register_read("memory", memory_read);
496 } /* void module_register */