Link the `disk' plugin against `IOKitLib' when available..
[collectd.git] / src / disk.c
1 /**
2  * collectd - src/disk.c
3  * Copyright (C) 2005,2006  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; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Florian octo Forster <octo at verplant.org>
21  **/
22
23 #include "collectd.h"
24 #include "common.h"
25 #include "plugin.h"
26 #include "utils_debug.h"
27
28 #define MODULE_NAME "disk"
29
30 #if HAVE_MACH_MACH_TYPES_H
31 #  include <mach/mach_types.h>
32 #endif
33 #if HAVE_MACH_MACH_INIT_H
34 #  include <mach/mach_init.h>
35 #endif
36 #if HAVE_MACH_MACH_ERROR_H
37 #  include <mach/mach_error.h>
38 #endif
39 #if HAVE_MACH_MACH_PORT_H
40 #  include <mach/mach_port.h>
41 #endif
42 #if HAVE_COREFOUNDATION_COREFOUNDATION_H
43 #  include <CoreFoundation/CoreFoundation.h>
44 #endif
45 #if HAVE_IOKIT_IOKITLIB_H
46 #  include <IOKit/IOKitLib.h>
47 #endif
48 #if HAVE_IOKIT_IOTYPES_H
49 #  include <IOKit/IOTypes.h>
50 #endif
51 #if HAVE_IOKIT_STORAGE_IOBLOCKSTORAGEDRIVER_H
52 #  include <IOKit/storage/IOBlockStorageDriver.h>
53 #endif
54 #if HAVE_IOKIT_IOBSD_H
55 #  include <IOKit/IOBSD.h>
56 #endif
57
58 #if HAVE_IOKIT_IOKITLIB_H || KERNEL_LINUX || HAVE_LIBKSTAT
59 # define DISK_HAVE_READ 1
60 #else
61 # define DISK_HAVE_READ 0
62 #endif
63
64 static char *disk_filename_template = "disk-%s.rrd";
65 static char *part_filename_template = "partition-%s.rrd";
66
67 /* 104857600 == 100 MB */
68 static char *disk_ds_def[] =
69 {
70         "DS:rcount:COUNTER:"COLLECTD_HEARTBEAT":0:U",
71         "DS:rmerged:COUNTER:"COLLECTD_HEARTBEAT":0:U",
72         "DS:rbytes:COUNTER:"COLLECTD_HEARTBEAT":0:104857600",
73         "DS:rtime:COUNTER:"COLLECTD_HEARTBEAT":0:U",
74         "DS:wcount:COUNTER:"COLLECTD_HEARTBEAT":0:U",
75         "DS:wmerged:COUNTER:"COLLECTD_HEARTBEAT":0:U",
76         "DS:wbytes:COUNTER:"COLLECTD_HEARTBEAT":0:104857600",
77         "DS:wtime:COUNTER:"COLLECTD_HEARTBEAT":0:U",
78         NULL
79 };
80 static int disk_ds_num = 8;
81
82 static char *part_ds_def[] =
83 {
84         "DS:rcount:COUNTER:"COLLECTD_HEARTBEAT":0:U",
85         "DS:rbytes:COUNTER:"COLLECTD_HEARTBEAT":0:104857600",
86         "DS:wcount:COUNTER:"COLLECTD_HEARTBEAT":0:U",
87         "DS:wbytes:COUNTER:"COLLECTD_HEARTBEAT":0:104857600",
88         NULL
89 };
90 static int part_ds_num = 4;
91
92 #if HAVE_IOKIT_IOKITLIB_H
93 static mach_port_t io_master_port = MACH_PORT_NULL;
94 /* #endif HAVE_IOKIT_IOKITLIB_H */
95
96 #elif KERNEL_LINUX
97 typedef struct diskstats
98 {
99         char *name;
100
101         /* This overflows in roughly 1361 year */
102         unsigned int poll_count;
103
104         unsigned int read_sectors;
105         unsigned int write_sectors;
106
107         unsigned long long read_bytes;
108         unsigned long long write_bytes;
109
110         struct diskstats *next;
111 } diskstats_t;
112
113 static diskstats_t *disklist;
114 /* #endif KERNEL_LINUX */
115
116 #elif HAVE_LIBKSTAT
117 #define MAX_NUMDISK 256
118 extern kstat_ctl_t *kc;
119 static kstat_t *ksp[MAX_NUMDISK];
120 static int numdisk = 0;
121 #endif /* HAVE_LIBKSTAT */
122
123 static void disk_init (void)
124 {
125 #if HAVE_IOKIT_IOKITLIB_H
126         kern_return_t status;
127         
128         if (io_master_port != MACH_PORT_NULL)
129         {
130                 mach_port_deallocate (mach_task_self (),
131                                 io_master_port);
132                 io_master_port = MACH_PORT_NULL;
133         }
134
135         status = IOMasterPort (MACH_PORT_NULL, &io_master_port);
136         if (status != kIOReturnSuccess)
137         {
138                 syslog (LOG_ERR, "IOMasterPort failed: %s",
139                                 mach_error_string (status));
140                 io_master_port = MACH_PORT_NULL;
141                 return;
142         }
143 /* #endif HAVE_IOKIT_IOKITLIB_H */
144
145 #elif KERNEL_LINUX
146         /* No init needed */
147 /* #endif KERNEL_LINUX */
148
149 #elif HAVE_LIBKSTAT
150         kstat_t *ksp_chain;
151
152         numdisk = 0;
153
154         if (kc == NULL)
155                 return;
156
157         for (numdisk = 0, ksp_chain = kc->kc_chain;
158                         (numdisk < MAX_NUMDISK) && (ksp_chain != NULL);
159                         ksp_chain = ksp_chain->ks_next)
160         {
161                 if (strncmp (ksp_chain->ks_class, "disk", 4)
162                                 && strncmp (ksp_chain->ks_class, "partition", 9))
163                         continue;
164                 if (ksp_chain->ks_type != KSTAT_TYPE_IO)
165                         continue;
166                 ksp[numdisk++] = ksp_chain;
167         }
168 #endif /* HAVE_LIBKSTAT */
169
170         return;
171 }
172
173 static void disk_write (char *host, char *inst, char *val)
174 {
175         char file[512];
176         int status;
177
178         status = snprintf (file, 512, disk_filename_template, inst);
179         if (status < 1)
180                 return;
181         else if (status >= 512)
182                 return;
183
184         rrd_update_file (host, file, val, disk_ds_def, disk_ds_num);
185 }
186
187 static void partition_write (char *host, char *inst, char *val)
188 {
189         char file[512];
190         int status;
191
192         status = snprintf (file, 512, part_filename_template, inst);
193         if (status < 1)
194                 return;
195         else if (status >= 512)
196                 return;
197
198         rrd_update_file (host, file, val, part_ds_def, part_ds_num);
199 }
200
201 #if DISK_HAVE_READ
202 #define BUFSIZE 512
203 static void disk_submit (char *disk_name,
204                 unsigned long long read_count,
205                 unsigned long long read_merged,
206                 unsigned long long read_bytes,
207                 unsigned long long read_time,
208                 unsigned long long write_count,
209                 unsigned long long write_merged,
210                 unsigned long long write_bytes,
211                 unsigned long long write_time)
212 {
213         char buf[BUFSIZE];
214
215         if (snprintf (buf, BUFSIZE, "%u:%llu:%llu:%llu:%llu:%llu:%llu:%llu:%llu",
216                                 (unsigned int) curtime,
217                                 read_count, read_merged, read_bytes, read_time,
218                                 write_count, write_merged, write_bytes,
219                                 write_time) >= BUFSIZE)
220                 return;
221
222         plugin_submit (MODULE_NAME, disk_name, buf);
223 }
224
225 #if KERNEL_LINUX || HAVE_LIBKSTAT
226 static void partition_submit (char *part_name,
227                 unsigned long long read_count,
228                 unsigned long long read_bytes,
229                 unsigned long long write_count,
230                 unsigned long long write_bytes)
231 {
232         char buf[BUFSIZE];
233
234         if (snprintf (buf, BUFSIZE, "%u:%llu:%llu:%llu:%llu",
235                                 (unsigned int) curtime,
236                                 read_count, read_bytes, write_count,
237                                 write_bytes) >= BUFSIZE)
238                 return;
239
240         plugin_submit ("partition", part_name, buf);
241 }
242 #endif /* KERNEL_LINUX || HAVE_LIBKSTAT */
243 #undef BUFSIZE
244
245 #if HAVE_IOKIT_IOKITLIB_H
246 static signed long long dict_get_value (CFDictionaryRef dict, const char *key)
247 {
248         signed long long val_int;
249         CFNumberRef      val_obj;
250         CFStringRef      key_obj;
251
252         CFStringRef CFStringCreateWithCString (
253                         CFAllocatorRef alloc,
254                         const char *cStr,
255                         CFStringEncoding encoding
256                         );
257
258         /* `key_obj' needs to be released. */
259         key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key,
260                         kCFStringEncodingASCII);
261         if (key_obj == NULL)
262                 return (-1LL);
263         
264         /* get => we don't need to release (== free) the object */
265         val_obj = (CFNumberRef) CFDictionaryGetValue (dict, key_obj);
266
267         CFRelease (key_obj);
268
269         if (val_obj == NULL)
270                 return (-1LL);
271
272         if (CFNumberGetValue (val_obj, kCFNumberSInt64Type, &val_int)
273                         != kIOReturnSuccess)
274                 return (-1LL);
275
276         return (val_int);
277 }
278 #endif /* HAVE_IOKIT_IOKITLIB_H */
279
280 static void disk_read (void)
281 {
282 #if HAVE_IOKIT_IOKITLIB_H
283         io_registry_entry_t     disk;
284         io_registry_entry_t     disk_child;
285         io_iterator_t           disk_list;
286         CFDictionaryRef         props_dict;
287         CFDictionaryRef         stats_dict;
288         CFDictionaryRef         child_dict;
289
290         signed long long read_ops;
291         signed long long read_byt;
292         signed long long read_tme;
293         signed long long write_ops;
294         signed long long write_byt;
295         signed long long write_tme;
296
297         int  disk_major;
298         int  disk_minor;
299         char disk_name[64];
300
301         /* Get the list of all disk objects. */
302         if (IOServiceGetMatchingServices (io_master_port,
303                                 IOServiceMatching (kIOBlockStorageDriverClass),
304                                 &disk_list) != kIOReturnSuccess)
305         {
306                 syslog (LOG_ERR, "disk-plugin: IOServiceGetMatchingServices failed.");
307                 return;
308         }
309
310         while ((disk = IOIteratorNext (disk_list)) != 0)
311         {
312                 props_dict = NULL;
313                 stats_dict = NULL;
314                 child_dict = NULL;
315
316                 /* We create `props_dict' => we need to release it later */
317                 if (IORegistryEntryCreateCFProperties (disk,
318                                         (CFMutableDictionaryRef *) &props_dict,
319                                         kCFAllocatorDefault,
320                                         kNilOptions)
321                                 != kIOReturnSuccess)
322                 {
323                         syslog (LOG_ERR, "disk-plugin: IORegistryEntryCreateCFProperties failed.");
324                         IOObjectRelease (disk);
325                         continue;
326                 }
327
328                 if (props_dict == NULL)
329                 {
330                         DBG ("IORegistryEntryCreateCFProperties (disk) failed.");
331                         IOObjectRelease (disk);
332                         continue;
333                 }
334
335                 stats_dict = (CFDictionaryRef) CFDictionaryGetValue (props_dict,
336                                 CFSTR (kIOBlockStorageDriverStatisticsKey));
337
338                 if (stats_dict == NULL)
339                 {
340                         DBG ("CFDictionaryGetValue (%s) failed.",
341                                         kIOBlockStorageDriverStatisticsKey);
342                         CFRelease (props_dict);
343                         IOObjectRelease (disk);
344                         continue;
345                 }
346
347                 /* `disk_child' must be released */
348                 if (IORegistryEntryGetChildEntry (disk, kIOServicePlane, &disk_child)
349                                 != kIOReturnSuccess)
350                 {
351                         DBG ("IORegistryEntryGetChildEntry (disk) failed.");
352                         CFRelease (props_dict);
353                         IOObjectRelease (disk);
354                         continue;
355                 }
356
357                 if (IORegistryEntryCreateCFProperties (disk_child,
358                                         (CFMutableDictionaryRef *) &child_dict,
359                                         kCFAllocatorDefault,
360                                         kNilOptions)
361                                 != kIOReturnSuccess)
362                 {
363                         DBG ("IORegistryEntryCreateCFProperties (disk_child) failed.");
364                         IOObjectRelease (disk_child);
365                         CFRelease (props_dict);
366                         IOObjectRelease (disk);
367                         continue;
368                 }
369
370                 disk_major = (int) dict_get_value (child_dict,
371                                 kIOBSDMajorKey);
372                 disk_minor = (int) dict_get_value (child_dict,
373                                 kIOBSDMinorKey);
374                 read_ops  = dict_get_value (stats_dict,
375                                 kIOBlockStorageDriverStatisticsReadsKey);
376                 read_byt  = dict_get_value (stats_dict,
377                                 kIOBlockStorageDriverStatisticsBytesReadKey);
378                 read_tme  = dict_get_value (stats_dict,
379                                 kIOBlockStorageDriverStatisticsTotalReadTimeKey);
380                 write_ops = dict_get_value (stats_dict,
381                                 kIOBlockStorageDriverStatisticsWritesKey);
382                 write_byt = dict_get_value (stats_dict,
383                                 kIOBlockStorageDriverStatisticsBytesWrittenKey);
384                 write_tme = dict_get_value (stats_dict,
385                                 kIOBlockStorageDriverStatisticsTotalWriteTimeKey);
386
387                 if (snprintf (disk_name, 64, "%i-%i", disk_major, disk_minor) >= 64)
388                 {
389                         DBG ("snprintf (major, minor) failed.");
390                         CFRelease (child_dict);
391                         IOObjectRelease (disk_child);
392                         CFRelease (props_dict);
393                         IOObjectRelease (disk);
394                         continue;
395                 }
396
397                 if ((read_ops != -1LL)
398                                 || (read_byt != -1LL)
399                                 || (read_tme != -1LL)
400                                 || (write_ops != -1LL)
401                                 || (write_byt != -1LL)
402                                 || (write_tme != -1LL))
403                         disk_submit (disk_name,
404                                         read_ops, 0ULL, read_byt, read_tme,
405                                         write_ops, 0ULL, write_byt, write_tme);
406
407                 CFRelease (child_dict);
408                 IOObjectRelease (disk_child);
409                 CFRelease (props_dict);
410                 IOObjectRelease (disk);
411         }
412         IOObjectRelease (disk_list);
413 /* #endif HAVE_IOKIT_IOKITLIB_H */
414
415 #elif KERNEL_LINUX
416         FILE *fh;
417         char buffer[1024];
418         char disk_name[128];
419         
420         char *fields[32];
421         int numfields;
422         int fieldshift = 0;
423
424         int major = 0;
425         int minor = 0;
426
427         unsigned int read_sectors;
428         unsigned int write_sectors;
429
430         unsigned long long read_count    = 0;
431         unsigned long long read_merged   = 0;
432         unsigned long long read_bytes    = 0;
433         unsigned long long read_time     = 0;
434         unsigned long long write_count   = 0;
435         unsigned long long write_merged  = 0;
436         unsigned long long write_bytes   = 0;
437         unsigned long long write_time    = 0;
438         int is_disk = 0;
439
440         diskstats_t *ds, *pre_ds;
441
442         if ((fh = fopen ("/proc/diskstats", "r")) == NULL)
443         {
444                 if ((fh = fopen ("/proc/partitions", "r")) == NULL)
445                         return;
446
447                 /* Kernel is 2.4.* */
448                 fieldshift = 1;
449         }
450
451         while (fgets (buffer, 1024, fh) != NULL)
452         {
453                 numfields = strsplit (buffer, fields, 32);
454
455                 if ((numfields != (14 + fieldshift)) && (numfields != 7))
456                         continue;
457
458                 major = atoll (fields[0]);
459                 minor = atoll (fields[1]);
460
461                 if (snprintf (disk_name, 128, "%i-%i", major, minor) < 1)
462                         continue;
463                 disk_name[127] = '\0';
464
465                 for (ds = disklist, pre_ds = disklist; ds != NULL; pre_ds = ds, ds = ds->next)
466                         if (strcmp (disk_name, ds->name) == 0)
467                                 break;
468
469                 if (ds == NULL)
470                 {
471                         if ((ds = (diskstats_t *) calloc (1, sizeof (diskstats_t))) == NULL)
472                                 continue;
473
474                         if ((ds->name = strdup (disk_name)) == NULL)
475                         {
476                                 free (ds);
477                                 continue;
478                         }
479
480                         if (pre_ds == NULL)
481                                 disklist = ds;
482                         else
483                                 pre_ds->next = ds;
484                 }
485
486                 is_disk = 0;
487                 if (numfields == 7)
488                 {
489                         /* Kernel 2.6, Partition */
490                         read_count    = atoll (fields[3]);
491                         read_sectors  = atoi  (fields[4]);
492                         write_count   = atoll (fields[5]);
493                         write_sectors = atoi  (fields[6]);
494                 }
495                 else if (numfields == (14 + fieldshift))
496                 {
497                         read_count  =  atoll (fields[3 + fieldshift]);
498                         write_count =  atoll (fields[7 + fieldshift]);
499
500                         read_sectors  = atoi (fields[5 + fieldshift]);
501                         write_sectors = atoi (fields[9 + fieldshift]);
502
503                         if ((fieldshift == 0) || (minor == 0))
504                         {
505                                 is_disk = 1;
506                                 read_merged  = atoll (fields[4 + fieldshift]);
507                                 read_time    = atoll (fields[6 + fieldshift]);
508                                 write_merged = atoll (fields[8 + fieldshift]);
509                                 write_time   = atoll (fields[10+ fieldshift]);
510                         }
511                 }
512                 else
513                 {
514                         continue;
515                 }
516
517
518                 if (read_sectors >= ds->read_sectors)
519                         ds->read_bytes += 512 * (read_sectors - ds->read_sectors);
520                 else
521                         ds->read_bytes += 512 * ((UINT_MAX - ds->read_sectors) + read_sectors);
522
523                 if (write_sectors >= ds->write_sectors)
524                         ds->write_bytes += 512 * (write_sectors - ds->write_sectors);
525                 else
526                         ds->write_bytes += 512 * ((UINT_MAX - ds->write_sectors) + write_sectors);
527
528                 ds->read_sectors  = read_sectors;
529                 ds->write_sectors = write_sectors;
530                 read_bytes  = ds->read_bytes;
531                 write_bytes = ds->write_bytes;
532
533                 /* Don't write to the RRDs if we've just started.. */
534                 ds->poll_count++;
535                 if (ds->poll_count <= 6)
536                         continue;
537
538                 if ((read_count == 0) && (write_count == 0))
539                         continue;
540
541                 if (is_disk)
542                         disk_submit (disk_name, read_count, read_merged, read_bytes, read_time,
543                                         write_count, write_merged, write_bytes, write_time);
544                 else
545                         partition_submit (disk_name, read_count, read_bytes, write_count, write_bytes);
546         }
547
548         fclose (fh);
549 /* #endif defined(KERNEL_LINUX) */
550
551 #elif HAVE_LIBKSTAT
552         static kstat_io_t kio;
553         int i;
554
555         if (kc == NULL)
556                 return;
557
558         for (i = 0; i < numdisk; i++)
559         {
560                 if (kstat_read (kc, ksp[i], &kio) == -1)
561                         continue;
562
563                 if (strncmp (ksp[i]->ks_class, "disk", 4) == 0)
564                         disk_submit (ksp[i]->ks_name,
565                                         kio.reads,  0LL, kio.nread,    kio.rtime,
566                                         kio.writes, 0LL, kio.nwritten, kio.wtime);
567                 else if (strncmp (ksp[i]->ks_class, "partition", 9) == 0)
568                         partition_submit (ksp[i]->ks_name,
569                                         kio.reads, kio.nread,
570                                         kio.writes,kio.nwritten);
571         }
572 #endif /* defined(HAVE_LIBKSTAT) */
573 } /* static void disk_read (void) */
574 #else
575 # define disk_read NULL
576 #endif /* DISK_HAVE_READ */
577
578 void module_register (void)
579 {
580         plugin_register ("partition", NULL, NULL, partition_write);
581         plugin_register (MODULE_NAME, disk_init, disk_read, disk_write);
582 }
583
584 #undef MODULE_NAME