Merge branch 'master' into katzj/memory
[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 verplant.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 static void memory_submit (const char *type_instance, gauge_t value, gauge_t total)
159 {
160         value_t values[1];
161         value_list_t vl = VALUE_LIST_INIT;
162
163         vl.values = values;
164         vl.values_len = 1;
165         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
166         sstrncpy (vl.plugin, "memory", sizeof (vl.plugin));
167         sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
168
169         if (values_absolute)
170         {
171                 values[0].gauge = value;
172                 sstrncpy (vl.type, "memory", sizeof (vl.type));
173                 plugin_dispatch_values (&vl);
174         }
175         if (values_percentage)
176         {
177                 values[0].gauge = 100.0 * value / total;
178                 sstrncpy (vl.type, "percent", sizeof (vl.type));
179                 plugin_dispatch_values (&vl);
180         }
181 }
182
183 static int memory_read (void)
184 {
185 #if HAVE_HOST_STATISTICS
186         kern_return_t status;
187         vm_statistics_data_t   vm_data;
188         mach_msg_type_number_t vm_data_len;
189
190         gauge_t wired;
191         gauge_t active;
192         gauge_t inactive;
193         gauge_t free;
194         gauge_t total;
195
196         if (!port_host || !pagesize)
197                 return (-1);
198
199         vm_data_len = sizeof (vm_data) / sizeof (natural_t);
200         if ((status = host_statistics (port_host, HOST_VM_INFO,
201                                         (host_info_t) &vm_data,
202                                         &vm_data_len)) != KERN_SUCCESS)
203         {
204                 ERROR ("memory-plugin: host_statistics failed and returned the value %i", (int) status);
205                 return (-1);
206         }
207
208         /*
209          * From <http://docs.info.apple.com/article.html?artnum=107918>:
210          *
211          * Wired memory
212          *   This information can't be cached to disk, so it must stay in RAM.
213          *   The amount depends on what applications you are using.
214          *
215          * Active memory
216          *   This information is currently in RAM and actively being used.
217          *
218          * Inactive memory
219          *   This information is no longer being used and has been cached to
220          *   disk, but it will remain in RAM until another application needs
221          *   the space. Leaving this information in RAM is to your advantage if
222          *   you (or a client of your computer) come back to it later.
223          *
224          * Free memory
225          *   This memory is not being used.
226          */
227
228         wired    = (gauge_t) (((uint64_t) vm_data.wire_count)     * ((uint64_t) pagesize));
229         active   = (gauge_t) (((uint64_t) vm_data.active_count)   * ((uint64_t) pagesize));
230         inactive = (gauge_t) (((uint64_t) vm_data.inactive_count) * ((uint64_t) pagesize));
231         free     = (gauge_t) (((uint64_t) vm_data.free_count)     * ((uint64_t) pagesize));
232         total    = wired + active + inactive + free;
233
234         memory_submit ("wired",    wired,    total);
235         memory_submit ("active",   active,   total);
236         memory_submit ("inactive", inactive, total);
237         memory_submit ("free",     free,     total);
238 /* #endif HAVE_HOST_STATISTICS */
239
240 #elif HAVE_SYSCTLBYNAME
241         /*
242          * vm.stats.vm.v_page_size: 4096
243          * vm.stats.vm.v_page_count: 246178
244          * vm.stats.vm.v_free_count: 28760
245          * vm.stats.vm.v_wire_count: 37526
246          * vm.stats.vm.v_active_count: 55239
247          * vm.stats.vm.v_inactive_count: 113730
248          * vm.stats.vm.v_cache_count: 10809
249          */
250         char *sysctl_keys[8] =
251         {
252                 "vm.stats.vm.v_page_size",
253                 "vm.stats.vm.v_page_count",
254                 "vm.stats.vm.v_free_count",
255                 "vm.stats.vm.v_wire_count",
256                 "vm.stats.vm.v_active_count",
257                 "vm.stats.vm.v_inactive_count",
258                 "vm.stats.vm.v_cache_count",
259                 NULL
260         };
261         double sysctl_vals[8];
262         gauge_t total;
263
264         int    i;
265
266         for (i = 0; sysctl_keys[i] != NULL; i++)
267         {
268                 int value;
269                 size_t value_len = sizeof (value);
270
271                 if (sysctlbyname (sysctl_keys[i], (void *) &value, &value_len,
272                                         NULL, 0) == 0)
273                 {
274                         sysctl_vals[i] = value;
275                         DEBUG ("memory plugin: %26s: %g", sysctl_keys[i], sysctl_vals[i]);
276                 }
277                 else
278                 {
279                         sysctl_vals[i] = NAN;
280                 }
281         } /* for (sysctl_keys) */
282
283         /* multiply all all page counts with the pagesize */
284         for (i = 1; sysctl_keys[i] != NULL; i++)
285                 if (!isnan (sysctl_vals[i]))
286                         sysctl_vals[i] *= sysctl_vals[0];
287
288         total = sysctl_vals[2] + sysctl_vals[3] + sysctl_vals[4] + sysctl_vals[5] + sysctl_vals[6];
289         memory_submit ("free",     sysctl_vals[2], total);
290         memory_submit ("wired",    sysctl_vals[3], total);
291         memory_submit ("active",   sysctl_vals[4], total);
292         memory_submit ("inactive", sysctl_vals[5], total);
293         memory_submit ("cache",    sysctl_vals[6], total);
294 /* #endif HAVE_SYSCTLBYNAME */
295
296 #elif KERNEL_LINUX
297         FILE *fh;
298         char buffer[1024];
299
300         char *fields[8];
301         int numfields;
302
303         long long mem_total = 0;
304         long long mem_used = 0;
305         long long mem_buffered = 0;
306         long long mem_cached = 0;
307         long long mem_free = 0;
308
309         if ((fh = fopen ("/proc/meminfo", "r")) == NULL)
310         {
311                 char errbuf[1024];
312                 WARNING ("memory: fopen: %s",
313                                 sstrerror (errno, errbuf, sizeof (errbuf)));
314                 return (-1);
315         }
316
317         while (fgets (buffer, 1024, fh) != NULL)
318         {
319                 long long *val = NULL;
320
321                 if (strncasecmp (buffer, "MemTotal:", 9) == 0)
322                         val = &mem_total;
323                 else if (strncasecmp (buffer, "MemFree:", 8) == 0)
324                         val = &mem_free;
325                 else if (strncasecmp (buffer, "Buffers:", 8) == 0)
326                         val = &mem_buffered;
327                 else if (strncasecmp (buffer, "Cached:", 7) == 0)
328                         val = &mem_cached;
329                 else
330                         continue;
331
332                 numfields = strsplit (buffer, fields, 8);
333
334                 if (numfields < 2)
335                         continue;
336
337                 *val = atoll (fields[1]) * 1024LL;
338         }
339
340         if (fclose (fh))
341         {
342                 char errbuf[1024];
343                 WARNING ("memory: fclose: %s",
344                                 sstrerror (errno, errbuf, sizeof (errbuf)));
345         }
346
347         if (mem_total < (mem_free + mem_buffered + mem_cached))
348                 return (0);
349
350         mem_used = mem_total - (mem_free + mem_buffered + mem_cached);
351         memory_submit ("used",     (gauge_t) mem_used,     (gauge_t) mem_total);
352         memory_submit ("buffered", (gauge_t) mem_buffered, (gauge_t) mem_total);
353         memory_submit ("cached",   (gauge_t) mem_cached,   (gauge_t) mem_total);
354         memory_submit ("free",     (gauge_t) mem_free,     (gauge_t) mem_total);
355 /* #endif KERNEL_LINUX */
356
357 #elif HAVE_LIBKSTAT
358         /* Most of the additions here were taken as-is from the k9toolkit from
359          * Brendan Gregg and are subject to change I guess */
360         long long mem_used;
361         long long mem_free;
362         long long mem_lock;
363         long long mem_kern;
364         long long mem_unus;
365         long long mem_total;
366
367         long long pp_kernel;
368         long long physmem;
369         long long availrmem;
370
371         if (ksp == NULL)
372                 return (-1);
373
374         mem_used = get_kstat_value (ksp, "pagestotal");
375         mem_free = get_kstat_value (ksp, "pagesfree");
376         mem_lock = get_kstat_value (ksp, "pageslocked");
377         mem_kern = 0;
378         mem_unus = 0;
379
380         pp_kernel = get_kstat_value (ksp, "pp_kernel");
381         physmem = get_kstat_value (ksp, "physmem");
382         availrmem = get_kstat_value (ksp, "availrmem");
383
384         if ((mem_used < 0LL) || (mem_free < 0LL) || (mem_lock < 0LL))
385         {
386                 WARNING ("memory plugin: one of used, free or locked is negative.");
387                 return (-1);
388         }
389
390         mem_unus = physmem - mem_used;
391
392         if (mem_used < (mem_free + mem_lock))
393         {
394                 /* source: http://wesunsolve.net/bugid/id/4909199
395                  * this seems to happen when swap space is small, e.g. 2G on a 32G system
396                  * we will make some assumptions here
397                  * educated solaris internals help welcome here */
398                 DEBUG ("memory plugin: pages total is smaller than \"free\" "
399                                 "+ \"locked\". This is probably due to small "
400                                 "swap space");
401                 mem_free = availrmem;
402                 mem_used = 0;
403         }
404         else
405         {
406                 mem_used -= mem_free + mem_lock;
407         }
408
409         /* mem_kern is accounted for in mem_lock */
410         if (pp_kernel < mem_lock)
411         {
412                 mem_kern = pp_kernel;
413                 mem_lock -= pp_kernel;
414         }
415         else
416         {
417                 mem_kern = mem_lock;
418                 mem_lock = 0;
419         }
420
421         mem_used *= pagesize; /* If this overflows you have some serious */
422         mem_free *= pagesize; /* memory.. Why not call me up and give me */
423         mem_lock *= pagesize; /* some? ;) */
424         mem_kern *= pagesize; /* it's 2011 RAM is cheap */
425         mem_unus *= pagesize;
426         mem_total = mem_used + mem_free + mem_lock + mem_kern + mem_unus;
427
428         memory_submit ("used",     (gauge_t) mem_used, (gauge_t) mem_total);
429         memory_submit ("free",     (gauge_t) mem_free, (gauge_t) mem_total);
430         memory_submit ("locked",   (gauge_t) mem_lock, (gauge_t) mem_total);
431         memory_submit ("kernel",   (gauge_t) mem_kern, (gauge_t) mem_total);
432         memory_submit ("unusable", (gauge_t) mem_unus, (gauge_t) mem_total);
433 /* #endif HAVE_LIBKSTAT */
434
435 #elif HAVE_SYSCTL
436         int mib[] = {CTL_VM, VM_METER};
437         struct vmtotal vmtotal;
438         gauge_t mem_active;
439         gauge_t mem_inactive;
440         gauge_t mem_free;
441         gauge_t mem_total;
442         size_t size;
443
444         memset (&vmtotal, 0, sizeof (vmtotal));
445         size = sizeof (vmtotal);
446
447         if (sysctl (mib, 2, &vmtotal, &size, NULL, 0) < 0) {
448                 char errbuf[1024];
449                 WARNING ("memory plugin: sysctl failed: %s",
450                         sstrerror (errno, errbuf, sizeof (errbuf)));
451                 return (-1);
452         }
453
454         assert (pagesize > 0);
455         mem_active   = (gauge_t) (vmtotal.t_arm * pagesize);
456         mem_inactive = (gauge_t) ((vmtotal.t_rm - vmtotal.t_arm) * pagesize);
457         mem_free     = (gauge_t) (vmtotal.t_free * pagesize);
458         mem_total    = mem_active + mem_inactive + mem_free;
459
460         memory_submit ("active",   mem_active,   mem_total);
461         memory_submit ("inactive", mem_inactive, mem_total);
462         memory_submit ("free",     mem_free,     mem_total);
463 /* #endif HAVE_SYSCTL */
464
465 #elif HAVE_LIBSTATGRAB
466         sg_mem_stats *ios;
467         gauge_t total;
468
469         ios = sg_get_mem_stats ();
470         if (ios == NULL)
471                 return (-1);
472
473         total = (gauge_t) (ios->used + ios->cache + ios->free);
474         memory_submit ("used",   (gauge_t) ios->used,  total);
475         memory_submit ("cached", (gauge_t) ios->cache, total);
476         memory_submit ("free",   (gauge_t) ios->free,  total);
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",   pmemory.real_free    * pagesize, pmemory.real_total * pagesize);
502         memory_submit ("cached", pmemory.numperm      * pagesize, pmemory.real_total * pagesize);
503         memory_submit ("system", pmemory.real_system  * pagesize, pmemory.real_total * pagesize);
504         memory_submit ("user",   pmemory.real_process * pagesize, pmemory.real_total * pagesize);
505 #endif /* HAVE_PERFSTAT */
506
507         return (0);
508 }
509
510 void module_register (void)
511 {
512         plugin_register_complex_config ("memory", memory_config);
513         plugin_register_init ("memory", memory_init);
514         plugin_register_read ("memory", memory_read);
515 } /* void module_register */