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