Merge pull request #3339 from jkohen/patch-1
[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         gauge_t mem_total = 0;
282         gauge_t mem_used = 0;
283         gauge_t mem_buffered = 0;
284         gauge_t mem_cached = 0;
285         gauge_t mem_free = 0;
286         gauge_t mem_slab_reclaimable = 0;
287         gauge_t mem_slab_unreclaimable = 0;
288
289         if ((fh = fopen ("/proc/meminfo", "r")) == NULL)
290         {
291                 char errbuf[1024];
292                 WARNING ("memory: fopen: %s",
293                                 sstrerror (errno, errbuf, sizeof (errbuf)));
294                 return (-1);
295         }
296
297         while (fgets (buffer, sizeof (buffer), fh) != NULL)
298         {
299                 gauge_t *val = NULL;
300
301                 if (strncasecmp (buffer, "MemTotal:", 9) == 0)
302                         val = &mem_total;
303                 else if (strncasecmp (buffer, "MemFree:", 8) == 0)
304                         val = &mem_free;
305                 else if (strncasecmp (buffer, "Buffers:", 8) == 0)
306                         val = &mem_buffered;
307                 else if (strncasecmp (buffer, "Cached:", 7) == 0)
308                         val = &mem_cached;
309                 else if (strncasecmp (buffer, "SReclaimable:", 13) == 0)
310                         val = &mem_slab_reclaimable;
311                 else if (strncasecmp (buffer, "SUnreclaim:", 11) == 0)
312                         val = &mem_slab_unreclaimable;
313                 else
314                         continue;
315
316                 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
317                 if (numfields < 2)
318                         continue;
319
320                 *val = 1024.0 * atof (fields[1]);
321         }
322
323         if (fclose (fh))
324         {
325                 char errbuf[1024];
326                 WARNING ("memory: fclose: %s",
327                                 sstrerror (errno, errbuf, sizeof (errbuf)));
328         }
329
330         if (mem_total < (mem_free + mem_buffered + mem_cached))
331                 return (-1);
332
333         mem_used = mem_total - (mem_free + mem_buffered + mem_cached + mem_slab_unreclaimable + mem_slab_reclaimable);
334         MEMORY_SUBMIT ("used",        mem_used,
335                        "buffered",    mem_buffered,
336                        "cached",      mem_cached,
337                        "free",        mem_free,
338                        "slab_unrecl", mem_slab_unreclaimable,
339                        "slab_recl",   mem_slab_reclaimable);
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
351         long long pp_kernel;
352         long long physmem;
353         long long availrmem;
354
355         if (ksp == 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         mem_kern = 0;
362         mem_unus = 0;
363
364         pp_kernel = get_kstat_value (ksp, "pp_kernel");
365         physmem = get_kstat_value (ksp, "physmem");
366         availrmem = get_kstat_value (ksp, "availrmem");
367
368         if ((mem_used < 0LL) || (mem_free < 0LL) || (mem_lock < 0LL))
369         {
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         {
378                 /* source: http://wesunsolve.net/bugid/id/4909199
379                  * this seems to happen when swap space is small, e.g. 2G on a 32G system
380                  * we will make some assumptions here
381                  * educated solaris internals help welcome here */
382                 DEBUG ("memory plugin: pages total is smaller than \"free\" "
383                                 "+ \"locked\". This is probably due to small "
384                                 "swap space");
385                 mem_free = availrmem;
386                 mem_used = 0;
387         }
388         else
389         {
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         {
396                 mem_kern = pp_kernel;
397                 mem_lock -= pp_kernel;
398         }
399         else
400         {
401                 mem_kern = mem_lock;
402                 mem_lock = 0;
403         }
404
405         mem_used *= pagesize; /* If this overflows you have some serious */
406         mem_free *= pagesize; /* memory.. Why not call me up and give me */
407         mem_lock *= pagesize; /* some? ;) */
408         mem_kern *= pagesize; /* it's 2011 RAM is cheap */
409         mem_unus *= pagesize;
410
411         MEMORY_SUBMIT ("used",     (gauge_t) mem_used,
412                        "free",     (gauge_t) mem_free,
413                        "locked",   (gauge_t) mem_lock,
414                        "kernel",   (gauge_t) mem_kern,
415                        "unusable", (gauge_t) mem_unus);
416 /* #endif HAVE_LIBKSTAT */
417
418 #elif HAVE_SYSCTL
419         int mib[] = {CTL_VM, VM_METER};
420         struct vmtotal vmtotal;
421         gauge_t mem_active;
422         gauge_t mem_inactive;
423         gauge_t mem_free;
424         size_t size;
425
426         memset (&vmtotal, 0, sizeof (vmtotal));
427         size = sizeof (vmtotal);
428
429         if (sysctl (mib, 2, &vmtotal, &size, NULL, 0) < 0) {
430                 char errbuf[1024];
431                 WARNING ("memory plugin: sysctl failed: %s",
432                         sstrerror (errno, errbuf, sizeof (errbuf)));
433                 return (-1);
434         }
435
436         assert (pagesize > 0);
437         mem_active   = (gauge_t) (vmtotal.t_arm * pagesize);
438         mem_inactive = (gauge_t) ((vmtotal.t_rm - vmtotal.t_arm) * pagesize);
439         mem_free     = (gauge_t) (vmtotal.t_free * pagesize);
440
441         MEMORY_SUBMIT ("active",   mem_active,
442                        "inactive", mem_inactive,
443                        "free",     mem_free);
444 /* #endif HAVE_SYSCTL */
445
446 #elif HAVE_LIBSTATGRAB
447         sg_mem_stats *ios;
448
449         ios = sg_get_mem_stats ();
450         if (ios == NULL)
451                 return (-1);
452
453         MEMORY_SUBMIT ("used",   (gauge_t) ios->used,
454                        "cached", (gauge_t) ios->cache,
455                        "free",   (gauge_t) ios->free);
456 /* #endif HAVE_LIBSTATGRAB */
457
458 #elif HAVE_PERFSTAT
459         perfstat_memory_total_t pmemory;
460
461         memset (&pmemory, 0, sizeof (pmemory));
462         if (perfstat_memory_total(NULL, &pmemory, sizeof(pmemory), 1) < 0)
463         {
464                 char errbuf[1024];
465                 WARNING ("memory plugin: perfstat_memory_total failed: %s",
466                         sstrerror (errno, errbuf, sizeof (errbuf)));
467                 return (-1);
468         }
469
470         /* Unfortunately, the AIX documentation is not very clear on how these
471          * numbers relate to one another. The only thing is states explcitly
472          * is:
473          *   real_total = real_process + real_free + numperm + real_system
474          *
475          * Another segmentation, which would be closer to the numbers reported
476          * by the "svmon" utility, would be:
477          *   real_total = real_free + real_inuse
478          *   real_inuse = "active" + real_pinned + numperm
479          */
480         MEMORY_SUBMIT ("free",   (gauge_t) (pmemory.real_free    * pagesize),
481                        "cached", (gauge_t) (pmemory.numperm      * pagesize),
482                        "system", (gauge_t) (pmemory.real_system  * pagesize),
483                        "user",   (gauge_t) (pmemory.real_process * pagesize));
484 #endif /* HAVE_PERFSTAT */
485
486         return (0);
487 } /* }}} int memory_read_internal */
488
489 static int memory_read (void) /* {{{ */
490 {
491         value_t v[1];
492         value_list_t vl = VALUE_LIST_INIT;
493
494         vl.values = v;
495         vl.values_len = STATIC_ARRAY_SIZE (v);
496         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
497         sstrncpy (vl.plugin, "memory", sizeof (vl.plugin));
498         sstrncpy (vl.type, "memory", sizeof (vl.type));
499         vl.time = cdtime ();
500
501         return (memory_read_internal (&vl));
502 } /* }}} int memory_read */
503
504 void module_register (void)
505 {
506         plugin_register_complex_config ("memory", memory_config);
507         plugin_register_init ("memory", memory_init);
508         plugin_register_read ("memory", memory_read);
509 } /* void module_register */