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