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