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