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