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