1 /**
2 * collectd - src/disk.c
3 * Copyright (C) 2005-2012 Florian octo Forster
4 * Copyright (C) 2009 Manuel Sanmartin
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; only version 2 of the License is applicable.
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 collectd.org>
21 * Manuel Sanmartin
22 **/
24 #include "collectd.h"
25 #include "common.h"
26 #include "plugin.h"
27 #include "utils_ignorelist.h"
29 #if HAVE_MACH_MACH_TYPES_H
30 # include <mach/mach_types.h>
31 #endif
32 #if HAVE_MACH_MACH_INIT_H
33 # include <mach/mach_init.h>
34 #endif
35 #if HAVE_MACH_MACH_ERROR_H
36 # include <mach/mach_error.h>
37 #endif
38 #if HAVE_MACH_MACH_PORT_H
39 # include <mach/mach_port.h>
40 #endif
41 #if HAVE_COREFOUNDATION_COREFOUNDATION_H
42 # include <CoreFoundation/CoreFoundation.h>
43 #endif
44 #if HAVE_IOKIT_IOKITLIB_H
45 # include <IOKit/IOKitLib.h>
46 #endif
47 #if HAVE_IOKIT_IOTYPES_H
48 # include <IOKit/IOTypes.h>
49 #endif
50 #if HAVE_IOKIT_STORAGE_IOBLOCKSTORAGEDRIVER_H
51 # include <IOKit/storage/IOBlockStorageDriver.h>
52 #endif
53 #if HAVE_IOKIT_IOBSD_H
54 # include <IOKit/IOBSD.h>
55 #endif
56 #if KERNEL_FREEBSD
57 #include <devstat.h>
58 #include <libgeom.h>
59 #endif
61 #if HAVE_LIMITS_H
62 # include <limits.h>
63 #endif
64 #ifndef UINT_MAX
65 # define UINT_MAX 4294967295U
66 #endif
68 #if HAVE_STATGRAB_H
69 # include <statgrab.h>
70 #endif
72 #if HAVE_PERFSTAT
73 # ifndef _AIXVERSION_610
74 # include <sys/systemcfg.h>
75 # endif
76 # include <sys/protosw.h>
77 # include <libperfstat.h>
78 #endif
80 #if HAVE_IOKIT_IOKITLIB_H
81 static mach_port_t io_master_port = MACH_PORT_NULL;
82 /* This defaults to false for backwards compatibility. Please fix in the next
83 * major version. */
84 static _Bool use_bsd_name = 0;
85 /* #endif HAVE_IOKIT_IOKITLIB_H */
87 #elif KERNEL_LINUX
88 typedef struct diskstats
89 {
90 char *name;
92 /* This overflows in roughly 1361 years */
93 unsigned int poll_count;
95 derive_t read_sectors;
96 derive_t write_sectors;
98 derive_t read_bytes;
99 derive_t write_bytes;
101 derive_t read_ops;
102 derive_t write_ops;
103 derive_t read_time;
104 derive_t write_time;
106 derive_t avg_read_time;
107 derive_t avg_write_time;
109 _Bool has_merged;
110 _Bool has_in_progress;
111 _Bool has_io_time;
113 struct diskstats *next;
114 } diskstats_t;
116 static diskstats_t *disklist;
117 /* #endif KERNEL_LINUX */
118 #elif KERNEL_FREEBSD
119 static struct gmesh geom_tree;
120 /* #endif KERNEL_FREEBSD */
122 #elif HAVE_LIBKSTAT
123 #define MAX_NUMDISK 1024
124 extern kstat_ctl_t *kc;
125 static kstat_t *ksp[MAX_NUMDISK];
126 static int numdisk = 0;
127 /* #endif HAVE_LIBKSTAT */
129 #elif defined(HAVE_LIBSTATGRAB)
130 /* #endif HAVE_LIBKSTATGRAB */
132 #elif HAVE_PERFSTAT
133 static perfstat_disk_t * stat_disk;
134 static int numdisk;
135 static int pnumdisk;
136 /* #endif HAVE_PERFSTAT */
138 #else
139 # error "No applicable input method."
140 #endif
142 #if HAVE_LIBUDEV
143 #include <libudev.h>
145 static char *conf_udev_name_attr = NULL;
146 static struct udev *handle_udev;
147 #endif
149 static const char *config_keys[] =
150 {
151 "Disk",
152 "UseBSDName",
153 "IgnoreSelected",
154 "UdevNameAttr"
155 };
156 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
158 static ignorelist_t *ignorelist = NULL;
160 static int disk_config (const char *key, const char *value)
161 {
162 if (ignorelist == NULL)
163 ignorelist = ignorelist_create (/* invert = */ 1);
164 if (ignorelist == NULL)
165 return (1);
167 if (strcasecmp ("Disk", key) == 0)
168 {
169 ignorelist_add (ignorelist, value);
170 }
171 else if (strcasecmp ("IgnoreSelected", key) == 0)
172 {
173 int invert = 1;
174 if (IS_TRUE (value))
175 invert = 0;
176 ignorelist_set_invert (ignorelist, invert);
177 }
178 else if (strcasecmp ("UseBSDName", key) == 0)
179 {
180 #if HAVE_IOKIT_IOKITLIB_H
181 use_bsd_name = IS_TRUE (value) ? 1 : 0;
182 #else
183 WARNING ("disk plugin: The \"UseBSDName\" option is only supported "
184 "on Mach / Mac OS X and will be ignored.");
185 #endif
186 }
187 else if (strcasecmp ("UdevNameAttr", key) == 0)
188 {
189 #if HAVE_LIBUDEV
190 if (conf_udev_name_attr != NULL)
191 {
192 free (conf_udev_name_attr);
193 conf_udev_name_attr = NULL;
194 }
195 if ((conf_udev_name_attr = strdup (value)) == NULL)
196 return (1);
197 #else
198 WARNING ("disk plugin: The \"UdevNameAttr\" option is only supported "
199 "if collectd is built with libudev support");
200 #endif
201 }
202 else
203 {
204 return (-1);
205 }
207 return (0);
208 } /* int disk_config */
210 static int disk_init (void)
211 {
212 #if HAVE_IOKIT_IOKITLIB_H
213 kern_return_t status;
215 if (io_master_port != MACH_PORT_NULL)
216 {
217 mach_port_deallocate (mach_task_self (),
218 io_master_port);
219 io_master_port = MACH_PORT_NULL;
220 }
222 status = IOMasterPort (MACH_PORT_NULL, &io_master_port);
223 if (status != kIOReturnSuccess)
224 {
225 ERROR ("IOMasterPort failed: %s",
226 mach_error_string (status));
227 io_master_port = MACH_PORT_NULL;
228 return (-1);
229 }
230 /* #endif HAVE_IOKIT_IOKITLIB_H */
232 #elif KERNEL_LINUX
233 /* do nothing */
234 /* #endif KERNEL_LINUX */
236 #elif KERNEL_FREEBSD
237 int rv;
239 rv = geom_gettree(&geom_tree);
240 if (rv != 0) {
241 ERROR ("geom_gettree() failed, returned %d", rv);
242 return (-1);
243 }
244 rv = geom_stats_open();
245 if (rv != 0) {
246 ERROR ("geom_stats_open() failed, returned %d", rv);
247 return (-1);
248 }
249 /* #endif KERNEL_FREEBSD */
251 #elif HAVE_LIBKSTAT
252 kstat_t *ksp_chain;
254 numdisk = 0;
256 if (kc == NULL)
257 return (-1);
259 for (numdisk = 0, ksp_chain = kc->kc_chain;
260 (numdisk < MAX_NUMDISK) && (ksp_chain != NULL);
261 ksp_chain = ksp_chain->ks_next)
262 {
263 if (strncmp (ksp_chain->ks_class, "disk", 4)
264 && strncmp (ksp_chain->ks_class, "partition", 9))
265 continue;
266 if (ksp_chain->ks_type != KSTAT_TYPE_IO)
267 continue;
268 ksp[numdisk++] = ksp_chain;
269 }
270 #endif /* HAVE_LIBKSTAT */
272 return (0);
273 } /* int disk_init */
275 static void disk_submit (const char *plugin_instance,
276 const char *type,
277 derive_t read, derive_t write)
278 {
279 value_t values[2];
280 value_list_t vl = VALUE_LIST_INIT;
282 /* Both `ignorelist' and `plugin_instance' may be NULL. */
283 if (ignorelist_match (ignorelist, plugin_instance) != 0)
284 return;
286 values[0].derive = read;
287 values[1].derive = write;
289 vl.values = values;
290 vl.values_len = 2;
291 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
292 sstrncpy (vl.plugin, "disk", sizeof (vl.plugin));
293 sstrncpy (vl.plugin_instance, plugin_instance,
294 sizeof (vl.plugin_instance));
295 sstrncpy (vl.type, type, sizeof (vl.type));
297 plugin_dispatch_values (&vl);
298 } /* void disk_submit */
300 #if KERNEL_LINUX
301 static void submit_in_progress (char const *disk_name, gauge_t in_progress)
302 {
303 value_t v;
304 value_list_t vl = VALUE_LIST_INIT;
306 if (ignorelist_match (ignorelist, disk_name) != 0)
307 return;
309 v.gauge = in_progress;
311 vl.values = &v;
312 vl.values_len = 1;
313 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
314 sstrncpy (vl.plugin, "disk", sizeof (vl.plugin));
315 sstrncpy (vl.plugin_instance, disk_name, sizeof (vl.plugin_instance));
316 sstrncpy (vl.type, "pending_operations", sizeof (vl.type));
318 plugin_dispatch_values (&vl);
319 }
321 static void submit_io_time (char const *plugin_instance, derive_t io_time, derive_t weighted_time)
322 {
323 value_t values[2];
324 value_list_t vl = VALUE_LIST_INIT;
326 if (ignorelist_match (ignorelist, plugin_instance) != 0)
327 return;
329 values[0].derive = io_time;
330 values[1].derive = weighted_time;
332 vl.values = values;
333 vl.values_len = 2;
334 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
335 sstrncpy (vl.plugin, "disk", sizeof (vl.plugin));
336 sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
337 sstrncpy (vl.type, "disk_io_time", sizeof (vl.type));
339 plugin_dispatch_values (&vl);
340 }
343 static counter_t disk_calc_time_incr (counter_t delta_time, counter_t delta_ops)
344 {
345 double interval = CDTIME_T_TO_DOUBLE (plugin_get_interval ());
346 double avg_time = ((double) delta_time) / ((double) delta_ops);
347 double avg_time_incr = interval * avg_time;
349 return ((counter_t) (avg_time_incr + .5));
350 }
351 #endif
353 #if HAVE_LIBUDEV
354 /**
355 * Attempt to provide an rename disk instance from an assigned udev attribute.
356 *
357 * On success, it returns a strduped char* to the desired attribute value.
358 * Otherwise it returns NULL.
359 */
361 static char *disk_udev_attr_name (struct udev *udev, char *disk_name, const char *attr)
362 {
363 struct udev_device *dev;
364 const char *prop;
365 char *output = NULL;
367 dev = udev_device_new_from_subsystem_sysname (udev, "block", disk_name);
368 if (dev != NULL)
369 {
370 prop = udev_device_get_property_value (dev, attr);
371 if (prop) {
372 output = strdup (prop);
373 DEBUG ("disk plugin: renaming %s => %s", disk_name, output);
374 }
375 udev_device_unref (dev);
376 }
377 return output;
378 }
379 #endif
381 #if HAVE_IOKIT_IOKITLIB_H
382 static signed long long dict_get_value (CFDictionaryRef dict, const char *key)
383 {
384 signed long long val_int;
385 CFNumberRef val_obj;
386 CFStringRef key_obj;
388 /* `key_obj' needs to be released. */
389 key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key,
390 kCFStringEncodingASCII);
391 if (key_obj == NULL)
392 {
393 DEBUG ("CFStringCreateWithCString (%s) failed.", key);
394 return (-1LL);
395 }
397 /* get => we don't need to release (== free) the object */
398 val_obj = (CFNumberRef) CFDictionaryGetValue (dict, key_obj);
400 CFRelease (key_obj);
402 if (val_obj == NULL)
403 {
404 DEBUG ("CFDictionaryGetValue (%s) failed.", key);
405 return (-1LL);
406 }
408 if (!CFNumberGetValue (val_obj, kCFNumberSInt64Type, &val_int))
409 {
410 DEBUG ("CFNumberGetValue (%s) failed.", key);
411 return (-1LL);
412 }
414 return (val_int);
415 }
416 #endif /* HAVE_IOKIT_IOKITLIB_H */
418 static int disk_read (void)
419 {
420 #if HAVE_IOKIT_IOKITLIB_H
421 io_registry_entry_t disk;
422 io_registry_entry_t disk_child;
423 io_iterator_t disk_list;
424 CFMutableDictionaryRef props_dict, child_dict;
425 CFDictionaryRef stats_dict;
426 CFStringRef tmp_cf_string_ref;
427 kern_return_t status;
429 signed long long read_ops, read_byt, read_tme;
430 signed long long write_ops, write_byt, write_tme;
432 int disk_major, disk_minor;
433 char disk_name[DATA_MAX_NAME_LEN];
434 char child_disk_name_bsd[DATA_MAX_NAME_LEN], props_disk_name_bsd[DATA_MAX_NAME_LEN];
436 /* Get the list of all disk objects. */
437 if (IOServiceGetMatchingServices (io_master_port, IOServiceMatching (kIOBlockStorageDriverClass), &disk_list) != kIOReturnSuccess) {
438 ERROR ("disk plugin: IOServiceGetMatchingServices failed.");
439 return (-1);
440 }
442 while ((disk = IOIteratorNext (disk_list)) != 0) {
443 props_dict = NULL;
444 stats_dict = NULL;
445 child_dict = NULL;
447 /* get child of disk entry and corresponding property dictionary */
448 if ((status = IORegistryEntryGetChildEntry (disk, kIOServicePlane, &disk_child)) != kIOReturnSuccess) {
449 /* This fails for example for DVD/CD drives, which we want to ignore anyway */
450 DEBUG ("IORegistryEntryGetChildEntry (disk) failed: 0x%08x", status);
451 IOObjectRelease (disk);
452 continue;
453 }
454 if (IORegistryEntryCreateCFProperties (disk_child, (CFMutableDictionaryRef *) &child_dict, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess || child_dict == NULL) {
455 ERROR ("disk plugin: IORegistryEntryCreateCFProperties (disk_child) failed.");
456 IOObjectRelease (disk_child);
457 IOObjectRelease (disk);
458 continue;
459 }
461 /* extract name and major/minor numbers */
462 memset (child_disk_name_bsd, 0, sizeof (child_disk_name_bsd));
463 tmp_cf_string_ref = (CFStringRef) CFDictionaryGetValue (child_dict, CFSTR(kIOBSDNameKey));
464 if (tmp_cf_string_ref) {
465 assert (CFGetTypeID (tmp_cf_string_ref) == CFStringGetTypeID ());
466 CFStringGetCString (tmp_cf_string_ref, child_disk_name_bsd, sizeof (child_disk_name_bsd), kCFStringEncodingUTF8);
467 }
468 disk_major = (int) dict_get_value (child_dict, kIOBSDMajorKey);
469 disk_minor = (int) dict_get_value (child_dict, kIOBSDMinorKey);
470 DEBUG ("disk plugin: child_disk_name_bsd=\"%s\" major=%d minor=%d", child_disk_name_bsd, disk_major, disk_minor);
471 CFRelease (child_dict);
472 IOObjectRelease (disk_child);
474 /* get property dictionary of the disk entry itself */
475 if (IORegistryEntryCreateCFProperties (disk, (CFMutableDictionaryRef *) &props_dict, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess || props_dict == NULL) {
476 ERROR ("disk-plugin: IORegistryEntryCreateCFProperties failed.");
477 IOObjectRelease (disk);
478 continue;
479 }
481 /* extract name and stats dictionary */
482 memset (props_disk_name_bsd, 0, sizeof (props_disk_name_bsd));
483 tmp_cf_string_ref = (CFStringRef) CFDictionaryGetValue (props_dict, CFSTR(kIOBSDNameKey));
484 if (tmp_cf_string_ref) {
485 assert (CFGetTypeID (tmp_cf_string_ref) == CFStringGetTypeID ());
486 CFStringGetCString (tmp_cf_string_ref, props_disk_name_bsd, sizeof (props_disk_name_bsd), kCFStringEncodingUTF8);
487 }
488 stats_dict = (CFDictionaryRef) CFDictionaryGetValue (props_dict, CFSTR (kIOBlockStorageDriverStatisticsKey));
489 if (stats_dict == NULL) {
490 ERROR ("disk plugin: CFDictionaryGetValue (%s) failed.", kIOBlockStorageDriverStatisticsKey);
491 CFRelease (props_dict);
492 IOObjectRelease (disk);
493 continue;
494 }
495 DEBUG ("disk plugin: props_disk_name_bsd=\"%s\"", props_disk_name_bsd);
497 /* choose name */
498 if (use_bsd_name) {
499 if (child_disk_name_bsd[0] != 0)
500 sstrncpy (disk_name, child_disk_name_bsd, sizeof (disk_name));
501 else if (props_disk_name_bsd[0] != 0)
502 sstrncpy (disk_name, props_disk_name_bsd, sizeof (disk_name));
503 else {
504 ERROR ("disk plugin: can't find bsd disk name.");
505 ssnprintf (disk_name, sizeof (disk_name), "%i-%i", disk_major, disk_minor);
506 }
507 }
508 else
509 ssnprintf (disk_name, sizeof (disk_name), "%i-%i", disk_major, disk_minor);
511 /* extract the stats */
512 read_ops = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsReadsKey);
513 read_byt = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsBytesReadKey);
514 read_tme = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsTotalReadTimeKey);
515 write_ops = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsWritesKey);
516 write_byt = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsBytesWrittenKey);
517 write_tme = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsTotalWriteTimeKey);
518 CFRelease (props_dict);
519 IOObjectRelease (disk);
521 /* and submit */
522 DEBUG ("disk plugin: disk_name = \"%s\"", disk_name);
523 if ((read_byt != -1LL) || (write_byt != -1LL))
524 disk_submit (disk_name, "disk_octets", read_byt, write_byt);
525 if ((read_ops != -1LL) || (write_ops != -1LL))
526 disk_submit (disk_name, "disk_ops", read_ops, write_ops);
527 if ((read_tme != -1LL) || (write_tme != -1LL))
528 disk_submit (disk_name, "disk_time", read_tme / 1000, write_tme / 1000);
530 }
531 IOObjectRelease (disk_list);
532 /* #endif HAVE_IOKIT_IOKITLIB_H */
534 #elif KERNEL_FREEBSD
535 int retry, dirty;
537 void *snap = NULL;
538 struct devstat *snap_iter;
540 struct gident *geom_id;
542 const char *disk_name;
543 long double read_time, write_time;
545 for (retry = 0, dirty = 1; retry < 5 && dirty == 1; retry++) {
546 if (snap != NULL)
547 geom_stats_snapshot_free(snap);
549 /* Get a fresh copy of stats snapshot */
550 snap = geom_stats_snapshot_get();
551 if (snap == NULL) {
552 ERROR("disk plugin: geom_stats_snapshot_get() failed.");
553 return (-1);
554 }
556 /* Check if we have dirty read from this snapshot */
557 dirty = 0;
558 geom_stats_snapshot_reset(snap);
559 while ((snap_iter = geom_stats_snapshot_next(snap)) != NULL) {
560 if (snap_iter->id == NULL)
561 continue;
562 geom_id = geom_lookupid(&geom_tree, snap_iter->id);
564 /* New device? refresh GEOM tree */
565 if (geom_id == NULL) {
566 geom_deletetree(&geom_tree);
567 if (geom_gettree(&geom_tree) != 0) {
568 ERROR("disk plugin: geom_gettree() failed");
569 geom_stats_snapshot_free(snap);
570 return (-1);
571 }
572 geom_id = geom_lookupid(&geom_tree, snap_iter->id);
573 }
574 /*
575 * This should be rare: the device come right before we take the
576 * snapshot and went away right after it. We will handle this
577 * case later, so don't mark dirty but silently ignore it.
578 */
579 if (geom_id == NULL)
580 continue;
582 /* Only collect PROVIDER data */
583 if (geom_id->lg_what != ISPROVIDER)
584 continue;
586 /* Only collect data when rank is 1 (physical devices) */
587 if (((struct gprovider *)(geom_id->lg_ptr))->lg_geom->lg_rank != 1)
588 continue;
590 /* Check if this is a dirty read quit for another try */
591 if (snap_iter->sequence0 != snap_iter->sequence1) {
592 dirty = 1;
593 break;
594 }
595 }
596 }
598 /* Reset iterator */
599 geom_stats_snapshot_reset(snap);
600 for (;;) {
601 snap_iter = geom_stats_snapshot_next(snap);
602 if (snap_iter == NULL)
603 break;
605 if (snap_iter->id == NULL)
606 continue;
607 geom_id = geom_lookupid(&geom_tree, snap_iter->id);
608 if (geom_id == NULL)
609 continue;
610 if (geom_id->lg_what != ISPROVIDER)
611 continue;
612 if (((struct gprovider *)(geom_id->lg_ptr))->lg_geom->lg_rank != 1)
613 continue;
614 /* Skip dirty reads, if present */
615 if (dirty && (snap_iter->sequence0 != snap_iter->sequence1))
616 continue;
618 disk_name = ((struct gprovider *)geom_id->lg_ptr)->lg_name;
620 if ((snap_iter->bytes[DEVSTAT_READ] != 0) || (snap_iter->bytes[DEVSTAT_WRITE] != 0)) {
621 disk_submit(disk_name, "disk_octets",
622 (derive_t)snap_iter->bytes[DEVSTAT_READ],
623 (derive_t)snap_iter->bytes[DEVSTAT_WRITE]);
624 }
626 if ((snap_iter->operations[DEVSTAT_READ] != 0) || (snap_iter->operations[DEVSTAT_WRITE] != 0)) {
627 disk_submit(disk_name, "disk_ops",
628 (derive_t)snap_iter->operations[DEVSTAT_READ],
629 (derive_t)snap_iter->operations[DEVSTAT_WRITE]);
630 }
632 read_time = devstat_compute_etime(&snap_iter->duration[DEVSTAT_READ], NULL);
633 write_time = devstat_compute_etime(&snap_iter->duration[DEVSTAT_WRITE], NULL);
634 if ((read_time != 0) || (write_time != 0)) {
635 disk_submit (disk_name, "disk_time",
636 (derive_t)(read_time*1000), (derive_t)(write_time*1000));
637 }
638 }
639 geom_stats_snapshot_free(snap);
641 #elif KERNEL_LINUX
642 FILE *fh;
643 char buffer[1024];
645 char *fields[32];
646 int numfields;
647 int fieldshift = 0;
649 int minor = 0;
651 derive_t read_sectors = 0;
652 derive_t write_sectors = 0;
654 derive_t read_ops = 0;
655 derive_t read_merged = 0;
656 derive_t read_time = 0;
657 derive_t write_ops = 0;
658 derive_t write_merged = 0;
659 derive_t write_time = 0;
660 gauge_t in_progress = NAN;
661 derive_t io_time = 0;
662 derive_t weighted_time = 0;
663 int is_disk = 0;
665 diskstats_t *ds, *pre_ds;
667 if ((fh = fopen ("/proc/diskstats", "r")) == NULL)
668 {
669 fh = fopen ("/proc/partitions", "r");
670 if (fh == NULL)
671 {
672 ERROR ("disk plugin: fopen (/proc/{diskstats,partitions}) failed.");
673 return (-1);
674 }
676 /* Kernel is 2.4.* */
677 fieldshift = 1;
678 }
680 #if HAVE_LIBUDEV
681 handle_udev = udev_new();
682 #endif
684 while (fgets (buffer, sizeof (buffer), fh) != NULL)
685 {
686 char *disk_name;
687 char *output_name;
689 numfields = strsplit (buffer, fields, 32);
691 if ((numfields != (14 + fieldshift)) && (numfields != 7))
692 continue;
694 minor = atoll (fields[1]);
696 disk_name = fields[2 + fieldshift];
698 for (ds = disklist, pre_ds = disklist; ds != NULL; pre_ds = ds, ds = ds->next)
699 if (strcmp (disk_name, ds->name) == 0)
700 break;
702 if (ds == NULL)
703 {
704 if ((ds = (diskstats_t *) calloc (1, sizeof (diskstats_t))) == NULL)
705 continue;
707 if ((ds->name = strdup (disk_name)) == NULL)
708 {
709 free (ds);
710 continue;
711 }
713 if (pre_ds == NULL)
714 disklist = ds;
715 else
716 pre_ds->next = ds;
717 }
719 is_disk = 0;
720 if (numfields == 7)
721 {
722 /* Kernel 2.6, Partition */
723 read_ops = atoll (fields[3]);
724 read_sectors = atoll (fields[4]);
725 write_ops = atoll (fields[5]);
726 write_sectors = atoll (fields[6]);
727 }
728 else if (numfields == (14 + fieldshift))
729 {
730 read_ops = atoll (fields[3 + fieldshift]);
731 write_ops = atoll (fields[7 + fieldshift]);
733 read_sectors = atoll (fields[5 + fieldshift]);
734 write_sectors = atoll (fields[9 + fieldshift]);
736 if ((fieldshift == 0) || (minor == 0))
737 {
738 is_disk = 1;
739 read_merged = atoll (fields[4 + fieldshift]);
740 read_time = atoll (fields[6 + fieldshift]);
741 write_merged = atoll (fields[8 + fieldshift]);
742 write_time = atoll (fields[10+ fieldshift]);
744 in_progress = atof (fields[11 + fieldshift]);
746 io_time = atof (fields[12 + fieldshift]);
747 weighted_time = atof (fields[13 + fieldshift]);
748 }
749 }
750 else
751 {
752 DEBUG ("numfields = %i; => unknown file format.", numfields);
753 continue;
754 }
756 {
757 derive_t diff_read_sectors;
758 derive_t diff_write_sectors;
760 /* If the counter wraps around, it's only 32 bits.. */
761 if (read_sectors < ds->read_sectors)
762 diff_read_sectors = 1 + read_sectors
763 + (UINT_MAX - ds->read_sectors);
764 else
765 diff_read_sectors = read_sectors - ds->read_sectors;
766 if (write_sectors < ds->write_sectors)
767 diff_write_sectors = 1 + write_sectors
768 + (UINT_MAX - ds->write_sectors);
769 else
770 diff_write_sectors = write_sectors - ds->write_sectors;
772 ds->read_bytes += 512 * diff_read_sectors;
773 ds->write_bytes += 512 * diff_write_sectors;
774 ds->read_sectors = read_sectors;
775 ds->write_sectors = write_sectors;
776 }
778 /* Calculate the average time an io-op needs to complete */
779 if (is_disk)
780 {
781 derive_t diff_read_ops;
782 derive_t diff_write_ops;
783 derive_t diff_read_time;
784 derive_t diff_write_time;
786 if (read_ops < ds->read_ops)
787 diff_read_ops = 1 + read_ops
788 + (UINT_MAX - ds->read_ops);
789 else
790 diff_read_ops = read_ops - ds->read_ops;
791 DEBUG ("disk plugin: disk_name = %s; read_ops = %"PRIi64"; "
792 "ds->read_ops = %"PRIi64"; diff_read_ops = %"PRIi64";",
793 disk_name,
794 read_ops, ds->read_ops, diff_read_ops);
796 if (write_ops < ds->write_ops)
797 diff_write_ops = 1 + write_ops
798 + (UINT_MAX - ds->write_ops);
799 else
800 diff_write_ops = write_ops - ds->write_ops;
802 if (read_time < ds->read_time)
803 diff_read_time = 1 + read_time
804 + (UINT_MAX - ds->read_time);
805 else
806 diff_read_time = read_time - ds->read_time;
808 if (write_time < ds->write_time)
809 diff_write_time = 1 + write_time
810 + (UINT_MAX - ds->write_time);
811 else
812 diff_write_time = write_time - ds->write_time;
814 if (diff_read_ops != 0)
815 ds->avg_read_time += disk_calc_time_incr (
816 diff_read_time, diff_read_ops);
817 if (diff_write_ops != 0)
818 ds->avg_write_time += disk_calc_time_incr (
819 diff_write_time, diff_write_ops);
821 ds->read_ops = read_ops;
822 ds->read_time = read_time;
823 ds->write_ops = write_ops;
824 ds->write_time = write_time;
826 if (read_merged || write_merged)
827 ds->has_merged = 1;
829 if (in_progress)
830 ds->has_in_progress = 1;
832 if (io_time)
833 ds->has_io_time = 1;
835 } /* if (is_disk) */
837 /* Don't write to the RRDs if we've just started.. */
838 ds->poll_count++;
839 if (ds->poll_count <= 2)
840 {
841 DEBUG ("disk plugin: (ds->poll_count = %i) <= "
842 "(min_poll_count = 2); => Not writing.",
843 ds->poll_count);
844 continue;
845 }
847 if ((read_ops == 0) && (write_ops == 0))
848 {
849 DEBUG ("disk plugin: ((read_ops == 0) && "
850 "(write_ops == 0)); => Not writing.");
851 continue;
852 }
854 output_name = disk_name;
856 #if HAVE_LIBUDEV
857 char *alt_name = disk_udev_attr_name (handle_udev, disk_name, conf_udev_name_attr);
858 if (alt_name != NULL)
859 output_name = alt_name;
860 #endif
862 if ((ds->read_bytes != 0) || (ds->write_bytes != 0))
863 disk_submit (output_name, "disk_octets",
864 ds->read_bytes, ds->write_bytes);
866 if ((ds->read_ops != 0) || (ds->write_ops != 0))
867 disk_submit (output_name, "disk_ops",
868 read_ops, write_ops);
870 if ((ds->avg_read_time != 0) || (ds->avg_write_time != 0))
871 disk_submit (output_name, "disk_time",
872 ds->avg_read_time, ds->avg_write_time);
874 if (is_disk)
875 {
876 if (ds->has_merged)
877 disk_submit (output_name, "disk_merged",
878 read_merged, write_merged);
879 if (ds->has_in_progress)
880 submit_in_progress (output_name, in_progress);
881 if (ds->has_io_time)
882 submit_io_time (output_name, io_time, weighted_time);
883 } /* if (is_disk) */
885 #if HAVE_LIBUDEV
886 /* release udev-based alternate name, if allocated */
887 sfree (alt_name);
888 #endif
889 } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
891 #if HAVE_LIBUDEV
892 udev_unref(handle_udev);
893 #endif
895 fclose (fh);
896 /* #endif defined(KERNEL_LINUX) */
898 #elif HAVE_LIBKSTAT
899 # if HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_NWRITES && HAVE_KSTAT_IO_T_WTIME
900 # define KIO_ROCTETS reads
901 # define KIO_WOCTETS writes
902 # define KIO_ROPS nreads
903 # define KIO_WOPS nwrites
904 # define KIO_RTIME rtime
905 # define KIO_WTIME wtime
906 # elif HAVE_KSTAT_IO_T_NWRITTEN && HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_WTIME
907 # define KIO_ROCTETS nread
908 # define KIO_WOCTETS nwritten
909 # define KIO_ROPS reads
910 # define KIO_WOPS writes
911 # define KIO_RTIME rtime
912 # define KIO_WTIME wtime
913 # else
914 # error "kstat_io_t does not have the required members"
915 # endif
916 static kstat_io_t kio;
917 int i;
919 if (kc == NULL)
920 return (-1);
922 for (i = 0; i < numdisk; i++)
923 {
924 if (kstat_read (kc, ksp[i], &kio) == -1)
925 continue;
927 if (strncmp (ksp[i]->ks_class, "disk", 4) == 0)
928 {
929 disk_submit (ksp[i]->ks_name, "disk_octets",
930 kio.KIO_ROCTETS, kio.KIO_WOCTETS);
931 disk_submit (ksp[i]->ks_name, "disk_ops",
932 kio.KIO_ROPS, kio.KIO_WOPS);
933 /* FIXME: Convert this to microseconds if necessary */
934 disk_submit (ksp[i]->ks_name, "disk_time",
935 kio.KIO_RTIME, kio.KIO_WTIME);
936 }
937 else if (strncmp (ksp[i]->ks_class, "partition", 9) == 0)
938 {
939 disk_submit (ksp[i]->ks_name, "disk_octets",
940 kio.KIO_ROCTETS, kio.KIO_WOCTETS);
941 disk_submit (ksp[i]->ks_name, "disk_ops",
942 kio.KIO_ROPS, kio.KIO_WOPS);
943 }
944 }
945 /* #endif defined(HAVE_LIBKSTAT) */
947 #elif defined(HAVE_LIBSTATGRAB)
948 sg_disk_io_stats *ds;
949 # if HAVE_LIBSTATGRAB_0_90
950 size_t disks;
951 # else
952 int disks;
953 #endif
954 int counter;
955 char name[DATA_MAX_NAME_LEN];
957 if ((ds = sg_get_disk_io_stats(&disks)) == NULL)
958 return (0);
960 for (counter=0; counter < disks; counter++) {
961 strncpy(name, ds->disk_name, sizeof(name));
962 name[sizeof(name)-1] = '\0'; /* strncpy doesn't terminate longer strings */
963 disk_submit (name, "disk_octets", ds->read_bytes, ds->write_bytes);
964 ds++;
965 }
966 /* #endif defined(HAVE_LIBSTATGRAB) */
968 #elif defined(HAVE_PERFSTAT)
969 derive_t read_sectors;
970 derive_t write_sectors;
971 derive_t read_time;
972 derive_t write_time;
973 derive_t read_ops;
974 derive_t write_ops;
975 perfstat_id_t firstpath;
976 int rnumdisk;
977 int i;
979 if ((numdisk = perfstat_disk(NULL, NULL, sizeof(perfstat_disk_t), 0)) < 0)
980 {
981 char errbuf[1024];
982 WARNING ("disk plugin: perfstat_disk: %s",
983 sstrerror (errno, errbuf, sizeof (errbuf)));
984 return (-1);
985 }
987 if (numdisk != pnumdisk || stat_disk==NULL) {
988 if (stat_disk!=NULL)
989 free(stat_disk);
990 stat_disk = (perfstat_disk_t *)calloc(numdisk, sizeof(perfstat_disk_t));
991 }
992 pnumdisk = numdisk;
994 firstpath.name[0]='\0';
995 if ((rnumdisk = perfstat_disk(&firstpath, stat_disk, sizeof(perfstat_disk_t), numdisk)) < 0)
996 {
997 char errbuf[1024];
998 WARNING ("disk plugin: perfstat_disk : %s",
999 sstrerror (errno, errbuf, sizeof (errbuf)));
1000 return (-1);
1001 }
1003 for (i = 0; i < rnumdisk; i++)
1004 {
1005 read_sectors = stat_disk[i].rblks*stat_disk[i].bsize;
1006 write_sectors = stat_disk[i].wblks*stat_disk[i].bsize;
1007 disk_submit (stat_disk[i].name, "disk_octets", read_sectors, write_sectors);
1009 read_ops = stat_disk[i].xrate;
1010 write_ops = stat_disk[i].xfers - stat_disk[i].xrate;
1011 disk_submit (stat_disk[i].name, "disk_ops", read_ops, write_ops);
1013 read_time = stat_disk[i].rserv;
1014 read_time *= ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac)) / 1000000.0;
1015 write_time = stat_disk[i].wserv;
1016 write_time *= ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac)) / 1000000.0;
1017 disk_submit (stat_disk[i].name, "disk_time", read_time, write_time);
1018 }
1019 #endif /* defined(HAVE_PERFSTAT) */
1021 return (0);
1022 } /* int disk_read */
1024 void module_register (void)
1025 {
1026 plugin_register_config ("disk", disk_config,
1027 config_keys, config_keys_num);
1028 plugin_register_init ("disk", disk_init);
1029 plugin_register_read ("disk", disk_read);
1030 } /* void module_register */