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