Merge branch 'collectd-4.3'
[collectd.git] / src / disk.c
1 /**
2  * collectd - src/disk.c
3  * Copyright (C) 2005-2008  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25 #include "utils_ignorelist.h"
26
27 #if HAVE_MACH_MACH_TYPES_H
28 #  include <mach/mach_types.h>
29 #endif
30 #if HAVE_MACH_MACH_INIT_H
31 #  include <mach/mach_init.h>
32 #endif
33 #if HAVE_MACH_MACH_ERROR_H
34 #  include <mach/mach_error.h>
35 #endif
36 #if HAVE_MACH_MACH_PORT_H
37 #  include <mach/mach_port.h>
38 #endif
39 #if HAVE_COREFOUNDATION_COREFOUNDATION_H
40 #  include <CoreFoundation/CoreFoundation.h>
41 #endif
42 #if HAVE_IOKIT_IOKITLIB_H
43 #  include <IOKit/IOKitLib.h>
44 #endif
45 #if HAVE_IOKIT_IOTYPES_H
46 #  include <IOKit/IOTypes.h>
47 #endif
48 #if HAVE_IOKIT_STORAGE_IOBLOCKSTORAGEDRIVER_H
49 #  include <IOKit/storage/IOBlockStorageDriver.h>
50 #endif
51 #if HAVE_IOKIT_IOBSD_H
52 #  include <IOKit/IOBSD.h>
53 #endif
54
55 #if HAVE_LIMITS_H
56 # include <limits.h>
57 #endif
58 #ifndef UINT_MAX
59 #  define UINT_MAX 4294967295U
60 #endif
61
62 #if HAVE_IOKIT_IOKITLIB_H
63 static mach_port_t io_master_port = MACH_PORT_NULL;
64 /* #endif HAVE_IOKIT_IOKITLIB_H */
65
66 #elif KERNEL_LINUX
67 typedef struct diskstats
68 {
69         char *name;
70
71         /* This overflows in roughly 1361 years */
72         unsigned int poll_count;
73
74         counter_t read_sectors;
75         counter_t write_sectors;
76
77         counter_t read_bytes;
78         counter_t write_bytes;
79
80         counter_t read_ops;
81         counter_t write_ops;
82         counter_t read_time;
83         counter_t write_time;
84
85         counter_t avg_read_time;
86         counter_t avg_write_time;
87
88         struct diskstats *next;
89 } diskstats_t;
90
91 static diskstats_t *disklist;
92 /* #endif KERNEL_LINUX */
93
94 #elif HAVE_LIBKSTAT
95 #define MAX_NUMDISK 256
96 extern kstat_ctl_t *kc;
97 static kstat_t *ksp[MAX_NUMDISK];
98 static int numdisk = 0;
99 /* #endif HAVE_LIBKSTAT */
100
101 #else
102 # error "No applicable input method."
103 #endif
104
105 static const char *config_keys[] =
106 {
107         "Disk",
108         "IgnoreSelected"
109 };
110 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
111
112 static ignorelist_t *ignorelist = NULL;
113
114 static int disk_config (const char *key, const char *value)
115 {
116   if (ignorelist == NULL)
117     ignorelist = ignorelist_create (/* invert = */ 1);
118   if (ignorelist == NULL)
119     return (1);
120
121   if (strcasecmp ("Disk", key) == 0)
122   {
123     ignorelist_add (ignorelist, value);
124   }
125   else if (strcasecmp ("IgnoreSelected", key) == 0)
126   {
127     int invert = 1;
128     if ((strcasecmp ("True", value) == 0)
129         || (strcasecmp ("Yes", value) == 0)
130         || (strcasecmp ("On", value) == 0))
131       invert = 0;
132     ignorelist_set_invert (ignorelist, invert);
133   }
134   else
135   {
136     return (-1);
137   }
138
139   return (0);
140 } /* int disk_config */
141
142 static int disk_init (void)
143 {
144 #if HAVE_IOKIT_IOKITLIB_H
145         kern_return_t status;
146         
147         if (io_master_port != MACH_PORT_NULL)
148         {
149                 mach_port_deallocate (mach_task_self (),
150                                 io_master_port);
151                 io_master_port = MACH_PORT_NULL;
152         }
153
154         status = IOMasterPort (MACH_PORT_NULL, &io_master_port);
155         if (status != kIOReturnSuccess)
156         {
157                 ERROR ("IOMasterPort failed: %s",
158                                 mach_error_string (status));
159                 io_master_port = MACH_PORT_NULL;
160                 return (-1);
161         }
162 /* #endif HAVE_IOKIT_IOKITLIB_H */
163
164 #elif KERNEL_LINUX
165         /* do nothing */
166 /* #endif KERNEL_LINUX */
167
168 #elif HAVE_LIBKSTAT
169         kstat_t *ksp_chain;
170
171         numdisk = 0;
172
173         if (kc == NULL)
174                 return (-1);
175
176         for (numdisk = 0, ksp_chain = kc->kc_chain;
177                         (numdisk < MAX_NUMDISK) && (ksp_chain != NULL);
178                         ksp_chain = ksp_chain->ks_next)
179         {
180                 if (strncmp (ksp_chain->ks_class, "disk", 4)
181                                 && strncmp (ksp_chain->ks_class, "partition", 9))
182                         continue;
183                 if (ksp_chain->ks_type != KSTAT_TYPE_IO)
184                         continue;
185                 ksp[numdisk++] = ksp_chain;
186         }
187 #endif /* HAVE_LIBKSTAT */
188
189         return (0);
190 } /* int disk_init */
191
192 static void disk_submit (const char *plugin_instance,
193                 const char *type,
194                 counter_t read, counter_t write)
195 {
196         value_t values[2];
197         value_list_t vl = VALUE_LIST_INIT;
198
199         /* Both `ignorelist' and `plugin_instance' may be NULL. */
200         if (ignorelist_match (ignorelist, plugin_instance) != 0)
201           return;
202
203         values[0].counter = read;
204         values[1].counter = write;
205
206         vl.values = values;
207         vl.values_len = 2;
208         vl.time = time (NULL);
209         strcpy (vl.host, hostname_g);
210         strcpy (vl.plugin, "disk");
211         strncpy (vl.plugin_instance, plugin_instance,
212                         sizeof (vl.plugin_instance));
213
214         plugin_dispatch_values (type, &vl);
215 } /* void disk_submit */
216
217 #if HAVE_IOKIT_IOKITLIB_H
218 static signed long long dict_get_value (CFDictionaryRef dict, const char *key)
219 {
220         signed long long val_int;
221         CFNumberRef      val_obj;
222         CFStringRef      key_obj;
223
224         /* `key_obj' needs to be released. */
225         key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key,
226                         kCFStringEncodingASCII);
227         if (key_obj == NULL)
228         {
229                 DEBUG ("CFStringCreateWithCString (%s) failed.", key);
230                 return (-1LL);
231         }
232         
233         /* get => we don't need to release (== free) the object */
234         val_obj = (CFNumberRef) CFDictionaryGetValue (dict, key_obj);
235
236         CFRelease (key_obj);
237
238         if (val_obj == NULL)
239         {
240                 DEBUG ("CFDictionaryGetValue (%s) failed.", key);
241                 return (-1LL);
242         }
243
244         if (!CFNumberGetValue (val_obj, kCFNumberSInt64Type, &val_int))
245         {
246                 DEBUG ("CFNumberGetValue (%s) failed.", key);
247                 return (-1LL);
248         }
249
250         return (val_int);
251 }
252 #endif /* HAVE_IOKIT_IOKITLIB_H */
253
254 static int disk_read (void)
255 {
256 #if HAVE_IOKIT_IOKITLIB_H
257         io_registry_entry_t     disk;
258         io_registry_entry_t     disk_child;
259         io_iterator_t           disk_list;
260         CFDictionaryRef         props_dict;
261         CFDictionaryRef         stats_dict;
262         CFDictionaryRef         child_dict;
263         kern_return_t           status;
264
265         signed long long read_ops;
266         signed long long read_byt;
267         signed long long read_tme;
268         signed long long write_ops;
269         signed long long write_byt;
270         signed long long write_tme;
271
272         int  disk_major;
273         int  disk_minor;
274         char disk_name[64];
275
276         /* Get the list of all disk objects. */
277         if (IOServiceGetMatchingServices (io_master_port,
278                                 IOServiceMatching (kIOBlockStorageDriverClass),
279                                 &disk_list) != kIOReturnSuccess)
280         {
281                 ERROR ("disk plugin: IOServiceGetMatchingServices failed.");
282                 return (-1);
283         }
284
285         while ((disk = IOIteratorNext (disk_list)) != 0)
286         {
287                 props_dict = NULL;
288                 stats_dict = NULL;
289                 child_dict = NULL;
290
291                 /* `disk_child' must be released */
292                 if ((status = IORegistryEntryGetChildEntry (disk, kIOServicePlane, &disk_child))
293                                 != kIOReturnSuccess)
294                 {
295                         /* This fails for example for DVD/CD drives.. */
296                         DEBUG ("IORegistryEntryGetChildEntry (disk) failed: 0x%08x", status);
297                         IOObjectRelease (disk);
298                         continue;
299                 }
300
301                 /* We create `props_dict' => we need to release it later */
302                 if (IORegistryEntryCreateCFProperties (disk,
303                                         (CFMutableDictionaryRef *) &props_dict,
304                                         kCFAllocatorDefault,
305                                         kNilOptions)
306                                 != kIOReturnSuccess)
307                 {
308                         ERROR ("disk-plugin: IORegistryEntryCreateCFProperties failed.");
309                         IOObjectRelease (disk_child);
310                         IOObjectRelease (disk);
311                         continue;
312                 }
313
314                 if (props_dict == NULL)
315                 {
316                         DEBUG ("IORegistryEntryCreateCFProperties (disk) failed.");
317                         IOObjectRelease (disk_child);
318                         IOObjectRelease (disk);
319                         continue;
320                 }
321
322                 stats_dict = (CFDictionaryRef) CFDictionaryGetValue (props_dict,
323                                 CFSTR (kIOBlockStorageDriverStatisticsKey));
324
325                 if (stats_dict == NULL)
326                 {
327                         DEBUG ("CFDictionaryGetValue (%s) failed.",
328                                         kIOBlockStorageDriverStatisticsKey);
329                         CFRelease (props_dict);
330                         IOObjectRelease (disk_child);
331                         IOObjectRelease (disk);
332                         continue;
333                 }
334
335                 if (IORegistryEntryCreateCFProperties (disk_child,
336                                         (CFMutableDictionaryRef *) &child_dict,
337                                         kCFAllocatorDefault,
338                                         kNilOptions)
339                                 != kIOReturnSuccess)
340                 {
341                         DEBUG ("IORegistryEntryCreateCFProperties (disk_child) failed.");
342                         IOObjectRelease (disk_child);
343                         CFRelease (props_dict);
344                         IOObjectRelease (disk);
345                         continue;
346                 }
347
348                 /* kIOBSDNameKey */
349                 disk_major = (int) dict_get_value (child_dict,
350                                 kIOBSDMajorKey);
351                 disk_minor = (int) dict_get_value (child_dict,
352                                 kIOBSDMinorKey);
353                 read_ops  = dict_get_value (stats_dict,
354                                 kIOBlockStorageDriverStatisticsReadsKey);
355                 read_byt  = dict_get_value (stats_dict,
356                                 kIOBlockStorageDriverStatisticsBytesReadKey);
357                 read_tme  = dict_get_value (stats_dict,
358                                 kIOBlockStorageDriverStatisticsTotalReadTimeKey);
359                 write_ops = dict_get_value (stats_dict,
360                                 kIOBlockStorageDriverStatisticsWritesKey);
361                 write_byt = dict_get_value (stats_dict,
362                                 kIOBlockStorageDriverStatisticsBytesWrittenKey);
363                 /* This property describes the number of nanoseconds spent
364                  * performing writes since the block storage driver was
365                  * instantiated. It is one of the statistic entries listed
366                  * under the top-level kIOBlockStorageDriverStatisticsKey
367                  * property table. It has an OSNumber value. */
368                 write_tme = dict_get_value (stats_dict,
369                                 kIOBlockStorageDriverStatisticsTotalWriteTimeKey);
370
371                 if (snprintf (disk_name, 64, "%i-%i", disk_major, disk_minor) >= 64)
372                 {
373                         DEBUG ("snprintf (major, minor) failed.");
374                         CFRelease (child_dict);
375                         IOObjectRelease (disk_child);
376                         CFRelease (props_dict);
377                         IOObjectRelease (disk);
378                         continue;
379                 }
380                 DEBUG ("disk_name = %s", disk_name);
381
382                 if ((read_byt != -1LL) || (write_byt != -1LL))
383                         disk_submit (disk_name, "disk_octets", read_byt, write_byt);
384                 if ((read_ops != -1LL) || (write_ops != -1LL))
385                         disk_submit (disk_name, "disk_ops", read_ops, write_ops);
386                 if ((read_tme != -1LL) || (write_tme != -1LL))
387                         disk_submit (disk_name, "disk_time",
388                                         read_tme / 1000,
389                                         write_tme / 1000);
390
391                 CFRelease (child_dict);
392                 IOObjectRelease (disk_child);
393                 CFRelease (props_dict);
394                 IOObjectRelease (disk);
395         }
396         IOObjectRelease (disk_list);
397 /* #endif HAVE_IOKIT_IOKITLIB_H */
398
399 #elif KERNEL_LINUX
400         FILE *fh;
401         char buffer[1024];
402         
403         char *fields[32];
404         int numfields;
405         int fieldshift = 0;
406
407         int major = 0;
408         int minor = 0;
409
410         counter_t read_sectors  = 0;
411         counter_t write_sectors = 0;
412
413         counter_t read_ops      = 0;
414         counter_t read_merged   = 0;
415         counter_t read_time     = 0;
416         counter_t write_ops     = 0;
417         counter_t write_merged  = 0;
418         counter_t write_time    = 0;
419         int is_disk = 0;
420
421         diskstats_t *ds, *pre_ds;
422
423         if ((fh = fopen ("/proc/diskstats", "r")) == NULL)
424         {
425                 fh = fopen ("/proc/partitions", "r");
426                 if (fh == NULL)
427                 {
428                         ERROR ("disk plugin: fopen (/proc/{diskstats,partitions}) failed.");
429                         return (-1);
430                 }
431
432                 /* Kernel is 2.4.* */
433                 fieldshift = 1;
434         }
435
436         while (fgets (buffer, sizeof (buffer), fh) != NULL)
437         {
438                 char *disk_name;
439
440                 numfields = strsplit (buffer, fields, 32);
441
442                 if ((numfields != (14 + fieldshift)) && (numfields != 7))
443                         continue;
444
445                 major = atoll (fields[0]);
446                 minor = atoll (fields[1]);
447
448                 disk_name = fields[2];
449
450                 for (ds = disklist, pre_ds = disklist; ds != NULL; pre_ds = ds, ds = ds->next)
451                         if (strcmp (disk_name, ds->name) == 0)
452                                 break;
453
454                 if (ds == NULL)
455                 {
456                         if ((ds = (diskstats_t *) calloc (1, sizeof (diskstats_t))) == NULL)
457                                 continue;
458
459                         if ((ds->name = strdup (disk_name)) == NULL)
460                         {
461                                 free (ds);
462                                 continue;
463                         }
464
465                         if (pre_ds == NULL)
466                                 disklist = ds;
467                         else
468                                 pre_ds->next = ds;
469                 }
470
471                 is_disk = 0;
472                 if (numfields == 7)
473                 {
474                         /* Kernel 2.6, Partition */
475                         read_ops      = atoll (fields[3]);
476                         read_sectors  = atoll (fields[4]);
477                         write_ops     = atoll (fields[5]);
478                         write_sectors = atoll (fields[6]);
479                 }
480                 else if (numfields == (14 + fieldshift))
481                 {
482                         read_ops  =  atoll (fields[3 + fieldshift]);
483                         write_ops =  atoll (fields[7 + fieldshift]);
484
485                         read_sectors  = atoll (fields[5 + fieldshift]);
486                         write_sectors = atoll (fields[9 + fieldshift]);
487
488                         if ((fieldshift == 0) || (minor == 0))
489                         {
490                                 is_disk = 1;
491                                 read_merged  = atoll (fields[4 + fieldshift]);
492                                 read_time    = atoll (fields[6 + fieldshift]);
493                                 write_merged = atoll (fields[8 + fieldshift]);
494                                 write_time   = atoll (fields[10+ fieldshift]);
495                         }
496                 }
497                 else
498                 {
499                         DEBUG ("numfields = %i; => unknown file format.", numfields);
500                         continue;
501                 }
502
503                 {
504                         counter_t diff_read_sectors;
505                         counter_t diff_write_sectors;
506
507                 /* If the counter wraps around, it's only 32 bits.. */
508                         if (read_sectors < ds->read_sectors)
509                                 diff_read_sectors = 1 + read_sectors
510                                         + (UINT_MAX - ds->read_sectors);
511                         else
512                                 diff_read_sectors = read_sectors - ds->read_sectors;
513                         if (write_sectors < ds->write_sectors)
514                                 diff_write_sectors = 1 + write_sectors
515                                         + (UINT_MAX - ds->write_sectors);
516                         else
517                                 diff_write_sectors = write_sectors - ds->write_sectors;
518
519                         ds->read_bytes += 512 * diff_read_sectors;
520                         ds->write_bytes += 512 * diff_write_sectors;
521                         ds->read_sectors = read_sectors;
522                         ds->write_sectors = write_sectors;
523                 }
524
525                 /* Calculate the average time an io-op needs to complete */
526                 if (is_disk)
527                 {
528                         counter_t diff_read_ops;
529                         counter_t diff_write_ops;
530                         counter_t diff_read_time;
531                         counter_t diff_write_time;
532
533                         if (read_ops < ds->read_ops)
534                                 diff_read_ops = 1 + read_ops
535                                         + (UINT_MAX - ds->read_ops);
536                         else
537                                 diff_read_ops = read_ops - ds->read_ops;
538                         DEBUG ("disk plugin: disk_name = %s; read_ops = %llu; "
539                                         "ds->read_ops = %llu; diff_read_ops = %llu;",
540                                         disk_name,
541                                         read_ops, ds->read_ops, diff_read_ops);
542
543                         if (write_ops < ds->write_ops)
544                                 diff_write_ops = 1 + write_ops
545                                         + (UINT_MAX - ds->write_ops);
546                         else
547                                 diff_write_ops = write_ops - ds->write_ops;
548
549                         if (read_time < ds->read_time)
550                                 diff_read_time = 1 + read_time
551                                         + (UINT_MAX - ds->read_time);
552                         else
553                                 diff_read_time = read_time - ds->read_time;
554
555                         if (write_time < ds->write_time)
556                                 diff_write_time = 1 + write_time
557                                         + (UINT_MAX - ds->write_time);
558                         else
559                                 diff_write_time = write_time - ds->write_time;
560
561                         if (diff_read_ops != 0)
562                                 ds->avg_read_time += (diff_read_time
563                                                 + (diff_read_ops / 2))
564                                         / diff_read_ops;
565                         if (diff_write_ops != 0)
566                                 ds->avg_write_time += (diff_write_time
567                                                 + (diff_write_ops / 2))
568                                         / diff_write_ops;
569
570                         ds->read_ops = read_ops;
571                         ds->read_time = read_time;
572                         ds->write_ops = write_ops;
573                         ds->write_time = write_time;
574                 } /* if (is_disk) */
575
576                 /* Don't write to the RRDs if we've just started.. */
577                 ds->poll_count++;
578                 if (ds->poll_count <= 2)
579                 {
580                         DEBUG ("disk plugin: (ds->poll_count = %i) <= "
581                                         "(min_poll_count = 2); => Not writing.",
582                                         ds->poll_count);
583                         continue;
584                 }
585
586                 if ((read_ops == 0) && (write_ops == 0))
587                 {
588                         DEBUG ("disk plugin: ((read_ops == 0) && "
589                                         "(write_ops == 0)); => Not writing.");
590                         continue;
591                 }
592
593                 if ((ds->read_bytes != 0) || (ds->write_bytes != 0))
594                         disk_submit (disk_name, "disk_octets",
595                                         ds->read_bytes, ds->write_bytes);
596
597                 if ((ds->read_ops != 0) || (ds->write_ops != 0))
598                         disk_submit (disk_name, "disk_ops",
599                                         read_ops, write_ops);
600
601                 if ((ds->avg_read_time != 0) || (ds->avg_write_time != 0))
602                         disk_submit (disk_name, "disk_time",
603                                         ds->avg_read_time, ds->avg_write_time);
604
605                 if (is_disk)
606                 {
607                         disk_submit (disk_name, "disk_merged",
608                                         read_merged, write_merged);
609                 } /* if (is_disk) */
610         } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
611
612         fclose (fh);
613 /* #endif defined(KERNEL_LINUX) */
614
615 #elif HAVE_LIBKSTAT
616 # if HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_NWRITES && HAVE_KSTAT_IO_T_WTIME
617 #  define KIO_ROCTETS reads
618 #  define KIO_WOCTETS writes
619 #  define KIO_ROPS    nreads
620 #  define KIO_WOPS    nwrites
621 #  define KIO_RTIME   rtime
622 #  define KIO_WTIME   wtime
623 # elif HAVE_KSTAT_IO_T_NWRITTEN && HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_WTIME
624 #  define KIO_ROCTETS nread
625 #  define KIO_WOCTETS nwritten
626 #  define KIO_ROPS    reads
627 #  define KIO_WOPS    writes
628 #  define KIO_RTIME   rtime
629 #  define KIO_WTIME   wtime
630 # else
631 #  error "kstat_io_t does not have the required members"
632 # endif
633         static kstat_io_t kio;
634         int i;
635
636         if (kc == NULL)
637                 return (-1);
638
639         for (i = 0; i < numdisk; i++)
640         {
641                 if (kstat_read (kc, ksp[i], &kio) == -1)
642                         continue;
643
644                 if (strncmp (ksp[i]->ks_class, "disk", 4) == 0)
645                 {
646                         disk_submit (ksp[i]->ks_name, "disk_octets",
647                                         kio.KIO_ROCTETS, kio.KIO_WOCTETS);
648                         disk_submit (ksp[i]->ks_name, "disk_ops",
649                                         kio.KIO_ROPS, kio.KIO_WOPS);
650                         /* FIXME: Convert this to microseconds if necessary */
651                         disk_submit (ksp[i]->ks_name, "disk_time",
652                                         kio.KIO_RTIME, kio.KIO_WTIME);
653                 }
654                 else if (strncmp (ksp[i]->ks_class, "partition", 9) == 0)
655                 {
656                         disk_submit (ksp[i]->ks_name, "disk_octets",
657                                         kio.KIO_ROCTETS, kio.KIO_WOCTETS);
658                         disk_submit (ksp[i]->ks_name, "disk_ops",
659                                         kio.KIO_ROPS, kio.KIO_WOPS);
660                 }
661         }
662 #endif /* defined(HAVE_LIBKSTAT) */
663
664         return (0);
665 } /* int disk_read */
666
667 void module_register (void)
668 {
669   plugin_register_config ("disk", disk_config,
670       config_keys, config_keys_num);
671   plugin_register_init ("disk", disk_init);
672   plugin_register_read ("disk", disk_read);
673 } /* void module_register */