Merge branch 'ff/netlib'
authorFlorian Forster <octo@collectd.org>
Sat, 17 Nov 2012 07:25:01 +0000 (08:25 +0100)
committerFlorian Forster <octo@collectd.org>
Sat, 17 Nov 2012 07:25:01 +0000 (08:25 +0100)
Conflicts:
src/collectdctl.c
src/libcollectdclient/client.c
src/libcollectdclient/collectd/client.h

178 files changed:
.gitignore
AUTHORS
ChangeLog
Makefile.am
README
bindings/Makefile.am
bindings/java/org/collectd/api/CollectdFlushInterface.java
bindings/java/org/collectd/api/ValueList.java
bindings/java/org/collectd/java/GenericJMXConfValue.java
bindings/perl/lib/Collectd.pm
bindings/perl/lib/Collectd/Plugins/OpenVZ.pm
configure.in
contrib/README
contrib/aix/collectd.spec [new file with mode: 0644]
contrib/aix/init.d-collectd [new file with mode: 0755]
contrib/collectd.service [new file with mode: 0644]
contrib/collectd_network.py
contrib/collectd_unixsock.py
contrib/collection3/bin/graph.cgi
contrib/collection3/bin/index.cgi
contrib/collection3/lib/Collectd/Graph/Common.pm
contrib/collection3/lib/Collectd/Graph/Type/Df.pm
contrib/collection3/lib/Collectd/Graph/TypeLoader.pm
contrib/exec-ksm.sh [new file with mode: 0755]
contrib/exec-nagios.conf
contrib/exec-nagios.px
contrib/migrate-4-5.px [new file with mode: 0755]
contrib/php-collection/definitions.php
contrib/redhat/collectd.spec
contrib/redhat/init.d-collectd
src/Makefile.am
src/aggregation.c [new file with mode: 0644]
src/amqp.c
src/apache.c
src/apcups.c
src/ascent.c
src/bind.c
src/collectd-nagios.c
src/collectd-perl.pod
src/collectd-python.pod
src/collectd-threshold.pod [new file with mode: 0644]
src/collectd.c
src/collectd.conf.in
src/collectd.conf.pod
src/collectd.h
src/collectdctl.c
src/common.c
src/common.h
src/configfile.c
src/configfile.h
src/conntrack.c
src/contextswitch.c
src/cpu.c
src/cpython.h
src/csv.c
src/curl.c
src/curl_json.c
src/curl_xml.c
src/dbi.c
src/df.c
src/disk.c
src/dns.c
src/email.c
src/ethstat.c [new file with mode: 0644]
src/exec.c
src/filter_chain.c
src/fscache.c
src/gmond.c
src/interface.c
src/ipmi.c
src/iptables.c
src/ipvs.c
src/irq.c
src/java.c
src/libcollectdclient/client.c
src/libcollectdclient/collectd/client.h
src/liboconfig/parser.y
src/libvirt.c
src/logfile.c
src/madwifi.c
src/match_empty_counter.c
src/match_timediff.c
src/md.c [new file with mode: 0644]
src/memcachec.c
src/memcached.c
src/memory.c
src/meta_data.c
src/meta_data.h
src/modbus.c
src/mysql.c
src/netapp.c
src/netlink.c
src/network.c
src/network.h
src/nfs.c
src/nginx.c
src/notify_desktop.c
src/notify_email.c
src/ntpd.c
src/numa.c [new file with mode: 0644]
src/onewire.c
src/openvpn.c
src/oracle.c
src/owniptc/Makefile.am [deleted file]
src/owniptc/README.collectd [deleted file]
src/owniptc/ipt_kernel_headers.h [deleted file]
src/owniptc/libip4tc.c [deleted file]
src/owniptc/libip6tc.c [deleted file]
src/owniptc/libip6tc.h [deleted file]
src/owniptc/libiptc.c [deleted file]
src/owniptc/libiptc.h [deleted file]
src/owniptc/libxtc.h [deleted file]
src/owniptc/linux_list.h [deleted file]
src/owniptc/xtables.h [deleted file]
src/perl.c
src/pinba.c
src/ping.c
src/plugin.c
src/plugin.h
src/postgresql.c
src/powerdns.c
src/processes.c
src/protocols.c
src/python.c
src/pyvalues.c
src/redis.c
src/routeros.c
src/rrdcached.c
src/rrdtool.c
src/sensors.c
src/serial.c
src/snmp.c
src/swap.c
src/syslog.c
src/tape.c
src/target_notification.c
src/target_scale.c
src/target_v5upgrade.c
src/tcpconns.c
src/teamspeak2.c
src/thermal.c
src/threshold.c [new file with mode: 0644]
src/types.db
src/types_list.c
src/unixsock.c
src/uptime.c
src/utils_avltree.c
src/utils_avltree.h
src/utils_cache.c
src/utils_cache.h
src/utils_cmd_flush.c
src/utils_cmd_listval.c
src/utils_cmd_putval.c
src/utils_complain.c
src/utils_db_query.c
src/utils_db_query.h
src/utils_dns.c
src/utils_fbhash.c
src/utils_format_graphite.c [new file with mode: 0644]
src/utils_format_graphite.h [new file with mode: 0644]
src/utils_format_json.c
src/utils_rrdcreate.c
src/utils_rrdcreate.h
src/utils_threshold.c [deleted file]
src/utils_threshold.h [deleted file]
src/utils_time.c [new file with mode: 0644]
src/utils_time.h [new file with mode: 0644]
src/utils_vl_lookup.c [new file with mode: 0644]
src/utils_vl_lookup.h [new file with mode: 0644]
src/utils_vl_lookup_test.c [new file with mode: 0644]
src/varnish.c
src/vmem.c
src/vserver.c
src/write_graphite.c [new file with mode: 0644]
src/write_http.c
src/write_mongodb.c [new file with mode: 0644]
src/zfs_arc.c
version-gen.sh

index cbdd62f..75cb307 100644 (file)
@@ -33,6 +33,7 @@ src/stamp-h1
 .libs/
 src/collectd
 src/collectd-nagios
+src/collectdctl
 src/collectdmon
 src/*.1
 src/*.5
diff --git a/AUTHORS b/AUTHORS
index c57f90b..78dbad1 100644 (file)
--- a/AUTHORS
+++ b/AUTHORS
@@ -15,6 +15,9 @@ Sebastian "tokkee" Harl <sh at tokkee.org>
 Contributors (sorted alphabetically)
 ====================================
 
+Akkarit Sangpetch <asangpet at andrew.cmu.edu>
+ - write_mongodb plugin.
+
 Alessandro Iurlano <alessandro.iurlano at gmail.com>
  - Initial filecount plugin.
 
@@ -44,10 +47,16 @@ Bruno Prémont <bonbons at linux-vserver.org>
    especially a nasty bug in the network plugin.
  - Wireshark dissector.
 
+Chris Lundquist <clundquist at bluebox.net>
+ - Improvements to the write_mongodb plugin.
+
 Christophe Kalt <collectd at klb.taranis.org>
  - The version 3 `log' mode.
  - Many Solaris related hints and fixes.
 
+Cyril Feraudet <cyril at feraudet.com>
+ - ethstat plugin.
+
 Dan Berrange <berrange at redhat.com>
  - uuid plugin.
 
@@ -67,6 +76,9 @@ Edward “Koko” Konetzko <konetzed at quixoticagony.com>
 Fabian Linzberger <e at lefant.net>
  - Percentage aggregation for `collectd-nagios'.
 
+Fabien Wernli <cpan at faxm0dem.org>
+ - Solaris improvements in the memory and interfaces plugin.
+
 Flavio Stanchina <flavio at stanchina.net>
  - mbmon plugin.
 
@@ -106,6 +118,9 @@ Marco Chiappero <marco at absence.it>
  - ip6tables support in the iptables plugin.
  - openvpn plugin (support for more status file formats)
 
+Michael Hanselmann <public at hansmi.ch>
+ - md plugin.
+
 Michael Stapelberg <michael+git at stapelberg.de>
  - OpenBSD port of the tcpconns plugin.
 
@@ -166,6 +181,9 @@ Rodolphe Quiédeville <rquiedeville at bearstech.com>
 Scott Garrett <sgarrett at technomancer.com>
  - tape plugin.
 
+Scott Sanders <scott at jssjr.com>
+ - Write-Graphite plugin.
+
 Sebastien Pahl <sebastien.pahl at dotcloud.com>
  - AMQP plugin.
 
@@ -182,6 +200,9 @@ Sven Trenkel <collectd at semidefinite.de>
  - netapp plugin.
  - python plugin.
 
+Thomas Meson <zllak at hycik.org>
+ - Graphite support for the AMQP plugin.
+
 Tomasz Pala <gotar at pld-linux.org>
  - conntrack plugin.
 
index c50ae2a..ef2023a 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,526 @@
+2012-11-11, Version 5.1.1
+       * collectd: Create new directories with mode 0777 and let umask remove
+         unwanted permission bits.
+       * collectd: Build issues have been fixed.
+       * collectd: An incorrect assertion has been fixed in some common code
+         for Solaris. This should resolve pseudo-random assertion failures
+         under Solaris. Thanks to Jeff Blane for his help debugging this.
+       * collectd: A couple of memory leaks through PThread thread attributes
+         have been fixed. Thanks to Gerrie Roos for fixing these.
+       * collectdctl: Fix PUTVAL for data sets with multiple data sources.
+         Thanks to Cyril Feraudet for reporting this problem.
+       * contrib/migrate-4-5.px: Handle to "df" to "df_complex" conversion
+         correctly.
+       * apcups plugin: Improve the reconnect behavior.
+       * curl_xml plugin: The "Host" setting was silently ignored. Thanks to
+         Fabien Wernli for fixing this.
+       * df plugin: Ignore "rootfs" devices under Linux to avoid having them
+         reported twice. Thanks to Brune Prémont for fixing this.
+       * disk plugin: Fix incorrect computation of read and write latency (the
+         "disk_time" type). Previously, the numbers reported where too small
+         by a factor of "interval", e.g. when the interval is set to 10
+         seconds, the values were too low by a factor of 10. Thanks to Manuel
+         Sanmartin for reporting this problem.
+       * dns plugin: A build issue under Solaris has been fixed. A erroneous
+         define that could lead to the reporting of bad data has been fixed by
+         Daniel Sutto.
+       * ethstat plugin: An off-by-one error and potential use of
+         uninitialized memory has been fixed. Thanks to Mark Voelker for
+         reporting these problems.
+       * memcachec plugin: A bug in the configuration handling has been fixed.
+         Thanks to Pascal Hofmann for fixing this issue.
+       * mysql plugin: Fix a bug when registering multiple databases. Thanks
+         to Sebastian Harl for fixing this.
+       * netapp plugin: Correctly close the connection on communication
+         errors.
+       * netlink plugin: The function used to query statistics has been
+         changed to be more in line with iproute2's behavior. Thanks to
+         "KIvosak" for the patch.
+       * network plugin: Initialization of libgcrypt has been fixed. Thanks to
+         Chris Lundquist for his patch.
+       * oracle plugin: Error messages have been improved.
+       * ping plugin: Don't enter the exponential back-off mode when
+         ping_send() fails. This should make recovery after a network failure
+         much faster.
+       * python plugin: Memory leaks have been fixed. Thanks to Tommie Gannert
+         and Sven Trenkel for fixing this.
+       * redis plugin: Fix a compilation problem on FreeBSD. Thanks to
+         "biancalana" for the fix.
+       * rrdtool plugin: Fix an out-of-bounds array access when printing a
+         warning message. Thanks to Will Hawkins for fixing this bug.
+       * snmp plugin: Support for the SNMP_ENDOFMIBVIEW return value has been
+         added. Support for more complex / unusual MIBs / subtrees has been
+         added. Thanks to Mark Juric to test the changes and point out these
+         problems.
+       * varnish plugin: Support for multiple instances of Varnish 3 has been
+         fixed. Thanks to Jonathan Huot for the patch.
+       * write_mongodb plugin: Add compatibility with libmongo 0.6.0 and
+         later. Thanks to Chris Lundquist for this patch.
+
+2012-04-01, Version 5.1.0
+       * Build system, iptables plugin: The shipped version of libiptc has
+         been removed.
+       * collectd-nagios: A list of value lists can now be queried using
+         "-n LIST". Thanks to Sebastian Harl for his patches.
+       * bind plugin: The "ParseTime" option has been added. It allows to use
+         the system time rather than the time reported by BIND.
+       * curl, memcachec, tail plugins: The "ExcludeRegexp" option has been
+         added. Thanks to Peter Warasin for his initial patch.
+       * ethstat plugin: The new "ethstat" plugin reads performance statistics
+         directly from ethernet cards. Thanks to Cyril Feraudet for his patch.
+       * GenericJMX plugin: Support for querying MBean "Operations" (in
+         addition to "Attributes") has been added. Thanks to Pierre-Yves
+         Ritschard for his patch.
+       * irq plugin: The selection / ignore code now uses the default
+         ignorelist infrastructure, providing the standard feature set, e.g.
+         regex matching.
+       * md plugin: The new "md" plugin reports the number of disks in various
+         states in Linux software RAID devices. Thanks to Michael Hanselmann
+         for his patch.
+       * modbus plugin: Support for signed integer register types has been
+         added.
+       * nfs plugin: Support for Solaris has been added. Thanks to Cosmin
+         Ioiart for his patch.
+       * numa plugin: The new "numa" plugin reports statistics of the
+         Non-Uniform Memory Access (NUMA) subsystem of Linux.
+       * processes plugin: Various fixes for the FreeBSD implementation.
+         Thanks to Phil Kulin for his patch.
+       * rrdcached plugin: Passing flushes to the caching daemon has been
+         added.
+       * sensors plugin: The initialization code has been improved. Thanks to
+         Henrique de Moraes Holschuh for his patch.
+       * swap plugin: The "ReportByDevice" option has been added.
+       * syslog plugin: Support for writing notifications has been added.
+         Thanks to Fabien Wernli for his patch.
+       * tcpconns plugin: Support for AIX has been added. Thanks to Manuel
+         Luis Sanmartín Rozada for his patch.
+       * threshold plugin: The "PersistOK" option has been added. Thanks to
+         Aaron Brady for his patch.
+       * varnish plugin: Support for Varnish 3.0 has been added. Thanks to
+         Jérôme Renard for his patches.
+       * write_mongodb plugin: The new "write_mongodb" plugin writes value
+         lists to MongoDB, a shema-less database. Thanks to Akkarit Sangpetch
+         and Chris Lundquist for their work.
+       * write_graphite plugin: The new "write_graphite" plugin writes value
+         lists to Carbon, the storage layer of the Graphite time-series
+         database. Thanks to Scott Sanders and Pierre-Yves Ritschard for their
+         work.
+       * zfs_arc plugin: Several new statistics have been added. Thanks to
+         Aurelien Rougemont for his patches.
+       * scale target: Support for scaling specific data sources only has been
+         added. Thanks to Gerrie Roos for his patch.
+
+2012-11-11, Version 5.0.5
+       * collectd: Create new directories with mode 0777 and let umask remove
+         unwanted permission bits.
+       * collectd: Build issues have been fixed.
+       * collectd: An incorrect assertion has been fixed in some common code
+         for Solaris. This should resolve pseudo-random assertion failures
+         under Solaris. Thanks to Jeff Blane for his help debugging this.
+       * collectd: A couple of memory leaks through PThread thread attributes
+         have been fixed. Thanks to Gerrie Roos for fixing these.
+       * collectdctl: Fix PUTVAL for data sets with multiple data sources.
+         Thanks to Cyril Feraudet for reporting this problem.
+       * contrib/migrate-4-5.px: Handle to "df" to "df_complex" conversion
+         correctly.
+       * apcups plugin: Improve the reconnect behavior.
+       * curl_xml plugin: The "Host" setting was silently ignored. Thanks to
+         Fabien Wernli for fixing this.
+       * df plugin: Ignore "rootfs" devices under Linux to avoid having them
+         reported twice. Thanks to Brune Prémont for fixing this.
+       * disk plugin: Fix incorrect computation of read and write latency (the
+         "disk_time" type). Previously, the numbers reported where too small
+         by a factor of "interval", e.g. when the interval is set to 10
+         seconds, the values were too low by a factor of 10. Thanks to Manuel
+         Sanmartin for reporting this problem.
+       * dns plugin: A build issue under Solaris has been fixed. A erroneous
+         define that could lead to the reporting of bad data has been fixed by
+         Daniel Sutto.
+       * memcachec plugin: A bug in the configuration handling has been fixed.
+         Thanks to Pascal Hofmann for fixing this issue.
+       * mysql plugin: Fix a bug when registering multiple databases. Thanks
+         to Sebastian Harl for fixing this.
+       * netapp plugin: Correctly close the connection on communication
+         errors.
+       * netlink plugin: The function used to query statistics has been
+         changed to be more in line with iproute2's behavior. Thanks to
+         "KIvosak" for the patch.
+       * network plugin: Initialization of libgcrypt has been fixed. Thanks to
+         Chris Lundquist for his patch.
+       * oracle plugin: Error messages have been improved.
+       * ping plugin: Don't enter the exponential back-off mode when
+         ping_send() fails. This should make recovery after a network failure
+         much faster.
+       * python plugin: Memory leaks have been fixed. Thanks to Tommie Gannert
+         and Sven Trenkel for fixing this.
+       * redis plugin: Fix a compilation problem on FreeBSD. Thanks to
+         "biancalana" for the fix.
+       * rrdtool plugin: Fix an out-of-bounds array access when printing a
+         warning message. Thanks to Will Hawkins for fixing this bug.
+       * snmp plugin: Support for the SNMP_ENDOFMIBVIEW return value has been
+         added. Support for more complex / unusual MIBs / subtrees has been
+         added. Thanks to Mark Juric to test the changes and point out these
+         problems.
+
+2012-04-01, Version 5.0.4
+       * Build system: Fix the use of a libltdl macro. Thanks to Clemens Lang
+         for fixing this. Adresses some issues with building the iptables
+         plugin under Gentoo.
+       * libcollectdclient: A memory leak in the lcc_getval() function has
+         been fixed. Thanks to Jason Schmidlapp for finding and fixing this
+         issue.
+       * bind plugin: The use of 'QType" types has been fixed.
+       * df plugin: Fixed compiler issue under Mac OS X 10.7.
+       * conntrack plugin: Support zero as legitimate value. Thanks to Louis
+         Opter for his patch.
+       * memcached plugin: Increased the size of a static buffer, which was
+         truncating status messages form memcached. Thanks to Timon for the
+         patch.
+       * network plugin: Forwarding of notifications has been disabled. This
+         was a contition not checked for before, which may retult in an
+         endless loop.
+       * processes plugin: Support for process names with spaces has been
+         added to the Linux implementation. Thanks to Darrell Bishop for his
+         patch.
+       * perl plugin: A race condition in several callbacks, including log and
+         write callbacks, has been fixed. Thanks to "Rrpv" for reporting this
+         bug.
+       * snmp plugin: A bug when casting unsigned integers to gauge values has
+         been fixed: Unsigned integers would be cast to a signed integer and
+         then to a gauge, possibly resulting in a negative value.
+       * tcpconns plugin: Compilation with newer versions of the FreeBSD
+         runtime has been fixed.
+
+2012-02-19, Version 5.0.3
+       * Build system: Fix problems when building the ipvs and iptables
+         plugins. Thanks to Sebastian Harl for his patch. A bashism in the
+         version-gen.sh script has been fixed. Thanks to Jo-Philipp Wich for
+         his patch.
+       * csv and rrdtool plugins: Print a more helpful error message when the
+         DataDir is a symlink pointing to a non-existing location. Thanks to
+         Jonathan Nieder for his patch.
+       * exec plugin: Fix a problem when using select(2) to read from file
+         handles. Thanks to Gerrie Roos for his patch.
+       * network plugin: An incorrect error message in the handling of the
+         "Interface" configuration option has been fixed. Thanks to Gerrie
+         Roos for his patch.
+       * oracle plugin: A potential endless loop in the error handling has
+         been fixed.
+       * python plugin: A crash bug in the configuration handling has been
+         fixed. Thanks to Sven Trenkel for his patch.
+       * interfaces plugin: The change which was supposed to ignore "bogus"
+         interfaces has been reverted, since it ignored legit interfaces, such
+         as bonding pseudo-devices as well.
+
+2012-01-21, Version 5.0.2
+       * curl_xml plugin: Fix handling of file:// and other URLs (which don't
+         follow HTTP status codes). Thanks to Fabien Wernli for his patch!
+       * df plugin: Fix handling of negative "available" counts. This can
+         occur with some file systems, for example UFS. Thanks to Toni Ylenius
+         for his patch.
+       * interface plugin: "mac" interfaces are now ignored on Solaris. These
+         pseudo-interfaces occur multiple times, causing warnings. Also switch
+         to 64-bit counters on Solaris, improving overflow behavior for
+         high-speed interfaces. Thanks to Eddy Geez and Fabien Wernli for
+         their patches.
+       * memory plugin: Account kernel and unused memory under Solaris. Thanks
+         to Fabien Wernli for his patch.
+       * network plugin: A bug in the interaction between the Network plugin
+         and filter chains has been fixed: When a filter modified a field such
+         as the hostname, subsequent values in the same network packets could
+         have ended up using the modified name rather than the original name.
+         Thanks to Sebastian Harl for identifying the problem.
+       * oracle plugin: A memory leak has been fixed in the parameter handling.
+       * python plugin: A memory leak has been fixed. Thanks to Sven Trenkel
+         for fixing this bug!
+
+2011-10-07, Version 5.0.1
+       * collectd: A mutex leak has been fixed in the meta data code. Thanks
+         to Rafal Lesniak for his patch.
+       * collectd: Compatibility fixes for GCC 4.6 have been applied. Thanks
+         to Peter Green for his patch.
+       * csv plugin: The line buffer size has been increased. Thanks to Colin
+         McCabe for the patch.
+       * curl_json plugin: Don't use the "parent" node to build the type
+         instance, if it is empty. Compatibility with libyajl 2 has been
+         added. Thanks to "spupykin" of the Arch Linux project for the initial
+         code. Formatting of time has been fixed in the JSON module.
+       * exec plugin: Fix the timestamp value passed to notification scripts.
+         Thanks to Alexander Kovalenko for fixing this.
+       * iptables plugin: Fix linking with some versions of libiptc.
+       * irq plugin: Fix support for interrupts under Linux. The old code
+         assumed that interrupts have a numeric value -- this is no longer
+         true for Linux. Thanks to Bostjan Skufca for implementing this.
+       * notify_desktop plugin: Compatibility with libnotify 0.7 has been
+         added. Thanks to Samuli Suominen for his patch.
+       * processes plugin: Fix handling of regular expressions containing
+         spaces. Thanks for Sebastian Harl for fixing this.
+       * rrdtool, rrdcached plugins: Improve precision of the XFF parameter.
+         Previously, values like 0.999 would have been rounded to 1.0. Thanks
+         to Francois-Xavier Bourlet for fixing this.
+       * varnish plugin: Fix data type handling of some metrics. Some values
+         were submitted as gauge even though they were derives.
+       * Various plugin: Set a multi-threading flag in libcurl. Thanks to Mike
+         Flisher for the fix.
+
+2011-03-28, Version 5.0.0
+       * collectd: The "FQDNLookup" option is now enabled by default.
+       * collectd: The internal representation of time has been changed to
+         allow a higher accuracy than one second.
+       * collectdcmd: This new command line utility can send various commands
+         to collectd using the UnixSock plugin. Thanks to Håkon Dugstad
+         Johnsen and Sebastian Harl for their code.
+       * collectd-nagios: The "-m" option has been implemented (treat NaNs as
+         critical).
+       * collectd-tg: Traffic generator creating bogus network traffic
+         compatible to the Network plugin. This utility can be used to
+         stress-test new write plugins and collectd in general.
+       * libcollectdclient: Creating and sending network packets has been
+         added to the collectd client library.
+       * All data sets: The data source name of all data sets with exactly
+         one data source has been changed to "value".
+       * All plugins: All "counter" data sources have been converted to
+         "derive" data sources. All plugins now use "derive" by default, but
+         plugins such as the network plugin can still handle "counter", of
+         course. The minimum value of all derive data sources is zero, the
+         maximum value is unspecified.
+       * amqp plugin: The new AMQP plugin can send data to and receive data
+         from an AMQP broker. Thanks to Sebastien Pahl for his code.
+       * apache plugin: Backwards compatibility code has been removed.
+         Support for the IBM HTTP Server has been added. Thanks to Manuel
+         Luis Sanmartín Rozada for his patch.
+       * contextswitch plugin: Support for sysctlbyname(3) has been added.
+         Thanks to Kimo Rosenbaum for his patch.
+       * df plugin: The default behavior has been changed to be equivalent to
+         the "ReportReserved" behavior of v4.
+       * dns plugin: Improved RFC 1035 name parsing has been imported from
+         "dnstop".
+       * exec plugin: Backwards compatibility code has been removed.
+       * GenericJMX plugin: The "InstancePrefix" option has been added to
+         "Connection" blocks.
+       * hddtemp plugin: The "TranslateDevicename" config option has been
+         removed.
+       * interface plugin: Use the "plugin instance" to store the interface
+         value.
+       * libvirt plugin: The "InterfaceFormat" option has been added. Thanks
+         to Ruben Kerkhof for his patch.
+       * lpar plugin: New plugins for "logical partitions", a virtualization
+         technique of POWER CPUs. Thanks to Aurélien Reynaud for his code and
+         patience.
+       * modbus plugin: Support for libmodbus 2.9.2 has been added and the
+         license has been changed to LGPLv2.1.
+       * mysql plugin: Backwards compatibility code has been removed. The
+         data sets used have been improved.
+       * network plugin: The default buffer size has been increased to
+         1452 bytes.
+       * perl plugin: Backwards compatibility code has been removed.
+       * postgresql plugin: Backwards compatibility code has been removed.
+       * redis plugin: Plugin for collecting statistics from Redis, a key-
+         value store, has been added. Thanks to Andres J. Diaz for his code.
+       * swap plugin: Implement collection of physical and virtual memory
+         statistics under Solaris. The new default is collecting physical
+         memory. Thanks to Aurélien Reynaud for his patches.
+       * threshold plugin: The threshold configuration has been moved into
+         this separate plugin.
+       * unixsock plugin: The "DeleteSocket" option has been added.
+       * varnish plugin: The new Varnish plugin reads statistics from
+         Varnish, a web accelerator. Thanks to Jérôme Renard and Marc
+         Fournier for their contributions.
+       * write_redis: New plugin for writing data to Redis, a key-value
+         store.
+       * zfs_arc plugin: The data sets have been replaced by more elegant
+         alternatives.
+       * v5upgrade target: Target for converting v4 data sets to the v5
+         schema.
+
+2012-11-11, Version 4.10.8
+       * collectd: Create new directories with mode 0777 and let umask remove
+         unwanted permission bits.
+       * collectd: Build issues have been fixed.
+       * collectd: An incorrect assertion has been fixed in some common code
+         for Solaris. This should resolve pseudo-random assertion failures
+         under Solaris. Thanks to Jeff Blane for his help debugging this.
+       * collectd: A couple of memory leaks through PThread thread attributes
+         have been fixed. Thanks to Gerrie Roos for fixing these.
+       * apcups plugin: Improve the reconnect behavior.
+       * df plugin: Ignore "rootfs" devices under Linux to avoid having them
+         reported twice. Thanks to Brune Prémont for fixing this.
+       * disk plugin: Fix incorrect computation of read and write latency (the
+         "disk_time" type). Previously, the numbers reported where too small
+         by a factor of "interval", e.g. when the interval is set to 10
+         seconds, the values were too low by a factor of 10. Thanks to Manuel
+         Sanmartin for reporting this problem.
+       * dns plugin: A build issue under Solaris has been fixed. A erroneous
+         define that could lead to the reporting of bad data has been fixed by
+         Daniel Sutto.
+       * memcachec plugin: A bug in the configuration handling has been fixed.
+         Thanks to Pascal Hofmann for fixing this issue.
+       * netapp plugin: Correctly close the connection on communication
+         errors.
+       * netlink plugin: The function used to query statistics has been
+         changed to be more in line with iproute2's behavior. Thanks to
+         "KIvosak" for the patch.
+       * network plugin: Initialization of libgcrypt has been fixed. Thanks to
+         Chris Lundquist for his patch.
+       * oracle plugin: Error messages have been improved.
+       * ping plugin: Don't enter the exponential back-off mode when
+         ping_send() fails. This should make recovery after a network failure
+         much faster.
+       * python plugin: Memory leaks have been fixed. Thanks to Tommie Gannert
+         and Sven Trenkel for fixing this.
+       * rrdtool plugin: Fix an out-of-bounds array access when printing a
+         warning message. Thanks to Will Hawkins for fixing this bug.
+       * snmp plugin: Support for the SNMP_ENDOFMIBVIEW return value has been
+         added. Support for more complex / unusual MIBs / subtrees has been
+         added. Thanks to Mark Juric to test the changes and point out these
+         problems.
+
+2012-04-01, Version 4.10.7
+       * Build system: Fix the use of a libltdl macro. Thanks to Clemens Lang
+         for fixing this. Adresses some issues with building the iptables
+         plugin under Gentoo.
+       * libcollectdclient: A memory leak in the lcc_getval() function has
+         been fixed. Thanks to Jason Schmidlapp for finding and fixing this
+         issue.
+       * bind plugin: The use of 'QType" types has been fixed.
+       * df plugin: Fixed compiler issue under Mac OS X 10.7.
+       * conntrack plugin: Support zero as legitimate value. Thanks to Louis
+         Opter for his patch.
+       * memcached plugin: Increased the size of a static buffer, which was
+         truncating status messages form memcached. Thanks to Timon for the
+         patch.
+       * network plugin: Forwarding of notifications has been disabled. This
+         was a contition not checked for before, which may retult in an
+         endless loop.
+       * processes plugin: Support for process names with spaces has been
+         added to the Linux implementation. Thanks to Darrell Bishop for his
+         patch.
+       * perl plugin: A race condition in several callbacks, including log and
+         write callbacks, has been fixed. Thanks to "Rrpv" for reporting this
+         bug.
+       * snmp plugin: A bug when casting unsigned integers to gauge values has
+         been fixed: Unsigned integers would be cast to a signed integer and
+         then to a gauge, possibly resulting in a negative value.
+       * tcpconns plugin: Compilation with newer versions of the FreeBSD
+         runtime has been fixed.
+
+2012-02-19, Version 4.10.6
+       * Build system: Fix problems when building the ipvs and iptables
+         plugins. Thanks to Sebastian Harl for his patch. A bashism in the
+         version-gen.sh script has been fixed. Thanks to Jo-Philipp Wich for
+         his patch.
+       * csv and rrdtool plugins: Print a more helpful error message when the
+         DataDir is a symlink pointing to a non-existing location. Thanks to
+         Jonathan Nieder for his patch.
+       * exec plugin: Fix a problem when using select(2) to read from file
+         handles. Thanks to Gerrie Roos for his patch.
+       * network plugin: An incorrect error message in the handling of the
+         "Interface" configuration option has been fixed. Thanks to Gerrie
+         Roos for his patch.
+       * oracle plugin: A potential endless loop in the error handling has
+         been fixed.
+       * python plugin: A crash bug in the configuration handling has been
+         fixed. Thanks to Sven Trenkel for his patch.
+       * interfaces plugin: The change which was supposed to ignore "bogus"
+         interfaces has been reverted, since it ignored legit interfaces, such
+         as bonding pseudo-devices as well.
+
+2012-01-21, Version 4.10.5
+       * curl_xml plugin: Fix handling of file:// and other URLs (which don't
+         follow HTTP status codes). Thanks to Fabien Wernli for his patch!
+       * df plugin: Fix handling of negative "available" counts. This can
+         occur with some file systems, for example UFS. Thanks to Toni Ylenius
+         for his patch.
+       * interface plugin: "mac" interfaces are now ignored on Solaris. These
+         pseudo-interfaces occur multiple times, causing warnings. Also switch
+         to 64-bit counters on Solaris, improving overflow behavior for
+         high-speed interfaces. Thanks to Eddy Geez and Fabien Wernli for
+         their patches.
+       * memory plugin: Account kernel and unused memory under Solaris. Thanks
+         to Fabien Wernli for his patch.
+       * network plugin: A bug in the interaction between the Network plugin
+         and filter chains has been fixed: When a filter modified a field such
+         as the hostname, subsequent values in the same network packets could
+         have ended up using the modified name rather than the original name.
+         Thanks to Sebastian Harl for identifying the problem.
+       * oracle plugin: A memory leak has been fixed in the parameter handling.
+       * python plugin: A memory leak has been fixed. Thanks to Sven Trenkel
+         for fixing this bug!
+
+2011-10-14, Version 4.10.4
+       * collectd: A mutex leak has been fixed in the meta data code. Thanks
+         to Rafal Lesniak for his patch.
+       * collectd: Compatibility fixes for GCC 4.6 have been applied. Thanks
+         to Peter Green for his patch.
+       * csv plugin: The line buffer size has been increased. Thanks to Colin
+         McCabe for the patch.
+       * curl_json plugin: Don't use the "parent" node to build the type
+         instance, if it is empty. Compatibility with libyajl 2 has been
+         added. Thanks to "spupykin" of the Arch Linux project for the initial
+         code.
+       * iptables plugin: Fix linking with some versions of libiptc.
+       * irq plugin: Fix support for interrupts under Linux. The old code
+         assumed that interrupts have a numeric value -- this is no longer
+         true for Linux. Thanks to Bostjan Skufca for implementing this.
+       * notify_desktop plugin: Compatibility with libnotify 0.7 has been
+         added. Thanks to Samuli Suominen for his patch.
+       * processes plugin: Fix handling of regular expressions containing
+         spaces. Thanks for Sebastian Harl for fixing this.
+       * rrdtool, rrdcached plugins: Improve precision of the XFF parameter.
+         Previously, values like 0.999 would have been rounded to 1.0. Thanks
+         to Francois-Xavier Bourlet for fixing this.
+       * Various plugin: Set a multi-threading flag in libcurl. Thanks to Mike
+         Flisher for the fix.
+
+2011-03-26, Version 4.10.3
+       * Documentation: Several updates and additions. Thanks to Sebastian Harl.
+       * collectd: Build issues (compiler warnings) have been fixed. Thanks to
+         Bruno Prémont.
+       * collectd: Threshold subsection: Handling of NAN values in the
+         percentage calculation has been fixed.
+       * collectd, java plugin, ntpd plugin: Several diagnostic messages have
+         been improved.
+       * curl_json plugin: Handling of arrays has been fixed.
+       * libvirt plugin: A bug in reading the virtual CPU statistics has been
+         fixed. Thanks to “JLPC” for reporting this problem.
+       * modbus plugin: Compatibility with libmodbus 2.0.3 has been restored.
+       * processes plugin: Potentially erroneous behavior has been fixed in an
+         error handling case.
+       * python plugin: Fix dispatching of values from Python scripts to
+         collectd. Thanks to Gregory Szorc for finding and fixing this
+         problem.
+
+2010-11-27, Version 4.10.2
+       * Documentation: Various documentation fixes.
+       * collectd: If including one configuration file fails, continue with
+         the rest of the configuration if possible.
+       * collectd: Fix a bug in the read function scheduling. In rare cases
+         read functions may not have been called as often as requested.
+       * collectd: Concurrency issues with errno(3) under AIX have been
+         fixed: A thread-safe version of errno has to be requested under AIX.
+         Thanks to Aurélien Reynaud for his patch.
+       * collectd: A left-over hard-coded 2 has been replaced by the
+         configurable timeout value.
+       * curl, memcachec, tail plugins: Fix handling of "DERIVE" data
+         sources. Matching the end of a string has been improved; thanks to
+         Sebastian Harl for the patch.
+       * curl_json plugin: Fix a problem when parsing 64bit integers. Reading
+         JSON data from non-HTTP sources has been fixed.
+       * netapp plugin: Pass the interval setting to the dispatch function.
+         Restore compatibility to NetApp Release 7.3. Thanks to Sven Trenkel
+         for the patch.
+       * network plugin: Be less verbose about unchecked signatures, in order
+         to prevent spamming the logs.
+       * notify_email plugin: Concurrency problems have been fixed.
+       * python plugin: Set "sys.argv", since many scripts don't expect that
+         it may not be set. Thanks to Sven Trenkel for the patch.
+       * rrdtool, rrdcached plugin: Fix a too strict assertion when creating
+         RRD files.
+       * swap plugin: A bug which lead to incorrect I/O values has been
+         fixed.
+       * value match: A minor memory leak has been fixed. Thanks to Sven
+         Trenkel for the patch.
+
 2010-07-09, Version 4.10.1
        * Build system: Checking for "strtok_r" under Solaris has been fixed.
        * Portability: Fixes for Solaris 8 have been applied. Thanks to
        * regex match: The "Invert" option has been added. Thanks to Julien
          Ammous for his patch.
 
+2011-03-26, Version 4.9.5
+       * Documentation: Several updates and additions. Thanks to Sebastian Harl.
+       * collectd: Build issues (compiler warnings) have been fixed. Thanks to
+         Bruno Prémont.
+       * collectd: Threshold subsection: Handling of NAN values in the
+         percentage calculation has been fixed.
+       * collectd, java plugin, ntpd plugin: Several diagnostic messages have
+         been improved.
+       * libvirt plugin: A bug in reading the virtual CPU statistics has been
+         fixed. Thanks to “JLPC” for reporting this problem.
+       * processes plugin: Potentially erroneous behavior has been fixed in an
+         error handling case.
+       * python plugin: Fix dispatching of values from Python scripts to
+         collectd. Thanks to Gregory Szorc for finding and fixing this
+         problem.
+
+2010-11-27, Version 4.9.4
+       * Documentation: Various documentation fixes.
+       * collectd: If including one configuration file fails, continue with
+         the rest of the configuration if possible.
+       * collectd: Fix a bug in the read function scheduling. In rare cases
+         read functions may not have been called as often as requested.
+       * collectd: Concurrency issues with errno(3) under AIX have been
+         fixed: A thread-safe version of errno has to be requested under AIX.
+         Thanks to Aurélien Reynaud for his patch.
+       * curl, memcachec, tail plugins: Fix handling of "DERIVE" data
+         sources. Matching the end of a string has been improved; thanks to
+         Sebastian Harl for the patch.
+       * curl_json plugin: Fix a problem when parsing 64bit integers. Reading
+         JSON data from non-HTTP sources has been fixed.
+       * netapp plugin: Pass the interval setting to the dispatch function.
+         Restore compatibility to NetApp Release 7.3. Thanks to Sven Trenkel
+         for the patch.
+       * network plugin: Be less verbose about unchecked signatures, in order
+         to prevent spamming the logs.
+       * notify_email plugin: Concurrency problems have been fixed.
+       * python plugin: Set "sys.argv", since many scripts don't expect that
+         it may not be set. Thanks to Sven Trenkel for the patch.
+       * rrdtool, rrdcached plugin: Fix a too strict assertion when creating
+         RRD files.
+       * value match: A minor memory leak has been fixed. Thanks to Sven
+         Trenkel for the patch.
+
 2010-07-09, Version 4.9.3
        * Build system: Checking for "strtok_r" under Solaris has been fixed.
        * Portability: Fixes for Solaris 8 have been applied. Thanks to
index 9e3feac..5267123 100644 (file)
@@ -1,6 +1,6 @@
 ACLOCAL_AMFLAGS = -I libltdl/m4
 
-SUBDIRS = libltdl src bindings
+SUBDIRS = libltdl src bindings .
 
 INCLUDES = $(LTDLINCL)
 
@@ -10,3 +10,8 @@ install-exec-hook:
        $(mkinstalldirs) $(DESTDIR)$(localstatedir)/run
        $(mkinstalldirs) $(DESTDIR)$(localstatedir)/lib/$(PACKAGE_NAME)
        $(mkinstalldirs) $(DESTDIR)$(localstatedir)/log
+
+maintainer-clean-local:
+       -rm -f -r libltdl
+       -rm -f INSTALL
+       -rm -f aclocal.m4
diff --git a/README b/README
index 2ed8934..67cac04 100644 (file)
--- a/README
+++ b/README
@@ -83,6 +83,9 @@ Features
     - entropy
       Amount of entropy available to the system.
 
+    - ethstat
+      Network interface card statistics.
+
     - exec
       Values gathered by a custom program or script.
       See collectd-exec(5).
@@ -140,6 +143,10 @@ Features
       Motherboard sensors: temperature, fanspeed and voltage information,
       using mbmon(1).
 
+    - md
+      Linux software-RAID device information (number of active, failed, spare
+      and missing disks).
+
     - memcachec
       Query and parse data from a memcache daemon (memcached).
 
@@ -192,6 +199,9 @@ Features
       Network UPS tools: UPS current, voltage, power, charge, utilisation,
       temperature, etc. See upsd(8).
 
+    - numa
+      Information about Non-Uniform Memory Access (NUMA).
+
     - olsrd
       Queries routing information from the “Optimized Link State Routing”
       daemon.
@@ -358,11 +368,17 @@ Features
       needed. Please read collectd-unixsock(5) for a description on how that's
       done.
 
+    - write_graphite
+      Sends data to Carbon, the storage layer of Graphite.
+
     - write_http
       Sends the values collected by collectd to a web-server using HTTP POST
       requests. The transmitted data is either in a form understood by the
       Exec plugin or formatted in JSON.
 
+    - write_redis
+      Sends the values to a Redis key-value database server.
+
   * Logging is, as everything in collectd, provided by plugins. The following
     plugins keep up informed about what's going on:
 
@@ -442,6 +458,10 @@ Features
 
   * Miscellaneous plugins:
 
+    - threshold
+      Checks values against configured thresholds and creates notifications if
+      values are out of bounds. See collectd-threshold(5) for details.
+
     - uuid
       Sets the hostname to an unique identifier. This is meant for setups
       where each client may migrate to another physical host, possibly going
@@ -569,8 +589,10 @@ Prerequisites
     <http://tangent.org/552/libmemcached.html>
 
   * libmodbus (optional)
-    Used by the `modbus' plugin to communicate with Modbus/TCP devices.
-    <https://launchpad.net/libmodbus>
+    Used by the “modbus” plugin to communicate with Modbus/TCP devices. The
+    “modbus” plugin works with version 2.0.3 of the library – due to frequent
+    API changes other versions may or may not compile cleanly.
+    <http://www.libmodbus.org/>
 
   * libmysqlclient (optional)
     Unsurprisingly used by the `mysql' plugin.
@@ -623,7 +645,8 @@ Prerequisites
     <http://code.google.com/p/protobuf-c/>
 
   * libpython (optional)
-    Used by the `python' plugin. Currently, only 2.3 ≦ Python < 3 is supported.
+    Used by the `python' plugin. Currently, Python 2.3 and later and Python 3
+    are supported.
     <http://www.python.org/>
 
   * librabbitmq (optional; also called “rabbitmq-c”)
index f39e9bb..3876cc2 100644 (file)
@@ -10,28 +10,55 @@ EXTRA_DIST = perl/Makefile.PL \
             perl/lib/Collectd/Plugins/Monitorus.pm \
             perl/lib/Collectd/Plugins/OpenVZ.pm
 
+CLEANFILES = \
+       buildperl/Collectd.pm \
+       buildperl/Collectd/Plugins/OpenVZ.pm \
+       buildperl/Collectd/Unixsock.pm \
+       buildperl/Makefile.PL \
+       .perl-directory-stamp
+
+DISTCLEANFILES = \
+       buildperl/Collectd.pm \
+       buildperl/Collectd/Plugins/OpenVZ.pm \
+       buildperl/Collectd/Unixsock.pm \
+       buildperl/Makefile.PL \
+       .perl-directory-stamp
+
 all-local: @PERL_BINDINGS@
 
+
 install-exec-local:
-       [ ! -f perl/Makefile ] || ( cd perl && $(MAKE) install )
+       [ ! -f buildperl/Makefile ] || ( cd buildperl && $(MAKE) install )
+
+# Perl 'make uninstall' does not work as well as wanted.
+# So we do the work here.
+uninstall-local:
+       rm -f $(DESTDIR)$(mandir)/man3/Collectd::Unixsock.3pm
+       rm -f $(DESTDIR)$(datarootdir)/perl5/Collectd.pm
+       rm -f $(DESTDIR)$(datarootdir)/perl5/Collectd/Plugins/OpenVZ.pm
+       rm -f $(DESTDIR)$(datarootdir)/perl5/Collectd/Unixsock.pm
+       rm -f $(DESTDIR)$(prefix)/lib64/perl5/perllocal.pod
+       rm -f $(DESTDIR)$(prefix)/lib64/perl5/auto/Collectd/.packlist
 
 clean-local:
-       [ ! -f perl/Makefile ] || ( cd perl && $(MAKE) realclean )
+       rm -rf buildperl
 
-perl: perl/Makefile
-       cd perl && $(MAKE)
+perl: buildperl/Makefile
+       cd buildperl && $(MAKE)
 
-perl/Makefile: .perl-directory-stamp perl/Makefile.PL \
+buildperl/Makefile: .perl-directory-stamp buildperl/Makefile.PL \
        $(top_builddir)/config.status
-       cd perl && @PERL@ Makefile.PL PREFIX=$(prefix) @PERL_BINDINGS_OPTIONS@
+       cd buildperl && @PERL@ Makefile.PL INSTALL_BASE=$(prefix) @PERL_BINDINGS_OPTIONS@
+
+buildperl/Makefile.PL: .perl-directory-stamp $(top_builddir)/config.status
 
 .perl-directory-stamp:
-       if test ! -d perl; then \
-         mkdir -p perl/Collectd/Plugins; \
-         cp $(srcdir)/perl/Collectd.pm perl/; \
-         cp $(srcdir)/perl/Makefile.PL perl/; \
-         cp $(srcdir)/perl/Collectd/Unixsock.pm perl/Collectd/; \
-         cp $(srcdir)/perl/Collectd/Plugins/OpenVZ.pm perl/Collectd/Plugins/; \
+       if test ! -d buildperl; then \
+         mkdir -p buildperl/Collectd/Plugins; \
+         cp $(srcdir)/perl/lib/Collectd.pm buildperl/; \
+         cp $(srcdir)/perl/Makefile.PL buildperl/; \
+         cp $(srcdir)/perl/lib/Collectd/Unixsock.pm buildperl/Collectd/; \
+         cp $(srcdir)/perl/lib/Collectd/Plugins/OpenVZ.pm buildperl/Collectd/Plugins/; \
        fi
        touch $@
 
index 3e492dd..410c61c 100644 (file)
@@ -29,5 +29,5 @@ package org.collectd.api;
  */
 public interface CollectdFlushInterface
 {
-       public int flush (int timeout, String identifier);
+       public int flush (Number timeout, String identifier);
 }
index 1baeff2..b8d6f40 100644 (file)
@@ -87,10 +87,16 @@ public class ValueList extends PluginData {
         _ds = new DataSet (_type, dsrc);
     }
 
+    /**
+     * Returns the interval (in milliseconds) of the value list.
+     */
     public long getInterval() {
         return _interval;
     }
 
+    /**
+     * Sets the interval (in milliseconds) of the value list.
+     */
     public void setInterval(long interval) {
         _interval = interval;
     }
index 0eb0d5f..9fb0fc2 100644 (file)
@@ -312,7 +312,14 @@ class GenericJMXConfValue
 
     try
     {
-      value = conn.getAttribute (objName, key);
+      try
+      {
+        value = conn.getAttribute (objName, key);
+      }
+      catch (javax.management.AttributeNotFoundException e)
+      {
+        value = conn.invoke (objName, key, /* args = */ null, /* types = */ null);
+      }
     }
     catch (Exception e)
     {
index ca3b5d2..c1adf44 100644 (file)
@@ -42,6 +42,7 @@ our %EXPORT_TAGS = (
                        plugin_register
                        plugin_unregister
                        plugin_dispatch_values
+                       plugin_get_interval
                        plugin_write
                        plugin_flush
                        plugin_flush_one
@@ -171,6 +172,7 @@ sub plugin_call_all {
        my $type = shift;
 
        my %plugins;
+       my $interval;
 
        our $cb_name = undef;
 
@@ -194,13 +196,15 @@ sub plugin_call_all {
                %plugins = %{$plugins[$type]};
        }
 
+       $interval = plugin_get_interval ();
+
        foreach my $plugin (keys %plugins) {
                my $p = $plugins{$plugin};
 
                my $status = 0;
 
                if ($p->{'wait_left'} > 0) {
-                       $p->{'wait_left'} -= $interval_g;
+                       $p->{'wait_left'} -= $interval;
                }
 
                next if ($p->{'wait_left'} > 0);
@@ -227,11 +231,11 @@ sub plugin_call_all {
 
                if ($status) {
                        $p->{'wait_left'} = 0;
-                       $p->{'wait_time'} = $interval_g;
+                       $p->{'wait_time'} = $interval;
                }
                elsif (TYPE_READ == $type) {
-                       if ($p->{'wait_time'} < $interval_g) {
-                               $p->{'wait_time'} = $interval_g;
+                       if ($p->{'wait_time'} < $interval) {
+                               $p->{'wait_time'} = $interval;
                        }
 
                        $p->{'wait_left'} = $p->{'wait_time'};
@@ -313,7 +317,7 @@ sub plugin_register {
                }
 
                %p = (
-                       wait_time => $interval_g,
+                       wait_time => plugin_get_interval (),
                        wait_left => 0,
                        cb_name   => $data,
                );
index 2944157..ea3cee9 100644 (file)
@@ -36,7 +36,7 @@ my $last_stat = {};
 
 sub openvz_read
 {
-    my %v = (time => time(), interval => $interval_g);
+    my %v = (time => time(), interval => plugin_get_interval());
     my (@veids, $veid, $name, $key, $val, $i, @lines, @parts, @counters);
 
     @veids = map { s/ //g; $_; } split(/\n/, `$vzlist -Ho veid`);
index af58442..7c4ec3a 100644 (file)
@@ -1,7 +1,8 @@
 dnl Process this file with autoconf to produce a configure script.
-AC_INIT(collectd, m4_esyscmd(./version-gen.sh))
+AC_INIT(collectd, [m4_esyscmd(./version-gen.sh)])
 AC_CONFIG_SRCDIR(src/collectd.c)
 AC_CONFIG_HEADERS(src/config.h)
+AC_CONFIG_AUX_DIR([libltdl/config])
 
 m4_ifdef([LT_PACKAGE_VERSION],
        # libtool >= 2.2
@@ -90,6 +91,7 @@ fi
 if test "x$ac_system" = "xSolaris"
 then
        AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1, [Define to enforce POSIX thread semantics under Solaris.])
+       AC_DEFINE(_REENTRANT,               1, [Define to enable reentrancy interfaces.])
 fi
 if test "x$ac_system" = "xAIX"
 then
@@ -298,6 +300,21 @@ fi
 # For hddtemp module
 AC_CHECK_HEADERS(linux/major.h libgen.h)
 
+# For md module (Linux only)
+if test "x$ac_system" = "xLinux"
+then
+       AC_CHECK_HEADERS(linux/raid/md_u.h,
+                        [have_linux_raid_md_u_h="yes"],
+                        [have_linux_raid_md_u_h="no"],
+[
+#include <sys/ioctl.h>
+#include <linux/major.h>
+#include <linux/types.h>
+])
+else
+       have_linux_raid_md_u_h="no"
+fi
+
 # For the battery plugin
 AC_CHECK_HEADERS(IOKit/ps/IOPowerSources.h, [], [],
 [
@@ -387,19 +404,64 @@ AC_CHECK_HEADERS(linux/netdevice.h, [], [],
 #endif
 ])
 
+# For ethstat module
+AC_CHECK_HEADERS(linux/sockios.h,
+    [have_linux_sockios_h="yes"],
+    [have_linux_sockios_h="no"],
+    [
+#if HAVE_SYS_IOCTL_H
+# include <sys/ioctl.h>
+#endif
+#if HAVE_NET_IF_H
+# include <net/if.h>
+#endif
+    ])
+AC_CHECK_HEADERS(linux/ethtool.h,
+    [have_linux_ethtool_h="yes"],
+    [have_linux_ethtool_h="no"],
+    [
+#if HAVE_SYS_IOCTL_H
+# include <sys/ioctl.h>
+#endif
+#if HAVE_NET_IF_H
+# include <net/if.h>
+#endif
+#if HAVE_LINUX_SOCKIOS_H
+# include <linux/sockios.h>
+#endif
+    ])
+
 # For ipvs module
+have_linux_ip_vs_h="no"
 have_net_ip_vs_h="no"
 have_ip_vs_h="no"
+ip_vs_h_needs_kernel_cflags="no"
 if test "x$ac_system" = "xLinux"
 then
-       SAVE_CFLAGS="$CFLAGS"
-       CFLAGS="$CFLAGS $KERNEL_CFLAGS"
-
+       AC_CHECK_HEADERS(linux/ip_vs.h, [have_linux_ip_vs_h="yes"])
        AC_CHECK_HEADERS(net/ip_vs.h, [have_net_ip_vs_h="yes"])
        AC_CHECK_HEADERS(ip_vs.h, [have_ip_vs_h="yes"])
 
-       CFLAGS="$SAVE_CFLAGS"
+       if test "x$have_linux_ip_vs_h$have_net_ip_vs_h$have_ip_vs_h" = "xnonono" && test -d "$KERNEL_DIR"
+       then
+               SAVE_CFLAGS="$CFLAGS"
+               CFLAGS="$CFLAGS $KERNEL_CFLAGS"
+
+               AC_MSG_NOTICE([Did not find ip_vs.h. Trying again using headers from $KERNEL_DIR.])
+
+               AC_CHECK_HEADERS(linux/ip_vs.h, [have_linux_ip_vs_h="yes"])
+               AC_CHECK_HEADERS(net/ip_vs.h, [have_net_ip_vs_h="yes"])
+               AC_CHECK_HEADERS(ip_vs.h, [have_ip_vs_h="yes"])
+
+               if test "x$have_linux_ip_vs_h" = "xyes" || test "x$have_net_ip_vs_h" = "xyes" || test "x$have_ip_vs_h" = "xyes"
+               then
+                       ip_vs_h_needs_kernel_cflags="yes"
+               fi
+
+               CFLAGS="$SAVE_CFLAGS"
+       fi
 fi
+AM_CONDITIONAL(IP_VS_H_NEEDS_KERNEL_CFLAGS, test "x$ip_vs_h_needs_kernel_cflags" = "xyes")
 
 # For quota module
 AC_CHECK_HEADERS(sys/ucred.h, [], [],
@@ -471,6 +533,8 @@ AC_CHECK_HEADERS(netinet/if_ether.h, [], [],
 #endif
 ])
 
+AC_CHECK_HEADERS(netinet/ip_compat.h)
+
 # For the multimeter plugin
 have_termios_h="no"
 AC_CHECK_HEADERS(termios.h, [have_termios_h="yes"])
@@ -572,6 +636,27 @@ socket_needs_socket="no"
 AC_CHECK_FUNCS(socket, [], AC_CHECK_LIB(socket, socket, [socket_needs_socket="yes"], AC_MSG_ERROR(cannot find socket)))
 AM_CONDITIONAL(BUILD_WITH_LIBSOCKET, test "x$socket_needs_socket" = "xyes")
 
+clock_gettime_needs_rt="no"
+clock_gettime_needs_posix4="no"
+have_clock_gettime="no"
+AC_CHECK_FUNCS(clock_gettime, [have_clock_gettime="yes"])
+if test "x$have_clock_gettime" = "xno"
+then
+       AC_CHECK_LIB(rt, clock_gettime, [clock_gettime_needs_rt="yes"
+                                        have_clock_gettime="yes"])
+fi
+if test "x$have_clock_gettime" = "xno"
+then
+       AC_CHECK_LIB(posix4, clock_gettime, [clock_gettime_needs_posix4="yes"
+                                            have_clock_gettime="yes"])
+fi
+if test "x$have_clock_gettime" = "xyes"
+then
+       AC_DEFINE(HAVE_CLOCK_GETTIME, 1, [Define if the clock_gettime(2) function is available.])
+else
+       AC_MSG_WARN(cannot find clock_gettime)
+fi
+
 nanosleep_needs_rt="no"
 nanosleep_needs_posix4="no"
 AC_CHECK_FUNCS(nanosleep,
@@ -581,8 +666,9 @@ AC_CHECK_FUNCS(nanosleep,
         AC_CHECK_LIB(posix4, nanosleep,
             [nanosleep_needs_posix4="yes"],
             AC_MSG_ERROR(cannot find nanosleep))))
-AM_CONDITIONAL(BUILD_WITH_LIBRT, test "x$nanosleep_needs_rt" = "xyes")
-AM_CONDITIONAL(BUILD_WITH_LIBPOSIX4, test "x$nanosleep_needs_posix4" = "xyes")
+
+AM_CONDITIONAL(BUILD_WITH_LIBRT, test "x$clock_gettime_needs_rt" = "xyes" || test "x$nanosleep_needs_rt" = "xyes")
+AM_CONDITIONAL(BUILD_WITH_LIBPOSIX4, test "x$clock_gettime_needs_posix4" = "xyes" || test "x$nanosleep_needs_posix4" = "xyes")
 
 AC_CHECK_FUNCS(sysctl, [have_sysctl="yes"], [have_sysctl="no"])
 AC_CHECK_FUNCS(sysctlbyname, [have_sysctlbyname="yes"], [have_sysctlbyname="no"])
@@ -592,9 +678,77 @@ AC_CHECK_FUNCS(thread_info, [have_thread_info="yes"], [have_thread_info="no"])
 AC_CHECK_FUNCS(statfs, [have_statfs="yes"], [have_statfs="no"])
 AC_CHECK_FUNCS(statvfs, [have_statvfs="yes"], [have_statvfs="no"])
 AC_CHECK_FUNCS(getifaddrs, [have_getifaddrs="yes"], [have_getifaddrs="no"])
+AC_CHECK_FUNCS(getloadavg, [have_getloadavg="yes"], [have_getloadavg="no"])
 AC_CHECK_FUNCS(syslog, [have_syslog="yes"], [have_syslog="no"])
 AC_CHECK_FUNCS(getutent, [have_getutent="yes"], [have_getutent="no"])
 AC_CHECK_FUNCS(getutxent, [have_getutxent="yes"], [have_getutxent="no"])
+
+# Check for strptime {{{
+if test "x$GCC" = "xyes"
+then
+       SAVE_CFLAGS="$CFLAGS"
+       CFLAGS="$CFLAGS -Wall -Wextra -Werror"
+fi
+
+AC_CHECK_FUNCS(strptime, [have_strptime="yes"], [have_strptime="no"])
+if test "x$have_strptime" = "xyes"
+then
+       AC_CACHE_CHECK([whether strptime is exported by default],
+                      [c_cv_have_strptime_default],
+                      AC_COMPILE_IFELSE(
+AC_LANG_PROGRAM(
+[[
+AC_INCLUDES_DEFAULT
+#include <time.h>
+]],
+[[
+ struct tm stm;
+ (void) strptime ("2010-12-30%13:42:42", "%Y-%m-%dT%T", &stm);
+]]),
+                      [c_cv_have_strptime_default="yes"],
+                      [c_cv_have_strptime_default="no"]))
+fi
+if test "x$have_strptime" = "xyes" && test "x$c_cv_have_strptime_default" = "xno"
+then
+       AC_CACHE_CHECK([whether strptime needs standards mode],
+                      [c_cv_have_strptime_standards],
+                      AC_COMPILE_IFELSE(
+AC_LANG_PROGRAM(
+[[
+#ifndef _ISOC99_SOURCE
+# define _ISOC99_SOURCE 1
+#endif
+#ifndef _POSIX_C_SOURCE
+# define _POSIX_C_SOURCE 200112L
+#endif
+#ifndef _XOPEN_SOURCE
+# define _XOPEN_SOURCE 500
+#endif
+AC_INCLUDES_DEFAULT
+#include <time.h>
+]],
+[[
+ struct tm stm;
+ (void) strptime ("2010-12-30%13:42:42", "%Y-%m-%dT%T", &stm);
+]]),
+                      [c_cv_have_strptime_standards="yes"],
+                      [c_cv_have_strptime_standards="no"]))
+
+       if test "x$c_cv_have_strptime_standards" = "xyes"
+       then
+               AC_DEFINE([STRPTIME_NEEDS_STANDARDS], 1, [Set to true if strptime is only exported in X/Open mode (GNU libc).])
+       else
+               have_strptime="no"
+       fi
+fi
+
+if test "x$GCC" = "xyes"
+then
+       CFLAGS="$SAVE_CFLAGS"
+fi
+
+# }}} Check for strptime
+
 AC_CHECK_FUNCS(swapctl, [have_swapctl="yes"], [have_swapctl="no"])
 if test "x$have_swapctl" = "xyes"; then
         AC_CACHE_CHECK([whether swapctl takes two arguments],
@@ -646,9 +800,6 @@ if test "x$have_swapctl" = "xyes"; then
         fi
 fi
 
-# For load module
-AC_CHECK_FUNCS(getloadavg, [have_getloadavg="yes"], [have_getloadavg="no"])
-
 # Check for NAN
 AC_ARG_WITH(nan-emulation, [AS_HELP_STRING([--with-nan-emulation], [use emulated NAN. For crosscompiling only.])],
 [
@@ -669,7 +820,7 @@ if test "x$nan_type" = "xnone"; then
       [[
 #include <stdlib.h>
 #include <math.h>
-static float foo = NAN;
+static double foo = NAN;
       ]],
       [[
        if (isnan (foo))
@@ -695,7 +846,7 @@ if test "x$nan_type" = "xnone"; then
 #include <stdlib.h>
 #define __USE_ISOC99 1
 #include <math.h>
-static float foo = NAN;
+static double foo = NAN;
       ]],
       [[
        if (isnan (foo))
@@ -729,7 +880,7 @@ if test "x$nan_type" = "xnone"; then
 #ifndef isnan
 # define isnan(f) ((f) != (f))
 #endif
-static float foo = NAN;
+static double foo = NAN;
       ]],
       [[
        if (isnan (foo))
@@ -1077,6 +1228,7 @@ AC_CHECK_MEMBERS([struct kinfo_proc.ki_pid, struct kinfo_proc.ki_rssize, struct
                have_struct_kinfo_proc_freebsd="no"
        ],
        [
+AC_INCLUDES_DEFAULT
 #include <kvm.h>
 #include <sys/param.h>
 #include <sys/sysctl.h>
@@ -1093,6 +1245,7 @@ AC_CHECK_MEMBERS([struct kinfo_proc.kp_proc, struct kinfo_proc.kp_eproc],
                have_struct_kinfo_proc_openbsd="no"
        ],
        [
+AC_INCLUDES_DEFAULT
 #include <sys/param.h>
 #include <sys/sysctl.h>
 #include <kvm.h>
@@ -1153,6 +1306,7 @@ AC_CHECK_MEMBERS([kstat_io_t.nwritten, kstat_io_t.writes, kstat_io_t.nwrites, ks
 #
 # Checks for libraries begin here
 #
+
 with_libresolv="yes"
 AC_CHECK_LIB(resolv, res_search,
 [
@@ -1274,6 +1428,7 @@ AM_CONDITIONAL(BUILD_WITH_LIBKVM_GETSWAPINFO, test "x$with_kvm_getswapinfo" = "x
 AC_CHECK_LIB(kvm, kvm_nlist, [with_kvm_nlist="yes"], [with_kvm_nlist="no"])
 if test "x$with_kvm_nlist" = "xyes"
 then
+       AC_CHECK_HEADERS(bsd/nlist.h nlist.h)
        AC_DEFINE(HAVE_LIBKVM_NLIST, 1,
                  [Define to 1 if you have the 'kvm' library with the 'kvm_nlist' symbol (-lkvm)])
        with_libkvm="yes"
@@ -1320,7 +1475,7 @@ then
        fi
        AC_CHECK_HEADERS(credis.h,
        [with_libcredis="yes"],
-       [with_libcredis="no ('credis.h' not found)"])
+       [with_libcredis="no (credis.h not found)"])
 fi
 if test "x$with_libcredis" = "xyes"
 then
@@ -1677,113 +1832,123 @@ AM_CONDITIONAL(BUILD_WITH_LIBGCRYPT, test "x$with_libgcrypt" = "xyes")
 # }}}
 
 # --with-libiptc {{{
-with_own_libiptc="no"
 AC_ARG_WITH(libiptc, [AS_HELP_STRING([--with-libiptc@<:@=PREFIX@:>@], [Path to libiptc.])],
 [
        if test "x$withval" = "xshipped"
        then
-               with_own_libiptc="yes"
-               with_libiptc="yes"
-       else if test "x$withval" != "xno" && test "x$withval" != "xyes"
+               with_libiptc="own"
+       else if test "x$withval" = "xyes"
        then
-               LIBIPTC_CPPFLAGS="$LIBIPTC_CPPFLAGS -I$withval/include"
-               LIBIPTC_LDFLAGS="$LIBIPTC_LDFLAGS -L$withval/lib"
-               with_libiptc="yes"
+               with_libiptc="pkgconfig"
+       else if test "x$withval" = "xno"
+       then
+               with_libiptc="no"
        else
-               with_libiptc="$withval"
-       fi; fi
+               with_libiptc="yes"
+               with_libiptc_cflags="-I$withval/include"
+               with_libiptc_libs="-L$withval/lib"
+       fi; fi; fi
 ],
 [
        if test "x$ac_system" = "xLinux"
        then
-               with_libiptc="yes"
+               with_libiptc="pkgconfig"
        else
                with_libiptc="no (Linux only)"
        fi
 ])
-SAVE_CPPFLAGS="$CPPFLAGS"
-SAVE_LDFLAGS="$LDFLAGS"
-CPPFLAGS="$CPPFLAGS $LIBIPTC_CPPFLAGS"
-LDFLAGS="$LDFLAGS $LIBIPTC_LDFLAGS"
-# check whether the header file for libiptc is available.
-if test "x$with_libiptc" = "xyes" && test "x$with_own_libiptc" = "xno"
+
+if test "x$with_libiptc" = "xpkgconfig" && test "x$PKG_CONFIG" = "x"
 then
-       AC_CHECK_HEADERS(libiptc/libiptc.h,
-       [
-               AC_DEFINE(HAVE_LIBIPTC_LIBIPTC_H, 1, [Define to 1 if you have the <libiptc/libiptc.h> header file.])
-       ],
-       [
-               with_libiptc="yes"
-               with_own_libiptc="yes"
-       ])
+       with_libiptc="no (Don't have pkg-config)"
 fi
-if test "x$with_libiptc" = "xyes" && test "x$with_own_libiptc" = "xno"
+
+if test "x$with_libiptc" = "xpkgconfig"
 then
-       AC_CHECK_HEADERS(libiptc/libip6tc.h,
-       [
-               AC_DEFINE(HAVE_LIBIPTC_LIBIP6TC_H, 1, [Define to 1 if you have the <libiptc/libip6tc.h> header file.])
-       ],
-       [
-               with_libiptc="yes"
-               with_own_libiptc="yes"
-       ])
+       $PKG_CONFIG --exists 'libiptc' 2>/dev/null
+       if test $? -ne 0
+       then
+               with_libiptc="no (pkg-config doesn't know libiptc)"
+       fi
+fi
+if test "x$with_libiptc" = "xpkgconfig"
+then
+       with_libiptc_cflags="`$PKG_CONFIG --cflags 'libiptc'`"
+       if test $? -ne 0
+       then
+               with_libiptc="no ($PKG_CONFIG failed)"
+       fi
+       with_libiptc_libs="`$PKG_CONFIG --libs 'libiptc'`"
+       if test $? -ne 0
+       then
+               with_libiptc="no ($PKG_CONFIG failed)"
+       fi
+fi
+
+SAVE_CPPFLAGS="$CPPFLAGS"
+CPPFLAGS="$CPPFLAGS $with_libiptc_cflags"
+
+# check whether the header file for libiptc is available.
+if test "x$with_libiptc" = "xpkgconfig"
+then
+       AC_CHECK_HEADERS(libiptc/libiptc.h libiptc/libip6tc.h, ,
+                       [with_libiptc="no (header file missing)"])
 fi
 # If the header file is available, check for the required type declaractions.
 # They may be missing in old versions of libiptc. In that case, they will be
 # declared in the iptables plugin.
-if test "x$with_libiptc" = "xyes" && test "x$with_own_libiptc" = "xno"
+if test "x$with_libiptc" = "xpkgconfig"
 then
-       AC_CHECK_TYPES([iptc_handle_t, ip6tc_handle_t], [], [],
-       [
-#if OWN_LIBIPTC
-# include "$srcdir/src/owniptc/libiptc.h"
-# include "$srcdir/src/owniptc/libip6tc.h"
-#else
-# include <libiptc/libiptc.h>
-# include <libiptc/libip6tc.h>
-#endif
-       ])
+       AC_CHECK_TYPES([iptc_handle_t, ip6tc_handle_t], [], [])
 fi
 # Check for the iptc_init symbol in the library.
-if test "x$with_libiptc" = "xyes" && test "x$with_own_libiptc" = "xno"
+# This could be in iptc or ip4tc
+if test "x$with_libiptc" = "xpkgconfig"
 then
-       AC_CHECK_LIB(iptc, iptc_init,
-       [
-               AC_DEFINE(HAVE_LIBIPTC, 1, [Define to 1 if you have the iptc library (-liptc).])
-       ],
-       [
-               with_libiptc="yes"
-               with_own_libiptc="yes"
-       ])
+       SAVE_LIBS="$LIBS"
+       AC_SEARCH_LIBS(iptc_init, [iptc ip4tc],
+                       [with_libiptc="pkgconfig"],
+                       [with_libiptc="no"],
+                       [$with_libiptc_libs])
+       LIBS="$SAVE_LIBS"
+fi
+if test "x$with_libiptc" = "xpkgconfig"
+then
+       with_libiptc="yes"
+fi
+
+CPPFLAGS="$SAVE_CPPFLAGS"
+
+if test "x$with_libiptc" = "xown"
+then
+       with_libiptc_cflags=""
+       with_libiptc_libs=""
 fi
-# The system wide version failed for some reason. Check if we have the required
-# headers to build the shipped version.
-if test "x$with_libiptc" = "xyes" && test "x$with_own_libiptc" = "xyes"
+if test "x$with_libiptc" = "xown"
 then
        AC_CHECK_HEADERS(linux/netfilter_ipv4/ip_tables.h linux/netfilter_ipv6/ip6_tables.h linux/netfilter/x_tables.h, [],
        [
                with_libiptc="no (Linux iptables headers not found)"
-               with_own_libiptc="no"
        ],
        [
 #include "$srcdir/src/owniptc/ipt_kernel_headers.h"
        ])
 fi
+AM_CONDITIONAL(BUILD_WITH_OWN_LIBIPTC, test "x$with_libiptc" = "xown")
+if test "x$with_libiptc" = "xown"
+then
+       AC_DEFINE(OWN_LIBIPTC, 1, [Define to 1 if we use the shipped iptc library.])
+       with_libiptc="yes"
+fi
+
 AM_CONDITIONAL(BUILD_WITH_LIBIPTC, test "x$with_libiptc" = "xyes")
-AM_CONDITIONAL(BUILD_WITH_OWN_LIBIPTC, test "x$with_own_libiptc" = "xyes")
 if test "x$with_libiptc" = "xyes"
 then
-       BUILD_WITH_LIBIPTC_CPPFLAGS="$LIBIPTC_CPPFLAGS"
-       BUILD_WITH_LIBIPTC_LDFLAGS="$LIBIPTC_LDFLAGS"
+       BUILD_WITH_LIBIPTC_CPPFLAGS="$with_libiptc_cflags"
+       BUILD_WITH_LIBIPTC_LDFLAGS="$with_libiptc_libs"
        AC_SUBST(BUILD_WITH_LIBIPTC_CPPFLAGS)
        AC_SUBST(BUILD_WITH_LIBIPTC_LDFLAGS)
 fi
-if test "x$with_own_libiptc" = "xyes"
-then
-       AC_DEFINE(OWN_LIBIPTC, 1, [Define to 1 if we use the shipped iptc library.])
-fi
-CPPFLAGS="$SAVE_CPPFLAGS"
-LDFLAGS="$SAVE_LDFLAGS"
 # }}}
 
 # --with-java {{{
@@ -2038,21 +2203,21 @@ then
 fi
 if test "x$with_libmodbus" = "xuse_pkgconfig"
 then
-       AC_MSG_NOTICE([Checking for modbus using $PKG_CONFIG])
-       $PKG_CONFIG --exists 'modbus' 2>/dev/null
+       AC_MSG_NOTICE([Checking for libmodbus using $PKG_CONFIG])
+       $PKG_CONFIG --exists 'libmodbus' 2>/dev/null
        if test $? -ne 0
        then
-               with_libmodbus="no (pkg-config doesn't know library)"
+               with_libmodbus="no (pkg-config doesn't know libmodbus)"
        fi
 fi
 if test "x$with_libmodbus" = "xuse_pkgconfig"
 then
-       with_libmodbus_cflags="`$PKG_CONFIG --cflags 'modbus'`"
+       with_libmodbus_cflags="`$PKG_CONFIG --cflags 'libmodbus'`"
        if test $? -ne 0
        then
                with_libmodbus="no ($PKG_CONFIG failed)"
        fi
-       with_libmodbus_libs="`$PKG_CONFIG --libs 'modbus'`"
+       with_libmodbus_libs="`$PKG_CONFIG --libs 'libmodbus'`"
        if test $? -ne 0
        then
                with_libmodbus="no ($PKG_CONFIG failed)"
@@ -2082,9 +2247,9 @@ then
        CPPFLAGS="$CPPFLAGS $with_libmodbus_cflags"
        LDFLAGS="$LDFLAGS $with_libmodbus_libs"
 
-       AC_CHECK_LIB(modbus, modbus_init_tcp,
+       AC_CHECK_LIB(modbus, modbus_connect,
                     [with_libmodbus="yes"],
-                    [with_libmodbus="no (symbol modbus_init_tcp not found)"])
+                    [with_libmodbus="no (symbol modbus_connect not found)"])
 
        CPPFLAGS="$SAVE_CPPFLAGS"
        LDFLAGS="$SAVE_LDFLAGS"
@@ -2098,6 +2263,69 @@ then
 fi
 # }}}
 
+# --with-libmongoc {{{
+AC_ARG_WITH(libmongoc, [AS_HELP_STRING([--with-libmongoc@<:@=PREFIX@:>@], [Path to libmongoc.])],
+[
+ if test "x$withval" = "xyes"
+ then
+        with_libmongoc="yes"
+ else if test "x$withval" = "xno"
+ then
+        with_libmongoc="no"
+ else
+        with_libmongoc="yes"
+        LIBMONGOC_CPPFLAGS="$LIBMONGOC_CPPFLAGS -I$withval/include"
+        LIBMONGOC_LDFLAGS="$LIBMONGOC_LDFLAGS -L$withval/lib"
+ fi; fi
+],
+[with_libmongoc="yes"])
+
+SAVE_CPPFLAGS="$CPPFLAGS"
+SAVE_LDFLAGS="$LDFLAGS"
+
+CPPFLAGS="$CPPFLAGS $LIBMONGOC_CPPFLAGS"
+LDFLAGS="$LDFLAGS $LIBMONGOC_LDFLAGS"
+
+if test "x$with_libmongoc" = "xyes"
+then
+       if test "x$LIBMONGOC_CPPFLAGS" != "x"
+       then
+               AC_MSG_NOTICE([libmongoc CPPFLAGS: $LIBMONGOC_CPPFLAGS])
+       fi
+       AC_CHECK_HEADERS(mongo.h,
+       [with_libmongoc="yes"],
+       [with_libmongoc="no ('mongo.h' not found)"],
+[#if HAVE_STDINT_H
+# define MONGO_HAVE_STDINT 1
+#else
+# define MONGO_USE_LONG_LONG_INT 1
+#endif
+])
+fi
+if test "x$with_libmongoc" = "xyes"
+then
+       if test "x$LIBMONGOC_LDFLAGS" != "x"
+       then
+               AC_MSG_NOTICE([libmongoc LDFLAGS: $LIBMONGOC_LDFLAGS])
+       fi
+       AC_CHECK_LIB(mongoc, mongo_run_command,
+       [with_libmongoc="yes"],
+       [with_libmongoc="no (symbol 'mongo_run_command' not found)"])
+fi
+
+CPPFLAGS="$SAVE_CPPFLAGS"
+LDFLAGS="$SAVE_LDFLAGS"
+
+if test "x$with_libmongoc" = "xyes"
+then
+       BUILD_WITH_LIBMONGOC_CPPFLAGS="$LIBMONGOC_CPPFLAGS"
+       BUILD_WITH_LIBMONGOC_LDFLAGS="$LIBMONGOC_LDFLAGS"
+       AC_SUBST(BUILD_WITH_LIBMONGOC_CPPFLAGS)
+       AC_SUBST(BUILD_WITH_LIBMONGOC_LDFLAGS)
+fi
+AM_CONDITIONAL(BUILD_WITH_LIBMONGOC, test "x$with_libmongoc" = "xyes")
+# }}}
+
 # --with-libmysql {{{
 with_mysql_config="mysql_config"
 with_mysql_cflags=""
@@ -2155,7 +2383,7 @@ then
 fi
 if test "x$with_libmysql" = "xyes"
 then
-       with_mysql_libs=`$with_mysql_config --libs 2>/dev/null`
+       with_mysql_libs=`$with_mysql_config --libs_r 2>/dev/null`
        mysql_config_status=$?
 
        if test $mysql_config_status -ne 0
@@ -2238,21 +2466,20 @@ then
 #include <asm/types.h>
 #include <sys/socket.h>])
 
-       AC_COMPILE_IFELSE(
-[#include <stdio.h>
-#include <sys/types.h>
-#include <asm/types.h>
-#include <sys/socket.h>
-#include <linux/netlink.h>
-#include <linux/rtnetlink.h>
-
-int main (void)
-{
-       int retval = TCA_STATS2;
-       return (retval);
-}],
-       [AC_DEFINE([HAVE_TCA_STATS2], 1, [True if the enum-member TCA_STATS2 exists])]
-       []);
+        AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+                           [
+                            #include <stdio.h>
+                            #include <sys/types.h>
+                            #include <asm/types.h>
+                            #include <sys/socket.h>
+                            #include <linux/netlink.h>
+                            #include <linux/rtnetlink.h>
+                            ], [
+                                int retval = TCA_STATS2;
+                                return (retval);
+                                ]
+                            )],
+                            [AC_DEFINE([HAVE_TCA_STATS2], [1], [True if the enum-member TCA_STATS2 exists])])
 
        AC_COMPILE_IFELSE(
 [#include <stdio.h>
@@ -2281,6 +2508,76 @@ then
 fi
 if test "x$with_libnetlink" = "xyes"
 then
+       SAVE_CFLAGS="$CFLAGS"
+       CFLAGS="$CFLAGS $with_libnetlink_cflags"
+
+       AC_CACHE_CHECK(
+               [if function 'rtnl_dump_filter' expects five arguments],
+               [c_cv_rtnl_dump_filter_five_args],
+               AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+                               [
+AC_INCLUDES_DEFAULT
+#include <asm/types.h>
+#include <sys/socket.h>
+#if HAVE_LIBNETLINK_H
+# include <libnetlink.h>
+#elif HAVE_IPROUTE_LIBNETLINK_H
+# include <iproute/libnetlink.h>
+#elif HAVE_LINUX_LIBNETLINK_H
+# include <linux/libnetlink.h>
+#endif
+                               ],
+                               [
+if (rtnl_dump_filter(NULL, NULL, NULL, NULL, NULL))
+       return 1;
+return 0;
+                               ]
+                       )],
+                       [c_cv_rtnl_dump_filter_five_args="yes"],
+                       [c_cv_rtnl_dump_filter_five_args="no"]
+               )
+       )
+
+       AC_CACHE_CHECK(
+               [if function 'rtnl_dump_filter' expects three arguments],
+               [c_cv_rtnl_dump_filter_three_args],
+               AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+                               [
+AC_INCLUDES_DEFAULT
+#include <asm/types.h>
+#include <sys/socket.h>
+#if HAVE_LIBNETLINK_H
+# include <libnetlink.h>
+#elif HAVE_IPROUTE_LIBNETLINK_H
+# include <iproute/libnetlink.h>
+#elif HAVE_LINUX_LIBNETLINK_H
+# include <linux/libnetlink.h>
+#endif
+                               ],
+                               [
+if (rtnl_dump_filter(NULL, NULL, NULL))
+       return 1;
+return 0;
+                               ]
+                       )],
+                       [c_cv_rtnl_dump_filter_three_args="yes"],
+                       [c_cv_rtnl_dump_filter_three_args="no"]
+               )
+       )
+
+       CFLAGS="$SAVE_CFLAGS"
+
+       if test "x$c_cv_rtnl_dump_filter_five_args" = "xyes"
+       then
+               AC_DEFINE(RTNL_DUMP_FILTER_FIVE_ARGS, 1,
+                               [Define to 1 if function 'rtnl_dump_filter' expects five arguments.])
+       fi
+       if test "x$c_cv_rtnl_dump_filter_three_args" = "xyes"
+       then
+               AC_DEFINE(RTNL_DUMP_FILTER_THREE_ARGS, 1,
+                               [Define to 1 if function 'rtnl_dump_filter' expects three arguments.])
+       fi
+
        BUILD_WITH_LIBNETLINK_CFLAGS="$with_libnetlink_cflags"
        BUILD_WITH_LIBNETLINK_LIBS="$with_libnetlink_libs"
        AC_SUBST(BUILD_WITH_LIBNETLINK_CFLAGS)
@@ -2507,7 +2804,7 @@ then
        fi
        AC_CHECK_HEADERS(oping.h,
        [with_liboping="yes"],
-       [with_liboping="no ('oping.h' not found)"])
+       [with_liboping="no (oping.h not found)"])
 fi
 if test "x$with_liboping" = "xyes"
 then
@@ -2673,19 +2970,14 @@ then
 fi
 if test "x$with_libpcap" = "xyes"
 then
-       AC_CHECK_HEADERS(pcap.h,
-       [
-               AC_DEFINE(HAVE_PCAP_H, 1, [Define to 1 if you have the <pcap.h> header file.])
-       ], [with_libpcap="no (pcap.h not found)"])
+       AC_CHECK_HEADERS(pcap.h,,
+                        [with_libpcap="no (pcap.h not found)"])
 fi
 if test "x$with_libpcap" = "xyes"
 then
-       collect_libpcap=1
-else
-       collect_libpcap=0
+       AC_CHECK_HEADERS(pcap-bpf.h,,
+                        [with_libpcap="no (pcap-bpf.h not found)"])
 fi
-AC_DEFINE_UNQUOTED(COLLECT_LIBPCAP, [$collect_libpcap],
-       [Wether or not to use the pcap library])
 AM_CONDITIONAL(BUILD_WITH_LIBPCAP, test "x$with_libpcap" = "xyes")
 # }}}
 
@@ -2693,7 +2985,7 @@ AM_CONDITIONAL(BUILD_WITH_LIBPCAP, test "x$with_libpcap" = "xyes")
 perl_interpreter="perl"
 AC_ARG_WITH(libperl, [AS_HELP_STRING([--with-libperl@<:@=PREFIX@:>@], [Path to libperl.])],
 [
-       if test -x "$withval"
+       if test -f "$withval" && test -x "$withval"
        then
                perl_interpreter="$withval"
                with_libperl="yes"
@@ -3136,26 +3428,39 @@ AC_ARG_WITH(librabbitmq, [AS_HELP_STRING([--with-librabbitmq@<:@=PREFIX@:>@], [P
 [
        with_librabbitmq="yes"
 ])
+SAVE_CPPFLAGS="$CPPFLAGS"
+SAVE_LDFLAGS="$LDFLAGS"
+CPPFLAGS="$CPPFLAGS $with_librabbitmq_cppflags"
+LDFLAGS="$LDFLAGS $with_librabbitmq_ldflags"
 if test "x$with_librabbitmq" = "xyes"
 then
-       SAVE_CPPFLAGS="$CPPFLAGS"
-       CPPFLAGS="$CPPFLAGS $with_librabbitmq_cppflags"
-
        AC_CHECK_HEADERS(amqp.h, [with_librabbitmq="yes"], [with_librabbitmq="no (amqp.h not found)"])
-
-       CPPFLAGS="$SAVE_CPPFLAGS"
 fi
 if test "x$with_librabbitmq" = "xyes"
 then
-       SAVE_CPPFLAGS="$CPPFLAGS"
-       SAVE_LDFLAGS="$LDFLAGS"
-       CPPFLAGS="$CPPFLAGS $with_librabbitmq_cppflags"
-       LDFLAGS="$LDFLAGS $with_librabbitmq_ldflags"
-
+       # librabbitmq up to version 0.9.1 provides "library_errno", later
+       # versions use "library_error". The library does not provide a version
+       # macro :( Use "AC_CHECK_MEMBERS" (plural) for automatic defines.
+       AC_CHECK_MEMBERS([amqp_rpc_reply_t.library_errno],,,
+                        [
+#if HAVE_STDLIB_H
+# include <stdlib.h>
+#endif
+#if HAVE_STDIO_H
+# include <stdio.h>
+#endif
+#if HAVE_STDINT_H
+# include <stdint.h>
+#endif
+#if HAVE_INTTYPES_H
+# include <inttypes.h>
+#endif
+#include <amqp.h>
+                         ])
+fi
+if test "x$with_librabbitmq" = "xyes"
+then
        AC_CHECK_LIB(rabbitmq, amqp_basic_publish, [with_librabbitmq="yes"], [with_librabbitmq="no (Symbol 'amqp_basic_publish' not found)"])
-
-       CPPFLAGS="$SAVE_CPPFLAGS"
-       LDFLAGS="$SAVE_LDFLAGS"
 fi
 if test "x$with_librabbitmq" = "xyes"
 then
@@ -3167,6 +3472,8 @@ then
        AC_SUBST(BUILD_WITH_LIBRABBITMQ_LIBS)
        AC_DEFINE(HAVE_LIBRABBITMQ, 1, [Define if librabbitmq is present and usable.])
 fi
+CPPFLAGS="$SAVE_CPPFLAGS"
+LDFLAGS="$SAVE_LDFLAGS"
 AM_CONDITIONAL(BUILD_WITH_LIBRABBITMQ, test "x$with_librabbitmq" = "xyes")
 # }}}
 
@@ -3201,7 +3508,7 @@ then
        fi
        AC_CHECK_HEADERS(routeros_api.h,
        [with_librouteros="yes"],
-       [with_librouteros="no ('routeros_api.h' not found)"])
+       [with_librouteros="no (routeros_api.h not found)"])
 fi
 if test "x$with_librouteros" = "xyes"
 then
@@ -3400,7 +3707,7 @@ then
     if test "$?" != "0"
     then
       with_libstatgrab_pkg_config="no"
-      with_libstatgrab="no ($PKG_CONFIG doesn't know libstatgrab)"
+      with_libstatgrab="no (pkg-config doesn't know libstatgrab)"
       temp_result="not found"
     fi
     AC_MSG_RESULT([$temp_result])
@@ -3559,7 +3866,7 @@ AM_CONDITIONAL(BUILD_WITH_LIBTOKYOTYRANT, test "x$with_libtokyotyrant" = "xyes")
 with_libupsclient_config=""
 with_libupsclient_cflags=""
 with_libupsclient_libs=""
-AC_ARG_WITH(libupsclient, [AS_HELP_STRING([--with-libupsclient@<:@=PREFIX@:>@], [Path to the Net-SNMPD library.])],
+AC_ARG_WITH(libupsclient, [AS_HELP_STRING([--with-libupsclient@<:@=PREFIX@:>@], [Path to the upsclient library.])],
 [
        if test "x$withval" = "xno"
        then
@@ -3620,7 +3927,7 @@ then
        $PKG_CONFIG --exists 'libupsclient' 2>/dev/null
        if test $? -ne 0
        then
-               with_libupsclient="no (pkg-config doesn't know library)"
+               with_libupsclient="no (pkg-config doesn't know libupsclient)"
        fi
 fi
 if test "x$with_libupsclient" = "xuse_pkgconfig"
@@ -3781,6 +4088,7 @@ then
        CPPFLAGS="$CPPFLAGS $with_libyajl_cppflags"
 
        AC_CHECK_HEADERS(yajl/yajl_parse.h, [with_libyajl="yes"], [with_libyajl="no (yajl/yajl_parse.h not found)"])
+       AC_CHECK_HEADERS(yajl/yajl_version.h)
 
        CPPFLAGS="$SAVE_CPPFLAGS"
 fi
@@ -3825,7 +4133,7 @@ AC_ARG_WITH(libvarnish, [AS_HELP_STRING([--with-libvarnish@<:@=PREFIX@:>@], [Pat
        then
                AC_MSG_NOTICE([Not checking for libvarnish: Manually configured])
                with_libvarnish_cflags="-I$withval/include"
-               with_libvarnish_libs="-L$withval/lib -lvarnish -lvarnishcompat -lvarnishapi"
+               with_libvarnish_libs="-L$withval/lib -lvarnishapi"
                with_libvarnish="yes"
        fi; fi; fi
 ],
@@ -3845,7 +4153,7 @@ then
        $PKG_CONFIG --exists 'varnishapi' 2>/dev/null
        if test $? -ne 0
        then
-               with_libvarnish="no (pkg-config doesn't know library)"
+               with_libvarnish="no (pkg-config doesn't know varnishapi)"
        fi
 fi
 if test "x$with_libvarnish" = "xuse_pkgconfig"
@@ -3884,10 +4192,9 @@ then
        CPPFLAGS="$CPPFLAGS $with_libvarnish_cflags"
        #LDFLAGS="$LDFLAGS $with_libvarnish_libs"
 
-       AC_CHECK_LIB(varnishapi, VSL_OpenStats,
-                    [with_libvarnish="yes"],
-                    [with_libvarnish="no (symbol VSL_OpenStats not found)"],
-                    [$with_libvarnish_libs])
+    AC_CHECK_HEADERS(varnish/vsc.h,
+        [AC_DEFINE([HAVE_VARNISH_V3], [1], [Varnish 3 API support])],
+        [AC_DEFINE([HAVE_VARNISH_V2], [1], [Varnish 2 API support])])
 
        CPPFLAGS="$SAVE_CPPFLAGS"
        #LDFLAGS="$SAVE_LDFLAGS"
@@ -3915,7 +4222,7 @@ then
        then
                with_libxml2="yes"
        else
-               with_libxml2="no (pkg-config doesn't know library)"
+               with_libxml2="no (pkg-config doesn't know libxml-2.0)"
        fi
 
        pkg-config --exists libvirt 2>/dev/null
@@ -3923,7 +4230,7 @@ then
        then
                with_libvirt="yes"
        else
-               with_libvirt="no (pkg-config doesn't know library)"
+               with_libvirt="no (pkg-config doesn't know libvirt)"
        fi
 fi
 if test "x$with_libxml2" = "xyes"
@@ -4040,7 +4347,7 @@ then
        $PKG_CONFIG --exists OpenIPMIpthread 2>/dev/null
        if test "$?" != "0"
        then
-               with_libopenipmipthread="no ($PKG_CONFIG doesn't know OpenIPMIpthread)"
+               with_libopenipmipthread="no (pkg-config doesn't know OpenIPMIpthread)"
        fi
        AC_MSG_RESULT([$with_libopenipmipthread])
 fi
@@ -4101,7 +4408,11 @@ fi
 
 PKG_CHECK_MODULES([LIBNOTIFY], [libnotify],
                [with_libnotify="yes"],
-               [with_libnotify="no ($LIBNOTIFY_PKG_ERRORS)"])
+               [if test "x$LIBNOTIFY_PKG_ERRORS" = "x"; then
+                        with_libnotify="no"
+                else
+                        with_libnotify="no ($LIBNOTIFY_PKG_ERRORS)"
+                fi])
 
 # Check for enabled/disabled features
 #
@@ -4241,6 +4552,8 @@ plugin_curl_xml="no"
 plugin_df="no"
 plugin_disk="no"
 plugin_entropy="no"
+plugin_ethstat="no"
+plugin_fscache="no"
 plugin_interface="no"
 plugin_ipmi="no"
 plugin_ipvs="no"
@@ -4250,7 +4563,7 @@ plugin_load="no"
 plugin_memory="no"
 plugin_multimeter="no"
 plugin_nfs="no"
-plugin_fscache="no"
+plugin_numa="no"
 plugin_perl="no"
 plugin_processes="no"
 plugin_protocols="no"
@@ -4277,12 +4590,13 @@ then
        plugin_cpufreq="yes"
        plugin_disk="yes"
        plugin_entropy="yes"
+       plugin_fscache="yes"
        plugin_interface="yes"
        plugin_irq="yes"
        plugin_load="yes"
        plugin_memory="yes"
        plugin_nfs="yes"
-       plugin_fscache="yes"
+       plugin_numa="yes"
        plugin_processes="yes"
        plugin_protocols="yes"
        plugin_serial="yes"
@@ -4294,7 +4608,7 @@ then
        plugin_vserver="yes"
        plugin_wireless="yes"
 
-       if test "x$have_net_ip_vs_h" = "xyes" || test "x$have_ip_vs_h" = "xyes"
+       if test "x$have_linux_ip_vs_h" = "xyes" || test "x$have_net_ip_vs_h" = "xyes" || test "x$have_ip_vs_h" = "xyes"
        then
                plugin_ipvs="yes"
        fi
@@ -4313,14 +4627,22 @@ then
 fi
 
 # AIX
+
+if test "x$ac_system" = "xAIX"
+then
+        plugin_tcpconns="yes"
+fi
+
 if test "x$with_perfstat" = "xyes"
 then
        plugin_cpu="yes"
+       plugin_contextswitch="yes"
        plugin_disk="yes"
        plugin_memory="yes"
        plugin_swap="yes"
        plugin_interface="yes"
        plugin_load="yes"
+       plugin_uptime="yes"
 fi
 
 if test "x$with_procinfo" = "xyes"
@@ -4331,6 +4653,7 @@ fi
 # Solaris
 if test "x$with_kstat" = "xyes"
 then
+       plugin_nfs="yes"
        plugin_uptime="yes"
        plugin_zfs_arc="yes"
 fi
@@ -4344,11 +4667,6 @@ then
        plugin_tape="yes"
 fi
 
-if test "x$have_sys_swap_h$with_kstat$ac_system" = "xyesyesSolaris"
-then
-       plugin_swap="yes"
-fi
-
 # libstatgrab
 if test "x$with_libstatgrab" = "xyes"
 then
@@ -4364,7 +4682,10 @@ fi
 if test "x$with_libcurl" = "xyes" && test "x$with_libxml2" = "xyes"
 then
        plugin_ascent="yes"
-       plugin_bind="yes"
+       if test "x$have_strptime" = "xyes"
+       then
+               plugin_bind="yes"
+       fi
 fi
 
 if test "x$with_libopenipmipthread" = "xyes"
@@ -4390,8 +4711,11 @@ if test "x$have_sysctl" = "xyes"
 then
        plugin_cpu="yes"
        plugin_memory="yes"
-       plugin_swap="yes"
        plugin_uptime="yes"
+       if test "x$ac_system" = "xDarwin"
+       then
+               plugin_swap="yes"
+       fi
 fi
 if test "x$have_sysctlbyname" = "xyes"
 then
@@ -4436,6 +4760,11 @@ then
        fi
 fi
 
+if test "x$have_linux_sockios_h$have_linux_ethtool_h" = "xyesyes"
+then
+       plugin_ethstat="yes"
+fi
+
 if test "x$have_getifaddrs" = "xyes"
 then
        plugin_interface="yes"
@@ -4483,7 +4812,7 @@ then
        plugin_swap="yes"
 fi
 
-if test "x$have_swapctl" = "xyes"
+if test "x$have_swapctl" = "xyes" && test "x$c_cv_have_swapctl_two_args" = "xyes"
 then
        plugin_swap="yes"
 fi
@@ -4523,6 +4852,7 @@ AC_ARG_ENABLE([all-plugins],
 
 m4_divert_once([HELP_ENABLE], [])
 
+AC_PLUGIN([aggregation], [yes],                [Aggregation plugin])
 AC_PLUGIN([amqp],        [$with_librabbitmq],  [AMQP output plugin])
 AC_PLUGIN([apache],      [$with_libcurl],      [Apache httpd statistics])
 AC_PLUGIN([apcups],      [yes],                [Statistics of UPSes by APC])
@@ -4544,6 +4874,7 @@ AC_PLUGIN([disk],        [$plugin_disk],       [Disk usage statistics])
 AC_PLUGIN([dns],         [$with_libpcap],      [DNS traffic analysis])
 AC_PLUGIN([email],       [yes],                [EMail statistics])
 AC_PLUGIN([entropy],     [$plugin_entropy],    [Entropy statistics])
+AC_PLUGIN([ethstat],     [$plugin_ethstat],    [Stats from NIC driver])
 AC_PLUGIN([exec],        [yes],                [Execution of external programs])
 AC_PLUGIN([filecount],   [yes],                [Count files in directories])
 AC_PLUGIN([fscache],     [$plugin_fscache],    [fscache statistics])
@@ -4566,6 +4897,7 @@ AC_PLUGIN([match_regex], [yes],                [The regex match])
 AC_PLUGIN([match_timediff], [yes],             [The timediff match])
 AC_PLUGIN([match_value], [yes],                [The value match])
 AC_PLUGIN([mbmon],       [yes],                [Query mbmond])
+AC_PLUGIN([md],          [$have_linux_raid_md_u_h], [md (Linux software RAID) devices])
 AC_PLUGIN([memcachec],   [$with_libmemcached], [memcachec statistics])
 AC_PLUGIN([memcached],   [yes],                [memcached statistics])
 AC_PLUGIN([memory],      [$plugin_memory],     [Memory usage])
@@ -4580,6 +4912,7 @@ AC_PLUGIN([nginx],       [$with_libcurl],      [nginx statistics])
 AC_PLUGIN([notify_desktop], [$with_libnotify], [Desktop notifications])
 AC_PLUGIN([notify_email], [$with_libesmtp],    [Email notifier])
 AC_PLUGIN([ntpd],        [yes],                [NTPd statistics])
+AC_PLUGIN([numa],        [$plugin_numa],       [NUMA virtual memory statistics])
 AC_PLUGIN([nut],         [$with_libupsclient], [Network UPS tools statistics])
 AC_PLUGIN([olsrd],       [yes],                [olsrd statistics])
 AC_PLUGIN([onewire],     [$with_libowcapi],    [OneWire sensor statistics])
@@ -4615,6 +4948,7 @@ AC_PLUGIN([tcpconns],    [$plugin_tcpconns],   [TCP connection statistics])
 AC_PLUGIN([teamspeak2],  [yes],                [TeamSpeak2 server statistics])
 AC_PLUGIN([ted],         [$plugin_ted],        [Read The Energy Detective values])
 AC_PLUGIN([thermal],     [$plugin_thermal],    [Linux ACPI thermal zone statistics])
+AC_PLUGIN([threshold],   [yes],                [Threshold checking plugin])
 AC_PLUGIN([tokyotyrant], [$with_libtokyotyrant],  [TokyoTyrant database statistics])
 AC_PLUGIN([unixsock],    [yes],                [Unixsock communication plugin])
 AC_PLUGIN([uptime],      [$plugin_uptime],     [Uptime statistics])
@@ -4624,8 +4958,10 @@ AC_PLUGIN([varnish],     [$with_libvarnish],   [Varnish cache statistics])
 AC_PLUGIN([vmem],        [$plugin_vmem],       [Virtual memory statistics])
 AC_PLUGIN([vserver],     [$plugin_vserver],    [Linux VServer statistics])
 AC_PLUGIN([wireless],    [$plugin_wireless],   [Wireless statistics])
+AC_PLUGIN([write_graphite], [yes],             [Graphite / Carbon output plugin])
 AC_PLUGIN([write_http],  [$with_libcurl],      [HTTP output plugin])
 AC_PLUGIN([write_redis], [$with_libcredis],    [Redis output plugin])
+AC_PLUGIN([write_mongodb], [$with_libmongoc],  [MongoDB output plugin])
 AC_PLUGIN([xmms],        [$with_libxmms],      [XMMS statistics])
 AC_PLUGIN([zfs_arc],     [$plugin_zfs_arc],    [ZFS ARC statistics])
 
@@ -4711,11 +5047,16 @@ AC_SUBST(LOAD_PLUGIN_CSV)
 
 dnl ip_vs.h
 if test "x$ac_system" = "xLinux" \
-       && test "x$have_net_ip_vs_h$have_ip_vs_h" = "xnono"
+       && test "x$have_linux_ip_vs_h$have_net_ip_vs_h$have_ip_vs_h" = "xnonono"
 then
        enable_ipvs="$enable_ipvs (ip_vs.h not found)"
 fi
 
+if test "x$ip_vs_h_needs_kernel_cflags" = "xyes"
+then
+       enable_ipvs="$enable_ipvs (needs $KERNEL_CFLAGS)"
+fi
+
 dnl Perl bindings
 AC_ARG_WITH(perl-bindings, [AS_HELP_STRING([--with-perl-bindings@<:@=OPTIONS@:>@], [Options passed to "perl Makefile.PL".])],
 [
@@ -4763,7 +5104,7 @@ AC_SUBST(LCC_VERSION_STRING)
 
 AC_CONFIG_FILES(src/libcollectdclient/collectd/lcc_features.h)
 
-AC_OUTPUT(Makefile src/Makefile src/collectd.conf src/owniptc/Makefile src/libcollectdclient/Makefile src/libcollectdclient/libcollectdclient.pc src/liboconfig/Makefile bindings/Makefile bindings/java/Makefile)
+AC_OUTPUT(Makefile src/Makefile src/collectd.conf src/libcollectdclient/Makefile src/libcollectdclient/libcollectdclient.pc src/liboconfig/Makefile bindings/Makefile bindings/java/Makefile)
 
 if test "x$with_librrd" = "xyes" \
        && test "x$librrd_threadsafe" != "xyes"
@@ -4771,11 +5112,6 @@ then
        with_librrd="yes (warning: librrd is not thread-safe)"
 fi
 
-if test "x$with_libiptc" = "xyes" && test "x$with_own_libiptc" = "xyes"
-then
-       with_libiptc="yes (shipped version)"
-fi
-
 if test "x$with_libperl" = "xyes"
 then
        with_libperl="yes (version `$perl_interpreter -MConfig -e 'print $Config{version};'`)"
@@ -4849,6 +5185,7 @@ Configuration:
     perl  . . . . . . . . $with_perl_bindings
 
   Modules:
+    aggregation . . . . . $enable_aggregation
     amqp    . . . . . . . $enable_amqp
     apache  . . . . . . . $enable_apache
     apcups  . . . . . . . $enable_apcups
@@ -4870,6 +5207,7 @@ Configuration:
     dns . . . . . . . . . $enable_dns
     email . . . . . . . . $enable_email
     entropy . . . . . . . $enable_entropy
+    ethstat . . . . . . . $enable_ethstat
     exec  . . . . . . . . $enable_exec
     filecount . . . . . . $enable_filecount
     fscache . . . . . . . $enable_fscache
@@ -4892,6 +5230,7 @@ Configuration:
     match_timediff  . . . $enable_match_timediff
     match_value . . . . . $enable_match_value
     mbmon . . . . . . . . $enable_mbmon
+    md  . . . . . . . . . $enable_md
     memcachec . . . . . . $enable_memcachec
     memcached . . . . . . $enable_memcached
     memory  . . . . . . . $enable_memory
@@ -4906,6 +5245,7 @@ Configuration:
     notify_desktop  . . . $enable_notify_desktop
     notify_email  . . . . $enable_notify_email
     ntpd  . . . . . . . . $enable_ntpd
+    numa  . . . . . . . . $enable_numa
     nut . . . . . . . . . $enable_nut
     olsrd . . . . . . . . $enable_olsrd
     onewire . . . . . . . $enable_onewire
@@ -4940,6 +5280,7 @@ Configuration:
     teamspeak2  . . . . . $enable_teamspeak2
     ted . . . . . . . . . $enable_ted
     thermal . . . . . . . $enable_thermal
+    threshold . . . . . . $enable_threshold
     tokyotyrant . . . . . $enable_tokyotyrant
     unixsock  . . . . . . $enable_unixsock
     uptime  . . . . . . . $enable_uptime
@@ -4949,8 +5290,10 @@ Configuration:
     vmem  . . . . . . . . $enable_vmem
     vserver . . . . . . . $enable_vserver
     wireless  . . . . . . $enable_wireless
+    write_graphite  . . . $enable_write_graphite
     write_http  . . . . . $enable_write_http
     write_redis . . . . . $enable_write_redis
+    write_mongodb . . . . $enable_write_mongodb
     xmms  . . . . . . . . $enable_xmms
     zfs_arc . . . . . . . $enable_zfs_arc
 
index bc1fe9f..1ebf1f1 100644 (file)
@@ -101,3 +101,8 @@ solaris-smf
 -----------
   Manifest file for the Solaris SMF system and detailed information on how to
 register collectd as a service with this system.
+
+collectd.service
+----------------
+  Service file for systemd. Please ship this file as
+  /lib/systemd/system/collectd.service in any linux package of collectd.
diff --git a/contrib/aix/collectd.spec b/contrib/aix/collectd.spec
new file mode 100644 (file)
index 0000000..c148d79
--- /dev/null
@@ -0,0 +1,75 @@
+
+%define name    collectd
+%define version 4.10.1
+%define release 1
+
+Name:           %{name}
+Summary:        Statistics collection daemon for filling RRD files.
+Version:        %{version}
+Release:        %{release}
+#Source:         http://collectd.org/files/%{name}-%{version}.tar.gz
+Source0:        %{name}-%{version}.tar.gz
+Group:          System Environment/Daemons
+BuildRoot:      %{_tmppath}/%{name}-%{version}-buildroot
+License:        GPL
+BuildPrereq:    rrdtool-devel,net-snmp-devel
+Requires:       rrdtool,net-snmp
+Packager:       Aurelien Reynaud <collectd@wattapower.net>
+Vendor:         collectd development team <collectd@verplant.org>
+
+%description
+collectd is a small daemon which collects system information periodically and
+provides mechanisms to monitor and store the values in a variety of ways. It
+is written in C for performance. Since the daemon doesn't need to startup
+every time it wants to update the values it's very fast and easy on the
+system. Also, the statistics are very fine grained since the files are updated
+every 10 seconds.
+
+%prep
+%setup
+
+%build
+# The RM variable in the RPM environment conflicts with that of the build environment,
+# at least when building on AIX 6.1. This is definitely a bug in one of the tools but
+# for now we work around it by unsetting the variable below.
+[ -n "$RM" ] && unset RM
+./configure LDFLAGS="-Wl,-brtl" --prefix=/opt/freeware --mandir=/opt/freeware/man --disable-dns --with-libnetsnmp=/opt/freeware/bin/net-snmp-config
+make
+
+%install
+make install DESTDIR=$RPM_BUILD_ROOT
+mkdir -p $RPM_BUILD_ROOT/%{_localstatedir}/lib/%{name}
+mkdir -p $RPM_BUILD_ROOT/%{_localstatedir}/run
+mkdir -p $RPM_BUILD_ROOT/etc/rc.d/init.d
+cp contrib/aix/init.d-collectd $RPM_BUILD_ROOT/etc/rc.d/init.d/collectd
+
+%clean
+[ "$RPM_BUILD_ROOT" != "/" ] && rm -rf "$RPM_BUILD_ROOT"
+
+%files
+%defattr(-,root,system)
+%doc AUTHORS COPYING ChangeLog INSTALL NEWS README
+%config(noreplace) %attr(0644,root,system) %{_sysconfdir}/collectd.conf
+%attr(0755,root,system) /etc/rc.d/init.d/collectd
+%attr(0755,root,system) %{_sbindir}/collectd
+%attr(0755,root,system) %{_bindir}/collectd-nagios
+%attr(0755,root,system) %{_sbindir}/collectdmon
+%attr(0644,root,system) %{_mandir}/man1/*
+%attr(0644,root,system) %{_mandir}/man5/*
+
+# client
+%attr(0644,root,system) %{_includedir}/%{name}/client.h
+%attr(0644,root,system) %{_includedir}/%{name}/lcc_features.h
+
+%attr(0644,root,system) %{_libdir}/libcollectdclient.*
+%attr(0644,root,system) %{_libdir}/pkgconfig/libcollectdclient.pc
+
+%attr(0444,root,system) %{_libdir}/%{name}/*.so
+%attr(0444,root,system) %{_libdir}/%{name}/*.a
+%attr(0444,root,system) %{_libdir}/%{name}/*.la
+
+%attr(0644,root,system) %{_datadir}/%{name}/types.db
+
+%dir %{_localstatedir}/lib/%{name}
+%dir %{_localstatedir}/run
+
diff --git a/contrib/aix/init.d-collectd b/contrib/aix/init.d-collectd
new file mode 100755 (executable)
index 0000000..d893153
--- /dev/null
@@ -0,0 +1,79 @@
+#!/bin/sh
+#
+# description: collectd startup script
+#
+# March 2010, Aurelien Reynaud <collectd@wattapower.net>
+#
+
+# Some plugins need libs in non-standard paths
+case `uname` in
+       SunOS)
+               LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/lib:/usr/local/ssl/lib"
+               export LD_LIBRARY_PATH
+               ;;
+       *)
+               ;;
+esac
+
+# Set umask
+umask 022
+
+COLLECTD_BIN=/opt/freeware/sbin/collectd
+PIDFILE=/opt/freeware/var/run/collectd.pid
+
+# Check for missing binaries (stale symlinks should not happen)
+if [ ! -x $COLLECTD_BIN ]; then
+       echo "$COLLECTD_BIN not installed"
+       [ "$1" = "stop" ] && exit 0
+       exit 5
+fi
+
+# Check for existence of needed config file and read it
+COLLECTD_CONFIG=/opt/freeware/etc/collectd.conf
+if [ ! -r $COLLECTD_CONFIG ]; then
+       echo "$COLLECTD_CONFIG not existing"
+       [ "$1" = "stop" ] && exit 0
+       exit 6
+fi
+
+case "$1" in
+    start)
+       if [ -r $PIDFILE ]; then
+           echo "collectd daemon is already running with PID `cat $PIDFILE`."
+           exit 1
+       fi
+       echo "Starting collectd..."
+
+       ## Start daemon
+       $COLLECTD_BIN
+       ;;
+    stop)
+       echo "Shutting down collectd daemon... "
+       ## Stop daemon.
+       if [ -r $PIDFILE ]; then
+           pid=`cat $PIDFILE`
+           kill -15 $pid
+           while ps -p $pid >/dev/null; do
+               sleep 1
+           done
+           rm -f $PIDFILE
+       fi
+       ;;
+    status)
+       if [ -r $PIDFILE ]; then
+           echo "collectd daemon is running with PID `cat $PIDFILE`."
+       else
+           echo "collectd daemon is not running."
+       fi
+       ;;
+    restart)
+       ## Stop the service and regardless of whether it was
+       ## running or not, start it again.
+       $0 stop
+       $0 start
+       ;;
+    *)
+       echo "Usage: $0 {start|stop|status|restart}"
+       exit 1
+       ;;
+esac
diff --git a/contrib/collectd.service b/contrib/collectd.service
new file mode 100644 (file)
index 0000000..ee4d596
--- /dev/null
@@ -0,0 +1,15 @@
+[Unit]
+Description=statistics collection daemon
+Documentation=man:collectd(1)
+After=local-fs.target network.target
+Requires=local-fs.target network.target
+
+[Service]
+ExecStart=/usr/sbin/collectd -C /etc/collectd/collectd.conf -f
+Restart=always
+RestartSec=10
+StandardOutput=syslog
+StandardError=syslog
+
+[Install]
+WantedBy=multi-user.target
index 445b183..9af0fb0 100644 (file)
@@ -4,19 +4,23 @@
 #
 # Copyright © 2009 Adrian Perez <aperez@igalia.com>
 #
-# Distributed under terms of the GPLv2 license.
+# Distributed under terms of the GPLv2 license or newer.
+# 
+# Frank Marien (frank@apsu.be) 6 Sep 2012
+# - quick fixes for 5.1 binary protocol
+# - updated to python 3
+# - fixed for larger packet sizes (possible on lo interface)
+# - fixed comment typo (decode_network_string decodes a string)
 
 """
 Collectd network protocol implementation.
 """
 
-import socket
-import struct
-
+import socket,struct,sys
 try:
-    from cStringIO import StringIO
+  from io import StringIO
 except ImportError:
-    from StringIO import StringIO
+  from cStringIO import StringIO
 
 from datetime import datetime
 from copy import deepcopy
@@ -31,17 +35,19 @@ DEFAULT_IPv4_GROUP = "239.192.74.66"
 DEFAULT_IPv6_GROUP = "ff18::efc0:4a42"
 """Default IPv6 multicast group"""
 
-
+HR_TIME_DIV = (2.0**30)
 
 # Message kinds
 TYPE_HOST            = 0x0000
 TYPE_TIME            = 0x0001
+TYPE_TIME_HR         = 0x0008
 TYPE_PLUGIN          = 0x0002
 TYPE_PLUGIN_INSTANCE = 0x0003
 TYPE_TYPE            = 0x0004
 TYPE_TYPE_INSTANCE   = 0x0005
 TYPE_VALUES          = 0x0006
 TYPE_INTERVAL        = 0x0007
+TYPE_INTERVAL_HR     = 0x0009
 
 # For notifications
 TYPE_MESSAGE         = 0x0100
@@ -50,14 +56,14 @@ TYPE_SEVERITY        = 0x0101
 # DS kinds
 DS_TYPE_COUNTER      = 0
 DS_TYPE_GAUGE        = 1
-
+DS_TYPE_DERIVE       = 2
+DS_TYPE_ABSOLUTE     = 3
 
 header = struct.Struct("!2H")
 number = struct.Struct("!Q")
 short  = struct.Struct("!H")
 double = struct.Struct("<d")
 
-
 def decode_network_values(ptype, plen, buf):
     """Decodes a list of DS values in collectd network format
     """
@@ -70,13 +76,19 @@ def decode_network_values(ptype, plen, buf):
     assert double.size == number.size
 
     result = []
-    for dstype in map(ord, buf[header.size+short.size:off]):
+    for dstype in buf[header.size+short.size:off]:
         if dstype == DS_TYPE_COUNTER:
             result.append((dstype, number.unpack_from(buf, off)[0]))
             off += valskip
         elif dstype == DS_TYPE_GAUGE:
             result.append((dstype, double.unpack_from(buf, off)[0]))
             off += valskip
+        elif dstype == DS_TYPE_DERIVE:
+            result.append((dstype, number.unpack_from(buf, off)[0]))
+            off += valskip
+        elif dstype == DS_TYPE_ABSOLUTE:
+            result.append((dstype, number.unpack_from(buf, off)[0]))
+            off += valskip
         else:
             raise ValueError("DS type %i unsupported" % dstype)
 
@@ -84,13 +96,13 @@ def decode_network_values(ptype, plen, buf):
 
 
 def decode_network_number(ptype, plen, buf):
-    """Decodes a number (64-bit unsigned) in collectd network format.
+    """Decodes a number (64-bit unsigned) from collectd network format.
     """
     return number.unpack_from(buf, header.size)[0]
 
 
 def decode_network_string(msgtype, plen, buf):
-    """Decodes a floating point number (64-bit) in collectd network format.
+    """Decodes a string from collectd network format.
     """
     return buf[header.size:plen-1]
 
@@ -99,7 +111,9 @@ def decode_network_string(msgtype, plen, buf):
 _decoders = {
     TYPE_VALUES         : decode_network_values,
     TYPE_TIME           : decode_network_number,
+    TYPE_TIME_HR        : decode_network_number,
     TYPE_INTERVAL       : decode_network_number,
+    TYPE_INTERVAL_HR    : decode_network_number,
     TYPE_HOST           : decode_network_string,
     TYPE_PLUGIN         : decode_network_string,
     TYPE_PLUGIN_INSTANCE: decode_network_string,
@@ -115,6 +129,7 @@ def decode_network_packet(buf):
     """
     off = 0
     blen = len(buf)
+
     while off < blen:
         ptype, plen = header.unpack_from(buf, off)
 
@@ -128,9 +143,6 @@ def decode_network_packet(buf):
         off += plen
 
 
-
-
-
 class Data(object):
     time = 0
     host = None
@@ -140,7 +152,7 @@ class Data(object):
     typeinstance = None
 
     def __init__(self, **kw):
-        [setattr(self, k, v) for k, v in kw.iteritems()]
+        [setattr(self, k, v) for k, v in kw.items()]
 
     @property
     def datetime(self):
@@ -150,19 +162,19 @@ class Data(object):
     def source(self):
         buf = StringIO()
         if self.host:
-            buf.write(self.host)
+            buf.write(str(self.host))
         if self.plugin:
             buf.write("/")
-            buf.write(self.plugin)
+            buf.write(str(self.plugin))
         if self.plugininstance:
             buf.write("/")
-            buf.write(self.plugininstance)
+            buf.write(str(self.plugininstance))
         if self.type:
             buf.write("/")
-            buf.write(self.type)
+            buf.write(str(self.type))
         if self.typeinstance:
             buf.write("/")
-            buf.write(self.typeinstance)
+            buf.write(str(self.typeinstance))
         return buf.getvalue()
 
     def __str__(self):
@@ -215,8 +227,12 @@ def interpret_opcodes(iterable):
     for kind, data in iterable:
         if kind == TYPE_TIME:
             vl.time = nt.time = data
+        elif kind == TYPE_TIME_HR:
+            vl.time = nt.time = data / HR_TIME_DIV
         elif kind == TYPE_INTERVAL:
             vl.interval = data
+        elif kind == TYPE_INTERVAL_HR:
+            vl.interval = data / HR_TIME_DIV
         elif kind == TYPE_HOST:
             vl.host = nt.host = data
         elif kind == TYPE_PLUGIN:
@@ -248,7 +264,7 @@ class Reader(object):
     host = None
     port = DEFAULT_PORT
 
-    BUFFER_SIZE = 1024
+    BUFFER_SIZE = 16384
 
 
     def __init__(self, host=None, port=DEFAULT_PORT, multicast=False):
@@ -311,8 +327,6 @@ class Reader(object):
         """
         if iterable is None:
             iterable = self.decode()
-        if isinstance(iterable, basestring):
+        if isinstance(iterable, str):
             iterable = self.decode(iterable)
         return interpret_opcodes(iterable)
-
-
index ebe040d..1b8e6b1 100644 (file)
@@ -68,8 +68,9 @@ class Collectd():
         """
         numvalues = self._cmd('GETTHRESHOLD "%s"' % identifier)
         lines = []
-        if numvalues:
-            lines = self._readlines(numvalues)
+        if not numvalues or numvalues < 0:
+            raise KeyError("Identifier '%s' not found" % identifier)
+        lines = self._readlines(numvalues)
         return lines
 
     def getval(self, identifier, flush_after=True):
@@ -83,8 +84,9 @@ class Collectd():
         """
         numvalues = self._cmd('GETVAL "%s"' % identifier)
         lines = []
-        if numvalues:
-            lines = self._readlines(numvalues)
+        if not numvalues or numvalues < 0:
+            raise KeyError("Identifier '%s' not found" % identifier)
+        lines = self._readlines(numvalues)
         if flush_after:
             self.flush(identifiers=[identifier])
         return lines
index 8a5bf85..2b3f2fe 100755 (executable)
@@ -1,14 +1,45 @@
 #!/usr/bin/perl
 
+# Copyright (C) 2008-2011  Florian Forster
+# Copyright (C) 2011       noris network AG
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; only version 2 of the License is applicable.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+#
+# Authors:
+#   Florian "octo" Forster <octo at collectd.org>
+
 use strict;
 use warnings;
-use lib ('../lib');
 use utf8;
+use vars (qw($BASE_DIR));
+
+BEGIN
+{
+  if (defined $ENV{'SCRIPT_FILENAME'})
+  {
+    if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$})
+    {
+      $::BASE_DIR = $1;
+      unshift (@::INC, "$::BASE_DIR/lib");
+    }
+  }
+}
 
-use FindBin ('$RealBin');
 use Carp (qw(confess cluck));
 use CGI (':cgi');
 use RRDs ();
+use File::Temp (':POSIX');
 
 use Collectd::Graph::Config (qw(gc_read_config gc_get_scalar));
 use Collectd::Graph::TypeLoader (qw(tl_load_type));
@@ -17,200 +48,287 @@ use Collectd::Graph::Common (qw(sanitize_type get_selected_files
       epoch_to_rfc1123 flush_files));
 use Collectd::Graph::Type ();
 
-our $Debug = param ('debug');
-our $Begin = param ('begin');
-our $End = param ('end');
-our $GraphWidth = param ('width');
-our $GraphHeight = param ('height');
-our $Index = param ('index') || 0;
-our $OutputFormat = 'PNG';
-our $ContentType = 'image/png';
-
-if (param ('format'))
+sub base_dir
 {
-  my $temp = param ('format') || '';
-  $temp = uc ($temp);
+  if (defined $::BASE_DIR)
+  {
+    return ($::BASE_DIR);
+  }
 
-  if ($temp =~ m/^(PNG|SVG|EPS|PDF)$/)
+  if (!defined ($ENV{'SCRIPT_FILENAME'}))
   {
-    $OutputFormat = $temp;
+    return;
+  }
 
-    if ($OutputFormat eq 'SVG') { $ContentType = 'image/svg+xml'; }
-    elsif ($OutputFormat eq 'EPS') { $ContentType = 'image/eps'; }
-    elsif ($OutputFormat eq 'PDF') { $ContentType = 'application/pdf'; }
+  if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$})
+  {
+    $::BASE_DIR = $1;
+    return ($::BASE_DIR);
   }
+
+  return;
 }
 
-if ($Debug)
+sub lib_dir
 {
-  print <<HTTP;
-Content-Type: text/plain
+  my $base = base_dir ();
 
-HTTP
+  if ($base)
+  {
+    return "$base/lib";
+  }
+  else
+  {
+    return "../lib";
+  }
 }
 
-gc_read_config ("$RealBin/../etc/collection.conf");
-
-if ($GraphWidth)
+sub sysconf_dir
 {
-  $GraphWidth =~ s/\D//g;
-}
+  my $base = base_dir ();
 
-if (!$GraphWidth)
-{
-  $GraphWidth = gc_get_scalar ('GraphWidth', 400);
+  if ($base)
+  {
+    return "$base/etc";
+  }
+  else
+  {
+    return "../etc";
+  }
 }
 
-if ($GraphHeight)
+sub init
 {
-  $GraphHeight =~ s/\D//g;
+  my $lib_dir = lib_dir ();
+  my $sysconf_dir = sysconf_dir ();
+
+  if (!grep { $lib_dir eq $_ } (@::INC))
+  {
+    unshift (@::INC, $lib_dir);
+  }
+
+  gc_read_config ("$sysconf_dir/collection.conf");
 }
 
-if (!$GraphHeight)
+sub main
 {
-  $GraphHeight = gc_get_scalar ('GraphHeight', 100);
-}
+  my $Begin = param ('begin');
+  my $End = param ('end');
+  my $GraphWidth = param ('width');
+  my $GraphHeight = param ('height');
+  my $Index = param ('index') || 0;
+  my $OutputFormat = 'PNG';
+  my $ContentType = 'image/png';
 
-{ # Sanitize begin and end times
-  $End ||= 0;
-  $Begin ||= 0;
+  init ();
 
-  if ($End =~ m/\D/)
+  if (param ('format'))
   {
-    $End = 0;
+    my $temp = param ('format') || '';
+    $temp = uc ($temp);
+
+    if ($temp =~ m/^(PNG|SVG|EPS|PDF)$/)
+    {
+      $OutputFormat = $temp;
+
+      if ($OutputFormat eq 'SVG') { $ContentType = 'image/svg+xml'; }
+      elsif ($OutputFormat eq 'EPS') { $ContentType = 'image/eps'; }
+      elsif ($OutputFormat eq 'PDF') { $ContentType = 'application/pdf'; }
+    }
   }
 
-  if (!$Begin || !($Begin =~ m/^-?([1-9][0-9]*)$/))
+  if (param ('debug'))
   {
-    $Begin = -86400;
+    print <<HTTP;
+Content-Type: text/plain
+
+HTTP
+    $ContentType = 'text/plain';
   }
 
-  if ($Begin < 0)
+  if ($GraphWidth)
   {
-    if ($End)
-    {
-      $Begin = $End + $Begin;
-    }
-    else
-    {
-      $Begin = time () + $Begin;
-    }
+    $GraphWidth =~ s/\D//g;
   }
 
-  if ($Begin < 0)
+  if (!$GraphWidth)
   {
-    $Begin = time () - 86400;
+    $GraphWidth = gc_get_scalar ('GraphWidth', 400);
   }
 
-  if (($End > 0) && ($Begin > $End))
+  if ($GraphHeight)
   {
-    my $temp = $End;
-    $End = $Begin;
-    $Begin = $temp;
+    $GraphHeight =~ s/\D//g;
   }
-}
 
-my $type = param ('type') or die;
-my $obj;
+  if (!$GraphHeight)
+  {
+    $GraphHeight = gc_get_scalar ('GraphHeight', 100);
+  }
 
-$obj = tl_load_type ($type);
-if (!$obj)
-{
-  confess ("tl_load_type ($type) failed");
-}
+  { # Sanitize begin and end times
+    $End ||= 0;
+    $Begin ||= 0;
 
-$type = ucfirst (lc ($type));
-$type =~ s/_([A-Za-z])/\U$1\E/g;
-$type = sanitize_type ($type);
+    if ($End =~ m/\D/)
+    {
+      $End = 0;
+    }
 
-my $files = get_selected_files ();
-if ($Debug)
-{
-  require Data::Dumper;
-  print STDOUT Data::Dumper->Dump ([$files], ['files']);
-}
-for (@$files)
-{
-  $obj->addFiles ($_);
-}
+    if (!$Begin || !($Begin =~ m/^-?([1-9][0-9]*)$/))
+    {
+      $Begin = -86400;
+    }
 
-my $expires = time ();
-# IF (End is `now')
-#    OR (Begin is before `now' AND End is after `now')
-if (($End == 0) || (($Begin <= $expires) && ($End >= $expires)))
-{
-  # 400 == width in pixels
-  my $timespan;
+    if ($Begin < 0)
+    {
+      if ($End)
+      {
+        $Begin = $End + $Begin;
+      }
+      else
+      {
+        $Begin = time () + $Begin;
+      }
+    }
+
+    if ($Begin < 0)
+    {
+      $Begin = time () - 86400;
+    }
+
+    if (($End > 0) && ($Begin > $End))
+    {
+      my $temp = $End;
+      $End = $Begin;
+      $Begin = $temp;
+    }
+  }
 
-  if ($End == 0)
+  my $type = param ('type') or die;
+  my $obj;
+
+  $obj = tl_load_type ($type);
+  if (!$obj)
   {
-    $timespan = $expires - $Begin;
+    confess ("tl_load_type ($type) failed");
   }
-  else
+
+  $type = ucfirst (lc ($type));
+  $type =~ s/_([A-Za-z])/\U$1\E/g;
+  $type = sanitize_type ($type);
+
+  my $files = get_selected_files ();
+  if (param ('debug'))
   {
-    $timespan = $End - $Begin;
+    require Data::Dumper;
+    print Data::Dumper->Dump ([$files], ['files']);
+  }
+  for (@$files)
+  {
+    $obj->addFiles ($_);
+  }
+
+  my $expires = time ();
+# IF (End is `now')
+#    OR (Begin is before `now' AND End is after `now')
+  if (($End == 0) || (($Begin <= $expires) && ($End >= $expires)))
+  {
+    # 400 == width in pixels
+    my $timespan;
+
+    if ($End == 0)
+    {
+      $timespan = $expires - $Begin;
+    }
+    else
+    {
+      $timespan = $End - $Begin;
+    }
+    $expires += int ($timespan / 400.0);
   }
-  $expires += int ($timespan / 400.0);
-}
 # IF (End is not `now')
 #    AND (End is before `now')
 # ==> Graph will never change again!
-elsif (($End > 0) && ($End < $expires))
-{
-  $expires += (366 * 86400);
-}
-elsif ($Begin > $expires)
-{
-  $expires = $Begin;
-}
+  elsif (($End > 0) && ($End < $expires))
+  {
+    $expires += (366 * 86400);
+  }
+  elsif ($Begin > $expires)
+  {
+    $expires = $Begin;
+  }
 
 # Send FLUSH command to the daemon if necessary and possible.
-flush_files ($files,
+  flush_files ($files,
     begin => $Begin,
     end => $End,
     addr => gc_get_scalar ('UnixSockAddr', undef),
     interval => gc_get_scalar ('Interval', 10));
 
-print STDOUT header (-Content_type => $ContentType,
-  -Last_Modified => epoch_to_rfc1123 ($obj->getLastModified ()),
-  -Expires => epoch_to_rfc1123 ($expires));
-
-if ($Debug)
-{
-  print "\$expires = $expires;\n";
-}
+  print header (-Content_type => $ContentType,
+    -Last_Modified => epoch_to_rfc1123 ($obj->getLastModified ()),
+    -Expires => epoch_to_rfc1123 ($expires));
 
-my $args = $obj->getRRDArgs (0 + $Index);
-
-if ($Debug)
-{
-  require Data::Dumper;
-  print STDOUT Data::Dumper->Dump ([$obj], ['obj']);
-  print STDOUT join (",\n", @$args) . "\n";
-  print STDOUT "Last-Modified: " . epoch_to_rfc1123 ($obj->getLastModified ()) . "\n";
-}
-else
-{
-  my @timesel = ();
+  if (param ('debug'))
+  {
+    print "\$expires = $expires;\n";
+  }
 
-  if ($End) # $Begin is always true
+  my $args = $obj->getRRDArgs (0 + $Index);
+  if (param ('debug'))
   {
-    @timesel = ('-s', $Begin, '-e', $End);
+    require Data::Dumper;
+    print Data::Dumper->Dump ([$obj], ['obj']);
+    print join (",\n", @$args) . "\n";
+    print "Last-Modified: " . epoch_to_rfc1123 ($obj->getLastModified ()) . "\n";
   }
   else
   {
-    @timesel = ('-s', $Begin); # End is implicitely `now'.
-  }
+    my @timesel = ();
+    my $tmpfile = tmpnam ();
+    my $status;
 
-  $| = 1;
-  RRDs::graph ('-', '-a', $OutputFormat, '--width', $GraphWidth, '--height', $GraphHeight, @timesel, @$args);
-  if (my $err = RRDs::error ())
-  {
-    print STDERR "RRDs::graph failed: $err\n";
-    exit (1);
+    if ($End) # $Begin is always true
+    {
+      @timesel = ('-s', $Begin, '-e', $End);
+    }
+    else
+    {
+      @timesel = ('-s', $Begin); # End is implicitely `now'.
+    }
+
+    if (-S "/var/run/rrdcached.sock" && -w "/var/run/rrdcached.sock")
+    {
+      $ENV{"RRDCACHED_ADDRESS"} = "/var/run/rrdcached.sock";
+    }
+    unlink ($tmpfile);
+    RRDs::graph ($tmpfile, '-a', $OutputFormat, '--width', $GraphWidth, '--height', $GraphHeight, @timesel, @$args);
+    if (my $err = RRDs::error ())
+    {
+      print STDERR "RRDs::graph failed: $err\n";
+      exit (1);
+    }
+
+    $status = open (IMG, '<', $tmpfile) or die ("open ($tmpfile): $!");
+    if (!$status)
+    {
+      print STDERR "graph.cgi: Unable to open temporary file \"$tmpfile\" for reading: $!\n";
+    }
+    else
+    {
+      local $/ = undef;
+      while (my $data = <IMG>)
+      {
+        print STDOUT $data;
+      }
+
+      close (IMG);
+      unlink ($tmpfile);
+    }
   }
-}
+} # sub main
 
-exit (0);
+main ();
 
 # vim: set shiftwidth=2 softtabstop=2 tabstop=8 :
index 85064b8..4723af9 100755 (executable)
@@ -1,6 +1,7 @@
 #!/usr/bin/perl
 
-# Copyright (C) 2008  Florian octo Forster <octo at verplant.org>
+# Copyright (C) 2008-2011  Florian Forster
+# Copyright (C) 2011       noris network AG
 #
 # This program is free software; you can redistribute it and/or modify it under
 # the terms of the GNU General Public License as published by the Free Software
 # You should have received a copy of the GNU General Public License along with
 # this program; if not, write to the Free Software Foundation, Inc.,
 # 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+#
+# Authors:
+#   Florian "octo" Forster <octo at collectd.org>
 
 use strict;
 use warnings;
-use lib ('../lib');
 use utf8;
+use vars (qw($BASE_DIR));
+
+BEGIN
+{
+  if (defined $ENV{'SCRIPT_FILENAME'})
+  {
+    if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$})
+    {
+      $::BASE_DIR = $1;
+      unshift (@::INC, "$::BASE_DIR/lib");
+    }
+  }
+}
 
 use Carp (qw(cluck confess));
-use FindBin ('$RealBin');
 use CGI (':cgi');
 use CGI::Carp ('fatalsToBrowser');
 use HTML::Entities ('encode_entities');
@@ -35,8 +50,6 @@ use Collectd::Graph::Common (qw(get_files_from_directory get_all_hosts
       get_plugin_selection flush_files));
 use Collectd::Graph::Type ();
 
-our $Debug = param ('debug') ? 1 : 0;
-
 our $TimeSpans =
 {
   Hour  =>        3600,
@@ -46,23 +59,90 @@ our $TimeSpans =
   Year  => 366 * 86400
 };
 
-my $action = param ('action') || 'list_hosts';
-our %Actions =
+my %Actions =
 (
   list_hosts => \&action_list_hosts,
   show_selection => \&action_show_selection
 );
 
-if (!exists ($Actions{$action}))
+sub base_dir
+{
+  if (defined $::BASE_DIR)
+  {
+    return ($::BASE_DIR);
+  }
+
+  if (!defined ($ENV{'SCRIPT_FILENAME'}))
+  {
+    return;
+  }
+
+  if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$})
+  {
+    $::BASE_DIR = $1;
+    return ($::BASE_DIR);
+  }
+
+  return;
+}
+
+sub lib_dir
 {
-  print STDERR "No such action: $action\n";
-  exit 1;
+  my $base = base_dir ();
+
+  if ($base)
+  {
+    return "$base/lib";
+  }
+  else
+  {
+    return "../lib";
+  }
 }
 
-gc_read_config ("$RealBin/../etc/collection.conf");
+sub sysconf_dir
+{
+  my $base = base_dir ();
 
-$Actions{$action}->();
-exit (0);
+  if ($base)
+  {
+    return "$base/etc";
+  }
+  else
+  {
+    return "../etc";
+  }
+}
+
+sub init
+{
+  my $lib_dir = lib_dir ();
+  my $sysconf_dir = sysconf_dir ();
+
+  if (!grep { $lib_dir eq $_ } (@::INC))
+  {
+    unshift (@::INC, $lib_dir);
+  }
+
+  gc_read_config ("$sysconf_dir/collection.conf");
+}
+
+sub main
+{
+  my $Debug = param ('debug') ? 1 : 0;
+  my $action = param ('action') || 'list_hosts';
+
+  if (!exists ($Actions{$action}))
+  {
+    print STDERR "No such action: $action\n";
+    return (1);
+  }
+
+  init ();
+
+  $Actions{$action}->();
+  return (1);
+} # sub main
 
 sub can_handle_xhtml
 {
@@ -104,7 +184,7 @@ sub can_handle_xhtml
   }
 } # can_handle_xhtml
 
-{my $html_started;
+my $html_started;
 sub start_html
 {
   return if ($html_started);
@@ -119,9 +199,8 @@ sub start_html
 
   if (can_handle_xhtml ())
   {
+    print header (-Content_Type => 'application/xhtml+xml; charset=UTF-8');
     print <<HTML;
-Content-Type: application/xhtml+xml; charset=UTF-8
-
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
     "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
@@ -133,9 +212,8 @@ HTML
   }
   else
   {
+    print header (-Content_Type => 'text/html; charset=UTF-8');
     print <<HTML;
-Content-Type: text/html; charset=UTF-8
-
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
     "http://www.w3.org/TR/html4/strict.dtd">
 <html>
@@ -151,7 +229,7 @@ HTML
   <body onload="nav_init ($begin, $end);">
 HTML
   $html_started = 1;
-}}
+}
 
 sub end_html
 {
@@ -159,6 +237,29 @@ sub end_html
   </body>
 </html>
 HTML
+  $html_started = 0;
+}
+
+sub contains_invalid_chars
+{
+  my $str = shift;
+
+  for (split (m//, $str))
+  {
+    my $n = ord ($_);
+
+    # Whitespace is allowed.
+    if (($n >= 9) && ($n <= 13))
+    {
+      next;
+    }
+    elsif ($n < 32)
+    {
+      return (1);
+    }
+  }
+
+  return;
 }
 
 sub show_selector
@@ -175,6 +276,7 @@ sub show_selector
 HTML
   for (sort (keys %$host_selection))
   {
+    next if contains_invalid_chars ($_);
     my $host = encode_entities ($_);
     my $selected = $host_selection->{$_}
     ? ' selected="selected"'
@@ -187,6 +289,7 @@ HTML
 HTML
   for (sort (keys %$plugin_selection))
   {
+    next if contains_invalid_chars ($_);
     my $plugin = encode_entities ($_);
     my $selected = $plugin_selection->{$_}
     ? ' selected="selected"'
@@ -199,6 +302,7 @@ HTML
 HTML
   for (sort { $TimeSpans->{$a} <=> $TimeSpans->{$b} } (keys (%$TimeSpans)))
   {
+    next if contains_invalid_chars ($_);
     my $name = encode_entities ($_);
     my $value = $TimeSpans->{$_};
     my $selected = ($value == $timespan_selection)
@@ -225,6 +329,7 @@ sub action_list_hosts
   for (sort @hosts)
   {
     my $url = encode_entities (script_name () . "?action=show_selection;hostname=$_");
+    next if contains_invalid_chars ($_);
     my $name = encode_entities ($_);
     print qq#      <li><a href="$url">$name</a></li>\n#;
   }
@@ -282,7 +387,7 @@ sub action_show_selection
   $all_files = get_selected_files ();
   $timespan = get_timespan_selection ();
 
-  if ($Debug)
+  if (param ('debug'))
   {
     print "<pre>", Data::Dumper->Dump ([$all_files], ['all_files']), "</pre>\n";
   }
@@ -307,7 +412,7 @@ sub action_show_selection
       $types->{$type} = tl_load_type ($file->{'type'});
       if (!$types->{$type})
       {
-        cluck ("tl_load_type (" . $file->{'type'} . ") failed");
+        warn ("tl_load_type (" . $file->{'type'} . ") failed");
         next;
       }
     }
@@ -320,6 +425,12 @@ sub action_show_selection
   for (sort (keys %$types))
   {
     my $type = $_;
+
+    if (!defined ($types->{$type}))
+    {
+      next;
+    }
+
     my $graphs_num = $types->{$type}->getGraphsNum ();
 
     for (my $i = 0; $i < $graphs_num; $i++)
@@ -374,6 +485,8 @@ EOF
   end_html ();
 }
 
+main ();
+
 =head1 SEE ALSO
 
 L<Collectd::Graph::Type>
index c6e2508..cc7e141 100644 (file)
@@ -1,5 +1,24 @@
 package Collectd::Graph::Common;
 
+# Copyright (C) 2008-2011  Florian Forster
+# Copyright (C) 2011       noris network AG
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; only version 2 of the License is applicable.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+#
+# Authors:
+#   Florian "octo" Forster <octo at collectd.org>
+
 use strict;
 use warnings;
 
@@ -11,6 +30,8 @@ use CGI (':cgi');
 use Exporter;
 use Collectd::Graph::Config (qw(gc_get_scalar));
 
+our $Cache = {};
+
 $ColorCanvas   = 'FFFFFF';
 $ColorFullBlue = '0000FF';
 $ColorHalfBlue = 'B7B7F7';
@@ -191,22 +212,48 @@ sub ident_to_filename
   return ($ret);
 } # ident_to_filename
 
+sub _part_to_string
+{
+  my $part = shift;
+
+  if (!defined ($part))
+  {
+    return ("(UNDEF)");
+  }
+  if (ref ($part) eq 'ARRAY')
+  {
+    if (1 == @$part)
+    {
+      return ($part->[0]);
+    }
+    else
+    {
+      return ('(' . join (',', @$part) . ')');
+    }
+  }
+  else
+  {
+    return ($part);
+  }
+} # _part_to_string
+
 sub ident_to_string
 {
   my $ident = shift;
 
   my $ret = '';
 
-  $ret .= $ident->{'hostname'} . '/' . $ident->{'plugin'};
+  $ret .= _part_to_string ($ident->{'hostname'})
+  . '/' . _part_to_string ($ident->{'plugin'});
   if (defined ($ident->{'plugin_instance'}))
   {
-    $ret .= '-' . $ident->{'plugin_instance'};
+    $ret .= '-' . _part_to_string ($ident->{'plugin_instance'});
   }
 
-  $ret .= '/' . $ident->{'type'};
+  $ret .= '/' . _part_to_string ($ident->{'type'});
   if (defined ($ident->{'type_instance'}))
   {
-    $ret .= '-' . $ident->{'type_instance'};
+    $ret .= '-' . _part_to_string ($ident->{'type_instance'});
   }
 
   return ($ret);
@@ -258,27 +305,36 @@ sub get_files_from_directory
 
 sub get_all_hosts
 {
-  my $dh;
-  my @ret = ();
-  my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir);
+  my $ret = [];
 
-  opendir ($dh, "$data_dir") or confess ("opendir ($data_dir): $!");
-  while (my $entry = readdir ($dh))
+  if (defined ($Cache->{'get_all_hosts'}))
   {
-    next if ($entry =~ m/^\./);
-    next if (!-d "$data_dir/$entry");
-    next if (!-r "$data_dir/$entry" or !-x "$data_dir/$entry");
-    push (@ret, sanitize_hostname ($entry));
+    $ret = $Cache->{'get_all_hosts'};
+  }
+  else
+  {
+    my $dh;
+    my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir);
+
+    opendir ($dh, "$data_dir") or confess ("opendir ($data_dir): $!");
+    while (my $entry = readdir ($dh))
+    {
+      next if ($entry =~ m/^\./);
+      next if (!-d "$data_dir/$entry");
+      push (@$ret, sanitize_hostname ($entry));
+    }
+    closedir ($dh);
+
+    $Cache->{'get_all_hosts'} = $ret;
   }
-  closedir ($dh);
 
   if (wantarray ())
   {
-    return (@ret);
+    return (@$ret);
   }
-  elsif (@ret)
+  elsif (@$ret)
   {
-    return (\@ret);
+    return ($ret);
   }
   else
   {
@@ -292,12 +348,32 @@ sub get_all_plugins
   my $ret = {};
   my $dh;
   my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir);
+  my $cache_key;
 
-  if (!@hosts)
+  if (@hosts)
   {
+    $cache_key = join (';', @hosts);
+  }
+  else
+  {
+    $cache_key = "/*/";
     @hosts = get_all_hosts ();
   }
 
+  if (defined ($Cache->{'get_all_plugins'}{$cache_key}))
+  {
+    $ret = $Cache->{'get_all_plugins'}{$cache_key};
+
+    if (wantarray ())
+    {
+      return (sort (keys %$ret));
+    }
+    else
+    {
+      return ($ret);
+    }
+  }
+
   for (@hosts)
   {
     my $host = $_;
@@ -331,6 +407,7 @@ sub get_all_plugins
     closedir ($dh);
   } # for (@hosts)
 
+  $Cache->{'get_all_plugins'}{$cache_key} = $ret;
   if (wantarray ())
   {
     return (sort (keys %$ret));
@@ -386,24 +463,44 @@ sub _filter_ident
   return (0);
 } # _filter_ident
 
+sub _get_all_files
+{
+  my $ret;
+
+  if (defined ($Cache->{'_get_all_files'}))
+  {
+    $ret = $Cache->{'_get_all_files'};
+  }
+  else
+  {
+    my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir);
+
+    $ret = get_files_from_directory ($data_dir, 3);
+    $Cache->{'_get_all_files'} = $ret;
+  }
+
+  return ($ret);
+} # _get_all_files
+
 sub get_files_by_ident
 {
   my $ident = shift;
   my $all_files;
   my @ret = ();
-  my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir);
 
-  #if ($ident->{'hostname'})
-  #{
-  #$all_files = get_files_for_host ($ident->{'hostname'});
-  #}
-  #else
-  #{
-    $all_files = get_files_from_directory ($data_dir, 3);
-    #}
+  my $cache_key = ident_to_string ($ident);
+  if (defined ($Cache->{'get_files_by_ident'}{$cache_key}))
+  {
+    my $ret = $Cache->{'get_files_by_ident'}{$cache_key};
+
+    return ($ret)
+  }
+
+  $all_files = _get_all_files ();
 
   @ret = grep { _filter_ident ($ident, $_) == 0 } (@$all_files);
 
+  $Cache->{'get_files_by_ident'}{$cache_key} = \@ret;
   return (\@ret);
 } # get_files_by_ident
 
index 0fbd0d3..4a70c41 100644 (file)
@@ -34,7 +34,7 @@ sub new
   my $obj = Collectd::Graph::Type->new (@_);
   $obj->{'data_sources'} = [qw(free used)];
   $obj->{'rrd_opts'} = ['-v', 'Bytes'];
-  $obj->{'rrd_title'} = 'Disk space ({type_instance})';
+  $obj->{'rrd_title'} = 'Disk space ({instance})';
   $obj->{'rrd_format'} = '%5.1lf%sB';
   $obj->{'colors'} = [qw(00b000 ff0000)];
 
@@ -58,7 +58,7 @@ sub getRRDArgs
   my $faded_green = get_faded_color ('00ff00');
   my $faded_red = get_faded_color ('ff0000');
 
-  return (['-t', 'Diskspace (' . $ident->{'type_instance'} . ')', '-v', 'Bytes', '-l', '0',
+  return (['-t', $obj->getTitle ($ident), '-v', 'Bytes', '-l', '0',
     "DEF:free_min=${filename}:free:MIN",
     "DEF:free_avg=${filename}:free:AVERAGE",
     "DEF:free_max=${filename}:free:MAX",
index 9078110..5a0b522 100644 (file)
@@ -92,7 +92,8 @@ sub _load_module_from_config
     $obj = _create_object ($module);
     if (!$obj)
     {
-      cluck ("Creating an $module object failed");
+      #cluck ("Creating an $module object failed");
+      warn ("Creating an $module object failed");
       return;
     }
   }
diff --git a/contrib/exec-ksm.sh b/contrib/exec-ksm.sh
new file mode 100755 (executable)
index 0000000..a21aa1d
--- /dev/null
@@ -0,0 +1,53 @@
+#!/bin/bash
+
+# collectd - contrib/exec-ksm.sh
+# Copyright (C) 2011  Florian Forster
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+# DEALINGS IN THE SOFTWARE.
+#
+# Authors:
+#   Florian Forster <octo at collectd.org>
+
+HOSTNAME="${COLLECTD_HOSTNAME:-$(hostname -f)}"
+INTERVAL="${COLLECTD_INTERVAL:-60}"
+
+function read_file() {
+  local type="$1"
+  local type_instance="$2"
+  local file_name="/sys/kernel/mm/ksm/$3"
+  local ident="$HOSTNAME/exec-ksm/vmpage_number-${type_instance}"
+
+  echo "PUTVAL \"$ident\" interval=$INTERVAL N:$(< $file_name)"
+}
+
+if [[ 0 -eq $(< /sys/kernel/mm/ksm/run) ]]; then
+  echo "$0: KSM not active." >&2
+  exit 1
+fi
+
+while sleep "$INTERVAL"
+do
+  read_file vmpage_number    shared   pages_shared
+  read_file vmpage_number    saved    pages_sharing
+  read_file vmpage_number    unshared pages_unshared
+  read_file vmpage_number    volatile pages_volatile
+  read_file total_operations scan     full_scans
+done
+
+exit 0
index 26dd621..71644f7 100644 (file)
@@ -1,5 +1,7 @@
 # Run `perldoc exec-nagios.px' for details on this config file.
 
+NRPEConfig /etc/nrpe.cfg
+
 Interval 300
 
 <Script /usr/lib/nagios/check_tcp>
index 4b112f9..c7f18c5 100755 (executable)
@@ -23,6 +23,7 @@ use Regexp::Common ('number');
 
 our $ConfigFile = '/etc/exec-nagios.conf';
 our $TypeMap = {};
+our $NRPEMap = {};
 our $Scripts = [];
 our $Interval = defined ($ENV{'COLLECTD_INTERVAL'}) ? (0 + $ENV{'COLLECTD_INTERVAL'}) : 300;
 our $Hostname = defined ($ENV{'COLLECTD_HOSTNAME'}) ? $ENV{'COLLECTD_HOSTNAME'} : '';
@@ -41,6 +42,7 @@ config syntax, so it's very similar to the F<collectd.conf> syntax, too.
 
 Here's a short sample config:
 
+  NRPEConfig "/etc/nrpe.cfg"
   Interval 300
   <Script /usr/lib/nagios/check_tcp>
     Arguments -H alice -p 22
@@ -55,6 +57,18 @@ The options have the following semantic (i.E<nbsp>e. meaning):
 
 =over 4
 
+=item B<NRPEConfig> I<File>
+
+Read the NRPE config and add the command definitions to an alias table. After
+reading the file you can use the NRPE command name rather than the script's
+filename within B<Script> blocks (see below). If both, the NRPE config and the
+B<Script> block, define arguments they will be merged by concatenating the
+arguments together in the order "NRPE-args Script-args".
+
+Please note that this option is rather dumb. It does not support "command
+argument processing" (i.e. replacing C<$ARG1$> and friends), inclusion of other
+NRPE config files, include directories etc.
+
 =item B<Interval> I<Seconds>
 
 Sets the interval in which the plugins are executed. This doesn't need to match
@@ -65,8 +79,9 @@ seconds.
 =item E<lt>B<Script> I<File>E<gt>
 
 Adds a script to the list of scripts to be executed once per I<Interval>
-seconds. You can use the following optional arguments to specify the operation
-further:
+seconds. If the B<NRPEConfig> is given above the B<Script> block, you may use
+the NRPE command name rather than the script's filename. You can use the
+following optional arguments to specify the operation further:
 
 =over 4
 
@@ -93,6 +108,48 @@ with the C<exec-plugin>).
 
 =cut
 
+sub parse_nrpe_conf
+{
+  my $file = shift;
+  my $fh;
+  my $status;
+
+  $status = open ($fh, '<', $file);
+  if (!$status)
+  {
+    print STDERR "Reading NRPE config from \"$file\" failed: $!\n";
+    return;
+  }
+
+  while (<$fh>)
+  {
+    my $line = $_;
+    chomp ($line);
+
+    if ($line =~ m/^\s*command\[([^\]]+)\]\s*=\s*(.+)$/)
+    {
+      my $alias = $1;
+      my $script;
+      my $arguments;
+
+      ($script, $arguments) = split (' ', $2, 2);
+
+      if ($NRPEMap->{$alias})
+      {
+        print STDERR "Warning: NRPE command \"$alias\" redefined.\n";
+      }
+
+      $NRPEMap->{$alias} = { script => $script };
+      if ($arguments)
+      {
+        $NRPEMap->{$alias}{'arguments'} = $arguments;
+      }
+    }
+  } # while (<$fh>)
+
+  close ($fh);
+} # parse_nrpe_conf
+
 sub handle_config_addtype
 {
   my $list = shift;
@@ -107,6 +164,30 @@ sub handle_config_addtype
   }
 } # handle_config_addtype
 
+# Update the script record. This function adds the name of the script /
+# executable to the hash and merges the configured and NRPE arguments if
+# required.
+sub update_script_opts
+{
+  my $opts = shift;
+  my $script = shift;
+  my $nrpe_args = shift;
+
+  $opts->{'script'} = $script;
+
+  if ($nrpe_args)
+  {
+    if ($opts->{'arguments'})
+    {
+      $opts->{'arguments'} = $nrpe_args . ' ' . $opts->{'arguments'};
+    }
+    else
+    {
+      $opts->{'arguments'} = $nrpe_args;
+    }
+  }
+} # update_script_opts
+
 sub handle_config_script
 {
   my $scripts = shift;
@@ -116,6 +197,20 @@ sub handle_config_script
     my $script = $_;
     my $opts = $scripts->{$script};
 
+    my $nrpe_args = '';
+
+    # Check if the script exists in the NRPE map. If so, replace the alias name
+    # with the actual script name.
+    if ($NRPEMap->{$script})
+    {
+      if ($NRPEMap->{$script}{'arguments'})
+      {
+        $nrpe_args = $NRPEMap->{$script}{'arguments'};
+      }
+      $script = $NRPEMap->{$script}{'script'};
+    }
+
+    # Check if the script exists and is executable.
     if (!-e $script)
     {
       print STDERR "Script `$script' doesn't exist.\n";
@@ -126,20 +221,21 @@ sub handle_config_script
     }
     else
     {
+      # Add the script to the global @$Script array.
       if (ref ($opts) eq 'ARRAY')
+      {
+        for (@$opts)
         {
-          for (@$opts)
-            {
-              my $opt = $_;
-              $opt->{'script'} = $script;
-              push (@$Scripts, $opt);
-            }
-        }
-          else
-        {
-          $opts->{'script'} = $script;
-          push (@$Scripts, $opts);
+          my $opt = $_;
+          update_script_opts ($opt, $script, $nrpe_args);
+          push (@$Scripts, $opt);
         }
+      }
+      else
+      {
+        update_script_opts ($opts, $script, $nrpe_args);
+        push (@$Scripts, $opts);
+      }
     }
   } # for (keys %$scripts)
 } # handle_config_script
@@ -148,6 +244,26 @@ sub handle_config
 {
   my $config = shift;
 
+  if (defined ($config->{'nrpeconfig'}))
+  {
+    if (ref ($config->{'nrpeconfig'}) eq 'ARRAY')
+    {
+      for (@{$config->{'nrpeconfig'}})
+      {
+        parse_nrpe_conf ($_);
+      }
+    }
+    elsif (ref ($config->{'nrpeconfig'}) eq '')
+    {
+      parse_nrpe_conf ($config->{'nrpeconfig'});
+    }
+    else
+    {
+      print STDERR "Cannot handle ref type '"
+      . ref ($config->{'nrpeconfig'}) . "' for option 'NRPEConfig'.\n";
+    }
+  }
+
   if (defined ($config->{'addtype'}))
   {
     if (ref ($config->{'addtype'}) eq 'ARRAY')
diff --git a/contrib/migrate-4-5.px b/contrib/migrate-4-5.px
new file mode 100755 (executable)
index 0000000..c2a9555
--- /dev/null
@@ -0,0 +1,255 @@
+#!/usr/bin/perl
+
+# collectd - contrib/migrate-4-5.px
+# Copyright (C) 2010  Florian Forster
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+# DEALINGS IN THE SOFTWARE.
+#
+# Authors:
+#   Florian Forster <octo at collectd.org>
+
+use strict;
+use warnings;
+
+use Getopt::Long ('GetOptions');
+use Data::Dumper ();
+use File::Basename ('dirname');
+
+our $InDir = '/var/lib/collectd';
+our $RRDtool = 'rrdtool';
+our $RRDFilter = 'rrd_filter.px';
+
+our %TypesCounterToDerive = # {{{
+(
+  apache_bytes => ["count"],
+  apache_requests => ["count"],
+  arc_counts => ["demand_data", "demand_metadata", "prefetch_data", "prefetch_metadata"],
+  arc_l2_bytes => ["read", "write"],
+  ath_stat => ["value"],
+  compression => ["uncompressed", "compressed"],
+  connections => ["value"],
+  cpu => ["value"],
+  current => ["value"],
+  disk_merged => ["read", "write"],
+  disk_octets => ["read", "write"],
+  disk_ops => ["read", "write"],
+  disk_ops_complex => ["value"],
+  disk_time => ["read", "write"],
+  dns_answer => ["value"],
+  dns_notify => ["value"],
+  dns_octets => ["queries", "responses"],
+  dns_opcode => ["value"],
+  dns_qtype => ["value"],
+  dns_query => ["value"],
+  dns_question => ["value"],
+  dns_rcode => ["value"],
+  dns_reject => ["value"],
+  dns_request => ["value"],
+  dns_resolver => ["value"],
+  dns_response => ["value"],
+  dns_transfer => ["value"],
+  dns_update => ["value"],
+  dns_zops => ["value"],
+  fscache_stat => ["value"],
+  fork_rate => ["value"],
+  http_request_methods => ["count"],
+  http_requests => ["count"],
+  http_response_codes => ["count"],
+  if_collisions => ["value"],
+  if_dropped => ["rx", "tx"],
+  if_errors => ["rx", "tx"],
+  if_multicast => ["value"],
+  if_octets => ["rx", "tx"],
+  if_packets => ["rx", "tx"],
+  if_rx_errors => ["value"],
+  if_tx_errors => ["value"],
+  io_octets => ["rx", "tx"],
+  io_packets => ["rx", "tx"],
+  ipt_bytes => ["value"],
+  ipt_packets => ["value"],
+  irq => ["value"],
+  memcached_command => ["value"],
+  memcached_octets => ["rx", "tx"],
+  memcached_ops => ["value"],
+  mysql_commands => ["value"],
+  mysql_handler => ["value"],
+  mysql_locks => ["value"],
+  mysql_log_position => ["value"],
+  mysql_octets => ["rx", "tx"],
+  nfs_procedure => ["value"],
+  nginx_requests => ["value"],
+  node_octets => ["rx", "tx"],
+  node_stat => ["value"],
+  operations => ["value"],
+  pg_blks => ["value"],
+  pg_n_tup_c => ["value"],
+  pg_scan => ["value"],
+  pg_xact => ["value"],
+  protocol_counter => ["value"],
+  ps_cputime => ["user", "syst"],
+  ps_pagefaults => ["minflt", "majflt"],
+  ps_code => ["value"],
+  ps_data => ["value"],
+  serial_octets => ["rx", "tx"],
+  swap_io => ["value"],
+  virt_cpu_total => ["ns"],
+  virt_vcpu => ["ns"],
+  vmpage_action => ["value"],
+  vmpage_faults => ["minflt", "majflt"],
+  vmpage_io => ["in", "out"],
+); # }}} %TypesCounterToDerive
+
+our %TypesRenameDataSource = # {{{
+(
+  absolute => "count",
+  apache_bytes => "count",
+  apache_connections => "count",
+  apache_idle_workers => "count",
+  apache_requests => "count",
+  apache_scoreboard => "count",
+  conntrack => "entropy",
+  contextswitch => "contextswitches",
+  delay => "seconds",
+  entropy => "entropy",
+  file_size => "bytes",
+  frequency => "frequency",
+  frequency_offset => "ppm",
+  http_request_methods => "count",
+  http_requests => "count",
+  http_response_codes => "count",
+  percent => "percent",
+  ping => "ping",
+  records => "count",
+  time_dispersion => "seconds",
+  timeleft => "timeleft",
+  time_offset => "seconds",
+  users => "users",
+  virt_cpu_total => "ns",
+  virt_vcpu => "ns",
+); # }}} %TypesRenameDataSource
+
+sub handle_file # {{{
+{
+  my @path = @_;
+  my $path = join ('/', @path);
+
+  if (!($path =~ m/\.rrd$/))
+  {
+    return;
+  }
+
+  my $tmp = pop (@path);
+  $tmp =~ s/\.rrd$//;
+  my ($type, $type_inst) = split (m/-/, $tmp, 2);
+  $type_inst ||= '';
+
+  $tmp = pop (@path);
+  my ($plugin, $plugin_inst) = split (m/-/, $tmp, 2);
+  $plugin_inst ||= '';
+
+  if ($TypesRenameDataSource{$type})
+  {
+    my $old_ds = $TypesRenameDataSource{$type};
+    print "$RRDtool tune \"$path\" --data-source-rename ${old_ds}:value\n";
+  }
+
+  if ($TypesCounterToDerive{$type})
+  {
+    my $ds_names = $TypesCounterToDerive{$type};
+    
+    for (@$ds_names)
+    {
+      my $name = $_;
+      print "$RRDtool tune \"$path\" --data-source-type ${name}:DERIVE --minimum ${name}:0 --maximum ${name}:U\n";
+    }
+  }
+
+  if ((($plugin eq 'df') || ($plugin eq 'interface'))
+    && (!$plugin_inst) && ($type_inst))
+  {
+    my $dir = join ('/', @path);
+    print "mkdir -p \"$dir/$plugin-$type_inst\"\n";
+    if (($plugin eq 'df') and ($type eq 'df'))
+    {
+      print "$RRDFilter --infile=\"$path\" --outfile=\"$dir/$plugin-$type_inst/df_complex-free.rrd\" --map free:value\n";
+      print "$RRDFilter --infile=\"$path\" --outfile=\"$dir/$plugin-$type_inst/df_complex-used.rrd\" --map used:value\n";
+    }
+    else
+    {
+      print "mv \"$path\" \"$dir/$plugin-$type_inst/$type.rrd\"\n";
+    }
+  }
+} # }}} sub handle_file
+
+sub scan_dir # {{{
+{
+  my @dir_parts = @_;
+  my $dir_str = join ('/', @dir_parts);
+  my $dh;
+
+  opendir ($dh, $dir_str) || die;
+  while (my $entry = readdir ($dh))
+  {
+    my $entry_path = "$dir_str/$entry";
+
+    if ($entry =~ m/^\./)
+    {
+      next;
+    }
+
+    if (-d $entry_path)
+    {
+      scan_dir (@dir_parts, $entry);
+    }
+    elsif (-f $entry_path)
+    {
+      handle_file (@dir_parts, $entry);
+    }
+  }
+  closedir ($dh);
+} # }}} sub scan_dir
+
+sub exit_usage # {{{
+{
+  print STDERR <<EOF;
+migrate-4-5.px [OPTIONS]
+
+Valid options are:
+
+  --indir <dir>         Source directory
+                        Default: $InDir
+  --rrdtool <path>      Path to the RRDtool binary
+                        Default: $RRDtool
+  --rrdfilter <path>    Path to the rrd_filter.px script
+                        Default: $RRDFilter
+
+EOF
+  exit (1);
+} # }}} sub exit_usage
+
+GetOptions ("indir|i=s" => \$InDir,
+        "rrdtool=s" => \$RRDtool,
+        "rrdfilter=s" => \$RRDFilter,
+        "help|h" => \&exit_usage) or exit_usage ();
+
+print "#!/bin/bash\n\n";
+
+scan_dir ($InDir);
+
+# vim: set sw=2 sts=2 et fdm=marker :
index c84aabe..7297d85 100644 (file)
@@ -48,9 +48,9 @@ function load_graph_definitions($logarithmic = false, $tinylegend = false) {
        $GraphDefs = array();
        $GraphDefs['apache_bytes'] = array(
                '-v', 'Bits/s',
-               'DEF:min_raw={file}:count:MIN',
-               'DEF:avg_raw={file}:count:AVERAGE',
-               'DEF:max_raw={file}:count:MAX',
+               'DEF:min_raw={file}:value:MIN',
+               'DEF:avg_raw={file}:value:AVERAGE',
+               'DEF:max_raw={file}:value:MAX',
                'CDEF:min=min_raw,8,*',
                'CDEF:avg=avg_raw,8,*',
                'CDEF:max=max_raw,8,*',
@@ -68,9 +68,9 @@ function load_graph_definitions($logarithmic = false, $tinylegend = false) {
                'GPRINT:avg_sum:LAST:(ca. %5.1lf%sB Total)\l');
        $GraphDefs['apache_requests'] = array(
                '-v', 'Requests/s',
-               'DEF:min={file}:count:MIN',
-               'DEF:avg={file}:count:AVERAGE',
-               'DEF:max={file}:count:MAX',
+               'DEF:min={file}:value:MIN',
+               'DEF:avg={file}:value:AVERAGE',
+               'DEF:max={file}:value:MAX',
                "AREA:max#$HalfBlue",
                "AREA:min#$Canvas",
                "LINE1:avg#$FullBlue:Requests/s",
@@ -79,9 +79,9 @@ function load_graph_definitions($logarithmic = false, $tinylegend = false) {
                'GPRINT:max:MAX:%6.2lf Max,',
                'GPRINT:avg:LAST:%6.2lf Last');
        $GraphDefs['apache_scoreboard'] = array(
-               'DEF:min={file}:count:MIN',
-               'DEF:avg={file}:count:AVERAGE',
-               'DEF:max={file}:count:MAX',
+               'DEF:min={file}:value:MIN',
+               'DEF:avg={file}:value:AVERAGE',
+               'DEF:max={file}:value:MAX',
                "AREA:max#$HalfBlue",
                "AREA:min#$Canvas",
                "LINE1:avg#$FullBlue:Processes",
@@ -2024,7 +2024,7 @@ function meta_graph_apache_scoreboard($host, $plugin, $plugin_instance, $type, $
                if ($file == '')
                        continue;
 
-               $sources[] = array('name'=>$inst, 'file'=>$file, 'ds'=>'count');
+               $sources[] = array('name'=>$inst, 'file'=>$file, 'ds'=>'value');
        }
 
        return collectd_draw_meta_stack($opts, $sources);
index 4617f6c..6eefac9 100644 (file)
@@ -3,7 +3,7 @@
 
 Summary:       Statistics collection daemon for filling RRD files.
 Name:          collectd
-Version:       4.9.0
+Version:       5.0.1
 Release:       1%{?dist}
 Source:                http://collectd.org/files/%{name}-%{version}.tar.gz
 License:       GPL
@@ -147,6 +147,7 @@ exit 0
 %attr(0755,root,root) /var/www/cgi-bin/collection.cgi
 %attr(0755,root,root) %{_sbindir}/collectd
 %attr(0755,root,root) %{_bindir}/collectd-nagios
+%attr(0755,root,root) %{_bindir}/collectdctl
 %attr(0755,root,root) %{_sbindir}/collectdmon
 %attr(0644,root,root) %{_mandir}/man1/*
 %attr(0644,root,root) %{_mandir}/man5/*
@@ -174,6 +175,7 @@ exit 0
 %plugin_macro cpu
 %plugin_macro csv
 %plugin_macro curl
+%plugin_macro curl_xml
 %plugin_macro df
 %plugin_macro disk
 %plugin_macro dns
@@ -197,6 +199,7 @@ exit 0
 %plugin_macro match_value
 
 %plugin_macro mbmon
+%plugin_macro memcachec
 %plugin_macro memcached
 %plugin_macro memory
 %plugin_macro multimeter
@@ -222,11 +225,14 @@ exit 0
 %plugin_macro target_replace
 %plugin_macro target_scale
 %plugin_macro target_set
+%plugin_macro target_v5upgrade
 
 %plugin_macro tcpconns
 %plugin_macro teamspeak2
 %plugin_macro ted
 %plugin_macro thermal
+%plugin_macro threshold
+
 %plugin_macro unixsock
 %plugin_macro uptime
 %plugin_macro users
@@ -243,6 +249,7 @@ exit 0
 %attr(0644,root,root) /usr/lib/perl5/site_perl/5.8.8/Collectd.pm
 %attr(0644,root,root) /usr/lib/perl5/site_perl/5.8.8/Collectd/Unixsock.pm
 %attr(0644,root,root) /usr/lib/perl5/site_perl/5.8.8/Collectd/Plugins/OpenVZ.pm
+%attr(0644,root,root) /usr/lib/perl5/site_perl/5.8.8/Collectd/Plugins/Monitorus.pm
 %attr(0644,root,root) /usr/share/man/man3/Collectd::Unixsock.3pm.gz
 
 %exclude /usr/share/collectd/postgresql_default.conf
@@ -251,8 +258,8 @@ exit 0
 
 %if %with_java
 %files java
-%attr(0644,root,root) /usr/share/%{name}/java/org/collectd/api/*.class
-%attr(0644,root,root) /usr/share/%{name}/java/org/collectd/java/*.class
+/usr/share/collectd/java/collectd-api.jar
+/usr/share/collectd/java/generic-jmx.jar
 %plugin_macro java
 %endif
 
@@ -283,6 +290,10 @@ exit 0
 %plugin_macro snmp
 
 %changelog
+* Tue Jan 03 2011 Monetate <jason.stelzer@monetate.com> 5.0.1
+- New upstream version
+- Changes to support 5.0.1
+
 * Tue Jan 04 2010 Rackspace <stu.hood@rackspace.com> 4.9.0
 - New upstream version
 - Changes to support 4.9.0
@@ -299,7 +310,7 @@ exit 0
 
 * Wed Jul 25 2007 Kjell Randa <Kjell.Randa@broadpark.no> 4.0.5
 - New major releas
-- Changes to support 4.0.5 
+- Changes to support 4.0.5
 
 * Wed Jan 11 2007 Iain Lea <iain@bricbrac.de> 3.11.0-0
 - fixed spec file to build correctly on fedora core
index b7c085c..a60acb3 100644 (file)
@@ -1,7 +1,7 @@
 #!/bin/bash
 #
 # collectd    Startup script for the Collectd statistics gathering daemon
-# chkconfig: - 86 15
+# chkconfig: - 99 01
 # description: Collectd is a statistics gathering daemon used to collect \
 #   system information ie. cpu, memory, disk, network
 # processname: collectd
@@ -15,6 +15,7 @@
 RETVAL=0
 ARGS=""
 prog="collectdmon"
+service="collectd"
 CONFIG=/etc/collectd.conf
 COLLECTD=/usr/sbin/collectd
 COLLECTDMONPID=/var/run/collectdmon.pid
@@ -30,7 +31,7 @@ start () {
                daemon $prog -P $COLLECTDMONPID -c $COLLECTD -- -C "$CONFIG"
                RETVAL=$?
                echo
-               [ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog
+               [ $RETVAL -eq 0 ] && touch /var/lock/subsys/$service
        fi
 }
 stop () {
@@ -38,7 +39,7 @@ stop () {
        killproc $prog
        RETVAL=$?
        echo
-       [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog
+       [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$service
 }
 # See how we were called.
 case "$1" in
index e64e167..3532e7b 100644 (file)
@@ -1,7 +1,4 @@
 SUBDIRS = libcollectdclient
-if BUILD_WITH_OWN_LIBIPTC
-SUBDIRS += owniptc
-endif
 if BUILD_WITH_OWN_LIBOCONFIG
 SUBDIRS += liboconfig
 endif
@@ -40,13 +37,13 @@ collectd_SOURCES = collectd.c collectd.h \
                   utils_match.c utils_match.h \
                   utils_subst.c utils_subst.h \
                   utils_tail.c utils_tail.h \
-                  utils_threshold.c utils_threshold.h \
+                  utils_time.c utils_time.h \
                   types_list.c types_list.h
 
 collectd_CPPFLAGS =  $(AM_CPPFLAGS) $(LTDLINCL)
 collectd_CFLAGS = $(AM_CFLAGS)
 collectd_LDFLAGS = -export-dynamic
-collectd_LDADD =
+collectd_LDADD = -lm
 collectd_DEPENDENCIES =
 
 # Link to these libraries..
@@ -73,7 +70,6 @@ collectd_LDADD += -ldevinfo
 endif
 if BUILD_AIX
 collectd_LDFLAGS += -Wl,-bexpall,-brtllib
-collectd_LDADD += -lm
 endif
 
 # The daemon needs to call sg_init, so we need to link it against libstatgrab,
@@ -85,7 +81,7 @@ endif
 
 if BUILD_WITH_OWN_LIBOCONFIG
 collectd_LDADD += $(LIBLTDL) liboconfig/liboconfig.la
-collectd_DEPENDENCIES += $(LIBLTDL) liboconfig/liboconfig.la
+collectd_DEPENDENCIES += liboconfig/liboconfig.la
 else
 collectd_LDADD += -loconfig
 endif
@@ -135,10 +131,21 @@ pkglib_LTLIBRARIES =
 BUILT_SOURCES = 
 CLEANFILES = 
 
+if BUILD_PLUGIN_AGGREGATION
+pkglib_LTLIBRARIES += aggregation.la
+aggregation_la_SOURCES = aggregation.c \
+                         utils_vl_lookup.c utils_vl_lookup.h
+aggregation_la_LDFLAGS = -module -avoid-version
+aggregation_la_LIBADD =
+collectd_LDADD += "-dlopen" aggregation.la
+collectd_DEPENDENCIES += aggregation.la
+endif
+
 if BUILD_PLUGIN_AMQP
 pkglib_LTLIBRARIES += amqp.la
 amqp_la_SOURCES = amqp.c \
                  utils_cmd_putval.c utils_cmd_putval.h \
+                 utils_format_graphite.c utils_format_graphite.h \
                  utils_format_json.c utils_format_json.h
 amqp_la_LDFLAGS = -module -avoid-version $(BUILD_WITH_LIBRABBITMQ_LDFLAGS)
 amqp_la_CPPFLAGS = $(AM_CPPFLAGS) $(BUILD_WITH_LIBRABBITMQ_CPPFLAGS)
@@ -228,6 +235,10 @@ if BUILD_PLUGIN_CONTEXTSWITCH
 pkglib_LTLIBRARIES += contextswitch.la
 contextswitch_la_SOURCES = contextswitch.c
 contextswitch_la_LDFLAGS = -module -avoid-version
+contextswitch_la_LIBADD =
+if BUILD_WITH_PERFSTAT
+contextswitch_la_LIBADD += -lperfstat
+endif
 collectd_LDADD += "-dlopen" contextswitch.la
 collectd_DEPENDENCIES += contextswitch.la
 endif
@@ -393,6 +404,14 @@ collectd_LDADD += "-dlopen" exec.la
 collectd_DEPENDENCIES += exec.la
 endif
 
+if BUILD_PLUGIN_ETHSTAT
+pkglib_LTLIBRARIES += ethstat.la
+ethstat_la_SOURCES = ethstat.c
+ethstat_la_LDFLAGS = -module -avoid-version
+collectd_LDADD += "-dlopen" ethstat.la
+collectd_DEPENDENCIES += ethstat.la
+endif
+
 if BUILD_PLUGIN_FILECOUNT
 pkglib_LTLIBRARIES += filecount.la
 filecount_la_SOURCES = filecount.c
@@ -452,12 +471,7 @@ pkglib_LTLIBRARIES += iptables.la
 iptables_la_SOURCES = iptables.c
 iptables_la_CPPFLAGS = $(AM_CPPFLAGS) $(BUILD_WITH_LIBIPTC_CPPFLAGS)
 iptables_la_LDFLAGS = -module -avoid-version $(BUILD_WITH_LIBIPTC_LDFLAGS)
-if BUILD_WITH_OWN_LIBIPTC
-iptables_la_LIBADD  = owniptc/libiptc.la
-iptables_la_DEPENDENCIES = owniptc/libiptc.la
-else
 iptables_la_LIBADD = -liptc
-endif
 collectd_LDADD += "-dlopen" iptables.la
 collectd_DEPENDENCIES += iptables.la
 endif
@@ -475,7 +489,9 @@ endif
 if BUILD_PLUGIN_IPVS
 pkglib_LTLIBRARIES += ipvs.la
 ipvs_la_SOURCES = ipvs.c
+if IP_VS_H_NEEDS_KERNEL_CFLAGS
 ipvs_la_CFLAGS = $(AM_CFLAGS) $(KERNEL_CFLAGS)
+endif
 ipvs_la_LDFLAGS = -module -avoid-version
 collectd_LDADD += "-dlopen" ipvs.la
 collectd_DEPENDENCIES += ipvs.la
@@ -605,6 +621,14 @@ collectd_LDADD += "-dlopen" mbmon.la
 collectd_DEPENDENCIES += mbmon.la
 endif
 
+if BUILD_PLUGIN_MD
+pkglib_LTLIBRARIES += md.la
+md_la_SOURCES = md.c
+md_la_LDFLAGS = -module -avoid-version
+collectd_LDADD += "-dlopen" md.la
+collectd_DEPENDENCIES += md.la
+endif
+
 if BUILD_PLUGIN_MEMCACHEC
 pkglib_LTLIBRARIES += memcachec.la
 memcachec_la_SOURCES = memcachec.c
@@ -782,6 +806,14 @@ collectd_LDADD += "-dlopen" ntpd.la
 collectd_DEPENDENCIES += ntpd.la
 endif
 
+if BUILD_PLUGIN_NUMA
+pkglib_LTLIBRARIES += numa.la
+numa_la_SOURCES = numa.c
+numa_la_LDFLAGS = -module -avoid-version
+collectd_LDADD += "-dlopen" numa.la
+collectd_DEPENDENCIES += numa.la
+endif
+
 if BUILD_PLUGIN_NUT
 pkglib_LTLIBRARIES += nut.la
 nut_la_SOURCES = nut.c
@@ -1142,6 +1174,14 @@ collectd_LDADD += "-dlopen" thermal.la
 collectd_DEPENDENCIES += thermal.la
 endif
 
+if BUILD_PLUGIN_THRESHOLD
+pkglib_LTLIBRARIES += threshold.la
+threshold_la_SOURCES = threshold.c
+threshold_la_LDFLAGS = -module -avoid-version
+collectd_LDADD += "-dlopen" threshold.la
+collectd_DEPENDENCIES += threshold.la
+endif
+
 if BUILD_PLUGIN_TOKYOTYRANT
 pkglib_LTLIBRARIES += tokyotyrant.la
 tokyotyrant_la_SOURCES = tokyotyrant.c
@@ -1160,7 +1200,6 @@ pkglib_LTLIBRARIES += unixsock.la
 unixsock_la_SOURCES = unixsock.c \
                      utils_cmd_flush.h utils_cmd_flush.c \
                      utils_cmd_getval.h utils_cmd_getval.c \
-                     utils_cmd_getthreshold.h utils_cmd_getthreshold.c \
                      utils_cmd_listval.h utils_cmd_listval.c \
                      utils_cmd_putval.h utils_cmd_putval.c \
                      utils_cmd_putnotif.h utils_cmd_putnotif.c
@@ -1179,6 +1218,9 @@ uptime_la_LIBADD =
 if BUILD_WITH_LIBKSTAT
 uptime_la_LIBADD += -lkstat
 endif
+if BUILD_WITH_PERFSTAT
+uptime_la_LIBADD += -lperfstat
+endif
 collectd_LDADD += "-dlopen" uptime.la
 collectd_DEPENDENCIES += uptime.la
 endif
@@ -1241,6 +1283,16 @@ collectd_LDADD += "-dlopen" wireless.la
 collectd_DEPENDENCIES += wireless.la
 endif
 
+if BUILD_PLUGIN_WRITE_GRAPHITE
+pkglib_LTLIBRARIES += write_graphite.la
+write_graphite_la_SOURCES = write_graphite.c \
+                        utils_format_graphite.c utils_format_graphite.h \
+                        utils_format_json.c utils_format_json.h
+write_graphite_la_LDFLAGS = -module -avoid-version
+collectd_LDADD += "-dlopen" write_graphite.la
+collectd_DEPENDENCIES += write_graphite.la
+endif
+
 if BUILD_PLUGIN_WRITE_HTTP
 pkglib_LTLIBRARIES += write_http.la
 write_http_la_SOURCES = write_http.c \
@@ -1256,6 +1308,16 @@ endif
 collectd_DEPENDENCIES += write_http.la
 endif
 
+if BUILD_PLUGIN_WRITE_MONGODB
+pkglib_LTLIBRARIES += write_mongodb.la
+write_mongodb_la_SOURCES = write_mongodb.c
+write_mongodb_la_CPPFLAGS = $(AM_CPPFLAGS) $(BUILD_WITH_LIBMONGOC_CPPFLAGS)
+write_mongodb_la_LDFLAGS = -module -avoid-version $(BUILD_WITH_LIBMONGOC_LDFLAGS)
+write_mongodb_la_LIBADD = -lmongoc
+collectd_LDADD += "-dlopen" write_mongodb.la
+collectd_DEPENDENCIES += write_mongodb.la
+endif
+
 if BUILD_PLUGIN_WRITE_REDIS
 pkglib_LTLIBRARIES += write_redis.la
 write_redis_la_SOURCES = write_redis.c
@@ -1286,6 +1348,8 @@ collectd_LDADD += "-dlopen" zfs_arc.la
 collectd_DEPENDENCIES += zfs_arc.la
 endif
 
+BUILT_SOURCES += $(dist_man_MANS)
+
 dist_man_MANS = collectd.1 \
                collectd.conf.5 \
                collectd-email.5 \
@@ -1297,6 +1361,7 @@ dist_man_MANS = collectd.1 \
                collectd-perl.5 \
                collectd-python.5 \
                collectd-snmp.5 \
+               collectd-threshold.5 \
                collectd-unixsock.5 \
                types.db.5
 
@@ -1315,6 +1380,7 @@ EXTRA_DIST +=   collectd.conf.pod \
                collectd-python.pod \
                collectd.pod \
                collectd-snmp.pod \
+               collectd-threshold.pod \
                collectd-unixsock.pod \
                postgresql_default.conf \
                types.db.pod
@@ -1336,7 +1402,7 @@ EXTRA_DIST +=   collectd.conf.pod \
        fi
 
 pinba.pb-c.c pinba.pb-c.h: pinba.proto
-       protoc-c --c_out $(builddir) pinba.proto
+       protoc-c --c_out . pinba.proto
 
 install-exec-hook:
        $(mkinstalldirs) $(DESTDIR)$(sysconfdir)
@@ -1350,3 +1416,21 @@ install-exec-hook:
        $(INSTALL) -m 0644 $(srcdir)/types.db $(DESTDIR)$(pkgdatadir)/types.db;
        $(INSTALL) -m 0644 $(srcdir)/postgresql_default.conf \
                $(DESTDIR)$(pkgdatadir)/postgresql_default.conf;
+
+uninstall-hook:
+       rm -f $(DESTDIR)$(pkgdatadir)/types.db;
+       rm -f $(DESTDIR)$(sysconfdir)/collectd.conf
+       rm -f $(DESTDIR)$(pkgdatadir)/postgresql_default.conf;
+
+if BUILD_FEATURE_DEBUG
+bin_PROGRAMS += utils_vl_lookup_test
+utils_vl_lookup_test_SOURCES = utils_vl_lookup_test.c \
+                               utils_vl_lookup.h utils_vl_lookup.c \
+                               utils_avltree.c utils_avltree.h \
+                               common.h
+
+utils_vl_lookup_test_CPPFLAGS =  $(AM_CPPFLAGS) $(LTDLINCL) -DBUILD_TEST=1
+utils_vl_lookup_test_CFLAGS = $(AM_CFLAGS)
+utils_vl_lookup_test_LDFLAGS = -export-dynamic
+utils_vl_lookup_test_LDADD =
+endif
diff --git a/src/aggregation.c b/src/aggregation.c
new file mode 100644 (file)
index 0000000..db33c17
--- /dev/null
@@ -0,0 +1,684 @@
+/**
+ * collectd - src/aggregation.c
+ * Copyright (C) 2012       Florian Forster
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *   Florian Forster <octo at collectd.org>
+ **/
+
+#include "collectd.h"
+#include "plugin.h"
+#include "common.h"
+#include "configfile.h"
+#include "meta_data.h"
+#include "utils_cache.h" /* for uc_get_rate() */
+#include "utils_vl_lookup.h"
+
+#include <pthread.h>
+
+struct aggregation_s /* {{{ */
+{
+  identifier_t ident;
+
+  _Bool calc_num;
+  _Bool calc_sum;
+  _Bool calc_average;
+  _Bool calc_min;
+  _Bool calc_max;
+  _Bool calc_stddev;
+}; /* }}} */
+typedef struct aggregation_s aggregation_t;
+
+struct agg_instance_s;
+typedef struct agg_instance_s agg_instance_t;
+struct agg_instance_s /* {{{ */
+{
+  pthread_mutex_t lock;
+  identifier_t ident;
+
+  int ds_type;
+
+  derive_t num;
+  gauge_t sum;
+  gauge_t squares_sum;
+
+  gauge_t min;
+  gauge_t max;
+
+  rate_to_value_state_t *state_num;
+  rate_to_value_state_t *state_sum;
+  rate_to_value_state_t *state_average;
+  rate_to_value_state_t *state_min;
+  rate_to_value_state_t *state_max;
+  rate_to_value_state_t *state_stddev;
+
+  agg_instance_t *next;
+}; /* }}} */
+
+static lookup_t *lookup = NULL;
+
+static pthread_mutex_t agg_instance_list_lock = PTHREAD_MUTEX_INITIALIZER;
+static agg_instance_t *agg_instance_list_head = NULL;
+
+static void agg_destroy (aggregation_t *agg) /* {{{ */
+{
+  sfree (agg);
+} /* }}} void agg_destroy */
+
+/* Frees all dynamically allocated memory within the instance. */
+static void agg_instance_destroy (agg_instance_t *inst) /* {{{ */
+{
+  if (inst == NULL)
+    return;
+
+  /* Remove this instance from the global list of instances. */
+  pthread_mutex_lock (&agg_instance_list_lock);
+  if (agg_instance_list_head == inst)
+    agg_instance_list_head = inst->next;
+  else if (agg_instance_list_head != NULL)
+  {
+    agg_instance_t *prev = agg_instance_list_head;
+    while ((prev != NULL) && (prev->next != inst))
+      prev = prev->next;
+    if (prev != NULL)
+      prev->next = inst->next;
+  }
+  pthread_mutex_unlock (&agg_instance_list_lock);
+
+  sfree (inst->state_num);
+  sfree (inst->state_sum);
+  sfree (inst->state_average);
+  sfree (inst->state_min);
+  sfree (inst->state_max);
+  sfree (inst->state_stddev);
+
+  memset (inst, 0, sizeof (*inst));
+  inst->ds_type = -1;
+  inst->min = NAN;
+  inst->max = NAN;
+} /* }}} void agg_instance_destroy */
+
+/* Create a new aggregation instance. */
+static agg_instance_t *agg_instance_create (data_set_t const *ds, /* {{{ */
+    value_list_t const *vl, aggregation_t *agg)
+{
+  agg_instance_t *inst;
+
+  DEBUG ("aggregation plugin: Creating new instance.");
+
+  inst = malloc (sizeof (*inst));
+  if (inst == NULL)
+  {
+    ERROR ("aggregation plugin: malloc() failed.");
+    return (NULL);
+  }
+  memset (inst, 0, sizeof (*inst));
+  pthread_mutex_init (&inst->lock, /* attr = */ NULL);
+
+  inst->ds_type = ds->ds[0].type;
+
+#define COPY_FIELD(fld) do { \
+  sstrncpy (inst->ident.fld, \
+      LU_IS_ANY (agg->ident.fld) ? vl->fld : agg->ident.fld, \
+      sizeof (inst->ident.fld)); \
+} while (0)
+
+  COPY_FIELD (host);
+  COPY_FIELD (plugin);
+  COPY_FIELD (plugin_instance);
+  COPY_FIELD (type);
+  COPY_FIELD (type_instance);
+
+#undef COPY_FIELD
+
+  inst->min = NAN;
+  inst->max = NAN;
+
+#define INIT_STATE(field) do { \
+  inst->state_ ## field = NULL; \
+  if (agg->calc_ ## field) { \
+    inst->state_ ## field = malloc (sizeof (*inst->state_ ## field)); \
+    if (inst->state_ ## field == NULL) { \
+      agg_instance_destroy (inst); \
+      ERROR ("aggregation plugin: malloc() failed."); \
+      return (NULL); \
+    } \
+    memset (inst->state_ ## field, 0, sizeof (*inst->state_ ## field)); \
+  } \
+} while (0)
+
+  INIT_STATE (num);
+  INIT_STATE (sum);
+  INIT_STATE (average);
+  INIT_STATE (min);
+  INIT_STATE (max);
+  INIT_STATE (stddev);
+
+#undef INIT_STATE
+
+  pthread_mutex_lock (&agg_instance_list_lock);
+  inst->next = agg_instance_list_head;
+  agg_instance_list_head = inst;
+  pthread_mutex_unlock (&agg_instance_list_lock);
+
+  return (inst);
+} /* }}} agg_instance_t *agg_instance_create */
+
+/* Update the num, sum, min, max, ... fields of the aggregation instance, if
+ * the rate of the value list is available. Value lists with more than one data
+ * source are not supported and will return an error. Returns zero on success
+ * and non-zero otherwise. */
+static int agg_instance_update (agg_instance_t *inst, /* {{{ */
+    data_set_t const *ds, value_list_t const *vl)
+{
+  gauge_t *rate;
+
+  if (ds->ds_num != 1)
+  {
+    ERROR ("aggregation plugin: The \"%s\" type (data set) has more than one "
+        "data source. This is currently not supported by this plugin. "
+        "Sorry.", ds->type);
+    return (EINVAL);
+  }
+
+  rate = uc_get_rate (ds, vl);
+  if (rate == NULL)
+  {
+    char ident[6 * DATA_MAX_NAME_LEN];
+    FORMAT_VL (ident, sizeof (ident), vl);
+    ERROR ("aggregation plugin: Unable to read the current rate of \"%s\".",
+        ident);
+    return (ENOENT);
+  }
+
+  if (isnan (rate[0]))
+  {
+    sfree (rate);
+    return (0);
+  }
+
+  pthread_mutex_lock (&inst->lock);
+
+  inst->num++;
+  inst->sum += rate[0];
+  inst->squares_sum += (rate[0] * rate[0]);
+
+  if (isnan (inst->min) || (inst->min > rate[0]))
+    inst->min = rate[0];
+  if (isnan (inst->max) || (inst->max < rate[0]))
+    inst->max = rate[0];
+
+  pthread_mutex_unlock (&inst->lock);
+
+  sfree (rate);
+  return (0);
+} /* }}} int agg_instance_update */
+
+static int agg_instance_read_func (agg_instance_t *inst, /* {{{ */
+  char const *func, gauge_t rate, rate_to_value_state_t *state,
+  value_list_t *vl, char const *pi_prefix, cdtime_t t)
+{
+  value_t v;
+  int status;
+
+  if (pi_prefix[0] != 0)
+    ssnprintf (vl->plugin_instance, sizeof (vl->plugin_instance), "%s-%s",
+        pi_prefix, func);
+  else
+    sstrncpy (vl->plugin_instance, func, sizeof (vl->plugin_instance));
+
+  memset (&v, 0, sizeof (v));
+  status = rate_to_value (&v, rate, state, inst->ds_type, t);
+  if (status != 0)
+  {
+    /* If this is the first iteration and rate_to_value() was asked to return a
+     * COUNTER or a DERIVE, it will return EAGAIN. Catch this and handle
+     * gracefully. */
+    if (status == EAGAIN)
+      return (0);
+
+    WARNING ("aggregation plugin: rate_to_value failed with status %i.",
+        status);
+    return (-1);
+  }
+
+  vl->values = &v;
+  vl->values_len = 1;
+
+  plugin_dispatch_values_secure (vl);
+
+  vl->values = NULL;
+  vl->values_len = 0;
+
+  return (0);
+} /* }}} int agg_instance_read_func */
+
+static int agg_instance_read (agg_instance_t *inst, cdtime_t t) /* {{{ */
+{
+  value_list_t vl = VALUE_LIST_INIT;
+  char pi_prefix[DATA_MAX_NAME_LEN];
+
+  /* Pre-set all the fields in the value list that will not change per
+   * aggregation type (sum, average, ...). The struct will be re-used and must
+   * therefore be dispatched using the "secure" function. */
+
+  vl.time = t;
+  vl.interval = 0;
+
+  vl.meta = meta_data_create ();
+  if (vl.meta == NULL)
+  {
+    ERROR ("aggregation plugin: meta_data_create failed.");
+    return (-1);
+  }
+  meta_data_add_boolean (vl.meta, "aggregation:created", 1);
+
+  if (LU_IS_ALL (inst->ident.host))
+    sstrncpy (vl.host, "global", sizeof (vl.host));
+  else
+    sstrncpy (vl.host, inst->ident.host, sizeof (vl.host));
+
+  sstrncpy (vl.plugin, "aggregation", sizeof (vl.plugin));
+
+  if (LU_IS_ALL (inst->ident.plugin))
+  {
+    if (LU_IS_ALL (inst->ident.plugin_instance))
+      sstrncpy (pi_prefix, "", sizeof (pi_prefix));
+    else
+      sstrncpy (pi_prefix, inst->ident.plugin_instance, sizeof (pi_prefix));
+  }
+  else
+  {
+    if (LU_IS_ALL (inst->ident.plugin_instance))
+      sstrncpy (pi_prefix, inst->ident.plugin, sizeof (pi_prefix));
+    else
+      ssnprintf (pi_prefix, sizeof (pi_prefix),
+          "%s-%s", inst->ident.plugin, inst->ident.plugin_instance);
+  }
+
+  sstrncpy (vl.type, inst->ident.type, sizeof (vl.type));
+
+  if (!LU_IS_ALL (inst->ident.type_instance))
+    sstrncpy (vl.type_instance, inst->ident.type_instance,
+        sizeof (vl.type_instance));
+
+#define READ_FUNC(func, rate) do { \
+  if (inst->state_ ## func != NULL) { \
+    agg_instance_read_func (inst, #func, rate, \
+        inst->state_ ## func, &vl, pi_prefix, t); \
+  } \
+} while (0)
+
+  pthread_mutex_lock (&inst->lock);
+
+  READ_FUNC (num, (gauge_t) inst->num);
+
+  /* All other aggregations are only defined when there have been any values
+   * at all. */
+  if (inst->num > 0)
+  {
+    READ_FUNC (sum, inst->sum);
+    READ_FUNC (average, (inst->sum / ((gauge_t) inst->num)));
+    READ_FUNC (min, inst->min);
+    READ_FUNC (max, inst->max);
+    READ_FUNC (stddev, sqrt((((gauge_t) inst->num) * inst->squares_sum)
+          - (inst->sum * inst->sum)) / ((gauge_t) inst->num));
+  }
+
+  /* Reset internal state. */
+  inst->num = 0;
+  inst->sum = 0.0;
+  inst->squares_sum = 0.0;
+  inst->min = NAN;
+  inst->max = NAN;
+
+  pthread_mutex_unlock (&inst->lock);
+
+  meta_data_destroy (vl.meta);
+  vl.meta = NULL;
+
+  return (0);
+} /* }}} int agg_instance_read */
+
+/* lookup_class_callback_t for utils_vl_lookup */
+static void *agg_lookup_class_callback ( /* {{{ */
+    __attribute__((unused)) data_set_t const *ds,
+    value_list_t const *vl, void *user_class)
+{
+  return (agg_instance_create (ds, vl, (aggregation_t *) user_class));
+} /* }}} void *agg_class_callback */
+
+/* lookup_obj_callback_t for utils_vl_lookup */
+static int agg_lookup_obj_callback (data_set_t const *ds, /* {{{ */
+    value_list_t const *vl,
+    __attribute__((unused)) void *user_class,
+    void *user_obj)
+{
+  return (agg_instance_update ((agg_instance_t *) user_obj, ds, vl));
+} /* }}} int agg_lookup_obj_callback */
+
+/* lookup_free_class_callback_t for utils_vl_lookup */
+static void agg_lookup_free_class_callback (void *user_class) /* {{{ */
+{
+  agg_destroy ((aggregation_t *) user_class);
+} /* }}} void agg_lookup_free_class_callback */
+
+/* lookup_free_obj_callback_t for utils_vl_lookup */
+static void agg_lookup_free_obj_callback (void *user_obj) /* {{{ */
+{
+  agg_instance_destroy ((agg_instance_t *) user_obj);
+} /* }}} void agg_lookup_free_obj_callback */
+
+/*
+ * <Plugin "aggregation">
+ *   <Aggregation>
+ *     Plugin "cpu"
+ *     Type "cpu"
+ *
+ *     GroupBy Host
+ *     GroupBy TypeInstance
+ *
+ *     CalculateNum true
+ *     CalculateSum true
+ *     CalculateAverage true
+ *     CalculateMinimum true
+ *     CalculateMaximum true
+ *     CalculateStddev true
+ *   </Aggregation>
+ * </Plugin>
+ */
+static int agg_config_handle_group_by (oconfig_item_t const *ci, /* {{{ */
+    aggregation_t *agg)
+{
+  int i;
+
+  for (i = 0; i < ci->values_num; i++)
+  {
+    char const *value;
+
+    if (ci->values[i].type != OCONFIG_TYPE_STRING)
+    {
+      ERROR ("aggregation plugin: Argument %i of the \"GroupBy\" option "
+          "is not a string.", i + 1);
+      continue;
+    }
+
+    value = ci->values[i].value.string;
+
+    if (strcasecmp ("Host", value) == 0)
+      sstrncpy (agg->ident.host, LU_ANY, sizeof (agg->ident.host));
+    else if (strcasecmp ("Plugin", value) == 0)
+      sstrncpy (agg->ident.plugin, LU_ANY, sizeof (agg->ident.plugin));
+    else if (strcasecmp ("PluginInstance", value) == 0)
+      sstrncpy (agg->ident.plugin_instance, LU_ANY,
+          sizeof (agg->ident.plugin_instance));
+    else if (strcasecmp ("TypeInstance", value) == 0)
+      sstrncpy (agg->ident.type_instance, LU_ANY, sizeof (agg->ident.type_instance));
+    else if (strcasecmp ("Type", value) == 0)
+      ERROR ("aggregation plugin: Grouping by type is not supported.");
+    else
+      WARNING ("aggregation plugin: The \"%s\" argument to the \"GroupBy\" "
+          "option is invalid and will be ignored.", value);
+  } /* for (ci->values) */
+
+  return (0);
+} /* }}} int agg_config_handle_group_by */
+
+static int agg_config_aggregation (oconfig_item_t *ci) /* {{{ */
+{
+  aggregation_t *agg;
+  _Bool is_valid;
+  int status;
+  int i;
+
+  agg = malloc (sizeof (*agg));
+  if (agg == NULL)
+  {
+    ERROR ("aggregation plugin: malloc failed.");
+    return (-1);
+  }
+  memset (agg, 0, sizeof (*agg));
+
+  sstrncpy (agg->ident.host, LU_ALL, sizeof (agg->ident.host));
+  sstrncpy (agg->ident.plugin, LU_ALL, sizeof (agg->ident.plugin));
+  sstrncpy (agg->ident.plugin_instance, LU_ALL,
+      sizeof (agg->ident.plugin_instance));
+  sstrncpy (agg->ident.type, LU_ALL, sizeof (agg->ident.type));
+  sstrncpy (agg->ident.type_instance, LU_ALL,
+      sizeof (agg->ident.type_instance));
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *child = ci->children + i;
+
+    if (strcasecmp ("Host", child->key) == 0)
+      cf_util_get_string_buffer (child, agg->ident.host,
+          sizeof (agg->ident.host));
+    else if (strcasecmp ("Plugin", child->key) == 0)
+      cf_util_get_string_buffer (child, agg->ident.plugin,
+          sizeof (agg->ident.plugin));
+    else if (strcasecmp ("PluginInstance", child->key) == 0)
+      cf_util_get_string_buffer (child, agg->ident.plugin_instance,
+          sizeof (agg->ident.plugin_instance));
+    else if (strcasecmp ("Type", child->key) == 0)
+      cf_util_get_string_buffer (child, agg->ident.type,
+          sizeof (agg->ident.type));
+    else if (strcasecmp ("TypeInstance", child->key) == 0)
+      cf_util_get_string_buffer (child, agg->ident.type_instance,
+          sizeof (agg->ident.type_instance));
+    else if (strcasecmp ("GroupBy", child->key) == 0)
+      agg_config_handle_group_by (child, agg);
+    else if (strcasecmp ("CalculateNum", child->key) == 0)
+      cf_util_get_boolean (child, &agg->calc_num);
+    else if (strcasecmp ("CalculateSum", child->key) == 0)
+      cf_util_get_boolean (child, &agg->calc_sum);
+    else if (strcasecmp ("CalculateAverage", child->key) == 0)
+      cf_util_get_boolean (child, &agg->calc_average);
+    else if (strcasecmp ("CalculateMinimum", child->key) == 0)
+      cf_util_get_boolean (child, &agg->calc_min);
+    else if (strcasecmp ("CalculateMaximum", child->key) == 0)
+      cf_util_get_boolean (child, &agg->calc_max);
+    else if (strcasecmp ("CalculateStddev", child->key) == 0)
+      cf_util_get_boolean (child, &agg->calc_stddev);
+    else
+      WARNING ("aggregation plugin: The \"%s\" key is not allowed inside "
+          "<Aggregation /> blocks and will be ignored.", child->key);
+  }
+
+  /* Sanity checking */
+  is_valid = 1;
+  if (LU_IS_ALL (agg->ident.type)) /* {{{ */
+  {
+    ERROR ("aggregation plugin: It appears you did not specify the required "
+        "\"Type\" option in this aggregation. "
+        "(Host \"%s\", Plugin \"%s\", PluginInstance \"%s\", "
+        "Type \"%s\", TypeInstance \"%s\")",
+        agg->ident.host, agg->ident.plugin, agg->ident.plugin_instance,
+        agg->ident.type, agg->ident.type_instance);
+    is_valid = 0;
+  }
+  else if (strchr (agg->ident.type, '/') != NULL)
+  {
+    ERROR ("aggregation plugin: The \"Type\" may not contain the '/' "
+        "character. Especially, it may not be a wildcard. The current "
+        "value is \"%s\".", agg->ident.type);
+    is_valid = 0;
+  } /* }}} */
+
+  if (!LU_IS_ALL (agg->ident.host) /* {{{ */
+      && !LU_IS_ALL (agg->ident.plugin)
+      && !LU_IS_ALL (agg->ident.plugin_instance)
+      && !LU_IS_ALL (agg->ident.type_instance))
+  {
+    ERROR ("aggregation plugin: An aggregation must contain at least one "
+        "wildcard. This is achieved by leaving at least one of the \"Host\", "
+        "\"Plugin\", \"PluginInstance\" and \"TypeInstance\" options blank "
+        "and not grouping by that field. "
+        "(Host \"%s\", Plugin \"%s\", PluginInstance \"%s\", "
+        "Type \"%s\", TypeInstance \"%s\")",
+        agg->ident.host, agg->ident.plugin, agg->ident.plugin_instance,
+        agg->ident.type, agg->ident.type_instance);
+    is_valid = 0;
+  } /* }}} */
+
+  if (!agg->calc_num && !agg->calc_sum && !agg->calc_average /* {{{ */
+      && !agg->calc_min && !agg->calc_max && !agg->calc_stddev)
+  {
+    ERROR ("aggregation plugin: No aggregation function has been specified. "
+        "Without this, I don't know what I should be calculating. "
+        "(Host \"%s\", Plugin \"%s\", PluginInstance \"%s\", "
+        "Type \"%s\", TypeInstance \"%s\")",
+        agg->ident.host, agg->ident.plugin, agg->ident.plugin_instance,
+        agg->ident.type, agg->ident.type_instance);
+    is_valid = 0;
+  } /* }}} */
+
+  if (!is_valid) /* {{{ */
+  {
+    sfree (agg);
+    return (-1);
+  } /* }}} */
+
+  status = lookup_add (lookup, &agg->ident, agg);
+  if (status != 0)
+  {
+    ERROR ("aggregation plugin: lookup_add failed with status %i.", status);
+    sfree (agg);
+    return (-1);
+  }
+
+  DEBUG ("aggregation plugin: Successfully added aggregation: "
+      "(Host \"%s\", Plugin \"%s\", PluginInstance \"%s\", "
+      "Type \"%s\", TypeInstance \"%s\")",
+      agg->ident.host, agg->ident.plugin, agg->ident.plugin_instance,
+      agg->ident.type, agg->ident.type_instance);
+  return (0);
+} /* }}} int agg_config_aggregation */
+
+static int agg_config (oconfig_item_t *ci) /* {{{ */
+{
+  int i;
+
+  pthread_mutex_lock (&agg_instance_list_lock);
+
+  if (lookup == NULL)
+  {
+    lookup = lookup_create (agg_lookup_class_callback,
+        agg_lookup_obj_callback,
+        agg_lookup_free_class_callback,
+        agg_lookup_free_obj_callback);
+    if (lookup == NULL)
+    {
+      pthread_mutex_unlock (&agg_instance_list_lock);
+      ERROR ("aggregation plugin: lookup_create failed.");
+      return (-1);
+    }
+  }
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *child = ci->children + i;
+
+    if (strcasecmp ("Aggregation", child->key) == 0)
+      agg_config_aggregation (child);
+    else
+      WARNING ("aggregation plugin: The \"%s\" key is not allowed inside "
+          "<Plugin aggregation /> blocks and will be ignored.", child->key);
+  }
+
+  pthread_mutex_unlock (&agg_instance_list_lock);
+
+  return (0);
+} /* }}} int agg_config */
+
+static int agg_read (void) /* {{{ */
+{
+  agg_instance_t *this;
+  cdtime_t t;
+  int success;
+
+  t = cdtime ();
+  success = 0;
+
+  pthread_mutex_lock (&agg_instance_list_lock);
+
+  /* agg_instance_list_head only holds data, after the "write" callback has
+   * been called with a matching value list at least once. So on startup,
+   * there's a race between the aggregations read() and write() callback. If
+   * the read() callback is called first, agg_instance_list_head is NULL and
+   * "success" may be zero. This is expected and should not result in an error.
+   * Therefore we need to handle this case separately. */
+  if (agg_instance_list_head == NULL)
+  {
+    pthread_mutex_unlock (&agg_instance_list_lock);
+    return (0);
+  }
+
+  for (this = agg_instance_list_head; this != NULL; this = this->next)
+  {
+    int status;
+
+    status = agg_instance_read (this, t);
+    if (status != 0)
+      WARNING ("aggregation plugin: Reading an aggregation instance "
+          "failed with status %i.", status);
+    else
+      success++;
+  }
+
+  pthread_mutex_unlock (&agg_instance_list_lock);
+
+  return ((success > 0) ? 0 : -1);
+} /* }}} int agg_read */
+
+static int agg_write (data_set_t const *ds, value_list_t const *vl, /* {{{ */
+    __attribute__((unused)) user_data_t *user_data)
+{
+  _Bool created_by_aggregation = 0;
+  int status;
+
+  /* Ignore values that were created by the aggregation plugin to avoid weird
+   * effects. */
+  (void) meta_data_get_boolean (vl->meta, "aggregation:created",
+      &created_by_aggregation);
+  if (created_by_aggregation)
+    return (0);
+
+  if (lookup == NULL)
+    status = ENOENT;
+  else
+  {
+    status = lookup_search (lookup, ds, vl);
+    if (status > 0)
+      status = 0;
+  }
+
+  return (status);
+} /* }}} int agg_write */
+
+void module_register (void)
+{
+  plugin_register_complex_config ("aggregation", agg_config);
+  plugin_register_read ("aggregation", agg_read);
+  plugin_register_write ("aggregation", agg_write, /* user_data = */ NULL);
+}
+
+/* vim: set sw=2 sts=2 tw=78 et fdm=marker : */
index f0abd44..9c8c6e5 100644 (file)
@@ -1,7 +1,7 @@
 /**
  * collectd - src/amqp.c
- * Copyright (C) 2009  Sebastien Pahl
- * Copyright (C) 2010  Florian Forster
+ * Copyright (C) 2009       Sebastien Pahl
+ * Copyright (C) 2010-2012  Florian Forster
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -31,6 +31,7 @@
 #include "plugin.h"
 #include "utils_cmd_putval.h"
 #include "utils_format_json.h"
+#include "utils_format_graphite.h"
 
 #include <pthread.h>
 
@@ -42,8 +43,9 @@
 #define CAMQP_DM_VOLATILE   1
 #define CAMQP_DM_PERSISTENT 2
 
-#define CAMQP_FORMAT_COMMAND 1
-#define CAMQP_FORMAT_JSON    2
+#define CAMQP_FORMAT_COMMAND    1
+#define CAMQP_FORMAT_JSON       2
+#define CAMQP_FORMAT_GRAPHITE   3
 
 #define CAMQP_CHANNEL 1
 
@@ -68,6 +70,10 @@ struct camqp_config_s
     uint8_t delivery_mode;
     _Bool   store_rates;
     int     format;
+    /* publish & graphite format only */
+    char    *prefix;
+    char    *postfix;
+    char    escape_char;
 
     /* subscribe only */
     char   *exchange_type;
@@ -129,6 +135,9 @@ static void camqp_config_free (void *ptr) /* {{{ */
     sfree (conf->exchange_type);
     sfree (conf->queue);
     sfree (conf->routing_key);
+    sfree (conf->prefix);
+    sfree (conf->postfix);
+
 
     sfree (conf);
 } /* }}} void camqp_config_free */
@@ -178,8 +187,13 @@ static char *camqp_strerror (camqp_config_t *conf, /* {{{ */
             break;
 
         case AMQP_RESPONSE_LIBRARY_EXCEPTION:
+#if HAVE_AMQP_RPC_REPLY_T_LIBRARY_ERRNO
             if (r.library_errno)
                 return (sstrerror (r.library_errno, buffer, buffer_size));
+#else
+            if (r.library_error)
+                return (sstrerror (r.library_error, buffer, buffer_size));
+#endif
             else
                 sstrncpy (buffer, "End of stream", sizeof (buffer));
             break;
@@ -216,6 +230,7 @@ static char *camqp_strerror (camqp_config_t *conf, /* {{{ */
     return (buffer);
 } /* }}} char *camqp_strerror */
 
+#if HAVE_AMQP_RPC_REPLY_T_LIBRARY_ERRNO
 static int camqp_create_exchange (camqp_config_t *conf) /* {{{ */
 {
     amqp_exchange_declare_ok_t *ed_ret;
@@ -246,6 +261,46 @@ static int camqp_create_exchange (camqp_config_t *conf) /* {{{ */
 
     return (0);
 } /* }}} int camqp_create_exchange */
+#else
+static int camqp_create_exchange (camqp_config_t *conf) /* {{{ */
+{
+    amqp_exchange_declare_ok_t *ed_ret;
+    amqp_table_t argument_table;
+    struct amqp_table_entry_t_ argument_table_entries[1];
+
+    if (conf->exchange_type == NULL)
+        return (0);
+
+    /* Valid arguments: "auto_delete", "internal" */
+    argument_table.num_entries = STATIC_ARRAY_SIZE (argument_table_entries);
+    argument_table.entries = argument_table_entries;
+    argument_table_entries[0].key = amqp_cstring_bytes ("auto_delete");
+    argument_table_entries[0].value.kind = AMQP_FIELD_KIND_BOOLEAN;
+    argument_table_entries[0].value.value.boolean = 1;
+
+    ed_ret = amqp_exchange_declare (conf->connection,
+            /* channel     = */ CAMQP_CHANNEL,
+            /* exchange    = */ amqp_cstring_bytes (conf->exchange),
+            /* type        = */ amqp_cstring_bytes (conf->exchange_type),
+            /* passive     = */ 0,
+            /* durable     = */ 0,
+            /* arguments   = */ argument_table);
+    if ((ed_ret == NULL) && camqp_is_error (conf))
+    {
+        char errbuf[1024];
+        ERROR ("amqp plugin: amqp_exchange_declare failed: %s",
+                camqp_strerror (conf, errbuf, sizeof (errbuf)));
+        camqp_close_connection (conf);
+        return (-1);
+    }
+
+    INFO ("amqp plugin: Successfully created exchange \"%s\" "
+            "with type \"%s\".",
+            conf->exchange, conf->exchange_type);
+
+    return (0);
+} /* }}} int camqp_create_exchange */
+#endif
 
 static int camqp_setup_queue (camqp_config_t *conf) /* {{{ */
 {
@@ -316,7 +371,9 @@ static int camqp_setup_queue (camqp_config_t *conf) /* {{{ */
             /* consumer_tag = */ AMQP_EMPTY_BYTES,
             /* no_local     = */ 0,
             /* no_ack       = */ 1,
-            /* exclusive    = */ 0);
+            /* exclusive    = */ 0,
+            /* arguments    = */ AMQP_EMPTY_TABLE
+        );
     if ((cm_ret == NULL) && camqp_is_error (conf))
     {
         char errbuf[1024];
@@ -543,6 +600,8 @@ static void *camqp_subscribe_thread (void *user_data) /* {{{ */
     camqp_config_t *conf = user_data;
     int status;
 
+    cdtime_t interval = plugin_get_interval ();
+
     while (subscriber_threads_running)
     {
         amqp_frame_t frame;
@@ -550,19 +609,25 @@ static void *camqp_subscribe_thread (void *user_data) /* {{{ */
         status = camqp_connect (conf);
         if (status != 0)
         {
+            struct timespec ts_interval;
             ERROR ("amqp plugin: camqp_connect failed. "
-                    "Will sleep for %i seconds.", interval_g);
-            sleep (interval_g);
+                    "Will sleep for %.3f seconds.",
+                    CDTIME_T_TO_DOUBLE (interval));
+            CDTIME_T_TO_TIMESPEC (interval, &ts_interval);
+            nanosleep (&ts_interval, /* remaining = */ NULL);
             continue;
         }
 
         status = amqp_simple_wait_frame (conf->connection, &frame);
         if (status < 0)
         {
+            struct timespec ts_interval;
             ERROR ("amqp plugin: amqp_simple_wait_frame failed. "
-                    "Will sleep for %i seconds.", interval_g);
+                    "Will sleep for %.3f seconds.",
+                    CDTIME_T_TO_DOUBLE (interval));
             camqp_close_connection (conf);
-            sleep (interval_g);
+            CDTIME_T_TO_TIMESPEC (interval, &ts_interval);
+            nanosleep (&ts_interval, /* remaining = */ NULL);
             continue;
         }
 
@@ -587,6 +652,7 @@ static void *camqp_subscribe_thread (void *user_data) /* {{{ */
 
     camqp_config_free (conf);
     pthread_exit (NULL);
+    return (NULL);
 } /* }}} void *camqp_subscribe_thread */
 
 static int camqp_subscribe_init (camqp_config_t *conf) /* {{{ */
@@ -606,7 +672,7 @@ static int camqp_subscribe_init (camqp_config_t *conf) /* {{{ */
     tmp = subscriber_threads + subscriber_threads_num;
     memset (tmp, 0, sizeof (*tmp));
 
-    status = pthread_create (tmp, /* attr = */ NULL,
+    status = plugin_thread_create (tmp, /* attr = */ NULL,
             camqp_subscribe_thread, conf);
     if (status != 0)
     {
@@ -644,6 +710,8 @@ static int camqp_write_locked (camqp_config_t *conf, /* {{{ */
         props.content_type = amqp_cstring_bytes("text/collectd");
     else if (conf->format == CAMQP_FORMAT_JSON)
         props.content_type = amqp_cstring_bytes("application/json");
+    else if (conf->format == CAMQP_FORMAT_GRAPHITE)
+        props.content_type = amqp_cstring_bytes("text/graphite");
     else
         assert (23 == 42);
     props.delivery_mode = conf->delivery_mode;
@@ -722,6 +790,18 @@ static int camqp_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
         format_json_value_list (buffer, &bfill, &bfree, ds, vl, conf->store_rates);
         format_json_finalize (buffer, &bfill, &bfree);
     }
+    else if (conf->format == CAMQP_FORMAT_GRAPHITE)
+    {
+        status = format_graphite (buffer, sizeof (buffer), ds, vl,
+                    conf->prefix, conf->postfix, conf->escape_char,
+                    conf->store_rates);
+        if (status != 0)
+        {
+            ERROR ("amqp plugin: format_graphite failed with status %i.",
+                    status);
+            return (status);
+        }
+    }
     else
     {
         ERROR ("amqp plugin: Invalid format (%i).", conf->format);
@@ -754,6 +834,8 @@ static int camqp_config_set_format (oconfig_item_t *ci, /* {{{ */
         conf->format = CAMQP_FORMAT_COMMAND;
     else if (strcasecmp ("JSON", string) == 0)
         conf->format = CAMQP_FORMAT_JSON;
+    else if (strcasecmp ("Graphite", string) == 0)
+        conf->format = CAMQP_FORMAT_GRAPHITE;
     else
     {
         WARNING ("amqp plugin: Invalid format string: %s",
@@ -794,6 +876,10 @@ static int camqp_config_connection (oconfig_item_t *ci, /* {{{ */
     /* publish only */
     conf->delivery_mode = CAMQP_DM_VOLATILE;
     conf->store_rates = 0;
+    /* publish & graphite only */
+    conf->prefix = NULL;
+    conf->postfix = NULL;
+    conf->escape_char = '_';
     /* subscribe only */
     conf->exchange_type = NULL;
     conf->queue = NULL;
@@ -851,6 +937,20 @@ static int camqp_config_connection (oconfig_item_t *ci, /* {{{ */
             status = cf_util_get_boolean (child, &conf->store_rates);
         else if ((strcasecmp ("Format", child->key) == 0) && publish)
             status = camqp_config_set_format (child, conf);
+        else if ((strcasecmp ("GraphitePrefix", child->key) == 0) && publish)
+            status = cf_util_get_string (child, &conf->prefix);
+        else if ((strcasecmp ("GraphitePostfix", child->key) == 0) && publish)
+            status = cf_util_get_string (child, &conf->postfix);
+        else if ((strcasecmp ("GraphiteEscapeChar", child->key) == 0) && publish)
+        {
+            char *tmp_buff = NULL;
+            status = cf_util_get_string (child, &tmp_buff);
+            if (strlen (tmp_buff) > 1)
+                WARNING ("amqp plugin: The option \"GraphiteEscapeChar\" handles "
+                        "only one character. Others will be ignored.");
+            conf->escape_char = tmp_buff[0];
+            sfree (tmp_buff);
+        }
         else
             WARNING ("amqp plugin: Ignoring unknown "
                     "configuration option \"%s\".", child->key);
index 506ba84..c31dd87 100644 (file)
@@ -373,6 +373,7 @@ static int init_host (apache_t *st) /* {{{ */
                return (-1);
        }
 
+       curl_easy_setopt (st->curl, CURLOPT_NOSIGNAL, 1);
        curl_easy_setopt (st->curl, CURLOPT_WRITEFUNCTION, apache_curl_callback);
        curl_easy_setopt (st->curl, CURLOPT_WRITEDATA, st);
 
@@ -476,13 +477,13 @@ static void submit_value (const char *type, const char *type_instance,
        plugin_dispatch_values (&vl);
 } /* void submit_value */
 
-static void submit_counter (const char *type, const char *type_instance,
-               counter_t c, apache_t *st)
+static void submit_derive (const char *type, const char *type_instance,
+               derive_t c, apache_t *st)
 {
        value_t v;
-       v.counter = c;
+       v.derive = c;
        submit_value (type, type_instance, v, st);
-} /* void submit_counter */
+} /* void submit_derive */
 
 static void submit_gauge (const char *type, const char *type_instance,
                gauge_t g, apache_t *st)
@@ -644,11 +645,11 @@ static int apache_read_host (user_data_t *user_data) /* {{{ */
                {
                        if ((strcmp (fields[0], "Total") == 0)
                                        && (strcmp (fields[1], "Accesses:") == 0))
-                               submit_counter ("apache_requests", "",
+                               submit_derive ("apache_requests", "",
                                                atoll (fields[2]), st);
                        else if ((strcmp (fields[0], "Total") == 0)
                                        && (strcmp (fields[1], "kBytes:") == 0))
-                               submit_counter ("apache_bytes", "",
+                               submit_derive ("apache_bytes", "",
                                                1024LL * atoll (fields[2]), st);
                }
                else if (fields_num == 2)
index a0629d5..4fbbde6 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * collectd - src/apcups.c
- * Copyright (C) 2006-2007  Florian octo Forster
+ * Copyright (C) 2006-2012  Florian octo Forster
  * Copyright (C) 2006       Anthony Gialluca <tonyabg at charter.net>
  * Copyright (C) 2000-2004  Kern Sibbald
  * Copyright (C) 1996-1999  Andre M. Hedrick <andre at suse.com>
@@ -73,6 +73,10 @@ static int   conf_port = NISPORT;
 
 static int global_sockfd = -1;
 
+static int count_retries = 0;
+static int count_iterations = 0;
+static _Bool close_socket = 0;
+
 static const char *config_keys[] =
 {
        "Host",
@@ -81,26 +85,31 @@ static const char *config_keys[] =
 };
 static int config_keys_num = 2;
 
-/* Close the network connection */
-static int apcups_shutdown (void)
+static int net_shutdown (int *fd)
 {
        uint16_t packet_size = 0;
 
-       if (global_sockfd < 0)
-               return (0);
+       if ((fd == NULL) || (*fd < 0))
+               return (EINVAL);
 
-       DEBUG ("Gracefully shutting down socket %i.", global_sockfd);
+       swrite (*fd, (void *) &packet_size, sizeof (packet_size));
+       close (*fd);
+       *fd = -1;
 
-       /* send EOF sentinel */
-       swrite (global_sockfd, (void *) &packet_size, sizeof (packet_size));
+       return (0);
+} /* int net_shutdown */
 
-       close (global_sockfd);
-       global_sockfd = -1;
+/* Close the network connection */
+static int apcups_shutdown (void)
+{
+       if (global_sockfd < 0)
+               return (0);
 
+       net_shutdown (&global_sockfd);
        return (0);
 } /* int apcups_shutdown */
 
-/*     
+/*
  * Open a TCP connection to the UPS network server
  * Returns -1 on error
  * Returns socket file descriptor otherwise
@@ -170,7 +179,7 @@ static int net_open (char *host, int port)
        return (sd);
 } /* int net_open (char *host, char *service, int port) */
 
-/* 
+/*
  * Receive a message from the other end. Each message consists of
  * two packets. The first is a header that contains the size
  * of the data that follows in the second packet.
@@ -186,6 +195,7 @@ static int net_recv (int *sockfd, char *buf, int buflen)
        /* get data size -- in short */
        if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
        {
+               close (*sockfd);
                *sockfd = -1;
                return (-1);
        }
@@ -193,7 +203,11 @@ static int net_recv (int *sockfd, char *buf, int buflen)
        packet_size = ntohs (packet_size);
        if (packet_size > buflen)
        {
-               DEBUG ("record length too large");
+               ERROR ("apcups plugin: Received %"PRIu16" bytes of payload "
+                               "but have only %i bytes of buffer available.",
+                               packet_size, buflen);
+               close (*sockfd);
+               *sockfd = -1;
                return (-2);
        }
 
@@ -203,6 +217,7 @@ static int net_recv (int *sockfd, char *buf, int buflen)
        /* now read the actual data */
        if (sread (*sockfd, (void *) buf, packet_size) != 0)
        {
+               close (*sockfd);
                *sockfd = -1;
                return (-1);
        }
@@ -229,6 +244,7 @@ static int net_send (int *sockfd, char *buff, int len)
 
        if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
        {
+               close (*sockfd);
                *sockfd = -1;
                return (-1);
        }
@@ -236,6 +252,7 @@ static int net_send (int *sockfd, char *buff, int len)
        /* send data packet */
        if (swrite (*sockfd, (void *) buff, len) != 0)
        {
+               close (*sockfd);
                *sockfd = -1;
                return (-2);
        }
@@ -253,6 +270,8 @@ static int apc_query_server (char *host, int port,
        char   *toksaveptr;
        char   *key;
        double  value;
+       _Bool retry = 1;
+       int status;
 
 #if APCMAIN
 # define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
@@ -260,21 +279,51 @@ static int apc_query_server (char *host, int port,
 # define PRINT_VALUE(name, val) /**/
 #endif
 
-       if (global_sockfd < 0)
+       while (retry)
        {
-               global_sockfd = net_open (host, port);
                if (global_sockfd < 0)
                {
-                       ERROR ("apcups plugin: Connecting to the "
-                                       "apcupsd failed.");
+                       global_sockfd = net_open (host, port);
+                       if (global_sockfd < 0)
+                       {
+                               ERROR ("apcups plugin: Connecting to the "
+                                               "apcupsd failed.");
+                               return (-1);
+                       }
+               }
+
+
+               status = net_send (&global_sockfd, "status", strlen ("status"));
+               if (status != 0)
+               {
+                       /* net_send is closing the socket on error. */
+                       assert (global_sockfd < 0);
+                       if (retry)
+                       {
+                               retry = 0;
+                               count_retries++;
+                               continue;
+                       }
+
+                       ERROR ("apcups plugin: Writing to the socket failed.");
                        return (-1);
                }
-       }
 
-       if (net_send (&global_sockfd, "status", 6) < 0)
+               break;
+       } /* while (retry) */
+
+        /* When collectd's collection interval is larger than apcupsd's
+         * timeout, we would have to retry / re-connect each iteration. Try to
+         * detect this situation and shut down the socket gracefully in that
+         * case. Otherwise, keep the socket open to avoid overhead. */
+       count_iterations++;
+       if ((count_iterations == 10) && (count_retries > 2))
        {
-               ERROR ("apcups plugin: Writing to the socket failed.");
-               return (-1);
+               NOTICE ("apcups plugin: There have been %i retries in the "
+                               "first %i iterations. Will close the socket "
+                               "in future iterations.",
+                               count_retries, count_iterations);
+               close_socket = 1;
        }
 
        while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
@@ -298,7 +347,7 @@ static int apc_query_server (char *host, int port,
 
                        if (strcmp ("LINEV", key) == 0)
                                apcups_detail->linev = value;
-                       else if (strcmp ("BATTV", key) == 0) 
+                       else if (strcmp ("BATTV", key) == 0)
                                apcups_detail->battv = value;
                        else if (strcmp ("ITEMP", key) == 0)
                                apcups_detail->itemp = value;
@@ -316,10 +365,16 @@ static int apc_query_server (char *host, int port,
                        tokptr = strtok_r (NULL, ":", &toksaveptr);
                } /* while (tokptr != NULL) */
        }
-       
+       status = errno; /* save errno, net_shutdown() may re-set it. */
+
+       if (close_socket)
+               net_shutdown (&global_sockfd);
+
        if (n < 0)
        {
-               WARNING ("apcups plugin: Error reading from socket");
+               char errbuf[1024];
+               ERROR ("apcups plugin: Reading from socket failed: %s",
+                               sstrerror (status, errbuf, sizeof (errbuf)));
                return (-1);
        }
 
@@ -398,12 +453,12 @@ static int apcups_read (void)
        apcups_detail.timeleft =   -1.0;
        apcups_detail.itemp    = -300.0;
        apcups_detail.linefreq =   -1.0;
-  
+
        status = apc_query_server (conf_host == NULL
                        ? APCUPS_DEFAULT_HOST
                        : conf_host,
                        conf_port, &apcups_detail);
+
        /*
         * if we did not connect then do not bother submitting
         * zeros. We want rrd files to have NAN.
index 6782fce..993e480 100644 (file)
@@ -539,6 +539,7 @@ static int ascent_init (void) /* {{{ */
     return (-1);
   }
 
+  curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1);
   curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, ascent_curl_callback);
   curl_easy_setopt (curl, CURLOPT_USERAGENT, PACKAGE_NAME"/"PACKAGE_VERSION);
   curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, ascent_curl_error);
index 6e0b907..5b7d7a0 100644 (file)
@@ -1,7 +1,7 @@
 /**
  * collectd - src/bind.c
- * Copyright (C) 2009  Bruno Prémont
- * Copyright (C) 2009  Florian Forster
+ * Copyright (C) 2009       Bruno Prémont
+ * Copyright (C) 2009,2010  Florian Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
  *
  * Authors:
  *   Bruno Prémont <bonbons at linux-vserver.org>
- *   Florian Forster <octo at verplant.org>
+ *   Florian Forster <octo at collectd.org>
  **/
 
 #include "config.h"
 
-#ifndef _XOPEN_SOURCE
-# define _XOPEN_SOURCE 600 /* glibc2 needs this for strptime */
-#endif
+#if STRPTIME_NEEDS_STANDARDS
+# ifndef _ISOC99_SOURCE
+#  define _ISOC99_SOURCE 1
+# endif
+# ifndef _POSIX_C_SOURCE
+#  define _POSIX_C_SOURCE 200112L
+# endif
+# ifndef _XOPEN_SOURCE
+#  define _XOPEN_SOURCE 500
+# endif
+#endif /* STRPTIME_NEEDS_STANDARDS */
 
 #include "collectd.h"
 #include "common.h"
@@ -90,6 +98,10 @@ struct list_info_ptr_s
 };
 typedef struct list_info_ptr_s list_info_ptr_t;
 
+/* FIXME: Enabled by default for backwards compatibility. */
+/* TODO: Remove time parsing code. */
+static _Bool config_parse_time = 1;
+
 static char *url                   = NULL;
 static int global_opcodes          = 1;
 static int global_qtypes           = 1;
@@ -241,7 +253,8 @@ static void submit (time_t ts, const char *plugin_instance, /* {{{ */
 
   vl.values = values;
   vl.values_len = 1;
-  vl.time = ts;
+  if (config_parse_time)
+    vl.time = TIME_T_TO_CDTIME_T (ts);
   sstrncpy(vl.host, hostname_g, sizeof(vl.host));
   sstrncpy(vl.plugin, "bind", sizeof(vl.plugin));
   if (plugin_instance) {
@@ -337,36 +350,31 @@ static int bind_xml_list_callback (const char *name, /* {{{ */
   return (0);
 } /* }}} int bind_xml_list_callback */
 
-static int bind_xml_read_counter (xmlDoc *doc, xmlNode *node, /* {{{ */
-    counter_t *ret_value)
+static int bind_xml_read_derive (xmlDoc *doc, xmlNode *node, /* {{{ */
+    derive_t *ret_value)
 {
-  char *str_ptr, *end_ptr;
-  long long int value;
+  char *str_ptr;
+  value_t value;
+  int status;
 
   str_ptr = (char *) xmlNodeListGetString (doc, node->xmlChildrenNode, 1);
   if (str_ptr == NULL)
   {
-    ERROR ("bind plugin: bind_xml_read_counter: xmlNodeListGetString failed.");
+    ERROR ("bind plugin: bind_xml_read_derive: xmlNodeListGetString failed.");
     return (-1);
   }
 
-  errno = 0;
-  value = strtoll (str_ptr, &end_ptr, 10);
-  xmlFree(str_ptr);
-  if (str_ptr == end_ptr || errno)
+  status = parse_value (str_ptr, &value, DS_TYPE_DERIVE);
+  if (status != 0)
   {
-    if (errno && (value < 0))
-      ERROR ("bind plugin: bind_xml_read_counter: strtoll failed with underflow.");
-    else if (errno && (value > 0))
-      ERROR ("bind plugin: bind_xml_read_counter: strtoll failed with overflow.");
-    else
-      ERROR ("bind plugin: bind_xml_read_counter: strtoll failed.");
+    ERROR ("bind plugin: Parsing string \"%s\" to derive value failed.",
+        str_ptr);
     return (-1);
   }
 
-  *ret_value = value;
+  *ret_value = value.derive;
   return (0);
-} /* }}} int bind_xml_read_counter */
+} /* }}} int bind_xml_read_derive */
 
 static int bind_xml_read_gauge (xmlDoc *doc, xmlNode *node, /* {{{ */
     gauge_t *ret_value)
@@ -527,7 +535,7 @@ static int bind_parse_generic_name_value (const char *xpath_expression, /* {{{ *
       if (ds_type == DS_TYPE_GAUGE)
         status = bind_xml_read_gauge (doc, counter, &value.gauge);
       else
-        status = bind_xml_read_counter (doc, counter, &value.counter);
+        status = bind_xml_read_derive (doc, counter, &value.derive);
       if (status != 0)
         continue;
 
@@ -600,7 +608,7 @@ static int bind_parse_generic_value_list (const char *xpath_expression, /* {{{ *
       if (ds_type == DS_TYPE_GAUGE)
         status = bind_xml_read_gauge (doc, child, &value.gauge);
       else
-        status = bind_xml_read_counter (doc, child, &value.counter);
+        status = bind_xml_read_derive (doc, child, &value.derive);
       if (status != 0)
         continue;
 
@@ -791,7 +799,7 @@ static int bind_xml_stats_handle_view (int version, xmlDoc *doc, /* {{{ */
     list_info_ptr_t list_info =
     {
       plugin_instance,
-      /* type = */ "dns_qtype_gauge"
+      /* type = */ "dns_qtype"
     };
 
     ssnprintf (plugin_instance, sizeof (plugin_instance), "%s-qtypes",
@@ -822,13 +830,14 @@ static int bind_xml_stats_handle_view (int version, xmlDoc *doc, /* {{{ */
         doc, path_ctx, current_time, DS_TYPE_COUNTER);
   } /* }}} */
 
+  /* Record types in the cache */
   if (view->cacherrsets != 0) /* {{{ */
   {
     char plugin_instance[DATA_MAX_NAME_LEN];
     list_info_ptr_t list_info =
     {
       plugin_instance,
-      /* type = */ "dns_qtype_gauge"
+      /* type = */ "dns_qtype_cached"
     };
 
     ssnprintf (plugin_instance, sizeof (plugin_instance), "%s-cache_rr_sets",
@@ -1360,6 +1369,8 @@ static int bind_config (oconfig_item_t *ci) /* {{{ */
       bind_config_set_bool ("MemoryStats", &global_memory_stats, child);
     else if (strcasecmp ("View", child->key) == 0)
       bind_config_add_view (child);
+    else if (strcasecmp ("ParseTime", child->key) == 0)
+      cf_util_get_boolean (child, &config_parse_time);
     else
     {
       WARNING ("bind plugin: Unknown configuration option "
@@ -1382,6 +1393,7 @@ static int bind_init (void) /* {{{ */
     return (-1);
   }
 
+  curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1);
   curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, bind_curl_callback);
   curl_easy_setopt (curl, CURLOPT_USERAGENT, PACKAGE_NAME"/"PACKAGE_VERSION);
   curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, bind_curl_error);
index 2d59ea7..e31d95c 100644 (file)
 # include "config.h"
 #endif
 
-#ifndef _ISOC99_SOURCE
-# define _ISOC99_SOURCE
-#endif
-
-#ifndef _POSIX_C_SOURCE
-# define _POSIX_C_SOURCE 200112L
-#endif
-
-#ifndef _XOPEN_SOURCE
-# define _XOPEN_SOURCE 600
-#endif
-
 #if !defined(__GNUC__) || !__GNUC__
 # define __attribute__(x) /**/
 #endif
 #include <string.h>
 #include <strings.h>
 #include <assert.h>
-#include <math.h>
+
+#if NAN_STATIC_DEFAULT
+# include <math.h>
+/* #endif NAN_STATIC_DEFAULT*/
+#elif NAN_STATIC_ISOC
+# ifndef __USE_ISOC99
+#  define DISABLE_ISOC99 1
+#  define __USE_ISOC99 1
+# endif /* !defined(__USE_ISOC99) */
+# include <math.h>
+# if DISABLE_ISOC99
+#  undef DISABLE_ISOC99
+#  undef __USE_ISOC99
+# endif /* DISABLE_ISOC99 */
+/* #endif NAN_STATIC_ISOC */
+#elif NAN_ZERO_ZERO
+# include <math.h>
+# ifdef NAN
+#  undef NAN
+# endif
+# define NAN (0.0 / 0.0)
+# ifndef isnan
+#  define isnan(f) ((f) != (f))
+# endif /* !defined(isnan) */
+# ifndef isfinite
+#  define isfinite(f) (((f) - (f)) == 0.0)
+# endif
+# ifndef isinf
+#  define isinf(f) (!isfinite(f) && !isnan(f))
+# endif
+#endif /* NAN_ZERO_ZERO */
 
 #include "libcollectdclient/collectd/client.h"
 
@@ -251,6 +269,67 @@ static void usage (const char *name)
        exit (1);
 } /* void usage */
 
+static int do_listval (lcc_connection_t *connection)
+{
+       lcc_identifier_t *ret_ident = NULL;
+       size_t ret_ident_num = 0;
+
+       char *hostname = NULL;
+
+       int status;
+       size_t i;
+
+       status = lcc_listval (connection, &ret_ident, &ret_ident_num);
+       if (status != 0) {
+               printf ("UNKNOWN: %s\n", lcc_strerror (connection));
+               if (ret_ident != NULL)
+                       free (ret_ident);
+               return (RET_UNKNOWN);
+       }
+
+       status = lcc_sort_identifiers (connection, ret_ident, ret_ident_num);
+       if (status != 0) {
+               printf ("UNKNOWN: %s\n", lcc_strerror (connection));
+               if (ret_ident != NULL)
+                       free (ret_ident);
+               return (RET_UNKNOWN);
+       }
+
+       for (i = 0; i < ret_ident_num; ++i) {
+               char id[1024];
+
+               if ((hostname_g != NULL) && (strcasecmp (hostname_g, ret_ident[i].host)))
+                       continue;
+
+               if ((hostname == NULL) || strcasecmp (hostname, ret_ident[i].host))
+               {
+                       if (hostname != NULL)
+                               free (hostname);
+                       hostname = strdup (ret_ident[i].host);
+                       printf ("Host: %s\n", hostname);
+               }
+
+               /* empty hostname; not to be printed again */
+               ret_ident[i].host[0] = '\0';
+
+               status = lcc_identifier_to_string (connection,
+                               id, sizeof (id), ret_ident + i);
+               if (status != 0) {
+                       printf ("ERROR: listval: Failed to convert returned "
+                                       "identifier to a string: %s\n",
+                                       lcc_strerror (connection));
+                       continue;
+               }
+
+               /* skip over the (empty) hostname and following '/' */
+               printf ("\t%s\n", id + 1);
+       }
+
+       if (ret_ident != NULL)
+               free (ret_ident);
+       return (RET_OKAY);
+} /* int do_listval */
+
 static int do_check_con_none (size_t values_num,
                double *values, char **values_names)
 {
@@ -490,34 +569,20 @@ static int do_check_con_percentage (size_t values_num,
        return (status_code);
 } /* int do_check_con_percentage */
 
-static int do_check (void)
+static int do_check (lcc_connection_t *connection)
 {
-       lcc_connection_t *connection;
        gauge_t *values;
        char   **values_names;
        size_t   values_num;
-       char address[1024];
        char ident_str[1024];
        lcc_identifier_t ident;
        size_t i;
        int status;
 
-       snprintf (address, sizeof (address), "unix:%s", socket_file_g);
-       address[sizeof (address) - 1] = 0;
-
        snprintf (ident_str, sizeof (ident_str), "%s/%s",
                        hostname_g, value_string_g);
        ident_str[sizeof (ident_str) - 1] = 0;
 
-       connection = NULL;
-       status = lcc_connect (address, &connection);
-       if (status != 0)
-       {
-               printf ("ERROR: Connecting to daemon at %s failed.\n",
-                               socket_file_g);
-               return (RET_CRITICAL);
-       }
-
        memset (&ident, 0, sizeof (ident));
        status = lcc_string_to_identifier (connection, &ident, ident_str);
        if (status != 0)
@@ -565,6 +630,11 @@ static int do_check (void)
 
 int main (int argc, char **argv)
 {
+       char address[1024];
+       lcc_connection_t *connection;
+
+       int status;
+
        range_critical_g.min = NAN;
        range_critical_g.max = NAN;
        range_critical_g.invert = 0;
@@ -646,11 +716,26 @@ int main (int argc, char **argv)
        }
 
        if ((socket_file_g == NULL) || (value_string_g == NULL)
-                       || (hostname_g == NULL))
+                       || ((hostname_g == NULL) && (strcasecmp (value_string_g, "LIST"))))
        {
                fprintf (stderr, "Missing required arguments.\n");
                usage (argv[0]);
        }
 
-       return (do_check ());
+       snprintf (address, sizeof (address), "unix:%s", socket_file_g);
+       address[sizeof (address) - 1] = 0;
+
+       connection = NULL;
+       status = lcc_connect (address, &connection);
+       if (status != 0)
+       {
+               printf ("ERROR: Connecting to daemon at %s failed.\n",
+                               socket_file_g);
+               return (RET_CRITICAL);
+       }
+
+       if (0 == strcasecmp (value_string_g, "LIST"))
+               return (do_listval (connection));
+
+       return (do_check (connection));
 } /* int main */
index 6b44722..ee05e00 100644 (file)
@@ -208,7 +208,7 @@ layout looks like this:
   {
     values => [123, 0.5],
     time   => time (),
-    interval => $interval_g,
+    interval => plugin_get_interval (),
     host   => $hostname_g,
     plugin => 'myplugin',
     type   => 'myplugin',
@@ -415,6 +415,13 @@ The message is passed to all log-callbacks that are registered with collectd.
 Wrappers around B<plugin_log>, using B<LOG_ERR>, B<LOG_WARNING>,
 B<LOG_NOTICE>, B<LOG_INFO> and B<LOG_DEBUG> respectively as I<log-level>.
 
+=item B<plugin_get_interval> ()
+
+Returns the interval of the current plugin as a floating point number in
+seconds. This value depends on the interval configured within the
+C<LoadPlugin perl> block or the global interval (see L<collectd.conf(5)> for
+details).
+
 =back
 
 The following function provides the filter chain C-interface to Perl-modules.
@@ -494,6 +501,11 @@ B<FQDNLookup> configuration options (see L<collectd.conf(5)> for details).
 This variable keeps the interval in seconds in which the read functions are
 queried (see the B<Interval> configuration option).
 
+B<Note:> This variable should no longer be used in favor of
+C<plugin_get_interval()> (see above). This function takes any plugin-specific
+interval settings into account (see the C<Interval> option of C<LoadPlugin> in
+L<collectd.conf(5)> for details).
+
 =back
 
 Any changes to these variables will be globally visible in collectd.
@@ -656,9 +668,9 @@ A very simple read function might look like:
 
   sub foobar_read
   {
-    my $vl = { plugin => 'foobar' };
+    my $vl = { plugin => 'foobar', type => 'gauge' };
     $vl->{'values'} = [ rand(42) ];
-    plugin_dispatch_values ('gauge', $vl);
+    plugin_dispatch_values ($vl);
     return 1;
   }
 
index 267296c..39503ad 100644 (file)
@@ -21,7 +21,7 @@ collectd-python - Documentation of collectd's C<python plugin>
   <Plugin python>
     ModulePath "/path/to/your/python/modules"
     LogTraces true
-    Interactive true
+    Interactive false
     Import "spam"
 
     <Module spam>
@@ -37,7 +37,7 @@ for collectd in Python. This is a lot more efficient than executing a
 Python-script every time you want to read a value with the C<exec plugin> (see
 L<collectd-exec(5)>) and provides a lot more functionality, too.
 
-At least python I<version 2.3> is required.
+The minimum required Python version is I<2.3>.
 
 =head1 CONFIGURATION
 
@@ -47,9 +47,9 @@ At least python I<version 2.3> is required.
 
 Loads the Python plugin I<Plugin>. Unlike most other LoadPlugin lines, this one
 should be a block containing the line "Globals true". This will cause collectd
-to export the name of all objects in the python interpreter for all plugins to
+to export the name of all objects in the Python interpreter for all plugins to
 see. If you don't do this or your platform does not support it, the embedded
-interpreter will start anyway but you won't be able to load certain python
+interpreter will start anyway but you won't be able to load certain Python
 modules, e.g. "time".
 
 =item B<Encoding> I<Name>
@@ -68,25 +68,25 @@ use multiple B<ModulePath> lines to add more than one directory.
 
 =item B<LogTraces> I<bool>
 
-If a python script throws an exception it will be logged by collectd with the
+If a Python script throws an exception it will be logged by collectd with the
 name of the exception and the message. If you set this option to true it will
 also log the full stacktrace just like the default output of an interactive
-python interpreter. This should probably be set to false most of the time but
+Python interpreter. This should probably be set to false most of the time but
 is very useful for development and debugging of new modules.
 
 =item B<Interactive> I<bool>
 
-This option will cause the module to launch an interactive python interpreter
+This option will cause the module to launch an interactive Python interpreter
 that reads from and writes to the terminal. Note that collectd will terminate
 right after starting up if you try to run it as a daemon while this option is
-enabled to make sure to start collectd with the B<-f> option.
+enabled so make sure to start collectd with the B<-f> option.
 
 The B<collectd> module is I<not> imported into the interpreter's globals. You
 have to do it manually. Be sure to read the help text of the module, it can be
 used as a reference guide during coding.
 
 This interactive session will behave slightly differently from a daemonized
-collectd script as well as from a normal python interpreter:
+collectd script as well as from a normal Python interpreter:
 
 =over 4
 
@@ -107,22 +107,22 @@ To quit collectd send I<EOF> (press I<Ctrl+D> at the beginning of a new line).
 
 =item
 
-B<3.> collectd handles I<SIGCHLD>. This means that python won't be able to
+B<3.> collectd handles I<SIGCHLD>. This means that Python won't be able to
 determine the return code of spawned processes with system(), popen() and
-subprocess. This will result in python not using external programs like less
+subprocess. This will result in Python not using external programs like less
 to display help texts. You can override this behavior with the B<PAGER>
 environment variable, e.g. I<export PAGER=less> before starting collectd.
-Depending on your version of python this might or might not result in an
+Depending on your version of Python this might or might not result in an
 B<OSError> exception which can be ignored.
 
-If you really need to spawn new processes from python you can register an init
+If you really need to spawn new processes from Python you can register an init
 callback and reset the action for SIGCHLD to the default behavior. Please note
 that this I<will> break the exec plugin. Do not even load the exec plugin if
 you intend to do this!
 
 There is an example script located in B<contrib/python/getsigchld.py>  to do
 this. If you import this from I<collectd.conf> SIGCHLD will be handled
-normally and spawning processes from python will work as intended.
+normally and spawning processes from Python will work as intended.
 
 =back
 
@@ -139,22 +139,22 @@ The I<name> identifies the callback.
 
 =head1 STRINGS
 
-There are a lot of places where strings are send from collectd to python and
-from python to collectd. How exactly this works depends on wheather byte or
-unicode strings or python2 or python3 are used.
+There are a lot of places where strings are sent from collectd to Python and
+from Python to collectd. How exactly this works depends on whether byte or
+unicode strings or Python2 or Python3 are used.
 
 Python2 has I<str>, which is just bytes, and I<unicode>. Python3 has I<str>,
 which is a unicode object, and I<bytes>.
 
-When passing strings from python to collectd all of these object are supported
+When passing strings from Python to collectd all of these object are supported
 in all places, however I<str> should be used if possible. These strings must
 not contain a NUL byte. Ignoring this will result in a I<TypeError> exception.
 If a byte string was used it will be used as is by collectd. If a unicode
 object was used it will be encoded using the default encoding (see above). If
-this is not possible python will raise a I<UnicodeEncodeError> exception.
+this is not possible Python will raise a I<UnicodeEncodeError> exception.
 
-Wenn passing strings from collectd to python the behavior depends on the
-python version used. Python2 will always receive a I<str> object. Python3 will
+When passing strings from collectd to Python the behavior depends on the
+Python version used. Python2 will always receive a I<str> object. Python3 will
 usually receive a I<str> object as well, however the original string will be
 decoded to unicode using the default encoding. If this fails because the
 string is not a valid sequence for this encoding a I<bytes> object will be
@@ -174,7 +174,7 @@ example. The following types of B<callback functions> are known to collectd
 
 =item configuration functions
 
-This type of functions is called during configuration if an appropriate
+These are called during configuration if an appropriate
 B<Module> block has been encountered. It is called once for each B<Module>
 block which matches the name of the callback as provided with the
 B<register_config> method - see below.
@@ -184,14 +184,14 @@ threading functions here!
 
 =item init functions
 
-This type of functions is called once after loading the module and before any
+These are called once after loading the module and before any
 calls to the read and write functions. It should be used to initialize the
 internal state of the plugin (e.E<nbsp>g. open sockets, ...). This is the
 earliest point where you may use threads.
 
 =item read functions
 
-This type of function is used to collect the actual data. It is called once
+These are used to collect the actual data. It is called once
 per interval (see the B<Interval> configuration option of collectd). Usually
 it will call B<plugin_dispatch_values> to dispatch the values to collectd
 which will pass them on to all registered B<write functions>. If this function
@@ -200,23 +200,23 @@ amount of time until it returns normally again.
 
 =item write functions
 
-This type of function is used to write the dispatched values. It is called
+These are used to write the dispatched values. It is called
 once for every value that was dispatched by any plugin.
 
 =item flush functions
 
-This type of function is used to flush internal caches of plugins. It is
+These are used to flush internal caches of plugins. It is
 usually triggered by the user only. Any plugin which caches data before
 writing it to disk should provide this kind of callback function.
 
 =item log functions
 
-This type of function is used to pass messages of plugins or the daemon itself
+These are used to pass messages of plugins or the daemon itself
 to the user.
 
 =item notification function
 
-This type of function is used to act upon notifications. In general, a
+These are used to act upon notifications. In general, a
 notification is a status message that may be associated with a data instance.
 Usually, a notification is generated by the daemon if a configured threshold
 has been exceeded (see the section "THRESHOLD CONFIGURATION" in
@@ -225,12 +225,12 @@ notifications as well.
 
 =item shutdown functions
 
-This type of function is called once before the daemon shuts down. It should
+These are called once before the daemon shuts down. It should
 be used to clean up the plugin (e.g. close sockets, ...).
 
 =back
 
-Any function (except log functions) may set throw an exception in case of any
+Any function (except log functions) may throw an exception in case of
 errors. The exception will be passed on to the user using collectd's logging
 mechanism. If a log callback throws an exception it will be printed to standard
 error instead.
@@ -306,7 +306,7 @@ config file. It will always be a string.
 This is a tuple (which might be empty) of all value, i.e. words following the
 keyword in any given line in the config file.
 
-Every item in this tuple will be either a string or a float or a boolean,
+Every item in this tuple will be either a string, a float or a boolean,
 depending on the contents of the configuration file.
 
 =item children
@@ -367,7 +367,7 @@ Type instance string. May be empty.
 
 =head2 Values
 
-A Value is an object which features a sequence of values. It is based on then
+A Value is an object which features a sequence of values. It is based on the
 I<PluginData> type and uses its members to identify the values.
 
  class Values(PluginData)
@@ -495,7 +495,7 @@ Data descriptors defined here:
 
 =item message
 
-Some kind of description what's going on and why this Notification was
+Some kind of description of what's going on and why this Notification was
 generated.
 
 =item severity
@@ -534,9 +534,12 @@ your callback, not even None.
 I<name> is an optional identifier for this callback. The default name is
 B<python>.I<module>. I<module> is taken from the B<__module__> attribute of
 your callback function. Every callback needs a unique identifier, so if you
-want to register the same callback multiple time in the same module you need to
-specify a name here. Otherwise it's save to ignore this parameter I<identifier>
-is the full identifier assigned to this callback.
+want to register the same callback multiple times in the same module you need to
+specify a name here. Otherwise it's safe to ignore this parameter.
+
+=item
+
+I<identifier> is the full identifier assigned to this callback.
 
 =back
 
@@ -549,7 +552,7 @@ L<"WRITING YOUR OWN PLUGINS"> above) and are passed the following arguments:
 
 The only argument passed is a I<Config> object. See above for the layout of this
 data type.
-Note that you can not receive the whole config files this way, only B<Module>
+Note that you cannot receive the whole config files this way, only B<Module>
 blocks inside the Python configuration block. Additionally you will only
 receive blocks where your callback identifier matches B<python.>I<blockname>.
 
@@ -570,7 +573,7 @@ The callback will be called without arguments.
 
 =item register_write
 
-The callback function will be called with one arguments passed, which will be a
+The callback function will be called with one argument passed, which will be a
 I<Values> object. For the layout of I<Values> see above.
 If this callback function throws an exception the next call will be delayed by
 an increasing interval.
@@ -657,7 +660,7 @@ types used by the read, write and match functions.
 
 =item
 
-Please feel free to send in new plugins to collectd's mailinglist at
+Please feel free to send in new plugins to collectd's mailing list at
 E<lt>collectdE<nbsp>atE<nbsp>verplant.orgE<gt> for review and, possibly,
 inclusion in the main distribution. In the latter case, we will take care of
 keeping the plugin up to date and adapting it to new versions of collectd.
@@ -673,7 +676,7 @@ L<http://collectd.org/dev-info.shtml>.
 
 =item
 
-collectd is heavily multi-threaded. Each collectd thread accessing the python
+collectd is heavily multi-threaded. Each collectd thread accessing the Python
 plugin will be mapped to a Python interpreter thread. Any such thread will be
 created and destroyed transparently and on-the-fly.
 
@@ -703,7 +706,7 @@ dispatched by the python plugin after upgrades.
 
 =item
 
-Not all aspects of the collectd API are accessible from python. This includes
+Not all aspects of the collectd API are accessible from Python. This includes
 but is not limited to filters and data sets.
 
 =back
diff --git a/src/collectd-threshold.pod b/src/collectd-threshold.pod
new file mode 100644 (file)
index 0000000..02e41b8
--- /dev/null
@@ -0,0 +1,201 @@
+=head1 NAME
+
+collectd-threshold - Documentation of collectd's I<Threshold plugin>
+
+=head1 SYNOPSIS
+
+ LoadPlugin "threshold"
+ <Plugin "threshold">
+   <Type "foo">
+     WarningMin    0.00
+     WarningMax 1000.00
+     FailureMin    0.00
+     FailureMax 1200.00
+     Invert false
+     Instance "bar"
+   </Type>
+ </Plugin>
+
+=head1 DESCRIPTION
+
+Starting with version C<4.3.0> I<collectd> has support for B<monitoring>. By
+that we mean that the values are not only stored or sent somewhere, but that
+they are judged and, if a problem is recognized, acted upon. The only action
+the I<Threshold plugin> takes itself is to generate and dispatch a
+I<notification>. Other plugins can register to receive notifications and
+perform appropriate further actions.
+
+Since systems and what you expect them to do differ a lot, you can configure
+I<thresholds> for your values freely. This gives you a lot of flexibility but
+also a lot of responsibility.
+
+Every time a value is out of range, a notification is dispatched. This means
+that the idle percentage of your CPU needs to be less then the configured
+threshold only once for a notification to be generated. There's no such thing
+as a moving average or similar - at least not now.
+
+Also, all values that match a threshold are considered to be relevant or
+"interesting". As a consequence collectd will issue a notification if they are
+not received for B<Timeout> iterations. The B<Timeout> configuration option is
+explained in section L<collectd.conf(5)/"GLOBAL OPTIONS">. If, for example,
+B<Timeout> is set to "2" (the default) and some hosts sends it's CPU statistics
+to the server every 60 seconds, a notification will be dispatched after about
+120 seconds. It may take a little longer because the timeout is checked only
+once each B<Interval> on the server.
+
+When a value comes within range again or is received after it was missing, an
+"OKAY-notification" is dispatched.
+
+=head1 CONFIGURATION
+
+Here is a configuration example to get you started. Read below for more
+information.
+
+ LoadPlugin "threshold"
+ <Plugin "threshold">
+   <Type "foo">
+     WarningMin    0.00
+     WarningMax 1000.00
+     FailureMin    0.00
+     FailureMax 1200.00
+     Invert false
+     Instance "bar"
+   </Type>
+   
+   <Plugin "interface">
+     Instance "eth0"
+     <Type "if_octets">
+       FailureMax 10000000
+       DataSource "rx"
+     </Type>
+   </Plugin>
+   
+   <Host "hostname">
+     <Type "cpu">
+       Instance "idle"
+       FailureMin 10
+     </Type>
+   
+     <Plugin "memory">
+       <Type "memory">
+         Instance "cached"
+         WarningMin 100000000
+       </Type>
+     </Plugin>
+   
+     <Type "load">
+       DataSource "midterm"
+       FailureMax 4
+       Hits 3
+       Hysteresis 3
+     </Type>
+   </Host>
+ </Plugin>
+
+There are basically two types of configuration statements: The C<Host>,
+C<Plugin>, and C<Type> blocks select the value for which a threshold should be
+configured. The C<Plugin> and C<Type> blocks may be specified further using the
+C<Instance> option. You can combine the block by nesting the blocks, though
+they must be nested in the above order, i.e. C<Host> may contain either
+C<Plugin> and C<Type> blocks, C<Plugin> may only contain C<Type> blocks and
+C<Type> may not contain other blocks. If multiple blocks apply to the same
+value the most specific block is used.
+
+The other statements specify the threshold to configure. They B<must> be
+included in a C<Type> block. Currently the following statements are recognized:
+
+=over 4
+
+=item B<FailureMax> I<Value>
+
+=item B<WarningMax> I<Value>
+
+Sets the upper bound of acceptable values. If unset defaults to positive
+infinity. If a value is greater than B<FailureMax> a B<FAILURE> notification
+will be created. If the value is greater than B<WarningMax> but less than (or
+equal to) B<FailureMax> a B<WARNING> notification will be created.
+
+=item B<FailureMin> I<Value>
+
+=item B<WarningMin> I<Value>
+
+Sets the lower bound of acceptable values. If unset defaults to negative
+infinity. If a value is less than B<FailureMin> a B<FAILURE> notification will
+be created. If the value is less than B<WarningMin> but greater than (or equal
+to) B<FailureMin> a B<WARNING> notification will be created.
+
+=item B<DataSource> I<DSName>
+
+Some data sets have more than one "data source". Interesting examples are the
+C<if_octets> data set, which has received (C<rx>) and sent (C<tx>) bytes and
+the C<disk_ops> data set, which holds C<read> and C<write> operations. The
+system load data set, C<load>, even has three data sources: C<shortterm>,
+C<midterm>, and C<longterm>.
+
+Normally, all data sources are checked against a configured threshold. If this
+is undesirable, or if you want to specify different limits for each data
+source, you can use the B<DataSource> option to have a threshold apply only to
+one data source.
+
+=item B<Invert> B<true>|B<false>
+
+If set to B<true> the range of acceptable values is inverted, i.e. values
+between B<FailureMin> and B<FailureMax> (B<WarningMin> and B<WarningMax>) are
+not okay. Defaults to B<false>.
+
+=item B<Persist> B<true>|B<false>
+
+Sets how often notifications are generated. If set to B<true> one notification
+will be generated for each value that is out of the acceptable range. If set to
+B<false> (the default) then a notification is only generated if a value is out
+of range but the previous value was okay.
+
+This applies to missing values, too: If set to B<true> a notification about a
+missing value is generated once every B<Interval> seconds. If set to B<false>
+only one such notification is generated until the value appears again.
+
+=item B<PersistOK> B<true>|B<false>
+
+Sets how OKAY notifications act. If set to B<true> one notification will be
+generated for each value that is in the acceptable range. If set to B<false>
+(the default) then a notification is only generated if a value is in range but
+the previous value was not.
+
+=item B<Percentage> B<true>|B<false>
+
+If set to B<true>, the minimum and maximum values given are interpreted as
+percentage value, relative to the other data sources. This is helpful for
+example for the "df" type, where you may want to issue a warning when less than
+5E<nbsp>% of the total space is available. Defaults to B<false>.
+
+=item B<Hits> I<Value>
+
+Sets the number of occurrences which the threshold must be raised before to
+dispatch any notification or, in other words, the number of B<Interval>s
+that the threshold must be match before dispatch any notification.
+
+=item B<Hysteresis> I<Value>
+
+Sets the hysteresis value for threshold. The hysteresis is a method to prevent
+flapping between states, until a new received value for a previously matched
+threshold down below the threshold condition (B<WarningMax>, B<FailureMin> or
+everything else) minus the hysteresis value, the failure (respectively warning)
+state will be keep.
+
+=item B<Interesting> B<true>|B<false>
+
+If set to B<true> (the default), the threshold must be treated as interesting
+and, when a number of B<Timeout> values will lost, then a missing notification
+will be dispatched. On the other hand, if set to B<false>, the missing
+notification will never dispatched for this threshold.
+
+=back
+
+=head1 SEE ALSO
+
+L<collectd(1)>,
+L<collectd.conf(5)>
+
+=head1 AUTHOR
+
+Florian Forster E<lt>octoE<nbsp>atE<nbsp>collectd.orgE<gt>
index 277d3b0..d96d676 100644 (file)
@@ -40,7 +40,7 @@
  * Global variables
  */
 char hostname_g[DATA_MAX_NAME_LEN];
-int  interval_g;
+cdtime_t interval_g;
 int  timeout_g;
 #if HAVE_LIBKSTAT
 kstat_ctl_t *kc;
@@ -51,7 +51,9 @@ static int loop = 0;
 static void *do_flush (void __attribute__((unused)) *arg)
 {
        INFO ("Flushing all data.");
-       plugin_flush (NULL, -1, NULL);
+       plugin_flush (/* plugin = */ NULL,
+                       /* timeout = */ 0,
+                       /* ident = */ NULL);
        INFO ("Finished flushing all data.");
        pthread_exit (NULL);
        return NULL;
@@ -77,6 +79,7 @@ static void sig_usr1_handler (int __attribute__((unused)) signal)
        pthread_attr_init (&attr);
        pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
        pthread_create (&thread, &attr, do_flush, NULL);
+       pthread_attr_destroy (&attr);
 }
 
 static int init_hostname (void)
@@ -135,19 +138,11 @@ static int init_hostname (void)
 
 static int init_global_variables (void)
 {
-       const char *str;
+       char const *str;
 
-       str = global_option_get ("Interval");
-       if (str == NULL)
-               str = "10";
-       interval_g = atoi (str);
-       if (interval_g <= 0)
-       {
-               fprintf (stderr, "Cannot set the interval to a correct value.\n"
-                               "Please check your settings.\n");
-               return (-1);
-       }
-       DEBUG ("interval_g = %i;", interval_g);
+       interval_g = cf_get_default_interval ();
+       assert (interval_g > 0);
+       DEBUG ("interval_g = %.3f;", CDTIME_T_TO_DOUBLE (interval_g));
 
        str = global_option_get ("Timeout");
        if (str == NULL)
@@ -170,10 +165,11 @@ static int init_global_variables (void)
 
 static int change_basedir (const char *orig_dir)
 {
-       char *dir = strdup (orig_dir);
-       int dirlen;
+       char *dir;
+       size_t dirlen;
        int status;
 
+       dir = strdup (orig_dir);
        if (dir == NULL)
        {
                char errbuf[1024];
@@ -190,39 +186,41 @@ static int change_basedir (const char *orig_dir)
                return (-1);
 
        status = chdir (dir);
-       free (dir);
+       if (status == 0)
+       {
+               free (dir);
+               return (0);
+       }
+       else if (errno != ENOENT)
+       {
+               char errbuf[1024];
+               ERROR ("change_basedir: chdir (%s): %s", dir,
+                               sstrerror (errno, errbuf, sizeof (errbuf)));
+               free (dir);
+               return (-1);
+       }
 
+       status = mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO);
        if (status != 0)
        {
-               if (errno == ENOENT)
-               {
-                       if (mkdir (orig_dir, 0755) == -1)
-                       {
-                               char errbuf[1024];
-                               ERROR ("change_basedir: mkdir (%s): %s", orig_dir,
-                                               sstrerror (errno, errbuf,
-                                                       sizeof (errbuf)));
-                               return (-1);
-                       }
-                       else if (chdir (orig_dir) == -1)
-                       {
-                               char errbuf[1024];
-                               ERROR ("chdir (%s): %s", orig_dir,
-                                               sstrerror (errno, errbuf,
-                                                       sizeof (errbuf)));
-                               return (-1);
-                       }
-               }
-               else
-               {
-                       char errbuf[1024];
-                       ERROR ("chdir (%s): %s", orig_dir,
-                                       sstrerror (errno, errbuf,
-                                               sizeof (errbuf)));
-                       return (-1);
-               }
+               char errbuf[1024];
+               ERROR ("change_basedir: mkdir (%s): %s", dir,
+                               sstrerror (errno, errbuf, sizeof (errbuf)));
+               free (dir);
+               return (-1);
+       }
+
+       status = chdir (dir);
+       if (status != 0)
+       {
+               char errbuf[1024];
+               ERROR ("change_basedir: chdir (%s): %s", dir,
+                               sstrerror (errno, errbuf, sizeof (errbuf)));
+               free (dir);
+               return (-1);
        }
 
+       free (dir);
        return (0);
 } /* static int change_basedir (char *dir) */
 
@@ -311,22 +309,15 @@ static int do_init (void)
 
 static int do_loop (void)
 {
-       struct timeval tv_now;
-       struct timeval tv_next;
-       struct timeval tv_wait;
-       struct timespec ts_wait;
+       cdtime_t interval = cf_get_default_interval ();
+       cdtime_t wait_until;
+
+       wait_until = cdtime () + interval;
 
        while (loop == 0)
        {
-               if (gettimeofday (&tv_next, NULL) < 0)
-               {
-                       char errbuf[1024];
-                       ERROR ("gettimeofday failed: %s",
-                                       sstrerror (errno, errbuf,
-                                               sizeof (errbuf)));
-                       return (-1);
-               }
-               tv_next.tv_sec += interval_g;
+               struct timespec ts_wait = { 0, 0 };
+               cdtime_t now;
 
 #if HAVE_LIBKSTAT
                update_kstat ();
@@ -335,27 +326,20 @@ static int do_loop (void)
                /* Issue all plugins */
                plugin_read_all ();
 
-               if (gettimeofday (&tv_now, NULL) < 0)
-               {
-                       char errbuf[1024];
-                       ERROR ("gettimeofday failed: %s",
-                                       sstrerror (errno, errbuf,
-                                               sizeof (errbuf)));
-                       return (-1);
-               }
-
-               if (timeval_cmp (tv_next, tv_now, &tv_wait) <= 0)
+               now = cdtime ();
+               if (now >= wait_until)
                {
                        WARNING ("Not sleeping because the next interval is "
-                                       "%i.%06i seconds in the past!",
-                                       (int) tv_wait.tv_sec, (int) tv_wait.tv_usec);
+                                       "%.3f seconds in the past!",
+                                       CDTIME_T_TO_DOUBLE (now - wait_until));
+                       wait_until = now + interval;
                        continue;
                }
 
-               ts_wait.tv_sec  = tv_wait.tv_sec;
-               ts_wait.tv_nsec = (long) (1000 * tv_wait.tv_usec);
+               CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
+               wait_until = wait_until + interval;
 
-               while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) == -1))
+               while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
                {
                        if (errno != EINTR)
                        {
@@ -368,7 +352,6 @@ static int do_loop (void)
                }
        } /* while (loop == 0) */
 
-       DEBUG ("return (0);");
        return (0);
 } /* int do_loop */
 
@@ -472,6 +455,8 @@ int main (int argc, char **argv)
        if (optind < argc)
                exit_usage (1);
 
+       plugin_init_ctx ();
+
        /*
         * Read options from the config file, the environment and the command
         * line (in that order, with later options overwriting previous ones in
index 42addd2..9f5dedc 100644 (file)
@@ -52,6 +52,7 @@
 # to missing dependencies or because they have been deactivated explicitly.  #
 ##############################################################################
 
+#@BUILD_PLUGIN_AGGREGATION_TRUE@LoadPlugin aggregation
 #@BUILD_PLUGIN_AMQP_TRUE@LoadPlugin amqp
 #@BUILD_PLUGIN_APACHE_TRUE@LoadPlugin apache
 #@BUILD_PLUGIN_APCUPS_TRUE@LoadPlugin apcups
@@ -73,6 +74,7 @@
 #@BUILD_PLUGIN_DNS_TRUE@LoadPlugin dns
 #@BUILD_PLUGIN_EMAIL_TRUE@LoadPlugin email
 #@BUILD_PLUGIN_ENTROPY_TRUE@LoadPlugin entropy
+#@BUILD_PLUGIN_ETHSTAT_TRUE@LoadPlugin ethstat
 #@BUILD_PLUGIN_EXEC_TRUE@LoadPlugin exec
 #@BUILD_PLUGIN_FILECOUNT_TRUE@LoadPlugin filecount
 #@BUILD_PLUGIN_FSCACHE_TRUE@LoadPlugin fscache
 #@BUILD_PLUGIN_JAVA_TRUE@LoadPlugin java
 #@BUILD_PLUGIN_LIBVIRT_TRUE@LoadPlugin libvirt
 @BUILD_PLUGIN_LOAD_TRUE@@BUILD_PLUGIN_LOAD_TRUE@LoadPlugin load
+#@BUILD_PLUGIN_LPAR_TRUE@LoadPlugin lpar
 #@BUILD_PLUGIN_MADWIFI_TRUE@LoadPlugin madwifi
 #@BUILD_PLUGIN_MBMON_TRUE@LoadPlugin mbmon
+#@BUILD_PLUGIN_MD_TRUE@LoadPlugin md
 #@BUILD_PLUGIN_MEMCACHEC_TRUE@LoadPlugin memcachec
 #@BUILD_PLUGIN_MEMCACHED_TRUE@LoadPlugin memcached
 @BUILD_PLUGIN_MEMORY_TRUE@@BUILD_PLUGIN_MEMORY_TRUE@LoadPlugin memory
 #@BUILD_PLUGIN_NOTIFY_DESKTOP_TRUE@LoadPlugin notify_desktop
 #@BUILD_PLUGIN_NOTIFY_EMAIL_TRUE@LoadPlugin notify_email
 #@BUILD_PLUGIN_NTPD_TRUE@LoadPlugin ntpd
+#@BUILD_PLUGIN_NUMA_TRUE@LoadPlugin numa
 #@BUILD_PLUGIN_NUT_TRUE@LoadPlugin nut
 #@BUILD_PLUGIN_OLSRD_TRUE@LoadPlugin olsrd
 #@BUILD_PLUGIN_ONEWIRE_TRUE@LoadPlugin onewire
 #@BUILD_PLUGIN_OPENVPN_TRUE@LoadPlugin openvpn
 #@BUILD_PLUGIN_ORACLE_TRUE@LoadPlugin oracle
-#@BUILD_PLUGIN_PERL_TRUE@LoadPlugin perl
+#@BUILD_PLUGIN_PERL_TRUE@<LoadPlugin perl>
+#@BUILD_PLUGIN_PERL_TRUE@  Globals true
+#@BUILD_PLUGIN_PERL_TRUE@</LoadPlugin>
 #@BUILD_PLUGIN_PINBA_TRUE@LoadPlugin pinba
 #@BUILD_PLUGIN_PING_TRUE@LoadPlugin ping
 #@BUILD_PLUGIN_POSTGRESQL_TRUE@LoadPlugin postgresql
 #@BUILD_PLUGIN_POWERDNS_TRUE@LoadPlugin powerdns
 #@BUILD_PLUGIN_PROCESSES_TRUE@LoadPlugin processes
 #@BUILD_PLUGIN_PROTOCOLS_TRUE@LoadPlugin protocols
-#@BUILD_PLUGIN_PYTHON_TRUE@LoadPlugin python
+#@BUILD_PLUGIN_PYTHON_TRUE@<LoadPlugin python>
+#@BUILD_PLUGIN_PYTHON_TRUE@  Globals true
+#@BUILD_PLUGIN_PYTHON_TRUE@</LoadPlugin>
 #@BUILD_PLUGIN_REDIS_TRUE@LoadPlugin redis
 #@BUILD_PLUGIN_ROUTEROS_TRUE@LoadPlugin routeros
 #@BUILD_PLUGIN_RRDCACHED_TRUE@LoadPlugin rrdcached
 #@BUILD_PLUGIN_VMEM_TRUE@LoadPlugin vmem
 #@BUILD_PLUGIN_VSERVER_TRUE@LoadPlugin vserver
 #@BUILD_PLUGIN_WIRELESS_TRUE@LoadPlugin wireless
+#@BUILD_PLUGIN_WRITE_GRAPHITE_TRUE@LoadPlugin write_graphite
 #@BUILD_PLUGIN_WRITE_HTTP_TRUE@LoadPlugin write_http
 #@BUILD_PLUGIN_WRITE_REDIS_TRUE@LoadPlugin write_redis
+#@BUILD_PLUGIN_WRITE_MONGODB_TRUE@LoadPlugin write_mongodb
 #@BUILD_PLUGIN_XMMS_TRUE@LoadPlugin xmms
 #@BUILD_PLUGIN_ZFS_ARC_TRUE@LoadPlugin zfs_arc
 
 # ription of those options is available in the collectd.conf(5) manual page. #
 ##############################################################################
 
+#<Plugin "aggregation">
+#  <Aggregation>
+#    #Host "unspecified"
+#    Plugin "cpu"
+#    #PluginInstance "unspecified"
+#    Type "cpu"
+#    #TypeInstance "unspecified"
+#
+#    GroupBy "Host"
+#    GroupBy "TypeInstance"
+#
+#    CalculateNum false
+#    CalculateSum false
+#    CalculateAverage true
+#    CalculateMinimum false
+#    CalculateMaximum false
+#    CalculateStddev false
+#  </Aggregation>
+#</Plugin>
+
 #<Plugin "amqp">
 #  <Publish "name">
 #    Host "localhost"
 
 #<Plugin "bind">
 #  URL "http://localhost:8053/"
+#  ParseTime       false
 #  OpCodes         true
 #  QTypes          true
 #
 #      MaxConns 5
 #</Plugin>
 
+#<Plugin ethstat>
+#      Interface "eth0"
+#      Map "rx_csum_offload_errors" "if_rx_errors" "checksum_offload"
+#      Map "multicast" "if_multicast"
+#      MappedOnly false
+#</Plugin>
+
 #<Plugin exec>
 #      Exec "user:group" "/path/to/exec"
 #      NotificationExec "user:group" "/path/to/exec"
 #<Plugin hddtemp>
 #  Host "127.0.0.1"
 #  Port "7634"
-#
-#  #----------------------------------------------------------------#
-#  # `TranslateDevicename' enables backwards compatibility behavior #
-#  # and is enabled by default. Setting this option to `false' is   #
-#  # highly recommended.                                            #
-#  #----------------------------------------------------------------#
-#  TranslateDevicename false
 #</Plugin>
 
 #<Plugin interface>
 #      InterfaceFormat name
 #</Plugin>
 
+#<Plugin lpar>
+#      CpuPoolStats   false
+#      ReportBySerial false
+#</Plugin>
+
 #<Plugin madwifi>
 #      Interface "wlan0"
 #      IgnoreSelected false
 #      Port "411"
 #</Plugin>
 
+#<Plugin md>
+#      Device "/dev/md0"
+#      IgnoreSelected false
+#</Plugin>
+
 #<Plugin memcachec>
 #      <Page "plugin_instance">
 #              Server "localhost"
 #</Plugin>
 
 #<Plugin memcached>
-#      Host "127.0.0.1"
-#      Port "11211"
+#      <Instance "local">
+#              Host "127.0.0.1"
+#              Port "11211"
+#      </Instance>
 #</Plugin>
 
 #<Plugin modbus>
 #      Host "localhost"
 #      Port 123
 #      ReverseLookups false
+#      IncludeUnitID true
 #</Plugin>
 
 #<Plugin nut>
 #</Plugin>
 
 #<Plugin sensors>
+#      SensorConfigFile "/etc/sensors.conf"
 #      Sensor "it8712-isa-0290/temperature-temp1"
 #      Sensor "it8712-isa-0290/fanspeed-fan3"
 #      Sensor "it8712-isa-0290/voltage-in8"
 #   </Host>
 #</Plugin>
 
+#<Plugin "swap">
+#      ReportByDevice false
+#      ReportBytes true
+#</Plugin>
+
 #<Plugin "table">
 #      <Table "/proc/slabinfo">
 #              Instance "slabinfo"
 #      SocketFile "@prefix@/var/run/@PACKAGE_NAME@-unixsock"
 #      SocketGroup "collectd"
 #      SocketPerms "0660"
+#      DeleteSocket false
 #</Plugin>
 
 #<Plugin uuid>
 #      Verbose false
 #</Plugin>
 
+#<Plugin write_graphite>
+#  <Carbon>
+#    Host "localhost"
+#    Port "2003"
+#    Prefix "collectd"
+#    Postfix "collectd"
+#    StoreRates false
+#    AlwaysAppendDS false
+#    EscapeCharacter "_"
+#  </Carbon>
+#</Plugin>
+
 #<Plugin write_http>
 #      <URL "http://example.com/collectd-post">
 #              User "collectd"
 #      </Node>
 #</Plugin>
 
+#<Plugin write_mongodb>
+#      <Node "example">
+#              Host "localhost"
+#              Port "27017"
+#              Timeout 1000
+#              StoreRates false
+#      </Node>
+#</Plugin>
+
 ##############################################################################
 # Filter configuration                                                       #
 #----------------------------------------------------------------------------#
 #@BUILD_PLUGIN_TARGET_REPLACE_TRUE@LoadPlugin target_replace
 #@BUILD_PLUGIN_TARGET_SCALE_TRUE@LoadPlugin target_scale
 #@BUILD_PLUGIN_TARGET_SET_TRUE@LoadPlugin target_set
+#@BUILD_PLUGIN_TARGET_V5UPGRADE_TRUE@LoadPlugin target_v5upgrade
 
 #----------------------------------------------------------------------------#
 # The following block demonstrates the default behavior if no filtering is   #
 #<Chain "PostCache">
 #  Target "write"
 #</Chain>
+
+##############################################################################
+# Threshold configuration                                                    #
+#----------------------------------------------------------------------------#
+# The following outlines how to configure collectd's threshold checking      #
+# plugin. The plugin and possible configuration options are documented in    #
+# the collectd-threshold(5) manual page.                                     #
+##############################################################################
+
+#@BUILD_PLUGIN_THRESHOLD_TRUE@LoadPlugin "threshold"
+#<Plugin "threshold">
+#  <Type "foo">
+#    WarningMin    0.00
+#    WarningMax 1000.00
+#    FailureMin    0.00
+#    FailureMax 1200.00
+#    Invert false
+#    Instance "bar"
+#  </Type>
+#
+#  <Plugin "interface">
+#    Instance "eth0"
+#    <Type "if_octets">
+#      FailureMax 10000000
+#      DataSource "rx"
+#    </Type>
+#  </Plugin>
+#
+#  <Host "hostname">
+#    <Type "cpu">
+#      Instance "idle"
+#      FailureMin 10
+#    </Type>
+#
+#    <Plugin "memory">
+#      <Type "memory">
+#        Instance "cached"
+#        WarningMin 100000000
+#      </Type>
+#    </Plugin>
+#
+#    <Type "load">
+#      DataSource "midterm"
+#      FailureMax 4
+#      Hits 3
+#      Hysteresis 3
+#    </Type>
+#  </Host>
+#</Plugin>
index 1da3598..15b6f68 100644 (file)
@@ -25,22 +25,32 @@ controls which plugins to load. These plugins ultimately define collectd's
 behavior.
 
 The syntax of this config file is similar to the config file of the famous
-B<Apache Webserver>. Each line contains either a key-value-pair or a
-section-start or -end. Empty lines and everything after the hash-symbol `#' is
-ignored. Values are either string, enclosed in double-quotes,
-(floating-point-)numbers or a boolean expression, i.E<nbsp>e. either B<true> or
-B<false>. String containing of only alphanumeric characters and underscores do
-not need to be quoted. Lines may be wrapped by using `\' as the last character
-before the newline. This allows long lines to be split into multiple lines.
-Quoted strings may be wrapped as well. However, those are treated special in
-that whitespace at the beginning of the following lines will be ignored, which
-allows for nicely indenting the wrapped lines.
-
-The configuration is read and processed in order, i.E<nbsp>e. from top to
-bottom. So the plugins are loaded in the order listed in this config file. It
-is a good idea to load any logging plugins first in order to catch messages
-from plugins during configuration. Also, the C<LoadPlugin> option B<must> occur
-B<before> the C<E<lt>Plugin ...E<gt>> block.
+I<Apache> webserver. Each line contains either an option (a key and a list of
+one or more values) or a section-start or -end. Empty lines and everything
+after a non-quoted hash-symbol (C<#>) is ignored. I<Keys> are unquoted
+strings, consisting only of alphanumeric characters and the underscore (C<_>)
+character. Keys are handled case insensitive by I<collectd> itself and all
+plugins included with it. I<Values> can either be an I<unquoted string>, a
+I<quoted string> (enclosed in double-quotes) a I<number> or a I<boolean>
+expression. I<Unquoted strings> consist of only alphanumeric characters and
+underscores (C<_>) and do not need to be quoted. I<Quoted strings> are
+enclosed in double quotes (C<">). You can use the backslash character (C<\>)
+to include double quotes as part of the string. I<Numbers> can be specified in
+decimal and floating point format (using a dot C<.> as decimal separator),
+hexadecimal when using the C<0x> prefix and octal with a leading zero (C<0>).
+I<Boolean> values are either B<true> or B<false>.
+
+Lines may be wrapped by using C<\> as the last character before the newline.
+This allows long lines to be split into multiple lines. Quoted strings may be
+wrapped as well. However, those are treated special in that whitespace at the
+beginning of the following lines will be ignored, which allows for nicely
+indenting the wrapped lines.
+
+The configuration is read and processed in order, i.e. from top to bottom. So
+the plugins are loaded in the order listed in this config file. It is a good
+idea to load any logging plugins first in order to catch messages from plugins
+during configuration. Also, the C<LoadPlugin> option B<must> occur B<before>
+the appropriate C<E<lt>Plugin ...E<gt>> block.
 
 =head1 GLOBAL OPTIONS
 
@@ -72,15 +82,25 @@ options are allowed inside a B<LoadPlugin> block:
 If enabled, collectd will export all global symbols of the plugin (and of all
 libraries loaded as dependencies of the plugin) and, thus, makes those symbols
 available for resolving unresolved symbols in subsequently loaded plugins if
-that is supported by your system. By default, this is disabled.
+that is supported by your system.
 
-This is useful (or possibly even required), e.E<nbsp>g., when loading a plugin
-that embeds some scripting language into the daemon (e.E<nbsp>g. the C<perl>
-or C<python> plugins). Scripting languages usually provide means to load
+This is useful (or possibly even required), e.g., when loading a plugin that
+embeds some scripting language into the daemon (e.g. the I<Perl> and
+I<Python plugins>). Scripting languages usually provide means to load
 extensions written in C. Those extensions require symbols provided by the
-interpreter, which is loaded as a dependency of the respective collectd
-plugin. See the documentation of those plugins (e.E<nbsp>g.,
-L<collectd-perl(5)> or L<collectd-python(5)>) for details.
+interpreter, which is loaded as a dependency of the respective collectd plugin.
+See the documentation of those plugins (e.g., L<collectd-perl(5)> or
+L<collectd-python(5)>) for details.
+
+By default, this is disabled. As a special exception, if the plugin name is
+either C<perl> or C<python>, the default is changed to enabled in order to keep
+the average user from ever having to deal with this low level linking stuff.
+
+=item B<Interval> I<Seconds>
+
+Sets a plugin-specific interval for collecting metrics. This overrides the
+global B<Interval> setting. If a plugin provides own support for specifying an
+interval, that setting will take precedence.
 
 =back
 
@@ -129,6 +149,10 @@ Configures the interval in which to query the read plugins. Obviously smaller
 values lead to a higher system load produced by collectd, while higher values
 lead to more coarse statistics.
 
+B<Warning:> You should set this once and then never touch it again. If you do,
+I<you will have to delete all your RRD files> or know some serious RRDtool
+magic! (Assuming you're using the I<RRDtool> or I<RRDCacheD> plugin.)
+
 =item B<Timeout> I<Iterations>
 
 Consider a value list "missing" when no update has been read or received for
@@ -137,7 +161,7 @@ missing when no update has been received for twice the update interval. Since
 this setting uses iterations, the maximum allowed time without update depends
 on the I<Interval> information contained in each value list. This is used in
 the I<Threshold> configuration to dispatch notifications about missing values,
-see L<"THRESHOLD CONFIGURATION"> below.
+see L<collectd-threshold(5)> for details.
 
 =item B<ReadThreads> I<Num>
 
@@ -175,12 +199,122 @@ C<Plugin>-Section. Which options exist depends on the plugin used. Some plugins
 require external configuration, too. The C<apache plugin>, for example,
 required C<mod_status> to be configured in the webserver you're going to
 collect data from. These plugins are listed below as well, even if they don't
-require any configuration within collectd's configfile.
+require any configuration within collectd's configuration file.
 
 A list of all plugins and a short summary for each plugin can be found in the
 F<README> file shipped with the sourcecode and hopefully binary packets as
 well.
 
+=head2 Plugin C<aggregation>
+
+The I<Aggregation plugin> makes it possible to aggregate several values into
+one using aggregation functions such as I<sum>, I<average>, I<min> and I<max>.
+This can be put to a wide variety of uses, e.g. average and total CPU
+statistics for your entire fleet.
+
+The grouping is powerful but, as with many powerful tools, may be a bit
+difficult to wrap your head around. The grouping will therefore be
+demonstrated using an example: The average and sum of the CPU usage across
+all CPUs of each host is to be calculated.
+
+To select all the affected values for our example, set C<Plugin cpu> and
+C<Type cpu>. The other values are left unspecified, meaning "all values". The
+I<Host>, I<Plugin>, I<PluginInstance>, I<Type> and I<TypeInstance> options
+work as if they were specified in the C<WHERE> clause of an C<SELECT> SQL
+statement.
+
+  Plugin "cpu"
+  Type "cpu"
+
+Although the I<Host>, I<PluginInstance> (CPU number, i.e. 0, 1, 2, ...)  and
+I<TypeInstance> (idle, user, system, ...) fields are left unspecified in the
+example, the intention is to have a new value for each host / type instance
+pair. This is achieved by "grouping" the values using the C<GroupBy> option.
+It can be specified multiple times to group by more than one field.
+
+  GroupBy "Host"
+  GroupBy "TypeInstance"
+
+We do neither specify nor group by I<plugin instance> (the CPU number), so all
+metrics that differ in the CPU number only will be aggregated. Each
+aggregation needs I<at least one> such field, otherwise no aggregation would
+take place.
+
+The full example configuration looks like this:
+
+ <Plugin "aggregation">
+   <Aggregation>
+     Plugin "cpu"
+     Type "cpu"
+     
+     GroupBy "Host"
+     GroupBy "TypeInstance"
+     
+     CalculateSum true
+     CalculateAverage true
+   </Aggregation>
+ </Plugin>
+
+There are a couple of limitations you should be aware of:
+
+=over 4
+
+=item
+
+The I<Type> cannot be left unspecified, because it is not reasonable to add
+apples to oranges. Also, the internal lookup structure won't work if you try
+to group by type.
+
+=item
+
+There must be at least one unspecified, ungrouped field. Otherwise nothing
+will be aggregated.
+
+=back
+
+As you can see in the example above, each aggregation has its own
+B<Aggregation> block. You can have multiple aggregation blocks and aggregation
+blocks may match the same values, i.e. one value list can update multiple
+aggregations. The following options are valid inside B<Aggregation> blocks:
+
+=over 4
+
+=item B<Host> I<Host>
+
+=item B<Plugin> I<Plugin>
+
+=item B<PluginInstance> I<PluginInstance>
+
+=item B<Type> I<Type>
+
+=item B<TypeInstance> I<TypeInstance>
+
+Selects the value lists to be added to this aggregation. B<Type> must be a
+valid data set name, see L<types.db(5)> for details.
+
+=item B<GroupBy> B<Host>|B<Plugin>|B<PluginInstance>|B<TypeInstance>
+
+Group valued by the specified field. The B<GroupBy> option may be repeated to
+group by multiple fields.
+
+=item B<CalculateNum> B<true>|B<false>
+
+=item B<CalculateSum> B<true>|B<false>
+
+=item B<CalculateAverage> B<true>|B<false>
+
+=item B<CalculateMinimum> B<true>|B<false>
+
+=item B<CalculateMaximum> B<true>|B<false>
+
+=item B<CalculateStddev> B<true>|B<false>
+
+Boolean options for enabling calculation of the number of value lists, their
+sum, average, minimum, maximum andE<nbsp>/ or standard deviation. All options
+are disabled by default.
+
+=back
+
 =head2 Plugin C<amqp>
 
 The I<AMQMP plugin> can be used to communicate with other instances of
@@ -202,6 +336,8 @@ possibly filtering or messages.
  #   Persistent false
  #   Format "command"
  #   StoreRates false
+ #   GraphitePrefix "collectd."
+ #   GraphiteEscapeChar "_"
    </Publish>
    
    # Receive values from an AMQP broker
@@ -302,6 +438,10 @@ If set to B<JSON>, the values are encoded in the I<JavaScript Object Notation>,
 an easy and straight forward exchange format. The C<Content-Type> header field
 will be set to C<application/json>.
 
+If set to B<Graphite>, values are encoded in the I<Graphite> format, which is
+"<metric> <value> <timestamp>\n". The C<Content-Type> header field will be set to
+C<text/graphite>.
+
 A subscribing client I<should> use the C<Content-Type> header field to
 determine how to decode the values. Currently, the I<AMQP plugin> itself can
 only decode the B<Command> format.
@@ -316,6 +456,25 @@ using the internal value cache.
 Please note that currently this option is only used if the B<Format> option has
 been set to B<JSON>.
 
+=item B<GraphitePrefix> (Publish and B<Format>=I<Graphite> only)
+
+A prefix can be added in the metric name when outputting in the I<Graphite> format.
+It's added before the I<Host> name.
+Metric name will be "<prefix><host><postfix><plugin><type><name>"
+
+=item B<GraphitePostfix> (Publish and B<Format>=I<Graphite> only)
+
+A postfix can be added in the metric name when outputting in the I<Graphite> format.
+It's added after the I<Host> name.
+Metric name will be "<prefix><host><postfix><plugin><type><name>"
+
+=item B<GraphiteEscapeChar> (Publish and B<Format>=I<Graphite> only)
+
+Specify a character to replace dots (.) in the host part of the metric name.
+In I<Graphite> metric name, dots are used as separators between different
+metric parts (host, plugin, type).
+Default is "_" (I<Underscore>).
+
 =back
 
 =head2 Plugin C<apache>
@@ -475,6 +634,7 @@ Synopsis:
 
  <Plugin "bind">
    URL "http://localhost:8053/"
+   ParseTime       false
    OpCodes         true
    QTypes          true
  
@@ -501,35 +661,44 @@ The bind plugin accepts the following configuration options:
 URL from which to retrieve the XML data. If not specified,
 C<http://localhost:8053/> will be used.
 
-=item B<OpCodes> I<true>|I<false>
+=item B<ParseTime> B<true>|B<false>
+
+When set to B<true>, the time provided by BIND will be parsed and used to
+dispatch the values. When set to B<false>, the local time source is queried.
+
+This setting is set to B<true> by default for backwards compatibility; setting
+this to B<false> is I<recommended> to avoid problems with timezones and
+localization.
+
+=item B<OpCodes> B<true>|B<false>
 
 When enabled, statistics about the I<"OpCodes">, for example the number of
 C<QUERY> packets, are collected.
 
 Default: Enabled.
 
-=item B<QTypes> I<true>|I<false>
+=item B<QTypes> B<true>|B<false>
 
 When enabled, the number of I<incoming> queries by query types (for example
 C<A>, C<MX>, C<AAAA>) is collected.
 
 Default: Enabled.
 
-=item B<ServerStats> I<true>|I<false>
+=item B<ServerStats> B<true>|B<false>
 
 Collect global server statistics, such as requests received over IPv4 and IPv6,
 successful queries, and failed updates.
 
 Default: Enabled.
 
-=item B<ZoneMaintStats> I<true>|I<false>
+=item B<ZoneMaintStats> B<true>|B<false>
 
 Collect zone maintenance statistics, mostly information about notifications
 (zone updates) and zone transfers.
 
 Default: Enabled.
 
-=item B<ResolverStats> I<true>|I<false>
+=item B<ResolverStats> B<true>|B<false>
 
 Collect resolver statistics, i.E<nbsp>e. statistics about outgoing requests
 (e.E<nbsp>g. queries over IPv4, lame servers). Since the global resolver
@@ -558,21 +727,21 @@ configured, no detailed view statistics will be collected.
 
 =over 4
 
-=item B<QTypes> I<true>|I<false>
+=item B<QTypes> B<true>|B<false>
 
 If enabled, the number of I<outgoing> queries by query type (e.E<nbsp>g. C<A>,
 C<MX>) is collected.
 
 Default: Enabled.
 
-=item B<ResolverStats> I<true>|I<false>
+=item B<ResolverStats> B<true>|B<false>
 
 Collect resolver statistics, i.E<nbsp>e. statistics about outgoing requests
 (e.E<nbsp>g. queries over IPv4, lame servers).
 
 Default: Enabled.
 
-=item B<CacheRRSets> I<true>|I<false>
+=item B<CacheRRSets> B<true>|B<false>
 
 If enabled, the number of entries (I<"RR sets">) in the view's cache by query
 type is collected. Negative entries (queries which resulted in an error, for
@@ -731,22 +900,6 @@ runtime statistics module of CouchDB
     </URL>
   </Plugin>
 
-Another CouchDB example:
-The following example will collect the status values from each database:
-
-  <URL "http://localhost:5984/_all_dbs">
-    Instance "dbs"
-    <Key "*/doc_count">
-      Type "gauge"
-    </Key>
-    <Key "*/doc_del_count">
-      Type "counter"
-    </Key>
-    <Key "*/disk_size">
-      Type "bytes"
-    </Key>
-  </URL>
-
 In the B<Plugin> block, there may be one or more B<URL> blocks, each defining
 a URL to be fetched via HTTP (using libcurl) and one or more B<Key> blocks.
 The B<Key> string argument must be in a path format, which is used to collect a
@@ -831,7 +984,7 @@ The B<curl_xml plugin> uses B<libcurl> (L<http://curl.haxx.se/>) and B<libxml2>
  </Plugin>
 
 In the B<Plugin> block, there may be one or more B<URL> blocks, each defining a
-URL to be fetched via HTTP (using libcurl). Within each B<URL> block there are
+URL to be fetched using libcurl. Within each B<URL> block there are
 options which specify the connection parameters, for example authentication
 information, and one or more B<XPath> blocks.
 
@@ -1270,6 +1423,41 @@ at most B<16384> to prevent typos and dumb mistakes.
 
 =back
 
+=head2 Plugin C<ethstat>
+
+The I<ethstat plugin> collects information about network interface cards (NICs)
+by talking directly with the underlying kernel driver using L<ioctl(2)>.
+
+B<Synopsis:>
+
+ <Plugin "ethstat">
+   Interface "eth0"
+   Map "rx_csum_offload_errors" "if_rx_errors" "checksum_offload"
+   Map "multicast" "if_multicast"
+ </Plugin>
+
+B<Options:>
+
+=over 4
+
+=item B<Interface> I<Name>
+
+Collect statistical information about interface I<Name>.
+
+=item B<Map> I<Name> I<Type> [I<TypeInstance>]
+
+By default, the plugin will submit values as type C<derive> and I<type
+instance> set to I<Name>, the name of the metric as reported by the driver. If
+an appropriate B<Map> option exists, the given I<Type> and, optionally,
+I<TypeInstance> will be used.
+
+=item B<MappedOnly> B<true>|B<false>
+
+When set to B<true>, only metrics that can be mapped to to a I<type> will be
+collected, all other metrics will be ignored. Defaults to B<false>.
+
+=back
+
 =head2 Plugin C<exec>
 
 Please make sure to read L<collectd-exec(5)> before using this plugin. It
@@ -1750,8 +1938,8 @@ debugging support.
 
 Sets the file to write log messages to. The special strings B<stdout> and
 B<stderr> can be used to write to the standard output and standard error
-channels, respectively. This, of course, only makes much sense when collectd is
-running in foreground- or non-daemon-mode.
+channels, respectively. This, of course, only makes much sense when I<collectd>
+is running in foreground- or non-daemon-mode.
 
 =item B<Timestamp> B<true>|B<false>
 
@@ -1768,6 +1956,33 @@ B<Note>: There is no need to notify the daemon after moving or removing the
 log file (e.E<nbsp>g. when rotating the logs). The plugin reopens the file
 for each line it writes.
 
+=head2 Plugin C<lpar>
+
+The I<LPAR plugin> reads CPU statistics of I<Logical Partitions>, a
+virtualization technique for IBM POWER processors. It takes into account CPU
+time stolen from or donated to a partition, in addition to the usual user,
+system, I/O statistics.
+
+The following configuration options are available:
+
+=over 4
+
+=item B<CpuPoolStats> B<false>|B<true>
+
+When enabled, statistics about the processor pool are read, too. The partition
+needs to have pool authority in order to be able to acquire this information.
+Defaults to false.
+
+=item B<ReportBySerial> B<false>|B<true>
+
+If enabled, the serial of the physical machine the partition is currently
+running on is reported as I<hostname> and the logical hostname of the machine
+is reported in the I<plugin instance>. Otherwise, the logical hostname will be
+used (just like other plugins) and the I<plugin instance> will be empty.
+Defaults to false.
+
+=back
+
 =head2 Plugin C<mbmon>
 
 The C<mbmon plugin> uses mbmon to retrieve temperature, voltage, etc.
@@ -1793,6 +2008,31 @@ TCP-Port to connect to. Defaults to B<411>.
 
 =back
 
+=head2 Plugin C<md>
+
+The C<md plugin> collects information from Linux Software-RAID devices (md).
+
+All reported values are of the type C<md_disks>. Reported type instances are
+I<active>, I<failed> (present but not operational), I<spare> (hot stand-by) and
+I<missing> (physically absent) disks.
+
+=over 4
+
+=item B<Device> I<Device>
+
+Select md devices based on device name. The I<device name> is the basename of
+the device, i.e. the name of the block device without the leading C</dev/>.
+See B<IgnoreSelected> for more details.
+
+=item B<IgnoreSelected> B<true>|B<false>
+
+Invert device selection: If set to B<true>, all md devices B<except> those
+listed using B<Device> are collected. If B<false> (the default), only those
+listed are collected. If no configuration is given, the B<md> plugin will
+collect data from all md devices.
+
+=back
+
 =head2 Plugin C<memcachec>
 
 The C<memcachec plugin> connects to a memcached server, queries one or more
@@ -1850,6 +2090,17 @@ The C<memcached plugin> connects to a memcached server and queries statistics
 about cache utilization, memory and bandwidth used.
 L<http://www.danga.com/memcached/>
 
+ <Plugin "memcached">
+   <Instance "name">
+     Host "memcache.example.com"
+     Port 11211
+   </Instance>
+ </Plugin>
+
+The plugin configuration consists of one or more B<Instance> blocks which
+specify one I<memcached> connection each. Within the B<Instance> blocks, the
+following options are allowed:
+
 =over 4
 
 =item B<Host> I<Hostname>
@@ -1860,6 +2111,11 @@ Hostname to connect to. Defaults to B<127.0.0.1>.
 
 TCP-Port to connect to. Defaults to B<11211>.
 
+=item B<Socket> I<Path>
+
+Connect to I<memcached> using the UNIX domain socket at I<Path>. If this
+setting is given, the B<Host> and B<Port> settings are ignored.
+
 =back
 
 =head2 Plugin C<modbus>
@@ -1914,11 +2170,11 @@ Configures the base register to read from the device. If the option
 B<RegisterType> has been set to B<Uint32> or B<Float>, this and the next
 register will be read (the register number is increased by one).
 
-=item B<RegisterType> B<Uint16>|B<Uint32>|B<Float>
+=item B<RegisterType> B<Int16>|B<Int32>|B<Uint16>|B<Uint32>|B<Float>
 
-Specifies what kind of data is returned by the device. If the type is B<Uint32>
-or B<Float>, two 16E<nbsp>bit registers will be read and the data is combined
-into one value. Defaults to B<Uint16>.
+Specifies what kind of data is returned by the device. If the type is B<Int32>,
+B<Uint32> or B<Float>, two 16E<nbsp>bit registers will be read and the data is
+combined into one value. Defaults to B<Uint16>.
 
 =item B<Type> I<Type>
 
@@ -2044,8 +2300,10 @@ Hostname of the database server. Defaults to B<localhost>.
 =item B<User> I<Username>
 
 Username to use when connecting to the database. The user does not have to be
-granted any privileges (which is synonym to granting the C<USAGE> privilege).
-Any existing MySQL user will do.
+granted any privileges (which is synonym to granting the C<USAGE> privilege),
+unless you want to collectd replication statistics (see B<MasterStats> and
+B<SlaveStats> below). In this case, the user needs the C<REPLICATION CLIENT>
+(or C<SUPER>) privileges. Else, any existing MySQL user will do.
 
 =item B<Password> I<Password>
 
@@ -2077,7 +2335,9 @@ C<mysql_real_connect> function for details.
 
 =item B<SlaveStats> I<true|false>
 
-Enable the collection of master / slave statistics in a replication setup.
+Enable the collection of master / slave statistics in a replication setup. In
+order to be able to get access to these statistics, the user needs special
+privileges. See the B<User> documentation above.
 
 =item B<SlaveNotifications> I<true|false>
 
@@ -2631,10 +2891,18 @@ The default IPv6 multicast group is C<ff18::efc0:4a42>. The default IPv4
 multicast group is C<239.192.74.66>. The default I<UDP> port is B<25826>.
 
 Both, B<Server> and B<Listen> can be used as single option or as block. When
-used as block, given options are valid for this socket only. For example:
+used as block, given options are valid for this socket only. The following
+example will export the metrics twice: Once to an "internal" server (without
+encryption and signing) and one to an external server (with cryptographic
+signature):
 
  <Plugin "network">
+   # Export to an internal server
+   # (demonstrates usage without additional options)
    Server "collectd.internal.tld"
+   
+   # Export to an external server
+   # (demonstrates usage with signature options)
    <Server "collectd.external.tld">
      SecurityLevel "sign"
      Username "myhostname"
@@ -2763,7 +3031,18 @@ operating systems.
 =item B<MaxPacketSize> I<1024-65535>
 
 Set the maximum size for datagrams received over the network. Packets larger
-than this will be truncated. Defaults to 1452E<nbsp>bytes.
+than this will be truncated. Defaults to 1452E<nbsp>bytes, which is the maximum
+payload size that can be transmitted in one Ethernet frame using IPv6E<nbsp>/
+UDP.
+
+On the server side, this limit should be set to the largest value used on
+I<any> client. Likewise, the value on the client must not be larger than the
+value on the server, or data will be lost.
+
+B<Compatibility:> Versions prior to I<versionE<nbsp>4.8> used a fixed sized
+buffer of 1024E<nbsp>bytes. Versions I<4.8>, I<4.9> and I<4.10> used a default
+value of 1024E<nbsp>bytes to avoid problems when sending data to an older
+server.
 
 =item B<Forward> I<true|false>
 
@@ -2835,7 +3114,8 @@ and are checked by default depends on the distribution you use.
 This plugin sends a desktop notification to a notification daemon, as defined
 in the Desktop Notification Specification. To actually display the
 notifications, B<notification-daemon> is required and B<collectd> has to be
-able to access the X server.
+able to access the X server (i.E<nbsp>e., the C<DISPLAY> and C<XAUTHORITY>
+environment variables have to be set correctly) and the D-Bus message bus.
 
 The Desktop Notification Specification can be found at
 L<http://www.galago-project.org/specs/notification/>.
@@ -2930,6 +3210,16 @@ IP-address may be used in a filename it is recommended to disable reverse
 lookups. The default is to do reverse lookups to preserve backwards
 compatibility, though.
 
+=item B<IncludeUnitID> B<true>|B<false>
+
+When a peer is a refclock, include the unit ID in the I<type instance>.
+Defaults to B<false> for backward compatibility.
+
+If two refclock peers use the same driver and this is B<false>, the plugin will
+try to write simultaneous measurements from both to the same type instance.
+This will result in error messages in the log and only one set of measurements
+making it through.
+
 =back
 
 =head2 Plugin C<nut>
@@ -3155,6 +3445,11 @@ values submitted to the daemon. Other than that, that name is not used.
 Defines the "database alias" or "service name" to connect to. Usually, these
 names are defined in the file named C<$ORACLE_HOME/network/admin/tnsnames.ora>.
 
+=item B<Host> I<Host>
+
+Hostname to use when dispatching values for this database. Defaults to using
+the global hostname of the I<collectd> instance.
+
 =item B<Username> I<Username>
 
 Username used for authentication.
@@ -3425,6 +3720,11 @@ used, the parameter expands to "localhost".
 
 The name of the database of the current connection.
 
+=item I<instance>
+
+The name of the database plugin instance. See the B<Instance> option of the
+database specification below for details.
+
 =item I<username>
 
 The username used to connect to the database.
@@ -3583,6 +3883,13 @@ Specify the password to be used when connecting to the server.
 Specify whether to use an SSL connection when contacting the server. The
 following modes are supported:
 
+=item B<Instance> I<name>
+
+Specify the plugin instance name that should be used instead of the database
+name (which is the default, if this option has not been specified). This
+allows to query multiple databases of the same name on the same host (e.g.
+when running multiple database server versions in parallel).
+
 =over 4
 
 =item I<disable>
@@ -3943,6 +4250,10 @@ The B<Port> option is the TCP port on which the Redis instance accepts
 connections. Either a service name of a port number may be given. Please note
 that numerical port numbers must be given as a string, too.
 
+=item B<Password> I<Password>
+
+Use I<Password> to authenticate when connecting to I<Redis>.
+
 =item B<Timeout> I<Timeout in miliseconds>
 
 The B<Timeout> option set the socket timeout for node response. Since the Redis
@@ -4000,6 +4311,50 @@ Enables or disables the creation of RRD files. If the daemon is not running
 locally, or B<DataDir> is set to a relative path, this will not work as
 expected. Default is B<true>.
 
+=item B<StepSize> I<Seconds>
+
+B<Force> the stepsize of newly created RRD-files. Ideally (and per default)
+this setting is unset and the stepsize is set to the interval in which the data
+is collected. Do not use this option unless you absolutely have to for some
+reason. Setting this option may cause problems with the C<snmp plugin>, the
+C<exec plugin> or when the daemon is set up to receive data from other hosts.
+
+=item B<HeartBeat> I<Seconds>
+
+B<Force> the heartbeat of newly created RRD-files. This setting should be unset
+in which case the heartbeat is set to twice the B<StepSize> which should equal
+the interval in which data is collected. Do not set this option unless you have
+a very good reason to do so.
+
+=item B<RRARows> I<NumRows>
+
+The C<rrdtool plugin> calculates the number of PDPs per CDP based on the
+B<StepSize>, this setting and a timespan. This plugin creates RRD-files with
+three times five RRAs, i. e. five RRAs with the CFs B<MIN>, B<AVERAGE>, and
+B<MAX>. The five RRAs are optimized for graphs covering one hour, one day, one
+week, one month, and one year.
+
+So for each timespan, it calculates how many PDPs need to be consolidated into
+one CDP by calculating:
+  number of PDPs = timespan / (stepsize * rrarows)
+
+Bottom line is, set this no smaller than the width of you graphs in pixels. The
+default is 1200.
+
+=item B<RRATimespan> I<Seconds>
+
+Adds an RRA-timespan, given in seconds. Use this option multiple times to have
+more then one RRA. If this option is never used, the built-in default of (3600,
+86400, 604800, 2678400, 31622400) is used.
+
+For more information on how RRA-sizes are calculated see B<RRARows> above.
+
+=item B<XFF> I<Factor>
+
+Set the "XFiles Factor". The default is 0.1. If unsure, don't set this option.
+I<Factor> must be in the range C<[0.0-1.0)>, i.e. between zero (inclusive) and
+one (exclusive).
+
 =back
 
 =head2 Plugin C<rrdtool>
@@ -4057,6 +4412,8 @@ For more information on how RRA-sizes are calculated see B<RRARows> above.
 =item B<XFF> I<Factor>
 
 Set the "XFiles Factor". The default is 0.1. If unsure, don't set this option.
+I<Factor> must be in the range C<[0.0-1.0)>, i.e. between zero (inclusive) and
+one (exclusive).
 
 =item B<CacheFlush> I<Seconds>
 
@@ -4115,7 +4472,7 @@ because all values were added to the internal cache at roughly the same time.
 
 =head2 Plugin C<sensors>
 
-The C<sensors plugin> uses B<lm_sensors> to retrieve sensor-values. This means
+The I<Sensors plugin> uses B<lm_sensors> to retrieve sensor-values. This means
 that all the needed modules have to be loaded and lm_sensors has to be
 configured (most likely by editing F</etc/sensors.conf>. Read
 L<sensors.conf(5)> for details.
@@ -4125,6 +4482,11 @@ L<http://secure.netroedge.com/~lm78/>.
 
 =over 4
 
+=item B<SensorConfigFile> I<File>
+
+Read the I<lm_sensors> configuration from I<File>. When unset (recommended),
+the library's default will be used.
+
 =item B<Sensor> I<chip-bus-address/type-feature>
 
 Selects the name of the sensor which you want to collect or ignore, depending
@@ -4150,6 +4512,30 @@ Since the configuration of the C<snmp plugin> is a little more complicated than
 other plugins, its documentation has been moved to an own manpage,
 L<collectd-snmp(5)>. Please see there for details.
 
+=head2 Plugin C<swap>
+
+The I<Swap plugin> collects information about used and available swap space. On
+I<Linux> and I<Solaris>, the following options are available:
+
+=over 4
+
+=item B<ReportByDevice> B<false>|B<true>
+
+Configures how to report physical swap devices. If set to B<false> (the
+default), the summary over all swap devices is reported only, i.e. the globally
+used and available space over all devices. If B<true> is configured, the used
+and available space of each device will be reported separately.
+
+This option is only available if the I<Swap plugin> can read C</proc/swaps>
+(under Linux) or use the L<swapctl(2)> mechanism (under I<Solaris>).
+
+=item B<ReportBytes> B<false>|B<true>
+
+When enabled, the I<swap I/O> is reported in bytes. When disabled, the default,
+I<swap I/O> is reported in pages. This option is available under Linux only.
+
+=back
+
 =head2 Plugin C<syslog>
 
 =over 4
@@ -4163,6 +4549,15 @@ syslog-daemon.
 Please note that B<debug> is only available if collectd has been compiled with
 debugging support.
 
+=item B<NotifyLevel> B<OKAY>|B<WARNING>|B<FAILURE>
+
+Controls which notifications should be sent to syslog. The default behaviour is
+not to send any. Less severe notifications always imply logging more severe
+notifications: Setting this to B<OKAY> means all notifications will be sent to
+syslog, setting this to B<WARNING> will send B<WARNING> and B<FAILURE>
+notifications but will dismiss B<OKAY> notifications. Setting this option to
+B<FAILURE> will only send failures to syslog.
+
 =back
 
 =head2 Plugin C<table>
@@ -4499,7 +4894,7 @@ port in numeric form.
 
 =item B<ForceUseProcfs> I<true>|I<false>
 
-By default, the C<thermal> plugin tries to read the statistics from the Linux
+By default, the I<Thermal plugin> tries to read the statistics from the Linux
 C<sysfs> interface. If that is not available, the plugin falls back to the
 C<procfs> interface. By setting this option to I<true>, you can force the
 plugin to use the latter. This option defaults to I<false>.
@@ -4519,9 +4914,18 @@ selection is configured at all, B<all> devices are selected.
 
 =back
 
+=head2 Plugin C<threshold>
+
+The I<Threshold plugin> checks values collected or received by I<collectd>
+against a configurable I<threshold> and issues I<notifications> if values are
+out of bounds.
+
+Documentation for this plugin is available in the L<collectd-threshold(5)>
+manual page.
+
 =head2 Plugin C<tokyotyrant>
 
-The C<tokyotyrant plugin> connects to a TokyoTyrant server and collects a
+The I<TokyoTyrant plugin> connects to a TokyoTyrant server and collects a
 couple metrics: number of records, and database size on disk.
 
 =over 4
@@ -4558,6 +4962,13 @@ Change the file permissions of the UNIX-socket after it has been created. The
 permissions must be given as a numeric, octal value as you would pass to
 L<chmod(1)>. Defaults to B<0770>.
 
+=item B<DeleteSocket> B<false>|B<true>
+
+If set to B<true>, delete the socket file before calling L<bind(2)>, if a file
+with the given name already exists. If I<collectd> crashes a socket file may be
+left over, preventing the daemon from opening a new socket when restarted.
+Since this is potentially dangerous, this defaults to B<false>.
+
 =back
 
 =head2 Plugin C<uuid>
@@ -4697,6 +5108,115 @@ traffic (e.E<nbsp>g. due to headers and retransmission). If you want to
 collect on-wire traffic you could, for example, use the logging facilities of
 iptables to feed data for the guest IPs into the iptables plugin.
 
+=head2 Plugin C<write_graphite>
+
+The C<write_graphite> plugin writes data to I<Graphite>, an open-source metrics
+storage and graphing project. The plugin connects to I<Carbon>, the data layer
+of I<Graphite>, and sends data via the "line based" protocol (per default using
+portE<nbsp>2003). The data will be sent in blocks of at most 1428 bytes to
+minimize the number of network packets.
+
+Synopsis:
+
+ <Plugin write_graphite>
+   <Carbon>
+     Host "localhost"
+     Port "2003"
+     Prefix "collectd"
+   </Carbon>
+ </Plugin>
+
+=over 4
+
+=item B<Host> I<Address>
+
+Hostname or address to connect to. Defaults to C<localhost>.
+
+=item B<Port> I<Service>
+
+Service name or port number to connect to. Defaults to C<2003>.
+
+=item B<Prefix> I<String>
+
+When set, I<String> is added in front of the host name. Dots and whitespace are
+I<not> escaped in this string (see B<EscapeCharacter> below).
+
+=item B<Postfix> I<String>
+
+When set, I<String> is appended to the host name. Dots and whitespace are
+I<not> escaped in this string (see B<EscapeCharacter> below).
+
+=item B<EscapeCharacter> I<Char>
+
+I<Carbon> uses the dot (C<.>) as escape character and doesn't allow whitespace
+in the identifier. The B<EscapeCharacter> option determines which character
+dots, whitespace and control characters are replaced with. Defaults to
+underscore (C<_>).
+
+=item B<StoreRates> B<false>|B<true>
+
+If set to B<true> (the default), convert counter values to rates. If set to
+B<false> counter values are stored as is, i.E<nbsp>e. as an increasing integer
+number.
+
+=item B<SeparateInstances> B<false>|B<true>
+
+If set to B<true>, the plugin instance and type instance will be in their own
+path component, for example C<host.cpu.0.cpu.idle>. If set to B<false> (the
+default), the plugin and plugin instance (and likewise the type and type
+instance) are put into one component, for example C<host.cpu-0.cpu-idle>.
+
+=item B<AlwaysAppendDS> B<false>|B<true>
+
+If set the B<true>, append the name of the I<Data Source> (DS) to the "metric"
+identifier. If set to B<false> (the default), this is only done when there is
+more than one DS.
+
+=back
+
+=head2 Plugin C<write_mongodb>
+
+The I<write_mongodb plugin> will send values to I<MongoDB>, a schema-less
+NoSQL database.
+
+B<Synopsis:>
+
+ <Plugin "write_mongodb">
+   <Node "default">
+     Host "localhost"
+     Port "27017"
+     Timeout 1000
+     StoreRates true
+   </Node>
+ </Plugin>
+
+The plugin can send values to multiple instances of I<MongoDB> by specifying
+one B<Node> block for each instance. Within the B<Node> blocks, the following
+options are available:
+
+=over 4
+
+=item B<Host> I<Address>
+
+Hostname or address to connect to. Defaults to C<localhost>.
+
+=item B<Port> I<Service>
+
+Service name or port number to connect to. Defaults to C<27017>.
+
+=item B<Timeout> I<Timeout>
+
+Set the timeout for each operation on I<MongoDB> to I<Timeout> milliseconds.
+Setting this option to zero means no timeout, which is the default.
+
+=item B<StoreRates> B<false>|B<true>
+
+If set to B<true> (the default), convert counter values to rates. If set to
+B<false> counter values are stored as is, i.e. as an increasing integer
+number.
+
+=back
+
 =head2 Plugin C<write_http>
 
 This output plugin submits values to an http server by POST them using the
@@ -4823,13 +5343,6 @@ information.
          WarningMin 100000000
        </Type>
      </Plugin>
-
-     <Type "load">
-       DataSource "midterm"
-       FailureMax 4
-       Hits 3
-       Hysteresis 3
-     </Type>
    </Host>
  </Threshold>
 
@@ -4902,26 +5415,33 @@ percentage value, relative to the other data sources. This is helpful for
 example for the "df" type, where you may want to issue a warning when less than
 5E<nbsp>% of the total space is available. Defaults to B<false>.
 
-=item B<Hits> I<Value>
+=item B<Hits> I<Number>
+
+Delay creating the notification until the threshold has been passed I<Number>
+times. When a notification has been generated, or when a subsequent value is
+inside the threshold, the counter is reset. If, for example, a value is
+collected once every 10E<nbsp>seconds and B<Hits> is set to 3, a notification
+will be dispatched at most once every 30E<nbsp>seconds.
+
+This is useful when short bursts are not a problem. If, for example, 100% CPU
+usage for up to a minute is normal (and data is collected every
+10E<nbsp>seconds), you could set B<Hits> to B<6> to account for this.
 
-Sets the number of occurrences which the threshold must be arised before to
-dispatch any notification or, in other words, the number of B<Interval>s
-than the threshold must be match before dispatch any notification.
+=item B<Hysteresis> I<Number>
 
-=item B<Hysteresis> I<Value>
+When set to non-zero, a hysteresis value is applied when checking minimum and
+maximum bounds. This is useful for values that increase slowly and fluctuate a
+bit while doing so. When these values come close to the threshold, they may
+"flap", i.e. switch between failure / warning case and okay case repeatedly.
 
-Sets the hysteresis value for threshold. The hysteresis is a method to
-prevent flapping between states, until a new received value for
-a previously matched threshold down below the threshold condition
-(B<WarningMax>, B<FailureMin> or everthing else) minus the hysteresis value,
-the failure (respectively warning) state will be keep.
+If, for example, the threshold is configures as
 
-=item B<Interesting> B<true>|B<false>
+  WarningMax 100.0
+  Hysteresis 1.0
 
-If set to B<true> (the default), the threshold must be treated as
-interesting and, when a number of B<Timeout> values will lost, then
-a missing notification will be dispatched. On the other hand, if set to
-B<false>, the missing notification will never dispatched for this threshold.
+then a I<Warning> notification is created when the value exceeds I<101> and the
+corresponding I<Okay> notification is only created once the value falls below
+I<99>, thus avoiding the "flapping".
 
 =back
 
@@ -5550,7 +6070,7 @@ convert counter values to rates.
 
 Please note that these placeholders are B<case sensitive>!
 
-=item B<Severity> B<"FATAL">|B<"WARNING">|B<"OKAY">
+=item B<Severity> B<"FAILURE">|B<"WARNING">|B<"OKAY">
 
 Sets the severity of the message. If omitted, the severity B<"WARNING"> is
 used.
index 93d356e..c0994d1 100644 (file)
 # define assert(...) /* nop */
 #endif
 
+#if !defined(HAVE__BOOL) || !HAVE__BOOL
+typedef int _Bool;
+# undef HAVE__BOOL
+# define HAVE__BOOL 1
+#endif
+
 #if NAN_STATIC_DEFAULT
 # include <math.h>
 /* #endif NAN_STATIC_DEFAULT*/
 # define COLLECTD_GRP_NAME "collectd"
 #endif
 
+#ifndef COLLECTD_DEFAULT_INTERVAL
+# define COLLECTD_DEFAULT_INTERVAL 10.0
+#endif
+
 #define STATIC_ARRAY_LEN(array) (sizeof (array) / sizeof ((array)[0]))
 
 /* Remove GNU specific __attribute__ settings when using another compiler */
 # endif
 #endif
 
-extern char hostname_g[];
-extern int  interval_g;
-extern int  timeout_g;
+/* Type for time as used by "utils_time.h" */
+typedef uint64_t cdtime_t;
+
+extern char     hostname_g[];
+extern cdtime_t interval_g;
+extern int      timeout_g;
 
 #endif /* COLLECTD_H */
index f16a70d..0b8d0c1 100644 (file)
 # include "config.h"
 #endif
 
-#ifndef _ISOC99_SOURCE
-# define _ISOC99_SOURCE
-#endif
-
-#ifndef _POSIX_C_SOURCE
-# define _POSIX_C_SOURCE 200112L
-#endif
-
-#ifndef _XOPEN_SOURCE
-# define _XOPEN_SOURCE 600
-#endif
-
 #include <stdlib.h>
 #include <unistd.h>
 #include <stdio.h>
 
 #include <assert.h>
 #include <errno.h>
-#include <math.h>
 
-#include "libcollectdclient/collectd/client.h"
+#if NAN_STATIC_DEFAULT
+# include <math.h>
+/* #endif NAN_STATIC_DEFAULT*/
+#elif NAN_STATIC_ISOC
+# ifndef __USE_ISOC99
+#  define DISABLE_ISOC99 1
+#  define __USE_ISOC99 1
+# endif /* !defined(__USE_ISOC99) */
+# include <math.h>
+# if DISABLE_ISOC99
+#  undef DISABLE_ISOC99
+#  undef __USE_ISOC99
+# endif /* DISABLE_ISOC99 */
+/* #endif NAN_STATIC_ISOC */
+#elif NAN_ZERO_ZERO
+# include <math.h>
+# ifdef NAN
+#  undef NAN
+# endif
+# define NAN (0.0 / 0.0)
+# ifndef isnan
+#  define isnan(f) ((f) != (f))
+# endif /* !defined(isnan) */
+# ifndef isfinite
+#  define isfinite(f) (((f) - (f)) == 0.0)
+# endif
+# ifndef isinf
+#  define isinf(f) (!isfinite(f) && !isnan(f))
+# endif
+#endif /* NAN_ZERO_ZERO */
 
+#include "libcollectdclient/collectd/client.h"
 
 #define DEFAULT_SOCK LOCALSTATEDIR"/run/"PACKAGE_NAME"-unixsock"
 
@@ -468,7 +485,7 @@ static int putval (lcc_connection_t *c, int argc, char **argv)
       while (value != 0) {
         char *dot, *endptr;
 
-        tmp = strchr (argv[i], (int)':');
+        tmp = strchr (value, (int)':');
 
         if (tmp != NULL) {
           *tmp = '\0';
index 08653dc..b679bf7 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/common.c
- * Copyright (C) 2005-2009  Florian octo Forster
+ * Copyright (C) 2005-2010  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Niki W. Waibel <niki.waibel@gmx.net>
  *   Sebastian Harl <sh at tokkee.org>
  *   Michał Mirosław <mirq-linux at rere.qmqm.pl>
 # include <math.h>
 #endif
 
-/* for ntohl and htonl */
-#if HAVE_ARPA_INET_H
-# include <arpa/inet.h>
-#endif
-
 /* for getaddrinfo */
 #include <sys/types.h>
 #include <sys/socket.h>
 # include <netinet/in.h>
 #endif
 
+/* for ntohl and htonl */
+#if HAVE_ARPA_INET_H
+# include <arpa/inet.h>
+#endif
+
 #ifdef HAVE_LIBKSTAT
 extern kstat_ctl_t *kc;
 #endif
@@ -543,11 +543,12 @@ int check_create_dir (const char *file_orig)
                }
 
                while (42) {
-                       if (stat (dir, &statbuf) == -1)
+                       if ((stat (dir, &statbuf) == -1)
+                                       && (lstat (dir, &statbuf) == -1))
                        {
                                if (errno == ENOENT)
                                {
-                                       if (mkdir (dir, 0755) == 0)
+                                       if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
                                                break;
 
                                        /* this might happen, if a different thread created
@@ -635,24 +636,23 @@ long long get_kstat_value (kstat_t *ksp, char *name)
        kstat_named_t *kn;
        long long retval = -1LL;
 
-#ifdef assert
-       assert (ksp != NULL);
-       assert (ksp->ks_type == KSTAT_TYPE_NAMED);
-#else
        if (ksp == NULL)
        {
-               ERROR ("ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
+               ERROR ("get_kstat_value (\"%s\"): ksp is NULL.", name);
                return (-1LL);
        }
        else if (ksp->ks_type != KSTAT_TYPE_NAMED)
        {
-               ERROR ("ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
+               ERROR ("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
+                               "is not KSTAT_TYPE_NAMED (%#x).",
+                               name,
+                               (unsigned int) ksp->ks_type,
+                               (unsigned int) KSTAT_TYPE_NAMED);
                return (-1LL);
        }
-#endif
 
        if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
-               return (retval);
+               return (-1LL);
 
        if (kn->data_type == KSTAT_DATA_INT32)
                retval = (long long) kn->value.i32;
@@ -833,7 +833,7 @@ int format_values (char *ret, size_t ret_len, /* {{{ */
                 offset += ((size_t) status); \
 } while (0)
 
-        BUFFER_ADD ("%lu", (unsigned long) vl->time);
+        BUFFER_ADD ("%.3f", CDTIME_T_TO_DOUBLE (vl->time));
 
         for (i = 0; i < ds->ds_num; i++)
         {
@@ -918,9 +918,59 @@ int parse_identifier (char *str, char **ret_host,
        return (0);
 } /* int parse_identifier */
 
-int parse_value (const char *value, value_t *ret_value, int ds_type)
+int parse_identifier_vl (const char *str, value_list_t *vl) /* {{{ */
 {
+       char str_copy[6 * DATA_MAX_NAME_LEN];
+       char *host = NULL;
+       char *plugin = NULL;
+       char *plugin_instance = NULL;
+       char *type = NULL;
+       char *type_instance = NULL;
+       int status;
+
+       if ((str == NULL) || (vl == NULL))
+               return (EINVAL);
+
+       sstrncpy (str_copy, str, sizeof (str_copy));
+
+       status = parse_identifier (str_copy, &host,
+                       &plugin, &plugin_instance,
+                       &type, &type_instance);
+       if (status != 0)
+               return (status);
+
+       sstrncpy (vl->host, host, sizeof (vl->host));
+       sstrncpy (vl->plugin, plugin, sizeof (vl->plugin));
+       sstrncpy (vl->plugin_instance,
+                       (plugin_instance != NULL) ? plugin_instance : "",
+                       sizeof (vl->plugin_instance));
+       sstrncpy (vl->type, type, sizeof (vl->type));
+       sstrncpy (vl->type_instance,
+                       (type_instance != NULL) ? type_instance : "",
+                       sizeof (vl->type_instance));
+
+       return (0);
+} /* }}} int parse_identifier_vl */
+
+int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
+{
+  char *value;
   char *endptr = NULL;
+  size_t value_len;
+
+  if (value_orig == NULL)
+    return (EINVAL);
+
+  value = strdup (value_orig);
+  if (value == NULL)
+    return (ENOMEM);
+  value_len = strlen (value);
+
+  while ((value_len > 0) && isspace ((int) value[value_len - 1]))
+  {
+    value[value_len - 1] = 0;
+    value_len--;
+  }
 
   switch (ds_type)
   {
@@ -933,25 +983,31 @@ int parse_value (const char *value, value_t *ret_value, int ds_type)
       break;
 
     case DS_TYPE_DERIVE:
-      ret_value->counter = (derive_t) strtoll (value, &endptr, 0);
+      ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
       break;
 
     case DS_TYPE_ABSOLUTE:
-      ret_value->counter = (absolute_t) strtoull (value, &endptr, 0);
+      ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
       break;
 
     default:
+      sfree (value);
       ERROR ("parse_value: Invalid data source type: %i.", ds_type);
       return -1;
   }
 
   if (value == endptr) {
-    ERROR ("parse_value: Failed to parse string as number: %s.", value);
+    sfree (value);
+    ERROR ("parse_value: Failed to parse string as %s: %s.",
+        DS_TYPE_TO_STRING (ds_type), value);
     return -1;
   }
   else if ((NULL != endptr) && ('\0' != *endptr))
-    WARNING ("parse_value: Ignoring trailing garbage after number: %s.",
-        endptr);
+    INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
+        "Input string was \"%s\".",
+        endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
+
+  sfree (value);
   return 0;
 } /* int parse_value */
 
@@ -979,9 +1035,22 @@ int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
                if (i == -1)
                {
                        if (strcmp ("N", ptr) == 0)
-                               vl->time = time (NULL);
+                               vl->time = cdtime ();
                        else
-                               vl->time = (time_t) atoi (ptr);
+                       {
+                               char *endptr = NULL;
+                               double tmp;
+
+                               errno = 0;
+                               tmp = strtod (ptr, &endptr);
+                               if ((errno != 0)                    /* Overflow */
+                                               || (endptr == ptr)  /* Invalid string */
+                                               || (endptr == NULL) /* This should not happen */
+                                               || (*endptr != 0))  /* Trailing chars */
+                                       return (-1);
+
+                               vl->time = DOUBLE_TO_CDTIME_T (tmp);
+                       }
                }
                else
                {
@@ -1160,7 +1229,102 @@ counter_t counter_diff (counter_t old_value, counter_t new_value)
        }
 
        return (diff);
-} /* counter_t counter_to_gauge */
+} /* counter_t counter_diff */
+
+int rate_to_value (value_t *ret_value, gauge_t rate, /* {{{ */
+               rate_to_value_state_t *state,
+               int ds_type, cdtime_t t)
+{
+       gauge_t delta_gauge;
+       cdtime_t delta_t;
+
+       if (ds_type == DS_TYPE_GAUGE)
+       {
+               state->last_value.gauge = rate;
+               state->last_time = t;
+
+               *ret_value = state->last_value;
+               return (0);
+       }
+
+       /* Counter and absolute can't handle negative rates. Reset "last time"
+        * to zero, so that the next valid rate will re-initialize the
+        * structure. */
+       if ((rate < 0.0)
+                       && ((ds_type == DS_TYPE_COUNTER)
+                               || (ds_type == DS_TYPE_ABSOLUTE)))
+       {
+               memset (state, 0, sizeof (*state));
+               return (EINVAL);
+       }
+
+       /* Another invalid state: The time is not increasing. */
+       if (t <= state->last_time)
+       {
+               memset (state, 0, sizeof (*state));
+               return (EINVAL);
+       }
+
+       delta_t = t - state->last_time;
+       delta_gauge = (rate * CDTIME_T_TO_DOUBLE (delta_t)) + state->residual;
+
+       /* Previous value is invalid. */
+       if (state->last_time == 0) /* {{{ */
+       {
+               if (ds_type == DS_TYPE_DERIVE)
+               {
+                       state->last_value.derive = (derive_t) rate;
+                       state->residual = rate - ((gauge_t) state->last_value.derive);
+               }
+               else if (ds_type == DS_TYPE_COUNTER)
+               {
+                       state->last_value.counter = (counter_t) rate;
+                       state->residual = rate - ((gauge_t) state->last_value.counter);
+               }
+               else if (ds_type == DS_TYPE_ABSOLUTE)
+               {
+                       state->last_value.absolute = (absolute_t) rate;
+                       state->residual = rate - ((gauge_t) state->last_value.absolute);
+               }
+               else
+               {
+                       assert (23 == 42);
+               }
+
+               state->last_time = t;
+               return (EAGAIN);
+       } /* }}} */
+
+       if (ds_type == DS_TYPE_DERIVE)
+       {
+               derive_t delta_derive = (derive_t) delta_gauge;
+
+               state->last_value.derive += delta_derive;
+               state->residual = delta_gauge - ((gauge_t) delta_derive);
+       }
+       else if (ds_type == DS_TYPE_COUNTER)
+       {
+               counter_t delta_counter = (counter_t) delta_gauge;
+
+               state->last_value.counter += delta_counter;
+               state->residual = delta_gauge - ((gauge_t) delta_counter);
+       }
+       else if (ds_type == DS_TYPE_ABSOLUTE)
+       {
+               absolute_t delta_absolute = (absolute_t) delta_gauge;
+
+               state->last_value.absolute = delta_absolute;
+               state->residual = delta_gauge - ((gauge_t) delta_absolute);
+       }
+       else
+       {
+               assert (23 == 42);
+       }
+
+        state->last_time = t;
+       *ret_value = state->last_value;
+       return (0);
+} /* }}} value_t rate_to_value */
 
 int service_name_to_port_number (const char *service_name)
 {
index 63ecca3..8a7d986 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/common.h
- * Copyright (C) 2005-2009  Florian octo Forster
+ * Copyright (C) 2005-2010  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Niki W. Waibel <niki.waibel@gmx.net>
 **/
 
                || (strcasecmp ("no", (s)) == 0) \
                || (strcasecmp ("off", (s)) == 0))
 
+struct rate_to_value_state_s
+{
+  value_t last_value;
+  cdtime_t last_time;
+  gauge_t residual;
+};
+typedef struct rate_to_value_state_s rate_to_value_state_t;
+
 char *sstrncpy (char *dest, const char *src, size_t n);
 int ssnprintf (char *dest, size_t n, const char *format, ...);
 char *sstrdup(const char *s);
@@ -265,6 +273,7 @@ int format_values (char *ret, size_t ret_len,
 int parse_identifier (char *str, char **ret_host,
                char **ret_plugin, char **ret_plugin_instance,
                char **ret_type, char **ret_type_instance);
+int parse_identifier_vl (const char *str, value_list_t *vl);
 int parse_value (const char *value, value_t *ret_value, int ds_type);
 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds);
 
@@ -277,19 +286,29 @@ int notification_init (notification_t *n, int severity, const char *message,
                const char *host,
                const char *plugin, const char *plugin_instance,
                const char *type, const char *type_instance);
-#define NOTIFICATION_INIT_VL(n, vl, ds) \
+#define NOTIFICATION_INIT_VL(n, vl) \
        notification_init (n, NOTIF_FAILURE, NULL, \
                        (vl)->host, (vl)->plugin, (vl)->plugin_instance, \
-                       (ds)->type, (vl)->type_instance)
+                       (vl)->type, (vl)->type_instance)
 
 typedef int (*dirwalk_callback_f)(const char *dirname, const char *filename,
                void *user_data);
 int walk_directory (const char *dir, dirwalk_callback_f callback,
                void *user_data, int hidden);
+/* Returns the number of bytes read or negative on error. */
 int read_file_contents (const char *filename, char *buf, int bufsize);
 
 counter_t counter_diff (counter_t old_value, counter_t new_value);
 
+/* Convert a rate back to a value_t. When converting to a derive_t, counter_t
+ * or absoltue_t, take fractional residuals into account. This is important
+ * when scaling counters, for example.
+ * Returns zero on success. Returns EAGAIN when called for the first time; in
+ * this case the value_t is invalid and the next call should succeed. Other
+ * return values indicate an error. */
+int rate_to_value (value_t *ret_value, gauge_t rate,
+               rate_to_value_state_t *state, int ds_type, cdtime_t t);
+
 /* Converts a service name (a string) to a port number
  * (in the range [1-65535]). Returns less than zero on error. */
 int service_name_to_port_number (const char *service_name);
index 99dded9..5920c53 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/configfile.c
- * Copyright (C) 2005-2010  Florian octo Forster
+ * Copyright (C) 2005-2011  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -17,7 +17,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Sebastian tokkee Harl <sh at tokkee.org>
  **/
 
@@ -29,7 +29,6 @@
 #include "plugin.h"
 #include "configfile.h"
 #include "types_list.h"
-#include "utils_threshold.h"
 #include "filter_chain.h"
 
 #if HAVE_WORDEXP_H
@@ -47,6 +46,7 @@ typedef struct cf_callback
        int  (*callback) (const char *, const char *);
        const char **keys;
        int    keys_num;
+       plugin_ctx_t ctx;
        struct cf_callback *next;
 } cf_callback_t;
 
@@ -54,6 +54,7 @@ typedef struct cf_complex_callback_s
 {
        char *type;
        int (*callback) (oconfig_item_t *);
+       plugin_ctx_t ctx;
        struct cf_complex_callback_s *next;
 } cf_complex_callback_t;
 
@@ -97,7 +98,7 @@ static cf_global_option_t cf_global_options[] =
        {"PIDFile",     NULL, PIDFILE},
        {"Hostname",    NULL, NULL},
        {"FQDNLookup",  NULL, "true"},
-       {"Interval",    NULL, "10"},
+       {"Interval",    NULL, NULL},
        {"ReadThreads", NULL, "5"},
        {"Timeout",     NULL, "2"},
        {"PreCacheChain",  NULL, "PreCache"},
@@ -129,6 +130,7 @@ static int cf_dispatch (const char *type, const char *orig_key,
                const char *orig_value)
 {
        cf_callback_t *cf_cb;
+       plugin_ctx_t old_ctx;
        char *key;
        char *value;
        int ret;
@@ -157,6 +159,8 @@ static int cf_dispatch (const char *type, const char *orig_key,
 
        ret = -1;
 
+       old_ctx = plugin_set_ctx (cf_cb->ctx);
+
        for (i = 0; i < cf_cb->keys_num; i++)
        {
                if ((cf_cb->keys[i] != NULL)
@@ -167,6 +171,8 @@ static int cf_dispatch (const char *type, const char *orig_key,
                }
        }
 
+       plugin_set_ctx (old_ctx);
+
        if (i >= cf_cb->keys_num)
                WARNING ("Plugin `%s' did not register for value `%s'.", type, key);
 
@@ -243,7 +249,12 @@ static int dispatch_value_plugindir (const oconfig_item_t *ci)
 static int dispatch_loadplugin (const oconfig_item_t *ci)
 {
        int i;
-       uint32_t flags = 0;
+       const char *name;
+       unsigned int flags = 0;
+       plugin_ctx_t ctx;
+       plugin_ctx_t old_ctx;
+       int ret_val;
+
        assert (strcasecmp (ci->key, "LoadPlugin") == 0);
 
        if (ci->values_num != 1)
@@ -251,19 +262,53 @@ static int dispatch_loadplugin (const oconfig_item_t *ci)
        if (ci->values[0].type != OCONFIG_TYPE_STRING)
                return (-1);
 
+       name = ci->values[0].value.string;
+
+       /* default to the global interval set before loading this plugin */
+       memset (&ctx, 0, sizeof (ctx));
+       ctx.interval = cf_get_default_interval ();
+
+       /*
+        * XXX: Magic at work:
+        *
+        * Some of the language bindings, for example the Python and Perl
+        * plugins, need to be able to export symbols to the scripts they run.
+        * For this to happen, the "Globals" flag needs to be set.
+        * Unfortunately, this technical detail is hard to explain to the
+        * average user and she shouldn't have to worry about this, ideally.
+        * So in order to save everyone's sanity use a different default for a
+        * handful of special plugins. --octo
+        */
+       if ((strcasecmp ("Perl", name) == 0)
+                       || (strcasecmp ("Python", name) == 0))
+               flags |= PLUGIN_FLAGS_GLOBAL;
+
        for (i = 0; i < ci->children_num; ++i) {
-               if (ci->children[i].values_num != 1 ||
-                               ci->children[i].values[0].type != OCONFIG_TYPE_BOOLEAN) {
-                       WARNING("Ignoring unknown LoadPlugin option %s for plugin %s", ci->children[i].key, ci->values[0].value.string);
-                       continue;
+               if (strcasecmp("Globals", ci->children[i].key) == 0)
+                       cf_util_get_flag (ci->children + i, &flags, PLUGIN_FLAGS_GLOBAL);
+               else if (strcasecmp ("Interval", ci->children[i].key) == 0) {
+                       double interval = 0.0;
+
+                       if (cf_util_get_double (ci->children + i, &interval) != 0) {
+                               /* cf_util_get_double will log an error */
+                               continue;
+                       }
+
+                       ctx.interval = DOUBLE_TO_CDTIME_T (interval);
                }
-               if (strcasecmp(ci->children[i].key, "globals") == 0) {
-                       flags |= PLUGIN_FLAGS_GLOBAL;
-               } else {
-                       WARNING("Ignoring unknown LoadPlugin option %s for plugin %s", ci->children[i].key, ci->values[0].value.string);
+               else {
+                       WARNING("Ignoring unknown LoadPlugin option \"%s\" "
+                                       "for plugin \"%s\"",
+                                       ci->children[i].key, ci->values[0].value.string);
                }
        }
-       return (plugin_load (ci->values[0].value.string, flags));
+
+       old_ctx = plugin_set_ctx (ctx);
+       ret_val = plugin_load (name, (uint32_t) flags);
+       /* reset to the "global" context */
+       plugin_set_ctx (old_ctx);
+
+       return (ret_val);
 } /* int dispatch_value_loadplugin */
 
 static int dispatch_value_plugin (const char *plugin, oconfig_item_t *ci)
@@ -342,8 +387,18 @@ static int dispatch_block_plugin (oconfig_item_t *ci)
 
        /* Check for a complex callback first */
        for (cb = complex_callback_head; cb != NULL; cb = cb->next)
+       {
                if (strcasecmp (name, cb->type) == 0)
-                       return (cb->callback (ci));
+               {
+                       plugin_ctx_t old_ctx;
+                       int ret_val;
+
+                       old_ctx = plugin_set_ctx (cb->ctx);
+                       ret_val = (cb->callback (ci));
+                       plugin_set_ctx (old_ctx);
+                       return (ret_val);
+               }
+       }
 
        /* Hm, no complex plugin found. Dispatch the values one by one */
        for (i = 0; i < ci->children_num; i++)
@@ -372,8 +427,6 @@ static int dispatch_block (oconfig_item_t *ci)
                return (dispatch_loadplugin (ci));
        else if (strcasecmp (ci->key, "Plugin") == 0)
                return (dispatch_block_plugin (ci));
-       else if (strcasecmp (ci->key, "Threshold") == 0)
-               return (ut_config (ci));
        else if (strcasecmp (ci->key, "Chain") == 0)
                return (fc_configure (ci));
 
@@ -815,6 +868,29 @@ const char *global_option_get (const char *option)
                        : cf_global_options[i].def);
 } /* char *global_option_get */
 
+cdtime_t cf_get_default_interval (void)
+{
+  char const *str = global_option_get ("Interval");
+  double interval_double = COLLECTD_DEFAULT_INTERVAL;
+
+  if (str != NULL)
+  {
+    char *endptr = NULL;
+    double tmp = strtod (str, &endptr);
+
+    if ((endptr == NULL) || (endptr == str) || (*endptr != 0))
+      ERROR ("cf_get_default_interval: Unable to parse string \"%s\" "
+          "as number.", str);
+    else if (tmp <= 0.0)
+      ERROR ("cf_get_default_interval: Interval must be a positive number. "
+          "The current number is %g.", tmp);
+    else
+      interval_double = tmp;
+  }
+
+  return (DOUBLE_TO_CDTIME_T (interval_double));
+} /* }}} cdtime_t cf_get_default_interval */
+
 void cf_unregister (const char *type)
 {
        cf_callback_t *this, *prev;
@@ -871,6 +947,7 @@ void cf_register (const char *type,
        cf_cb->callback = callback;
        cf_cb->keys     = keys;
        cf_cb->keys_num = keys_num;
+       cf_cb->ctx      = plugin_get_ctx ();
 
        cf_cb->next = first_callback;
        first_callback = cf_cb;
@@ -894,6 +971,8 @@ int cf_register_complex (const char *type, int (*callback) (oconfig_item_t *))
        new->callback = callback;
        new->next = NULL;
 
+       new->ctx = plugin_get_ctx ();
+
        if (complex_callback_head == NULL)
        {
                complex_callback_head = new;
@@ -1002,6 +1081,23 @@ int cf_util_get_int (const oconfig_item_t *ci, int *ret_value) /* {{{ */
        return (0);
 } /* }}} int cf_util_get_int */
 
+int cf_util_get_double (const oconfig_item_t *ci, double *ret_value) /* {{{ */
+{
+       if ((ci == NULL) || (ret_value == NULL))
+               return (EINVAL);
+
+       if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
+       {
+               ERROR ("cf_util_get_double: The %s option requires "
+                               "exactly one numeric argument.", ci->key);
+               return (-1);
+       }
+
+       *ret_value = ci->values[0].value.number;
+
+       return (0);
+} /* }}} int cf_util_get_double */
+
 int cf_util_get_boolean (const oconfig_item_t *ci, _Bool *ret_bool) /* {{{ */
 {
        if ((ci == NULL) || (ret_bool == NULL))
@@ -1045,17 +1141,111 @@ int cf_util_get_flag (const oconfig_item_t *ci, /* {{{ */
        return (0);
 } /* }}} int cf_util_get_flag */
 
-/* Assures that the config option is a string. The string is then converted to
- * a port number using `service_name_to_port_number' and returned. Returns the
- * port number in the range [1-65535] or less than zero upon failure. */
+/* Assures that the config option is a string or a number if the correct range
+ * of 1-65535. The string is then converted to a port number using
+ * `service_name_to_port_number' and returned.
+ * Returns the port number in the range [1-65535] or less than zero upon
+ * failure. */
 int cf_util_get_port_number (const oconfig_item_t *ci) /* {{{ */
 {
-       if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
+       int tmp;
+
+       if ((ci->values_num != 1)
+                       || ((ci->values[0].type != OCONFIG_TYPE_STRING)
+                               && (ci->values[0].type != OCONFIG_TYPE_NUMBER)))
        {
-               ERROR ("cf_util_get_port_number: The %s option requires "
+               ERROR ("cf_util_get_port_number: The \"%s\" option requires "
                                "exactly one string argument.", ci->key);
                return (-1);
        }
 
-       return (service_name_to_port_number (ci->values[0].value.string));
+       if (ci->values[0].type == OCONFIG_TYPE_STRING)
+               return (service_name_to_port_number (ci->values[0].value.string));
+
+       assert (ci->values[0].type == OCONFIG_TYPE_NUMBER);
+       tmp = (int) (ci->values[0].value.number + 0.5);
+       if ((tmp < 1) || (tmp > 65535))
+       {
+               ERROR ("cf_util_get_port_number: The \"%s\" option requires "
+                               "a service name or a port number. The number "
+                               "you specified, %i, is not in the valid "
+                               "range of 1-65535.",
+                               ci->key, tmp);
+               return (-1);
+       }
+
+       return (tmp);
 } /* }}} int cf_util_get_port_number */
+
+int cf_util_get_service (const oconfig_item_t *ci, char **ret_string) /* {{{ */
+{
+       int port;
+       char *service;
+       int status;
+
+       if (ci->values_num != 1)
+       {
+               ERROR ("cf_util_get_service: The %s option requires exactly "
+                               "one argument.", ci->key);
+               return (-1);
+       }
+
+       if (ci->values[0].type == OCONFIG_TYPE_STRING)
+               return (cf_util_get_string (ci, ret_string));
+       if (ci->values[0].type != OCONFIG_TYPE_NUMBER)
+       {
+               ERROR ("cf_util_get_service: The %s option requires "
+                               "exactly one string or numeric argument.",
+                               ci->key);
+       }
+
+       port = 0;
+       status = cf_util_get_int (ci, &port);
+       if (status != 0)
+               return (status);
+       else if ((port < 1) || (port > 65535))
+       {
+               ERROR ("cf_util_get_service: The port number given "
+                               "for the %s option is out of "
+                               "range (%i).", ci->key, port);
+               return (-1);
+       }
+
+       service = malloc (6);
+       if (service == NULL)
+       {
+               ERROR ("cf_util_get_service: Out of memory.");
+               return (-1);
+       }
+       ssnprintf (service, 6, "%i", port);
+
+       sfree (*ret_string);
+       *ret_string = service;
+
+       return (0);
+} /* }}} int cf_util_get_service */
+
+int cf_util_get_cdtime (const oconfig_item_t *ci, cdtime_t *ret_value) /* {{{ */
+{
+       if ((ci == NULL) || (ret_value == NULL))
+               return (EINVAL);
+
+       if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
+       {
+               ERROR ("cf_util_get_cdtime: The %s option requires "
+                               "exactly one numeric argument.", ci->key);
+               return (-1);
+       }
+
+       if (ci->values[0].value.number < 0.0)
+       {
+               ERROR ("cf_util_get_cdtime: The numeric argument of the %s "
+                               "option must not be negative.", ci->key);
+               return (-1);
+       }
+
+       *ret_value = DOUBLE_TO_CDTIME_T (ci->values[0].value.number);
+
+       return (0);
+} /* }}} int cf_util_get_cdtime */
+
index 519a6ff..5a719a4 100644 (file)
@@ -2,7 +2,7 @@
 #define CONFIGFILE_H
 /**
  * collectd - src/configfile.h
- * Copyright (C) 2005-2010  Florian octo Forster
+ * Copyright (C) 2005-2011  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
+#include "utils_time.h"
 #include "liboconfig/oconfig.h"
 
 /*
@@ -86,6 +87,8 @@ int cf_read (char *filename);
 int global_option_set (const char *option, const char *value);
 const char *global_option_get (const char *option);
 
+cdtime_t cf_get_default_interval (void);
+
 /* Assures the config option is a string, duplicates it and returns the copy in
  * "ret_string". If necessary "*ret_string" is freed first. Returns zero upon
  * success. */
@@ -99,6 +102,9 @@ int cf_util_get_string_buffer (const oconfig_item_t *ci, char *buffer,
 /* Assures the config option is a number and returns it as an int. */
 int cf_util_get_int (const oconfig_item_t *ci, int *ret_value);
 
+/* Assures the config option is a number and returns it as a double. */
+int cf_util_get_double (const oconfig_item_t *ci, double *ret_value);
+
 /* Assures the config option is a boolean and assignes it to `ret_bool'.
  * Otherwise, `ret_bool' is not changed and non-zero is returned. */
 int cf_util_get_boolean (const oconfig_item_t *ci, _Bool *ret_bool);
@@ -108,9 +114,19 @@ int cf_util_get_boolean (const oconfig_item_t *ci, _Bool *ret_bool);
 int cf_util_get_flag (const oconfig_item_t *ci,
                unsigned int *ret_value, unsigned int flag);
 
-/* Assures that the config option is a string. The string is then converted to
- * a port number using `service_name_to_port_number' and returned. Returns the
- * port number in the range [1-65535] or less than zero upon failure. */
+/* Assures that the config option is a string or a number if the correct range
+ * of 1-65535. The string is then converted to a port number using
+ * `service_name_to_port_number' and returned.
+ * Returns the port number in the range [1-65535] or less than zero upon
+ * failure. */
 int cf_util_get_port_number (const oconfig_item_t *ci);
 
+/* Assures that the config option is either a service name (a string) or a port
+ * number (an integer in the appropriate range) and returns a newly allocated
+ * string. If ret_string points to a non-NULL pointer, it is freed before
+ * assigning a new value. */
+int cf_util_get_service (const oconfig_item_t *ci, char **ret_string);
+
+int cf_util_get_cdtime (const oconfig_item_t *ci, cdtime_t *ret_value);
+
 #endif /* defined(CONFIGFILE_H) */
index e70ff5f..33236c4 100644 (file)
 
 #define CONNTRACK_FILE "/proc/sys/net/netfilter/nf_conntrack_count"
 
-static void conntrack_submit (double conntrack)
+static void conntrack_submit (value_t conntrack)
 {
-       value_t values[1];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].gauge = conntrack;
-
-       vl.values = values;
+       vl.values = &conntrack;
        vl.values_len = 1;
        sstrncpy (vl.host, hostname_g, sizeof (vl.host));
        sstrncpy (vl.plugin, "conntrack", sizeof (vl.plugin));
@@ -49,14 +46,16 @@ static void conntrack_submit (double conntrack)
 
 static int conntrack_read (void)
 {
-       double conntrack;
+       value_t conntrack;
        FILE *fh;
        char buffer[64];
+       size_t buffer_len;
 
        fh = fopen (CONNTRACK_FILE, "r");
        if (fh == NULL)
                return (-1);
 
+       memset (buffer, 0, sizeof (buffer));
        if (fgets (buffer, sizeof (buffer), fh) == NULL)
        {
                fclose (fh);
@@ -64,10 +63,18 @@ static int conntrack_read (void)
        }
        fclose (fh);
 
-       conntrack = atof (buffer);
+       /* strip trailing newline. */
+       buffer_len = strlen (buffer);
+       while ((buffer_len > 0) && isspace ((int) buffer[buffer_len - 1]))
+       {
+               buffer[buffer_len - 1] = 0;
+               buffer_len--;
+       }
+
+       if (parse_value (buffer, &conntrack, DS_TYPE_GAUGE) != 0)
+               return (-1);
 
-       if (conntrack > 0.0)
-               conntrack_submit (conntrack);
+       conntrack_submit (conntrack);
 
        return (0);
 } /* static int conntrack_read */
index c207318..344f76e 100644 (file)
 /* no global variables */
 /* #endif KERNEL_LINUX */
 
+#elif HAVE_PERFSTAT
+# include <sys/protosw.h>
+# include <libperfstat.h>
+/* #endif HAVE_PERFSTAT */
+
 #else
 # error "No applicable input method."
 #endif
@@ -121,7 +126,24 @@ static int cs_read (void)
 
        if (status == -2)
                ERROR ("contextswitch plugin: Unable to find context switch value.");
-#endif /* KERNEL_LINUX */
+/* #endif  KERNEL_LINUX */
+
+#elif HAVE_PERFSTAT
+       int status = 0;
+       perfstat_cpu_total_t perfcputotal;
+
+       status = perfstat_cpu_total(NULL, &perfcputotal, sizeof(perfstat_cpu_total_t), 1);
+       if (status < 0)
+       {
+               char errbuf[1024];
+               ERROR ("contextswitch plugin: perfstat_cpu_total: %s",
+                       sstrerror (errno, errbuf, sizeof (errbuf)));
+               return (-1);
+       }
+
+       cs_submit(perfcputotal.pswitch);
+       status = 0;
+#endif /* defined(HAVE_PERFSTAT) */
 
        return status;
 }
index 7aa6361..5448003 100644 (file)
--- a/src/cpu.c
+++ b/src/cpu.c
@@ -1,6 +1,6 @@
 /**
  * collectd - src/cpu.c
- * Copyright (C) 2005-2009  Florian octo Forster
+ * Copyright (C) 2005-2010  Florian octo Forster
  * Copyright (C) 2008       Oleg King
  * Copyright (C) 2009       Simon Kuhnle
  * Copyright (C) 2009       Manuel Sanmartin
@@ -163,7 +163,7 @@ static int init (void)
        DEBUG ("host_processors returned %i %s", (int) cpu_list_len, cpu_list_len == 1 ? "processor" : "processors");
        INFO ("cpu plugin: Found %i processor%s.", (int) cpu_list_len, cpu_list_len == 1 ? "" : "s");
 
-       cpu_temp_retry_max = 86400 / interval_g;
+       cpu_temp_retry_max = 86400 / CDTIME_T_TO_TIME_T (plugin_get_interval ());
 /* #endif PROCESSOR_CPU_LOAD_INFO */
 
 #elif defined(HAVE_LIBKSTAT)
@@ -241,12 +241,12 @@ static int init (void)
        return (0);
 } /* int init */
 
-static void submit (int cpu_num, const char *type_instance, counter_t value)
+static void submit (int cpu_num, const char *type_instance, derive_t value)
 {
        value_t values[1];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = value;
+       values[0].derive = value;
 
        vl.values = values;
        vl.values_len = 1;
@@ -298,10 +298,10 @@ static int cpu_read (void)
                        continue;
                }
 
-               submit (cpu, "user", (counter_t) cpu_info.cpu_ticks[CPU_STATE_USER]);
-               submit (cpu, "nice", (counter_t) cpu_info.cpu_ticks[CPU_STATE_NICE]);
-               submit (cpu, "system", (counter_t) cpu_info.cpu_ticks[CPU_STATE_SYSTEM]);
-               submit (cpu, "idle", (counter_t) cpu_info.cpu_ticks[CPU_STATE_IDLE]);
+               submit (cpu, "user", (derive_t) cpu_info.cpu_ticks[CPU_STATE_USER]);
+               submit (cpu, "nice", (derive_t) cpu_info.cpu_ticks[CPU_STATE_NICE]);
+               submit (cpu, "system", (derive_t) cpu_info.cpu_ticks[CPU_STATE_SYSTEM]);
+               submit (cpu, "idle", (derive_t) cpu_info.cpu_ticks[CPU_STATE_IDLE]);
 #endif /* PROCESSOR_CPU_LOAD_INFO */
 #if PROCESSOR_TEMPERATURE
                /*
@@ -352,8 +352,8 @@ static int cpu_read (void)
 
 #elif defined(KERNEL_LINUX)
        int cpu;
-       counter_t user, nice, syst, idle;
-       counter_t wait, intr, sitr; /* sitr == soft interrupt */
+       derive_t user, nice, syst, idle;
+       derive_t wait, intr, sitr; /* sitr == soft interrupt */
        FILE *fh;
        char buf[1024];
 
@@ -410,7 +410,7 @@ static int cpu_read (void)
 
 #elif defined(HAVE_LIBKSTAT)
        int cpu;
-       counter_t user, syst, idle, wait;
+       derive_t user, syst, idle, wait;
        static cpu_stat_t cs;
 
        if (kc == NULL)
@@ -421,10 +421,10 @@ static int cpu_read (void)
                if (kstat_read (kc, ksp[cpu], &cs) == -1)
                        continue; /* error message? */
 
-               idle = (counter_t) cs.cpu_sysinfo.cpu[CPU_IDLE];
-               user = (counter_t) cs.cpu_sysinfo.cpu[CPU_USER];
-               syst = (counter_t) cs.cpu_sysinfo.cpu[CPU_KERNEL];
-               wait = (counter_t) cs.cpu_sysinfo.cpu[CPU_WAIT];
+               idle = (derive_t) cs.cpu_sysinfo.cpu[CPU_IDLE];
+               user = (derive_t) cs.cpu_sysinfo.cpu[CPU_USER];
+               syst = (derive_t) cs.cpu_sysinfo.cpu[CPU_KERNEL];
+               wait = (derive_t) cs.cpu_sysinfo.cpu[CPU_WAIT];
 
                submit (ksp[cpu]->ks_instance, "user", user);
                submit (ksp[cpu]->ks_instance, "system", syst);
@@ -551,12 +551,12 @@ static int cpu_read (void)
                return (-1);
        }
 
-       submit (0, "idle",   (counter_t) cs->idle);
-       submit (0, "nice",   (counter_t) cs->nice);
-       submit (0, "swap",   (counter_t) cs->swap);
-       submit (0, "system", (counter_t) cs->kernel);
-       submit (0, "user",   (counter_t) cs->user);
-       submit (0, "wait",   (counter_t) cs->iowait);
+       submit (0, "idle",   (derive_t) cs->idle);
+       submit (0, "nice",   (derive_t) cs->nice);
+       submit (0, "swap",   (derive_t) cs->swap);
+       submit (0, "system", (derive_t) cs->kernel);
+       submit (0, "user",   (derive_t) cs->user);
+       submit (0, "wait",   (derive_t) cs->iowait);
 /* #endif HAVE_LIBSTATGRAB */
 
 #elif defined(HAVE_PERFSTAT)
@@ -591,10 +591,10 @@ static int cpu_read (void)
 
        for (i = 0; i < cpus; i++) 
        {
-               submit (i, "idle",   (counter_t) perfcpu[i].idle);
-               submit (i, "system", (counter_t) perfcpu[i].sys);
-               submit (i, "user",   (counter_t) perfcpu[i].user);
-               submit (i, "wait",   (counter_t) perfcpu[i].wait);
+               submit (i, "idle",   (derive_t) perfcpu[i].idle);
+               submit (i, "system", (derive_t) perfcpu[i].sys);
+               submit (i, "user",   (derive_t) perfcpu[i].user);
+               submit (i, "wait",   (derive_t) perfcpu[i].wait);
        }
 #endif /* HAVE_PERFSTAT */
 
index 46e2301..4b8aa72 100644 (file)
@@ -188,7 +188,7 @@ typedef struct {
        PluginData data;
        PyObject *values;    /* Sequence */
        PyObject *meta;      /* dict */
-       int interval;
+       double interval;
 } Values;
 PyTypeObject ValuesType;
 #define Values_New() PyObject_CallFunctionObjArgs((PyObject *) &ValuesType, (void *) 0)
index 96c1e3e..02d62c1 100644 (file)
--- a/src/csv.c
+++ b/src/csv.c
@@ -53,7 +53,8 @@ static int value_list_to_string (char *buffer, int buffer_len,
 
        memset (buffer, '\0', buffer_len);
 
-       status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) vl->time);
+       status = ssnprintf (buffer, buffer_len, "%.3f",
+                       CDTIME_T_TO_DOUBLE (vl->time));
        if ((status < 1) || (status >= buffer_len))
                return (-1);
        offset = status;
@@ -263,7 +264,7 @@ static int csv_write (const data_set_t *ds, const value_list_t *vl,
 {
        struct stat  statbuf;
        char         filename[512];
-       char         values[512];
+       char         values[4096];
        FILE        *csv;
        int          csv_fd;
        struct flock fl;
@@ -298,8 +299,10 @@ static int csv_write (const data_set_t *ds, const value_list_t *vl,
                }
 
                fprintf (use_stdio == 1 ? stdout : stderr,
-                        "PUTVAL %s interval=%i %s\n",
-                        filename, vl->interval, values);
+                        "PUTVAL %s interval=%.3f %s\n",
+                        filename,
+                        CDTIME_T_TO_DOUBLE (vl->interval),
+                        values);
                return (0);
        }
 
index 8b95c80..2160b98 100644 (file)
@@ -370,6 +370,7 @@ static int cc_page_init_curl (web_page_t *wp) /* {{{ */
     return (-1);
   }
 
+  curl_easy_setopt (wp->curl, CURLOPT_NOSIGNAL, 1);
   curl_easy_setopt (wp->curl, CURLOPT_WRITEFUNCTION, cc_curl_callback);
   curl_easy_setopt (wp->curl, CURLOPT_WRITEDATA, wp);
   curl_easy_setopt (wp->curl, CURLOPT_USERAGENT,
index 433764e..cc8b4ad 100644 (file)
@@ -1,7 +1,7 @@
 /**
  * collectd - src/curl_json.c
  * Copyright (C) 2009       Doug MacEachern
- * Copyright (C) 2006-2010  Florian octo Forster
+ * Copyright (C) 2006-2011  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -18,7 +18,7 @@
  *
  * Authors:
  *   Doug MacEachern <dougm at hyperic.com>
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
 #include "plugin.h"
 #include "configfile.h"
 #include "utils_avltree.h"
+#include "utils_complain.h"
 
 #include <curl/curl.h>
 #include <yajl/yajl_parse.h>
+#if HAVE_YAJL_YAJL_VERSION_H
+# include <yajl/yajl_version.h>
+#endif
+
+#if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
+# define HAVE_YAJL_V2 1
+#endif
 
 #define CJ_DEFAULT_HOST "localhost"
 #define CJ_KEY_MAGIC 0x43484b59UL /* CHKY */
-#define CJ_IS_KEY(key) (key)->magic == CJ_KEY_MAGIC
+#define CJ_IS_KEY(key) ((key)->magic == CJ_KEY_MAGIC)
 #define CJ_ANY "*"
 #define COUCH_MIN(x,y) ((x) < (y) ? (x) : (y))
 
@@ -56,8 +64,8 @@ struct cj_s /* {{{ */
   char *user;
   char *pass;
   char *credentials;
-  int   verify_peer;
-  int   verify_host;
+  _Bool verify_peer;
+  _Bool verify_host;
   char *cacert;
 
   CURL *curl;
@@ -77,6 +85,12 @@ struct cj_s /* {{{ */
 };
 typedef struct cj_s cj_t; /* }}} */
 
+#if HAVE_YAJL_V2
+typedef size_t yajl_len_t;
+#else
+typedef unsigned int yajl_len_t;
+#endif
+
 static int cj_read (user_data_t *ud);
 static int cj_curl_perform (cj_t *db, CURL *curl);
 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
@@ -97,9 +111,22 @@ static size_t cj_curl_callback (void *buf, /* {{{ */
   if (db == NULL)
     return (0);
 
-  status = yajl_parse(db->yajl, (unsigned char *)buf, len);
-  if ((status != yajl_status_ok)
-      && (status != yajl_status_insufficient_data))
+  status = yajl_parse(db->yajl, (unsigned char *) buf, len);
+  if (status == yajl_status_ok)
+  {
+#if HAVE_YAJL_V2
+    status = yajl_complete_parse(db->yajl);
+#else
+    status = yajl_parse_complete(db->yajl);
+#endif
+    return (len);
+  }
+#if !HAVE_YAJL_V2
+  else if (status == yajl_status_insufficient_data)
+    return (len);
+#endif
+
+  if (status != yajl_status_ok)
   {
     unsigned char *msg =
       yajl_get_error(db->yajl, /* verbose = */ 1,
@@ -118,9 +145,31 @@ static int cj_get_type (cj_key_t *key)
 
   ds = plugin_get_ds (key->type);
   if (ds == NULL)
-    return -1; /* let plugin_write do the complaining */
-  else
-    return ds->ds[0].type; /* XXX support ds->ds_len > 1 */
+  {
+    static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
+
+    assert (key->type != NULL);
+    if (strcmp (type, key->type) != 0)
+    {
+      ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
+          key->type);
+      sstrncpy (type, key->type, sizeof (type));
+    }
+
+    return -1;
+  }
+  else if (ds->ds_num > 1)
+  {
+    static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
+
+    c_complain_once (LOG_WARNING, &complaint,
+        "curl_json plugin: The type \"%s\" has more than one data source. "
+        "This is currently not supported. I will return the type of the "
+        "first data source, but this will likely lead to problems later on.",
+        key->type);
+  }
+
+  return ds->ds[0].type;
 }
 
 /* yajl callbacks */
@@ -130,45 +179,27 @@ static int cj_get_type (cj_key_t *key)
 /* "number" may not be null terminated, so copy it into a buffer before
  * parsing. */
 static int cj_cb_number (void *ctx,
-    const char *number, unsigned int number_len)
+    const char *number, yajl_len_t number_len)
 {
   char buffer[number_len + 1];
 
   cj_t *db = (cj_t *)ctx;
   cj_key_t *key = db->state[db->depth].key;
-  char *endptr;
   value_t vt;
   int type;
+  int status;
 
-  if (key == NULL)
+  if ((key == NULL) || !CJ_IS_KEY (key))
     return (CJ_CB_CONTINUE);
 
   memcpy (buffer, number, number_len);
   buffer[sizeof (buffer) - 1] = 0;
 
   type = cj_get_type (key);
-
-  endptr = NULL;
-  errno = 0;
-
-  if (type == DS_TYPE_COUNTER)
-    vt.counter = (counter_t) strtoull (buffer, &endptr, /* base = */ 0);
-  else if (type == DS_TYPE_GAUGE)
-    vt.gauge = (gauge_t) strtod (buffer, &endptr);
-  else if (type == DS_TYPE_DERIVE)
-    vt.derive = (derive_t) strtoll (buffer, &endptr, /* base = */ 0);
-  else if (type == DS_TYPE_ABSOLUTE)
-    vt.absolute = (absolute_t) strtoull (buffer, &endptr, /* base = */ 0);
-  else
-  {
-    ERROR ("curl_json plugin: Unknown data source type: \"%s\"", key->type);
-    return (CJ_CB_ABORT);
-  }
-
-  if ((endptr == &buffer[0]) || (errno != 0))
+  status = parse_value (buffer, &vt, type);
+  if (status != 0)
   {
-    NOTICE ("curl_json plugin: Overflow while parsing number. "
-        "Ignoring this value.");
+    NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
     return (CJ_CB_CONTINUE);
   }
 
@@ -177,7 +208,7 @@ static int cj_cb_number (void *ctx,
 } /* int cj_cb_number */
 
 static int cj_cb_map_key (void *ctx, const unsigned char *val,
-                            unsigned int len)
+    yajl_len_t len)
 {
   cj_t *db = (cj_t *)ctx;
   c_avl_tree_t *tree;
@@ -205,37 +236,29 @@ static int cj_cb_map_key (void *ctx, const unsigned char *val,
 }
 
 static int cj_cb_string (void *ctx, const unsigned char *val,
-                           unsigned int len)
+    yajl_len_t len)
 {
   cj_t *db = (cj_t *)ctx;
-  c_avl_tree_t *tree;
-  char *ptr;
-
-  if (db->depth != 1) /* e.g. _all_dbs */
-    return (CJ_CB_CONTINUE);
+  char str[len + 1];
 
-  cj_cb_map_key (ctx, val, len); /* same logic */
+  /* Create a null-terminated version of the string. */
+  memcpy (str, val, len);
+  str[len] = 0;
 
-  tree = db->state[db->depth].tree;
+  /* No configuration for this string -> simply return. */
+  if (db->state[db->depth].key == NULL)
+    return (CJ_CB_CONTINUE);
 
-  if ((tree != NULL) && (ptr = rindex (db->url, '/')))
+  if (!CJ_IS_KEY (db->state[db->depth].key))
   {
-    char url[PATH_MAX];
-    CURL *curl;
-
-    /* url =~ s,[^/]+$,$name, */
-    len = (ptr - db->url) + 1;
-    ptr = url;
-    sstrncpy (ptr, db->url, sizeof (url));
-    sstrncpy (ptr + len, db->state[db->depth].name, sizeof (url) - len);
-
-    curl = curl_easy_duphandle (db->curl);
-    curl_easy_setopt (curl, CURLOPT_URL, url);
-    cj_curl_perform (db, curl);
-    curl_easy_cleanup (curl);
+    NOTICE ("curl_json plugin: Found string \"%s\", but the configuration "
+        "expects a map here.", str);
+    return (CJ_CB_CONTINUE);
   }
-  return (CJ_CB_CONTINUE);
-}
+
+  /* Handle the string as if it was a number. */
+  return (cj_cb_number (ctx, (const char *) val, len));
+} /* int cj_cb_string */
 
 static int cj_cb_start (void *ctx)
 {
@@ -273,7 +296,7 @@ static int cj_cb_start_array (void * ctx)
 
 static int cj_cb_end_array (void * ctx)
 {
-  return cj_cb_start (ctx);
+  return cj_cb_end (ctx);
 }
 
 static yajl_callbacks ycallbacks = {
@@ -357,37 +380,6 @@ static void cj_free (void *arg) /* {{{ */
 
 /* Configuration handling functions {{{ */
 
-static int cj_config_add_string (const char *name, char **dest, /* {{{ */
-                                      oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
-  {
-    WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
-    return (-1);
-  }
-
-  sfree (*dest);
-  *dest = strdup (ci->values[0].value.string);
-  if (*dest == NULL)
-    return (-1);
-
-  return (0);
-} /* }}} int cj_config_add_string */
-
-static int cj_config_set_boolean (const char *name, int *dest, /* {{{ */
-                                       oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_BOOLEAN))
-  {
-    WARNING ("curl_json plugin: `%s' needs exactly one boolean argument.", name);
-    return (-1);
-  }
-
-  *dest = ci->values[0].value.boolean ? 1 : 0;
-
-  return (0);
-} /* }}} int cj_config_set_boolean */
-
 static c_avl_tree_t *cj_avl_create(void)
 {
   return c_avl_create ((int (*) (const void *, const void *)) strcmp);
@@ -419,7 +411,7 @@ static int cj_config_add_key (cj_t *db, /* {{{ */
 
   if (strcasecmp ("Key", ci->key) == 0)
   {
-    status = cj_config_add_string ("Key", &key->path, ci);
+    status = cf_util_get_string (ci, &key->path);
     if (status != 0)
     {
       sfree (key);
@@ -439,9 +431,9 @@ static int cj_config_add_key (cj_t *db, /* {{{ */
     oconfig_item_t *child = ci->children + i;
 
     if (strcasecmp ("Type", child->key) == 0)
-      status = cj_config_add_string ("Type", &key->type, child);
+      status = cf_util_get_string (child, &key->type);
     else if (strcasecmp ("Instance", child->key) == 0)
-      status = cj_config_add_string ("Instance", &key->instance, child);
+      status = cf_util_get_string (child, &key->instance);
     else
     {
       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
@@ -529,6 +521,7 @@ static int cj_init_curl (cj_t *db) /* {{{ */
     return (-1);
   }
 
+  curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1);
   curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
   curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
   curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
@@ -556,9 +549,9 @@ static int cj_init_curl (cj_t *db) /* {{{ */
     curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
   }
 
-  curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, db->verify_peer);
+  curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (int) db->verify_peer);
   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
-                    db->verify_host ? 2 : 0);
+                    (int) (db->verify_host ? 2 : 0));
   if (db->cacert != NULL)
     curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
 
@@ -589,7 +582,7 @@ static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
 
   if (strcasecmp ("URL", ci->key) == 0)
   {
-    status = cj_config_add_string ("URL", &db->url, ci);
+    status = cf_util_get_string (ci, &db->url);
     if (status != 0)
     {
       sfree (db);
@@ -609,19 +602,19 @@ static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
     oconfig_item_t *child = ci->children + i;
 
     if (strcasecmp ("Instance", child->key) == 0)
-      status = cj_config_add_string ("Instance", &db->instance, child);
+      status = cf_util_get_string (child, &db->instance);
     else if (strcasecmp ("Host", child->key) == 0)
-      status = cj_config_add_string ("Host", &db->host, child);
+      status = cf_util_get_string (child, &db->host);
     else if (strcasecmp ("User", child->key) == 0)
-      status = cj_config_add_string ("User", &db->user, child);
+      status = cf_util_get_string (child, &db->user);
     else if (strcasecmp ("Password", child->key) == 0)
-      status = cj_config_add_string ("Password", &db->pass, child);
+      status = cf_util_get_string (child, &db->pass);
     else if (strcasecmp ("VerifyPeer", child->key) == 0)
-      status = cj_config_set_boolean ("VerifyPeer", &db->verify_peer, child);
+      status = cf_util_get_boolean (child, &db->verify_peer);
     else if (strcasecmp ("VerifyHost", child->key) == 0)
-      status = cj_config_set_boolean ("VerifyHost", &db->verify_host, child);
+      status = cf_util_get_boolean (child, &db->verify_host);
     else if (strcasecmp ("CACert", child->key) == 0)
-      status = cj_config_add_string ("CACert", &db->cacert, child);
+      status = cf_util_get_string (child, &db->cacert);
     else if (strcasecmp ("Key", child->key) == 0)
       status = cj_config_add_key (db, child);
     else
@@ -734,8 +727,13 @@ static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
     host = db->host;
 
   if (key->instance == NULL)
-    ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
-               db->state[db->depth-1].name, db->state[db->depth].name);
+  {
+    if ((db->depth == 0) || (strcmp ("", db->state[db->depth-1].name) == 0))
+      sstrncpy (vl.type_instance, db->state[db->depth].name, sizeof (vl.type_instance));
+    else
+      ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
+          db->state[db->depth-1].name, db->state[db->depth].name);
+  }
   else
     sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
 
@@ -754,7 +752,13 @@ static int cj_curl_perform (cj_t *db, CURL *curl) /* {{{ */
   char *url;
   yajl_handle yprev = db->yajl;
 
-  db->yajl = yajl_alloc (&ycallbacks, NULL, NULL, (void *)db);
+  db->yajl = yajl_alloc (&ycallbacks,
+#if HAVE_YAJL_V2
+      /* alloc funcs = */ NULL,
+#else
+      /* alloc funcs = */ NULL, NULL,
+#endif
+      /* context = */ (void *)db);
   if (db->yajl == NULL)
   {
     ERROR ("curl_json plugin: yajl_alloc failed.");
@@ -762,17 +766,19 @@ static int cj_curl_perform (cj_t *db, CURL *curl) /* {{{ */
     return (-1);
   }
 
+  url = NULL;
+  curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
+
   status = curl_easy_perform (curl);
   if (status != 0)
   {
     ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
-           status, db->curl_errbuf, url);
+           status, db->curl_errbuf, (url != NULL) ? url : "<null>");
     yajl_free (db->yajl);
     db->yajl = yprev;
     return (-1);
   }
 
-  curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
   curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
 
   /* The response code is zero if a non-HTTP transport was used. */
@@ -785,7 +791,11 @@ static int cj_curl_perform (cj_t *db, CURL *curl) /* {{{ */
     return (-1);
   }
 
-  status = yajl_parse_complete (db->yajl);
+#if HAVE_YAJL_V2
+    status = yajl_complete_parse(db->yajl);
+#else
+    status = yajl_parse_complete(db->yajl);
+#endif
   if (status != yajl_status_ok)
   {
     unsigned char *errmsg;
index c10955c..46e0d49 100644 (file)
@@ -419,7 +419,8 @@ static int cx_handle_instance_xpath (xmlXPathContextPtr xpath_ctx, /* {{{ */
   return (0);
 } /* }}} int cx_handle_instance_xpath */
 
-static int  cx_handle_base_xpath (char *plugin_instance, /* {{{ */
+static int  cx_handle_base_xpath (char const *plugin_instance, /* {{{ */
+    char const *host,
     xmlXPathContextPtr xpath_ctx, const data_set_t *ds, 
     char *base_xpath, cx_xpath_t *xpath)
 {
@@ -461,7 +462,7 @@ static int  cx_handle_base_xpath (char *plugin_instance, /* {{{ */
   vl.values_len = ds->ds_num;
   sstrncpy (vl.type, xpath->type, sizeof (vl.type));
   sstrncpy (vl.plugin, "curl_xml", sizeof (vl.plugin));
-  sstrncpy (vl.host, hostname_g, sizeof (vl.host));
+  sstrncpy (vl.host, (host != NULL) ? host : hostname_g, sizeof (vl.host));
   if (plugin_instance != NULL)
     sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); 
 
@@ -504,7 +505,8 @@ static int cx_handle_parsed_xml(xmlDocPtr doc, /* {{{ */
     ds = plugin_get_ds (xpath->type);
 
     if ( (cx_check_type(ds, xpath) == 0) &&
-         (cx_handle_base_xpath(db->instance, xpath_ctx, ds, le->key, xpath) == 0) )
+         (cx_handle_base_xpath(db->instance, db->host,
+                               xpath_ctx, ds, le->key, xpath) == 0) )
       status = 0; /* we got atleast one success */
 
     le = le->next;
@@ -555,7 +557,8 @@ static int cx_curl_perform (cx_t *db, CURL *curl) /* {{{ */
   curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
   curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
 
-  if (rc != 200)
+  /* The response code is zero if a non-HTTP transport was used. */
+  if ((rc != 0) && (rc != 200))
   {
     ERROR ("curl_xml plugin: curl_easy_perform failed with response code %ld (%s)",
            rc, url);
@@ -734,6 +737,7 @@ static int cx_init_curl (cx_t *db) /* {{{ */
     return (-1);
   }
 
+  curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1);
   curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cx_curl_callback);
   curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
   curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
index cd9240a..caa41ef 100644 (file)
--- a/src/dbi.c
+++ b/src/dbi.c
@@ -566,7 +566,7 @@ static int cdbi_read_database_query (cdbi_database_t *db, /* {{{ */
 
   udb_query_prepare_result (q, prep_area, hostname_g,
       /* plugin = */ "dbi", db->name,
-      column_names, column_num, /* interval = */ -1);
+      column_names, column_num, /* interval = */ 0);
 
   /* 0 = error; 1 = success; */
   status = dbi_result_first_row (res); /* {{{ */
index 4b3cba0..ded374b 100644 (file)
--- a/src/df.c
+++ b/src/df.c
 #  include <sys/statvfs.h>
 # endif
 # define STATANYFS statvfs
+# define STATANYFS_STR "statvfs"
 # define BLOCKSIZE(s) ((s).f_frsize ? (s).f_frsize : (s).f_bsize)
 #elif HAVE_STATFS
 # if HAVE_SYS_STATFS_H
 #  include <sys/statfs.h>
 # endif
 # define STATANYFS statfs
+# define STATANYFS_STR "statfs"
 # define BLOCKSIZE(s) (s).f_bsize
 #else
 # error "No applicable input method."
@@ -198,7 +200,8 @@ static int df_read (void)
                if (STATANYFS (mnt_ptr->dir, &statbuf) < 0)
                {
                        char errbuf[1024];
-                       ERROR ("statv?fs failed: %s",
+                       ERROR (STATANYFS_STR"(%s) failed: %s",
+                                       mnt_ptr->dir,
                                        sstrerror (errno, errbuf,
                                                sizeof (errbuf)));
                        continue;
@@ -225,6 +228,8 @@ static int df_read (void)
                {
                        if (strcmp (mnt_ptr->dir, "/") == 0)
                        {
+                               if (strcmp (mnt_ptr->type, "rootfs") == 0)
+                                       continue;
                                sstrncpy (disk_name, "root", sizeof (disk_name));
                        }
                        else
@@ -242,7 +247,24 @@ static int df_read (void)
 
                blocksize = BLOCKSIZE(statbuf);
 
-               /* Sanity-check for the values in the struct */
+               /*
+                * Sanity-check for the values in the struct
+                */
+               /* Check for negative "available" byes. For example UFS can
+                * report negative free space for user. Notice. blk_reserved
+                * will start to diminish after this. */
+#if HAVE_STATVFS
+               /* Cast and temporary variable are needed to avoid
+                * compiler warnings.
+                * ((struct statvfs).f_bavail is unsigned (POSIX)) */
+               int64_t signed_bavail = (int64_t) statbuf.f_bavail;
+               if (signed_bavail < 0)
+                       statbuf.f_bavail = 0;
+#elif HAVE_STATFS
+               if (statbuf.f_bavail < 0)
+                       statbuf.f_bavail = 0;
+#endif
+               /* Make sure that f_blocks >= f_bfree >= f_bavail */
                if (statbuf.f_bfree < statbuf.f_bavail)
                        statbuf.f_bfree = statbuf.f_bavail;
                if (statbuf.f_blocks < statbuf.f_bfree)
index 0a90899..3728d55 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/disk.c
- * Copyright (C) 2005-2008  Florian octo Forster
+ * Copyright (C) 2005-2012  Florian octo Forster
  * Copyright (C) 2009       Manuel Sanmartin
  *
  * This program is free software; you can redistribute it and/or modify it
@@ -17,7 +17,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Manuel Sanmartin
  **/
 
@@ -75,6 +75,9 @@
 
 #if HAVE_IOKIT_IOKITLIB_H
 static mach_port_t io_master_port = MACH_PORT_NULL;
+/* This defaults to false for backwards compatibility. Please fix in the next
+ * major version. */
+static _Bool use_bsd_name = 0;
 /* #endif HAVE_IOKIT_IOKITLIB_H */
 
 #elif KERNEL_LINUX
@@ -85,19 +88,19 @@ typedef struct diskstats
        /* This overflows in roughly 1361 years */
        unsigned int poll_count;
 
-       counter_t read_sectors;
-       counter_t write_sectors;
+       derive_t read_sectors;
+       derive_t write_sectors;
 
-       counter_t read_bytes;
-       counter_t write_bytes;
+       derive_t read_bytes;
+       derive_t write_bytes;
 
-       counter_t read_ops;
-       counter_t write_ops;
-       counter_t read_time;
-       counter_t write_time;
+       derive_t read_ops;
+       derive_t write_ops;
+       derive_t read_time;
+       derive_t write_time;
 
-       counter_t avg_read_time;
-       counter_t avg_write_time;
+       derive_t avg_read_time;
+       derive_t avg_write_time;
 
        struct diskstats *next;
 } diskstats_t;
@@ -128,6 +131,7 @@ static int pnumdisk;
 static const char *config_keys[] =
 {
        "Disk",
+       "UseBSDName",
        "IgnoreSelected"
 };
 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
@@ -152,6 +156,15 @@ static int disk_config (const char *key, const char *value)
       invert = 0;
     ignorelist_set_invert (ignorelist, invert);
   }
+  else if (strcasecmp ("UseBSDName", key) == 0)
+  {
+#if HAVE_IOKIT_IOKITLIB_H
+    use_bsd_name = IS_TRUE (value) ? 1 : 0;
+#else
+    WARNING ("disk plugin: The \"UseBSDName\" option is only supported "
+        "on Mach / Mac OS X and will be ignored.");
+#endif
+  }
   else
   {
     return (-1);
@@ -212,7 +225,7 @@ static int disk_init (void)
 
 static void disk_submit (const char *plugin_instance,
                const char *type,
-               counter_t read, counter_t write)
+               derive_t read, derive_t write)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
@@ -221,8 +234,8 @@ static void disk_submit (const char *plugin_instance,
        if (ignorelist_match (ignorelist, plugin_instance) != 0)
          return;
 
-       values[0].counter = read;
-       values[1].counter = write;
+       values[0].derive = read;
+       values[1].derive = write;
 
        vl.values = values;
        vl.values_len = 2;
@@ -235,6 +248,17 @@ static void disk_submit (const char *plugin_instance,
        plugin_dispatch_values (&vl);
 } /* void disk_submit */
 
+#if KERNEL_LINUX
+static counter_t disk_calc_time_incr (counter_t delta_time, counter_t delta_ops)
+{
+       double interval = CDTIME_T_TO_DOUBLE (plugin_get_interval ());
+       double avg_time = ((double) delta_time) / ((double) delta_ops);
+       double avg_time_incr = interval * avg_time;
+
+       return ((counter_t) (avg_time_incr + .5));
+}
+#endif
+
 #if HAVE_IOKIT_IOKITLIB_H
 static signed long long dict_get_value (CFDictionaryRef dict, const char *key)
 {
@@ -281,7 +305,8 @@ static int disk_read (void)
        CFDictionaryRef         props_dict;
        CFDictionaryRef         stats_dict;
        CFDictionaryRef         child_dict;
-       kern_return_t           status;
+       CFStringRef             tmp_cf_string_ref;
+       kern_return_t           status;
 
        signed long long read_ops;
        signed long long read_byt;
@@ -292,7 +317,8 @@ static int disk_read (void)
 
        int  disk_major;
        int  disk_minor;
-       char disk_name[64];
+       char disk_name[DATA_MAX_NAME_LEN];
+       char disk_name_bsd[DATA_MAX_NAME_LEN];
 
        /* Get the list of all disk objects. */
        if (IOServiceGetMatchingServices (io_master_port,
@@ -340,12 +366,41 @@ static int disk_read (void)
                        continue;
                }
 
+               /* tmp_cf_string_ref doesn't need to be released. */
+               tmp_cf_string_ref = (CFStringRef) CFDictionaryGetValue (props_dict,
+                               CFSTR(kIOBSDNameKey));
+               if (!tmp_cf_string_ref)
+               {
+                       DEBUG ("disk plugin: CFDictionaryGetValue("
+                                       "kIOBSDNameKey) failed.");
+                       CFRelease (props_dict);
+                       IOObjectRelease (disk_child);
+                       IOObjectRelease (disk);
+                       continue;
+               }
+               assert (CFGetTypeID (tmp_cf_string_ref) == CFStringGetTypeID ());
+
+               memset (disk_name_bsd, 0, sizeof (disk_name_bsd));
+               CFStringGetCString (tmp_cf_string_ref,
+                               disk_name_bsd, sizeof (disk_name_bsd),
+                               kCFStringEncodingUTF8);
+               if (disk_name_bsd[0] == 0)
+               {
+                       ERROR ("disk plugin: CFStringGetCString() failed.");
+                       CFRelease (props_dict);
+                       IOObjectRelease (disk_child);
+                       IOObjectRelease (disk);
+                       continue;
+               }
+               DEBUG ("disk plugin: disk_name_bsd = \"%s\"", disk_name_bsd);
+
                stats_dict = (CFDictionaryRef) CFDictionaryGetValue (props_dict,
                                CFSTR (kIOBlockStorageDriverStatisticsKey));
 
                if (stats_dict == NULL)
                {
-                       DEBUG ("CFDictionaryGetValue (%s) failed.",
+                       DEBUG ("disk plugin: CFDictionaryGetValue ("
+                                       "%s) failed.",
                                        kIOBlockStorageDriverStatisticsKey);
                        CFRelease (props_dict);
                        IOObjectRelease (disk_child);
@@ -359,7 +414,8 @@ static int disk_read (void)
                                        kNilOptions)
                                != kIOReturnSuccess)
                {
-                       DEBUG ("IORegistryEntryCreateCFProperties (disk_child) failed.");
+                       DEBUG ("disk plugin: IORegistryEntryCreateCFProperties ("
+                                       "disk_child) failed.");
                        IOObjectRelease (disk_child);
                        CFRelease (props_dict);
                        IOObjectRelease (disk);
@@ -389,17 +445,12 @@ static int disk_read (void)
                write_tme = dict_get_value (stats_dict,
                                kIOBlockStorageDriverStatisticsTotalWriteTimeKey);
 
-               if (ssnprintf (disk_name, sizeof (disk_name),
-                               "%i-%i", disk_major, disk_minor) >= sizeof (disk_name))
-               {
-                       DEBUG ("snprintf (major, minor) failed.");
-                       CFRelease (child_dict);
-                       IOObjectRelease (disk_child);
-                       CFRelease (props_dict);
-                       IOObjectRelease (disk);
-                       continue;
-               }
-               DEBUG ("disk_name = %s", disk_name);
+               if (use_bsd_name)
+                       sstrncpy (disk_name, disk_name_bsd, sizeof (disk_name));
+               else
+                       ssnprintf (disk_name, sizeof (disk_name), "%i-%i",
+                                       disk_major, disk_minor);
+               DEBUG ("disk plugin: disk_name = \"%s\"", disk_name);
 
                if ((read_byt != -1LL) || (write_byt != -1LL))
                        disk_submit (disk_name, "disk_octets", read_byt, write_byt);
@@ -426,18 +477,17 @@ static int disk_read (void)
        int numfields;
        int fieldshift = 0;
 
-       int major = 0;
        int minor = 0;
 
-       counter_t read_sectors  = 0;
-       counter_t write_sectors = 0;
+       derive_t read_sectors  = 0;
+       derive_t write_sectors = 0;
 
-       counter_t read_ops      = 0;
-       counter_t read_merged   = 0;
-       counter_t read_time     = 0;
-       counter_t write_ops     = 0;
-       counter_t write_merged  = 0;
-       counter_t write_time    = 0;
+       derive_t read_ops      = 0;
+       derive_t read_merged   = 0;
+       derive_t read_time     = 0;
+       derive_t write_ops     = 0;
+       derive_t write_merged  = 0;
+       derive_t write_time    = 0;
        int is_disk = 0;
 
        diskstats_t *ds, *pre_ds;
@@ -464,7 +514,6 @@ static int disk_read (void)
                if ((numfields != (14 + fieldshift)) && (numfields != 7))
                        continue;
 
-               major = atoll (fields[0]);
                minor = atoll (fields[1]);
 
                disk_name = fields[2 + fieldshift];
@@ -523,8 +572,8 @@ static int disk_read (void)
                }
 
                {
-                       counter_t diff_read_sectors;
-                       counter_t diff_write_sectors;
+                       derive_t diff_read_sectors;
+                       derive_t diff_write_sectors;
 
                /* If the counter wraps around, it's only 32 bits.. */
                        if (read_sectors < ds->read_sectors)
@@ -547,18 +596,18 @@ static int disk_read (void)
                /* Calculate the average time an io-op needs to complete */
                if (is_disk)
                {
-                       counter_t diff_read_ops;
-                       counter_t diff_write_ops;
-                       counter_t diff_read_time;
-                       counter_t diff_write_time;
+                       derive_t diff_read_ops;
+                       derive_t diff_write_ops;
+                       derive_t diff_read_time;
+                       derive_t diff_write_time;
 
                        if (read_ops < ds->read_ops)
                                diff_read_ops = 1 + read_ops
                                        + (UINT_MAX - ds->read_ops);
                        else
                                diff_read_ops = read_ops - ds->read_ops;
-                       DEBUG ("disk plugin: disk_name = %s; read_ops = %llu; "
-                                       "ds->read_ops = %llu; diff_read_ops = %llu;",
+                       DEBUG ("disk plugin: disk_name = %s; read_ops = %"PRIi64"; "
+                                       "ds->read_ops = %"PRIi64"; diff_read_ops = %"PRIi64";",
                                        disk_name,
                                        read_ops, ds->read_ops, diff_read_ops);
 
@@ -581,13 +630,11 @@ static int disk_read (void)
                                diff_write_time = write_time - ds->write_time;
 
                        if (diff_read_ops != 0)
-                               ds->avg_read_time += (diff_read_time
-                                               + (diff_read_ops / 2))
-                                       / diff_read_ops;
+                               ds->avg_read_time += disk_calc_time_incr (
+                                               diff_read_time, diff_read_ops);
                        if (diff_write_ops != 0)
-                               ds->avg_write_time += (diff_write_time
-                                               + (diff_write_ops / 2))
-                                       / diff_write_ops;
+                               ds->avg_write_time += disk_calc_time_incr (
+                                               diff_write_time, diff_write_ops);
 
                        ds->read_ops = read_ops;
                        ds->read_time = read_time;
@@ -700,12 +747,12 @@ static int disk_read (void)
 /* #endif defined(HAVE_LIBSTATGRAB) */
 
 #elif defined(HAVE_PERFSTAT)
-       counter_t read_sectors;
-       counter_t write_sectors;
-       counter_t read_time;
-       counter_t write_time;
-       counter_t read_ops;
-       counter_t write_ops;
+       derive_t read_sectors;
+       derive_t write_sectors;
+       derive_t read_time;
+       derive_t write_time;
+       derive_t read_ops;
+       derive_t write_ops;
        perfstat_id_t firstpath;
        int rnumdisk;
        int i;
index 6e63fe4..fe3b672 100644 (file)
--- a/src/dns.c
+++ b/src/dns.c
@@ -1,6 +1,6 @@
 /**
  * collectd - src/dns.c
- * Copyright (C) 2006,2007  Florian octo Forster
+ * Copyright (C) 2006-2011  Florian octo Forster
  * Copyright (C) 2009       Mirko Buffoni
  *
  * This program is free software; you can redistribute it and/or modify it
@@ -17,7 +17,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Mirko Buffoni <briareos at eswat.org>
  **/
 
 
 #include "utils_dns.h"
 #include <pthread.h>
-#include <pcap.h>
 #include <poll.h>
 
+#include <pcap.h>
+#include <pcap-bpf.h>
+
 /*
  * Private data types
  */
@@ -59,8 +61,8 @@ static int select_numeric_qtype = 1;
 #define PCAP_SNAPLEN 1460
 static char   *pcap_device = NULL;
 
-static counter_t       tr_queries;
-static counter_t       tr_responses;
+static derive_t       tr_queries;
+static derive_t       tr_responses;
 static counter_list_t *qtype_list;
 static counter_list_t *opcode_list;
 static counter_list_t *rcode_list;
@@ -206,7 +208,7 @@ static void dns_child_callback (const rfc1035_header_t *dns)
        pthread_mutex_unlock (&opcode_mutex);
 }
 
-static void *dns_child_loop (void __attribute__((unused)) *dummy)
+static void *dns_child_loop (__attribute__((unused)) void *dummy)
 {
        pcap_t *pcap_obj;
        char    pcap_error[PCAP_ERRBUF_SIZE];
@@ -226,7 +228,7 @@ static void *dns_child_loop (void __attribute__((unused)) *dummy)
        pcap_obj = pcap_open_live ((pcap_device != NULL) ? pcap_device : "any",
                        PCAP_SNAPLEN,
                        0 /* Not promiscuous */,
-                       interval_g,
+                       (int) CDTIME_T_TO_MS (plugin_get_interval () / 2),
                        pcap_error);
        if (pcap_obj == NULL)
        {
@@ -284,7 +286,7 @@ static int dns_init (void)
        if (listen_thread_init != 0)
                return (-1);
 
-       status = pthread_create (&listen_thread, NULL, dns_child_loop,
+       status = plugin_thread_create (&listen_thread, NULL, dns_child_loop,
                        (void *) 0);
        if (status != 0)
        {
@@ -299,13 +301,13 @@ static int dns_init (void)
        return (0);
 } /* int dns_init */
 
-static void submit_counter (const char *type, const char *type_instance,
-               counter_t value)
+static void submit_derive (const char *type, const char *type_instance,
+               derive_t value)
 {
        value_t values[1];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = value;
+       values[0].derive = value;
 
        vl.values = values;
        vl.values_len = 1;
@@ -315,15 +317,15 @@ static void submit_counter (const char *type, const char *type_instance,
        sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
 
        plugin_dispatch_values (&vl);
-} /* void submit_counter */
+} /* void submit_derive */
 
-static void submit_octets (counter_t queries, counter_t responses)
+static void submit_octets (derive_t queries, derive_t responses)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = queries;
-       values[1].counter = responses;
+       values[0].derive = queries;
+       values[1].derive = responses;
 
        vl.values = values;
        vl.values_len = 2;
@@ -332,7 +334,7 @@ static void submit_octets (counter_t queries, counter_t responses)
        sstrncpy (vl.type, "dns_octets", sizeof (vl.type));
 
        plugin_dispatch_values (&vl);
-} /* void submit_counter */
+} /* void submit_octets */
 
 static int dns_read (void)
 {
@@ -364,7 +366,7 @@ static int dns_read (void)
        for (i = 0; i < len; i++)
        {
                DEBUG ("dns plugin: qtype = %u; counter = %u;", keys[i], values[i]);
-               submit_counter ("dns_qtype", qtype_str (keys[i]), values[i]);
+               submit_derive ("dns_qtype", qtype_str (keys[i]), values[i]);
        }
 
        pthread_mutex_lock (&opcode_mutex);
@@ -380,7 +382,7 @@ static int dns_read (void)
        for (i = 0; i < len; i++)
        {
                DEBUG ("dns plugin: opcode = %u; counter = %u;", keys[i], values[i]);
-               submit_counter ("dns_opcode", opcode_str (keys[i]), values[i]);
+               submit_derive ("dns_opcode", opcode_str (keys[i]), values[i]);
        }
 
        pthread_mutex_lock (&rcode_mutex);
@@ -396,7 +398,7 @@ static int dns_read (void)
        for (i = 0; i < len; i++)
        {
                DEBUG ("dns plugin: rcode = %u; counter = %u;", keys[i], values[i]);
-               submit_counter ("dns_rcode", rcode_str (keys[i]), values[i]);
+               submit_derive ("dns_rcode", rcode_str (keys[i]), values[i]);
        }
 
        return (0);
index 8fc5509..8f633cd 100644 (file)
@@ -376,6 +376,7 @@ static void *collect (void *arg)
        } /* while (1) */
 
        pthread_exit ((void *)0);
+       return ((void *) 0);
 } /* static void *collect (void *) */
 
 static void *open_connection (void __attribute__((unused)) *arg)
@@ -481,8 +482,8 @@ static void *open_connection (void __attribute__((unused)) *arg)
                        collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
                        collectors[i]->socket = NULL;
 
-                       if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
-                                                       collect, collectors[i]))) {
+                       if (0 != (err = plugin_thread_create (&collectors[i]->thread,
+                                                       &ptattr, collect, collectors[i]))) {
                                char errbuf[1024];
                                log_err ("pthread_create() failed: %s",
                                                sstrerror (errno, errbuf, sizeof (errbuf)));
@@ -548,14 +549,16 @@ static void *open_connection (void __attribute__((unused)) *arg)
 
                pthread_cond_signal (&conn_available);
        }
-       pthread_exit ((void *)0);
+
+       pthread_exit ((void *) 0);
+       return ((void *) 0);
 } /* static void *open_connection (void *) */
 
 static int email_init (void)
 {
        int err = 0;
 
-       if (0 != (err = pthread_create (&connector, NULL,
+       if (0 != (err = plugin_thread_create (&connector, NULL,
                                open_connection, NULL))) {
                char errbuf[1024];
                disabled = 1;
diff --git a/src/ethstat.c b/src/ethstat.c
new file mode 100644 (file)
index 0000000..08381a8
--- /dev/null
@@ -0,0 +1,337 @@
+/**
+ * collectd - src/ethstat.c
+ * Copyright (C) 2011       Cyril Feraudet
+ * Copyright (C) 2012       Florian "octo" Forster
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or (at your
+ * option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Authors:
+ *   Cyril Feraudet <cyril at feraudet.com>
+ *   Florian "octo" Forster <octo@collectd.org>
+ **/
+
+#include "collectd.h"
+#include "common.h"
+#include "plugin.h"
+#include "configfile.h"
+#include "utils_avltree.h"
+#include "utils_complain.h"
+
+#if HAVE_SYS_IOCTL_H
+# include <sys/ioctl.h>
+#endif
+#if HAVE_NET_IF_H
+# include <net/if.h>
+#endif
+#if HAVE_LINUX_SOCKIOS_H
+# include <linux/sockios.h>
+#endif
+#if HAVE_LINUX_ETHTOOL_H
+# include <linux/ethtool.h>
+#endif
+
+struct value_map_s
+{
+  char type[DATA_MAX_NAME_LEN];
+  char type_instance[DATA_MAX_NAME_LEN];
+};
+typedef struct value_map_s value_map_t;
+
+static char **interfaces = NULL;
+static size_t interfaces_num = 0;
+
+static c_avl_tree_t *value_map = NULL;
+
+static _Bool collect_mapped_only = 0;
+
+static int ethstat_add_interface (const oconfig_item_t *ci) /* {{{ */
+{
+  char **tmp;
+  int status;
+
+  tmp = realloc (interfaces,
+      sizeof (*interfaces) * (interfaces_num + 1));
+  if (tmp == NULL)
+    return (-1);
+  interfaces = tmp;
+  interfaces[interfaces_num] = NULL;
+
+  status = cf_util_get_string (ci, interfaces + interfaces_num);
+  if (status != 0)
+    return (status);
+
+  interfaces_num++;
+  INFO("ethstat plugin: Registred interface %s",
+      interfaces[interfaces_num - 1]);
+
+  return (0);
+} /* }}} int ethstat_add_interface */
+
+static int ethstat_add_map (const oconfig_item_t *ci) /* {{{ */
+{
+  value_map_t *map;
+  int status;
+
+  if ((ci->values_num < 2)
+      || (ci->values_num > 3)
+      || (ci->values[0].type != OCONFIG_TYPE_STRING)
+      || (ci->values[1].type != OCONFIG_TYPE_STRING)
+      || ((ci->values_num == 3)
+        && (ci->values[2].type != OCONFIG_TYPE_STRING)))
+  {
+    ERROR ("ethstat plugin: The %s option requires "
+        "two or three string arguments.", ci->key);
+    return (-1);
+  }
+
+  map = malloc (sizeof (*map));
+  if (map == NULL)
+  {
+    ERROR ("ethstat plugin: malloc(3) failed.");
+    return (ENOMEM);
+  }
+  memset (map, 0, sizeof (*map));
+
+  sstrncpy (map->type, ci->values[1].value.string, sizeof (map->type));
+  if (ci->values_num == 3)
+    sstrncpy (map->type_instance, ci->values[2].value.string,
+        sizeof (map->type_instance));
+
+  if (value_map == NULL)
+  {
+    value_map = c_avl_create ((void *) strcmp);
+    if (value_map == NULL)
+    {
+      sfree (map);
+      ERROR ("ethstat plugin: c_avl_create() failed.");
+      return (-1);
+    }
+  }
+
+  status = c_avl_insert (value_map,
+      /* key = */ ci->values[0].value.string,
+      /* value = */ map);
+  if (status != 0)
+  {
+    sfree (map);
+    if (status > 0)
+      ERROR ("ethstat plugin: Multiple mappings for \"%s\".",
+          ci->values[0].value.string);
+    else
+      ERROR ("ethstat plugin: c_avl_insert(\"%s\") failed.",
+          ci->values[0].value.string);
+    return (-1);
+  }
+
+  return (0);
+} /* }}} int ethstat_add_map */
+
+static int ethstat_config (oconfig_item_t *ci) /* {{{ */
+{
+  int i;
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *child = ci->children + i;
+
+    if (strcasecmp ("Interface", child->key) == 0)
+      ethstat_add_interface (child);
+    else if (strcasecmp ("Map", child->key) == 0)
+      ethstat_add_map (child);
+    else if (strcasecmp ("MappedOnly", child->key) == 0)
+      (void) cf_util_get_boolean (child, &collect_mapped_only);
+    else
+      WARNING ("ethstat plugin: The config option \"%s\" is unknown.",
+          child->key);
+  }
+
+  return (0);
+} /* }}} */
+
+static void ethstat_submit_value (const char *device,
+    const char *type_instance, derive_t value)
+{
+  static c_complain_t complain_no_map = C_COMPLAIN_INIT_STATIC;
+
+  value_t values[1];
+  value_list_t vl = VALUE_LIST_INIT;
+  value_map_t *map = NULL;
+
+  if (value_map != NULL)
+    c_avl_get (value_map, type_instance, (void *) &map);
+
+  /* If the "MappedOnly" option is specified, ignore unmapped values. */
+  if (collect_mapped_only && (map == NULL))
+  {
+    if (value_map == NULL)
+      c_complain (LOG_WARNING, &complain_no_map,
+          "ethstat plugin: The \"MappedOnly\" option has been set to true, "
+          "but no mapping has been configured. All values will be ignored!");
+    return;
+  }
+
+  values[0].derive = value;
+  vl.values = values;
+  vl.values_len = 1;
+
+  sstrncpy (vl.host, hostname_g, sizeof (vl.host));
+  sstrncpy (vl.plugin, "ethstat", sizeof (vl.plugin));
+  sstrncpy (vl.plugin_instance, device, sizeof (vl.plugin_instance));
+  if (map != NULL)
+  {
+    sstrncpy (vl.type, map->type, sizeof (vl.type));
+    sstrncpy (vl.type_instance, map->type_instance,
+        sizeof (vl.type_instance));
+  }
+  else
+  {
+    sstrncpy (vl.type, "derive", sizeof (vl.type));
+    sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
+  }
+
+  plugin_dispatch_values (&vl);
+}
+
+static int ethstat_read_interface (char *device)
+{
+  int fd;
+  struct ifreq req;
+  struct ethtool_drvinfo drvinfo;
+  struct ethtool_gstrings *strings;
+  struct ethtool_stats *stats;
+  size_t n_stats;
+  size_t strings_size;
+  size_t stats_size;
+  size_t i;
+  int status;
+
+  memset (&req, 0, sizeof (req));
+  sstrncpy(req.ifr_name, device, sizeof (req.ifr_name));
+
+  fd = socket(AF_INET, SOCK_DGRAM, /* protocol = */ 0);
+  if (fd < 0)
+  {
+    char errbuf[1024];
+    ERROR("ethstat plugin: Failed to open control socket: %s",
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return 1;
+  }
+
+  memset (&drvinfo, 0, sizeof (drvinfo));
+  drvinfo.cmd = ETHTOOL_GDRVINFO;
+  req.ifr_data = (void *) &drvinfo;
+  status = ioctl (fd, SIOCETHTOOL, &req);
+  if (status < 0)
+  {
+    char errbuf[1024];
+    close (fd);
+    ERROR ("ethstat plugin: Failed to get driver information "
+        "from %s: %s", device,
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return (-1);
+  }
+
+  n_stats = (size_t) drvinfo.n_stats;
+  if (n_stats < 1)
+  {
+    close (fd);
+    ERROR("ethstat plugin: No stats available for %s", device);
+    return (-1);
+  }
+
+  strings_size = sizeof (struct ethtool_gstrings)
+    + (n_stats * ETH_GSTRING_LEN);
+  stats_size = sizeof (struct ethtool_stats)
+    + (n_stats * sizeof (uint64_t));
+
+  strings = malloc (strings_size);
+  stats = malloc (stats_size);
+  if ((strings == NULL) || (stats == NULL))
+  {
+    close (fd);
+    sfree (strings);
+    sfree (stats);
+    ERROR("ethstat plugin: malloc(3) failed.");
+    return (-1);
+  }
+
+  strings->cmd = ETHTOOL_GSTRINGS;
+  strings->string_set = ETH_SS_STATS;
+  strings->len = n_stats;
+  req.ifr_data = (void *) strings;
+  status = ioctl (fd, SIOCETHTOOL, &req);
+  if (status < 0)
+  {
+    char errbuf[1024];
+    close (fd);
+    free (strings);
+    free (stats);
+    ERROR ("ethstat plugin: Cannot get strings from %s: %s",
+        device,
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return (-1);
+  }
+
+  stats->cmd = ETHTOOL_GSTATS;
+  stats->n_stats = n_stats;
+  req.ifr_data = (void *) stats;
+  status = ioctl (fd, SIOCETHTOOL, &req);
+  if (status < 0)
+  {
+    char errbuf[1024];
+    close (fd);
+    free(strings);
+    free(stats);
+    ERROR("ethstat plugin: Reading statistics from %s failed: %s",
+        device,
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return (-1);
+  }
+
+  for (i = 0; i < n_stats; i++)
+  {
+    const char *stat_name;
+
+    stat_name = (void *) &strings->data[i * ETH_GSTRING_LEN];
+    DEBUG("ethstat plugin: device = \"%s\": %s = %"PRIu64,
+        device, stat_name, (uint64_t) stats->data[i]);
+    ethstat_submit_value (device,
+        stat_name, (derive_t) stats->data[i]);
+  }
+
+  close (fd);
+  sfree (strings);
+  sfree (stats);
+
+  return (0);
+} /* }}} ethstat_read_interface */
+
+static int ethstat_read(void)
+{
+  size_t i;
+
+  for (i = 0; i < interfaces_num; i++)
+    ethstat_read_interface (interfaces[i]);
+
+  return 0;
+}
+
+void module_register (void)
+{
+  plugin_register_complex_config ("ethstat", ethstat_config);
+  plugin_register_read ("ethstat", ethstat_read);
+}
+
+/* vim: set sw=2 sts=2 et fdm=marker : */
index 9aabe9f..14d288f 100644 (file)
@@ -93,7 +93,7 @@ static void sigchld_handler (int __attribute__((unused)) signal) /* {{{ */
     program_list_t *pl;
     for (pl = pl_head; pl != NULL; pl = pl->next)
       if (pl->pid == pid)
-       break;
+        break;
     if (pl != NULL)
       pl->status = status;
   } /* while (waitpid) */
@@ -108,20 +108,20 @@ static int exec_config_exec (oconfig_item_t *ci) /* {{{ */
   if (ci->children_num != 0)
   {
     WARNING ("exec plugin: The config option `%s' may not be a block.",
-       ci->key);
+        ci->key);
     return (-1);
   }
   if (ci->values_num < 2)
   {
     WARNING ("exec plugin: The config option `%s' needs at least two "
-       "arguments.", ci->key);
+        "arguments.", ci->key);
     return (-1);
   }
   if ((ci->values[0].type != OCONFIG_TYPE_STRING)
       || (ci->values[1].type != OCONFIG_TYPE_STRING))
   {
     WARNING ("exec plugin: The first two arguments to the `%s' option must "
-       "be string arguments.", ci->key);
+        "be string arguments.", ci->key);
     return (-1);
   }
 
@@ -201,15 +201,15 @@ static int exec_config_exec (oconfig_item_t *ci) /* {{{ */
     {
       if (ci->values[i + 1].type == OCONFIG_TYPE_NUMBER)
       {
-       ssnprintf (buffer, sizeof (buffer), "%lf",
-           ci->values[i + 1].value.number);
+        ssnprintf (buffer, sizeof (buffer), "%lf",
+            ci->values[i + 1].value.number);
       }
       else
       {
-       if (ci->values[i + 1].value.boolean)
-         sstrncpy (buffer, "true", sizeof (buffer));
-       else
-         sstrncpy (buffer, "false", sizeof (buffer));
+        if (ci->values[i + 1].value.boolean)
+          sstrncpy (buffer, "true", sizeof (buffer));
+        else
+          sstrncpy (buffer, "false", sizeof (buffer));
       }
 
       pl->argv[i] = strdup (buffer);
@@ -254,7 +254,7 @@ static int exec_config (oconfig_item_t *ci) /* {{{ */
   {
     oconfig_item_t *child = ci->children + i;
     if ((strcasecmp ("Exec", child->key) == 0)
-       || (strcasecmp ("NotificationExec", child->key) == 0))
+        || (strcasecmp ("NotificationExec", child->key) == 0))
       exec_config_exec (child);
     else
     {
@@ -270,22 +270,20 @@ static void set_environment (void) /* {{{ */
   char buffer[1024];
 
 #ifdef HAVE_SETENV
-  ssnprintf (buffer, sizeof (buffer), "%i", interval_g);
+  ssnprintf (buffer, sizeof (buffer), "%.3f",
+      CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
   setenv ("COLLECTD_INTERVAL", buffer, /* overwrite = */ 1);
 
   ssnprintf (buffer, sizeof (buffer), "%s", hostname_g);
   setenv ("COLLECTD_HOSTNAME", buffer, /* overwrite = */ 1);
 #else
-  ssnprintf (buffer, sizeof (buffer), "COLLECTD_INTERVAL=%i", interval_g);
+  ssnprintf (buffer, sizeof (buffer), "COLLECTD_INTERVAL=%.3f",
+      CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
   putenv (buffer);
 
   ssnprintf (buffer, sizeof (buffer), "COLLECTD_HOSTNAME=%s", hostname_g);
   putenv (buffer);
 #endif
-
-#ifdef HAVE_SETENV
-#else
-#endif
 } /* }}} void set_environment */
 
 __attribute__((noreturn))
@@ -306,7 +304,7 @@ static void exec_child (program_list_t *pl) /* {{{ */
   if (status != 0)
   {
     ERROR ("exec plugin: Failed to get user information for user ``%s'': %s",
-       pl->user, sstrerror (errno, errbuf, sizeof (errbuf)));
+        pl->user, sstrerror (errno, errbuf, sizeof (errbuf)));
     exit (-1);
   }
   if (sp_ptr == NULL)
@@ -335,15 +333,15 @@ static void exec_child (program_list_t *pl) /* {{{ */
       status = getgrnam_r (pl->group, &gr, nambuf, sizeof (nambuf), &gr_ptr);
       if (0 != status)
       {
-       ERROR ("exec plugin: Failed to get group information "
-           "for group ``%s'': %s", pl->group,
-           sstrerror (errno, errbuf, sizeof (errbuf)));
-       exit (-1);
+        ERROR ("exec plugin: Failed to get group information "
+            "for group ``%s'': %s", pl->group,
+            sstrerror (errno, errbuf, sizeof (errbuf)));
+        exit (-1);
       }
       if (NULL == gr_ptr)
       {
-       ERROR ("exec plugin: No such group: `%s'", pl->group);
-       exit (-1);
+        ERROR ("exec plugin: No such group: `%s'", pl->group);
+        exit (-1);
       }
 
       egid = gr.gr_gid;
@@ -377,7 +375,7 @@ static void exec_child (program_list_t *pl) /* {{{ */
   if (status != 0)
   {
     ERROR ("exec plugin: setgid (%i) failed: %s",
-       gid, sstrerror (errno, errbuf, sizeof (errbuf)));
+        gid, sstrerror (errno, errbuf, sizeof (errbuf)));
     exit (-1);
   }
 
@@ -387,7 +385,7 @@ static void exec_child (program_list_t *pl) /* {{{ */
     if (status != 0)
     {
       ERROR ("exec plugin: setegid (%i) failed: %s",
-         egid, sstrerror (errno, errbuf, sizeof (errbuf)));
+          egid, sstrerror (errno, errbuf, sizeof (errbuf)));
       exit (-1);
     }
   }
@@ -396,7 +394,7 @@ static void exec_child (program_list_t *pl) /* {{{ */
   if (status != 0)
   {
     ERROR ("exec plugin: setuid (%i) failed: %s",
-       uid, sstrerror (errno, errbuf, sizeof (errbuf)));
+        uid, sstrerror (errno, errbuf, sizeof (errbuf)));
     exit (-1);
   }
 
@@ -438,7 +436,7 @@ static int fork_child (program_list_t *pl, int *fd_in, int *fd_out, int *fd_err)
   if (status != 0)
   {
     ERROR ("exec plugin: pipe failed: %s",
-       sstrerror (errno, errbuf, sizeof (errbuf)));
+        sstrerror (errno, errbuf, sizeof (errbuf)));
     return (-1);
   }
 
@@ -446,7 +444,7 @@ static int fork_child (program_list_t *pl, int *fd_in, int *fd_out, int *fd_err)
   if (status != 0)
   {
     ERROR ("exec plugin: pipe failed: %s",
-       sstrerror (errno, errbuf, sizeof (errbuf)));
+        sstrerror (errno, errbuf, sizeof (errbuf)));
     return (-1);
   }
 
@@ -454,7 +452,7 @@ static int fork_child (program_list_t *pl, int *fd_in, int *fd_out, int *fd_err)
   if (status != 0)
   {
     ERROR ("exec plugin: pipe failed: %s",
-       sstrerror (errno, errbuf, sizeof (errbuf)));
+        sstrerror (errno, errbuf, sizeof (errbuf)));
     return (-1);
   }
 
@@ -462,7 +460,7 @@ static int fork_child (program_list_t *pl, int *fd_in, int *fd_out, int *fd_err)
   if (pid < 0)
   {
     ERROR ("exec plugin: fork failed: %s",
-       sstrerror (errno, errbuf, sizeof (errbuf)));
+        sstrerror (errno, errbuf, sizeof (errbuf)));
     return (-1);
   }
   else if (pid == 0)
@@ -475,9 +473,9 @@ static int fork_child (program_list_t *pl, int *fd_in, int *fd_out, int *fd_err)
     for (fd = 0; fd < fd_num; fd++)
     {
       if ((fd == fd_pipe_in[0])
-         || (fd == fd_pipe_out[1])
-         || (fd == fd_pipe_err[1]))
-       continue;
+          || (fd == fd_pipe_out[1])
+          || (fd == fd_pipe_err[1]))
+        continue;
       close (fd);
     }
 
@@ -581,10 +579,18 @@ static void *exec_read_one (void *arg) /* {{{ */
   /* We use a copy of fdset, as select modifies it */
   copy = fdset;
 
-  while (select(highest_fd + 1, &copy, NULL, NULL, NULL ) > 0)
+  while (1)
   {
     int len;
 
+    status = select (highest_fd + 1, &copy, NULL, NULL, NULL);
+    if (status < 0)
+    {
+      if (errno == EINTR)
+        continue;
+      break;
+    }
+
     if (FD_ISSET(fd, &copy))
     {
       char *pnl;
@@ -630,19 +636,24 @@ static void *exec_read_one (void *arg) /* {{{ */
 
       if (len < 0)
       {
-        if (errno == EAGAIN || errno == EINTR)  continue;
+        if (errno == EAGAIN || errno == EINTR)
+          continue;
         break;
       }
       else if (len == 0)
       {
-       /* We've reached EOF */
-       NOTICE ("exec plugin: Program `%s' has closed STDERR.",
-           pl->exec);
-       close (fd_err);
-       FD_CLR (fd_err, &fdset);
-       highest_fd = fd;
-       fd_err = -1;
-       continue;
+        /* We've reached EOF */
+        NOTICE ("exec plugin: Program `%s' has closed STDERR.", pl->exec);
+
+        /* Remove file descriptor form select() set. */
+        FD_CLR (fd_err, &fdset);
+        copy = fdset;
+        highest_fd = fd;
+
+        /* Clean up file descriptor */
+        close (fd_err);
+        fd_err = -1;
+        continue;
       }
 
       pbuffer_err[len] = '\0';
@@ -716,7 +727,7 @@ static void *exec_notification_one (void *arg) /* {{{ */
   {
     char errbuf[1024];
     ERROR ("exec plugin: fdopen (%i) failed: %s", fd,
-       sstrerror (errno, errbuf, sizeof (errbuf)));
+        sstrerror (errno, errbuf, sizeof (errbuf)));
     kill (pl->pid, SIGTERM);
     pl->pid = 0;
     close (fd);
@@ -732,8 +743,8 @@ static void *exec_notification_one (void *arg) /* {{{ */
 
   fprintf (fh,
       "Severity: %s\n"
-      "Time: %u\n",
-      severity, (unsigned int) n->time);
+      "Time: %.3f\n",
+      severity, CDTIME_T_TO_DOUBLE (n->time));
 
   /* Print the optional fields */
   if (strlen (n->host) > 0)
@@ -759,7 +770,7 @@ static void *exec_notification_one (void *arg) /* {{{ */
       fprintf (fh, "%s: %e\n", meta->name, meta->nm_value.nm_double);
     else if (meta->type == NM_TYPE_BOOLEAN)
       fprintf (fh, "%s: %s\n", meta->name,
-         meta->nm_value.nm_boolean ? "true" : "false");
+          meta->nm_value.nm_boolean ? "true" : "false");
   }
 
   fprintf (fh, "\n%s\n", n->message);
@@ -816,7 +827,8 @@ static int exec_read (void) /* {{{ */
 
     pthread_attr_init (&attr);
     pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
-    pthread_create (&t, &attr, exec_read_one, (void *) pl);
+    plugin_thread_create (&t, &attr, exec_read_one, (void *) pl);
+    pthread_attr_destroy (&attr);
   } /* for (pl) */
 
   return (0);
@@ -842,7 +854,7 @@ static int exec_notification (const notification_t *n, /* {{{ */
       continue;
 
     pln = (program_list_and_notification_t *) malloc (sizeof
-       (program_list_and_notification_t));
+        (program_list_and_notification_t));
     if (pln == NULL)
     {
       ERROR ("exec plugin: malloc failed.");
@@ -859,7 +871,8 @@ static int exec_notification (const notification_t *n, /* {{{ */
 
     pthread_attr_init (&attr);
     pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
-    pthread_create (&t, &attr, exec_notification_one, (void *) pln);
+    plugin_thread_create (&t, &attr, exec_notification_one, (void *) pln);
+    pthread_attr_destroy (&attr);
   } /* for (pl) */
 
   return (0);
index 4b164dc..ed2df61 100644 (file)
@@ -22,6 +22,7 @@
 #include "collectd.h"
 #include "configfile.h"
 #include "plugin.h"
+#include "utils_complain.h"
 #include "common.h"
 #include "filter_chain.h"
 
@@ -692,10 +693,15 @@ static int fc_bit_write_invoke (const data_set_t *ds, /* {{{ */
 
   if ((plugin_list == NULL) || (plugin_list[0] == NULL))
   {
+    static c_complain_t enoent_complaint = C_COMPLAIN_INIT_STATIC;
+
     status = plugin_write (/* plugin = */ NULL, ds, vl);
     if (status == ENOENT)
     {
-      INFO ("Filter subsystem: Built-in target `write': Dispatching value to "
+      /* in most cases this is a permanent error, so use the complain
+       * mechanism rather than spamming the logs */
+      c_complain (LOG_INFO, &enoent_complaint,
+          "Filter subsystem: Built-in target `write': Dispatching value to "
           "all write plugins failed with status %i (ENOENT). "
           "Most likely this means you didn't load any write plugins.",
           status);
@@ -705,6 +711,13 @@ static int fc_bit_write_invoke (const data_set_t *ds, /* {{{ */
       INFO ("Filter subsystem: Built-in target `write': Dispatching value to "
           "all write plugins failed with status %i.", status);
     }
+    else
+    {
+      assert (status == 0);
+      c_release (LOG_INFO, &enoent_complaint, "Filter subsystem: "
+          "Built-in target `write': Some write plugin is back to normal "
+          "operation. `write' succeeded.");
+    }
   }
   else
   {
index dc0eb11..8fbd271 100644 (file)
@@ -107,16 +107,13 @@ Ops pend=N  Number of times async ops added to pending queues
 63 events to collect in 13 groups
 */
 static void fscache_submit (const char *section, const char *name,
-        counter_t counter_value)
+        value_t value)
 {
-    value_t values[1];
     value_list_t vl = VALUE_LIST_INIT;
 
-    vl.values = values;
+    vl.values = &value;
     vl.values_len = 1;
 
-    vl.values[0].counter = counter_value;
-
     sstrncpy(vl.host, hostname_g, sizeof (vl.host));
     sstrncpy(vl.plugin, "fscache", sizeof (vl.plugin));
     sstrncpy(vl.plugin_instance, section, sizeof (vl.plugin_instance));
@@ -189,8 +186,8 @@ static void fscache_read_stats_file (FILE *fh)
         {
             char *field_name;
             char *field_value_str;
-            char *endptr;
-            counter_t field_value_cnt;
+            value_t field_value_cnt;
+            int status;
 
             field_name = fields[i];
             assert (field_name != NULL);
@@ -201,11 +198,9 @@ static void fscache_read_stats_file (FILE *fh)
             *field_value_str = 0;
             field_value_str++;
 
-            errno = 0;
-            endptr = NULL;
-            field_value_cnt = (counter_t) strtoull (field_value_str,
-                    &endptr, /* base = */ 10);
-            if ((errno != 0) || (endptr == field_value_str))
+            status = parse_value (field_value_str, &field_value_cnt,
+                    DS_TYPE_DERIVE);
+            if (status != 0)
                 continue;
 
             fscache_submit (section, field_name, field_value_cnt);
index 2ffc42a..28be092 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/gmond.c
- * Copyright (C) 2009  Florian octo Forster
+ * Copyright (C) 2009,2010  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
@@ -545,6 +545,8 @@ static int staging_entry_update (const char *host, const char *name, /* {{{ */
     se->vl.values[ds_index].derive += value.derive;
   else if (ds_type == DS_TYPE_ABSOLUTE)
     se->vl.values[ds_index].absolute = value.absolute;
+  else
+    assert (23 == 42);
 
   se->flags |= (0x01 << ds_index);
 
@@ -593,32 +595,24 @@ static int mc_handle_value_msg (Ganglia_value_msg *msg) /* {{{ */
     case gmetric_string:
     {
       Ganglia_gmetric_string msg_string;
-      char *endptr;
+      int status;
 
       msg_string = msg->Ganglia_value_msg_u.gstr;
 
       host = msg_string.metric_id.host;
       name = msg_string.metric_id.name;
 
-      endptr = NULL;
-      errno = 0;
-      value_counter.counter = (counter_t) strtoull (msg_string.str,
-          &endptr, /* base = */ 0);
-      if ((endptr == msg_string.str) || (errno != 0))
-        value_counter.counter = -1;
-
-      endptr = NULL;
-      errno = 0;
-      value_gauge.gauge = (gauge_t) strtod (msg_string.str, &endptr);
-      if ((endptr == msg_string.str) || (errno != 0))
+      status = parse_value (msg_string.str, &value_derive, DS_TYPE_DERIVE);
+      if (status != 0)
+        value_derive.derive = -1;
+
+      status = parse_value (msg_string.str, &value_gauge, DS_TYPE_GAUGE);
+      if (status != 0)
         value_gauge.gauge = NAN;
 
-      endptr = NULL;
-      errno = 0;
-      value_derive.derive = (derive_t) strtoll (msg_string.str,
-          &endptr, /* base = */ 0);
-      if ((endptr == msg_string.str) || (errno != 0))
-        value_derive.derive = 0;
+      status = parse_value (msg_string.str, &value_counter, DS_TYPE_COUNTER);
+      if (status != 0)
+        value_counter.counter = 0;
 
       break;
     }
@@ -663,11 +657,15 @@ static int mc_handle_value_msg (Ganglia_value_msg *msg) /* {{{ */
   {
     value_t val_copy;
 
-    val_copy = value_counter;
+    if ((map->ds_type == DS_TYPE_COUNTER)
+        || (map->ds_type == DS_TYPE_ABSOLUTE))
+      val_copy = value_counter;
     if (map->ds_type == DS_TYPE_GAUGE)
       val_copy = value_gauge;
     else if (map->ds_type == DS_TYPE_DERIVE)
       val_copy = value_derive;
+    else
+      assert (23 == 42);
 
     return (staging_entry_update (host, name,
           map->type, map->type_instance,
@@ -719,7 +717,7 @@ static int mc_handle_metadata_msg (Ganglia_metadata_msg *msg) /* {{{ */
           map->type, map->type_instance,
           ds->ds_num);
       if (se != NULL)
-        se->vl.interval = (int) msg_meta.metric.tmax;
+        se->vl.interval = TIME_T_TO_CDTIME_T (msg_meta.metric.tmax);
       pthread_mutex_unlock (&staging_lock);
 
       if (se == NULL)
@@ -881,7 +879,7 @@ static int mc_receive_thread_start (void) /* {{{ */
 
   mc_receive_thread_loop = 1;
 
-  status = pthread_create (&mc_receive_thread_id, /* attr = */ NULL,
+  status = plugin_thread_create (&mc_receive_thread_id, /* attr = */ NULL,
       mc_receive_thread, /* args = */ NULL);
   if (status != 0)
   {
index 177afba..ea82039 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/interface.c
- * Copyright (C) 2005-2008  Florian octo Forster
+ * Copyright (C) 2005-2010  Florian octo Forster
  * Copyright (C) 2009       Manuel Sanmartin
  *
  * This program is free software; you can redistribute it and/or modify it
@@ -128,7 +128,7 @@ static int interface_config (const char *key, const char *value)
 static int interface_init (void)
 {
        kstat_t *ksp_chain;
-       unsigned long long val;
+       derive_t val;
 
        numif = 0;
 
@@ -155,8 +155,8 @@ static int interface_init (void)
 #endif /* HAVE_LIBKSTAT */
 
 static void if_submit (const char *dev, const char *type,
-               unsigned long long rx,
-               unsigned long long tx)
+               derive_t rx,
+               derive_t tx)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
@@ -164,8 +164,8 @@ static void if_submit (const char *dev, const char *type,
        if (ignorelist_match (ignorelist, dev) != 0)
                return;
 
-       values[0].counter = rx;
-       values[1].counter = tx;
+       values[0].derive = rx;
+       values[1].derive = tx;
 
        vl.values = values;
        vl.values_len = 2;
@@ -233,7 +233,7 @@ static int interface_read (void)
 #elif KERNEL_LINUX
        FILE *fh;
        char buffer[1024];
-       unsigned long long incoming, outgoing;
+       derive_t incoming, outgoing;
        char *device;
 
        char *dummy;
@@ -285,8 +285,8 @@ static int interface_read (void)
 
 #elif HAVE_LIBKSTAT
        int i;
-       unsigned long long rx;
-       unsigned long long tx;
+       derive_t rx;
+       derive_t tx;
 
        if (kc == NULL)
                return (-1);
@@ -296,16 +296,29 @@ static int interface_read (void)
                if (kstat_read (kc, ksp[i], NULL) == -1)
                        continue;
 
-               rx = get_kstat_value (ksp[i], "rbytes");
-               tx = get_kstat_value (ksp[i], "obytes");
+               /* try to get 64bit counters */
+               rx = get_kstat_value (ksp[i], "rbytes64");
+               tx = get_kstat_value (ksp[i], "obytes64");
+               /* or fallback to 32bit */
+               if (rx == -1LL)
+                       rx = get_kstat_value (ksp[i], "rbytes");
+               if (tx == -1LL)
+                       tx = get_kstat_value (ksp[i], "obytes");
                if ((rx != -1LL) || (tx != -1LL))
                        if_submit (ksp[i]->ks_name, "if_octets", rx, tx);
 
-               rx = get_kstat_value (ksp[i], "ipackets");
-               tx = get_kstat_value (ksp[i], "opackets");
+               /* try to get 64bit counters */
+               rx = get_kstat_value (ksp[i], "ipackets64");
+               tx = get_kstat_value (ksp[i], "opackets64");
+               /* or fallback to 32bit */
+               if (rx == -1LL)
+                       rx = get_kstat_value (ksp[i], "ipackets");
+               if (tx == -1LL)
+                       tx = get_kstat_value (ksp[i], "opackets");
                if ((rx != -1LL) || (tx != -1LL))
                        if_submit (ksp[i]->ks_name, "if_packets", rx, tx);
 
+               /* no 64bit error counters yet */
                rx = get_kstat_value (ksp[i], "ierrors");
                tx = get_kstat_value (ksp[i], "oerrors");
                if ((rx != -1LL) || (tx != -1LL))
index 95b3dbf..fada5bd 100644 (file)
@@ -136,7 +136,7 @@ static void sensor_read_handler (ipmi_sensor_t *sensor,
 
         if (c_ipmi_nofiy_notpresent)
         {
-          notification_t n = { NOTIF_WARNING, time(NULL), "", "", "ipmi",
+          notification_t n = { NOTIF_WARNING, cdtime (), "", "", "ipmi",
             "", "", "", NULL };
 
           sstrncpy (n.host, hostname_g, sizeof (n.host));
@@ -190,7 +190,7 @@ static void sensor_read_handler (ipmi_sensor_t *sensor,
 
     if (c_ipmi_nofiy_notpresent)
     {
-      notification_t n = { NOTIF_OKAY, time(NULL), "", "", "ipmi",
+      notification_t n = { NOTIF_OKAY, cdtime (), "", "", "ipmi",
         "", "", "", NULL };
 
       sstrncpy (n.host, hostname_g, sizeof (n.host));
@@ -363,7 +363,7 @@ static int sensor_list_add (ipmi_sensor_t *sensor)
 
   if (c_ipmi_nofiy_add && (c_ipmi_init_in_progress == 0))
   {
-    notification_t n = { NOTIF_OKAY, time(NULL), "", "", "ipmi",
+    notification_t n = { NOTIF_OKAY, cdtime (), "", "", "ipmi",
                          "", "", "", NULL };
 
     sstrncpy (n.host, hostname_g, sizeof (n.host));
@@ -417,7 +417,7 @@ static int sensor_list_remove (ipmi_sensor_t *sensor)
 
   if (c_ipmi_nofiy_remove && c_ipmi_active)
   {
-    notification_t n = { NOTIF_WARNING, time(NULL), "", "",
+    notification_t n = { NOTIF_WARNING, cdtime (), "", "",
                          "ipmi", "", "", "", NULL };
 
     sstrncpy (n.host, hostname_g, sizeof (n.host));
@@ -664,11 +664,12 @@ static int c_ipmi_init (void)
   int status;
 
   /* Don't send `ADD' notifications during startup (~ 1 minute) */
-  c_ipmi_init_in_progress = 1 + (60 / interval_g);
+  time_t iv = CDTIME_T_TO_TIME_T (plugin_get_interval ());
+  c_ipmi_init_in_progress = 1 + (60 / iv);
 
   c_ipmi_active = 1;
 
-  status = pthread_create (&thread_id, /* attr = */ NULL, thread_main,
+  status = plugin_thread_create (&thread_id, /* attr = */ NULL, thread_main,
       /* user data = */ NULL);
   if (status != 0)
   {
index aa53074..49454f0 100644 (file)
@@ -1,8 +1,8 @@
 /**
  * collectd - src/iptables.c
- * Copyright (C) 2007 Sjoerd van der Berg
- * Copyright (C) 2007 Florian octo Forster
- * Copyright (C) 2009 Marco Chiappero
+ * Copyright (C) 2007       Sjoerd van der Berg
+ * Copyright (C) 2007-2010  Florian octo Forster
+ * Copyright (C) 2009       Marco Chiappero
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -20,7 +20,7 @@
  *
  * Authors:
  *  Sjoerd van der Berg <harekiet at users.sourceforge.net>
- *  Florian Forster <octo at verplant.org>
+ *  Florian Forster <octo at collectd.org>
  *  Marco Chiappero <marco at absence.it>
  **/
 
 
 #include <sys/socket.h>
 
-#if OWN_LIBIPTC
-# include "owniptc/libiptc.h"
-# include "owniptc/libip6tc.h"
-
-# define HAVE_IPTC_HANDLE_T 1
-# define HAVE_IP6TC_HANDLE_T 1
-
-#else /* if !OWN_LIBIPTC */
-# include <libiptc/libiptc.h>
-# include <libiptc/libip6tc.h>
+#include <libiptc/libiptc.h>
+#include <libiptc/libip6tc.h>
 
 /*
  * iptc_handle_t was available before libiptc was officially available as a
  * this is somewhat hacky, I didn't find better way to solve that :-/
  * -tokkee
  */
-# ifndef HAVE_IPTC_HANDLE_T
+#ifndef HAVE_IPTC_HANDLE_T
 typedef struct iptc_handle iptc_handle_t;
-# endif
-# ifndef HAVE_IP6TC_HANDLE_T
+#endif
+#ifndef HAVE_IP6TC_HANDLE_T
 typedef struct ip6tc_handle ip6tc_handle_t;
-# endif
-#endif /* !OWN_LIBIPTC */
+#endif
 
 /*
  * (Module-)Global variables
@@ -297,11 +288,11 @@ static int submit6_match (const struct ip6t_entry_match *match,
     }
 
     sstrncpy (vl.type, "ipt_bytes", sizeof (vl.type));
-    values[0].counter = (counter_t) entry->counters.bcnt;
+    values[0].derive = (derive_t) entry->counters.bcnt;
     plugin_dispatch_values (&vl);
 
     sstrncpy (vl.type, "ipt_packets", sizeof (vl.type));
-    values[0].counter = (counter_t) entry->counters.pcnt;
+    values[0].derive = (derive_t) entry->counters.pcnt;
     plugin_dispatch_values (&vl);
 
     return (0);
@@ -358,11 +349,11 @@ static int submit_match (const struct ipt_entry_match *match,
     }
 
     sstrncpy (vl.type, "ipt_bytes", sizeof (vl.type));
-    values[0].counter = (counter_t) entry->counters.bcnt;
+    values[0].derive = (derive_t) entry->counters.bcnt;
     plugin_dispatch_values (&vl);
 
     sstrncpy (vl.type, "ipt_packets", sizeof (vl.type));
-    values[0].counter = (counter_t) entry->counters.pcnt;
+    values[0].derive = (derive_t) entry->counters.pcnt;
     plugin_dispatch_values (&vl);
 
     return (0);
index 87eee10..fa89489 100644 (file)
@@ -45,7 +45,9 @@
 #endif /* HAVE_NETINET_IN_H */
 
 /* this can probably only be found in the kernel sources */
-#if HAVE_NET_IP_VS_H
+#if HAVE_LINUX_IP_VS_H
+# include <linux/ip_vs.h>
+#elif HAVE_NET_IP_VS_H
 # include <net/ip_vs.h>
 #elif HAVE_IP_VS_H
 # include <ip_vs.h>
@@ -225,18 +227,16 @@ static int get_ti (struct ip_vs_dest_entry *de, char *ti, size_t size)
        return 0;
 } /* get_ti */
 
-static void cipvs_submit_connections (char *pi, char *ti, counter_t value)
+static void cipvs_submit_connections (char *pi, char *ti, derive_t value)
 {
        value_t values[1];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = value;
+       values[0].derive = value;
 
        vl.values     = values;
        vl.values_len = 1;
 
-       vl.interval = interval_g;
-
        sstrncpy (vl.host, hostname_g, sizeof (vl.host));
        sstrncpy (vl.plugin, "ipvs", sizeof (vl.plugin));
        sstrncpy (vl.plugin_instance, pi, sizeof (vl.plugin_instance));
@@ -249,19 +249,17 @@ static void cipvs_submit_connections (char *pi, char *ti, counter_t value)
 } /* cipvs_submit_connections */
 
 static void cipvs_submit_if (char *pi, char *t, char *ti,
-               counter_t rx, counter_t tx)
+               derive_t rx, derive_t tx)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = rx;
-       values[1].counter = tx;
+       values[0].derive = rx;
+       values[1].derive = tx;
 
        vl.values     = values;
        vl.values_len = 2;
 
-       vl.interval = interval_g;
-
        sstrncpy (vl.host, hostname_g, sizeof (vl.host));
        sstrncpy (vl.plugin, "ipvs", sizeof (vl.plugin));
        sstrncpy (vl.plugin_instance, pi, sizeof (vl.plugin_instance));
index 401cc6f..1168b97 100644 (file)
--- a/src/irq.c
+++ b/src/irq.c
@@ -1,6 +1,7 @@
 /**
  * collectd - src/irq.c
  * Copyright (C) 2007  Peter Holik
+ * Copyright (C) 2011  Florian Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
 #include "common.h"
 #include "plugin.h"
 #include "configfile.h"
+#include "utils_ignorelist.h"
 
 #if !KERNEL_LINUX
 # error "No applicable input method."
 #endif
 
-#define BUFSIZE 128
-
 /*
  * (Module-)Global variables
  */
@@ -41,155 +41,142 @@ static const char *config_keys[] =
 };
 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
 
-static unsigned int *irq_list;
-static unsigned int irq_list_num;
+static ignorelist_t *ignorelist = NULL;
 
-/* 
- * irq_list_action:
- * 0 => default is to collect selected irqs
- * 1 => ignore selcted irqs
+/*
+ * Private functions
  */
-static int irq_list_action;
-
 static int irq_config (const char *key, const char *value)
 {
+       if (ignorelist == NULL)
+               ignorelist = ignorelist_create (/* invert = */ 1);
+
        if (strcasecmp (key, "Irq") == 0)
        {
-               unsigned int *temp;
-               unsigned int irq;
-               char *endptr;
-
-               temp = (unsigned int *) realloc (irq_list, (irq_list_num + 1) * sizeof (unsigned int *));
-               if (temp == NULL)
-               {
-                       fprintf (stderr, "irq plugin: Cannot allocate more memory.\n");
-                       ERROR ("irq plugin: Cannot allocate more memory.");
-                       return (1);
-               }
-               irq_list = temp;
-
-               /* Clear errno, because we need it to see if an error occured. */
-               errno = 0;
-
-               irq = strtol(value, &endptr, 10);
-               if ((endptr == value) || (errno != 0))
-               {
-                       fprintf (stderr, "irq plugin: Irq value is not a "
-                                       "number: `%s'\n", value);
-                       ERROR ("irq plugin: Irq value is not a "
-                                       "number: `%s'", value);
-                       return (1);
-               }
-               irq_list[irq_list_num] = irq;
-               irq_list_num++;
+               ignorelist_add (ignorelist, value);
        }
        else if (strcasecmp (key, "IgnoreSelected") == 0)
        {
+               int invert = 1;
                if (IS_TRUE (value))
-                       irq_list_action = 1;
-               else
-                       irq_list_action = 0;
+                       invert = 0;
+               ignorelist_set_invert (ignorelist, invert);
        }
        else
        {
                return (-1);
        }
-       return (0);
-}
-
-/*
- * Check if this interface/instance should be ignored. This is called from
- * both, `submit' and `write' to give client and server the ability to
- * ignore certain stuff..
- */
-static int check_ignore_irq (const unsigned int irq)
-{
-       int i;
-
-       if (irq_list_num < 1)
-               return (0);
-
-       for (i = 0; (unsigned int)i < irq_list_num; i++)
-               if (irq == irq_list[i])
-                       return (irq_list_action);
 
-       return (1 - irq_list_action);
+       return (0);
 }
 
-static void irq_submit (unsigned int irq, counter_t value)
+static void irq_submit (const char *irq_name, derive_t value)
 {
        value_t values[1];
        value_list_t vl = VALUE_LIST_INIT;
-       int status;
 
-       if (check_ignore_irq (irq))
+       if (ignorelist_match (ignorelist, irq_name) != 0)
                return;
 
-       values[0].counter = value;
+       values[0].derive = value;
 
        vl.values = values;
        vl.values_len = 1;
        sstrncpy (vl.host, hostname_g, sizeof (vl.host));
        sstrncpy (vl.plugin, "irq", sizeof (vl.plugin));
        sstrncpy (vl.type, "irq", sizeof (vl.type));
-
-       status = ssnprintf (vl.type_instance, sizeof (vl.type_instance),
-                       "%u", irq);
-       if ((status < 1) || ((unsigned int)status >= sizeof (vl.type_instance)))
-               return;
+       sstrncpy (vl.type_instance, irq_name, sizeof (vl.type_instance));
 
        plugin_dispatch_values (&vl);
 } /* void irq_submit */
 
 static int irq_read (void)
 {
-#undef BUFSIZE
-#define BUFSIZE 256
-
        FILE *fh;
-       char buffer[BUFSIZE];
-       unsigned int irq;
-       unsigned long long irq_value;
-       unsigned long long value;
-       char *endptr;
-       int i;
-
-       char *fields[64];
-       int fields_num;
-
-       if ((fh = fopen ("/proc/interrupts", "r")) == NULL)
+       char buffer[1024];
+       int  cpu_count;
+       char *fields[256];
+
+       /*
+        * Example content:
+        *         CPU0       CPU1       CPU2       CPU3
+        * 0:       2574          1          3          2   IO-APIC-edge      timer
+        * 1:     102553     158669     218062      70587   IO-APIC-edge      i8042
+        * 8:          0          0          0          1   IO-APIC-edge      rtc0
+        */
+       fh = fopen ("/proc/interrupts", "r");
+       if (fh == NULL)
        {
                char errbuf[1024];
-               WARNING ("irq plugin: fopen (/proc/interrupts): %s",
+               ERROR ("irq plugin: fopen (/proc/interrupts): %s",
                                sstrerror (errno, errbuf, sizeof (errbuf)));
                return (-1);
        }
-       while (fgets (buffer, BUFSIZE, fh) != NULL)
+
+       /* Get CPU count from the first line */
+       if(fgets (buffer, sizeof (buffer), fh) != NULL) {
+               cpu_count = strsplit (buffer, fields,
+                               STATIC_ARRAY_SIZE (fields));
+       } else {
+               ERROR ("irq plugin: unable to get CPU count from first line "
+                               "of /proc/interrupts");
+               return (-1);
+       }
+
+       while (fgets (buffer, sizeof (buffer), fh) != NULL)
        {
-               fields_num = strsplit (buffer, fields, 64);
+               char *irq_name;
+               size_t irq_name_len;
+               derive_t irq_value;
+               int i;
+               int fields_num;
+               int irq_values_to_parse;
+
+               fields_num = strsplit (buffer, fields,
+                               STATIC_ARRAY_SIZE (fields));
                if (fields_num < 2)
                        continue;
 
-               errno = 0;    /* To distinguish success/failure after call */
-               irq = strtol (fields[0], &endptr, 10);
+               /* Parse this many numeric fields, skip the rest
+                * (+1 because first there is a name of irq in each line) */
+               if (fields_num >= cpu_count + 1)
+                       irq_values_to_parse = cpu_count;
+               else
+                       irq_values_to_parse = fields_num - 1;
+
+               /* First field is irq name and colon */
+               irq_name = fields[0];
+               irq_name_len = strlen (irq_name);
+               if (irq_name_len < 2)
+                       continue;
 
-               if ((endptr == fields[0]) || (errno != 0) || (*endptr != ':'))
+               /* Check if irq name ends with colon.
+                * Otherwise it's a header. */
+               if (irq_name[irq_name_len - 1] != ':')
                        continue;
 
+               irq_name[irq_name_len - 1] = 0;
+               irq_name_len--;
+
                irq_value = 0;
-               for (i = 1; i < fields_num; i++)
+               for (i = 1; i <= irq_values_to_parse; i++)
                {
-                       errno = 0;
-                       value = strtoull (fields[i], &endptr, 10);
+                       /* Per-CPU value */
+                       value_t v;
+                       int status;
 
-                       if ((*endptr != '\0') || (errno != 0))
+                       status = parse_value (fields[i], &v, DS_TYPE_DERIVE);
+                       if (status != 0)
                                break;
 
-                       irq_value += value;
+                       irq_value += v.derive;
                } /* for (i) */
 
-               /* Force 32bit wrap-around */
-               irq_submit (irq, irq_value % 4294967296ULL);
+               /* No valid fields -> do not submit anything. */
+               if (i <= 1)
+                       continue;
+
+               irq_submit (irq_name, irq_value);
        }
 
        fclose (fh);
@@ -203,5 +190,3 @@ void module_register (void)
                        config_keys, config_keys_num);
        plugin_register_read ("irq", irq_read);
 } /* void module_register */
-
-#undef BUFSIZE
index 528ec9c..b69ca94 100644 (file)
@@ -109,7 +109,7 @@ static int cjni_callback_register (JNIEnv *jvm_env, jobject o_name,
 static int cjni_read (user_data_t *user_data);
 static int cjni_write (const data_set_t *ds, const value_list_t *vl,
     user_data_t *ud);
-static int cjni_flush (int timeout, const char *identifier, user_data_t *ud);
+static int cjni_flush (cdtime_t timeout, const char *identifier, user_data_t *ud);
 static void cjni_log (int severity, const char *message, user_data_t *ud);
 static int cjni_notification (const notification_t *n, user_data_t *ud);
 
@@ -809,7 +809,7 @@ static jobject ctoj_value_list (JNIEnv *jvm_env, /* {{{ */
 #undef SET_STRING
 
   /* Set the `time' member. Java stores time in milliseconds. */
-  status = ctoj_long (jvm_env, ((jlong) vl->time) * ((jlong) 1000),
+  status = ctoj_long (jvm_env, (jlong) CDTIME_T_TO_MS (vl->time),
       c_valuelist, o_valuelist, "setTime");
   if (status != 0)
   {
@@ -819,7 +819,8 @@ static jobject ctoj_value_list (JNIEnv *jvm_env, /* {{{ */
   }
 
   /* Set the `interval' member.. */
-  status = ctoj_long (jvm_env, (jlong) vl->interval,
+  status = ctoj_long (jvm_env,
+      (jlong) CDTIME_T_TO_MS (vl->interval),
       c_valuelist, o_valuelist, "setInterval");
   if (status != 0)
   {
@@ -914,7 +915,7 @@ static jobject ctoj_notification (JNIEnv *jvm_env, /* {{{ */
     return (NULL);
   }
 
-  /* Set the `interval' member.. */
+  /* Set the `severity' member.. */
   status = ctoj_int (jvm_env, (jint) n->severity,
       c_notification, o_notification, "setSeverity");
   if (status != 0)
@@ -1242,7 +1243,7 @@ static int jtoc_value_list (JNIEnv *jvm_env, value_list_t *vl, /* {{{ */
     return (-1);
   }
   /* Java measures time in milliseconds. */
-  vl->time = (time_t) (tmp_long / ((jlong) 1000));
+  vl->time = MS_TO_CDTIME_T (tmp_long);
 
   status = jtoc_long (jvm_env, &tmp_long,
       class_ptr, object_ptr, "getInterval");
@@ -1251,7 +1252,7 @@ static int jtoc_value_list (JNIEnv *jvm_env, value_list_t *vl, /* {{{ */
     ERROR ("java plugin: jtoc_value_list: jtoc_long (getInterval) failed.");
     return (-1);
   }
-  vl->interval = (int) tmp_long;
+  vl->interval = MS_TO_CDTIME_T (tmp_long);
 
   status = jtoc_values_array (jvm_env, ds, vl, class_ptr, object_ptr);
   if (status != 0)
@@ -1729,7 +1730,7 @@ static cjni_callback_info_t *cjni_callback_info_create (JNIEnv *jvm_env, /* {{{
 
     case CB_TYPE_FLUSH:
       method_name = "flush";
-      method_signature = "(ILjava/lang/String;)I";
+      method_signature = "(Ljava/lang/Number;Ljava/lang/String;)I";
       break;
 
     case CB_TYPE_SHUTDOWN:
@@ -1931,7 +1932,9 @@ static int cjni_init_native (JNIEnv *jvm_env) /* {{{ */
   api_class_ptr = (*jvm_env)->FindClass (jvm_env, "org/collectd/api/Collectd");
   if (api_class_ptr == NULL)
   {
-    ERROR ("cjni_init_native: Cannot find API class `org/collectd/api/Collectd'.");
+    ERROR ("cjni_init_native: Cannot find the API class \"org.collectd.api"
+        ".Collectd\". Please set the correct class path "
+        "using 'JVMArg \"-Djava.class.path=...\"'.");
     return (-1);
   }
 
@@ -2253,7 +2256,6 @@ static int cjni_config_plugin_block (oconfig_item_t *ci) /* {{{ */
   cjni_callback_info_t *cbi;
   jobject o_ocitem;
   const char *name;
-  int status;
   size_t i;
 
   jclass class;
@@ -2308,7 +2310,7 @@ static int cjni_config_plugin_block (oconfig_item_t *ci) /* {{{ */
   method = (*jvm_env)->GetMethodID (jvm_env, class,
       "config", "(Lorg/collectd/api/OConfigItem;)I");
 
-  status = (*jvm_env)->CallIntMethod (jvm_env,
+  (*jvm_env)->CallIntMethod (jvm_env,
       cbi->object, method, o_ocitem);
 
   (*jvm_env)->DeleteLocalRef (jvm_env, o_ocitem);
@@ -2551,11 +2553,12 @@ static int cjni_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
 } /* }}} int cjni_write */
 
 /* Call the CB_TYPE_FLUSH callback pointed to by the `user_data_t' pointer. */
-static int cjni_flush (int timeout, const char *identifier, /* {{{ */
+static int cjni_flush (cdtime_t timeout, const char *identifier, /* {{{ */
     user_data_t *ud)
 {
   JNIEnv *jvm_env;
   cjni_callback_info_t *cbi;
+  jobject o_timeout;
   jobject o_identifier;
   int status;
   int ret_status;
@@ -2578,21 +2581,32 @@ static int cjni_flush (int timeout, const char *identifier, /* {{{ */
 
   cbi = (cjni_callback_info_t *) ud->data;
 
+  o_timeout = ctoj_jdouble_to_number (jvm_env,
+      (jdouble) CDTIME_T_TO_DOUBLE (timeout));
+  if (o_timeout == NULL)
+  {
+    ERROR ("java plugin: cjni_flush: Converting double "
+        "to Number object failed.");
+    return (-1);
+  }
+
   o_identifier = NULL;
   if (identifier != NULL)
   {
     o_identifier = (*jvm_env)->NewStringUTF (jvm_env, identifier);
     if (o_identifier == NULL)
     {
+      (*jvm_env)->DeleteLocalRef (jvm_env, o_timeout);
       ERROR ("java plugin: cjni_flush: NewStringUTF failed.");
       return (-1);
     }
   }
 
   ret_status = (*jvm_env)->CallIntMethod (jvm_env,
-      cbi->object, cbi->method, (jint) timeout, o_identifier);
+      cbi->object, cbi->method, o_timeout, o_identifier);
 
   (*jvm_env)->DeleteLocalRef (jvm_env, o_identifier);
+  (*jvm_env)->DeleteLocalRef (jvm_env, o_timeout);
 
   status = cjni_thread_detach ();
   if (status != 0)
@@ -3065,9 +3079,8 @@ static int cjni_init (void) /* {{{ */
 
   if (config_block != NULL)
   {
-    int status;
 
-    status = cjni_config_perform (config_block);
+    cjni_config_perform (config_block);
     oconfig_free (config_block);
     config_block = NULL;
   }
index abe3ed8..3987590 100644 (file)
@@ -164,27 +164,14 @@ static int lcc_set_errno (lcc_connection_t *c, int err) /* {{{ */
   return (0);
 } /* }}} int lcc_set_errno */
 
-/* lcc_strdup: Since `strdup' is an XSI extension, we provide our own version
- * here. */
-__attribute__((malloc, nonnull (1)))
-static char *lcc_strdup (const char *str) /* {{{ */
-{
-  size_t strsize;
-  char *ret;
-
-  strsize = strlen (str) + 1;
-  ret = (char *) malloc (strsize);
-  if (ret != NULL)
-    memcpy (ret, str, strsize);
-  return (ret);
-} /* }}} char *lcc_strdup */
-
-__attribute__((nonnull (1, 2)))
 static char *lcc_strescape (char *dest, const char *src, size_t dest_size) /* {{{ */
 {
   size_t dest_pos;
   size_t src_pos;
 
+  if ((dest == NULL) || (src == NULL))
+    return (NULL);
+
   dest_pos = 0;
   src_pos = 0;
 
@@ -338,7 +325,7 @@ static int lcc_receive (lcc_connection_t *c, /* {{{ */
     lcc_chomp (buffer);
     LCC_DEBUG ("receive: <-- %s\n", buffer);
 
-    res.lines[i] = lcc_strdup (buffer);
+    res.lines[i] = strdup (buffer);
     if (res.lines[i] == NULL)
     {
       lcc_set_errno (c, ENOMEM);
@@ -733,7 +720,7 @@ int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
 
     if (values_names != NULL)
     {
-      values_names[i] = lcc_strdup (key);
+      values_names[i] = strdup (key);
       if (values_names[i] == NULL)
         BAIL_OUT (ENOMEM);
     }
@@ -746,6 +733,8 @@ int lcc_getval (lcc_connection_t *c, lcc_identifier_t *ident, /* {{{ */
   if (ret_values_names != NULL)
     *ret_values_names = values_names;
 
+  lcc_response_free (&res);
+
   return (0);
 } /* }}} int lcc_getval */
 
@@ -1013,7 +1002,7 @@ int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */
   char *type;
   char *type_instance;
 
-  string_copy = lcc_strdup (string);
+  string_copy = strdup (string);
   if (string_copy == NULL)
   {
     lcc_set_errno (c, ENOMEM);
@@ -1098,4 +1087,18 @@ int lcc_identifier_compare (const lcc_identifier_t *i0, /* {{{ */
     return (0);
 } /* }}} int lcc_identifier_compare */
 
+int lcc_sort_identifiers (lcc_connection_t *c, /* {{{ */
+    lcc_identifier_t *idents, size_t idents_num)
+{
+  if (idents == NULL)
+  {
+    lcc_set_errno (c, EINVAL);
+    return (-1);
+  }
+
+  qsort (idents, idents_num, sizeof (*idents),
+      (void *) lcc_identifier_compare);
+  return (0);
+} /* }}} int lcc_sort_identifiers */
+
 /* vim: set sw=2 sts=2 et fdm=marker : */
index 1494c8d..b2354ff 100644 (file)
@@ -121,6 +121,8 @@ int lcc_string_to_identifier (lcc_connection_t *c,
  * "i0" and "i1" are identical, zero is returned. */
 int lcc_identifier_compare (const lcc_identifier_t *i0,
     const lcc_identifier_t *i1);
+int lcc_sort_identifiers (lcc_connection_t *c,
+    lcc_identifier_t *idents, size_t idents_num);
 
 LCC_END_DECLS
 
index 5b7aa94..19f58b2 100644 (file)
@@ -148,6 +148,19 @@ block:
         $$.children = $2.statement;
         $$.children_num = $2.statement_num;
        }
+       | block_begin block_end
+       {
+        if (strcmp ($1.key, $2) != 0)
+        {
+               printf ("block_begin = %s; block_end = %s;\n", $1.key, $2);
+               yyerror ("Block not closed..\n");
+               exit (1);
+        }
+        free ($2); $2 = NULL;
+        $$ = $1;
+        $$.children = NULL;
+        $$.children_num = 0;
+       }
        ;
 
 statement:
@@ -191,6 +204,13 @@ entire_file:
         ci_root->children = $1.statement;
         ci_root->children_num = $1.statement_num;
        }
+       | /* epsilon */
+       {
+        ci_root = malloc (sizeof (oconfig_item_t));
+        memset (ci_root, '\0', sizeof (oconfig_item_t));
+        ci_root->children = NULL;
+        ci_root->children_num = 0;
+       }
        ;
 
 %%
index 44f3832..e076891 100644 (file)
@@ -125,17 +125,6 @@ static time_t last_refresh = (time_t) 0;
 
 static int refresh_lists (void);
 
-/* Submit functions. */
-static void cpu_submit (unsigned long long cpu_time,
-                        time_t t,
-                        virDomainPtr dom, const char *type);
-static void vcpu_submit (unsigned long long cpu_time,
-                         time_t t,
-                         virDomainPtr dom, int vcpu_nr, const char *type);
-static void submit_counter2 (const char *type, counter_t v0, counter_t v1,
-             time_t t,
-             virDomainPtr dom, const char *devname);
-
 /* ERROR(...) macro for virterrors. */
 #define VIRT_ERROR(conn,s) do {                 \
         virErrorPtr err;                        \
@@ -143,6 +132,107 @@ static void submit_counter2 (const char *type, counter_t v0, counter_t v1,
         if (err) ERROR ("%s: %s", (s), err->message);                   \
     } while(0)
 
+static void
+init_value_list (value_list_t *vl, virDomainPtr dom)
+{
+    int i, n;
+    const char *name;
+    char uuid[VIR_UUID_STRING_BUFLEN];
+
+    sstrncpy (vl->plugin, "libvirt", sizeof (vl->plugin));
+
+    vl->host[0] = '\0';
+
+    /* Construct the hostname field according to HostnameFormat. */
+    for (i = 0; i < HF_MAX_FIELDS; ++i) {
+        if (hostname_format[i] == hf_none)
+            continue;
+
+        n = DATA_MAX_NAME_LEN - strlen (vl->host) - 2;
+
+        if (i > 0 && n >= 1) {
+            strncat (vl->host, ":", 1);
+            n--;
+        }
+
+        switch (hostname_format[i]) {
+        case hf_none: break;
+        case hf_hostname:
+            strncat (vl->host, hostname_g, n);
+            break;
+        case hf_name:
+            name = virDomainGetName (dom);
+            if (name)
+                strncat (vl->host, name, n);
+            break;
+        case hf_uuid:
+            if (virDomainGetUUIDString (dom, uuid) == 0)
+                strncat (vl->host, uuid, n);
+            break;
+        }
+    }
+
+    vl->host[sizeof (vl->host) - 1] = '\0';
+} /* void init_value_list */
+
+static void
+cpu_submit (unsigned long long cpu_time,
+            virDomainPtr dom, const char *type)
+{
+    value_t values[1];
+    value_list_t vl = VALUE_LIST_INIT;
+
+    init_value_list (&vl, dom);
+
+    values[0].derive = cpu_time;
+
+    vl.values = values;
+    vl.values_len = 1;
+
+    sstrncpy (vl.type, type, sizeof (vl.type));
+
+    plugin_dispatch_values (&vl);
+}
+
+static void
+vcpu_submit (derive_t cpu_time,
+             virDomainPtr dom, int vcpu_nr, const char *type)
+{
+    value_t values[1];
+    value_list_t vl = VALUE_LIST_INIT;
+
+    init_value_list (&vl, dom);
+
+    values[0].derive = cpu_time;
+    vl.values = values;
+    vl.values_len = 1;
+
+    sstrncpy (vl.type, type, sizeof (vl.type));
+    ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%d", vcpu_nr);
+
+    plugin_dispatch_values (&vl);
+}
+
+static void
+submit_derive2 (const char *type, derive_t v0, derive_t v1,
+             virDomainPtr dom, const char *devname)
+{
+    value_t values[2];
+    value_list_t vl = VALUE_LIST_INIT;
+
+    init_value_list (&vl, dom);
+
+    values[0].derive = v0;
+    values[1].derive = v1;
+    vl.values = values;
+    vl.values_len = 2;
+
+    sstrncpy (vl.type, type, sizeof (vl.type));
+    sstrncpy (vl.type_instance, devname, sizeof (vl.type_instance));
+
+    plugin_dispatch_values (&vl);
+} /* void submit_derive2 */
+
 static int
 lv_init (void)
 {
@@ -317,28 +407,38 @@ lv_read (void)
     for (i = 0; i < nr_domains; ++i) {
         virDomainInfo info;
         virVcpuInfoPtr vinfo = NULL;
+        int status;
         int j;
 
-        if (virDomainGetInfo (domains[i], &info) != 0)
+        status = virDomainGetInfo (domains[i], &info);
+        if (status != 0)
+        {
+            ERROR ("libvirt plugin: virDomainGetInfo failed with status %i.",
+                    status);
             continue;
+        }
 
-        cpu_submit (info.cpuTime, t, domains[i], "virt_cpu_total");
+        cpu_submit (info.cpuTime, domains[i], "virt_cpu_total");
 
-        vinfo = malloc (info.nrVirtCpu * sizeof vinfo[0]);
+        vinfo = malloc (info.nrVirtCpu * sizeof (vinfo[0]));
         if (vinfo == NULL) {
             ERROR ("libvirt plugin: malloc failed.");
             continue;
         }
 
-        if (virDomainGetVcpus (domains[i], vinfo, info.nrVirtCpu,
-                    NULL, 0) != 0) {
-            sfree (vinfo);
+        status = virDomainGetVcpus (domains[i], vinfo, info.nrVirtCpu,
+                /* cpu map = */ NULL, /* cpu map length = */ 0);
+        if (status < 0)
+        {
+            ERROR ("libvirt plugin: virDomainGetVcpus failed with status %i.",
+                    status);
+            free (vinfo);
             continue;
         }
 
         for (j = 0; j < info.nrVirtCpu; ++j)
             vcpu_submit (vinfo[j].cpuTime,
-                    t, domains[i], vinfo[j].number, "virt_vcpu");
+                    domains[i], vinfo[j].number, "virt_vcpu");
 
         sfree (vinfo);
     }
@@ -352,14 +452,14 @@ lv_read (void)
             continue;
 
         if ((stats.rd_req != -1) && (stats.wr_req != -1))
-            submit_counter2 ("disk_ops",
-                    (counter_t) stats.rd_req, (counter_t) stats.wr_req,
-                    t, block_devices[i].dom, block_devices[i].path);
+            submit_derive2 ("disk_ops",
+                    (derive_t) stats.rd_req, (derive_t) stats.wr_req,
+                    block_devices[i].dom, block_devices[i].path);
 
         if ((stats.rd_bytes != -1) && (stats.wr_bytes != -1))
-            submit_counter2 ("disk_octets",
-                    (counter_t) stats.rd_bytes, (counter_t) stats.wr_bytes,
-                    t, block_devices[i].dom, block_devices[i].path);
+            submit_derive2 ("disk_octets",
+                    (derive_t) stats.rd_bytes, (derive_t) stats.wr_bytes,
+                    block_devices[i].dom, block_devices[i].path);
     } /* for (nr_block_devices) */
 
     /* Get interface stats for each domain. */
@@ -376,24 +476,24 @@ lv_read (void)
             continue;
 
        if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
-           submit_counter2 ("if_octets",
-                   (counter_t) stats.rx_bytes, (counter_t) stats.tx_bytes,
-                   t, interface_devices[i].dom, display_name);
+           submit_derive2 ("if_octets",
+                   (derive_t) stats.rx_bytes, (derive_t) stats.tx_bytes,
+                   interface_devices[i].dom, display_name);
 
        if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
-           submit_counter2 ("if_packets",
-                   (counter_t) stats.rx_packets, (counter_t) stats.tx_packets,
-                   t, interface_devices[i].dom, display_name);
+           submit_derive2 ("if_packets",
+                   (derive_t) stats.rx_packets, (derive_t) stats.tx_packets,
+                   interface_devices[i].dom, display_name);
 
        if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
-           submit_counter2 ("if_errors",
-                   (counter_t) stats.rx_errs, (counter_t) stats.tx_errs,
-                   t, interface_devices[i].dom, display_name);
+           submit_derive2 ("if_errors",
+                   (derive_t) stats.rx_errs, (derive_t) stats.tx_errs,
+                   interface_devices[i].dom, display_name);
 
        if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
-           submit_counter2 ("if_dropped",
-                   (counter_t) stats.rx_drop, (counter_t) stats.tx_drop,
-                   t, interface_devices[i].dom, display_name);
+           submit_derive2 ("if_dropped",
+                   (derive_t) stats.rx_drop, (derive_t) stats.tx_drop,
+                   interface_devices[i].dom, display_name);
     } /* for (nr_interface_devices) */
 
     return 0;
@@ -698,117 +798,6 @@ ignore_device_match (ignorelist_t *il, const char *domname, const char *devpath)
     return r;
 }
 
-static void
-init_value_list (value_list_t *vl, time_t t, virDomainPtr dom)
-{
-    int i, n;
-    const char *name;
-    char uuid[VIR_UUID_STRING_BUFLEN];
-    char  *host_ptr;
-    size_t host_len;
-
-    vl->time = t;
-    vl->interval = interval_g;
-
-    sstrncpy (vl->plugin, "libvirt", sizeof (vl->plugin));
-
-    vl->host[0] = '\0';
-    host_ptr = vl->host;
-    host_len = sizeof (vl->host);
-
-    /* Construct the hostname field according to HostnameFormat. */
-    for (i = 0; i < HF_MAX_FIELDS; ++i) {
-        if (hostname_format[i] == hf_none)
-            continue;
-
-        n = DATA_MAX_NAME_LEN - strlen (vl->host) - 2;
-
-        if (i > 0 && n >= 1) {
-            strncat (vl->host, ":", 1);
-            n--;
-        }
-
-        switch (hostname_format[i]) {
-        case hf_none: break;
-        case hf_hostname:
-            strncat (vl->host, hostname_g, n);
-            break;
-        case hf_name:
-            name = virDomainGetName (dom);
-            if (name)
-                strncat (vl->host, name, n);
-            break;
-        case hf_uuid:
-            if (virDomainGetUUIDString (dom, uuid) == 0)
-                strncat (vl->host, uuid, n);
-            break;
-        }
-    }
-
-    vl->host[sizeof (vl->host) - 1] = '\0';
-} /* void init_value_list */
-
-static void
-cpu_submit (unsigned long long cpu_time,
-            time_t t,
-            virDomainPtr dom, const char *type)
-{
-    value_t values[1];
-    value_list_t vl = VALUE_LIST_INIT;
-
-    init_value_list (&vl, t, dom);
-
-    values[0].counter = cpu_time;
-
-    vl.values = values;
-    vl.values_len = 1;
-
-    sstrncpy (vl.type, type, sizeof (vl.type));
-
-    plugin_dispatch_values (&vl);
-}
-
-static void
-vcpu_submit (counter_t cpu_time,
-             time_t t,
-             virDomainPtr dom, int vcpu_nr, const char *type)
-{
-    value_t values[1];
-    value_list_t vl = VALUE_LIST_INIT;
-
-    init_value_list (&vl, t, dom);
-
-    values[0].counter = cpu_time;
-    vl.values = values;
-    vl.values_len = 1;
-
-    sstrncpy (vl.type, type, sizeof (vl.type));
-    ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%d", vcpu_nr);
-
-    plugin_dispatch_values (&vl);
-}
-
-static void
-submit_counter2 (const char *type, counter_t v0, counter_t v1,
-             time_t t,
-             virDomainPtr dom, const char *devname)
-{
-    value_t values[2];
-    value_list_t vl = VALUE_LIST_INIT;
-
-    init_value_list (&vl, t, dom);
-
-    values[0].counter = v0;
-    values[1].counter = v1;
-    vl.values = values;
-    vl.values_len = 2;
-
-    sstrncpy (vl.type, type, sizeof (vl.type));
-    sstrncpy (vl.type_instance, devname, sizeof (vl.type_instance));
-
-    plugin_dispatch_values (&vl);
-} /* void submit_counter2 */
-
 static int
 lv_shutdown (void)
 {
index 6d0f6e0..ded7732 100644 (file)
@@ -53,23 +53,8 @@ static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
 static int logfile_config (const char *key, const char *value)
 {
        if (0 == strcasecmp (key, "LogLevel")) {
-               if ((0 == strcasecmp (value, "emerg"))
-                               || (0 == strcasecmp (value, "alert"))
-                               || (0 == strcasecmp (value, "crit"))
-                               || (0 == strcasecmp (value, "err")))
-                       log_level = LOG_ERR;
-               else if (0 == strcasecmp (value, "warning"))
-                       log_level = LOG_WARNING;
-               else if (0 == strcasecmp (value, "notice"))
-                       log_level = LOG_NOTICE;
-               else if (0 == strcasecmp (value, "info"))
-                       log_level = LOG_INFO;
-#if COLLECT_DEBUG
-               else if (0 == strcasecmp (value, "debug"))
-                       log_level = LOG_DEBUG;
-#endif /* COLLECT_DEBUG */
-               else
-                       return 1;
+               log_level = parse_log_severity(value);
+               if (log_level == -1) return 1; /* to keep previous behaviour */
        }
        else if (0 == strcasecmp (key, "File")) {
                sfree (log_file);
@@ -92,7 +77,8 @@ static int logfile_config (const char *key, const char *value)
        return 0;
 } /* int logfile_config (const char *, const char *) */
 
-static void logfile_print (const char *msg, int severity, time_t timestamp_time)
+static void logfile_print (const char *msg, int severity,
+               cdtime_t timestamp_time)
 {
        FILE *fh;
        int do_close = 0;
@@ -126,7 +112,8 @@ static void logfile_print (const char *msg, int severity, time_t timestamp_time)
 
        if (print_timestamp)
        {
-               localtime_r (&timestamp_time, &timestamp_tm);
+               time_t tt = CDTIME_T_TO_TIME_T (timestamp_time);
+               localtime_r (&tt, &timestamp_tm);
 
                strftime (timestamp_str, sizeof (timestamp_str), "%Y-%m-%d %H:%M:%S",
                                &timestamp_tm);
@@ -179,7 +166,7 @@ static void logfile_log (int severity, const char *msg,
        if (severity > log_level)
                return;
 
-       logfile_print (msg, severity, time (NULL));
+       logfile_print (msg, severity, cdtime ());
 } /* void logfile_log (int, const char *) */
 
 static int logfile_notification (const notification_t *n,
@@ -218,7 +205,7 @@ static int logfile_notification (const notification_t *n,
        buf[sizeof (buf) - 1] = '\0';
 
        logfile_print (buf, LOG_INFO,
-                       (n->time > 0) ? n->time : time (NULL));
+                       (n->time != 0) ? n->time : cdtime ());
 
        return (0);
 } /* int logfile_notification */
index 8b3266d..13301ff 100644 (file)
@@ -561,20 +561,20 @@ static void submit (const char *dev, const char *type, const char *ti1,
        plugin_dispatch_values (&vl);
 }
 
-static void submit_counter (const char *dev, const char *type, const char *ti1,
-                               const char *ti2, counter_t val)
+static void submit_derive (const char *dev, const char *type, const char *ti1,
+                               const char *ti2, derive_t val)
 {
        value_t item;
-       item.counter = val;
+       item.derive = val;
        submit (dev, type, ti1, ti2, &item, 1);
 }
 
-static void submit_counter2 (const char *dev, const char *type, const char *ti1,
-                               const char *ti2, counter_t val1, counter_t val2)
+static void submit_derive2 (const char *dev, const char *type, const char *ti1,
+                               const char *ti2, derive_t val1, derive_t val2)
 {
        value_t items[2];
-       items[0].counter = val1;
-       items[1].counter = val2;
+       items[0].derive = val1;
+       items[1].derive = val2;
        submit (dev, type, ti1, ti2, items, 2);
 }
 
@@ -598,8 +598,8 @@ static void submit_antx (const char *dev, const char *name,
                        continue;
 
                ssnprintf (ti2, sizeof (ti2), "%i", i);
-               submit_counter (dev, "ath_stat", name, ti2,
-                               (counter_t) vals[i]);
+               submit_derive (dev, "ath_stat", name, ti2,
+                               (derive_t) vals[i]);
        }
 }
 
@@ -625,14 +625,14 @@ process_stat_struct (int which, const void *ptr, const char *dev, const char *ma
                uint32_t val = *(uint32_t *)(((char *) ptr) + specs[i].offset) ;
 
                if (item_watched (i) && (val != 0))
-                       submit_counter (dev, type_name, specs[i].name, mac, val);
+                       submit_derive (dev, type_name, specs[i].name, mac, val);
 
                if (item_summed (i))
                        misc += val;
        }
        
        if (misc != 0)
-               submit_counter (dev, type_name, misc_name, mac, misc);
+               submit_derive (dev, type_name, misc_name, mac, misc);
 
 }
 
@@ -734,13 +734,13 @@ process_station (int sk, const char *dev, struct ieee80211req_sta_info *si)
        /* These two stats are handled as a special case as they are
           a pair of 64bit values */
        if (item_watched (STAT_NODE_OCTETS))
-               submit_counter2 (dev, "node_octets", mac, NULL,
+               submit_derive2 (dev, "node_octets", mac, NULL,
                        ns->ns_rx_bytes, ns->ns_tx_bytes);
 
        /* This stat is handled as a special case, because it is stored
           as uin64_t, but we will ignore upper half */
        if (item_watched (STAT_NS_RX_BEACONS))
-               submit_counter (dev, "node_stat", "ns_rx_beacons", mac,
+               submit_derive (dev, "node_stat", "ns_rx_beacons", mac,
                        (ns->ns_rx_beacons & 0xFFFFFFFF));
 
        /* All other node statistics */
index b9afd81..1ab445a 100644 (file)
@@ -73,7 +73,6 @@ static int mec_match (const data_set_t __attribute__((unused)) *ds, /* {{{ */
     const value_list_t *vl,
     notification_meta_t __attribute__((unused)) **meta, void **user_data)
 {
-  mec_match_t *m;
   int num_counters;
   int num_empty;
   int i;
@@ -81,7 +80,6 @@ static int mec_match (const data_set_t __attribute__((unused)) *ds, /* {{{ */
   if ((user_data == NULL) || (*user_data == NULL))
     return (-1);
 
-  m = *user_data;
 
   num_counters = 0;
   num_empty = 0;
index 4ac944a..2e27415 100644 (file)
@@ -34,29 +34,13 @@ struct mt_match_s;
 typedef struct mt_match_s mt_match_t;
 struct mt_match_s
 {
-  time_t future;
-  time_t past;
+  cdtime_t future;
+  cdtime_t past;
 };
 
 /*
  * internal helper functions
  */
-static int mt_config_add_time_t (time_t *ret_value, /* {{{ */
-    oconfig_item_t *ci)
-{
-
-  if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
-  {
-    ERROR ("timediff match: `%s' needs exactly one numeric argument.",
-        ci->key);
-    return (-1);
-  }
-
-  *ret_value = (time_t) ci->values[0].value.number;
-
-  return (0);
-} /* }}} int mt_config_add_time_t */
-
 static int mt_create (const oconfig_item_t *ci, void **user_data) /* {{{ */
 {
   mt_match_t *m;
@@ -80,9 +64,9 @@ static int mt_create (const oconfig_item_t *ci, void **user_data) /* {{{ */
     oconfig_item_t *child = ci->children + i;
 
     if (strcasecmp ("Future", child->key) == 0)
-      status = mt_config_add_time_t (&m->future, child);
+      status = cf_util_get_cdtime (child, &m->future);
     else if (strcasecmp ("Past", child->key) == 0)
-      status = mt_config_add_time_t (&m->past, child);
+      status = cf_util_get_cdtime (child, &m->past);
     else
     {
       ERROR ("timediff match: The `%s' configuration option is not "
@@ -132,13 +116,13 @@ static int mt_match (const data_set_t __attribute__((unused)) *ds, /* {{{ */
     notification_meta_t __attribute__((unused)) **meta, void **user_data)
 {
   mt_match_t *m;
-  time_t now;
+  cdtime_t now;
 
   if ((user_data == NULL) || (*user_data == NULL))
     return (-1);
 
   m = *user_data;
-  now = time (NULL);
+  now = cdtime ();
 
   if (m->future != 0)
   {
diff --git a/src/md.c b/src/md.c
new file mode 100644 (file)
index 0000000..3725f9a
--- /dev/null
+++ b/src/md.c
@@ -0,0 +1,218 @@
+/**
+ * collectd - src/md.c
+ * Copyright (C) 2010,2011  Michael Hanselmann
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; only version 2 of the License is applicable.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Author:
+ *   Michael Hanselmann
+ **/
+
+#include "collectd.h"
+#include "common.h"
+#include "plugin.h"
+#include "utils_ignorelist.h"
+
+#include <sys/ioctl.h>
+
+#include <linux/major.h>
+#include <linux/raid/md_u.h>
+
+#define PROC_DISKSTATS "/proc/diskstats"
+#define DEV_DIR "/dev"
+
+static const char *config_keys[] =
+{
+  "Device",
+  "IgnoreSelected"
+};
+static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
+
+static ignorelist_t *ignorelist = NULL;
+
+static int md_config (const char *key, const char *value)
+{
+  if (ignorelist == NULL)
+    ignorelist = ignorelist_create (/* invert = */ 1);
+  if (ignorelist == NULL)
+    return (1);
+
+  if (strcasecmp (key, "Device") == 0)
+  {
+    ignorelist_add (ignorelist, value);
+  }
+  else if (strcasecmp (key, "IgnoreSelected") == 0)
+  {
+    ignorelist_set_invert (ignorelist, IS_TRUE (value) ? 0 : 1);
+  }
+  else
+  {
+    return (-1);
+  }
+
+  return (0);
+}
+
+static void md_submit (const int minor, const char *type_instance,
+    gauge_t value)
+{
+  value_t values[1];
+  value_list_t vl = VALUE_LIST_INIT;
+
+  values[0].gauge = value;
+
+  vl.values = values;
+  vl.values_len = 1;
+  sstrncpy (vl.host, hostname_g, sizeof (vl.host));
+  sstrncpy (vl.plugin, "md", sizeof (vl.plugin));
+  ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
+      "%i", minor);
+  sstrncpy (vl.type, "md_disks", sizeof (vl.type));
+  sstrncpy (vl.type_instance, type_instance,
+      sizeof (vl.type_instance));
+
+  plugin_dispatch_values (&vl);
+} /* void md_submit */
+
+static void md_process (const int minor, const char *path)
+{
+  char errbuf[1024];
+  int fd;
+  struct stat st;
+  mdu_array_info_t array;
+  gauge_t disks_missing;
+
+  fd = open (path, O_RDONLY);
+  if (fd < 0)
+  {
+    WARNING ("md: open(%s): %s", path,
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return;
+  }
+
+  if (fstat (fd, &st) < 0)
+  {
+    WARNING ("md: Unable to fstat file descriptor for %s: %s", path,
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    close (fd);
+    return;
+  }
+
+  if (! S_ISBLK (st.st_mode))
+  {
+    WARNING ("md: %s is no block device", path);
+    close (fd);
+    return;
+  }
+
+  if (st.st_rdev != makedev (MD_MAJOR, minor))
+  {
+    WARNING ("md: Major/minor of %s are %i:%i, should be %i:%i",
+        path, (int)major(st.st_rdev), (int)minor(st.st_rdev),
+        (int)MD_MAJOR, minor);
+    close (fd);
+    return;
+  }
+
+  /* Retrieve md information */
+  if (ioctl (fd, GET_ARRAY_INFO, &array) < 0) {
+    WARNING ("md: Unable to retrieve array info from %s: %s", path,
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    close (fd);
+    return;
+  }
+
+  close (fd);
+
+  /*
+   * The mdu_array_info_t structure contains numbers of disks in the array.
+   * However, disks are accounted for more than once:
+   *
+   * active:  Number of active (in sync) disks.
+   * spare:   Number of stand-by disks.
+   * working: Number of working disks. (active + sync)
+   * failed:  Number of failed disks.
+   * nr:      Number of physically present disks. (working + failed)
+   * raid:    Number of disks in the RAID. This may be larger than "nr" if
+   *          disks are missing and smaller than "nr" when spare disks are
+   *          around.
+   */
+  md_submit (minor, "active",  (gauge_t) array.active_disks);
+  md_submit (minor, "failed",  (gauge_t) array.failed_disks);
+  md_submit (minor, "spare",   (gauge_t) array.spare_disks);
+
+  disks_missing = 0.0;
+  if (array.raid_disks > array.nr_disks)
+    disks_missing = (gauge_t) (array.raid_disks - array.nr_disks);
+  md_submit (minor, "missing", disks_missing);
+} /* void md_process */
+
+static int md_read (void)
+{
+  FILE *fh;
+  char buffer[1024];
+
+  fh = fopen (PROC_DISKSTATS, "r");
+  if (fh == NULL) {
+    char errbuf[1024];
+    WARNING ("md: Unable to open %s: %s",
+        PROC_DISKSTATS ,
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return (-1);
+  }
+
+  /* Iterate md devices */
+  while (fgets (buffer, sizeof (buffer), fh) != NULL)
+  {
+    char path[PATH_MAX];
+    char *fields[4];
+    char *name;
+    int major, minor;
+
+    /* Extract interesting fields */
+    if (strsplit (buffer, fields, STATIC_ARRAY_SIZE(fields)) < 3)
+      continue;
+
+    major = atoi (fields[0]);
+
+    if (major != MD_MAJOR)
+      continue;
+
+    minor = atoi (fields[1]);
+    name = fields[2];
+
+    if (ignorelist_match (ignorelist, name))
+      continue;
+
+    /* FIXME: Don't hardcode path. Walk /dev collecting major,
+     * minor and name, then use lookup table to find device.
+     * Alternatively create a temporary device file with correct
+     * major/minor, but that again can be tricky if the filesystem
+     * with the device file is mounted using the "nodev" option.
+     */
+    ssnprintf (path, sizeof (path), "%s/%s", DEV_DIR, name);
+
+    md_process (minor, path);
+  }
+
+  fclose (fh);
+
+  return (0);
+} /* int md_read */
+
+void module_register (void)
+{
+  plugin_register_config ("md", md_config, config_keys, config_keys_num);
+  plugin_register_read ("md", md_read);
+} /* void module_register */
index 8f51e22..c57a831 100644 (file)
@@ -328,7 +328,7 @@ static int cmc_config_add_page (oconfig_item_t *ci) /* {{{ */
 
     if (strcasecmp ("Server", child->key) == 0)
       status = cmc_config_add_string ("Server", &page->server, child);
-    if (strcasecmp ("Key", child->key) == 0)
+    else if (strcasecmp ("Key", child->key) == 0)
       status = cmc_config_add_string ("Key", &page->key, child);
     else if (strcasecmp ("Match", child->key) == 0)
       /* Be liberal with failing matches => don't set `status'. */
index 8490bf6..a09f45e 100644 (file)
@@ -1,9 +1,10 @@
 /**
  * collectd - src/memcached.c, based on src/hddtemp.c
  * Copyright (C) 2007       Antony Dovgal
- * Copyright (C) 2007-2009  Florian Forster
+ * Copyright (C) 2007-2012  Florian Forster
  * Copyright (C) 2009       Doug MacEachern
  * Copyright (C) 2009       Franck Lombardi
+ * Copyright (C) 2012       Nicolas Szalay
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
  *
  * Authors:
  *   Antony Dovgal <tony at daylessday dot org>
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Doug MacEachern <dougm at hyperic.com>
  *   Franck Lombardi
+ *   Nicolas Szalay
  **/
 
 #include "collectd.h"
 #include "plugin.h"
 #include "configfile.h"
 
-# include <poll.h>
-# include <netdb.h>
-# include <sys/socket.h>
-# include <sys/un.h>
-# include <netinet/in.h>
-# include <netinet/tcp.h>
-
-/* Hack to work around the missing define in AIX */
-#ifndef MSG_DONTWAIT
-# define MSG_DONTWAIT MSG_NONBLOCK
-#endif
+#include <netdb.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
 
 #define MEMCACHED_DEF_HOST "127.0.0.1"
 #define MEMCACHED_DEF_PORT "11211"
 
-#define MEMCACHED_RETRY_COUNT 100
-
-static const char *config_keys[] =
+struct memcached_s
 {
-       "Socket",
-       "Host",
-       "Port"
+  char *name;
+  char *socket;
+  char *host;
+  char *port;
 };
-static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
+typedef struct memcached_s memcached_t;
 
-static char *memcached_socket = NULL;
-static char *memcached_host = NULL;
-static char memcached_port[16];
+static _Bool memcached_have_instances = 0;
 
-static int memcached_query_daemon (char *buffer, int buffer_size) /* {{{ */
+static void memcached_free (memcached_t *st)
 {
-       int fd;
-       ssize_t status;
-       int buffer_fill;
-       int i = 0;
-
-       if (memcached_socket != NULL) {
-               struct sockaddr_un serv_addr;
-
-               memset (&serv_addr, 0, sizeof (serv_addr));
-               serv_addr.sun_family = AF_UNIX;
-               sstrncpy (serv_addr.sun_path, memcached_socket,
-                               sizeof (serv_addr.sun_path));
-
-               /* create our socket descriptor */
-               fd = socket (AF_UNIX, SOCK_STREAM, 0);
-               if (fd < 0) {
-                       char errbuf[1024];
-                       ERROR ("memcached: unix socket: %s", sstrerror (errno, errbuf,
-                                               sizeof (errbuf)));
-                       return -1;
-               }
-
-               /* connect to the memcached daemon */
-               status = (ssize_t) connect (fd, (struct sockaddr *) &serv_addr,
-                               sizeof (serv_addr));
-               if (status != 0) {
-                       shutdown (fd, SHUT_RDWR);
-                       close (fd);
-                       fd = -1;
-               }
-       }
-       else { /* if (memcached_socket == NULL) */
-               const char *host;
-               const char *port;
-
-               struct addrinfo  ai_hints;
-               struct addrinfo *ai_list, *ai_ptr;
-               int              ai_return = 0;
-
-               memset (&ai_hints, '\0', sizeof (ai_hints));
-               ai_hints.ai_flags    = 0;
+  if (st == NULL)
+    return;
+
+  sfree (st->name);
+  sfree (st->socket);
+  sfree (st->host);
+  sfree (st->port);
+}
+
+static int memcached_connect_unix (memcached_t *st)
+{
+  struct sockaddr_un serv_addr;
+  int fd;
+
+  memset (&serv_addr, 0, sizeof (serv_addr));
+  serv_addr.sun_family = AF_UNIX;
+  sstrncpy (serv_addr.sun_path, st->socket,
+      sizeof (serv_addr.sun_path));
+
+  /* create our socket descriptor */
+  fd = socket (AF_UNIX, SOCK_STREAM, 0);
+  if (fd < 0)
+  {
+    char errbuf[1024];
+    ERROR ("memcached plugin: memcached_connect_unix: socket(2) failed: %s",
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return (-1);
+  }
+
+  return (fd);
+} /* int memcached_connect_unix */
+
+static int memcached_connect_inet (memcached_t *st)
+{
+  char *host;
+  char *port;
+
+  struct addrinfo  ai_hints;
+  struct addrinfo *ai_list, *ai_ptr;
+  int status;
+  int fd = -1;
+
+  memset (&ai_hints, 0, sizeof (ai_hints));
+  ai_hints.ai_flags    = 0;
 #ifdef AI_ADDRCONFIG
-               /*      ai_hints.ai_flags   |= AI_ADDRCONFIG; */
+  ai_hints.ai_flags   |= AI_ADDRCONFIG;
 #endif
-               ai_hints.ai_family   = AF_INET;
-               ai_hints.ai_socktype = SOCK_STREAM;
-               ai_hints.ai_protocol = 0;
-
-               host = memcached_host;
-               if (host == NULL) {
-                       host = MEMCACHED_DEF_HOST;
-               }
-
-               port = memcached_port;
-               if (strlen (port) == 0) {
-                       port = MEMCACHED_DEF_PORT;
-               }
-
-               if ((ai_return = getaddrinfo (host, port, &ai_hints, &ai_list)) != 0) {
-                       char errbuf[1024];
-                       ERROR ("memcached: getaddrinfo (%s, %s): %s",
-                                       host, port,
-                                       (ai_return == EAI_SYSTEM)
-                                       ? sstrerror (errno, errbuf, sizeof (errbuf))
-                                       : gai_strerror (ai_return));
-                       return -1;
-               }
-
-               fd = -1;
-               for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
-                       /* create our socket descriptor */
-                       fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
-                       if (fd < 0) {
-                               char errbuf[1024];
-                               ERROR ("memcached: socket: %s", sstrerror (errno, errbuf, sizeof (errbuf)));
-                               continue;
-                       }
-
-                       /* connect to the memcached daemon */
-                       status = (ssize_t) connect (fd, (struct sockaddr *) ai_ptr->ai_addr, ai_ptr->ai_addrlen);
-                       if (status != 0) {
-                               shutdown (fd, SHUT_RDWR);
-                               close (fd);
-                               fd = -1;
-                               continue;
-                       }
-
-                       /* A socket could be opened and connecting succeeded. We're
-                        * done. */
-                       break;
-               }
-
-               freeaddrinfo (ai_list);
-       }
-
-       if (fd < 0) {
-               ERROR ("memcached: Could not connect to daemon.");
-               return -1;
-       }
-
-       if (send(fd, "stats\r\n", sizeof("stats\r\n") - 1, MSG_DONTWAIT) != (sizeof("stats\r\n") - 1)) {
-               ERROR ("memcached: Could not send command to the memcached daemon.");
-               return -1;
-       }
-
-       {
-               struct pollfd p;
-               int status;
-
-               memset (&p, 0, sizeof (p));
-               p.fd = fd;
-               p.events = POLLIN | POLLERR | POLLHUP;
-               p.revents = 0;
-
-               status = poll (&p, /* nfds = */ 1, /* timeout = */ 1000 * interval_g);
-               if (status <= 0)
-               {
-                       if (status == 0)
-                       {
-                               ERROR ("memcached: poll(2) timed out after %i seconds.", interval_g);
-                       }
-                       else
-                       {
-                               char errbuf[1024];
-                               ERROR ("memcached: poll(2) failed: %s",
-                                               sstrerror (errno, errbuf, sizeof (errbuf)));
-                       }
-                       shutdown (fd, SHUT_RDWR);
-                       close (fd);
-                       return (-1);
-               }
-       }
-
-       /* receive data from the memcached daemon */
-       memset (buffer, '\0', buffer_size);
-
-       buffer_fill = 0;
-       while ((status = recv (fd, buffer + buffer_fill, buffer_size - buffer_fill, MSG_DONTWAIT)) != 0) {
-               if (i > MEMCACHED_RETRY_COUNT) {
-                       ERROR("recv() timed out");
-                       break;
-               }
-               i++;
-
-               if (status == -1) {
-                       char errbuf[1024];
-
-                       if (errno == EAGAIN) {
-                               continue;
-                       }
-
-                       ERROR ("memcached: Error reading from socket: %s",
-                                       sstrerror (errno, errbuf, sizeof (errbuf)));
-                       shutdown(fd, SHUT_RDWR);
-                       close (fd);
-                       return -1;
-               }
-               buffer_fill += status;
-
-               if (buffer_fill > 3 && buffer[buffer_fill-5] == 'E' && buffer[buffer_fill-4] == 'N' && buffer[buffer_fill-3] == 'D') {
-                       /* we got all the data */
-                       break;
-               }
-       }
-
-       if (buffer_fill >= buffer_size) {
-               buffer[buffer_size - 1] = '\0';
-               WARNING ("memcached: Message from memcached has been truncated.");
-       } else if (buffer_fill == 0) {
-               WARNING ("memcached: Peer has unexpectedly shut down the socket. "
-                               "Buffer: `%s'", buffer);
-               shutdown(fd, SHUT_RDWR);
-               close(fd);
-               return -1;
-       }
-
-       shutdown(fd, SHUT_RDWR);
-       close(fd);
-       return 0;
+  ai_hints.ai_family   = AF_UNSPEC;
+  ai_hints.ai_socktype = SOCK_STREAM;
+  ai_hints.ai_protocol = 0;
+
+  host = (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST;
+  port = (st->port != NULL) ? st->port : MEMCACHED_DEF_PORT;
+
+  ai_list = NULL;
+  status = getaddrinfo (host, port, &ai_hints, &ai_list);
+  if (status != 0)
+  {
+    char errbuf[1024];
+    ERROR ("memcached plugin: memcached_connect_inet: "
+        "getaddrinfo(%s,%s) failed: %s",
+        host, port,
+        (status == EAI_SYSTEM)
+        ? sstrerror (errno, errbuf, sizeof (errbuf))
+        : gai_strerror (status));
+    return (-1);
+  }
+
+  for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
+  {
+    /* create our socket descriptor */
+    fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
+    if (fd < 0)
+    {
+      char errbuf[1024];
+      WARNING ("memcached plugin: memcached_connect_inet: "
+          "socket(2) failed: %s",
+          sstrerror (errno, errbuf, sizeof (errbuf)));
+      continue;
+    }
+
+    /* connect to the memcached daemon */
+    status = (int) connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
+    if (status != 0)
+    {
+      shutdown (fd, SHUT_RDWR);
+      close (fd);
+      fd = -1;
+      continue;
+    }
+
+    /* A socket could be opened and connecting succeeded. We're done. */
+    break;
+  }
+
+  freeaddrinfo (ai_list);
+  return (fd);
+} /* int memcached_connect_inet */
+
+static int memcached_connect (memcached_t *st)
+{
+  if (st->socket != NULL)
+    return (memcached_connect_unix (st));
+  else
+    return (memcached_connect_inet (st));
 }
-/* }}} */
 
-static int memcached_config (const char *key, const char *value) /* {{{ */
+static int memcached_query_daemon (char *buffer, size_t buffer_size, memcached_t *st)
 {
-       if (strcasecmp (key, "Socket") == 0) {
-               if (memcached_socket != NULL) {
-                       free (memcached_socket);
-               }
-               memcached_socket = strdup (value);
-       } else if (strcasecmp (key, "Host") == 0) {
-               if (memcached_host != NULL) {
-                       free (memcached_host);
-               }
-               memcached_host = strdup (value);
-       } else if (strcasecmp (key, "Port") == 0) {
-               int port = (int) (atof (value));
-               if ((port > 0) && (port <= 65535)) {
-                       ssnprintf (memcached_port, sizeof (memcached_port), "%i", port);
-               } else {
-                       sstrncpy (memcached_port, value, sizeof (memcached_port));
-               }
-       } else {
-               return -1;
-       }
-
-       return 0;
+  int fd = -1;
+  int status;
+  size_t buffer_fill;
+
+  fd = memcached_connect (st);
+  if (fd < 0) {
+    ERROR ("memcached plugin: Instance \"%s\" could not connect to daemon.",
+        st->name);
+    return -1;
+  }
+
+  status = (int) swrite (fd, "stats\r\n", strlen ("stats\r\n"));
+  if (status != 0)
+  {
+    char errbuf[1024];
+    ERROR ("memcached plugin: write(2) failed: %s",
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    shutdown(fd, SHUT_RDWR);
+    close (fd);
+    return (-1);
+  }
+
+  /* receive data from the memcached daemon */
+  memset (buffer, 0, buffer_size);
+
+  buffer_fill = 0;
+  while ((status = (int) recv (fd, buffer + buffer_fill,
+          buffer_size - buffer_fill, /* flags = */ 0)) != 0)
+  {
+    char const end_token[5] = {'E', 'N', 'D', '\r', '\n'};
+    if (status < 0)
+    {
+      char errbuf[1024];
+
+      if ((errno == EAGAIN) || (errno == EINTR))
+          continue;
+
+      ERROR ("memcached: Error reading from socket: %s",
+          sstrerror (errno, errbuf, sizeof (errbuf)));
+      shutdown(fd, SHUT_RDWR);
+      close (fd);
+      return (-1);
+    }
+
+    buffer_fill += (size_t) status;
+    if (buffer_fill > buffer_size)
+    {
+      buffer_fill = buffer_size;
+      WARNING ("memcached plugin: Message was truncated.");
+      break;
+    }
+
+    /* If buffer ends in end_token, we have all the data. */
+    if (memcmp (buffer + buffer_fill - sizeof (end_token),
+          end_token, sizeof (end_token)) == 0)
+      break;
+  } /* while (recv) */
+
+  status = 0;
+  if (buffer_fill == 0)
+  {
+    WARNING ("memcached plugin: No data returned by memcached.");
+    status = -1;
+  }
+
+  shutdown(fd, SHUT_RDWR);
+  close(fd);
+  return (status);
+} /* int memcached_query_daemon */
+
+static void memcached_init_vl (value_list_t *vl, memcached_t const *st)
+{
+  sstrncpy (vl->plugin, "memcached", sizeof (vl->plugin));
+  if (strcmp (st->name, "__legacy__") == 0) /* legacy mode */
+  {
+    sstrncpy (vl->host, hostname_g, sizeof (vl->host));
+  }
+  else
+  {
+    if (st->socket != NULL)
+      sstrncpy (vl->host, hostname_g, sizeof (vl->host));
+    else
+      sstrncpy (vl->host,
+          (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST,
+          sizeof (vl->host));
+    sstrncpy (vl->plugin_instance, st->name, sizeof (vl->plugin_instance));
+  }
 }
-/* }}} */
 
-static void submit_counter (const char *type, const char *type_inst,
-               counter_t value) /* {{{ */
+static void submit_derive (const char *type, const char *type_inst,
+    derive_t value, memcached_t *st)
 {
-       value_t values[1];
-       value_list_t vl = VALUE_LIST_INIT;
+  value_t values[1];
+  value_list_t vl = VALUE_LIST_INIT;
+  memcached_init_vl (&vl, st);
 
-       values[0].counter = value;
+  values[0].derive = value;
 
-       vl.values = values;
-       vl.values_len = 1;
-       sstrncpy (vl.host, hostname_g, sizeof (vl.host));
-       sstrncpy (vl.plugin, "memcached", sizeof (vl.plugin));
-       sstrncpy (vl.type, type, sizeof (vl.type));
-       if (type_inst != NULL)
-               sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
+  vl.values = values;
+  vl.values_len = 1;
+  sstrncpy (vl.type, type, sizeof (vl.type));
+  if (type_inst != NULL)
+    sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
 
-       plugin_dispatch_values (&vl);
-} /* void memcached_submit_cmd */
-/* }}} */
+  plugin_dispatch_values (&vl);
+}
 
-static void submit_counter2 (const char *type, const char *type_inst,
-               counter_t value0, counter_t value1) /* {{{ */
+static void submit_derive2 (const char *type, const char *type_inst,
+    derive_t value0, derive_t value1, memcached_t *st)
 {
-       value_t values[2];
-       value_list_t vl = VALUE_LIST_INIT;
+  value_t values[2];
+  value_list_t vl = VALUE_LIST_INIT;
+  memcached_init_vl (&vl, st);
 
-       values[0].counter = value0;
-       values[1].counter = value1;
+  values[0].derive = value0;
+  values[1].derive = value1;
 
-       vl.values = values;
-       vl.values_len = 2;
-       sstrncpy (vl.host, hostname_g, sizeof (vl.host));
-       sstrncpy (vl.plugin, "memcached", sizeof (vl.plugin));
-       sstrncpy (vl.type, type, sizeof (vl.type));
-       if (type_inst != NULL)
-               sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
+  vl.values = values;
+  vl.values_len = 2;
+  sstrncpy (vl.type, type, sizeof (vl.type));
+  if (type_inst != NULL)
+    sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
 
-       plugin_dispatch_values (&vl);
-} /* void memcached_submit_cmd */
-/* }}} */
+  plugin_dispatch_values (&vl);
+}
 
 static void submit_gauge (const char *type, const char *type_inst,
-               gauge_t value) /* {{{ */
+    gauge_t value, memcached_t *st)
 {
-       value_t values[1];
-       value_list_t vl = VALUE_LIST_INIT;
+  value_t values[1];
+  value_list_t vl = VALUE_LIST_INIT;
+  memcached_init_vl (&vl, st);
 
-       values[0].gauge = value;
+  values[0].gauge = value;
 
-       vl.values = values;
-       vl.values_len = 1;
-       sstrncpy (vl.host, hostname_g, sizeof (vl.host));
-       sstrncpy (vl.plugin, "memcached", sizeof (vl.plugin));
-       sstrncpy (vl.type, type, sizeof (vl.type));
-       if (type_inst != NULL)
-               sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
+  vl.values = values;
+  vl.values_len = 1;
+  sstrncpy (vl.type, type, sizeof (vl.type));
+  if (type_inst != NULL)
+    sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
 
-       plugin_dispatch_values (&vl);
+  plugin_dispatch_values (&vl);
 }
-/* }}} */
 
 static void submit_gauge2 (const char *type, const char *type_inst,
-               gauge_t value0, gauge_t value1) /* {{{ */
+    gauge_t value0, gauge_t value1, memcached_t *st)
 {
-       value_t values[2];
-       value_list_t vl = VALUE_LIST_INIT;
+  value_t values[2];
+  value_list_t vl = VALUE_LIST_INIT;
+  memcached_init_vl (&vl, st);
 
-       values[0].gauge = value0;
-       values[1].gauge = value1;
+  values[0].gauge = value0;
+  values[1].gauge = value1;
 
-       vl.values = values;
-       vl.values_len = 2;
-       sstrncpy (vl.host, hostname_g, sizeof (vl.host));
-       sstrncpy (vl.plugin, "memcached", sizeof (vl.plugin));
-       sstrncpy (vl.type, type, sizeof (vl.type));
-       if (type_inst != NULL)
-               sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
+  vl.values = values;
+  vl.values_len = 2;
+  sstrncpy (vl.type, type, sizeof (vl.type));
+  if (type_inst != NULL)
+    sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
 
-       plugin_dispatch_values (&vl);
+  plugin_dispatch_values (&vl);
 }
-/* }}} */
 
-static int memcached_read (void) /* {{{ */
+static int memcached_read (user_data_t *user_data)
 {
-       char buf[1024];
-       char *fields[3];
-       char *ptr;
-       char *line;
-       char *saveptr;
-       int fields_num;
-
-       gauge_t bytes_used = NAN;
-       gauge_t bytes_total = NAN;
-       gauge_t hits = NAN;
-       gauge_t gets = NAN;
-       counter_t rusage_user = 0;
-       counter_t rusage_syst = 0;
-       counter_t octets_rx = 0;
-       counter_t octets_tx = 0;
-
-       /* get data from daemon */
-       if (memcached_query_daemon (buf, sizeof (buf)) < 0) {
-               return -1;
-       }
+  char buf[4096];
+  char *fields[3];
+  char *ptr;
+  char *line;
+  char *saveptr;
+  int fields_num;
+
+  gauge_t bytes_used = NAN;
+  gauge_t bytes_total = NAN;
+  gauge_t hits = NAN;
+  gauge_t gets = NAN;
+  derive_t rusage_user = 0;
+  derive_t rusage_syst = 0;
+  derive_t octets_rx = 0;
+  derive_t octets_tx = 0;
+
+  memcached_t *st;
+  st = user_data->data;
+
+  /* get data from daemon */
+  if (memcached_query_daemon (buf, sizeof (buf), st) < 0) {
+    return -1;
+  }
 
 #define FIELD_IS(cnst) \
-       (((sizeof(cnst) - 1) == name_len) && (strcmp (cnst, fields[1]) == 0))
-
-       ptr = buf;
-       saveptr = NULL;
-       while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL)
-       {
-               int name_len;
-
-               ptr = NULL;
-
-               fields_num = strsplit(line, fields, 3);
-               if (fields_num != 3)
-                       continue;
-
-               name_len = strlen(fields[1]);
-               if (name_len == 0)
-                       continue;
-
-               /*
-                * For an explanation on these fields please refer to
-                * <http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt>
-                */
-
-               /*
-                * CPU time consumed by the memcached process
-                */
-               if (FIELD_IS ("rusage_user"))
-               {
-                       rusage_user = atoll (fields[2]);
-               }
-               else if (FIELD_IS ("rusage_system"))
-               {
-                       rusage_syst = atoll(fields[2]);
-               }
-
-               /*
-                * Number of threads of this instance
-                */
-               else if (FIELD_IS ("threads"))
-               {
-                       submit_gauge2 ("ps_count", NULL, NAN, atof (fields[2]));
-               }
-
-               /*
-                * Number of items stored
-                */
-               else if (FIELD_IS ("curr_items"))
-               {
-                       submit_gauge ("memcached_items", "current", atof (fields[2]));
-               }
-
-               /*
-                * Number of bytes used and available (total - used)
-                */
-               else if (FIELD_IS ("bytes"))
-               {
-                       bytes_used = atof (fields[2]);
-               }
-               else if (FIELD_IS ("limit_maxbytes"))
-               {
-                       bytes_total = atof(fields[2]);
-               }
-
-               /*
-                * Connections
-                */
-               else if (FIELD_IS ("curr_connections"))
-               {
-                       submit_gauge ("memcached_connections", "current", atof (fields[2]));
-               }
-
-               /*
-                * Commands
-                */
-               else if ((name_len > 4) && (strncmp (fields[1], "cmd_", 4) == 0))
-               {
-                       const char *name = fields[1] + 4;
-                       submit_counter ("memcached_command", name, atoll (fields[2]));
-                       if (strcmp (name, "get") == 0)
-                               gets = atof (fields[2]);
-               }
-
-               /*
-                * Operations on the cache, i. e. cache hits, cache misses and evictions of items
-                */
-               else if (FIELD_IS ("get_hits"))
-               {
-                       submit_counter ("memcached_ops", "hits", atoll (fields[2]));
-                       hits = atof (fields[2]);
-               }
-               else if (FIELD_IS ("get_misses"))
-               {
-                       submit_counter ("memcached_ops", "misses", atoll (fields[2]));
-               }
-               else if (FIELD_IS ("evictions"))
-               {
-                       submit_counter ("memcached_ops", "evictions", atoll (fields[2]));
-               }
-
-               /*
-                * Network traffic
-                */
-               else if (FIELD_IS ("bytes_read"))
-               {
-                       octets_rx = atoll (fields[2]);
-               }
-               else if (FIELD_IS ("bytes_written"))
-               {
-                       octets_tx = atoll (fields[2]);
-               }
-       } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
-
-       if (!isnan (bytes_used) && !isnan (bytes_total) && (bytes_used <= bytes_total))
-               submit_gauge2 ("df", "cache", bytes_used, bytes_total - bytes_used);
-
-       if ((rusage_user != 0) || (rusage_syst != 0))
-               submit_counter2 ("ps_cputime", NULL, rusage_user, rusage_syst);
-
-       if ((octets_rx != 0) || (octets_tx != 0))
-               submit_counter2 ("memcached_octets", NULL, octets_rx, octets_tx);
-
-       if (!isnan (gets) && !isnan (hits))
-       {
-               gauge_t rate = NAN;
-
-               if (gets != 0.0)
-                       rate = 100.0 * hits / gets;
-
-               submit_gauge ("percent", "hitratio", rate);
-       }
-
-       return 0;
+  (((sizeof(cnst) - 1) == name_len) && (strcmp (cnst, fields[1]) == 0))
+
+  ptr = buf;
+  saveptr = NULL;
+  while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL)
+  {
+    int name_len;
+
+    ptr = NULL;
+
+    fields_num = strsplit(line, fields, 3);
+    if (fields_num != 3)
+      continue;
+
+    name_len = strlen(fields[1]);
+    if (name_len == 0)
+      continue;
+
+    /*
+     * For an explanation on these fields please refer to
+     * <http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt>
+     */
+
+    /*
+     * CPU time consumed by the memcached process
+     */
+    if (FIELD_IS ("rusage_user"))
+    {
+      rusage_user = atoll (fields[2]);
+    }
+    else if (FIELD_IS ("rusage_system"))
+    {
+      rusage_syst = atoll(fields[2]);
+    }
+
+    /*
+     * Number of threads of this instance
+     */
+    else if (FIELD_IS ("threads"))
+    {
+      submit_gauge2 ("ps_count", NULL, NAN, atof (fields[2]), st);
+    }
+
+    /*
+     * Number of items stored
+     */
+    else if (FIELD_IS ("curr_items"))
+    {
+      submit_gauge ("memcached_items", "current", atof (fields[2]), st);
+    }
+
+    /*
+     * Number of bytes used and available (total - used)
+     */
+    else if (FIELD_IS ("bytes"))
+    {
+      bytes_used = atof (fields[2]);
+    }
+    else if (FIELD_IS ("limit_maxbytes"))
+    {
+      bytes_total = atof(fields[2]);
+    }
+
+    /*
+     * Connections
+     */
+    else if (FIELD_IS ("curr_connections"))
+    {
+      submit_gauge ("memcached_connections", "current", atof (fields[2]), st);
+    }
+
+    /*
+     * Commands
+     */
+    else if ((name_len > 4) && (strncmp (fields[1], "cmd_", 4) == 0))
+    {
+      const char *name = fields[1] + 4;
+      submit_derive ("memcached_command", name, atoll (fields[2]), st);
+      if (strcmp (name, "get") == 0)
+        gets = atof (fields[2]);
+    }
+
+    /*
+     * Operations on the cache, i. e. cache hits, cache misses and evictions of items
+     */
+    else if (FIELD_IS ("get_hits"))
+    {
+      submit_derive ("memcached_ops", "hits", atoll (fields[2]), st);
+      hits = atof (fields[2]);
+    }
+    else if (FIELD_IS ("get_misses"))
+    {
+      submit_derive ("memcached_ops", "misses", atoll (fields[2]), st);
+    }
+    else if (FIELD_IS ("evictions"))
+    {
+      submit_derive ("memcached_ops", "evictions", atoll (fields[2]), st);
+    }
+
+    /*
+     * Network traffic
+     */
+    else if (FIELD_IS ("bytes_read"))
+    {
+      octets_rx = atoll (fields[2]);
+    }
+    else if (FIELD_IS ("bytes_written"))
+    {
+      octets_tx = atoll (fields[2]);
+    }
+  } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
+
+  if (!isnan (bytes_used) && !isnan (bytes_total) && (bytes_used <= bytes_total))
+    submit_gauge2 ("df", "cache", bytes_used, bytes_total - bytes_used, st);
+
+  if ((rusage_user != 0) || (rusage_syst != 0))
+    submit_derive2 ("ps_cputime", NULL, rusage_user, rusage_syst, st);
+
+  if ((octets_rx != 0) || (octets_tx != 0))
+    submit_derive2 ("memcached_octets", NULL, octets_rx, octets_tx, st);
+
+  if (!isnan (gets) && !isnan (hits))
+  {
+    gauge_t rate = NAN;
+
+    if (gets != 0.0)
+      rate = 100.0 * hits / gets;
+
+    submit_gauge ("percent", "hitratio", rate, st);
+  }
+
+  return 0;
+} /* int memcached_read */
+
+static int memcached_add_read_callback (memcached_t *st)
+{
+  user_data_t ud;
+  char callback_name[3*DATA_MAX_NAME_LEN];
+  int status;
+
+  memset (&ud, 0, sizeof (ud));
+  ud.data = st;
+  ud.free_func = (void *) memcached_free;
+
+  assert (st->name != NULL);
+  ssnprintf (callback_name, sizeof (callback_name), "memcached/%s", st->name);
+
+  status = plugin_register_complex_read (/* group = */ "memcached",
+      /* name      = */ callback_name,
+      /* callback  = */ memcached_read,
+      /* interval  = */ NULL,
+      /* user_data = */ &ud);
+  return (status);
+} /* int memcached_add_read_callback */
+
+/* Configuration handling functiions
+ * <Plugin memcached>
+ *   <Instance "instance_name">
+ *     Host foo.zomg.com
+ *     Port "1234"
+ *   </Instance>
+ * </Plugin>
+ */
+static int config_add_instance(oconfig_item_t *ci)
+{
+  memcached_t *st;
+  int i;
+  int status = 0;
+
+  /* Disable automatic generation of default instance in the init callback. */
+  memcached_have_instances = 1;
+
+  st = malloc (sizeof (*st));
+  if (st == NULL)
+  {
+    ERROR ("memcached plugin: malloc failed.");
+    return (-1);
+  }
+
+  memset (st, 0, sizeof (*st));
+  st->name = NULL;
+  st->socket = NULL;
+  st->host = NULL;
+  st->port = NULL;
+
+  if (strcasecmp (ci->key, "Plugin") == 0) /* default instance */
+    st->name = sstrdup ("__legacy__");
+  else /* <Instance /> block */
+    status = cf_util_get_string (ci, &st->name);
+  if (status != 0)
+  {
+    sfree (st);
+    return (status);
+  }
+  assert (st->name != NULL);
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *child = ci->children + i;
+
+    if (strcasecmp ("Socket", child->key) == 0)
+      status = cf_util_get_string (child, &st->socket);
+    else if (strcasecmp ("Host", child->key) == 0)
+      status = cf_util_get_string (child, &st->host);
+    else if (strcasecmp ("Port", child->key) == 0)
+      status = cf_util_get_service (child, &st->port);
+    else
+    {
+      WARNING ("memcached plugin: Option `%s' not allowed here.",
+          child->key);
+      status = -1;
+    }
+
+    if (status != 0)
+      break;
+  }
+
+  if (status == 0)
+    status = memcached_add_read_callback (st);
+
+  if (status != 0)
+  {
+    memcached_free(st);
+    return (-1);
+  }
+
+  return (0);
 }
-/* }}} */
 
-void module_register (void) /* {{{ */
+static int memcached_config (oconfig_item_t *ci)
 {
-       plugin_register_config ("memcached", memcached_config, config_keys, config_keys_num);
-       plugin_register_read ("memcached", memcached_read);
+  int status = 0;
+  _Bool have_instance_block = 0;
+  int i;
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *child = ci->children + i;
+
+    if (strcasecmp ("Instance", child->key) == 0)
+    {
+      config_add_instance (child);
+      have_instance_block = 1;
+    }
+    else if (!have_instance_block)
+    {
+      /* Non-instance option: Assume legacy configuration (without <Instance />
+       * blocks) and call config_add_instance() with the <Plugin /> block. */
+      return (config_add_instance (ci));
+    }
+    else
+      WARNING ("memcached plugin: The configuration option "
+          "\"%s\" is not allowed here. Did you "
+          "forget to add an <Instance /> block "
+          "around the configuration?",
+          child->key);
+  } /* for (ci->children) */
+
+  return (status);
 }
-/* }}} */
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- * vim600: sw=4 ts=4 fdm=marker noexpandtab
- * vim<600: sw=4 ts=4 noexpandtab
- */
 
+static int memcached_init (void)
+{
+  memcached_t *st;
+  int status;
+
+  if (memcached_have_instances)
+    return (0);
+
+  /* No instances were configured, lets start a default instance. */
+  st = malloc (sizeof (*st));
+  if (st == NULL)
+    return (ENOMEM);
+  memset (st, 0, sizeof (*st));
+  st->name = sstrdup ("__legacy__");
+  st->socket = NULL;
+  st->host = NULL;
+  st->port = NULL;
+
+  status = memcached_add_read_callback (st);
+  if (status == 0)
+    memcached_have_instances = 1;
+  else
+    memcached_free (st);
+
+  return (status);
+} /* int memcached_init */
+
+void module_register (void)
+{
+  plugin_register_complex_config ("memcached", memcached_config);
+  plugin_register_init ("memcached", memcached_init);
+}
index b79a74b..6a50161 100644 (file)
@@ -321,9 +321,17 @@ static int memory_read (void)
 /* #endif KERNEL_LINUX */
 
 #elif HAVE_LIBKSTAT
+        /* Most of the additions here were taken as-is from the k9toolkit from
+         * Brendan Gregg and are subject to change I guess */
        long long mem_used;
        long long mem_free;
        long long mem_lock;
+       long long mem_kern;
+       long long mem_unus;
+
+       long long pp_kernel;
+       long long physmem;
+       long long availrmem;
 
        if (ksp == NULL)
                return (-1);
@@ -331,20 +339,61 @@ static int memory_read (void)
        mem_used = get_kstat_value (ksp, "pagestotal");
        mem_free = get_kstat_value (ksp, "pagesfree");
        mem_lock = get_kstat_value (ksp, "pageslocked");
+       mem_kern = 0;
+       mem_unus = 0;
+
+       pp_kernel = get_kstat_value (ksp, "pp_kernel");
+       physmem = get_kstat_value (ksp, "physmem");
+       availrmem = get_kstat_value (ksp, "availrmem");
 
        if ((mem_used < 0LL) || (mem_free < 0LL) || (mem_lock < 0LL))
+       {
+               WARNING ("memory plugin: one of used, free or locked is negative.");
                return (-1);
+       }
+
+       mem_unus = physmem - mem_used;
+
        if (mem_used < (mem_free + mem_lock))
-               return (-1);
+       {
+               /* source: http://wesunsolve.net/bugid/id/4909199
+                * this seems to happen when swap space is small, e.g. 2G on a 32G system
+                * we will make some assumptions here
+                * educated solaris internals help welcome here */
+               DEBUG ("memory plugin: pages total is smaller than \"free\" "
+                               "+ \"locked\". This is probably due to small "
+                               "swap space");
+               mem_free = availrmem;
+               mem_used = 0;
+       }
+       else
+       {
+               mem_used -= mem_free + mem_lock;
+       }
+
+       /* mem_kern is accounted for in mem_lock */
+       if ( pp_kernel < mem_lock )
+       {
+               mem_kern = pp_kernel;
+               mem_lock -= pp_kernel;
+       }
+       else
+       {
+               mem_kern = mem_lock;
+               mem_lock = 0;
+       }
 
-       mem_used -= mem_free + mem_lock;
        mem_used *= pagesize; /* If this overflows you have some serious */
        mem_free *= pagesize; /* memory.. Why not call me up and give me */
        mem_lock *= pagesize; /* some? ;) */
+       mem_kern *= pagesize; /* it's 2011 RAM is cheap */
+       mem_unus *= pagesize;
 
        memory_submit ("used",   mem_used);
        memory_submit ("free",   mem_free);
        memory_submit ("locked", mem_lock);
+       memory_submit ("kernel", mem_kern);
+       memory_submit ("unusable", mem_unus);
 /* #endif HAVE_LIBKSTAT */
 
 #elif HAVE_SYSCTL
index 6a336c4..ea98ba9 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/meta_data.c
- * Copyright (C) 2008,2009  Florian octo Forster
+ * Copyright (C) 2008-2011  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -101,6 +101,24 @@ static meta_entry_t *md_entry_alloc (const char *key) /* {{{ */
   return (e);
 } /* }}} meta_entry_t *md_entry_alloc */
 
+static meta_entry_t *md_entry_clone (const meta_entry_t *orig) /* {{{ */
+{
+  meta_entry_t *copy;
+
+  if (orig == NULL)
+    return (NULL);
+
+  copy = md_entry_alloc (orig->key);
+  copy->type = orig->type;
+  if (copy->type == MD_TYPE_STRING)
+    copy->value.mv_string = strdup (orig->value.mv_string);
+  else
+    copy->value = orig->value;
+
+  copy->next = md_entry_clone (orig->next);
+  return (copy);
+} /* }}} meta_entry_t *md_entry_clone */
+
 static void md_entry_free (meta_entry_t *e) /* {{{ */
 {
   if (e == NULL)
@@ -209,12 +227,32 @@ meta_data_t *meta_data_create (void) /* {{{ */
   return (md);
 } /* }}} meta_data_t *meta_data_create */
 
+meta_data_t *meta_data_clone (meta_data_t *orig) /* {{{ */
+{
+  meta_data_t *copy;
+
+  if (orig == NULL)
+    return (NULL);
+
+  copy = meta_data_create ();
+  if (copy == NULL)
+    return (NULL);
+
+  pthread_mutex_lock (&orig->lock);
+  copy->head = md_entry_clone (orig->head);
+  pthread_mutex_unlock (&orig->lock);
+
+  return (copy);
+} /* }}} meta_data_t *meta_data_clone */
+
 void meta_data_destroy (meta_data_t *md) /* {{{ */
 {
   if (md == NULL)
     return;
 
+  pthread_mutex_destroy(&md->lock);
   md_entry_free (md->head);
+  pthread_mutex_destroy (&md->lock);
   free (md);
 } /* }}} void meta_data_destroy */
 
index 9ef7b0a..f1af40e 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/meta_data.h
- * Copyright (C) 2008,2009  Florian octo Forster
+ * Copyright (C) 2008-2011  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -37,6 +37,7 @@ struct meta_data_s;
 typedef struct meta_data_s meta_data_t;
 
 meta_data_t *meta_data_create (void);
+meta_data_t *meta_data_clone (meta_data_t *orig);
 void meta_data_destroy (meta_data_t *md);
 
 int meta_data_exists (meta_data_t *md, const char *key);
index adab0d0..8a9fe93 100644 (file)
@@ -1,19 +1,20 @@
 /**
  * collectd - src/modbus.c
- * Copyright (C) 2010  noris network AG
+ * Copyright (C) 2010,2011  noris network AG
  *
  * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; only version 2.1 of the License is
+ * applicable.
  *
  * This program is distributed in the hope that it will be useful, but
  * WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
+ * Lesser General Public License for more details.
  *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  *
  * Authors:
  *   Florian Forster <octo at noris.net>
 
 #include <modbus/modbus.h>
 
+#ifndef LIBMODBUS_VERSION_CHECK
+/* Assume version 2.0.3 */
+# define LEGACY_LIBMODBUS 1
+#else
+/* Assume version 2.9.2 */
+#endif
+
 #ifndef MODBUS_TCP_DEFAULT_PORT
 # ifdef MODBUS_TCP_PORT
 #  define MODBUS_TCP_DEFAULT_PORT MODBUS_TCP_PORT
@@ -61,6 +69,8 @@
  */
 enum mb_register_type_e /* {{{ */
 {
+  REG_TYPE_INT16,
+  REG_TYPE_INT32,
   REG_TYPE_UINT16,
   REG_TYPE_UINT32,
   REG_TYPE_FLOAT
@@ -94,12 +104,16 @@ struct mb_host_s /* {{{ */
   char node[NI_MAXHOST];
   /* char service[NI_MAXSERV]; */
   int port;
-  int interval;
+  cdtime_t interval;
 
   mb_slave_t *slaves;
   size_t slaves_num;
 
+#if LEGACY_LIBMODBUS
   modbus_param_t connection;
+#else
+  modbus_t *connection;
+#endif
   _Bool is_connected;
   _Bool have_reconnected;
 }; /* }}} */
@@ -223,7 +237,7 @@ static int mb_submit (mb_host_t *host, mb_slave_t *slave, /* {{{ */
     return (EINVAL);
 
   if (host->interval <= 0)
-    host->interval = interval_g;
+    host->interval = plugin_get_interval ();
 
   if (slave->instance[0] == 0)
     ssnprintf (slave->instance, sizeof (slave->instance), "slave_%i",
@@ -265,6 +279,8 @@ static float mb_register_to_float (uint16_t hi, uint16_t lo) /* {{{ */
   return (conv.f);
 } /* }}} float mb_register_to_float */
 
+#if LEGACY_LIBMODBUS
+/* Version 2.0.3 */
 static int mb_init_connection (mb_host_t *host) /* {{{ */
 {
   int status;
@@ -281,10 +297,8 @@ static int mb_init_connection (mb_host_t *host) /* {{{ */
 
   modbus_set_debug (&host->connection, 1);
 
-#if 0
   /* We'll do the error handling ourselves. */
   modbus_set_error_handling (&host->connection, NOP_ON_ERROR);
-#endif
 
   if ((host->port < 1) || (host->port > 65535))
     host->port = MODBUS_TCP_DEFAULT_PORT;
@@ -293,10 +307,8 @@ static int mb_init_connection (mb_host_t *host) /* {{{ */
       host->node, host->port);
 
   modbus_init_tcp (&host->connection,
-      /* host = */ host->node);
-#if 0
+      /* host = */ host->node,
       /* port = */ host->port);
-#endif
 
   status = modbus_connect (&host->connection);
   if (status != 0)
@@ -310,6 +322,57 @@ static int mb_init_connection (mb_host_t *host) /* {{{ */
   host->have_reconnected = 1;
   return (0);
 } /* }}} int mb_init_connection */
+/* #endif LEGACY_LIBMODBUS */
+
+#else /* if !LEGACY_LIBMODBUS */
+/* Version 2.9.2 */
+static int mb_init_connection (mb_host_t *host) /* {{{ */
+{
+  int status;
+
+  if (host == NULL)
+    return (EINVAL);
+
+  if (host->connection != NULL)
+    return (0);
+
+  /* Only reconnect once per interval. */
+  if (host->have_reconnected)
+    return (-1);
+
+  if ((host->port < 1) || (host->port > 65535))
+    host->port = MODBUS_TCP_DEFAULT_PORT;
+
+  DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
+      host->node, host->port);
+
+  host->connection = modbus_new_tcp (host->node, host->port);
+  if (host->connection == NULL)
+  {
+    host->have_reconnected = 1;
+    ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
+    return (-1);
+  }
+
+  modbus_set_debug (host->connection, 1);
+
+  /* We'll do the error handling ourselves. */
+  modbus_set_error_recovery (host->connection, 0);
+
+  status = modbus_connect (host->connection);
+  if (status != 0)
+  {
+    ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
+        host->node, host->port, status);
+    modbus_free (host->connection);
+    host->connection = NULL;
+    return (status);
+  }
+
+  host->have_reconnected = 1;
+  return (0);
+} /* }}} int mb_init_connection */
+#endif /* !LEGACY_LIBMODBUS */
 
 #define CAST_TO_VALUE_T(ds,vt,raw) do { \
   if ((ds)->ds[0].type == DS_TYPE_COUNTER) \
@@ -325,7 +388,7 @@ static int mb_init_connection (mb_host_t *host) /* {{{ */
 static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
     mb_data_t *data)
 {
-  int values[2];
+  uint16_t values[2];
   int values_num;
   const data_set_t *ds;
   int status;
@@ -350,6 +413,7 @@ static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
   }
 
   if ((ds->ds[0].type != DS_TYPE_GAUGE)
+      && (data->register_type != REG_TYPE_INT32)
       && (data->register_type != REG_TYPE_UINT32))
   {
     NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. "
@@ -358,28 +422,53 @@ static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
   }
 
   memset (values, 0, sizeof (values));
-  if ((data->register_type == REG_TYPE_UINT32)
+  if ((data->register_type == REG_TYPE_INT32)
+      || (data->register_type == REG_TYPE_UINT32)
       || (data->register_type == REG_TYPE_FLOAT))
     values_num = 2;
   else
     values_num = 1;
 
+#if LEGACY_LIBMODBUS
+  /* Version 2.0.3: Pass the connection struct as a pointer and pass the slave
+   * id to each call of "read_holding_registers". */
+# define modbus_read_registers(ctx, addr, nb, dest) \
+  read_holding_registers (&(ctx), slave->id, (addr), (nb), (dest))
+#else /* if !LEGACY_LIBMODBUS */
+  /* Version 2.9.2: Set the slave id once before querying the registers. */
+  status = modbus_set_slave (host->connection, slave->id);
+  if (status != 0)
+  {
+    ERROR ("Modbus plugin: modbus_set_slave (%i) failed with status %i.",
+        slave->id, status);
+    return (-1);
+  }
+#endif
+
   for (i = 0; i < 2; i++)
   {
-    status = read_holding_registers (&host->connection,
-        /* slave = */ slave->id, /* start_addr = */ data->register_base,
+    status = modbus_read_registers (host->connection,
+        /* start_addr = */ data->register_base,
         /* num_registers = */ values_num, /* buffer = */ values);
     if (status > 0)
       break;
 
     if (host->is_connected)
+    {
+#if LEGACY_LIBMODBUS
       modbus_close (&host->connection);
-    host->is_connected = 0;
+      host->is_connected = 0;
+#else
+      modbus_close (host->connection);
+      modbus_free (host->connection);
+      host->connection = NULL;
+#endif
+    }
 
     /* If we already tried reconnecting this round, give up. */
     if (host->have_reconnected)
     {
-      ERROR ("Modbus plugin: read_holding_registers (%s) failed. "
+      ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
           "Reconnecting has already been tried. Giving up.", host->host);
       return (-1);
     }
@@ -389,7 +478,7 @@ static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
     status = mb_init_connection (host);
     if (status != 0)
     {
-      ERROR ("Modbus plugin: read_holding_registers (%s) failed. "
+      ERROR ("Modbus plugin: modbus_read_registers (%s) failed. "
           "While trying to reconnect, connecting to \"%s\" failed. "
           "Giving up.",
           host->host, host->node);
@@ -403,7 +492,7 @@ static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
   } /* for (i = 0, 1) */
 
   DEBUG ("Modbus plugin: mb_read_data: Success! "
-      "read_holding_registers returned with status %i.", status);
+      "modbus_read_registers returned with status %i.", status);
 
   if (data->register_type == REG_TYPE_FLOAT)
   {
@@ -417,12 +506,47 @@ static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */
     CAST_TO_VALUE_T (ds, vt, float_value);
     mb_submit (host, slave, data, vt);
   }
+  else if (data->register_type == REG_TYPE_INT32)
+  {
+    union
+    {
+      uint32_t u32;
+      int32_t  i32;
+    } v;
+    value_t vt;
+
+    v.u32 = (((uint32_t) values[0]) << 16)
+      | ((uint32_t) values[1]);
+    DEBUG ("Modbus plugin: mb_read_data: "
+        "Returned int32 value is %"PRIi32, v.i32);
+
+    CAST_TO_VALUE_T (ds, vt, v.i32);
+    mb_submit (host, slave, data, vt);
+  }
+  else if (data->register_type == REG_TYPE_INT16)
+  {
+    union
+    {
+      uint16_t u16;
+      int16_t  i16;
+    } v;
+    value_t vt;
+
+    v.u16 = values[0];
+
+    DEBUG ("Modbus plugin: mb_read_data: "
+        "Returned int16 value is %"PRIi16, v.i16);
+
+    CAST_TO_VALUE_T (ds, vt, v.i16);
+    mb_submit (host, slave, data, vt);
+  }
   else if (data->register_type == REG_TYPE_UINT32)
   {
     uint32_t v32;
     value_t vt;
 
-    v32 = (values[0] << 16) | values[1];
+    v32 = (((uint32_t) values[0]) << 16)
+      | ((uint32_t) values[1]);
     DEBUG ("Modbus plugin: mb_read_data: "
         "Returned uint32 value is %"PRIu32, v32);
 
@@ -578,6 +702,10 @@ static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */
       status = cf_util_get_string_buffer (child, tmp, sizeof (tmp));
       if (status != 0)
         /* do nothing */;
+      else if (strcasecmp ("Int16", tmp) == 0)
+        data.register_type = REG_TYPE_INT16;
+      else if (strcasecmp ("Int32", tmp) == 0)
+        data.register_type = REG_TYPE_INT32;
       else if (strcasecmp ("Uint16", tmp) == 0)
         data.register_type = REG_TYPE_UINT16;
       else if (strcasecmp ("Uint32", tmp) == 0)
@@ -771,7 +899,7 @@ static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
         status = -1;
     }
     else if (strcasecmp ("Interval", child->key) == 0)
-      status = cf_util_get_int (child, &host->interval);
+      status = cf_util_get_cdtime (child, &host->interval);
     else if (strcasecmp ("Slave", child->key) == 0)
       /* Don't set status: Gracefully continue if a slave fails. */
       mb_config_add_slave (host, child);
@@ -797,21 +925,19 @@ static int mb_config_add_host (oconfig_item_t *ci) /* {{{ */
   {
     user_data_t ud;
     char name[1024];
-    struct timespec interval;
+    struct timespec interval = { 0, 0 };
 
     ud.data = host;
     ud.free_func = host_free;
 
     ssnprintf (name, sizeof (name), "modbus-%s", host->host);
 
-    interval.tv_nsec = 0;
-    if (host->interval > 0)
-      interval.tv_sec = host->interval;
-    else
-      interval.tv_sec = 0;
+    CDTIME_T_TO_TIMESPEC (host->interval, &interval);
 
     plugin_register_complex_read (/* group = */ NULL, name,
-        mb_read, (interval.tv_sec > 0) ? &interval : NULL, &ud);
+        /* callback = */ mb_read,
+        /* interval = */ (host->interval > 0) ? &interval : NULL,
+        &ud);
   }
   else
   {
index a01bbe4..32b352b 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/mysql.c
- * Copyright (C) 2006-2009  Florian octo Forster
+ * Copyright (C) 2006-2010  Florian octo Forster
  * Copyright (C) 2008       Mirko Buffoni
  * Copyright (C) 2009       Doug MacEachern
  * Copyright (C) 2009       Sebastian tokkee Harl
@@ -20,7 +20,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Mirko Buffoni <briareos at eswat.org>
  *   Doug MacEachern <dougm at hyperic.com>
  *   Sebastian tokkee Harl <sh at tokkee.org>
@@ -192,9 +192,9 @@ static int mysql_config_database (oconfig_item_t *ci) /* {{{ */
                ud.data = (void *) db;
                ud.free_func = mysql_database_free;
 
-               if (db->database != NULL)
+               if (db->instance != NULL)
                        ssnprintf (cb_name, sizeof (cb_name), "mysql-%s",
-                                       db->database);
+                                       db->instance);
                else
                        sstrncpy (cb_name, "mysql", sizeof (cb_name));
 
@@ -321,11 +321,11 @@ static void submit (const char *type, const char *type_instance,
 } /* submit */
 
 static void counter_submit (const char *type, const char *type_instance,
-               counter_t value, mysql_database_t *db)
+               derive_t value, mysql_database_t *db)
 {
        value_t values[1];
 
-       values[0].counter = value;
+       values[0].derive = value;
        submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
 } /* void counter_submit */
 
@@ -347,12 +347,12 @@ static void derive_submit (const char *type, const char *type_instance,
        submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
 } /* void derive_submit */
 
-static void traffic_submit (counter_t rx, counter_t tx, mysql_database_t *db)
+static void traffic_submit (derive_t rx, derive_t tx, mysql_database_t *db)
 {
        value_t values[2];
 
-       values[0].counter = rx;
-       values[1].counter = tx;
+       values[0].derive = rx;
+       values[1].derive = tx;
 
        submit ("mysql_octets", NULL, values, STATIC_ARRAY_SIZE (values), db);
 } /* void traffic_submit */
@@ -485,7 +485,7 @@ static int mysql_read_slave_stats (mysql_database_t *db, MYSQL *con)
 
        if (db->slave_notif)
        {
-               notification_t n = { 0, time (NULL), "", "",
+               notification_t n = { 0, cdtime (), "", "",
                        "mysql", "", "time_offset", "", NULL };
 
                char *io, *sql;
@@ -555,7 +555,6 @@ static int mysql_read (user_data_t *ud)
        MYSQL_RES *res;
        MYSQL_ROW  row;
        char      *query;
-       int        field_num;
 
        derive_t qcache_hits          = 0;
        derive_t qcache_inserts       = 0;
@@ -591,7 +590,6 @@ static int mysql_read (user_data_t *ud)
        if (res == NULL)
                return (-1);
 
-       field_num = mysql_num_fields (res);
        while ((row = mysql_fetch_row (res)))
        {
                char *key;
index c50b3db..f7bc04d 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/netapp.c
- * Copyright (C) 2009  Sven Trenkel
+ * Copyright (C) 2009,2010  Sven Trenkel
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -38,8 +38,8 @@ typedef void service_handler_t(host_config_t *host, na_elem_t *result, void *dat
 
 struct cna_interval_s
 {
-       time_t interval;
-       time_t last_read;
+       cdtime_t interval;
+       cdtime_t last_read;
 };
 typedef struct cna_interval_s cna_interval_t;
 
@@ -79,7 +79,7 @@ typedef struct {
        cna_interval_t interval;
        na_elem_t *query;
 
-       time_t timestamp;
+       cdtime_t timestamp;
        uint64_t name_cache_hit;
        uint64_t name_cache_miss;
        uint64_t find_dir_hit;
@@ -104,7 +104,7 @@ typedef struct {
 typedef struct disk_s {
        char *name;
        uint32_t flags;
-       time_t timestamp;
+       cdtime_t timestamp;
        uint64_t disk_busy;
        uint64_t base_for_disk_busy;
        double disk_busy_percent;
@@ -153,7 +153,7 @@ typedef struct data_volume_perf_s data_volume_perf_t;
 struct data_volume_perf_s {
        char *name;
        uint32_t flags;
-       time_t timestamp;
+       cdtime_t timestamp;
 
        uint64_t read_bytes;
        uint64_t write_bytes;
@@ -242,7 +242,7 @@ struct host_config_s {
        int port;
        char *username;
        char *password;
-       int interval;
+       cdtime_t interval;
 
        na_server_t *srv;
        cfg_wafl_t *cfg_wafl;
@@ -566,7 +566,7 @@ static int submit_values (const char *host, /* {{{ */
                const char *plugin_inst,
                const char *type, const char *type_inst,
                value_t *values, int values_len,
-               time_t timestamp, int interval)
+               cdtime_t timestamp, cdtime_t interval)
 {
        value_list_t vl = VALUE_LIST_INIT;
 
@@ -593,33 +593,34 @@ static int submit_values (const char *host, /* {{{ */
        return (plugin_dispatch_values (&vl));
 } /* }}} int submit_uint64 */
 
-static int submit_two_counters (const char *host, const char *plugin_inst, /* {{{ */
-               const char *type, const char *type_inst, counter_t val0, counter_t val1,
-               time_t timestamp, int interval)
+static int submit_two_derive (const char *host, const char *plugin_inst, /* {{{ */
+               const char *type, const char *type_inst, derive_t val0, derive_t val1,
+               cdtime_t timestamp, cdtime_t interval)
 {
        value_t values[2];
 
-       values[0].counter = val0;
-       values[1].counter = val1;
+       values[0].derive = val0;
+       values[1].derive = val1;
 
        return (submit_values (host, plugin_inst, type, type_inst,
                                values, 2, timestamp, interval));
-} /* }}} int submit_two_counters */
+} /* }}} int submit_two_derive */
 
-static int submit_counter (const char *host, const char *plugin_inst, /* {{{ */
-               const char *type, const char *type_inst, counter_t counter, time_t timestamp, int interval)
+static int submit_derive (const char *host, const char *plugin_inst, /* {{{ */
+               const char *type, const char *type_inst, derive_t counter,
+               cdtime_t timestamp, cdtime_t interval)
 {
        value_t v;
 
-       v.counter = counter;
+       v.derive = counter;
 
        return (submit_values (host, plugin_inst, type, type_inst,
                                &v, 1, timestamp, interval));
-} /* }}} int submit_counter */
+} /* }}} int submit_derive */
 
 static int submit_two_gauge (const char *host, const char *plugin_inst, /* {{{ */
                const char *type, const char *type_inst, gauge_t val0, gauge_t val1,
-               time_t timestamp, int interval)
+               cdtime_t timestamp, cdtime_t interval)
 {
        value_t values[2];
 
@@ -631,7 +632,8 @@ static int submit_two_gauge (const char *host, const char *plugin_inst, /* {{{ *
 } /* }}} int submit_two_gauge */
 
 static int submit_double (const char *host, const char *plugin_inst, /* {{{ */
-               const char *type, const char *type_inst, double d, time_t timestamp, int interval)
+               const char *type, const char *type_inst, double d,
+               cdtime_t timestamp, cdtime_t interval)
 {
        value_t v;
 
@@ -650,8 +652,8 @@ static int submit_cache_ratio (const char *host, /* {{{ */
                uint64_t new_misses,
                uint64_t old_hits,
                uint64_t old_misses,
-               time_t timestamp,
-               int interval)
+               cdtime_t timestamp,
+               cdtime_t interval)
 {
        value_t v;
 
@@ -742,16 +744,16 @@ static int submit_volume_perf_data (const char *hostname, /* {{{ */
        if (HAS_ALL_FLAGS (old_data->flags, CFG_VOLUME_PERF_IO)
                        && HAS_ALL_FLAGS (new_data->flags, HAVE_VOLUME_PERF_BYTES_READ | HAVE_VOLUME_PERF_BYTES_WRITE))
        {
-               submit_two_counters (hostname, plugin_instance, "disk_octets", /* type instance = */ NULL,
-                               (counter_t) new_data->read_bytes, (counter_t) new_data->write_bytes, new_data->timestamp, interval);
+               submit_two_derive (hostname, plugin_instance, "disk_octets", /* type instance = */ NULL,
+                               (derive_t) new_data->read_bytes, (derive_t) new_data->write_bytes, new_data->timestamp, interval);
        }
 
        /* Check for and submit disk-operations values */
        if (HAS_ALL_FLAGS (old_data->flags, CFG_VOLUME_PERF_OPS)
                        && HAS_ALL_FLAGS (new_data->flags, HAVE_VOLUME_PERF_OPS_READ | HAVE_VOLUME_PERF_OPS_WRITE))
        {
-               submit_two_counters (hostname, plugin_instance, "disk_ops", /* type instance = */ NULL,
-                               (counter_t) new_data->read_ops, (counter_t) new_data->write_ops, new_data->timestamp, interval);
+               submit_two_derive (hostname, plugin_instance, "disk_ops", /* type instance = */ NULL,
+                               (derive_t) new_data->read_ops, (derive_t) new_data->write_ops, new_data->timestamp, interval);
        }
 
        /* Check for, calculate and submit disk-latency values */
@@ -816,6 +818,16 @@ static int submit_volume_perf_data (const char *hostname, /* {{{ */
        return (0);
 } /* }}} int submit_volume_perf_data */
 
+static cdtime_t cna_child_get_cdtime (na_elem_t *data) /* {{{ */
+{
+       time_t t;
+
+       t = (time_t) na_child_get_uint64 (data, "timestamp", /* default = */ 0);
+
+       return (TIME_T_TO_CDTIME_T (t));
+} /* }}} cdtime_t cna_child_get_cdtime */
+
+
 /* 
  * Query functions
  *
@@ -835,7 +847,7 @@ static int cna_handle_wafl_data (const char *hostname, cfg_wafl_t *cfg_wafl, /*
 
        memset (&perf_data, 0, sizeof (perf_data));
        
-       perf_data.timestamp = (time_t) na_child_get_uint64 (data, "timestamp", 0);
+       perf_data.timestamp = cna_child_get_cdtime (data);
 
        instances = na_elem_child(na_elem_child (data, "instances"), "instance-data");
        if (instances == NULL)
@@ -950,7 +962,7 @@ static int cna_query_wafl (host_config_t *host) /* {{{ */
 {
        na_elem_t *data;
        int status;
-       time_t now;
+       cdtime_t now;
 
        if (host == NULL)
                return (EINVAL);
@@ -959,7 +971,7 @@ static int cna_query_wafl (host_config_t *host) /* {{{ */
        if (host->cfg_wafl == NULL)
                return (0);
 
-       now = time (NULL);
+       now = cdtime ();
        if ((host->cfg_wafl->interval.interval + host->cfg_wafl->interval.last_read) > now)
                return (0);
 
@@ -988,9 +1000,9 @@ static int cna_query_wafl (host_config_t *host) /* {{{ */
 
 /* Data corresponding to <Disks /> */
 static int cna_handle_disk_data (const char *hostname, /* {{{ */
-               cfg_disk_t *cfg_disk, na_elem_t *data, int interval)
+               cfg_disk_t *cfg_disk, na_elem_t *data, cdtime_t interval)
 {
-       time_t timestamp;
+       cdtime_t timestamp;
        na_elem_t *instances;
        na_elem_t *instance;
        na_elem_iter_t instance_iter;
@@ -999,7 +1011,7 @@ static int cna_handle_disk_data (const char *hostname, /* {{{ */
        if ((cfg_disk == NULL) || (data == NULL))
                return (EINVAL);
        
-       timestamp = (time_t) na_child_get_uint64(data, "timestamp", 0);
+       timestamp = cna_child_get_cdtime (data);
 
        instances = na_elem_child (data, "instances");
        if (instances == NULL)
@@ -1144,7 +1156,7 @@ static int cna_query_disk (host_config_t *host) /* {{{ */
 {
        na_elem_t *data;
        int status;
-       time_t now;
+       cdtime_t now;
 
        if (host == NULL)
                return (EINVAL);
@@ -1154,7 +1166,7 @@ static int cna_query_disk (host_config_t *host) /* {{{ */
        if (host->cfg_disk == NULL)
                return (0);
 
-       now = time (NULL);
+       now = cdtime ();
        if ((host->cfg_disk->interval.interval + host->cfg_disk->interval.last_read) > now)
                return (0);
 
@@ -1183,14 +1195,14 @@ static int cna_query_disk (host_config_t *host) /* {{{ */
 
 /* Data corresponding to <VolumePerf /> */
 static int cna_handle_volume_perf_data (const char *hostname, /* {{{ */
-               cfg_volume_perf_t *cvp, na_elem_t *data, int interval)
+               cfg_volume_perf_t *cvp, na_elem_t *data, cdtime_t interval)
 {
-       time_t timestamp;
+       cdtime_t timestamp;
        na_elem_t *elem_instances;
        na_elem_iter_t iter_instances;
        na_elem_t *elem_instance;
        
-       timestamp = (time_t) na_child_get_uint64(data, "timestamp", 0);
+       timestamp = cna_child_get_cdtime (data);
 
        elem_instances = na_elem_child(data, "instances");
        if (elem_instances == NULL)
@@ -1315,7 +1327,7 @@ static int cna_query_volume_perf (host_config_t *host) /* {{{ */
 {
        na_elem_t *data;
        int status;
-       time_t now;
+       cdtime_t now;
 
        if (host == NULL)
                return (EINVAL);
@@ -1325,7 +1337,7 @@ static int cna_query_volume_perf (host_config_t *host) /* {{{ */
        if (host->cfg_volume_perf == NULL)
                return (0);
 
-       now = time (NULL);
+       now = cdtime ();
        if ((host->cfg_volume_perf->interval.interval + host->cfg_volume_perf->interval.last_read) > now)
                return (0);
 
@@ -1444,7 +1456,7 @@ static int cna_change_volume_status (const char *hostname, /* {{{ */
        notification_t n;
 
        memset (&n, 0, sizeof (&n));
-       n.time = time (NULL);
+       n.time = cdtime ();
        sstrncpy (n.host, hostname, sizeof (n.host));
        sstrncpy (n.plugin, "netapp", sizeof (n.plugin));
        sstrncpy (n.plugin_instance, v->name, sizeof (n.plugin_instance));
@@ -1590,6 +1602,9 @@ static int cna_handle_volume_usage_data (const host_config_t *host, /* {{{ */
                if (sis == NULL)
                        continue;
 
+               if (na_elem_child(sis, "sis-info"))
+                       sis = na_elem_child(sis, "sis-info");
+               
                sis_state = na_child_get_string(sis, "state");
                if (sis_state == NULL)
                        continue;
@@ -1679,7 +1694,7 @@ static int cna_query_volume_usage (host_config_t *host) /* {{{ */
 {
        na_elem_t *data;
        int status;
-       time_t now;
+       cdtime_t now;
 
        if (host == NULL)
                return (EINVAL);
@@ -1689,7 +1704,7 @@ static int cna_query_volume_usage (host_config_t *host) /* {{{ */
        if (host->cfg_volume_usage == NULL)
                return (0);
 
-       now = time (NULL);
+       now = cdtime ();
        if ((host->cfg_volume_usage->interval.interval + host->cfg_volume_usage->interval.last_read) > now)
                return (0);
 
@@ -1724,15 +1739,15 @@ static int cna_handle_system_data (const char *hostname, /* {{{ */
        na_elem_t *counter;
        na_elem_iter_t counter_iter;
 
-       counter_t disk_read = 0, disk_written = 0;
-       counter_t net_recv = 0, net_sent = 0;
-       counter_t cpu_busy = 0, cpu_total = 0;
+       derive_t disk_read = 0, disk_written = 0;
+       derive_t net_recv = 0, net_sent = 0;
+       derive_t cpu_busy = 0, cpu_total = 0;
        uint32_t counter_flags = 0;
 
        const char *instance;
-       time_t timestamp;
+       cdtime_t timestamp;
        
-       timestamp = (time_t) na_child_get_uint64 (data, "timestamp", 0);
+       timestamp = cna_child_get_cdtime (data);
 
        instances = na_elem_child(na_elem_child (data, "instances"), "instance-data");
        if (instances == NULL)
@@ -1769,47 +1784,47 @@ static int cna_handle_system_data (const char *hostname, /* {{{ */
                        continue;
 
                if (!strcmp(name, "disk_data_read")) {
-                       disk_read = (counter_t) (value * 1024);
+                       disk_read = (derive_t) (value * 1024);
                        counter_flags |= 0x01;
                } else if (!strcmp(name, "disk_data_written")) {
-                       disk_written = (counter_t) (value * 1024);
+                       disk_written = (derive_t) (value * 1024);
                        counter_flags |= 0x02;
                } else if (!strcmp(name, "net_data_recv")) {
-                       net_recv = (counter_t) (value * 1024);
+                       net_recv = (derive_t) (value * 1024);
                        counter_flags |= 0x04;
                } else if (!strcmp(name, "net_data_sent")) {
-                       net_sent = (counter_t) (value * 1024);
+                       net_sent = (derive_t) (value * 1024);
                        counter_flags |= 0x08;
                } else if (!strcmp(name, "cpu_busy")) {
-                       cpu_busy = (counter_t) value;
+                       cpu_busy = (derive_t) value;
                        counter_flags |= 0x10;
                } else if (!strcmp(name, "cpu_elapsed_time")) {
-                       cpu_total = (counter_t) value;
+                       cpu_total = (derive_t) value;
                        counter_flags |= 0x20;
                } else if ((cfg_system->flags & CFG_SYSTEM_OPS)
                                && (value > 0) && (strlen(name) > 4)
                                && (!strcmp(name + strlen(name) - 4, "_ops"))) {
-                       submit_counter (hostname, instance, "disk_ops_complex", name,
-                                       (counter_t) value, timestamp, interval);
+                       submit_derive (hostname, instance, "disk_ops_complex", name,
+                                       (derive_t) value, timestamp, interval);
                }
        } /* for (counter) */
 
        if ((cfg_system->flags & CFG_SYSTEM_DISK)
                        && (HAS_ALL_FLAGS (counter_flags, 0x01 | 0x02)))
-               submit_two_counters (hostname, instance, "disk_octets", NULL,
+               submit_two_derive (hostname, instance, "disk_octets", NULL,
                                disk_read, disk_written, timestamp, interval);
                                
        if ((cfg_system->flags & CFG_SYSTEM_NET)
                        && (HAS_ALL_FLAGS (counter_flags, 0x04 | 0x08)))
-               submit_two_counters (hostname, instance, "if_octets", NULL,
+               submit_two_derive (hostname, instance, "if_octets", NULL,
                                net_recv, net_sent, timestamp, interval);
 
        if ((cfg_system->flags & CFG_SYSTEM_CPU)
                        && (HAS_ALL_FLAGS (counter_flags, 0x10 | 0x20)))
        {
-               submit_counter (hostname, instance, "cpu", "system",
+               submit_derive (hostname, instance, "cpu", "system",
                                cpu_busy, timestamp, interval);
-               submit_counter (hostname, instance, "cpu", "idle",
+               submit_derive (hostname, instance, "cpu", "idle",
                                cpu_total - cpu_busy, timestamp, interval);
        }
 
@@ -1839,7 +1854,7 @@ static int cna_query_system (host_config_t *host) /* {{{ */
 {
        na_elem_t *data;
        int status;
-       time_t now;
+       cdtime_t now;
 
        if (host == NULL)
                return (EINVAL);
@@ -1848,7 +1863,7 @@ static int cna_query_system (host_config_t *host) /* {{{ */
        if (host->cfg_system == NULL)
                return (0);
 
-       now = time (NULL);
+       now = cdtime ();
        if ((host->cfg_system->interval.interval + host->cfg_system->interval.last_read) > now)
                return (0);
 
@@ -1905,23 +1920,12 @@ static int cna_config_bool_to_flag (const oconfig_item_t *ci, /* {{{ */
 static int cna_config_get_interval (const oconfig_item_t *ci, /* {{{ */
                cna_interval_t *out_interval)
 {
-       time_t tmp;
-
-       if ((ci == NULL) || (out_interval == NULL))
-               return (EINVAL);
-
-       if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
-       {
-               WARNING ("netapp plugin: The `Interval' option needs exactly one numeric argument.");
-               return (-1);
-       }
+       cdtime_t tmp = 0;
+       int status;
 
-       tmp = (time_t) (ci->values[0].value.number + .5);
-       if (tmp < 1)
-       {
-               WARNING ("netapp plugin: The `Interval' option needs a positive integer argument.");
-               return (-1);
-       }
+       status = cf_util_get_cdtime (ci, &tmp);
+       if (status != 0)
+               return (status);
 
        out_interval->interval = tmp;
        out_interval->last_read = 0;
@@ -2421,11 +2425,7 @@ static host_config_t *cna_config_host (const oconfig_item_t *ci) /* {{{ */
                } else if (!strcasecmp(item->key, "Password")) {
                        status = cf_util_get_string (item, &host->password);
                } else if (!strcasecmp(item->key, "Interval")) {
-                       if (item->values_num != 1 || item->values[0].type != OCONFIG_TYPE_NUMBER || item->values[0].value.number != (int) item->values[0].value.number || item->values[0].value.number < 2) {
-                               WARNING("netapp plugin: \"Interval\" of host %s needs exactly one integer argument.", ci->values[0].value.string);
-                               continue;
-                       }
-                       host->interval = item->values[0].value.number;
+                       status = cf_util_get_cdtime (item, &host->interval);
                } else if (!strcasecmp(item->key, "WAFL")) {
                        cna_config_wafl(host, item);
                } else if (!strcasecmp(item->key, "Disks")) {
@@ -2497,7 +2497,7 @@ static int cna_init_host (host_config_t *host) /* {{{ */
        na_server_adminuser(host->srv, host->username, host->password);
        na_server_set_timeout(host->srv, 5 /* seconds */);
 
-       return 0;
+       return (0);
 } /* }}} int cna_init_host */
 
 static int cna_init (void) /* {{{ */
@@ -2514,6 +2514,32 @@ static int cna_init (void) /* {{{ */
        return (0);
 } /* }}} cna_init */
 
+static int cna_read_internal (host_config_t *host) { /* {{{ */
+       int status;
+
+       status = cna_query_wafl (host);
+       if (status != 0)
+               return (status);
+
+       status = cna_query_disk (host);
+       if (status != 0)
+               return (status);
+
+       status = cna_query_volume_perf (host);
+       if (status != 0)
+               return (status);
+
+       status = cna_query_volume_usage (host);
+       if (status != 0)
+               return (status);
+
+       status = cna_query_system (host);
+       if (status != 0)
+               return (status);
+
+       return 0;
+} /* }}} int cna_read_internal */
+
 static int cna_read (user_data_t *ud) { /* {{{ */
        host_config_t *host;
        int status;
@@ -2526,12 +2552,14 @@ static int cna_read (user_data_t *ud) { /* {{{ */
        status = cna_init_host (host);
        if (status != 0)
                return (status);
-       
-       cna_query_wafl (host);
-       cna_query_disk (host);
-       cna_query_volume_perf (host);
-       cna_query_volume_usage (host);
-       cna_query_system (host);
+
+       status = cna_read_internal (host);
+       if (status != 0)
+       {
+               if (host->srv != NULL)
+                       na_server_close (host->srv);
+               host->srv = NULL;
+       }
 
        return 0;
 } /* }}} int cna_read */
@@ -2556,8 +2584,7 @@ static int cna_config (oconfig_item_t *ci) { /* {{{ */
 
                        ssnprintf (cb_name, sizeof (cb_name), "netapp-%s", host->name);
 
-                       memset (&interval, 0, sizeof (interval));
-                       interval.tv_sec = host->interval;
+                       CDTIME_T_TO_TIMESPEC (host->interval, &interval);
 
                        memset (&ud, 0, sizeof (ud));
                        ud.data = host;
index 49c4e99..39536d9 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/netlink.c
- * Copyright (C) 2007  Florian octo Forster
+ * Copyright (C) 2007-2010  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
@@ -161,12 +161,12 @@ static int check_ignorelist (const char *dev,
 } /* int check_ignorelist */
 
 static void submit_one (const char *dev, const char *type,
-    const char *type_instance, counter_t value)
+    const char *type_instance, derive_t value)
 {
   value_t values[1];
   value_list_t vl = VALUE_LIST_INIT;
 
-  values[0].counter = value;
+  values[0].derive = value;
 
   vl.values = values;
   vl.values_len = 1;
@@ -183,13 +183,13 @@ static void submit_one (const char *dev, const char *type,
 
 static void submit_two (const char *dev, const char *type,
     const char *type_instance,
-    counter_t rx, counter_t tx)
+    derive_t rx, derive_t tx)
 {
   value_t values[2];
   value_list_t vl = VALUE_LIST_INIT;
 
-  values[0].counter = rx;
-  values[1].counter = tx;
+  values[0].derive = rx;
+  values[1].derive = tx;
 
   vl.values = values;
   vl.values_len = 2;
@@ -223,7 +223,7 @@ static int link_filter (const struct sockaddr_nl __attribute__((unused)) *sa,
 
   msg = NLMSG_DATA (nmh);
 
-  msg_len = nmh->nlmsg_len - sizeof (struct ifinfomsg);
+  msg_len = nmh->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifinfomsg));
   if (msg_len < 0)
   {
     ERROR ("netlink plugin: link_filter: msg_len = %i < 0;", msg_len);
@@ -554,24 +554,26 @@ static int ir_init (void)
 
 static int ir_read (void)
 {
-  struct ifinfomsg im;
   struct tcmsg tm;
   int ifindex;
 
   static const int type_id[] = { RTM_GETQDISC, RTM_GETTCLASS, RTM_GETTFILTER };
   static const char *type_name[] = { "qdisc", "class", "filter" };
 
-  memset (&im, '\0', sizeof (im));
-  im.ifi_type = AF_UNSPEC;
-
-  if (rtnl_dump_request (&rth, RTM_GETLINK, &im, sizeof (im)) < 0)
+  if (rtnl_wilddump_request (&rth, AF_UNSPEC, RTM_GETLINK) < 0)
   {
-    ERROR ("netlink plugin: ir_read: rtnl_dump_request failed.");
+    ERROR ("netlink plugin: ir_read: rtnl_wilddump_request failed.");
     return (-1);
   }
 
+#ifdef RTNL_DUMP_FILTER_FIVE_ARGS
   if (rtnl_dump_filter (&rth, link_filter, /* arg1 = */ NULL,
        NULL, NULL) != 0)
+#elif defined(RTNL_DUMP_FILTER_THREE_ARGS)
+  if (rtnl_dump_filter (&rth, link_filter, /* arg = */ NULL) != 0)
+#else
+#error "Failed to determine the number of arguments to 'rtnl_dump_filter'!"
+#endif
   {
     ERROR ("netlink plugin: ir_read: rtnl_dump_filter failed.");
     return (-1);
@@ -608,8 +610,14 @@ static int ir_read (void)
        continue;
       }
 
+#ifdef RTNL_DUMP_FILTER_FIVE_ARGS
       if (rtnl_dump_filter (&rth, qos_filter, (void *) &ifindex,
            NULL, NULL) != 0)
+#elif defined(RTNL_DUMP_FILTER_THREE_ARGS)
+      if (rtnl_dump_filter (&rth, qos_filter, /* arg = */ &ifindex) != 0)
+#else
+#error "Failed to determine the number of arguments to 'rtnl_dump_filter'!"
+#endif
       {
        ERROR ("netlink plugin: ir_read: rtnl_dump_filter failed.");
        continue;
index 3ad1177..e8b45a3 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/network.c
- * Copyright (C) 2005-2009  Florian octo Forster
+ * Copyright (C) 2005-2010  Florian octo Forster
  * Copyright (C) 2009       Aman Gupta
  *
  * This program is free software; you can redistribute it and/or modify it
 #endif
 
 #if HAVE_LIBGCRYPT
+# include <pthread.h>
+# if defined __APPLE__
+/* default xcode compiler throws warnings even when deprecated functionality
+ * is not used. -Werror breaks the build because of erroneous warnings.
+ * http://stackoverflow.com/questions/10556299/compiler-warnings-with-libgcrypt-v1-5-0/12830209#12830209
+ */
+#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+# endif
 # include <gcrypt.h>
+# if defined __APPLE__
+/* Re enable deprecation warnings */
+#  pragma GCC diagnostic warning "-Wdeprecated-declarations"
+# endif
 GCRY_THREAD_OPTION_PTHREAD_IMPL;
 #endif
 
@@ -259,6 +271,7 @@ typedef struct receive_list_entry_s receive_list_entry_t;
  * Private variables
  */
 static int network_config_ttl = 0;
+/* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
 static size_t network_config_packet_size = 1452;
 static int network_config_forward = 0;
 static int network_config_stats = 0;
@@ -296,14 +309,14 @@ static pthread_mutex_t  send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
  * example). Only if neither is true, the stats_lock is acquired. The counters
  * are always read without holding a lock in the hope that writing 8 bytes to
  * memory is an atomic operation. */
-static uint64_t stats_octets_rx  = 0;
-static uint64_t stats_octets_tx  = 0;
-static uint64_t stats_packets_rx = 0;
-static uint64_t stats_packets_tx = 0;
-static uint64_t stats_values_dispatched = 0;
-static uint64_t stats_values_not_dispatched = 0;
-static uint64_t stats_values_sent = 0;
-static uint64_t stats_values_not_sent = 0;
+static derive_t stats_octets_rx  = 0;
+static derive_t stats_octets_tx  = 0;
+static derive_t stats_packets_rx = 0;
+static derive_t stats_packets_tx = 0;
+static derive_t stats_values_dispatched = 0;
+static derive_t stats_values_not_dispatched = 0;
+static derive_t stats_values_sent = 0;
+static derive_t stats_values_not_sent = 0;
 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
 
 /*
@@ -351,6 +364,43 @@ static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
   return (!received);
 } /* }}} _Bool check_send_okay */
 
+static _Bool check_notify_received (const notification_t *n) /* {{{ */
+{
+  notification_meta_t *ptr;
+
+  for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
+    if ((strcmp ("network:received", ptr->name) == 0)
+        && (ptr->type == NM_TYPE_BOOLEAN))
+      return ((_Bool) ptr->nm_value.nm_boolean);
+
+  return (0);
+} /* }}} _Bool check_notify_received */
+
+static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
+{
+  static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
+  _Bool received = 0;
+
+  if (n->meta == NULL)
+    return (1);
+
+  received = check_notify_received (n);
+
+  if (network_config_forward && received)
+  {
+    c_complain_once (LOG_ERR, &complain_forwarding,
+        "network plugin: A notification has been received via the network "
+        "forwarding if enabled. Forwarding of notifications is currently "
+        "not supported, because there is not loop-deteciton available. "
+        "Please contact the collectd mailing list if you need this "
+        "feature.");
+  }
+
+  /* By default, only *send* value lists that were not *received* by the
+   * network plugin. */
+  return (!received);
+} /* }}} _Bool check_send_notify_okay */
+
 static int network_dispatch_values (value_list_t *vl, /* {{{ */
     const char *username)
 {
@@ -405,7 +455,7 @@ static int network_dispatch_values (value_list_t *vl, /* {{{ */
     }
   }
 
-  plugin_dispatch_values (vl);
+  plugin_dispatch_values_secure (vl);
   stats_values_dispatched++;
 
   meta_data_destroy (vl->meta);
@@ -414,6 +464,29 @@ static int network_dispatch_values (value_list_t *vl, /* {{{ */
   return (0);
 } /* }}} int network_dispatch_values */
 
+static int network_dispatch_notification (notification_t *n) /* {{{ */
+{
+  int status;
+
+  assert (n->meta == NULL);
+
+  status = plugin_notification_meta_add_boolean (n, "network:received", 1);
+  if (status != 0)
+  {
+    ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
+    plugin_notification_meta_free (n->meta);
+    n->meta = NULL;
+    return (status);
+  }
+
+  status = plugin_dispatch_notification (n);
+
+  plugin_notification_meta_free (n->meta);
+  n->meta = NULL;
+
+  return (status);
+} /* }}} int network_dispatch_notification */
+
 #if HAVE_LIBGCRYPT
 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
     const void *iv, size_t iv_size, const char *username)
@@ -600,7 +673,7 @@ static int write_part_number (char **ret_buffer, int *ret_buffer_len,
 
        part_header_t pkg_head;
        uint64_t pkg_value;
-       
+
        int offset;
 
        packet_len = sizeof (pkg_head) + sizeof (pkg_value);
@@ -704,7 +777,7 @@ static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
 
        exp_size = 3 * sizeof (uint16_t)
                + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
-       if ((buffer_len < 0) || (buffer_len < exp_size))
+       if (buffer_len < exp_size)
        {
                WARNING ("network plugin: parse_part_values: "
                                "Packet too short: "
@@ -788,9 +861,8 @@ static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
        size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
 
        uint16_t pkg_length;
-       uint16_t pkg_type;
 
-       if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
+       if (buffer_len < exp_size)
        {
                WARNING ("network plugin: parse_part_number: "
                                "Packet too short: "
@@ -802,7 +874,7 @@ static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
 
        memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
        buffer += sizeof (tmp16);
-       pkg_type = ntohs (tmp16);
+       /* pkg_type = ntohs (tmp16); */
 
        memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
        buffer += sizeof (tmp16);
@@ -828,9 +900,8 @@ static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
        size_t header_size = 2 * sizeof (uint16_t);
 
        uint16_t pkg_length;
-       uint16_t pkg_type;
 
-       if ((buffer_len < 0) || (buffer_len < header_size))
+       if (buffer_len < header_size)
        {
                WARNING ("network plugin: parse_part_string: "
                                "Packet too short: "
@@ -842,7 +913,7 @@ static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
 
        memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
        buffer += sizeof (tmp16);
-       pkg_type = ntohs (tmp16);
+       /* pkg_type = ntohs (tmp16); */
 
        memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
        buffer += sizeof (tmp16);
@@ -1381,8 +1452,19 @@ static int parse_packet (sockent_t *se, /* {{{ */
                                        &tmp);
                        if (status == 0)
                        {
-                               vl.time = (time_t) tmp;
-                               n.time = (time_t) tmp;
+                               vl.time = TIME_T_TO_CDTIME_T (tmp);
+                               n.time  = TIME_T_TO_CDTIME_T (tmp);
+                       }
+               }
+               else if (pkg_type == TYPE_TIME_HR)
+               {
+                       uint64_t tmp = 0;
+                       status = parse_part_number (&buffer, &buffer_size,
+                                       &tmp);
+                       if (status == 0)
+                       {
+                               vl.time = (cdtime_t) tmp;
+                               n.time  = (cdtime_t) tmp;
                        }
                }
                else if (pkg_type == TYPE_INTERVAL)
@@ -1391,7 +1473,15 @@ static int parse_packet (sockent_t *se, /* {{{ */
                        status = parse_part_number (&buffer, &buffer_size,
                                        &tmp);
                        if (status == 0)
-                               vl.interval = (int) tmp;
+                               vl.interval = TIME_T_TO_CDTIME_T (tmp);
+               }
+               else if (pkg_type == TYPE_INTERVAL_HR)
+               {
+                       uint64_t tmp = 0;
+                       status = parse_part_number (&buffer, &buffer_size,
+                                       &tmp);
+                       if (status == 0)
+                               vl.interval = (cdtime_t) tmp;
                }
                else if (pkg_type == TYPE_HOST)
                {
@@ -1466,7 +1556,7 @@ static int parse_packet (sockent_t *se, /* {{{ */
                        }
                        else
                        {
-                               plugin_dispatch_notification (&n);
+                               network_dispatch_notification (&n);
                        }
                }
                else if (pkg_type == TYPE_SEVERITY)
@@ -1587,7 +1677,7 @@ static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
                                        sizeof (network_config_ttl)) != 0)
                {
                        char errbuf[1024];
-                       ERROR ("setsockopt: %s",
+                       ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
                                        sstrerror (errno, errbuf, sizeof (errbuf)));
                        return (-1);
                }
@@ -1608,7 +1698,7 @@ static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
                                        sizeof (network_config_ttl)) != 0)
                {
                        char errbuf[1024];
-                       ERROR ("setsockopt: %s",
+                       ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
                                        sstrerror (errno, errbuf,
                                                sizeof (errbuf)));
                        return (-1);
@@ -1655,7 +1745,7 @@ static int network_set_interface (const sockent_t *se, const struct addrinfo *ai
                                                &mreq, sizeof (mreq)) != 0)
                        {
                                char errbuf[1024];
-                               ERROR ("setsockopt: %s",
+                               ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
                                                sstrerror (errno, errbuf, sizeof (errbuf)));
                                return (-1);
                        }
@@ -1674,7 +1764,7 @@ static int network_set_interface (const sockent_t *se, const struct addrinfo *ai
                                                sizeof (se->interface)) != 0)
                        {
                                char errbuf[1024];
-                               ERROR ("setsockopt: %s",
+                               ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
                                                sstrerror (errno, errbuf,
                                                        sizeof (errbuf)));
                                return (-1);
@@ -1685,9 +1775,9 @@ static int network_set_interface (const sockent_t *se, const struct addrinfo *ai
        }
 
        /* else: Not a multicast interface. */
-#if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
        if (se->interface != 0)
        {
+#if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
                char interface_name[IFNAMSIZ];
 
                if (if_indextoname (se->interface, interface_name) == NULL)
@@ -1700,37 +1790,42 @@ static int network_set_interface (const sockent_t *se, const struct addrinfo *ai
                                        sizeof(interface_name)) == -1 )
                {
                        char errbuf[1024];
-                       ERROR ("setsockopt: %s",
+                       ERROR ("network plugin: setsockopt (bind-if): %s",
                                        sstrerror (errno, errbuf, sizeof (errbuf)));
                        return (-1);
                }
-       }
 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
 
 #else
-       WARNING ("network plugin: Cannot set the interface on a unicast "
+               WARNING ("network plugin: Cannot set the interface on a unicast "
                        "socket because "
 # if !defined(SO_BINDTODEVICE)
-                       "the the \"SO_BINDTODEVICE\" socket option "
+                       "the \"SO_BINDTODEVICE\" socket option "
 # else
                        "the \"if_indextoname\" function "
 # endif
                        "is not available on your system.");
 #endif
 
+       }
+
        return (0);
 } /* }}} network_set_interface */
 
 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
 {
+#if KERNEL_SOLARIS
+       char loop   = 0;
+#else
        int loop = 0;
+#endif
        int yes  = 1;
 
        /* allow multiple sockets to use the same PORT number */
        if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
                                &yes, sizeof(yes)) == -1) {
                 char errbuf[1024];
-                ERROR ("setsockopt: %s", 
+                ERROR ("network plugin: setsockopt (reuseaddr): %s",
                                 sstrerror (errno, errbuf, sizeof (errbuf)));
                return (-1);
        }
@@ -1773,7 +1868,7 @@ static int network_bind_socket (int fd, const struct addrinfo *ai, const int int
                                                &loop, sizeof (loop)) == -1)
                        {
                                char errbuf[1024];
-                               ERROR ("setsockopt: %s",
+                               ERROR ("network plugin: setsockopt (multicast-loop): %s",
                                                sstrerror (errno, errbuf,
                                                        sizeof (errbuf)));
                                return (-1);
@@ -1783,7 +1878,7 @@ static int network_bind_socket (int fd, const struct addrinfo *ai, const int int
                                                &mreq, sizeof (mreq)) == -1)
                        {
                                char errbuf[1024];
-                               ERROR ("setsockopt: %s",
+                               ERROR ("network plugin: setsockopt (add-membership): %s",
                                                sstrerror (errno, errbuf,
                                                        sizeof (errbuf)));
                                return (-1);
@@ -1821,7 +1916,7 @@ static int network_bind_socket (int fd, const struct addrinfo *ai, const int int
                                                &loop, sizeof (loop)) == -1)
                        {
                                char errbuf[1024];
-                               ERROR ("setsockopt: %s",
+                               ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
                                                sstrerror (errno, errbuf,
                                                        sizeof (errbuf)));
                                return (-1);
@@ -1831,7 +1926,7 @@ static int network_bind_socket (int fd, const struct addrinfo *ai, const int int
                                                &mreq, sizeof (mreq)) == -1)
                        {
                                char errbuf[1024];
-                               ERROR ("setsockopt: %s",
+                               ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
                                                sstrerror (errno, errbuf,
                                                        sizeof (errbuf)));
                                return (-1);
@@ -1859,7 +1954,7 @@ static int network_bind_socket (int fd, const struct addrinfo *ai, const int int
                                        sizeof(interface_name)) == -1 )
                {
                        char errbuf[1024];
-                       ERROR ("setsockopt: %s",
+                       ERROR ("network plugin: setsockopt (bind-if): %s",
                                        sstrerror (errno, errbuf, sizeof (errbuf)));
                        return (-1);
                }
@@ -2587,7 +2682,7 @@ static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
 
        if (vl_def->time != vl->time)
        {
-               if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
+               if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
                                        (uint64_t) vl->time))
                        return (-1);
                vl_def->time = vl->time;
@@ -2595,7 +2690,7 @@ static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
 
        if (vl_def->interval != vl->interval)
        {
-               if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
+               if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
                                        (uint64_t) vl->interval))
                        return (-1);
                vl_def->interval = vl->interval;
@@ -2634,7 +2729,7 @@ static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
                        return (-1);
                sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
        }
-       
+
        if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
                return (-1);
 
@@ -3068,17 +3163,19 @@ static int network_config (oconfig_item_t *ci) /* {{{ */
 } /* }}} int network_config */
 
 static int network_notification (const notification_t *n,
-               user_data_t __attribute__((unused)) *user_data)
+    user_data_t __attribute__((unused)) *user_data)
 {
   char  buffer[network_config_packet_size];
   char *buffer_ptr = buffer;
   int   buffer_free = sizeof (buffer);
   int   status;
 
-  memset (buffer, '\0', sizeof (buffer));
+  if (!check_send_notify_okay (n))
+    return (0);
 
+  memset (buffer, 0, sizeof (buffer));
 
-  status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
+  status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
       (uint64_t) n->time);
   if (status != 0)
     return (-1);
@@ -3091,7 +3188,7 @@ static int network_notification (const notification_t *n,
   if (strlen (n->host) > 0)
   {
     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
-       n->host, strlen (n->host));
+        n->host, strlen (n->host));
     if (status != 0)
       return (-1);
   }
@@ -3099,7 +3196,7 @@ static int network_notification (const notification_t *n,
   if (strlen (n->plugin) > 0)
   {
     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
-       n->plugin, strlen (n->plugin));
+        n->plugin, strlen (n->plugin));
     if (status != 0)
       return (-1);
   }
@@ -3107,8 +3204,8 @@ static int network_notification (const notification_t *n,
   if (strlen (n->plugin_instance) > 0)
   {
     status = write_part_string (&buffer_ptr, &buffer_free,
-       TYPE_PLUGIN_INSTANCE,
-       n->plugin_instance, strlen (n->plugin_instance));
+        TYPE_PLUGIN_INSTANCE,
+        n->plugin_instance, strlen (n->plugin_instance));
     if (status != 0)
       return (-1);
   }
@@ -3116,7 +3213,7 @@ static int network_notification (const notification_t *n,
   if (strlen (n->type) > 0)
   {
     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
-       n->type, strlen (n->type));
+        n->type, strlen (n->type));
     if (status != 0)
       return (-1);
   }
@@ -3124,7 +3221,7 @@ static int network_notification (const notification_t *n,
   if (strlen (n->type_instance) > 0)
   {
     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
-       n->type_instance, strlen (n->type_instance));
+        n->type_instance, strlen (n->type_instance));
     if (status != 0)
       return (-1);
   }
@@ -3183,15 +3280,15 @@ static int network_shutdown (void)
 
 static int network_stats_read (void) /* {{{ */
 {
-       uint64_t copy_octets_rx;
-       uint64_t copy_octets_tx;
-       uint64_t copy_packets_rx;
-       uint64_t copy_packets_tx;
-       uint64_t copy_values_dispatched;
-       uint64_t copy_values_not_dispatched;
-       uint64_t copy_values_sent;
-       uint64_t copy_values_not_sent;
-       uint64_t copy_receive_list_length;
+       derive_t copy_octets_rx;
+       derive_t copy_octets_tx;
+       derive_t copy_packets_rx;
+       derive_t copy_packets_tx;
+       derive_t copy_values_dispatched;
+       derive_t copy_values_not_dispatched;
+       derive_t copy_values_sent;
+       derive_t copy_values_not_sent;
+       derive_t copy_receive_list_length;
        value_list_t vl = VALUE_LIST_INIT;
        value_t values[2];
 
@@ -3209,21 +3306,20 @@ static int network_stats_read (void) /* {{{ */
        vl.values = values;
        vl.values_len = 2;
        vl.time = 0;
-       vl.interval = interval_g;
        sstrncpy (vl.host, hostname_g, sizeof (vl.host));
        sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
 
        /* Octets received / sent */
-       vl.values[0].counter = (counter_t) copy_octets_rx;
-       vl.values[1].counter = (counter_t) copy_octets_tx;
+       vl.values[0].derive = (derive_t) copy_octets_rx;
+       vl.values[1].derive = (derive_t) copy_octets_tx;
        sstrncpy (vl.type, "if_octets", sizeof (vl.type));
-       plugin_dispatch_values (&vl);
+       plugin_dispatch_values_secure (&vl);
 
        /* Packets received / send */
-       vl.values[0].counter = (counter_t) copy_packets_rx;
-       vl.values[1].counter = (counter_t) copy_packets_tx;
+       vl.values[0].derive = (derive_t) copy_packets_rx;
+       vl.values[1].derive = (derive_t) copy_packets_tx;
        sstrncpy (vl.type, "if_packets", sizeof (vl.type));
-       plugin_dispatch_values (&vl);
+       plugin_dispatch_values_secure (&vl);
 
        /* Values (not) dispatched and (not) send */
        sstrncpy (vl.type, "total_values", sizeof (vl.type));
@@ -3232,28 +3328,28 @@ static int network_stats_read (void) /* {{{ */
        vl.values[0].derive = (derive_t) copy_values_dispatched;
        sstrncpy (vl.type_instance, "dispatch-accepted",
                        sizeof (vl.type_instance));
-       plugin_dispatch_values (&vl);
+       plugin_dispatch_values_secure (&vl);
 
        vl.values[0].derive = (derive_t) copy_values_not_dispatched;
        sstrncpy (vl.type_instance, "dispatch-rejected",
                        sizeof (vl.type_instance));
-       plugin_dispatch_values (&vl);
+       plugin_dispatch_values_secure (&vl);
 
        vl.values[0].derive = (derive_t) copy_values_sent;
        sstrncpy (vl.type_instance, "send-accepted",
                        sizeof (vl.type_instance));
-       plugin_dispatch_values (&vl);
+       plugin_dispatch_values_secure (&vl);
 
        vl.values[0].derive = (derive_t) copy_values_not_sent;
        sstrncpy (vl.type_instance, "send-rejected",
                        sizeof (vl.type_instance));
-       plugin_dispatch_values (&vl);
+       plugin_dispatch_values_secure (&vl);
 
        /* Receive queue length */
        vl.values[0].gauge = (gauge_t) copy_receive_list_length;
        sstrncpy (vl.type, "queue_length", sizeof (vl.type));
        vl.type_instance[0] = 0;
-       plugin_dispatch_values (&vl);
+       plugin_dispatch_values_secure (&vl);
 
        return (0);
 } /* }}} int network_stats_read */
@@ -3269,9 +3365,17 @@ static int network_init (void)
        have_init = 1;
 
 #if HAVE_LIBGCRYPT
-       gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
-       gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
-       gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+    /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
+     * Because you can't know in a library whether another library has
+     * already initialized the library
+     */
+    if (!gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
+    {
+        gcry_check_version(NULL); /* before calling any other functions */
+        gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
+        gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
+        gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+    }
 #endif
 
        if (network_config_stats != 0)
@@ -3305,7 +3409,7 @@ static int network_init (void)
        if (dispatch_thread_running == 0)
        {
                int status;
-               status = pthread_create (&dispatch_thread_id,
+               status = plugin_thread_create (&dispatch_thread_id,
                                NULL /* no attributes */,
                                dispatch_thread,
                                NULL /* no argument */);
@@ -3325,7 +3429,7 @@ static int network_init (void)
        if (receive_thread_running == 0)
        {
                int status;
-               status = pthread_create (&receive_thread_id,
+               status = plugin_thread_create (&receive_thread_id,
                                NULL /* no attributes */,
                                receive_thread,
                                NULL /* no argument */);
@@ -3345,16 +3449,16 @@ static int network_init (void)
        return (0);
 } /* int network_init */
 
-/* 
+/*
  * The flush option of the network plugin cannot flush individual identifiers.
  * All the values are added to a buffer and sent when the buffer is full, the
  * requested value may or may not be in there, it's not worth finding out. We
  * just send the buffer if `flush'  is called - if the requested value was in
  * there, good. If not, well, then there is nothing to flush.. -octo
  */
-static int network_flush (int timeout,
-               const char __attribute__((unused)) *identifier,
-               user_data_t __attribute__((unused)) *user_data)
+static int network_flush (__attribute__((unused)) cdtime_t timeout,
+               __attribute__((unused)) const char *identifier,
+               __attribute__((unused)) user_data_t *user_data)
 {
        pthread_mutex_lock (&send_buffer_lock);
 
index 777616c..1b35456 100644 (file)
 
 #define TYPE_HOST            0x0000
 #define TYPE_TIME            0x0001
+#define TYPE_TIME_HR         0x0008
 #define TYPE_PLUGIN          0x0002
 #define TYPE_PLUGIN_INSTANCE 0x0003
 #define TYPE_TYPE            0x0004
 #define TYPE_TYPE_INSTANCE   0x0005
 #define TYPE_VALUES          0x0006
 #define TYPE_INTERVAL        0x0007
+#define TYPE_INTERVAL_HR     0x0009
 
 /* Types to transmit notifications */
 #define TYPE_MESSAGE         0x0100
index e4d12e3..461e806 100644 (file)
--- a/src/nfs.c
+++ b/src/nfs.c
  * Authors:
  *   Jason Pepas <cell at ices.utexas.edu>
  *   Florian octo Forster <octo at verplant.org>
+ *   Cosmin Ioiart <cioiart at gmail.com>
  **/
 
 #include "collectd.h"
 #include "common.h"
 #include "plugin.h"
 
-#if !KERNEL_LINUX
-# error "No applicable input method."
+#if HAVE_KSTAT_H
+#include <kstat.h>
 #endif
 
 /*
@@ -92,10 +93,9 @@ static const char *nfs2_procedures_names[] =
        "mkdir",
        "rmdir",
        "readdir",
-       "fsstat",
-       NULL
+       "fsstat"
 };
-static int nfs2_procedures_names_num = 18;
+static size_t nfs2_procedures_names_num = STATIC_ARRAY_SIZE (nfs2_procedures_names);
 
 static const char *nfs3_procedures_names[] =
 {
@@ -120,12 +120,57 @@ static const char *nfs3_procedures_names[] =
        "fsstat",
        "fsinfo",
        "pathconf",
+       "commit"
+};
+static size_t nfs3_procedures_names_num = STATIC_ARRAY_SIZE (nfs3_procedures_names);
+
+#if HAVE_LIBKSTAT
+static const char *nfs4_procedures_names[] =
+{
+       "null",
+       "compound",
+       "reserved",
+       "access",
+       "close",
        "commit",
-       NULL
+       "create",
+       "delegpurge",
+       "delegreturn",
+       "getattr",
+       "getfh",
+       "link",
+       "lock",
+       "lockt",
+       "locku",
+       "lookup",
+       "lookupp",
+       "nverify",
+       "open",
+       "openattr",
+       "open_confirm",
+       "open_downgrade",
+       "putfh",
+       "putpubfh",
+       "putrootfh",
+       "read",
+       "readdir",
+       "readlink",
+       "remove",
+       "rename",
+       "renew",
+       "restorefh",
+       "savefh",
+       "secinfo",
+       "setattr",
+       "setclientid",
+       "setclientid_confirm",
+       "verify",
+       "write"
 };
-static int nfs3_procedures_names_num = 22;
+static size_t nfs4_procedures_names_num = STATIC_ARRAY_SIZE (nfs4_procedures_names);
+#endif
 
-#if HAVE_LIBKSTAT && 0
+#if HAVE_LIBKSTAT
 extern kstat_ctl_t *kc;
 static kstat_t *nfs2_ksp_client;
 static kstat_t *nfs2_ksp_server;
@@ -137,11 +182,17 @@ static kstat_t *nfs4_ksp_server;
 
 /* Possibly TODO: NFSv4 statistics */
 
-#if 0
+#if KERNEL_LINUX
+static int nfs_init (void)
+{
+       return (0);
+}
+/* #endif KERNEL_LINUX */
+
+#elif HAVE_LIBKSTAT
 static int nfs_init (void)
 {
-#if HAVE_LIBKSTAT && 0
-       kstat_t *ksp_chain;
+       kstat_t *ksp_chain = NULL;
 
        nfs2_ksp_client = NULL;
        nfs2_ksp_server = NULL;
@@ -149,9 +200,9 @@ static int nfs_init (void)
        nfs3_ksp_server = NULL;
        nfs4_ksp_client = NULL;
        nfs4_ksp_server = NULL;
-       
+
        if (kc == NULL)
-               return;
+               return (-1);
 
        for (ksp_chain = kc->kc_chain; ksp_chain != NULL;
                        ksp_chain = ksp_chain->ks_next)
@@ -171,192 +222,168 @@ static int nfs_init (void)
                else if (strncmp (ksp_chain->ks_name, "rfsreqcnt_v4", 12) == 0)
                        nfs4_ksp_client = ksp_chain;
        }
-#endif
 
        return (0);
 } /* int nfs_init */
 #endif
 
-#define BUFSIZE 1024
 static void nfs_procedures_submit (const char *plugin_instance,
-               unsigned long long *val, const char **names, int len)
+               const char **type_instances,
+               value_t *values, size_t values_num)
 {
-       value_t values[1];
        value_list_t vl = VALUE_LIST_INIT;
-       int i;
+       size_t i;
 
-       vl.values = values;
        vl.values_len = 1;
        sstrncpy (vl.host, hostname_g, sizeof (vl.host));
        sstrncpy (vl.plugin, "nfs", sizeof (vl.plugin));
        sstrncpy (vl.plugin_instance, plugin_instance,
-                       sizeof (vl.plugin_instance));
+                       sizeof (vl.plugin_instance));
        sstrncpy (vl.type, "nfs_procedure", sizeof (vl.type));
 
-       for (i = 0; i < len; i++)
+       for (i = 0; i < values_num; i++)
        {
-               values[0].counter = val[i];
-               sstrncpy (vl.type_instance, names[i],
+               vl.values = values + i;
+               sstrncpy (vl.type_instance, type_instances[i],
                                sizeof (vl.type_instance));
-               DEBUG ("%s-%s/nfs_procedure-%s = %llu",
-                               vl.plugin, vl.plugin_instance,
-                               vl.type_instance, val[i]);
-               plugin_dispatch_values (&vl);
+               plugin_dispatch_values_secure (&vl);
        }
 } /* void nfs_procedures_submit */
 
-static void nfs_read_stats_file (FILE *fh, char *inst)
+#if KERNEL_LINUX
+static int nfs_submit_fields (int nfs_version, const char *instance,
+               char **fields, size_t fields_num,
+               const char **proc_names, size_t proc_names_num)
 {
-       char buffer[BUFSIZE];
-
        char plugin_instance[DATA_MAX_NAME_LEN];
+       value_t values[fields_num];
+       size_t i;
+
+       if (fields_num != proc_names_num)
+       {
+               WARNING ("nfs plugin: Wrong number of fields for "
+                               "NFSv%i %s statistics. Expected %zu, got %zu.",
+                               nfs_version, instance,
+                               proc_names_num, fields_num);
+               return (EINVAL);
+       }
+
+       ssnprintf (plugin_instance, sizeof (plugin_instance), "v%i%s",
+                       nfs_version, instance);
+
+       for (i = 0; i < proc_names_num; i++)
+               (void) parse_value (fields[i], &values[i], DS_TYPE_DERIVE);
+
+       nfs_procedures_submit (plugin_instance, proc_names, values,
+                       proc_names_num);
+
+       return (0);
+}
+
+static void nfs_read_linux (FILE *fh, char *inst)
+{
+       char buffer[1024];
 
        char *fields[48];
-       int numfields = 0;
+       int fields_num = 0;
 
        if (fh == NULL)
                return;
 
-       while (fgets (buffer, BUFSIZE, fh) != NULL)
+       while (fgets (buffer, sizeof (buffer), fh) != NULL)
        {
-               numfields = strsplit (buffer, fields, 48);
+               fields_num = strsplit (buffer,
+                               fields, STATIC_ARRAY_SIZE (fields));
 
-               if (((numfields - 2) != nfs2_procedures_names_num)
-                               && ((numfields - 2)
-                                       != nfs3_procedures_names_num))
+               if (fields_num < 3)
                        continue;
 
                if (strcmp (fields[0], "proc2") == 0)
                {
-                       int i;
-                       unsigned long long *values;
-
-                       if ((numfields - 2) != nfs2_procedures_names_num)
-                       {
-                               WARNING ("nfs plugin: Wrong "
-                                               "number of fields (= %i) "
-                                               "for NFSv2 statistics.",
-                                               numfields - 2);
-                               continue;
-                       }
-
-                       ssnprintf (plugin_instance, sizeof (plugin_instance),
-                                       "v2%s", inst);
-
-                       values = (unsigned long long *) malloc (nfs2_procedures_names_num * sizeof (unsigned long long));
-                       if (values == NULL)
-                       {
-                               char errbuf[1024];
-                               ERROR ("nfs plugin: malloc "
-                                               "failed: %s",
-                                               sstrerror (errno, errbuf, sizeof (errbuf)));
-                               continue;
-                       }
-
-                       for (i = 0; i < nfs2_procedures_names_num; i++)
-                               values[i] = atoll (fields[i + 2]);
-
-                       nfs_procedures_submit (plugin_instance, values,
+                       nfs_submit_fields (/* version = */ 2, inst,
+                                       fields + 2, (size_t) (fields_num - 2),
                                        nfs2_procedures_names,
                                        nfs2_procedures_names_num);
-
-                       free (values);
                }
                else if (strncmp (fields[0], "proc3", 5) == 0)
                {
-                       int i;
-                       unsigned long long *values;
-
-                       if ((numfields - 2) != nfs3_procedures_names_num)
-                       {
-                               WARNING ("nfs plugin: Wrong "
-                                               "number of fields (= %i) "
-                                               "for NFSv3 statistics.",
-                                               numfields - 2);
-                               continue;
-                       }
-
-                       ssnprintf (plugin_instance, sizeof (plugin_instance),
-                                       "v3%s", inst);
-
-                       values = (unsigned long long *) malloc (nfs3_procedures_names_num * sizeof (unsigned long long));
-                       if (values == NULL)
-                       {
-                               char errbuf[1024];
-                               ERROR ("nfs plugin: malloc "
-                                               "failed: %s",
-                                               sstrerror (errno, errbuf, sizeof (errbuf)));
-                               continue;
-                       }
-
-                       for (i = 0; i < nfs3_procedures_names_num; i++)
-                               values[i] = atoll (fields[i + 2]);
-
-                       nfs_procedures_submit (plugin_instance, values,
+                       nfs_submit_fields (/* version = */ 3, inst,
+                                       fields + 2, (size_t) (fields_num - 2),
                                        nfs3_procedures_names,
                                        nfs3_procedures_names_num);
-
-                       free (values);
                }
-       } /* while (fgets (buffer, BUFSIZE, fh) != NULL) */
-} /* void nfs_read_stats_file */
-#undef BUFSIZE
+       } /* while (fgets) */
+} /* void nfs_read_linux */
+#endif /* KERNEL_LINUX */
 
-#if HAVE_LIBKSTAT && 0
-static void nfs2_read_kstat (kstat_t *ksp, char *inst)
+#if HAVE_LIBKSTAT
+static int nfs_read_kstat (kstat_t *ksp, int nfs_version, char *inst,
+               const char **proc_names, size_t proc_names_num)
 {
-       unsigned long long values[18];
-
-       values[0] = get_kstat_value (ksp, "null");
-       values[1] = get_kstat_value (ksp, "getattr");
-       values[2] = get_kstat_value (ksp, "setattr");
-       values[3] = get_kstat_value (ksp, "root");
-       values[4] = get_kstat_value (ksp, "lookup");
-       values[5] = get_kstat_value (ksp, "readlink");
-       values[6] = get_kstat_value (ksp, "read");
-       values[7] = get_kstat_value (ksp, "wrcache");
-       values[8] = get_kstat_value (ksp, "write");
-       values[9] = get_kstat_value (ksp, "create");
-       values[10] = get_kstat_value (ksp, "remove");
-       values[11] = get_kstat_value (ksp, "rename");
-       values[12] = get_kstat_value (ksp, "link");
-       values[13] = get_kstat_value (ksp, "symlink");
-       values[14] = get_kstat_value (ksp, "mkdir");
-       values[15] = get_kstat_value (ksp, "rmdir");
-       values[16] = get_kstat_value (ksp, "readdir");
-       values[17] = get_kstat_value (ksp, "statfs");
-
-       nfs2_procedures_submit (values, inst);
+       char plugin_instance[DATA_MAX_NAME_LEN];
+       value_t values[proc_names_num];
+       size_t i;
+
+       if (ksp == NULL)
+               return (EINVAL);
+
+       ssnprintf (plugin_instance, sizeof (plugin_instance), "v%i%s",
+                       nfs_version, inst);
+
+       kstat_read(kc, ksp, NULL);
+       for (i = 0; i < proc_names_num; i++)
+               values[i].counter = (derive_t) get_kstat_value (ksp,
+                               (char *)proc_names[i]);
+
+       nfs_procedures_submit (plugin_instance, proc_names, values,
+                       proc_names_num);
+       return (0);
 }
 #endif
 
+#if KERNEL_LINUX
 static int nfs_read (void)
 {
        FILE *fh;
 
        if ((fh = fopen ("/proc/net/rpc/nfs", "r")) != NULL)
        {
-               nfs_read_stats_file (fh, "client");
+               nfs_read_linux (fh, "client");
                fclose (fh);
        }
 
        if ((fh = fopen ("/proc/net/rpc/nfsd", "r")) != NULL)
        {
-               nfs_read_stats_file (fh, "server");
+               nfs_read_linux (fh, "server");
                fclose (fh);
        }
 
-#if HAVE_LIBKSTAT && 0
-       if (nfs2_ksp_client != NULL)
-               nfs2_read_kstat (nfs2_ksp_client, "client");
-       if (nfs2_ksp_server != NULL)
-               nfs2_read_kstat (nfs2_ksp_server, "server");
-#endif /* defined(HAVE_LIBKSTAT) */
+       return (0);
+}
+/* #endif KERNEL_LINUX */
+
+#elif HAVE_LIBKSTAT
+static int nfs_read (void)
+{
+       nfs_read_kstat (nfs2_ksp_client, /* version = */ 2, "client",
+                       nfs2_procedures_names, nfs2_procedures_names_num);
+       nfs_read_kstat (nfs2_ksp_server, /* version = */ 2, "server",
+                       nfs2_procedures_names, nfs2_procedures_names_num);
+       nfs_read_kstat (nfs3_ksp_client, /* version = */ 3, "client",
+                       nfs3_procedures_names, nfs3_procedures_names_num);
+       nfs_read_kstat (nfs3_ksp_server, /* version = */ 3, "server",
+                       nfs3_procedures_names, nfs3_procedures_names_num);
+       nfs_read_kstat (nfs4_ksp_client, /* version = */ 4, "client",
+                       nfs4_procedures_names, nfs4_procedures_names_num);
+       nfs_read_kstat (nfs4_ksp_server, /* version = */ 4, "server",
+                       nfs4_procedures_names, nfs4_procedures_names_num);
 
        return (0);
 }
+#endif /* HAVE_LIBKSTAT */
 
 void module_register (void)
 {
+       plugin_register_init ("nfs", nfs_init);
        plugin_register_read ("nfs", nfs_read);
 } /* void module_register */
index 36d3d8d..3e162ba 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/nginx.c
- * Copyright (C) 2006,2007  Florian octo Forster
+ * Copyright (C) 2006-2010  Florian octo Forster
  * Copyright (C) 2008       Sebastian Harl
  *
  * This program is free software; you can redistribute it and/or modify it
@@ -18,7 +18,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Sebastian Harl <sh at tokkee.org>
  **/
 
@@ -120,6 +120,7 @@ static int init (void)
     return (-1);
   }
 
+  curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1);
   curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, nginx_curl_callback);
   curl_easy_setopt (curl, CURLOPT_USERAGENT, PACKAGE_NAME"/"PACKAGE_VERSION);
   curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, nginx_curl_error);
@@ -178,7 +179,7 @@ static void submit (char *type, char *inst, long long value)
   if (strcmp (type, "nginx_connections") == 0)
     values[0].gauge = value;
   else if (strcmp (type, "nginx_requests") == 0)
-    values[0].counter = value;
+    values[0].derive = value;
   else
     return;
 
index 839bc61..3f3c6df 100644 (file)
 #include <glib.h>
 #include <libnotify/notify.h>
 
+#ifndef NOTIFY_CHECK_VERSION
+# define NOTIFY_CHECK_VERSION(x,y,z) 0
+#endif
+
 #define log_info(...) INFO ("notify_desktop: " __VA_ARGS__)
 #define log_warn(...) WARNING ("notify_desktop: " __VA_ARGS__)
 #define log_err(...) ERROR ("notify_desktop: " __VA_ARGS__)
@@ -95,7 +99,12 @@ static int c_notify (const notification_t *n,
                                : (NOTIF_WARNING == n->severity) ? "WARNING"
                                : (NOTIF_OKAY == n->severity) ? "OKAY" : "UNKNOWN");
 
-       notification = notify_notification_new (summary, n->message, NULL, NULL);
+       notification = notify_notification_new (summary, n->message, NULL
+#if NOTIFY_CHECK_VERSION (0, 7, 0)
+       );
+#else
+       , NULL);
+#endif
        if (NULL == notification) {
                log_err ("Failed to create a new notification.");
                return -1;
index 0aed27f..cd216ca 100644 (file)
@@ -228,8 +228,8 @@ static int notify_email_config (const char *key, const char *value)
 static int notify_email_notification (const notification_t *n,
     user_data_t __attribute__((unused)) *user_data)
 {
-  smtp_recipient_t recipient;
 
+  time_t tt;
   struct tm timestamp_tm;
   char timestamp_str[64];
 
@@ -249,7 +249,8 @@ static int notify_email_notification (const notification_t *n,
       (email_subject == NULL) ? DEFAULT_SMTP_SUBJECT : email_subject,
       severity, n->host);
 
-  localtime_r (&n->time, &timestamp_tm);
+  tt = CDTIME_T_TO_TIME_T (n->time);
+  localtime_r (&tt, &timestamp_tm);
   strftime (timestamp_str, sizeof (timestamp_str), "%Y-%m-%d %H:%M:%S",
       &timestamp_tm);
   timestamp_str[sizeof (timestamp_str) - 1] = '\0';
@@ -288,7 +289,7 @@ static int notify_email_notification (const notification_t *n,
   smtp_set_message_str (message, buf);
 
   for (i = 0; i < recipients_len; i++)
-    recipient = smtp_add_recipient (message, recipients[i]);
+    smtp_add_recipient (message, recipients[i]);
 
   /* Initiate a connection to the SMTP server and transfer the message. */
   if (!smtp_start_session (session)) {
@@ -298,11 +299,13 @@ static int notify_email_notification (const notification_t *n,
     pthread_mutex_unlock (&session_lock);
     return (-1);
   } else {
+    #if COLLECT_DEBUG
     const smtp_status_t *status;
     /* Report on the success or otherwise of the mail transfer. */
     status = smtp_message_transfer_status (message);
     DEBUG ("notify_email plugin: SMTP server report: %d %s",
-        status->code, (status->text != NULL) ? status->text : "\n");
+      status->code, (status->text != NULL) ? status->text : "\n");
+    #endif
     smtp_enumerate_recipients (message, print_recipient_status, NULL);
   }
 
index ecc87c7..bbc455f 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/ntpd.c
- * Copyright (C) 2006-2007  Florian octo Forster
+ * Copyright (C) 2006-2012  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #define _BSD_SOURCE /* For NI_MAXHOST */
@@ -52,11 +52,17 @@ static const char *config_keys[] =
 {
        "Host",
        "Port",
-       "ReverseLookups"
+       "ReverseLookups",
+       "IncludeUnitID"
 };
 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
 
-static int do_reverse_lookups = 1;
+static _Bool do_reverse_lookups = 1;
+
+/* This option only exists for backward compatibility. If it is false and two
+ * ntpd peers use the same refclock driver, the plugin will try to write
+ * simultaneous measurements from both to the same type instance. */
+static _Bool include_unit_id = 0;
 
 # define NTPD_DEFAULT_HOST "localhost"
 # define NTPD_DEFAULT_PORT "123"
@@ -283,6 +289,13 @@ static int ntpd_config (const char *key, const char *value)
                else
                        do_reverse_lookups = 0;
        }
+       else if (strcasecmp (key, "IncludeUnitID") == 0)
+       {
+               if (IS_TRUE (value))
+                       include_unit_id = 1;
+               else
+                       include_unit_id = 0;
+       }
        else
        {
                return (-1);
@@ -309,6 +322,18 @@ static void ntpd_submit (char *type, char *type_inst, double value)
        plugin_dispatch_values (&vl);
 }
 
+/* Each time a peer is polled, ntpd shifts the reach register to the left and
+ * sets the LSB based on whether the peer was reachable. If the LSB is zero,
+ * the values are out of date. */
+static void ntpd_submit_reach (char *type, char *type_inst, uint8_t reach,
+               double value)
+{
+       if (!(reach & 1))
+               value = NAN;
+
+       ntpd_submit (type, type_inst, value);
+}
+
 static int ntpd_connect (void)
 {
        char *host;
@@ -763,6 +788,108 @@ static double ntpd_read_fp (int32_t val_int)
        return (val_double);
 }
 
+static uint32_t ntpd_get_refclock_id (struct info_peer_summary const *peer_info)
+{
+       uint32_t addr = ntohl (peer_info->srcadr);
+       uint32_t refclock_id = (addr >> 8) & 0x00FF;
+
+       return (refclock_id);
+}
+
+static int ntpd_get_name_from_address (char *buffer, size_t buffer_size,
+               struct info_peer_summary const *peer_info, _Bool do_reverse_lookup)
+{
+       struct sockaddr_storage sa;
+       socklen_t sa_len;
+       int flags = 0;
+       int status;
+
+       memset (&sa, 0, sizeof (sa));
+
+       if (peer_info->v6_flag)
+       {
+               struct sockaddr_in6 sa6;
+
+               assert (sizeof (sa) >= sizeof (sa6));
+
+               memset (&sa6, 0, sizeof (sa6));
+               sa6.sin6_family = AF_INET6;
+               sa6.sin6_port = htons (123);
+               memcpy (&sa6.sin6_addr, &peer_info->srcadr6,
+                               sizeof (struct in6_addr));
+               sa_len = sizeof (sa6);
+
+               memcpy (&sa, &sa6, sizeof (sa6));
+       }
+       else
+       {
+               struct sockaddr_in sa4;
+
+               assert (sizeof (sa) >= sizeof (sa4));
+
+               memset (&sa4, 0, sizeof (sa4));
+               sa4.sin_family = AF_INET;
+               sa4.sin_port = htons (123);
+               memcpy (&sa4.sin_addr, &peer_info->srcadr,
+                               sizeof (struct in_addr));
+               sa_len = sizeof (sa4);
+
+               memcpy (&sa, &sa4, sizeof (sa4));
+       }
+
+       if (!do_reverse_lookup)
+               flags |= NI_NUMERICHOST;
+
+       status = getnameinfo ((struct sockaddr const *) &sa, sa_len,
+                       buffer, buffer_size,
+                       NULL, 0, /* No port name */
+                       flags);
+       if (status != 0)
+       {
+               char errbuf[1024];
+               ERROR ("ntpd plugin: getnameinfo failed: %s",
+                               (status == EAI_SYSTEM)
+                               ? sstrerror (errno, errbuf, sizeof (errbuf))
+                               : gai_strerror (status));
+               return (-1);
+       }
+
+       return (0);
+} /* ntpd_get_name_from_address */
+
+static int ntpd_get_name_refclock (char *buffer, size_t buffer_size,
+               struct info_peer_summary const *peer_info)
+{
+       uint32_t refclock_id = ntpd_get_refclock_id (peer_info);
+       uint32_t unit_id = ntohl (peer_info->srcadr) & 0x00FF;
+
+       if (refclock_id >= refclock_names_num)
+               return (ntpd_get_name_from_address (buffer, buffer_size,
+                                       peer_info,
+                                       /* do_reverse_lookup = */ 0));
+
+       if (include_unit_id)
+               ssnprintf (buffer, buffer_size, "%s-%"PRIu32,
+                               refclock_names[refclock_id], unit_id);
+       else
+               sstrncpy (buffer, refclock_names[refclock_id], buffer_size);
+
+       return (0);
+} /* int ntpd_get_name_refclock */
+
+static int ntpd_get_name (char *buffer, size_t buffer_size,
+               struct info_peer_summary const *peer_info)
+{
+       uint32_t addr = ntohl (peer_info->srcadr);
+
+       if (!peer_info->v6_flag && ((addr & REFCLOCK_MASK) == REFCLOCK_ADDR))
+               return (ntpd_get_name_refclock (buffer, buffer_size,
+                                       peer_info));
+       else
+               return (ntpd_get_name_from_address (buffer, buffer_size,
+                                       peer_info, do_reverse_lookups));
+} /* int ntpd_addr_to_name */
+
 static int ntpd_read (void)
 {
        struct info_kernel *ik;
@@ -784,15 +911,15 @@ static int ntpd_read (void)
                        0, 0, NULL, /* request data */
                        &ik_num, &ik_size, (char **) ((void *) &ik), /* response data */
                        sizeof (struct info_kernel));
-
        if (status != 0)
        {
-               DEBUG ("ntpd_do_query failed with status %i", status);
-               return (-1);
+               ERROR ("ntpd plugin: ntpd_do_query (REQ_GET_KERNEL) failed with status %i", status);
+               return (status);
        }
-       if ((ik == NULL) || (ik_num == 0) || (ik_size == 0))
+       else if ((ik == NULL) || (ik_num == 0) || (ik_size == 0))
        {
-               DEBUG ("ntpd_do_query returned: ik = %p; ik_num = %i; ik_size = %i;",
+               ERROR ("ntpd plugin: ntpd_do_query returned unexpected data. "
+                               "(ik = %p; ik_num = %i; ik_size = %i)",
                                (void *) ik, ik_num, ik_size);
                return (-1);
        }
@@ -820,12 +947,13 @@ static int ntpd_read (void)
                        sizeof (struct info_peer_summary));
        if (status != 0)
        {
-               DEBUG ("ntpd_do_query failed with status %i", status);
-               return (-1);
+               ERROR ("ntpd plugin: ntpd_do_query (REQ_PEER_LIST_SUM) failed with status %i", status);
+               return (status);
        }
-       if ((ps == NULL) || (ps_num == 0) || (ps_size == 0))
+       else if ((ps == NULL) || (ps_num == 0) || (ps_size == 0))
        {
-               DEBUG ("ntpd_do_query returned: ps = %p; ps_num = %i; ps_size = %i;",
+               ERROR ("ntpd plugin: ntpd_do_query returned unexpected data. "
+                               "(ps = %p; ps_num = %i; ps_size = %i)",
                                (void *) ps, ps_num, ps_size);
                return (-1);
        }
@@ -836,99 +964,26 @@ static int ntpd_read (void)
                double offset;
 
                char peername[NI_MAXHOST];
-               int refclock_id;
-               
-               ptr = ps + i;
-               refclock_id = 0;
+               uint32_t refclock_id;
 
-               /* Convert the `long floating point' offset value to double */
-               M_LFPTOD (ntohl (ptr->offset_int), ntohl (ptr->offset_frc), offset);
+               ptr = ps + i;
 
-               /* Special IP addresses for hardware clocks and stuff.. */
-               if (!ptr->v6_flag
-                               && ((ntohl (ptr->srcadr) & REFCLOCK_MASK)
-                                       == REFCLOCK_ADDR))
+               status = ntpd_get_name (peername, sizeof (peername), ptr);
+               if (status != 0)
                {
-                       struct in_addr  addr_obj;
-                       char *addr_str;
-
-                       refclock_id = (ntohl (ptr->srcadr) >> 8) & 0x000000FF;
-
-                       if (refclock_id < refclock_names_num)
-                       {
-                               sstrncpy (peername, refclock_names[refclock_id],
-                                               sizeof (peername));
-                       }
-                       else
-                       {
-                               memset ((void *) &addr_obj, '\0', sizeof (addr_obj));
-                               addr_obj.s_addr = ptr->srcadr;
-                               addr_str = inet_ntoa (addr_obj);
-
-                               sstrncpy (peername, addr_str, sizeof (peername));
-                       }
+                       ERROR ("ntpd plugin: Determining name of peer failed.");
+                       continue;
                }
-               else /* Normal network host. */
-               {
-                       struct sockaddr_storage sa;
-                       socklen_t sa_len;
-                       int flags = 0;
-
-                       memset (&sa, '\0', sizeof (sa));
-
-                       if (ptr->v6_flag)
-                       {
-                               struct sockaddr_in6 sa6;
-
-                               assert (sizeof (sa) >= sizeof (sa6));
-
-                               memset (&sa6, 0, sizeof (sa6));
-                               sa6.sin6_family = AF_INET6;
-                               sa6.sin6_port = htons (123);
-                               memcpy (&sa6.sin6_addr, &ptr->srcadr6,
-                                               sizeof (struct in6_addr));
-                               sa_len = sizeof (sa6);
-
-                               memcpy (&sa, &sa6, sizeof (sa6));
-                       }
-                       else
-                       {
-                               struct sockaddr_in sa4;
 
-                               assert (sizeof (sa) >= sizeof (sa4));
+               refclock_id = ntpd_get_refclock_id (ptr);
 
-                               memset (&sa4, 0, sizeof (sa4));
-                               sa4.sin_family = AF_INET;
-                               sa4.sin_port = htons (123);
-                               memcpy (&sa4.sin_addr, &ptr->srcadr,
-                                               sizeof (struct in_addr));
-                               sa_len = sizeof (sa4);
-
-                               memcpy (&sa, &sa4, sizeof (sa4));
-                       }
-
-                       if (do_reverse_lookups == 0)
-                               flags |= NI_NUMERICHOST;
-
-                       status = getnameinfo ((const struct sockaddr *) &sa,
-                                       sa_len,
-                                       peername, sizeof (peername),
-                                       NULL, 0, /* No port name */
-                                       flags);
-                       if (status != 0)
-                       {
-                               char errbuf[1024];
-                               ERROR ("ntpd plugin: getnameinfo failed: %s",
-                                               (status == EAI_SYSTEM)
-                                               ? sstrerror (errno, errbuf, sizeof (errbuf))
-                                               : gai_strerror (status));
-                               continue;
-                       }
-               }
+               /* Convert the `long floating point' offset value to double */
+               M_LFPTOD (ntohl (ptr->offset_int), ntohl (ptr->offset_frc), offset);
 
                DEBUG ("peer %i:\n"
                                "  peername   = %s\n"
                                "  srcadr     = 0x%08x\n"
+                               "  reach      = 0%03o\n"
                                "  delay      = %f\n"
                                "  offset_int = %i\n"
                                "  offset_frc = %i\n"
@@ -937,6 +992,7 @@ static int ntpd_read (void)
                                i,
                                peername,
                                ntohl (ptr->srcadr),
+                               ptr->reach,
                                ntpd_read_fp (ptr->delay),
                                ntohl (ptr->offset_int),
                                ntohl (ptr->offset_frc),
@@ -944,10 +1000,13 @@ static int ntpd_read (void)
                                ntpd_read_fp (ptr->dispersion));
 
                if (refclock_id != 1) /* not the system clock (offset will always be zero.. */
-                       ntpd_submit ("time_offset", peername, offset);
-               ntpd_submit ("time_dispersion", peername, ntpd_read_fp (ptr->dispersion));
+                       ntpd_submit_reach ("time_offset", peername, ptr->reach,
+                                       offset);
+               ntpd_submit_reach ("time_dispersion", peername, ptr->reach,
+                               ntpd_read_fp (ptr->dispersion));
                if (refclock_id == 0) /* not a reference clock */
-                       ntpd_submit ("delay", peername, ntpd_read_fp (ptr->delay));
+                       ntpd_submit_reach ("delay", peername, ptr->reach,
+                                       ntpd_read_fp (ptr->delay));
        }
 
        free (ps);
diff --git a/src/numa.c b/src/numa.c
new file mode 100644 (file)
index 0000000..4b4ef20
--- /dev/null
@@ -0,0 +1,168 @@
+/**
+ * collectd - src/numa.c
+ * Copyright (C) 2012  Florian Forster
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *   Florian Forster <octo at collectd.org>
+ **/
+
+#include "collectd.h"
+#include "common.h"
+#include "plugin.h"
+
+#if !KERNEL_LINUX
+# error "No applicable input method."
+#endif
+
+#ifndef NUMA_ROOT_DIR
+# define NUMA_ROOT_DIR "/sys/devices/system/node"
+#endif
+
+static int max_node = -1;
+
+static void numa_dispatch_value (int node, /* {{{ */
+    const char *type_instance, value_t v)
+{
+  value_list_t vl = VALUE_LIST_INIT;
+
+  vl.values = &v;
+  vl.values_len = 1;
+
+  sstrncpy (vl.host, hostname_g, sizeof (vl.host));
+  sstrncpy (vl.plugin, "numa", sizeof (vl.plugin));
+  ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance), "node%i", node);
+  sstrncpy (vl.type, "vmpage_action", sizeof (vl.type));
+  sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
+
+  plugin_dispatch_values (&vl);
+} /* }}} void numa_dispatch_value */
+
+static int numa_read_node (int node) /* {{{ */
+{
+  char path[PATH_MAX];
+  FILE *fh;
+  char buffer[128];
+  int status;
+  int success;
+
+  ssnprintf (path, sizeof (path), NUMA_ROOT_DIR "/node%i/numastat", node);
+
+  fh = fopen (path, "r");
+  if (fh == NULL)
+  {
+    char errbuf[1024];
+    ERROR ("numa plugin: Reading node %i failed: open(%s): %s",
+        node, path, sstrerror (errno, errbuf, sizeof (errbuf)));
+    return (-1);
+  }
+
+  success = 0;
+  while (fgets (buffer, sizeof (buffer), fh) != NULL)
+  {
+    char *fields[4];
+    value_t v;
+
+    status = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
+    if (status != 2)
+    {
+      WARNING ("numa plugin: Ignoring line with unexpected "
+          "number of fields (node %i).", node);
+      continue;
+    }
+
+    v.derive = 0;
+    status = parse_value (fields[1], &v, DS_TYPE_DERIVE);
+    if (status != 0)
+      continue;
+
+    numa_dispatch_value (node, fields[0], v);
+    success++;
+  }
+
+  fclose (fh);
+  return (success ? 0 : -1);
+} /* }}} int numa_read_node */
+
+static int numa_read (void) /* {{{ */
+{
+  int i;
+  int status;
+  int success;
+
+  if (max_node < 0)
+  {
+    WARNING ("numa plugin: No NUMA nodes were detected.");
+    return (-1);
+  }
+
+  success = 0;
+  for (i = 0; i <= max_node; i++)
+  {
+    status = numa_read_node (i);
+    if (status == 0)
+      success++;
+  }
+
+  return (success ? 0 : -1);
+} /* }}} int numa_read */
+
+static int numa_init (void) /* {{{ */
+{
+  /* Determine the number of nodes on this machine. */
+  while (42)
+  {
+    char path[PATH_MAX];
+    struct stat statbuf;
+    int status;
+
+    ssnprintf (path, sizeof (path), NUMA_ROOT_DIR "/node%i", max_node + 1);
+    memset (&statbuf, 0, sizeof (statbuf));
+
+    status = stat (path, &statbuf);
+    if (status == 0)
+    {
+      max_node++;
+      continue;
+    }
+    else if (errno == ENOENT)
+    {
+      break;
+    }
+    else /* ((status != 0) && (errno != ENOENT)) */
+    {
+      char errbuf[1024];
+      ERROR ("numa plugin: stat(%s) failed: %s", path,
+          sstrerror (errno, errbuf, sizeof (errbuf)));
+      return (-1);
+    }
+  }
+
+  DEBUG ("numa plugin: Found %i nodes.", max_node + 1);
+  return (0);
+} /* }}} int numa_init */
+
+void module_register (void)
+{
+  plugin_register_init ("numa", numa_init);
+  plugin_register_read ("numa", numa_read);
+} /* void module_register */
+
+/* vim: set sw=2 sts=2 et : */
index 462458c..09a6bf0 100644 (file)
@@ -59,7 +59,7 @@ static ow_family_features_t ow_family_features[] =
 static int ow_family_features_num = STATIC_ARRAY_SIZE (ow_family_features);
 
 static char *device_g = NULL;
-static int   ow_interval = 0;
+static cdtime_t ow_interval = 0;
 
 static const char *config_keys[] =
 {
@@ -106,10 +106,10 @@ static int cow_load_config (const char *key, const char *value)
   }
   else if (strcasecmp ("Interval", key) == 0)
   {
-    int tmp;
-    tmp = atoi (value);
-    if (tmp > 0)
-      ow_interval = tmp;
+    double tmp;
+    tmp = atof (value);
+    if (tmp > 0.0)
+      ow_interval = DOUBLE_TO_CDTIME_T (tmp);
     else
       ERROR ("onewire plugin: Invalid `Interval' setting: %s", value);
   }
@@ -306,12 +306,11 @@ static int cow_init (void)
     return (1);
   }
 
-  memset (&cb_interval, 0, sizeof (cb_interval));
-  if (ow_interval > 0)
-    cb_interval.tv_sec = (time_t) ow_interval;
+  CDTIME_T_TO_TIMESPEC (ow_interval, &cb_interval);
 
   plugin_register_complex_read (/* group = */ NULL, "onewire", cow_read,
-      &cb_interval, /* user data = */ NULL);
+      (ow_interval != 0) ? &cb_interval : NULL,
+      /* user data = */ NULL);
   plugin_register_shutdown ("onewire", cow_shutdown);
 
   return (0);
index 2aca414..9ce23b4 100644 (file)
@@ -1,9 +1,9 @@
 /**
  * collectd - src/openvpn.c
- * Copyright (C) 2008  Doug MacEachern
- * Copyright (C) 2009  Florian octo Forster
- * Copyright (C) 2009  Marco Chiappero
- * Copyright (C) 2009  Fabian Schuh
+ * Copyright (C) 2008       Doug MacEachern
+ * Copyright (C) 2009,2010  Florian octo Forster
+ * Copyright (C) 2009       Marco Chiappero
+ * Copyright (C) 2009       Fabian Schuh
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -20,7 +20,7 @@
  *
  * Authors:
  *   Doug MacEachern <dougm at hyperic.com>
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Marco Chiappero <marco at absence.it>
  *   Fabian Schuh <mail at xeroc.org>
  **/
@@ -114,13 +114,13 @@ static void numusers_submit (char *pinst, char *tinst, gauge_t value)
 } /* void numusers_submit */
 
 /* dispatches stats about traffic (TCP or UDP) generated by the tunnel per single endpoint */
-static void iostats_submit (char *pinst, char *tinst, counter_t rx, counter_t tx)
+static void iostats_submit (char *pinst, char *tinst, derive_t rx, derive_t tx)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = rx;
-       values[1].counter = tx;
+       values[0].derive = rx;
+       values[1].derive = tx;
 
        /* NOTE ON THE NEW NAMING SCHEMA:
         *       using plugin_instance to identify each vpn config (and
@@ -144,13 +144,13 @@ static void iostats_submit (char *pinst, char *tinst, counter_t rx, counter_t tx
 
 /* dispatches stats about data compression shown when in single mode */
 static void compression_submit (char *pinst, char *tinst,
-               counter_t uncompressed, counter_t compressed)
+               derive_t uncompressed, derive_t compressed)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = uncompressed;
-       values[1].counter = compressed;
+       values[0].derive = uncompressed;
+       values[1].derive = compressed;
 
        vl.values = values;
        vl.values_len = STATIC_ARRAY_SIZE (values);
@@ -173,11 +173,11 @@ static int single_read (char *name, FILE *fh)
        const int max_fields = STATIC_ARRAY_SIZE (fields);
        int  fields_num, read = 0;
 
-       counter_t link_rx, link_tx;
-       counter_t tun_rx, tun_tx;
-       counter_t pre_compress, post_compress;
-       counter_t pre_decompress, post_decompress;
-       counter_t overhead_rx, overhead_tx;
+       derive_t link_rx, link_tx;
+       derive_t tun_rx, tun_tx;
+       derive_t pre_compress, post_compress;
+       derive_t pre_decompress, post_decompress;
+       derive_t overhead_rx, overhead_tx;
 
        link_rx = 0;
        link_tx = 0;
index 2f21851..ab0812b 100644 (file)
@@ -1,6 +1,7 @@
 /**
  * collectd - src/oracle.c
- * Copyright (C) 2008,2009  Florian octo Forster
+ * Copyright (C) 2008,2009  noris network AG
+ * Copyright (C) 2012       Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -41,7 +42,7 @@
  * affiliates. Other names may be trademarks of their respective owners.
  *
  * Authors:
- *   Florian octo Forster <octo at noris.net>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
@@ -58,6 +59,7 @@
 struct o_database_s
 {
   char *name;
+  char *host;
   char *connect_id;
   char *username;
   char *password;
@@ -85,38 +87,58 @@ OCIError *oci_error = NULL;
  * Functions
  */
 static void o_report_error (const char *where, /* {{{ */
+    const char *db_name, const char *query_name,
     const char *what, OCIError *eh)
 {
   char buffer[2048];
   sb4 error_code;
   int status;
+  unsigned int record_number;
 
-  status = OCIErrorGet (eh, /* record number = */ 1,
-      /* sqlstate = */ NULL,
-      &error_code,
-      (text *) &buffer[0],
-      (ub4) sizeof (buffer),
-      OCI_HTYPE_ERROR);
-  buffer[sizeof (buffer) - 1] = 0;
+  if (db_name == NULL)
+    db_name = "(none)";
+  if (query_name == NULL)
+    query_name = "(none)";
 
-  if (status == OCI_SUCCESS)
+  /* An operation may cause / return multiple errors. Loop until we have
+   * handled all errors available (with a fail-save limit of 16). */
+  for (record_number = 1; record_number <= 16; record_number++)
   {
-    size_t buffer_length;
+    memset (buffer, 0, sizeof (buffer));
+    error_code = -1;
 
-    buffer_length = strlen (buffer);
-    while ((buffer_length > 0) && (buffer[buffer_length - 1] < 32))
+    status = OCIErrorGet (eh, (ub4) record_number,
+        /* sqlstate = */ NULL,
+        &error_code,
+        (text *) &buffer[0],
+        (ub4) sizeof (buffer),
+        OCI_HTYPE_ERROR);
+    buffer[sizeof (buffer) - 1] = 0;
+
+    if (status == OCI_NO_DATA)
+      return;
+
+    if (status == OCI_SUCCESS)
     {
-      buffer_length--;
-      buffer[buffer_length] = 0;
-    }
+      size_t buffer_length;
 
-    ERROR ("oracle plugin: %s: %s failed: %s",
-        where, what, buffer);
-  }
-  else
-  {
-    ERROR ("oracle plugin: %s: %s failed. Additionally, OCIErrorGet failed with status %i.",
-        where, what, status);
+      buffer_length = strlen (buffer);
+      while ((buffer_length > 0) && (buffer[buffer_length - 1] < 32))
+      {
+        buffer_length--;
+        buffer[buffer_length] = 0;
+      }
+
+      ERROR ("oracle plugin: %s (db = %s, query = %s): %s failed: %s",
+          where, db_name, query_name, what, buffer);
+    }
+    else
+    {
+      ERROR ("oracle plugin: %s (db = %s, query = %s): %s failed. "
+          "Additionally, OCIErrorGet failed with status %i.",
+          where, db_name, query_name, what, status);
+      return;
+    }
   }
 } /* }}} void o_report_error */
 
@@ -162,33 +184,6 @@ static void o_database_free (o_database_t *db) /* {{{ */
  * </Plugin>
  */
 
-static int o_config_set_string (char **ret_string, /* {{{ */
-    oconfig_item_t *ci)
-{
-  char *string;
-
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_STRING))
-  {
-    WARNING ("oracle plugin: The `%s' config option "
-        "needs exactly one string argument.", ci->key);
-    return (-1);
-  }
-
-  string = strdup (ci->values[0].value.string);
-  if (string == NULL)
-  {
-    ERROR ("oracle plugin: strdup failed.");
-    return (-1);
-  }
-
-  if (*ret_string != NULL)
-    free (*ret_string);
-  *ret_string = string;
-
-  return (0);
-} /* }}} int o_config_set_string */
-
 static int o_config_add_database (oconfig_item_t *ci) /* {{{ */
 {
   o_database_t *db;
@@ -210,8 +205,13 @@ static int o_config_add_database (oconfig_item_t *ci) /* {{{ */
     return (-1);
   }
   memset (db, 0, sizeof (*db));
+  db->name = NULL;
+  db->host = NULL;
+  db->connect_id = NULL;
+  db->username = NULL;
+  db->password = NULL;
 
-  status = o_config_set_string (&db->name, ci);
+  status = cf_util_get_string (ci, &db->name);
   if (status != 0)
   {
     sfree (db);
@@ -224,11 +224,13 @@ static int o_config_add_database (oconfig_item_t *ci) /* {{{ */
     oconfig_item_t *child = ci->children + i;
 
     if (strcasecmp ("ConnectID", child->key) == 0)
-      status = o_config_set_string (&db->connect_id, child);
+      status = cf_util_get_string (child, &db->connect_id);
+    else if (strcasecmp ("Host", child->key) == 0)
+      status = cf_util_get_string (child, &db->host);
     else if (strcasecmp ("Username", child->key) == 0)
-      status = o_config_set_string (&db->username, child);
+      status = cf_util_get_string (child, &db->username);
     else if (strcasecmp ("Password", child->key) == 0)
-      status = o_config_set_string (&db->password, child);
+      status = cf_util_get_string (child, &db->password);
     else if (strcasecmp ("Query", child->key) == 0)
       status = udb_query_pick_from_list (child, queries, queries_num,
           &db->queries, &db->queries_num);
@@ -414,7 +416,8 @@ static int o_read_database_query (o_database_t *db, /* {{{ */
         OCI_HTYPE_STMT, /* user_data_size = */ 0, /* user_data = */ NULL);
     if (status != OCI_SUCCESS)
     {
-      o_report_error ("o_read_database_query", "OCIHandleAlloc", oci_error);
+      o_report_error ("o_read_database_query", db->name,
+          udb_query_get_name (q), "OCIHandleAlloc", oci_error);
       oci_statement = NULL;
       return (-1);
     }
@@ -425,7 +428,8 @@ static int o_read_database_query (o_database_t *db, /* {{{ */
         /* mode     = */ OCI_DEFAULT);
     if (status != OCI_SUCCESS)
     {
-      o_report_error ("o_read_database_query", "OCIStmtPrepare", oci_error);
+      o_report_error ("o_read_database_query", db->name,
+          udb_query_get_name (q), "OCIStmtPrepare", oci_error);
       OCIHandleFree (oci_statement, OCI_HTYPE_STMT);
       oci_statement = NULL;
       return (-1);
@@ -449,10 +453,8 @@ static int o_read_database_query (o_database_t *db, /* {{{ */
       /* mode = */ OCI_DEFAULT);
   if (status != OCI_SUCCESS)
   {
-    DEBUG ("oracle plugin: o_read_database_query: status = %i (%#x)", status, status);
-    o_report_error ("o_read_database_query", "OCIStmtExecute", oci_error);
-    ERROR ("oracle plugin: o_read_database_query: "
-        "Failing statement was: %s", udb_query_get_statement (q));
+    o_report_error ("o_read_database_query", db->name, udb_query_get_name (q),
+        "OCIStmtExecute", oci_error);
     return (-1);
   } /* }}} */
 
@@ -465,7 +467,8 @@ static int o_read_database_query (o_database_t *db, /* {{{ */
         OCI_ATTR_PARAM_COUNT, oci_error);
     if (status != OCI_SUCCESS)
     {
-      o_report_error ("o_read_database_query", "OCIAttrGet", oci_error);
+      o_report_error ("o_read_database_query", db->name,
+          udb_query_get_name (q), "OCIAttrGet", oci_error);
       return (-1);
     } /* }}} */
 
@@ -543,8 +546,10 @@ static int o_read_database_query (o_database_t *db, /* {{{ */
     if (status != OCI_SUCCESS)
     {
       /* This is probably alright */
-      DEBUG ("oracle plugin: o_read_database_query: status = %#x (= %i);", status, status);
-      o_report_error ("o_read_database_query", "OCIParamGet", oci_error);
+      DEBUG ("oracle plugin: o_read_database_query: status = %#x (= %i);",
+          status, status);
+      o_report_error ("o_read_database_query", db->name,
+          udb_query_get_name (q), "OCIParamGet", oci_error);
       status = OCI_SUCCESS;
       break;
     }
@@ -555,11 +560,15 @@ static int o_read_database_query (o_database_t *db, /* {{{ */
         &column_name, &column_name_length, OCI_ATTR_NAME, oci_error);
     if (status != OCI_SUCCESS)
     {
-      o_report_error ("o_read_database_query", "OCIAttrGet (OCI_ATTR_NAME)",
-          oci_error);
+      OCIDescriptorFree (oci_param, OCI_DTYPE_PARAM);
+      o_report_error ("o_read_database_query", db->name,
+          udb_query_get_name (q), "OCIAttrGet (OCI_ATTR_NAME)", oci_error);
       continue;
     }
 
+    OCIDescriptorFree (oci_param, OCI_DTYPE_PARAM);
+    oci_param = NULL;
+
     /* Copy the name to column_names. Warning: The ``string'' returned by OCI
      * may not be null terminated! */
     memset (column_names[i], 0, DATA_MAX_NAME_LEN);
@@ -578,15 +587,17 @@ static int o_read_database_query (o_database_t *db, /* {{{ */
         NULL, NULL, NULL, OCI_DEFAULT);
     if (status != OCI_SUCCESS)
     {
-      o_report_error ("o_read_database_query", "OCIDefineByPos", oci_error);
+      o_report_error ("o_read_database_query", db->name,
+          udb_query_get_name (q), "OCIDefineByPos", oci_error);
       continue;
     }
   } /* for (j = 1; j <= param_counter; j++) */
   /* }}} End of the ``define'' stuff. */
 
-  status = udb_query_prepare_result (q, prep_area, hostname_g,
+  status = udb_query_prepare_result (q, prep_area,
+      (db->host != NULL) ? db->host : hostname_g,
       /* plugin = */ "oracle", db->name, column_names, column_num,
-      /* interval = */ -1);
+      /* interval = */ 0);
   if (status != 0)
   {
     ERROR ("oracle plugin: o_read_database_query (%s, %s): "
@@ -609,7 +620,8 @@ static int o_read_database_query (o_database_t *db, /* {{{ */
     }
     else if ((status != OCI_SUCCESS) && (status != OCI_SUCCESS_WITH_INFO))
     {
-      o_report_error ("o_read_database_query", "OCIStmtFetch2", oci_error);
+      o_report_error ("o_read_database_query", db->name,
+          udb_query_get_name (q), "OCIStmtFetch2", oci_error);
       break;
     }
 
@@ -646,7 +658,8 @@ static int o_read_database (o_database_t *db) /* {{{ */
         OCI_ATTR_SERVER, oci_error);
     if (status != OCI_SUCCESS)
     {
-      o_report_error ("o_read_database", "OCIAttrGet", oci_error);
+      o_report_error ("o_read_database", db->name, NULL, "OCIAttrGet",
+          oci_error);
       return (-1);
     }
 
@@ -662,7 +675,8 @@ static int o_read_database (o_database_t *db) /* {{{ */
           OCI_ATTR_SERVER_STATUS, oci_error);
       if (status != OCI_SUCCESS)
       {
-        o_report_error ("o_read_database", "OCIAttrGet", oci_error);
+        o_report_error ("o_read_database", db->name, NULL, "OCIAttrGet",
+            oci_error);
         return (-1);
       }
     }
@@ -683,14 +697,22 @@ static int o_read_database (o_database_t *db) /* {{{ */
         (OraText *) db->username, (ub4) strlen (db->username),
         (OraText *) db->password, (ub4) strlen (db->password),
         (OraText *) db->connect_id, (ub4) strlen (db->connect_id));
-    if (status != OCI_SUCCESS)
+    if ((status != OCI_SUCCESS) && (status != OCI_SUCCESS_WITH_INFO))
     {
-      o_report_error ("o_read_database", "OCILogon", oci_error);
+      char errfunc[256];
+
+      ssnprintf (errfunc, sizeof (errfunc), "OCILogon(\"%s\")", db->connect_id);
+
+      o_report_error ("o_read_database", db->name, NULL, errfunc, oci_error);
       DEBUG ("oracle plugin: OCILogon (%s): db->oci_service_context = %p;",
           db->connect_id, db->oci_service_context);
       db->oci_service_context = NULL;
       return (-1);
     }
+    else if (status == OCI_SUCCESS_WITH_INFO)
+    {
+      /* TODO: Print NOTIFY message. */
+    }
     assert (db->oci_service_context != NULL);
   }
 
@@ -737,6 +759,7 @@ static int o_shutdown (void) /* {{{ */
   }
   
   OCIHandleFree (oci_env, OCI_HTYPE_ENV);
+  oci_env = NULL;
 
   udb_query_free (queries, queries_num);
   queries = NULL;
diff --git a/src/owniptc/Makefile.am b/src/owniptc/Makefile.am
deleted file mode 100644 (file)
index d51e993..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-AUTOMAKE_OPTIONS = foreign no-dependencies
-
-EXTRA_DIST = libiptc.c README.collectd
-
-if COMPILER_IS_GCC
-AM_CFLAGS = -Wall -Werror
-endif
-
-noinst_LTLIBRARIES = libiptc.la
-
-libiptc_la_SOURCES = libip4tc.c libip6tc.c \
-               ipt_kernel_headers.h libip6tc.h libiptc.h linux_list.h \
-               xtables.h libxtc.h
-
diff --git a/src/owniptc/README.collectd b/src/owniptc/README.collectd
deleted file mode 100644 (file)
index adb53b0..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
- libiptc (IPTables Chains) in collectd
-=======================================
-http://netfilter.org/
-http://collectd.org/
-
-About
------
-
-  This is libiptc taken from the iptables source distribution. As it is not
-  meant to be a public interface by upstream it is not shipped in some binary
-  distributions. Thus, collectd ships its own copy as a fall-back.
-
-  The presently available version was imported from iptables 1.4.1.1.
-
-Changes to the iptables upstream sources:
------------------------------------------
-
-  * Added copyright headers mentioning the "Netfilter Core Team" as copyright
-    holder.
-
-  * Changed "libiptc/*" includes to "*".
-
-  * Use the shipped copy of "xtables.h" instead of the one possibly available
-    on the system.
-
diff --git a/src/owniptc/ipt_kernel_headers.h b/src/owniptc/ipt_kernel_headers.h
deleted file mode 100644 (file)
index bf81f6e..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * This file was imported from the iptables sources.
- * Copyright (C) 1999-2008 Netfilter Core Team
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- */
-
-/* This is the userspace/kernel interface for Generic IP Chains,
-   required for libc6. */
-#ifndef _FWCHAINS_KERNEL_HEADERS_H
-#define _FWCHAINS_KERNEL_HEADERS_H
-
-#include <limits.h>
-
-#if defined(__GLIBC__) && __GLIBC__ == 2
-#include <netinet/ip.h>
-#include <netinet/in.h>
-#include <netinet/ip_icmp.h>
-#include <netinet/tcp.h>
-#include <netinet/udp.h>
-#include <net/if.h>
-#include <sys/types.h>
-#else /* libc5 */
-#include <sys/socket.h>
-#include <linux/ip.h>
-#include <linux/in.h>
-#include <linux/if.h>
-#include <linux/icmp.h>
-#include <linux/tcp.h>
-#include <linux/udp.h>
-#include <linux/types.h>
-#include <linux/in6.h>
-#endif
-#endif
diff --git a/src/owniptc/libip4tc.c b/src/owniptc/libip4tc.c
deleted file mode 100644 (file)
index bf7327c..0000000
+++ /dev/null
@@ -1,517 +0,0 @@
-/**
- * This file was imported from the iptables sources.
- * Copyright (C) 1999-2008 Netfilter Core Team
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- */
-
-/* Library which manipulates firewall rules.  Version 0.1. */
-
-/* Architecture of firewall rules is as follows:
- *
- * Chains go INPUT, FORWARD, OUTPUT then user chains.
- * Each user chain starts with an ERROR node.
- * Every chain ends with an unconditional jump: a RETURN for user chains,
- * and a POLICY for built-ins.
- */
-
-/* (C)1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See
-   COPYING for details). */
-
-#include <assert.h>
-#include <string.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <unistd.h>
-
-#ifdef DEBUG_CONNTRACK
-#define inline
-#endif
-
-#if !defined(__GLIBC__) || (__GLIBC__ < 2)
-typedef unsigned int socklen_t;
-#endif
-
-#include "libiptc.h"
-
-#define IP_VERSION     4
-#define IP_OFFSET      0x1FFF
-
-#define HOOK_PRE_ROUTING       NF_IP_PRE_ROUTING
-#define HOOK_LOCAL_IN          NF_IP_LOCAL_IN
-#define HOOK_FORWARD           NF_IP_FORWARD
-#define HOOK_LOCAL_OUT         NF_IP_LOCAL_OUT
-#define HOOK_POST_ROUTING      NF_IP_POST_ROUTING
-#ifdef NF_IP_DROPPING
-#define HOOK_DROPPING          NF_IP_DROPPING
-#endif
-
-#define STRUCT_ENTRY_TARGET    struct ipt_entry_target
-#define STRUCT_ENTRY           struct ipt_entry
-#define STRUCT_ENTRY_MATCH     struct ipt_entry_match
-#define STRUCT_GETINFO         struct ipt_getinfo
-#define STRUCT_GET_ENTRIES     struct ipt_get_entries
-#define STRUCT_COUNTERS                struct ipt_counters
-#define STRUCT_COUNTERS_INFO   struct ipt_counters_info
-#define STRUCT_STANDARD_TARGET struct ipt_standard_target
-#define STRUCT_REPLACE         struct ipt_replace
-
-#define STRUCT_TC_HANDLE       struct iptc_handle
-#define TC_HANDLE_T            iptc_handle_t
-
-#define ENTRY_ITERATE          IPT_ENTRY_ITERATE
-#define TABLE_MAXNAMELEN       IPT_TABLE_MAXNAMELEN
-#define FUNCTION_MAXNAMELEN    IPT_FUNCTION_MAXNAMELEN
-
-#define GET_TARGET             ipt_get_target
-
-#define ERROR_TARGET           IPT_ERROR_TARGET
-#define NUMHOOKS               NF_IP_NUMHOOKS
-
-#define IPT_CHAINLABEL         ipt_chainlabel
-
-#define TC_DUMP_ENTRIES                dump_entries
-#define TC_IS_CHAIN            iptc_is_chain
-#define TC_FIRST_CHAIN         iptc_first_chain
-#define TC_NEXT_CHAIN          iptc_next_chain
-#define TC_FIRST_RULE          iptc_first_rule
-#define TC_NEXT_RULE           iptc_next_rule
-#define TC_GET_TARGET          iptc_get_target
-#define TC_BUILTIN             iptc_builtin
-#define TC_GET_POLICY          iptc_get_policy
-#define TC_INSERT_ENTRY                iptc_insert_entry
-#define TC_REPLACE_ENTRY       iptc_replace_entry
-#define TC_APPEND_ENTRY                iptc_append_entry
-#define TC_DELETE_ENTRY                iptc_delete_entry
-#define TC_DELETE_NUM_ENTRY    iptc_delete_num_entry
-#define TC_CHECK_PACKET                iptc_check_packet
-#define TC_FLUSH_ENTRIES       iptc_flush_entries
-#define TC_ZERO_ENTRIES                iptc_zero_entries
-#define TC_READ_COUNTER                iptc_read_counter
-#define TC_ZERO_COUNTER                iptc_zero_counter
-#define TC_SET_COUNTER         iptc_set_counter
-#define TC_CREATE_CHAIN                iptc_create_chain
-#define TC_GET_REFERENCES      iptc_get_references
-#define TC_DELETE_CHAIN                iptc_delete_chain
-#define TC_RENAME_CHAIN                iptc_rename_chain
-#define TC_SET_POLICY          iptc_set_policy
-#define TC_GET_RAW_SOCKET      iptc_get_raw_socket
-#define TC_INIT                        iptc_init
-#define TC_FREE                        iptc_free
-#define TC_COMMIT              iptc_commit
-#define TC_STRERROR            iptc_strerror
-#define TC_NUM_RULES           iptc_num_rules
-#define TC_GET_RULE            iptc_get_rule
-
-#define TC_AF                  AF_INET
-#define TC_IPPROTO             IPPROTO_IP
-
-#define SO_SET_REPLACE         IPT_SO_SET_REPLACE
-#define SO_SET_ADD_COUNTERS    IPT_SO_SET_ADD_COUNTERS
-#define SO_GET_INFO            IPT_SO_GET_INFO
-#define SO_GET_ENTRIES         IPT_SO_GET_ENTRIES
-#define SO_GET_VERSION         IPT_SO_GET_VERSION
-
-#define STANDARD_TARGET                IPT_STANDARD_TARGET
-#define LABEL_RETURN           IPTC_LABEL_RETURN
-#define LABEL_ACCEPT           IPTC_LABEL_ACCEPT
-#define LABEL_DROP             IPTC_LABEL_DROP
-#define LABEL_QUEUE            IPTC_LABEL_QUEUE
-
-#define ALIGN                  IPT_ALIGN
-#define RETURN                 IPT_RETURN
-
-#include "libiptc.c"
-
-#define IP_PARTS_NATIVE(n)                     \
-(unsigned int)((n)>>24)&0xFF,                  \
-(unsigned int)((n)>>16)&0xFF,                  \
-(unsigned int)((n)>>8)&0xFF,                   \
-(unsigned int)((n)&0xFF)
-
-#define IP_PARTS(n) IP_PARTS_NATIVE(ntohl(n))
-
-int
-dump_entry(STRUCT_ENTRY *e, const TC_HANDLE_T handle)
-{
-       size_t i;
-       STRUCT_ENTRY_TARGET *t;
-
-       printf("Entry %u (%lu):\n", iptcb_entry2index(handle, e),
-              iptcb_entry2offset(handle, e));
-       printf("SRC IP: %u.%u.%u.%u/%u.%u.%u.%u\n",
-              IP_PARTS(e->ip.src.s_addr),IP_PARTS(e->ip.smsk.s_addr));
-       printf("DST IP: %u.%u.%u.%u/%u.%u.%u.%u\n",
-              IP_PARTS(e->ip.dst.s_addr),IP_PARTS(e->ip.dmsk.s_addr));
-       printf("Interface: `%s'/", e->ip.iniface);
-       for (i = 0; i < IFNAMSIZ; i++)
-               printf("%c", e->ip.iniface_mask[i] ? 'X' : '.');
-       printf("to `%s'/", e->ip.outiface);
-       for (i = 0; i < IFNAMSIZ; i++)
-               printf("%c", e->ip.outiface_mask[i] ? 'X' : '.');
-       printf("\nProtocol: %u\n", e->ip.proto);
-       printf("Flags: %02X\n", e->ip.flags);
-       printf("Invflags: %02X\n", e->ip.invflags);
-       printf("Counters: %llu packets, %llu bytes\n",
-              (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);
-       printf("Cache: %08X\n", e->nfcache);
-
-       IPT_MATCH_ITERATE(e, print_match);
-
-       t = GET_TARGET(e);
-       printf("Target name: `%s' [%u]\n", t->u.user.name, t->u.target_size);
-       if (strcmp(t->u.user.name, STANDARD_TARGET) == 0) {
-               const unsigned char *data = t->data;
-               int pos = *(const int *)data;
-               if (pos < 0)
-                       printf("verdict=%s\n",
-                              pos == -NF_ACCEPT-1 ? "NF_ACCEPT"
-                              : pos == -NF_DROP-1 ? "NF_DROP"
-                              : pos == -NF_QUEUE-1 ? "NF_QUEUE"
-                              : pos == RETURN ? "RETURN"
-                              : "UNKNOWN");
-               else
-                       printf("verdict=%u\n", pos);
-       } else if (strcmp(t->u.user.name, IPT_ERROR_TARGET) == 0)
-               printf("error=`%s'\n", t->data);
-
-       printf("\n");
-       return 0;
-}
-
-static unsigned char *
-is_same(const STRUCT_ENTRY *a, const STRUCT_ENTRY *b, unsigned char *matchmask)
-{
-       unsigned int i;
-       unsigned char *mptr;
-
-       /* Always compare head structures: ignore mask here. */
-       if (a->ip.src.s_addr != b->ip.src.s_addr
-           || a->ip.dst.s_addr != b->ip.dst.s_addr
-           || a->ip.smsk.s_addr != b->ip.smsk.s_addr
-           || a->ip.dmsk.s_addr != b->ip.dmsk.s_addr
-           || a->ip.proto != b->ip.proto
-           || a->ip.flags != b->ip.flags
-           || a->ip.invflags != b->ip.invflags)
-               return NULL;
-
-       for (i = 0; i < IFNAMSIZ; i++) {
-               if (a->ip.iniface_mask[i] != b->ip.iniface_mask[i])
-                       return NULL;
-               if ((a->ip.iniface[i] & a->ip.iniface_mask[i])
-                   != (b->ip.iniface[i] & b->ip.iniface_mask[i]))
-                       return NULL;
-               if (a->ip.outiface_mask[i] != b->ip.outiface_mask[i])
-                       return NULL;
-               if ((a->ip.outiface[i] & a->ip.outiface_mask[i])
-                   != (b->ip.outiface[i] & b->ip.outiface_mask[i]))
-                       return NULL;
-       }
-
-       if (a->target_offset != b->target_offset
-           || a->next_offset != b->next_offset)
-               return NULL;
-
-       mptr = matchmask + sizeof(STRUCT_ENTRY);
-       if (IPT_MATCH_ITERATE(a, match_different, a->elems, b->elems, &mptr))
-               return NULL;
-       mptr += IPT_ALIGN(sizeof(struct ipt_entry_target));
-
-       return mptr;
-}
-
-#if 0
-/***************************** DEBUGGING ********************************/
-static inline int
-unconditional(const struct ipt_ip *ip)
-{
-       unsigned int i;
-
-       for (i = 0; i < sizeof(*ip)/sizeof(u_int32_t); i++)
-               if (((u_int32_t *)ip)[i])
-                       return 0;
-
-       return 1;
-}
-
-static inline int
-check_match(const STRUCT_ENTRY_MATCH *m, unsigned int *off)
-{
-       assert(m->u.match_size >= sizeof(STRUCT_ENTRY_MATCH));
-       assert(ALIGN(m->u.match_size) == m->u.match_size);
-
-       (*off) += m->u.match_size;
-       return 0;
-}
-
-static inline int
-check_entry(const STRUCT_ENTRY *e, unsigned int *i, unsigned int *off,
-           unsigned int user_offset, int *was_return,
-           TC_HANDLE_T h)
-{
-       unsigned int toff;
-       STRUCT_STANDARD_TARGET *t;
-
-       assert(e->target_offset >= sizeof(STRUCT_ENTRY));
-       assert(e->next_offset >= e->target_offset
-              + sizeof(STRUCT_ENTRY_TARGET));
-       toff = sizeof(STRUCT_ENTRY);
-       IPT_MATCH_ITERATE(e, check_match, &toff);
-
-       assert(toff == e->target_offset);
-
-       t = (STRUCT_STANDARD_TARGET *)
-               GET_TARGET((STRUCT_ENTRY *)e);
-       /* next_offset will have to be multiple of entry alignment. */
-       assert(e->next_offset == ALIGN(e->next_offset));
-       assert(e->target_offset == ALIGN(e->target_offset));
-       assert(t->target.u.target_size == ALIGN(t->target.u.target_size));
-       assert(!TC_IS_CHAIN(t->target.u.user.name, h));
-
-       if (strcmp(t->target.u.user.name, STANDARD_TARGET) == 0) {
-               assert(t->target.u.target_size
-                      == ALIGN(sizeof(STRUCT_STANDARD_TARGET)));
-
-               assert(t->verdict == -NF_DROP-1
-                      || t->verdict == -NF_ACCEPT-1
-                      || t->verdict == RETURN
-                      || t->verdict < (int)h->entries->size);
-
-               if (t->verdict >= 0) {
-                       STRUCT_ENTRY *te = get_entry(h, t->verdict);
-                       int idx;
-
-                       idx = iptcb_entry2index(h, te);
-                       assert(strcmp(GET_TARGET(te)->u.user.name,
-                                     IPT_ERROR_TARGET)
-                              != 0);
-                       assert(te != e);
-
-                       /* Prior node must be error node, or this node. */
-                       assert(t->verdict == iptcb_entry2offset(h, e)+e->next_offset
-                              || strcmp(GET_TARGET(index2entry(h, idx-1))
-                                        ->u.user.name, IPT_ERROR_TARGET)
-                              == 0);
-               }
-
-               if (t->verdict == RETURN
-                   && unconditional(&e->ip)
-                   && e->target_offset == sizeof(*e))
-                       *was_return = 1;
-               else
-                       *was_return = 0;
-       } else if (strcmp(t->target.u.user.name, IPT_ERROR_TARGET) == 0) {
-               assert(t->target.u.target_size
-                      == ALIGN(sizeof(struct ipt_error_target)));
-
-               /* If this is in user area, previous must have been return */
-               if (*off > user_offset)
-                       assert(*was_return);
-
-               *was_return = 0;
-       }
-       else *was_return = 0;
-
-       if (*off == user_offset)
-               assert(strcmp(t->target.u.user.name, IPT_ERROR_TARGET) == 0);
-
-       (*off) += e->next_offset;
-       (*i)++;
-       return 0;
-}
-
-#ifdef IPTC_DEBUG
-/* Do every conceivable sanity check on the handle */
-static void
-do_check(TC_HANDLE_T h, unsigned int line)
-{
-       unsigned int i, n;
-       unsigned int user_offset; /* Offset of first user chain */
-       int was_return;
-
-       assert(h->changed == 0 || h->changed == 1);
-       if (strcmp(h->info.name, "filter") == 0) {
-               assert(h->info.valid_hooks
-                      == (1 << NF_IP_LOCAL_IN
-                          | 1 << NF_IP_FORWARD
-                          | 1 << NF_IP_LOCAL_OUT));
-
-               /* Hooks should be first three */
-               assert(h->info.hook_entry[NF_IP_LOCAL_IN] == 0);
-
-               n = get_chain_end(h, 0);
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP_FORWARD] == n);
-
-               n = get_chain_end(h, n);
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n);
-
-               user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT];
-       } else if (strcmp(h->info.name, "nat") == 0) {
-               assert((h->info.valid_hooks
-                       == (1 << NF_IP_PRE_ROUTING
-                           | 1 << NF_IP_POST_ROUTING
-                           | 1 << NF_IP_LOCAL_OUT)) ||
-                      (h->info.valid_hooks
-                       == (1 << NF_IP_PRE_ROUTING
-                           | 1 << NF_IP_LOCAL_IN
-                           | 1 << NF_IP_POST_ROUTING
-                           | 1 << NF_IP_LOCAL_OUT)));
-
-               assert(h->info.hook_entry[NF_IP_PRE_ROUTING] == 0);
-
-               n = get_chain_end(h, 0);
-
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP_POST_ROUTING] == n);
-               n = get_chain_end(h, n);
-
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n);
-               user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT];
-
-               if (h->info.valid_hooks & (1 << NF_IP_LOCAL_IN)) {
-                       n = get_chain_end(h, n);
-                       n += get_entry(h, n)->next_offset;
-                       assert(h->info.hook_entry[NF_IP_LOCAL_IN] == n);
-                       user_offset = h->info.hook_entry[NF_IP_LOCAL_IN];
-               }
-
-       } else if (strcmp(h->info.name, "mangle") == 0) {
-               /* This code is getting ugly because linux < 2.4.18-pre6 had
-                * two mangle hooks, linux >= 2.4.18-pre6 has five mangle hooks
-                * */
-               assert((h->info.valid_hooks
-                       == (1 << NF_IP_PRE_ROUTING
-                           | 1 << NF_IP_LOCAL_OUT)) || 
-                      (h->info.valid_hooks
-                       == (1 << NF_IP_PRE_ROUTING
-                           | 1 << NF_IP_LOCAL_IN
-                           | 1 << NF_IP_FORWARD
-                           | 1 << NF_IP_LOCAL_OUT
-                           | 1 << NF_IP_POST_ROUTING)));
-
-               /* Hooks should be first five */
-               assert(h->info.hook_entry[NF_IP_PRE_ROUTING] == 0);
-
-               n = get_chain_end(h, 0);
-
-               if (h->info.valid_hooks & (1 << NF_IP_LOCAL_IN)) {
-                       n += get_entry(h, n)->next_offset;
-                       assert(h->info.hook_entry[NF_IP_LOCAL_IN] == n);
-                       n = get_chain_end(h, n);
-               }
-
-               if (h->info.valid_hooks & (1 << NF_IP_FORWARD)) {
-                       n += get_entry(h, n)->next_offset;
-                       assert(h->info.hook_entry[NF_IP_FORWARD] == n);
-                       n = get_chain_end(h, n);
-               }
-
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n);
-               user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT];
-
-               if (h->info.valid_hooks & (1 << NF_IP_POST_ROUTING)) {
-                       n = get_chain_end(h, n);
-                       n += get_entry(h, n)->next_offset;
-                       assert(h->info.hook_entry[NF_IP_POST_ROUTING] == n);
-                       user_offset = h->info.hook_entry[NF_IP_POST_ROUTING];
-               }
-       } else if (strcmp(h->info.name, "raw") == 0) {
-               assert(h->info.valid_hooks
-                      == (1 << NF_IP_PRE_ROUTING
-                          | 1 << NF_IP_LOCAL_OUT));
-
-               /* Hooks should be first three */
-               assert(h->info.hook_entry[NF_IP_PRE_ROUTING] == 0);
-
-               n = get_chain_end(h, n);
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n);
-
-               user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT];
-
-#ifdef NF_IP_DROPPING
-       } else if (strcmp(h->info.name, "drop") == 0) {
-               assert(h->info.valid_hooks == (1 << NF_IP_DROPPING));
-
-               /* Hook should be first */
-               assert(h->info.hook_entry[NF_IP_DROPPING] == 0);
-               user_offset = 0;
-#endif
-       } else {
-               fprintf(stderr, "Unknown table `%s'\n", h->info.name);
-               abort();
-       }
-
-       /* User chain == end of last builtin + policy entry */
-       user_offset = get_chain_end(h, user_offset);
-       user_offset += get_entry(h, user_offset)->next_offset;
-
-       /* Overflows should be end of entry chains, and unconditional
-           policy nodes. */
-       for (i = 0; i < NUMHOOKS; i++) {
-               STRUCT_ENTRY *e;
-               STRUCT_STANDARD_TARGET *t;
-
-               if (!(h->info.valid_hooks & (1 << i)))
-                       continue;
-               assert(h->info.underflow[i]
-                      == get_chain_end(h, h->info.hook_entry[i]));
-
-               e = get_entry(h, get_chain_end(h, h->info.hook_entry[i]));
-               assert(unconditional(&e->ip));
-               assert(e->target_offset == sizeof(*e));
-               t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
-               assert(t->target.u.target_size == ALIGN(sizeof(*t)));
-               assert(e->next_offset == sizeof(*e) + ALIGN(sizeof(*t)));
-
-               assert(strcmp(t->target.u.user.name, STANDARD_TARGET)==0);
-               assert(t->verdict == -NF_DROP-1 || t->verdict == -NF_ACCEPT-1);
-
-               /* Hooks and underflows must be valid entries */
-               entry2index(h, get_entry(h, h->info.hook_entry[i]));
-               entry2index(h, get_entry(h, h->info.underflow[i]));
-       }
-
-       assert(h->info.size
-              >= h->info.num_entries * (sizeof(STRUCT_ENTRY)
-                                        +sizeof(STRUCT_STANDARD_TARGET)));
-
-       assert(h->entries.size
-              >= (h->new_number
-                  * (sizeof(STRUCT_ENTRY)
-                     + sizeof(STRUCT_STANDARD_TARGET))));
-       assert(strcmp(h->info.name, h->entries.name) == 0);
-
-       i = 0; n = 0;
-       was_return = 0;
-       /* Check all the entries. */
-       ENTRY_ITERATE(h->entries.entrytable, h->entries.size,
-                     check_entry, &i, &n, user_offset, &was_return, h);
-
-       assert(i == h->new_number);
-       assert(n == h->entries.size);
-
-       /* Final entry must be error node */
-       assert(strcmp(GET_TARGET(index2entry(h, h->new_number-1))
-                     ->u.user.name,
-                     ERROR_TARGET) == 0);
-}
-#endif /*IPTC_DEBUG*/
-
-#endif
diff --git a/src/owniptc/libip6tc.c b/src/owniptc/libip6tc.c
deleted file mode 100644 (file)
index 672dae1..0000000
+++ /dev/null
@@ -1,456 +0,0 @@
-/**
- * This file was imported from the iptables sources.
- * Copyright (C) 1999-2008 Netfilter Core Team
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- */
-
-/* Library which manipulates firewall rules.  Version 0.1. */
-
-/* Architecture of firewall rules is as follows:
- *
- * Chains go INPUT, FORWARD, OUTPUT then user chains.
- * Each user chain starts with an ERROR node.
- * Every chain ends with an unconditional jump: a RETURN for user chains,
- * and a POLICY for built-ins.
- */
-
-/* (C)1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See
-   COPYING for details). */
-
-#include <assert.h>
-#include <string.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <arpa/inet.h>
-
-#ifdef DEBUG_CONNTRACK
-#define inline
-#endif
-
-#if !defined(__GLIBC__) || (__GLIBC__ < 2)
-typedef unsigned int socklen_t;
-#endif
-
-#include "libip6tc.h"
-
-#define HOOK_PRE_ROUTING       NF_IP6_PRE_ROUTING
-#define HOOK_LOCAL_IN          NF_IP6_LOCAL_IN
-#define HOOK_FORWARD           NF_IP6_FORWARD
-#define HOOK_LOCAL_OUT         NF_IP6_LOCAL_OUT
-#define HOOK_POST_ROUTING      NF_IP6_POST_ROUTING
-
-#define STRUCT_ENTRY_TARGET    struct ip6t_entry_target
-#define STRUCT_ENTRY           struct ip6t_entry
-#define STRUCT_ENTRY_MATCH     struct ip6t_entry_match
-#define STRUCT_GETINFO         struct ip6t_getinfo
-#define STRUCT_GET_ENTRIES     struct ip6t_get_entries
-#define STRUCT_COUNTERS                struct ip6t_counters
-#define STRUCT_COUNTERS_INFO   struct ip6t_counters_info
-#define STRUCT_STANDARD_TARGET struct ip6t_standard_target
-#define STRUCT_REPLACE         struct ip6t_replace
-
-#define STRUCT_TC_HANDLE       struct ip6tc_handle
-#define TC_HANDLE_T            ip6tc_handle_t
-
-#define ENTRY_ITERATE          IP6T_ENTRY_ITERATE
-#define TABLE_MAXNAMELEN       IP6T_TABLE_MAXNAMELEN
-#define FUNCTION_MAXNAMELEN    IP6T_FUNCTION_MAXNAMELEN
-
-#define GET_TARGET             ip6t_get_target
-
-#define ERROR_TARGET           IP6T_ERROR_TARGET
-#define NUMHOOKS               NF_IP6_NUMHOOKS
-
-#define IPT_CHAINLABEL         ip6t_chainlabel
-
-#define TC_DUMP_ENTRIES                dump_entries6
-#define TC_IS_CHAIN            ip6tc_is_chain
-#define TC_FIRST_CHAIN         ip6tc_first_chain
-#define TC_NEXT_CHAIN          ip6tc_next_chain
-#define TC_FIRST_RULE          ip6tc_first_rule
-#define TC_NEXT_RULE           ip6tc_next_rule
-#define TC_GET_TARGET          ip6tc_get_target
-#define TC_BUILTIN             ip6tc_builtin
-#define TC_GET_POLICY          ip6tc_get_policy
-#define TC_INSERT_ENTRY                ip6tc_insert_entry
-#define TC_REPLACE_ENTRY       ip6tc_replace_entry
-#define TC_APPEND_ENTRY                ip6tc_append_entry
-#define TC_DELETE_ENTRY                ip6tc_delete_entry
-#define TC_DELETE_NUM_ENTRY    ip6tc_delete_num_entry
-#define TC_CHECK_PACKET                ip6tc_check_packet
-#define TC_FLUSH_ENTRIES       ip6tc_flush_entries
-#define TC_ZERO_ENTRIES                ip6tc_zero_entries
-#define TC_ZERO_COUNTER                ip6tc_zero_counter
-#define TC_READ_COUNTER                ip6tc_read_counter
-#define TC_SET_COUNTER         ip6tc_set_counter
-#define TC_CREATE_CHAIN                ip6tc_create_chain
-#define TC_GET_REFERENCES      ip6tc_get_references
-#define TC_DELETE_CHAIN                ip6tc_delete_chain
-#define TC_RENAME_CHAIN                ip6tc_rename_chain
-#define TC_SET_POLICY          ip6tc_set_policy
-#define TC_GET_RAW_SOCKET      ip6tc_get_raw_socket
-#define TC_INIT                        ip6tc_init
-#define TC_FREE                        ip6tc_free
-#define TC_COMMIT              ip6tc_commit
-#define TC_STRERROR            ip6tc_strerror
-#define TC_NUM_RULES           ip6tc_num_rules
-#define TC_GET_RULE            ip6tc_get_rule
-
-#define TC_AF                  AF_INET6
-#define TC_IPPROTO             IPPROTO_IPV6
-
-#define SO_SET_REPLACE         IP6T_SO_SET_REPLACE
-#define SO_SET_ADD_COUNTERS    IP6T_SO_SET_ADD_COUNTERS
-#define SO_GET_INFO            IP6T_SO_GET_INFO
-#define SO_GET_ENTRIES         IP6T_SO_GET_ENTRIES
-#define SO_GET_VERSION         IP6T_SO_GET_VERSION
-
-#define STANDARD_TARGET                IP6T_STANDARD_TARGET
-#define LABEL_RETURN           IP6TC_LABEL_RETURN
-#define LABEL_ACCEPT           IP6TC_LABEL_ACCEPT
-#define LABEL_DROP             IP6TC_LABEL_DROP
-#define LABEL_QUEUE            IP6TC_LABEL_QUEUE
-
-#define ALIGN                  IP6T_ALIGN
-#define RETURN                 IP6T_RETURN
-
-#include "libiptc.c"
-
-#define BIT6(a, l) \
- ((ntohl(a->s6_addr32[(l) / 32]) >> (31 - ((l) & 31))) & 1)
-
-int
-ipv6_prefix_length(const struct in6_addr *a)
-{
-       int l, i;
-       for (l = 0; l < 128; l++) {
-               if (BIT6(a, l) == 0)
-                       break;
-       }
-       for (i = l + 1; i < 128; i++) {
-               if (BIT6(a, i) == 1)
-                       return -1;
-       }
-       return l;
-}
-
-static int
-dump_entry(struct ip6t_entry *e, const ip6tc_handle_t handle)
-{
-       size_t i;
-       char buf[40];
-       int len;
-       struct ip6t_entry_target *t;
-       
-       printf("Entry %u (%lu):\n", iptcb_entry2index(handle, e),
-              iptcb_entry2offset(handle, e));
-       puts("SRC IP: ");
-       inet_ntop(AF_INET6, &e->ipv6.src, buf, sizeof buf);
-       puts(buf);
-       putchar('/');
-       len = ipv6_prefix_length(&e->ipv6.smsk);
-       if (len != -1)
-               printf("%d", len);
-       else {
-               inet_ntop(AF_INET6, &e->ipv6.smsk, buf, sizeof buf);
-               puts(buf);
-       }
-       putchar('\n');
-       
-       puts("DST IP: ");
-       inet_ntop(AF_INET6, &e->ipv6.dst, buf, sizeof buf);
-       puts(buf);
-       putchar('/');
-       len = ipv6_prefix_length(&e->ipv6.dmsk);
-       if (len != -1)
-               printf("%d", len);
-       else {
-               inet_ntop(AF_INET6, &e->ipv6.dmsk, buf, sizeof buf);
-               puts(buf);
-       }
-       putchar('\n');
-       
-       printf("Interface: `%s'/", e->ipv6.iniface);
-       for (i = 0; i < IFNAMSIZ; i++)
-               printf("%c", e->ipv6.iniface_mask[i] ? 'X' : '.');
-       printf("to `%s'/", e->ipv6.outiface);
-       for (i = 0; i < IFNAMSIZ; i++)
-               printf("%c", e->ipv6.outiface_mask[i] ? 'X' : '.');
-       printf("\nProtocol: %u\n", e->ipv6.proto);
-       if (e->ipv6.flags & IP6T_F_TOS)
-               printf("TOS: %u\n", e->ipv6.tos);
-       printf("Flags: %02X\n", e->ipv6.flags);
-       printf("Invflags: %02X\n", e->ipv6.invflags);
-       printf("Counters: %llu packets, %llu bytes\n",
-              (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);
-       printf("Cache: %08X\n", e->nfcache);
-       
-       IP6T_MATCH_ITERATE(e, print_match);
-
-       t = ip6t_get_target(e);
-       printf("Target name: `%s' [%u]\n", t->u.user.name, t->u.target_size);
-       if (strcmp(t->u.user.name, IP6T_STANDARD_TARGET) == 0) {
-               const unsigned char *data = t->data;
-               int pos = *(const int *)data;
-               if (pos < 0)
-                       printf("verdict=%s\n",
-                              pos == -NF_ACCEPT-1 ? "NF_ACCEPT"
-                              : pos == -NF_DROP-1 ? "NF_DROP"
-                              : pos == IP6T_RETURN ? "RETURN"
-                              : "UNKNOWN");
-               else
-                       printf("verdict=%u\n", pos);
-       } else if (strcmp(t->u.user.name, IP6T_ERROR_TARGET) == 0)
-               printf("error=`%s'\n", t->data);
-
-       printf("\n");
-       return 0;
-}
-
-static unsigned char *
-is_same(const STRUCT_ENTRY *a, const STRUCT_ENTRY *b,
-       unsigned char *matchmask)
-{
-       unsigned int i;
-       unsigned char *mptr;
-
-       /* Always compare head structures: ignore mask here. */
-       if (memcmp(&a->ipv6.src, &b->ipv6.src, sizeof(struct in6_addr))
-           || memcmp(&a->ipv6.dst, &b->ipv6.dst, sizeof(struct in6_addr))
-           || memcmp(&a->ipv6.smsk, &b->ipv6.smsk, sizeof(struct in6_addr))
-           || memcmp(&a->ipv6.dmsk, &b->ipv6.dmsk, sizeof(struct in6_addr))
-           || a->ipv6.proto != b->ipv6.proto
-           || a->ipv6.tos != b->ipv6.tos
-           || a->ipv6.flags != b->ipv6.flags
-           || a->ipv6.invflags != b->ipv6.invflags)
-               return NULL;
-
-       for (i = 0; i < IFNAMSIZ; i++) {
-               if (a->ipv6.iniface_mask[i] != b->ipv6.iniface_mask[i])
-                       return NULL;
-               if ((a->ipv6.iniface[i] & a->ipv6.iniface_mask[i])
-                   != (b->ipv6.iniface[i] & b->ipv6.iniface_mask[i]))
-                       return NULL;
-               if (a->ipv6.outiface_mask[i] != b->ipv6.outiface_mask[i])
-                       return NULL;
-               if ((a->ipv6.outiface[i] & a->ipv6.outiface_mask[i])
-                   != (b->ipv6.outiface[i] & b->ipv6.outiface_mask[i]))
-                       return NULL;
-       }
-
-       if (a->target_offset != b->target_offset
-           || a->next_offset != b->next_offset)
-               return NULL;
-
-       mptr = matchmask + sizeof(STRUCT_ENTRY);
-       if (IP6T_MATCH_ITERATE(a, match_different, a->elems, b->elems, &mptr))
-               return NULL;
-       mptr += IP6T_ALIGN(sizeof(struct ip6t_entry_target));
-
-       return mptr;
-}
-
-/* All zeroes == unconditional rule. */
-static inline int
-unconditional(const struct ip6t_ip6 *ipv6)
-{
-       unsigned int i;
-
-       for (i = 0; i < sizeof(*ipv6); i++)
-               if (((char *)ipv6)[i])
-                       break;
-
-       return (i == sizeof(*ipv6));
-}
-
-#ifdef IPTC_DEBUG
-/* Do every conceivable sanity check on the handle */
-static void
-do_check(TC_HANDLE_T h, unsigned int line)
-{
-       unsigned int i, n;
-       unsigned int user_offset; /* Offset of first user chain */
-       int was_return;
-
-       assert(h->changed == 0 || h->changed == 1);
-       if (strcmp(h->info.name, "filter") == 0) {
-               assert(h->info.valid_hooks
-                      == (1 << NF_IP6_LOCAL_IN
-                          | 1 << NF_IP6_FORWARD
-                          | 1 << NF_IP6_LOCAL_OUT));
-
-               /* Hooks should be first three */
-               assert(h->info.hook_entry[NF_IP6_LOCAL_IN] == 0);
-
-               n = get_chain_end(h, 0);
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP6_FORWARD] == n);
-
-               n = get_chain_end(h, n);
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n);
-
-               user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT];
-       } else if (strcmp(h->info.name, "nat") == 0) {
-               assert((h->info.valid_hooks
-                       == (1 << NF_IP6_PRE_ROUTING
-                           | 1 << NF_IP6_LOCAL_OUT
-                           | 1 << NF_IP6_POST_ROUTING)) ||
-                      (h->info.valid_hooks
-                       == (1 << NF_IP6_PRE_ROUTING
-                           | 1 << NF_IP6_LOCAL_IN
-                           | 1 << NF_IP6_LOCAL_OUT
-                           | 1 << NF_IP6_POST_ROUTING)));
-
-               assert(h->info.hook_entry[NF_IP6_PRE_ROUTING] == 0);
-
-               n = get_chain_end(h, 0);
-
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP6_POST_ROUTING] == n);
-               n = get_chain_end(h, n);
-
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n);
-               user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT];
-
-               if (h->info.valid_hooks & (1 << NF_IP6_LOCAL_IN)) {
-                       n = get_chain_end(h, n);
-                       n += get_entry(h, n)->next_offset;
-                       assert(h->info.hook_entry[NF_IP6_LOCAL_IN] == n);
-                       user_offset = h->info.hook_entry[NF_IP6_LOCAL_IN];
-               }
-
-       } else if (strcmp(h->info.name, "mangle") == 0) {
-               /* This code is getting ugly because linux < 2.4.18-pre6 had
-                * two mangle hooks, linux >= 2.4.18-pre6 has five mangle hooks
-                * */
-               assert((h->info.valid_hooks
-                       == (1 << NF_IP6_PRE_ROUTING
-                           | 1 << NF_IP6_LOCAL_OUT)) ||
-                      (h->info.valid_hooks
-                       == (1 << NF_IP6_PRE_ROUTING
-                           | 1 << NF_IP6_LOCAL_IN
-                           | 1 << NF_IP6_FORWARD
-                           | 1 << NF_IP6_LOCAL_OUT
-                           | 1 << NF_IP6_POST_ROUTING)));
-
-               /* Hooks should be first five */
-               assert(h->info.hook_entry[NF_IP6_PRE_ROUTING] == 0);
-
-               n = get_chain_end(h, 0);
-
-               if (h->info.valid_hooks & (1 << NF_IP6_LOCAL_IN)) {
-                       n += get_entry(h, n)->next_offset;
-                       assert(h->info.hook_entry[NF_IP6_LOCAL_IN] == n);
-                       n = get_chain_end(h, n);
-               }
-
-               if (h->info.valid_hooks & (1 << NF_IP6_FORWARD)) {
-                       n += get_entry(h, n)->next_offset;
-                       assert(h->info.hook_entry[NF_IP6_FORWARD] == n);
-                       n = get_chain_end(h, n);
-               }
-
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n);
-               user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT];
-
-               if (h->info.valid_hooks & (1 << NF_IP6_POST_ROUTING)) {
-                       n = get_chain_end(h, n);
-                       n += get_entry(h, n)->next_offset;
-                       assert(h->info.hook_entry[NF_IP6_POST_ROUTING] == n);
-                       user_offset = h->info.hook_entry[NF_IP6_POST_ROUTING];
-               }
-       } else if (strcmp(h->info.name, "raw") == 0) {
-               assert(h->info.valid_hooks
-                      == (1 << NF_IP6_PRE_ROUTING
-                          | 1 << NF_IP6_LOCAL_OUT));
-
-               /* Hooks should be first three */
-               assert(h->info.hook_entry[NF_IP6_PRE_ROUTING] == 0);
-
-               n = get_chain_end(h, n);
-               n += get_entry(h, n)->next_offset;
-               assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n);
-
-               user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT];
-       } else {
-                fprintf(stderr, "Unknown table `%s'\n", h->info.name);
-               abort();
-       }
-
-       /* User chain == end of last builtin + policy entry */
-       user_offset = get_chain_end(h, user_offset);
-       user_offset += get_entry(h, user_offset)->next_offset;
-
-       /* Overflows should be end of entry chains, and unconditional
-           policy nodes. */
-       for (i = 0; i < NUMHOOKS; i++) {
-               STRUCT_ENTRY *e;
-               STRUCT_STANDARD_TARGET *t;
-
-               if (!(h->info.valid_hooks & (1 << i)))
-                       continue;
-               assert(h->info.underflow[i]
-                      == get_chain_end(h, h->info.hook_entry[i]));
-
-               e = get_entry(h, get_chain_end(h, h->info.hook_entry[i]));
-               assert(unconditional(&e->ipv6));
-               assert(e->target_offset == sizeof(*e));
-               t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
-               printf("target_size=%u, align=%u\n",
-                       t->target.u.target_size, ALIGN(sizeof(*t)));
-               assert(t->target.u.target_size == ALIGN(sizeof(*t)));
-               assert(e->next_offset == sizeof(*e) + ALIGN(sizeof(*t)));
-
-               assert(strcmp(t->target.u.user.name, STANDARD_TARGET)==0);
-               assert(t->verdict == -NF_DROP-1 || t->verdict == -NF_ACCEPT-1);
-
-               /* Hooks and underflows must be valid entries */
-               iptcb_entry2index(h, get_entry(h, h->info.hook_entry[i]));
-               iptcb_entry2index(h, get_entry(h, h->info.underflow[i]));
-       }
-
-       assert(h->info.size
-              >= h->info.num_entries * (sizeof(STRUCT_ENTRY)
-                                        +sizeof(STRUCT_STANDARD_TARGET)));
-
-       assert(h->entries.size
-              >= (h->new_number
-                  * (sizeof(STRUCT_ENTRY)
-                     + sizeof(STRUCT_STANDARD_TARGET))));
-       assert(strcmp(h->info.name, h->entries.name) == 0);
-
-       i = 0; n = 0;
-       was_return = 0;
-
-#if 0
-       /* Check all the entries. */
-       ENTRY_ITERATE(h->entries.entrytable, h->entries.size,
-                     check_entry, &i, &n, user_offset, &was_return, h);
-
-       assert(i == h->new_number);
-       assert(n == h->entries.size);
-
-       /* Final entry must be error node */
-       assert(strcmp(GET_TARGET(index2entry(h, h->new_number-1))
-                     ->u.user.name,
-                     ERROR_TARGET) == 0);
-#endif
-}
-#endif /*IPTC_DEBUG*/
diff --git a/src/owniptc/libip6tc.h b/src/owniptc/libip6tc.h
deleted file mode 100644 (file)
index 9253e11..0000000
+++ /dev/null
@@ -1,175 +0,0 @@
-/**
- * This file was imported from the iptables sources.
- * Copyright (C) 1999-2008 Netfilter Core Team
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- */
-
-#ifndef _LIBIP6TC_H
-#define _LIBIP6TC_H
-/* Library which manipulates firewall rules. Version 0.2. */
-
-#include <linux/types.h>
-#include "ipt_kernel_headers.h"
-#include <linux/netfilter_ipv6/ip6_tables.h>
-
-#ifndef IP6T_MIN_ALIGN
-#define IP6T_MIN_ALIGN (__alignof__(struct ip6t_entry))
-#endif
-#define IP6T_ALIGN(s) (((s) + (IP6T_MIN_ALIGN-1)) & ~(IP6T_MIN_ALIGN-1))
-
-typedef char ip6t_chainlabel[32];
-
-#define IP6TC_LABEL_ACCEPT "ACCEPT"
-#define IP6TC_LABEL_DROP "DROP"
-#define IP6TC_LABEL_QUEUE   "QUEUE"
-#define IP6TC_LABEL_RETURN "RETURN"
-
-/* Transparent handle type. */
-typedef struct ip6tc_handle *ip6tc_handle_t;
-
-/* Does this chain exist? */
-int ip6tc_is_chain(const char *chain, const ip6tc_handle_t handle);
-
-/* Take a snapshot of the rules. Returns NULL on error. */
-ip6tc_handle_t ip6tc_init(const char *tablename);
-
-/* Cleanup after ip6tc_init(). */
-void ip6tc_free(ip6tc_handle_t *h);
-
-/* Iterator functions to run through the chains.  Returns NULL at end. */
-const char *ip6tc_first_chain(ip6tc_handle_t *handle);
-const char *ip6tc_next_chain(ip6tc_handle_t *handle);
-
-/* Get first rule in the given chain: NULL for empty chain. */
-const struct ip6t_entry *ip6tc_first_rule(const char *chain,
-                                         ip6tc_handle_t *handle);
-
-/* Returns NULL when rules run out. */
-const struct ip6t_entry *ip6tc_next_rule(const struct ip6t_entry *prev,
-                                        ip6tc_handle_t *handle);
-
-/* Returns a pointer to the target name of this position. */
-const char *ip6tc_get_target(const struct ip6t_entry *e,
-                            ip6tc_handle_t *handle);
-
-/* Is this a built-in chain? */
-int ip6tc_builtin(const char *chain, const ip6tc_handle_t handle);
-
-/* Get the policy of a given built-in chain */
-const char *ip6tc_get_policy(const char *chain,
-                            struct ip6t_counters *counters,
-                            ip6tc_handle_t *handle);
-
-/* These functions return TRUE for OK or 0 and set errno. If errno ==
-   0, it means there was a version error (ie. upgrade libiptc). */
-/* Rule numbers start at 1 for the first rule. */
-
-/* Insert the entry `fw' in chain `chain' into position `rulenum'. */
-int ip6tc_insert_entry(const ip6t_chainlabel chain,
-                      const struct ip6t_entry *e,
-                      unsigned int rulenum,
-                      ip6tc_handle_t *handle);
-
-/* Atomically replace rule `rulenum' in `chain' with `fw'. */
-int ip6tc_replace_entry(const ip6t_chainlabel chain,
-                       const struct ip6t_entry *e,
-                       unsigned int rulenum,
-                       ip6tc_handle_t *handle);
-
-/* Append entry `fw' to chain `chain'. Equivalent to insert with
-   rulenum = length of chain. */
-int ip6tc_append_entry(const ip6t_chainlabel chain,
-                      const struct ip6t_entry *e,
-                      ip6tc_handle_t *handle);
-
-/* Delete the first rule in `chain' which matches `fw'. */
-int ip6tc_delete_entry(const ip6t_chainlabel chain,
-                      const struct ip6t_entry *origfw,
-                      unsigned char *matchmask,
-                      ip6tc_handle_t *handle);
-
-/* Delete the rule in position `rulenum' in `chain'. */
-int ip6tc_delete_num_entry(const ip6t_chainlabel chain,
-                          unsigned int rulenum,
-                          ip6tc_handle_t *handle);
-
-/* Check the packet `fw' on chain `chain'. Returns the verdict, or
-   NULL and sets errno. */
-const char *ip6tc_check_packet(const ip6t_chainlabel chain,
-                              struct ip6t_entry *,
-                              ip6tc_handle_t *handle);
-
-/* Flushes the entries in the given chain (ie. empties chain). */
-int ip6tc_flush_entries(const ip6t_chainlabel chain,
-                       ip6tc_handle_t *handle);
-
-/* Zeroes the counters in a chain. */
-int ip6tc_zero_entries(const ip6t_chainlabel chain,
-                      ip6tc_handle_t *handle);
-
-/* Creates a new chain. */
-int ip6tc_create_chain(const ip6t_chainlabel chain,
-                      ip6tc_handle_t *handle);
-
-/* Deletes a chain. */
-int ip6tc_delete_chain(const ip6t_chainlabel chain,
-                      ip6tc_handle_t *handle);
-
-/* Renames a chain. */
-int ip6tc_rename_chain(const ip6t_chainlabel oldname,
-                      const ip6t_chainlabel newname,
-                      ip6tc_handle_t *handle);
-
-/* Sets the policy on a built-in chain. */
-int ip6tc_set_policy(const ip6t_chainlabel chain,
-                    const ip6t_chainlabel policy,
-                    struct ip6t_counters *counters,
-                    ip6tc_handle_t *handle);
-
-/* Get the number of references to this chain */
-int ip6tc_get_references(unsigned int *ref, const ip6t_chainlabel chain,
-                        ip6tc_handle_t *handle);
-
-/* read packet and byte counters for a specific rule */
-struct ip6t_counters *ip6tc_read_counter(const ip6t_chainlabel chain,
-                                       unsigned int rulenum,
-                                       ip6tc_handle_t *handle);
-
-/* zero packet and byte counters for a specific rule */
-int ip6tc_zero_counter(const ip6t_chainlabel chain,
-                      unsigned int rulenum,
-                      ip6tc_handle_t *handle);
-
-/* set packet and byte counters for a specific rule */
-int ip6tc_set_counter(const ip6t_chainlabel chain,
-                     unsigned int rulenum,
-                     struct ip6t_counters *counters,
-                     ip6tc_handle_t *handle);
-
-/* Makes the actual changes. */
-int ip6tc_commit(ip6tc_handle_t *handle);
-
-/* Get raw socket. */
-int ip6tc_get_raw_socket(void);
-
-/* Translates errno numbers into more human-readable form than strerror. */
-const char *ip6tc_strerror(int err);
-
-/* Return prefix length, or -1 if not contiguous */
-int ipv6_prefix_length(const struct in6_addr *a);
-
-extern void dump_entries6(const ip6tc_handle_t);
-
-#endif /* _LIBIP6TC_H */
diff --git a/src/owniptc/libiptc.c b/src/owniptc/libiptc.c
deleted file mode 100644 (file)
index 8f0b0f0..0000000
+++ /dev/null
@@ -1,2716 +0,0 @@
-/**
- * This file was imported from the iptables sources.
- * Copyright (C) 1999-2008 Netfilter Core Team
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- */
-
-/* Library which manipulates firewall rules.  Version $Revision: 7138 $ */
-
-/* Architecture of firewall rules is as follows:
- *
- * Chains go INPUT, FORWARD, OUTPUT then user chains.
- * Each user chain starts with an ERROR node.
- * Every chain ends with an unconditional jump: a RETURN for user chains,
- * and a POLICY for built-ins.
- */
-
-/* (C) 1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See
- * COPYING for details). 
- * (C) 2000-2004 by the Netfilter Core Team <coreteam@netfilter.org>
- *
- * 2003-Jun-20: Harald Welte <laforge@netfilter.org>:
- *     - Reimplementation of chain cache to use offsets instead of entries
- * 2003-Jun-23: Harald Welte <laforge@netfilter.org>:
- *     - performance optimization, sponsored by Astaro AG (http://www.astaro.com/)
- *       don't rebuild the chain cache after every operation, instead fix it
- *       up after a ruleset change.  
- * 2004-Aug-18: Harald Welte <laforge@netfilter.org>:
- *     - futher performance work: total reimplementation of libiptc.
- *     - libiptc now has a real internal (linked-list) represntation of the
- *       ruleset and a parser/compiler from/to this internal representation
- *     - again sponsored by Astaro AG (http://www.astaro.com/)
- */
-#include <sys/types.h>
-#include <sys/socket.h>
-#include "xtables.h"
-
-#include "linux_list.h"
-
-//#define IPTC_DEBUG2 1
-
-#ifdef IPTC_DEBUG2
-#include <fcntl.h>
-#define DEBUGP(x, args...)     fprintf(stderr, "%s: " x, __FUNCTION__, ## args)
-#define DEBUGP_C(x, args...)   fprintf(stderr, x, ## args)
-#else
-#define DEBUGP(x, args...)
-#define DEBUGP_C(x, args...)
-#endif
-
-#ifdef DEBUG
-#define debug(x, args...)      fprintf(stderr, x, ## args)
-#else
-#define debug(x, args...)
-#endif
-
-static int sockfd = -1;
-static int sockfd_use = 0;
-static void *iptc_fn = NULL;
-
-static const char *hooknames[] = {
-       [HOOK_PRE_ROUTING]      = "PREROUTING",
-       [HOOK_LOCAL_IN]         = "INPUT",
-       [HOOK_FORWARD]          = "FORWARD",
-       [HOOK_LOCAL_OUT]        = "OUTPUT",
-       [HOOK_POST_ROUTING]     = "POSTROUTING",
-#ifdef HOOK_DROPPING
-       [HOOK_DROPPING]         = "DROPPING"
-#endif
-};
-
-/* Convenience structures */
-struct ipt_error_target
-{
-       STRUCT_ENTRY_TARGET t;
-       char error[TABLE_MAXNAMELEN];
-};
-
-struct chain_head;
-struct rule_head;
-
-struct counter_map
-{
-       enum {
-               COUNTER_MAP_NOMAP,
-               COUNTER_MAP_NORMAL_MAP,
-               COUNTER_MAP_ZEROED,
-               COUNTER_MAP_SET
-       } maptype;
-       unsigned int mappos;
-};
-
-enum iptcc_rule_type {
-       IPTCC_R_STANDARD,               /* standard target (ACCEPT, ...) */
-       IPTCC_R_MODULE,                 /* extension module (SNAT, ...) */
-       IPTCC_R_FALLTHROUGH,            /* fallthrough rule */
-       IPTCC_R_JUMP,                   /* jump to other chain */
-};
-
-struct rule_head
-{
-       struct list_head list;
-       struct chain_head *chain;
-       struct counter_map counter_map;
-
-       unsigned int index;             /* index (needed for counter_map) */
-       unsigned int offset;            /* offset in rule blob */
-
-       enum iptcc_rule_type type;
-       struct chain_head *jump;        /* jump target, if IPTCC_R_JUMP */
-
-       unsigned int size;              /* size of entry data */
-       STRUCT_ENTRY entry[0];
-};
-
-struct chain_head
-{
-       struct list_head list;
-       char name[TABLE_MAXNAMELEN];
-       unsigned int hooknum;           /* hook number+1 if builtin */
-       unsigned int references;        /* how many jumps reference us */
-       int verdict;                    /* verdict if builtin */
-
-       STRUCT_COUNTERS counters;       /* per-chain counters */
-       struct counter_map counter_map;
-
-       unsigned int num_rules;         /* number of rules in list */
-       struct list_head rules;         /* list of rules */
-
-       unsigned int index;             /* index (needed for jump resolval) */
-       unsigned int head_offset;       /* offset in rule blob */
-       unsigned int foot_index;        /* index (needed for counter_map) */
-       unsigned int foot_offset;       /* offset in rule blob */
-};
-
-STRUCT_TC_HANDLE
-{
-       int changed;                     /* Have changes been made? */
-
-       struct list_head chains;
-       
-       struct chain_head *chain_iterator_cur;
-       struct rule_head *rule_iterator_cur;
-
-       unsigned int num_chains;         /* number of user defined chains */
-
-       struct chain_head **chain_index;   /* array for fast chain list access*/
-       unsigned int        chain_index_sz;/* size of chain index array */
-
-       STRUCT_GETINFO info;
-       STRUCT_GET_ENTRIES *entries;
-};
-
-/* allocate a new chain head for the cache */
-static struct chain_head *iptcc_alloc_chain_head(const char *name, int hooknum)
-{
-       struct chain_head *c = malloc(sizeof(*c));
-       if (!c)
-               return NULL;
-       memset(c, 0, sizeof(*c));
-
-       strncpy(c->name, name, TABLE_MAXNAMELEN);
-       c->hooknum = hooknum;
-       INIT_LIST_HEAD(&c->rules);
-
-       return c;
-}
-
-/* allocate and initialize a new rule for the cache */
-static struct rule_head *iptcc_alloc_rule(struct chain_head *c, unsigned int size)
-{
-       struct rule_head *r = malloc(sizeof(*r)+size);
-       if (!r)
-               return NULL;
-       memset(r, 0, sizeof(*r));
-
-       r->chain = c;
-       r->size = size;
-
-       return r;
-}
-
-/* notify us that the ruleset has been modified by the user */
-static inline void
-set_changed(TC_HANDLE_T h)
-{
-       h->changed = 1;
-}
-
-#ifdef IPTC_DEBUG
-static void do_check(TC_HANDLE_T h, unsigned int line);
-#define CHECK(h) do { if (!getenv("IPTC_NO_CHECK")) do_check((h), __LINE__); } while(0)
-#else
-#define CHECK(h)
-#endif
-
-
-/**********************************************************************
- * iptc blob utility functions (iptcb_*)
- **********************************************************************/
-
-static inline int
-iptcb_get_number(const STRUCT_ENTRY *i,
-          const STRUCT_ENTRY *seek,
-          unsigned int *pos)
-{
-       if (i == seek)
-               return 1;
-       (*pos)++;
-       return 0;
-}
-
-static inline int
-iptcb_get_entry_n(STRUCT_ENTRY *i,
-           unsigned int number,
-           unsigned int *pos,
-           STRUCT_ENTRY **pe)
-{
-       if (*pos == number) {
-               *pe = i;
-               return 1;
-       }
-       (*pos)++;
-       return 0;
-}
-
-static inline STRUCT_ENTRY *
-iptcb_get_entry(TC_HANDLE_T h, unsigned int offset)
-{
-       return (STRUCT_ENTRY *)((char *)h->entries->entrytable + offset);
-}
-
-static unsigned int
-iptcb_entry2index(const TC_HANDLE_T h, const STRUCT_ENTRY *seek)
-{
-       unsigned int pos = 0;
-
-       if (ENTRY_ITERATE(h->entries->entrytable, h->entries->size,
-                         iptcb_get_number, seek, &pos) == 0) {
-               fprintf(stderr, "ERROR: offset %u not an entry!\n",
-                       (unsigned int)((char *)seek - (char *)h->entries->entrytable));
-               abort();
-       }
-       return pos;
-}
-
-static inline STRUCT_ENTRY *
-iptcb_offset2entry(TC_HANDLE_T h, unsigned int offset)
-{
-       return (STRUCT_ENTRY *) ((void *)h->entries->entrytable+offset);
-}
-
-
-static inline unsigned long
-iptcb_entry2offset(const TC_HANDLE_T h, const STRUCT_ENTRY *e)
-{
-       return (void *)e - (void *)h->entries->entrytable;
-}
-
-static inline unsigned int
-iptcb_offset2index(const TC_HANDLE_T h, unsigned int offset)
-{
-       return iptcb_entry2index(h, iptcb_offset2entry(h, offset));
-}
-
-/* Returns 0 if not hook entry, else hooknumber + 1 */
-static inline unsigned int
-iptcb_ent_is_hook_entry(STRUCT_ENTRY *e, TC_HANDLE_T h)
-{
-       unsigned int i;
-
-       for (i = 0; i < NUMHOOKS; i++) {
-               if ((h->info.valid_hooks & (1 << i))
-                   && iptcb_get_entry(h, h->info.hook_entry[i]) == e)
-                       return i+1;
-       }
-       return 0;
-}
-
-
-/**********************************************************************
- * Chain index (cache utility) functions
- **********************************************************************
- * The chain index is an array with pointers into the chain list, with
- * CHAIN_INDEX_BUCKET_LEN spacing.  This facilitates the ability to
- * speedup chain list searching, by find a more optimal starting
- * points when searching the linked list.
- *
- * The starting point can be found fast by using a binary search of
- * the chain index. Thus, reducing the previous search complexity of
- * O(n) to O(log(n/k) + k) where k is CHAIN_INDEX_BUCKET_LEN.
- *
- * A nice property of the chain index, is that the "bucket" list
- * length is max CHAIN_INDEX_BUCKET_LEN (when just build, inserts will
- * change this). Oppose to hashing, where the "bucket" list length can
- * vary a lot.
- */
-#ifndef CHAIN_INDEX_BUCKET_LEN
-#define CHAIN_INDEX_BUCKET_LEN 40
-#endif
-
-/* Another nice property of the chain index is that inserting/creating
- * chains in chain list don't change the correctness of the chain
- * index, it only causes longer lists in the buckets.
- *
- * To mitigate the performance penalty of longer bucket lists and the
- * penalty of rebuilding, the chain index is rebuild only when
- * CHAIN_INDEX_INSERT_MAX chains has been added.
- */
-#ifndef CHAIN_INDEX_INSERT_MAX
-#define CHAIN_INDEX_INSERT_MAX 355
-#endif
-
-static inline unsigned int iptcc_is_builtin(struct chain_head *c);
-
-
-/* Use binary search in the chain index array, to find a chain_head
- * pointer closest to the place of the searched name element.
- *
- * Notes that, binary search (obviously) requires that the chain list
- * is sorted by name.
- */
-static struct list_head *
-iptcc_bsearch_chain_index(const char *name, unsigned int *idx, TC_HANDLE_T handle)
-{
-       unsigned int pos, end;
-       int res;
-
-       struct list_head *list_pos;
-       list_pos=&handle->chains;
-
-       /* Check for empty array, e.g. no user defined chains */
-       if (handle->chain_index_sz == 0) {
-               debug("WARNING: handle->chain_index_sz == 0\n");
-               return list_pos;
-       }
-
-       /* Init */
-       end = handle->chain_index_sz;
-       pos = end / 2;
-
-       debug("bsearch Find chain:%s (pos:%d end:%d)\n", name, pos, end);
-
-       /* Loop */
- loop:
-       if (!handle->chain_index[pos]) {
-               fprintf(stderr, "ERROR: NULL pointer chain_index[%d]\n", pos);
-               return &handle->chains; /* Be safe, return orig start pos */
-       }
-
-       res = strcmp(name, handle->chain_index[pos]->name);
-       list_pos = &handle->chain_index[pos]->list;
-       *idx = pos;
-
-       debug("bsearch Index[%d] name:%s res:%d ",
-             pos, handle->chain_index[pos]->name, res);
-
-       if (res == 0) { /* Found element, by direct hit */
-               debug("[found] Direct hit pos:%d end:%d\n", pos, end);
-               return list_pos;
-       } else if (res < 0) { /* Too far, jump back */
-               end = pos;
-               pos = pos / 2;
-
-               /* Exit case: First element of array */
-               if (end == 0) {
-                       debug("[found] Reached first array elem (end%d)\n",end);
-                       return list_pos;
-               }
-               debug("jump back to pos:%d (end:%d)\n", pos, end);
-               goto loop;
-       } else if (res > 0 ){ /* Not far enough, jump forward */
-
-               /* Exit case: Last element of array */
-               if (pos == handle->chain_index_sz-1) {
-                       debug("[found] Last array elem (end:%d)\n", end);
-                       return list_pos;
-               }
-
-               /* Exit case: Next index less, thus elem in this list section */
-               res = strcmp(name, handle->chain_index[pos+1]->name);
-               if (res < 0) {
-                       debug("[found] closest list (end:%d)\n", end);
-                       return list_pos;
-               }
-
-               pos = (pos+end)/2;
-               debug("jump forward to pos:%d (end:%d)\n", pos, end);
-               goto loop;
-       }
-
-       return list_pos;
-}
-
-#ifdef DEBUG
-/* Trivial linear search of chain index. Function used for verifying
-   the output of bsearch function */
-static struct list_head *
-iptcc_linearly_search_chain_index(const char *name, TC_HANDLE_T handle)
-{
-       unsigned int i=0;
-       int res=0;
-
-       struct list_head *list_pos;
-       list_pos = &handle->chains;
-
-       if (handle->chain_index_sz)
-               list_pos = &handle->chain_index[0]->list;
-
-       /* Linearly walk of chain index array */
-
-       for (i=0; i < handle->chain_index_sz; i++) {
-               if (handle->chain_index[i]) {
-                       res = strcmp(handle->chain_index[i]->name, name);
-                       if (res > 0)
-                               break; // One step too far
-                       list_pos = &handle->chain_index[i]->list;
-                       if (res == 0)
-                               break; // Direct hit
-               }
-       }
-
-       return list_pos;
-}
-#endif
-
-static int iptcc_chain_index_alloc(TC_HANDLE_T h)
-{
-       unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
-       unsigned int array_elems;
-       unsigned int array_mem;
-
-       /* Allocate memory for the chain index array */
-       array_elems = (h->num_chains / list_length) +
-                      (h->num_chains % list_length ? 1 : 0);
-       array_mem   = sizeof(h->chain_index) * array_elems;
-
-       debug("Alloc Chain index, elems:%d mem:%d bytes\n",
-             array_elems, array_mem);
-
-       h->chain_index = malloc(array_mem);
-       if (!h->chain_index) {
-               h->chain_index_sz = 0;
-               return -ENOMEM;
-       }
-       memset(h->chain_index, 0, array_mem);
-       h->chain_index_sz = array_elems;
-
-       return 1;
-}
-
-static void iptcc_chain_index_free(TC_HANDLE_T h)
-{
-       h->chain_index_sz = 0;
-       free(h->chain_index);
-}
-
-
-#ifdef DEBUG
-static void iptcc_chain_index_dump(TC_HANDLE_T h)
-{
-       unsigned int i = 0;
-
-       /* Dump: contents of chain index array */
-       for (i=0; i < h->chain_index_sz; i++) {
-               if (h->chain_index[i]) {
-                       fprintf(stderr, "Chain index[%d].name: %s\n",
-                               i, h->chain_index[i]->name);
-               }
-       }
-}
-#endif
-
-/* Build the chain index */
-static int iptcc_chain_index_build(TC_HANDLE_T h)
-{
-       unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
-       unsigned int chains = 0;
-       unsigned int cindex = 0;
-       struct chain_head *c;
-
-       /* Build up the chain index array here */
-       debug("Building chain index\n");
-
-       debug("Number of user defined chains:%d bucket_sz:%d array_sz:%d\n",
-               h->num_chains, list_length, h->chain_index_sz);
-
-       if (h->chain_index_sz == 0)
-               return 0;
-
-       list_for_each_entry(c, &h->chains, list) {
-
-               /* Issue: The index array needs to start after the
-                * builtin chains, as they are not sorted */
-               if (!iptcc_is_builtin(c)) {
-                       cindex=chains / list_length;
-
-                       /* Safe guard, break out on array limit, this
-                        * is useful if chains are added and array is
-                        * rebuild, without realloc of memory. */
-                       if (cindex >= h->chain_index_sz)
-                               break;
-
-                       if ((chains % list_length)== 0) {
-                               debug("\nIndex[%d] Chains:", cindex);
-                               h->chain_index[cindex] = c;
-                       }
-                       chains++;
-               }
-               debug("%s, ", c->name);
-       }
-       debug("\n");
-
-       return 1;
-}
-
-static int iptcc_chain_index_rebuild(TC_HANDLE_T h)
-{
-       debug("REBUILD chain index array\n");
-       iptcc_chain_index_free(h);
-       if ((iptcc_chain_index_alloc(h)) < 0)
-               return -ENOMEM;
-       iptcc_chain_index_build(h);
-       return 1;
-}
-
-/* Delete chain (pointer) from index array.  Removing an element from
- * the chain list only affects the chain index array, if the chain
- * index points-to/uses that list pointer.
- *
- * There are different strategies, the simple and safe is to rebuild
- * the chain index every time.  The more advanced is to update the
- * array index to point to the next element, but that requires some
- * house keeping and boundry checks.  The advanced is implemented, as
- * the simple approach behaves badly when all chains are deleted
- * because list_for_each processing will always hit the first chain
- * index, thus causing a rebuild for every chain.
- */
-static int iptcc_chain_index_delete_chain(struct chain_head *c, TC_HANDLE_T h)
-{
-       struct list_head *index_ptr, *index_ptr2, *next;
-       struct chain_head *c2;
-       unsigned int idx, idx2;
-
-       index_ptr = iptcc_bsearch_chain_index(c->name, &idx, h);
-
-       debug("Del chain[%s] c->list:%p index_ptr:%p\n",
-             c->name, &c->list, index_ptr);
-
-       /* Save the next pointer */
-       next = c->list.next;
-       list_del(&c->list);
-
-       if (index_ptr == &c->list) { /* Chain used as index ptr */
-
-               /* See if its possible to avoid a rebuild, by shifting
-                * to next pointer.  Its possible if the next pointer
-                * is located in the same index bucket.
-                */
-               c2         = list_entry(next, struct chain_head, list);
-               index_ptr2 = iptcc_bsearch_chain_index(c2->name, &idx2, h);
-               if (idx != idx2) {
-                       /* Rebuild needed */
-                       return iptcc_chain_index_rebuild(h);
-               } else {
-                       /* Avoiding rebuild */
-                       debug("Update cindex[%d] with next ptr name:[%s]\n",
-                             idx, c2->name);
-                       h->chain_index[idx]=c2;
-                       return 0;
-               }
-       }
-       return 0;
-}
-
-
-/**********************************************************************
- * iptc cache utility functions (iptcc_*)
- **********************************************************************/
-
-/* Is the given chain builtin (1) or user-defined (0) */
-static inline unsigned int iptcc_is_builtin(struct chain_head *c)
-{
-       return (c->hooknum ? 1 : 0);
-}
-
-/* Get a specific rule within a chain */
-static struct rule_head *iptcc_get_rule_num(struct chain_head *c,
-                                           unsigned int rulenum)
-{
-       struct rule_head *r;
-       unsigned int num = 0;
-
-       list_for_each_entry(r, &c->rules, list) {
-               num++;
-               if (num == rulenum)
-                       return r;
-       }
-       return NULL;
-}
-
-/* Get a specific rule within a chain backwards */
-static struct rule_head *iptcc_get_rule_num_reverse(struct chain_head *c,
-                                           unsigned int rulenum)
-{
-       struct rule_head *r;
-       unsigned int num = 0;
-
-       list_for_each_entry_reverse(r, &c->rules, list) {
-               num++;
-               if (num == rulenum)
-                       return r;
-       }
-       return NULL;
-}
-
-/* Returns chain head if found, otherwise NULL. */
-static struct chain_head *
-iptcc_find_chain_by_offset(TC_HANDLE_T handle, unsigned int offset)
-{
-       struct list_head *pos;
-
-       if (list_empty(&handle->chains))
-               return NULL;
-
-       list_for_each(pos, &handle->chains) {
-               struct chain_head *c = list_entry(pos, struct chain_head, list);
-               if (offset >= c->head_offset && offset <= c->foot_offset)
-                       return c;
-       }
-
-       return NULL;
-}
-
-/* Returns chain head if found, otherwise NULL. */
-static struct chain_head *
-iptcc_find_label(const char *name, TC_HANDLE_T handle)
-{
-       struct list_head *pos;
-       struct list_head *list_start_pos;
-       unsigned int i=0;
-       int res;
-
-       if (list_empty(&handle->chains))
-               return NULL;
-
-       /* First look at builtin chains */
-       list_for_each(pos, &handle->chains) {
-               struct chain_head *c = list_entry(pos, struct chain_head, list);
-               if (!iptcc_is_builtin(c))
-                       break;
-               if (!strcmp(c->name, name))
-                       return c;
-       }
-
-       /* Find a smart place to start the search via chain index */
-       //list_start_pos = iptcc_linearly_search_chain_index(name, handle);
-       list_start_pos = iptcc_bsearch_chain_index(name, &i, handle);
-
-       /* Handel if bsearch bails out early */
-       if (list_start_pos == &handle->chains) {
-               list_start_pos = pos;
-       }
-#ifdef DEBUG
-       else {
-               /* Verify result of bsearch against linearly index search */
-               struct list_head *test_pos;
-               struct chain_head *test_c, *tmp_c;
-               test_pos = iptcc_linearly_search_chain_index(name, handle);
-               if (list_start_pos != test_pos) {
-                       debug("BUG in chain_index search\n");
-                       test_c=list_entry(test_pos,      struct chain_head,list);
-                       tmp_c =list_entry(list_start_pos,struct chain_head,list);
-                       debug("Verify search found:\n");
-                       debug(" Chain:%s\n", test_c->name);
-                       debug("BSearch found:\n");
-                       debug(" Chain:%s\n", tmp_c->name);
-                       exit(42);
-               }
-       }
-#endif
-
-       /* Initial/special case, no user defined chains */
-       if (handle->num_chains == 0)
-               return NULL;
-
-       /* Start searching through the chain list */
-       list_for_each(pos, list_start_pos->prev) {
-               struct chain_head *c = list_entry(pos, struct chain_head, list);
-               res = strcmp(c->name, name);
-               debug("List search name:%s == %s res:%d\n", name, c->name, res);
-               if (res==0)
-                       return c;
-
-               /* We can stop earlier as we know list is sorted */
-               if (res>0 && !iptcc_is_builtin(c)) { /* Walked too far*/
-                       debug(" Not in list, walked too far, sorted list\n");
-                       return NULL;
-               }
-
-               /* Stop on wrap around, if list head is reached */
-               if (pos == &handle->chains) {
-                       debug("Stop, list head reached\n");
-                       return NULL;
-               }
-       }
-
-       debug("List search NOT found name:%s\n", name);
-       return NULL;
-}
-
-/* called when rule is to be removed from cache */
-static void iptcc_delete_rule(struct rule_head *r)
-{
-       DEBUGP("deleting rule %p (offset %u)\n", r, r->offset);
-       /* clean up reference count of called chain */
-       if (r->type == IPTCC_R_JUMP
-           && r->jump)
-               r->jump->references--;
-
-       list_del(&r->list);
-       free(r);
-}
-
-
-/**********************************************************************
- * RULESET PARSER (blob -> cache)
- **********************************************************************/
-
-/* Delete policy rule of previous chain, since cache doesn't contain
- * chain policy rules.
- * WARNING: This function has ugly design and relies on a lot of context, only
- * to be called from specific places within the parser */
-static int __iptcc_p_del_policy(TC_HANDLE_T h, unsigned int num)
-{
-       const unsigned char *data;
-
-       if (h->chain_iterator_cur) {
-               /* policy rule is last rule */
-               struct rule_head *pr = (struct rule_head *)
-                       h->chain_iterator_cur->rules.prev;
-
-               /* save verdict */
-               data = GET_TARGET(pr->entry)->data;
-               h->chain_iterator_cur->verdict = *(const int *)data;
-
-               /* save counter and counter_map information */
-               h->chain_iterator_cur->counter_map.maptype = 
-                                               COUNTER_MAP_NORMAL_MAP;
-               h->chain_iterator_cur->counter_map.mappos = num-1;
-               memcpy(&h->chain_iterator_cur->counters, &pr->entry->counters, 
-                       sizeof(h->chain_iterator_cur->counters));
-
-               /* foot_offset points to verdict rule */
-               h->chain_iterator_cur->foot_index = num;
-               h->chain_iterator_cur->foot_offset = pr->offset;
-
-               /* delete rule from cache */
-               iptcc_delete_rule(pr);
-               h->chain_iterator_cur->num_rules--;
-
-               return 1;
-       }
-       return 0;
-}
-
-/* alphabetically insert a chain into the list */
-static inline void iptc_insert_chain(TC_HANDLE_T h, struct chain_head *c)
-{
-       struct chain_head *tmp;
-       struct list_head  *list_start_pos;
-       unsigned int i=1;
-
-       /* Find a smart place to start the insert search */
-       list_start_pos = iptcc_bsearch_chain_index(c->name, &i, h);
-
-       /* Handle the case, where chain.name is smaller than index[0] */
-       if (i==0 && strcmp(c->name, h->chain_index[0]->name) <= 0) {
-               h->chain_index[0] = c; /* Update chain index head */
-               list_start_pos = h->chains.next;
-               debug("Update chain_index[0] with %s\n", c->name);
-       }
-
-       /* Handel if bsearch bails out early */
-       if (list_start_pos == &h->chains) {
-               list_start_pos = h->chains.next;
-       }
-
-       /* sort only user defined chains */
-       if (!c->hooknum) {
-               list_for_each_entry(tmp, list_start_pos->prev, list) {
-                       if (!tmp->hooknum && strcmp(c->name, tmp->name) <= 0) {
-                               list_add(&c->list, tmp->list.prev);
-                               return;
-                       }
-
-                       /* Stop if list head is reached */
-                       if (&tmp->list == &h->chains) {
-                               debug("Insert, list head reached add to tail\n");
-                               break;
-                       }
-               }
-       }
-
-       /* survived till end of list: add at tail */
-       list_add_tail(&c->list, &h->chains);
-}
-
-/* Another ugly helper function split out of cache_add_entry to make it less
- * spaghetti code */
-static void __iptcc_p_add_chain(TC_HANDLE_T h, struct chain_head *c,
-                               unsigned int offset, unsigned int *num)
-{
-       struct list_head  *tail = h->chains.prev;
-       struct chain_head *ctail;
-
-       __iptcc_p_del_policy(h, *num);
-
-       c->head_offset = offset;
-       c->index = *num;
-
-       /* Chains from kernel are already sorted, as they are inserted
-        * sorted. But there exists an issue when shifting to 1.4.0
-        * from an older version, as old versions allow last created
-        * chain to be unsorted.
-        */
-       if (iptcc_is_builtin(c)) /* Only user defined chains are sorted*/
-               list_add_tail(&c->list, &h->chains);
-       else {
-               ctail = list_entry(tail, struct chain_head, list);
-               if (strcmp(c->name, ctail->name) > 0)
-                       list_add_tail(&c->list, &h->chains);/* Already sorted*/
-               else
-                       iptc_insert_chain(h, c);/* Was not sorted */
-       }
-
-       h->chain_iterator_cur = c;
-}
-
-/* main parser function: add an entry from the blob to the cache */
-static int cache_add_entry(STRUCT_ENTRY *e, 
-                          TC_HANDLE_T h, 
-                          STRUCT_ENTRY **prev,
-                          unsigned int *num)
-{
-       unsigned int builtin;
-       unsigned int offset = (char *)e - (char *)h->entries->entrytable;
-
-       DEBUGP("entering...");
-
-       /* Last entry ("policy rule"). End it.*/
-       if (iptcb_entry2offset(h,e) + e->next_offset == h->entries->size) {
-               /* This is the ERROR node at the end of the chain */
-               DEBUGP_C("%u:%u: end of table:\n", *num, offset);
-
-               __iptcc_p_del_policy(h, *num);
-
-               h->chain_iterator_cur = NULL;
-               goto out_inc;
-       }
-
-       /* We know this is the start of a new chain if it's an ERROR
-        * target, or a hook entry point */
-
-       if (strcmp(GET_TARGET(e)->u.user.name, ERROR_TARGET) == 0) {
-               struct chain_head *c = 
-                       iptcc_alloc_chain_head((const char *)GET_TARGET(e)->data, 0);
-               DEBUGP_C("%u:%u:new userdefined chain %s: %p\n", *num, offset, 
-                       (char *)c->name, c);
-               if (!c) {
-                       errno = -ENOMEM;
-                       return -1;
-               }
-               h->num_chains++; /* New user defined chain */
-
-               __iptcc_p_add_chain(h, c, offset, num);
-
-       } else if ((builtin = iptcb_ent_is_hook_entry(e, h)) != 0) {
-               struct chain_head *c =
-                       iptcc_alloc_chain_head((char *)hooknames[builtin-1], 
-                                               builtin);
-               DEBUGP_C("%u:%u new builtin chain: %p (rules=%p)\n", 
-                       *num, offset, c, &c->rules);
-               if (!c) {
-                       errno = -ENOMEM;
-                       return -1;
-               }
-
-               c->hooknum = builtin;
-
-               __iptcc_p_add_chain(h, c, offset, num);
-
-               /* FIXME: this is ugly. */
-               goto new_rule;
-       } else {
-               /* has to be normal rule */
-               struct rule_head *r;
-new_rule:
-
-               if (!(r = iptcc_alloc_rule(h->chain_iterator_cur, 
-                                          e->next_offset))) {
-                       errno = ENOMEM;
-                       return -1;
-               }
-               DEBUGP_C("%u:%u normal rule: %p: ", *num, offset, r);
-
-               r->index = *num;
-               r->offset = offset;
-               memcpy(r->entry, e, e->next_offset);
-               r->counter_map.maptype = COUNTER_MAP_NORMAL_MAP;
-               r->counter_map.mappos = r->index;
-
-               /* handling of jumps, etc. */
-               if (!strcmp(GET_TARGET(e)->u.user.name, STANDARD_TARGET)) {
-                       STRUCT_STANDARD_TARGET *t;
-
-                       t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
-                       if (t->target.u.target_size
-                           != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
-                               errno = EINVAL;
-                               return -1;
-                       }
-
-                       if (t->verdict < 0) {
-                               DEBUGP_C("standard, verdict=%d\n", t->verdict);
-                               r->type = IPTCC_R_STANDARD;
-                       } else if (t->verdict == r->offset+e->next_offset) {
-                               DEBUGP_C("fallthrough\n");
-                               r->type = IPTCC_R_FALLTHROUGH;
-                       } else {
-                               DEBUGP_C("jump, target=%u\n", t->verdict);
-                               r->type = IPTCC_R_JUMP;
-                               /* Jump target fixup has to be deferred
-                                * until second pass, since we migh not
-                                * yet have parsed the target */
-                       }
-               } else {
-                       DEBUGP_C("module, target=%s\n", GET_TARGET(e)->u.user.name);
-                       r->type = IPTCC_R_MODULE;
-               }
-
-               list_add_tail(&r->list, &h->chain_iterator_cur->rules);
-               h->chain_iterator_cur->num_rules++;
-       }
-out_inc:
-       (*num)++;
-       return 0;
-}
-
-
-/* parse an iptables blob into it's pieces */
-static int parse_table(TC_HANDLE_T h)
-{
-       STRUCT_ENTRY *prev;
-       unsigned int num = 0;
-       struct chain_head *c;
-
-       /* First pass: over ruleset blob */
-       ENTRY_ITERATE(h->entries->entrytable, h->entries->size,
-                       cache_add_entry, h, &prev, &num);
-
-       /* Build the chain index, used for chain list search speedup */
-       if ((iptcc_chain_index_alloc(h)) < 0)
-               return -ENOMEM;
-       iptcc_chain_index_build(h);
-
-       /* Second pass: fixup parsed data from first pass */
-       list_for_each_entry(c, &h->chains, list) {
-               struct rule_head *r;
-               list_for_each_entry(r, &c->rules, list) {
-                       struct chain_head *lc;
-                       STRUCT_STANDARD_TARGET *t;
-
-                       if (r->type != IPTCC_R_JUMP)
-                               continue;
-
-                       t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
-                       lc = iptcc_find_chain_by_offset(h, t->verdict);
-                       if (!lc)
-                               return -1;
-                       r->jump = lc;
-                       lc->references++;
-               }
-       }
-
-       /* FIXME: sort chains */
-
-       return 1;
-}
-
-
-/**********************************************************************
- * RULESET COMPILATION (cache -> blob)
- **********************************************************************/
-
-/* Convenience structures */
-struct iptcb_chain_start{
-       STRUCT_ENTRY e;
-       struct ipt_error_target name;
-};
-#define IPTCB_CHAIN_START_SIZE (sizeof(STRUCT_ENTRY) +                 \
-                                ALIGN(sizeof(struct ipt_error_target)))
-
-struct iptcb_chain_foot {
-       STRUCT_ENTRY e;
-       STRUCT_STANDARD_TARGET target;
-};
-#define IPTCB_CHAIN_FOOT_SIZE  (sizeof(STRUCT_ENTRY) +                 \
-                                ALIGN(sizeof(STRUCT_STANDARD_TARGET)))
-
-struct iptcb_chain_error {
-       STRUCT_ENTRY entry;
-       struct ipt_error_target target;
-};
-#define IPTCB_CHAIN_ERROR_SIZE (sizeof(STRUCT_ENTRY) +                 \
-                                ALIGN(sizeof(struct ipt_error_target)))
-
-
-
-/* compile rule from cache into blob */
-static inline int iptcc_compile_rule (TC_HANDLE_T h, STRUCT_REPLACE *repl, struct rule_head *r)
-{
-       /* handle jumps */
-       if (r->type == IPTCC_R_JUMP) {
-               STRUCT_STANDARD_TARGET *t;
-               t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
-               /* memset for memcmp convenience on delete/replace */
-               memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN);
-               strcpy(t->target.u.user.name, STANDARD_TARGET);
-               /* Jumps can only happen to builtin chains, so we
-                * can safely assume that they always have a header */
-               t->verdict = r->jump->head_offset + IPTCB_CHAIN_START_SIZE;
-       } else if (r->type == IPTCC_R_FALLTHROUGH) {
-               STRUCT_STANDARD_TARGET *t;
-               t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
-               t->verdict = r->offset + r->size;
-       }
-       
-       /* copy entry from cache to blob */
-       memcpy((char *)repl->entries+r->offset, r->entry, r->size);
-
-       return 1;
-}
-
-/* compile chain from cache into blob */
-static int iptcc_compile_chain(TC_HANDLE_T h, STRUCT_REPLACE *repl, struct chain_head *c)
-{
-       int ret;
-       struct rule_head *r;
-       struct iptcb_chain_start *head;
-       struct iptcb_chain_foot *foot;
-
-       /* only user-defined chains have heaer */
-       if (!iptcc_is_builtin(c)) {
-               /* put chain header in place */
-               head = (void *)repl->entries + c->head_offset;
-               head->e.target_offset = sizeof(STRUCT_ENTRY);
-               head->e.next_offset = IPTCB_CHAIN_START_SIZE;
-               strcpy(head->name.t.u.user.name, ERROR_TARGET);
-               head->name.t.u.target_size = 
-                               ALIGN(sizeof(struct ipt_error_target));
-               strcpy(head->name.error, c->name);
-       } else {
-               repl->hook_entry[c->hooknum-1] = c->head_offset;        
-               repl->underflow[c->hooknum-1] = c->foot_offset;
-       }
-
-       /* iterate over rules */
-       list_for_each_entry(r, &c->rules, list) {
-               ret = iptcc_compile_rule(h, repl, r);
-               if (ret < 0)
-                       return ret;
-       }
-
-       /* put chain footer in place */
-       foot = (void *)repl->entries + c->foot_offset;
-       foot->e.target_offset = sizeof(STRUCT_ENTRY);
-       foot->e.next_offset = IPTCB_CHAIN_FOOT_SIZE;
-       strcpy(foot->target.target.u.user.name, STANDARD_TARGET);
-       foot->target.target.u.target_size =
-                               ALIGN(sizeof(STRUCT_STANDARD_TARGET));
-       /* builtin targets have verdict, others return */
-       if (iptcc_is_builtin(c))
-               foot->target.verdict = c->verdict;
-       else
-               foot->target.verdict = RETURN;
-       /* set policy-counters */
-       memcpy(&foot->e.counters, &c->counters, sizeof(STRUCT_COUNTERS));
-
-       return 0;
-}
-
-/* calculate offset and number for every rule in the cache */
-static int iptcc_compile_chain_offsets(TC_HANDLE_T h, struct chain_head *c,
-                                      unsigned int *offset, unsigned int *num)
-{
-       struct rule_head *r;
-
-       c->head_offset = *offset;
-       DEBUGP("%s: chain_head %u, offset=%u\n", c->name, *num, *offset);
-
-       if (!iptcc_is_builtin(c))  {
-               /* Chain has header */
-               *offset += sizeof(STRUCT_ENTRY) 
-                            + ALIGN(sizeof(struct ipt_error_target));
-               (*num)++;
-       }
-
-       list_for_each_entry(r, &c->rules, list) {
-               DEBUGP("rule %u, offset=%u, index=%u\n", *num, *offset, *num);
-               r->offset = *offset;
-               r->index = *num;
-               *offset += r->size;
-               (*num)++;
-       }
-
-       DEBUGP("%s; chain_foot %u, offset=%u, index=%u\n", c->name, *num, 
-               *offset, *num);
-       c->foot_offset = *offset;
-       c->foot_index = *num;
-       *offset += sizeof(STRUCT_ENTRY)
-                  + ALIGN(sizeof(STRUCT_STANDARD_TARGET));
-       (*num)++;
-
-       return 1;
-}
-
-/* put the pieces back together again */
-static int iptcc_compile_table_prep(TC_HANDLE_T h, unsigned int *size)
-{
-       struct chain_head *c;
-       unsigned int offset = 0, num = 0;
-       int ret = 0;
-
-       /* First pass: calculate offset for every rule */
-       list_for_each_entry(c, &h->chains, list) {
-               ret = iptcc_compile_chain_offsets(h, c, &offset, &num);
-               if (ret < 0)
-                       return ret;
-       }
-
-       /* Append one error rule at end of chain */
-       num++;
-       offset += sizeof(STRUCT_ENTRY)
-                 + ALIGN(sizeof(struct ipt_error_target));
-
-       /* ruleset size is now in offset */
-       *size = offset;
-       return num;
-}
-
-static int iptcc_compile_table(TC_HANDLE_T h, STRUCT_REPLACE *repl)
-{
-       struct chain_head *c;
-       struct iptcb_chain_error *error;
-
-       /* Second pass: copy from cache to offsets, fill in jumps */
-       list_for_each_entry(c, &h->chains, list) {
-               int ret = iptcc_compile_chain(h, repl, c);
-               if (ret < 0)
-                       return ret;
-       }
-
-       /* Append error rule at end of chain */
-       error = (void *)repl->entries + repl->size - IPTCB_CHAIN_ERROR_SIZE;
-       error->entry.target_offset = sizeof(STRUCT_ENTRY);
-       error->entry.next_offset = IPTCB_CHAIN_ERROR_SIZE;
-       error->target.t.u.user.target_size = 
-               ALIGN(sizeof(struct ipt_error_target));
-       strcpy((char *)&error->target.t.u.user.name, ERROR_TARGET);
-       strcpy((char *)&error->target.error, "ERROR");
-
-       return 1;
-}
-
-/**********************************************************************
- * EXTERNAL API (operates on cache only)
- **********************************************************************/
-
-/* Allocate handle of given size */
-static TC_HANDLE_T
-alloc_handle(const char *tablename, unsigned int size, unsigned int num_rules)
-{
-       size_t len;
-       TC_HANDLE_T h;
-
-       len = sizeof(STRUCT_TC_HANDLE) + size;
-
-       h = malloc(sizeof(STRUCT_TC_HANDLE));
-       if (!h) {
-               errno = ENOMEM;
-               return NULL;
-       }
-       memset(h, 0, sizeof(*h));
-       INIT_LIST_HEAD(&h->chains);
-       strcpy(h->info.name, tablename);
-
-       h->entries = malloc(sizeof(STRUCT_GET_ENTRIES) + size);
-       if (!h->entries)
-               goto out_free_handle;
-
-       strcpy(h->entries->name, tablename);
-       h->entries->size = size;
-
-       return h;
-
-out_free_handle:
-       free(h);
-
-       return NULL;
-}
-
-
-TC_HANDLE_T
-TC_INIT(const char *tablename)
-{
-       TC_HANDLE_T h;
-       STRUCT_GETINFO info;
-       unsigned int tmp;
-       socklen_t s;
-
-       iptc_fn = TC_INIT;
-
-       if (strlen(tablename) >= TABLE_MAXNAMELEN) {
-               errno = EINVAL;
-               return NULL;
-       }
-       
-       if (sockfd_use == 0) {
-               sockfd = socket(TC_AF, SOCK_RAW, IPPROTO_RAW);
-               if (sockfd < 0)
-                       return NULL;
-       }
-       sockfd_use++;
-retry:
-       s = sizeof(info);
-
-       strcpy(info.name, tablename);
-       if (getsockopt(sockfd, TC_IPPROTO, SO_GET_INFO, &info, &s) < 0) {
-               if (--sockfd_use == 0) {
-                       close(sockfd);
-                       sockfd = -1;
-               }
-               return NULL;
-       }
-
-       DEBUGP("valid_hooks=0x%08x, num_entries=%u, size=%u\n",
-               info.valid_hooks, info.num_entries, info.size);
-
-       if ((h = alloc_handle(info.name, info.size, info.num_entries))
-           == NULL) {
-               if (--sockfd_use == 0) {
-                       close(sockfd);
-                       sockfd = -1;
-               }
-               return NULL;
-       }
-
-       /* Initialize current state */
-       h->info = info;
-
-       h->entries->size = h->info.size;
-
-       tmp = sizeof(STRUCT_GET_ENTRIES) + h->info.size;
-
-       if (getsockopt(sockfd, TC_IPPROTO, SO_GET_ENTRIES, h->entries,
-                      &tmp) < 0)
-               goto error;
-
-#ifdef IPTC_DEBUG2
-       {
-               int fd = open("/tmp/libiptc-so_get_entries.blob", 
-                               O_CREAT|O_WRONLY);
-               if (fd >= 0) {
-                       write(fd, h->entries, tmp);
-                       close(fd);
-               }
-       }
-#endif
-
-       if (parse_table(h) < 0)
-               goto error;
-
-       CHECK(h);
-       return h;
-error:
-       TC_FREE(&h);
-       /* A different process changed the ruleset size, retry */
-       if (errno == EAGAIN)
-               goto retry;
-       return NULL;
-}
-
-void
-TC_FREE(TC_HANDLE_T *h)
-{
-       struct chain_head *c, *tmp;
-
-       iptc_fn = TC_FREE;
-       if (--sockfd_use == 0) {
-               close(sockfd);
-               sockfd = -1;
-       }
-
-       list_for_each_entry_safe(c, tmp, &(*h)->chains, list) {
-               struct rule_head *r, *rtmp;
-
-               list_for_each_entry_safe(r, rtmp, &c->rules, list) {
-                       free(r);
-               }
-
-               free(c);
-       }
-
-       iptcc_chain_index_free(*h);
-
-       free((*h)->entries);
-       free(*h);
-
-       *h = NULL;
-}
-
-static inline int
-print_match(const STRUCT_ENTRY_MATCH *m)
-{
-       printf("Match name: `%s'\n", m->u.user.name);
-       return 0;
-}
-
-static int dump_entry(STRUCT_ENTRY *e, const TC_HANDLE_T handle);
-void
-TC_DUMP_ENTRIES(const TC_HANDLE_T handle)
-{
-       iptc_fn = TC_DUMP_ENTRIES;
-       CHECK(handle);
-
-       printf("libiptc v%s. %u bytes.\n",
-              XTABLES_VERSION, handle->entries->size);
-       printf("Table `%s'\n", handle->info.name);
-       printf("Hooks: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n",
-              handle->info.hook_entry[HOOK_PRE_ROUTING],
-              handle->info.hook_entry[HOOK_LOCAL_IN],
-              handle->info.hook_entry[HOOK_FORWARD],
-              handle->info.hook_entry[HOOK_LOCAL_OUT],
-              handle->info.hook_entry[HOOK_POST_ROUTING]);
-       printf("Underflows: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n",
-              handle->info.underflow[HOOK_PRE_ROUTING],
-              handle->info.underflow[HOOK_LOCAL_IN],
-              handle->info.underflow[HOOK_FORWARD],
-              handle->info.underflow[HOOK_LOCAL_OUT],
-              handle->info.underflow[HOOK_POST_ROUTING]);
-
-       ENTRY_ITERATE(handle->entries->entrytable, handle->entries->size,
-                     dump_entry, handle);
-}
-
-/* Does this chain exist? */
-int TC_IS_CHAIN(const char *chain, const TC_HANDLE_T handle)
-{
-       iptc_fn = TC_IS_CHAIN;
-       return iptcc_find_label(chain, handle) != NULL;
-}
-
-static void iptcc_chain_iterator_advance(TC_HANDLE_T handle)
-{
-       struct chain_head *c = handle->chain_iterator_cur;
-
-       if (c->list.next == &handle->chains)
-               handle->chain_iterator_cur = NULL;
-       else
-               handle->chain_iterator_cur = 
-                       list_entry(c->list.next, struct chain_head, list);
-}
-
-/* Iterator functions to run through the chains. */
-const char *
-TC_FIRST_CHAIN(TC_HANDLE_T *handle)
-{
-       struct chain_head *c = list_entry((*handle)->chains.next,
-                                         struct chain_head, list);
-
-       iptc_fn = TC_FIRST_CHAIN;
-
-
-       if (list_empty(&(*handle)->chains)) {
-               DEBUGP(": no chains\n");
-               return NULL;
-       }
-
-       (*handle)->chain_iterator_cur = c;
-       iptcc_chain_iterator_advance(*handle);
-
-       DEBUGP(": returning `%s'\n", c->name);
-       return c->name;
-}
-
-/* Iterator functions to run through the chains.  Returns NULL at end. */
-const char *
-TC_NEXT_CHAIN(TC_HANDLE_T *handle)
-{
-       struct chain_head *c = (*handle)->chain_iterator_cur;
-
-       iptc_fn = TC_NEXT_CHAIN;
-
-       if (!c) {
-               DEBUGP(": no more chains\n");
-               return NULL;
-       }
-
-       iptcc_chain_iterator_advance(*handle);
-       
-       DEBUGP(": returning `%s'\n", c->name);
-       return c->name;
-}
-
-/* Get first rule in the given chain: NULL for empty chain. */
-const STRUCT_ENTRY *
-TC_FIRST_RULE(const char *chain, TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r;
-
-       iptc_fn = TC_FIRST_RULE;
-
-       DEBUGP("first rule(%s): ", chain);
-
-       c = iptcc_find_label(chain, *handle);
-       if (!c) {
-               errno = ENOENT;
-               return NULL;
-       }
-
-       /* Empty chain: single return/policy rule */
-       if (list_empty(&c->rules)) {
-               DEBUGP_C("no rules, returning NULL\n");
-               return NULL;
-       }
-
-       r = list_entry(c->rules.next, struct rule_head, list);
-       (*handle)->rule_iterator_cur = r;
-       DEBUGP_C("%p\n", r);
-
-       return r->entry;
-}
-
-/* Returns NULL when rules run out. */
-const STRUCT_ENTRY *
-TC_NEXT_RULE(const STRUCT_ENTRY *prev, TC_HANDLE_T *handle)
-{
-       struct rule_head *r;
-
-       iptc_fn = TC_NEXT_RULE;
-       DEBUGP("rule_iterator_cur=%p...", (*handle)->rule_iterator_cur);
-
-       if (!(*handle)->rule_iterator_cur) {
-               DEBUGP_C("returning NULL\n");
-               return NULL;
-       }
-       
-       r = list_entry((*handle)->rule_iterator_cur->list.next, 
-                       struct rule_head, list);
-
-       iptc_fn = TC_NEXT_RULE;
-
-       DEBUGP_C("next=%p, head=%p...", &r->list, 
-               &(*handle)->rule_iterator_cur->chain->rules);
-
-       if (&r->list == &(*handle)->rule_iterator_cur->chain->rules) {
-               (*handle)->rule_iterator_cur = NULL;
-               DEBUGP_C("finished, returning NULL\n");
-               return NULL;
-       }
-
-       (*handle)->rule_iterator_cur = r;
-
-       /* NOTE: prev is without any influence ! */
-       DEBUGP_C("returning rule %p\n", r);
-       return r->entry;
-}
-
-/* How many rules in this chain? */
-#if 0
-static unsigned int
-TC_NUM_RULES(const char *chain, TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       iptc_fn = TC_NUM_RULES;
-       CHECK(*handle);
-
-       c = iptcc_find_label(chain, *handle);
-       if (!c) {
-               errno = ENOENT;
-               return (unsigned int)-1;
-       }
-       
-       return c->num_rules;
-}
-#endif
-
-#if 0
-static const STRUCT_ENTRY *
-TC_GET_RULE(const char *chain, unsigned int n, TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r;
-       
-       iptc_fn = TC_GET_RULE;
-
-       CHECK(*handle);
-
-       c = iptcc_find_label(chain, *handle);
-       if (!c) {
-               errno = ENOENT;
-               return NULL;
-       }
-
-       r = iptcc_get_rule_num(c, n);
-       if (!r)
-               return NULL;
-       return r->entry;
-}
-#endif
-
-/* Returns a pointer to the target name of this position. */
-static const char *standard_target_map(int verdict)
-{
-       switch (verdict) {
-               case RETURN:
-                       return LABEL_RETURN;
-                       break;
-               case -NF_ACCEPT-1:
-                       return LABEL_ACCEPT;
-                       break;
-               case -NF_DROP-1:
-                       return LABEL_DROP;
-                       break;
-               case -NF_QUEUE-1:
-                       return LABEL_QUEUE;
-                       break;
-               default:
-                       fprintf(stderr, "ERROR: %d not a valid target)\n",
-                               verdict);
-                       abort();
-                       break;
-       }
-       /* not reached */
-       return NULL;
-}
-
-/* Returns a pointer to the target name of this position. */
-const char *TC_GET_TARGET(const STRUCT_ENTRY *ce,
-                         TC_HANDLE_T *handle)
-{
-       STRUCT_ENTRY *e = (STRUCT_ENTRY *)ce;
-       struct rule_head *r = container_of(e, struct rule_head, entry[0]);
-       const unsigned char *data;
-
-       iptc_fn = TC_GET_TARGET;
-
-       switch(r->type) {
-               int spos;
-               case IPTCC_R_FALLTHROUGH:
-                       return "";
-                       break;
-               case IPTCC_R_JUMP:
-                       DEBUGP("r=%p, jump=%p, name=`%s'\n", r, r->jump, r->jump->name);
-                       return r->jump->name;
-                       break;
-               case IPTCC_R_STANDARD:
-                       data = GET_TARGET(e)->data;
-                       spos = *(const int *)data;
-                       DEBUGP("r=%p, spos=%d'\n", r, spos);
-                       return standard_target_map(spos);
-                       break;
-               case IPTCC_R_MODULE:
-                       return GET_TARGET(e)->u.user.name;
-                       break;
-       }
-       return NULL;
-}
-/* Is this a built-in chain?  Actually returns hook + 1. */
-int
-TC_BUILTIN(const char *chain, const TC_HANDLE_T handle)
-{
-       struct chain_head *c;
-       
-       iptc_fn = TC_BUILTIN;
-
-       c = iptcc_find_label(chain, handle);
-       if (!c) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       return iptcc_is_builtin(c);
-}
-
-/* Get the policy of a given built-in chain */
-const char *
-TC_GET_POLICY(const char *chain,
-             STRUCT_COUNTERS *counters,
-             TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-
-       iptc_fn = TC_GET_POLICY;
-
-       DEBUGP("called for chain %s\n", chain);
-
-       c = iptcc_find_label(chain, *handle);
-       if (!c) {
-               errno = ENOENT;
-               return NULL;
-       }
-
-       if (!iptcc_is_builtin(c))
-               return NULL;
-
-       *counters = c->counters;
-
-       return standard_target_map(c->verdict);
-}
-
-static int
-iptcc_standard_map(struct rule_head *r, int verdict)
-{
-       STRUCT_ENTRY *e = r->entry;
-       STRUCT_STANDARD_TARGET *t;
-
-       t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
-
-       if (t->target.u.target_size
-           != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
-               errno = EINVAL;
-               return 0;
-       }
-       /* memset for memcmp convenience on delete/replace */
-       memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN);
-       strcpy(t->target.u.user.name, STANDARD_TARGET);
-       t->verdict = verdict;
-
-       r->type = IPTCC_R_STANDARD;
-
-       return 1;
-}
-
-static int
-iptcc_map_target(const TC_HANDLE_T handle,
-          struct rule_head *r)
-{
-       STRUCT_ENTRY *e = r->entry;
-       STRUCT_ENTRY_TARGET *t = GET_TARGET(e);
-
-       /* Maybe it's empty (=> fall through) */
-       if (strcmp(t->u.user.name, "") == 0) {
-               r->type = IPTCC_R_FALLTHROUGH;
-               return 1;
-       }
-       /* Maybe it's a standard target name... */
-       else if (strcmp(t->u.user.name, LABEL_ACCEPT) == 0)
-               return iptcc_standard_map(r, -NF_ACCEPT - 1);
-       else if (strcmp(t->u.user.name, LABEL_DROP) == 0)
-               return iptcc_standard_map(r, -NF_DROP - 1);
-       else if (strcmp(t->u.user.name, LABEL_QUEUE) == 0)
-               return iptcc_standard_map(r, -NF_QUEUE - 1);
-       else if (strcmp(t->u.user.name, LABEL_RETURN) == 0)
-               return iptcc_standard_map(r, RETURN);
-       else if (TC_BUILTIN(t->u.user.name, handle)) {
-               /* Can't jump to builtins. */
-               errno = EINVAL;
-               return 0;
-       } else {
-               /* Maybe it's an existing chain name. */
-               struct chain_head *c;
-               DEBUGP("trying to find chain `%s': ", t->u.user.name);
-
-               c = iptcc_find_label(t->u.user.name, handle);
-               if (c) {
-                       DEBUGP_C("found!\n");
-                       r->type = IPTCC_R_JUMP;
-                       r->jump = c;
-                       c->references++;
-                       return 1;
-               }
-               DEBUGP_C("not found :(\n");
-       }
-
-       /* Must be a module?  If not, kernel will reject... */
-       /* memset to all 0 for your memcmp convenience: don't clear version */
-       memset(t->u.user.name + strlen(t->u.user.name),
-              0,
-              FUNCTION_MAXNAMELEN - 1 - strlen(t->u.user.name));
-       r->type = IPTCC_R_MODULE;
-       set_changed(handle);
-       return 1;
-}
-
-/* Insert the entry `fw' in chain `chain' into position `rulenum'. */
-int
-TC_INSERT_ENTRY(const IPT_CHAINLABEL chain,
-               const STRUCT_ENTRY *e,
-               unsigned int rulenum,
-               TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r;
-       struct list_head *prev;
-
-       iptc_fn = TC_INSERT_ENTRY;
-
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       /* first rulenum index = 0
-          first c->num_rules index = 1 */
-       if (rulenum > c->num_rules) {
-               errno = E2BIG;
-               return 0;
-       }
-
-       /* If we are inserting at the end just take advantage of the
-          double linked list, insert will happen before the entry
-          prev points to. */
-       if (rulenum == c->num_rules) {
-               prev = &c->rules;
-       } else if (rulenum + 1 <= c->num_rules/2) {
-               r = iptcc_get_rule_num(c, rulenum + 1);
-               prev = &r->list;
-       } else {
-               r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
-               prev = &r->list;
-       }
-
-       if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
-               errno = ENOMEM;
-               return 0;
-       }
-
-       memcpy(r->entry, e, e->next_offset);
-       r->counter_map.maptype = COUNTER_MAP_SET;
-
-       if (!iptcc_map_target(*handle, r)) {
-               free(r);
-               return 0;
-       }
-
-       list_add_tail(&r->list, prev);
-       c->num_rules++;
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-/* Atomically replace rule `rulenum' in `chain' with `fw'. */
-int
-TC_REPLACE_ENTRY(const IPT_CHAINLABEL chain,
-                const STRUCT_ENTRY *e,
-                unsigned int rulenum,
-                TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r, *old;
-
-       iptc_fn = TC_REPLACE_ENTRY;
-
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (rulenum >= c->num_rules) {
-               errno = E2BIG;
-               return 0;
-       }
-
-       /* Take advantage of the double linked list if possible. */
-       if (rulenum + 1 <= c->num_rules/2) {
-               old = iptcc_get_rule_num(c, rulenum + 1);
-       } else {
-               old = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
-       }
-
-       if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
-               errno = ENOMEM;
-               return 0;
-       }
-
-       memcpy(r->entry, e, e->next_offset);
-       r->counter_map.maptype = COUNTER_MAP_SET;
-
-       if (!iptcc_map_target(*handle, r)) {
-               free(r);
-               return 0;
-       }
-
-       list_add(&r->list, &old->list);
-       iptcc_delete_rule(old);
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-/* Append entry `fw' to chain `chain'.  Equivalent to insert with
-   rulenum = length of chain. */
-int
-TC_APPEND_ENTRY(const IPT_CHAINLABEL chain,
-               const STRUCT_ENTRY *e,
-               TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r;
-
-       iptc_fn = TC_APPEND_ENTRY;
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               DEBUGP("unable to find chain `%s'\n", chain);
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
-               DEBUGP("unable to allocate rule for chain `%s'\n", chain);
-               errno = ENOMEM;
-               return 0;
-       }
-
-       memcpy(r->entry, e, e->next_offset);
-       r->counter_map.maptype = COUNTER_MAP_SET;
-
-       if (!iptcc_map_target(*handle, r)) {
-               DEBUGP("unable to map target of rule for chain `%s'\n", chain);
-               free(r);
-               return 0;
-       }
-
-       list_add_tail(&r->list, &c->rules);
-       c->num_rules++;
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-static inline int
-match_different(const STRUCT_ENTRY_MATCH *a,
-               const unsigned char *a_elems,
-               const unsigned char *b_elems,
-               unsigned char **maskptr)
-{
-       const STRUCT_ENTRY_MATCH *b;
-       unsigned int i;
-
-       /* Offset of b is the same as a. */
-       b = (void *)b_elems + ((unsigned char *)a - a_elems);
-
-       if (a->u.match_size != b->u.match_size)
-               return 1;
-
-       if (strcmp(a->u.user.name, b->u.user.name) != 0)
-               return 1;
-
-       *maskptr += ALIGN(sizeof(*a));
-
-       for (i = 0; i < a->u.match_size - ALIGN(sizeof(*a)); i++)
-               if (((a->data[i] ^ b->data[i]) & (*maskptr)[i]) != 0)
-                       return 1;
-       *maskptr += i;
-       return 0;
-}
-
-static inline int
-target_same(struct rule_head *a, struct rule_head *b,const unsigned char *mask)
-{
-       unsigned int i;
-       STRUCT_ENTRY_TARGET *ta, *tb;
-
-       if (a->type != b->type)
-               return 0;
-
-       ta = GET_TARGET(a->entry);
-       tb = GET_TARGET(b->entry);
-
-       switch (a->type) {
-       case IPTCC_R_FALLTHROUGH:
-               return 1;
-       case IPTCC_R_JUMP:
-               return a->jump == b->jump;
-       case IPTCC_R_STANDARD:
-               return ((STRUCT_STANDARD_TARGET *)ta)->verdict
-                       == ((STRUCT_STANDARD_TARGET *)tb)->verdict;
-       case IPTCC_R_MODULE:
-               if (ta->u.target_size != tb->u.target_size)
-                       return 0;
-               if (strcmp(ta->u.user.name, tb->u.user.name) != 0)
-                       return 0;
-
-               for (i = 0; i < ta->u.target_size - sizeof(*ta); i++)
-                       if (((ta->data[i] ^ tb->data[i]) & mask[i]) != 0)
-                               return 0;
-               return 1;
-       default:
-               fprintf(stderr, "ERROR: bad type %i\n", a->type);
-               abort();
-       }
-}
-
-static unsigned char *
-is_same(const STRUCT_ENTRY *a,
-       const STRUCT_ENTRY *b,
-       unsigned char *matchmask);
-
-/* Delete the first rule in `chain' which matches `fw'. */
-int
-TC_DELETE_ENTRY(const IPT_CHAINLABEL chain,
-               const STRUCT_ENTRY *origfw,
-               unsigned char *matchmask,
-               TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r, *i;
-
-       iptc_fn = TC_DELETE_ENTRY;
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       /* Create a rule_head from origfw. */
-       r = iptcc_alloc_rule(c, origfw->next_offset);
-       if (!r) {
-               errno = ENOMEM;
-               return 0;
-       }
-
-       memcpy(r->entry, origfw, origfw->next_offset);
-       r->counter_map.maptype = COUNTER_MAP_NOMAP;
-       if (!iptcc_map_target(*handle, r)) {
-               DEBUGP("unable to map target of rule for chain `%s'\n", chain);
-               free(r);
-               return 0;
-       } else {
-               /* iptcc_map_target increment target chain references
-                * since this is a fake rule only used for matching
-                * the chain references count is decremented again. 
-                */
-               if (r->type == IPTCC_R_JUMP
-                   && r->jump)
-                       r->jump->references--;
-       }
-
-       list_for_each_entry(i, &c->rules, list) {
-               unsigned char *mask;
-
-               mask = is_same(r->entry, i->entry, matchmask);
-               if (!mask)
-                       continue;
-
-               if (!target_same(r, i, mask))
-                       continue;
-
-               /* If we are about to delete the rule that is the
-                * current iterator, move rule iterator back.  next
-                * pointer will then point to real next node */
-               if (i == (*handle)->rule_iterator_cur) {
-                       (*handle)->rule_iterator_cur = 
-                               list_entry((*handle)->rule_iterator_cur->list.prev,
-                                          struct rule_head, list);
-               }
-
-               c->num_rules--;
-               iptcc_delete_rule(i);
-
-               set_changed(*handle);
-               free(r);
-               return 1;
-       }
-
-       free(r);
-       errno = ENOENT;
-       return 0;
-}
-
-
-/* Delete the rule in position `rulenum' in `chain'. */
-int
-TC_DELETE_NUM_ENTRY(const IPT_CHAINLABEL chain,
-                   unsigned int rulenum,
-                   TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r;
-
-       iptc_fn = TC_DELETE_NUM_ENTRY;
-
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (rulenum >= c->num_rules) {
-               errno = E2BIG;
-               return 0;
-       }
-
-       /* Take advantage of the double linked list if possible. */
-       if (rulenum + 1 <= c->num_rules/2) {
-               r = iptcc_get_rule_num(c, rulenum + 1);
-       } else {
-               r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
-       }
-
-       /* If we are about to delete the rule that is the current
-        * iterator, move rule iterator back.  next pointer will then
-        * point to real next node */
-       if (r == (*handle)->rule_iterator_cur) {
-               (*handle)->rule_iterator_cur = 
-                       list_entry((*handle)->rule_iterator_cur->list.prev,
-                                  struct rule_head, list);
-       }
-
-       c->num_rules--;
-       iptcc_delete_rule(r);
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-/* Check the packet `fw' on chain `chain'.  Returns the verdict, or
-   NULL and sets errno. */
-const char *
-TC_CHECK_PACKET(const IPT_CHAINLABEL chain,
-               STRUCT_ENTRY *entry,
-               TC_HANDLE_T *handle)
-{
-       iptc_fn = TC_CHECK_PACKET;
-       errno = ENOSYS;
-       return NULL;
-}
-
-/* Flushes the entries in the given chain (ie. empties chain). */
-int
-TC_FLUSH_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r, *tmp;
-
-       iptc_fn = TC_FLUSH_ENTRIES;
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       list_for_each_entry_safe(r, tmp, &c->rules, list) {
-               iptcc_delete_rule(r);
-       }
-
-       c->num_rules = 0;
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-/* Zeroes the counters in a chain. */
-int
-TC_ZERO_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r;
-
-       iptc_fn = TC_ZERO_ENTRIES;
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (c->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
-               c->counter_map.maptype = COUNTER_MAP_ZEROED;
-
-       list_for_each_entry(r, &c->rules, list) {
-               if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
-                       r->counter_map.maptype = COUNTER_MAP_ZEROED;
-       }
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-STRUCT_COUNTERS *
-TC_READ_COUNTER(const IPT_CHAINLABEL chain,
-               unsigned int rulenum,
-               TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r;
-
-       iptc_fn = TC_READ_COUNTER;
-       CHECK(*handle);
-
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return NULL;
-       }
-
-       if (!(r = iptcc_get_rule_num(c, rulenum))) {
-               errno = E2BIG;
-               return NULL;
-       }
-
-       return &r->entry[0].counters;
-}
-
-int
-TC_ZERO_COUNTER(const IPT_CHAINLABEL chain,
-               unsigned int rulenum,
-               TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r;
-       
-       iptc_fn = TC_ZERO_COUNTER;
-       CHECK(*handle);
-
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (!(r = iptcc_get_rule_num(c, rulenum))) {
-               errno = E2BIG;
-               return 0;
-       }
-
-       if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
-               r->counter_map.maptype = COUNTER_MAP_ZEROED;
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-int 
-TC_SET_COUNTER(const IPT_CHAINLABEL chain,
-              unsigned int rulenum,
-              STRUCT_COUNTERS *counters,
-              TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       struct rule_head *r;
-       STRUCT_ENTRY *e;
-
-       iptc_fn = TC_SET_COUNTER;
-       CHECK(*handle);
-
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (!(r = iptcc_get_rule_num(c, rulenum))) {
-               errno = E2BIG;
-               return 0;
-       }
-
-       e = r->entry;
-       r->counter_map.maptype = COUNTER_MAP_SET;
-
-       memcpy(&e->counters, counters, sizeof(STRUCT_COUNTERS));
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-/* Creates a new chain. */
-/* To create a chain, create two rules: error node and unconditional
- * return. */
-int
-TC_CREATE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
-{
-       static struct chain_head *c;
-       int capacity;
-       int exceeded;
-
-       iptc_fn = TC_CREATE_CHAIN;
-
-       /* find_label doesn't cover built-in targets: DROP, ACCEPT,
-           QUEUE, RETURN. */
-       if (iptcc_find_label(chain, *handle)
-           || strcmp(chain, LABEL_DROP) == 0
-           || strcmp(chain, LABEL_ACCEPT) == 0
-           || strcmp(chain, LABEL_QUEUE) == 0
-           || strcmp(chain, LABEL_RETURN) == 0) {
-               DEBUGP("Chain `%s' already exists\n", chain);
-               errno = EEXIST;
-               return 0;
-       }
-
-       if (strlen(chain)+1 > sizeof(IPT_CHAINLABEL)) {
-               DEBUGP("Chain name `%s' too long\n", chain);
-               errno = EINVAL;
-               return 0;
-       }
-
-       c = iptcc_alloc_chain_head(chain, 0);
-       if (!c) {
-               DEBUGP("Cannot allocate memory for chain `%s'\n", chain);
-               errno = ENOMEM;
-               return 0;
-
-       }
-       (*handle)->num_chains++; /* New user defined chain */
-
-       DEBUGP("Creating chain `%s'\n", chain);
-       iptc_insert_chain(*handle, c); /* Insert sorted */
-
-       /* Inserting chains don't change the correctness of the chain
-        * index (except if its smaller than index[0], but that
-        * handled by iptc_insert_chain).  It only causes longer lists
-        * in the buckets. Thus, only rebuild chain index when the
-        * capacity is exceed with CHAIN_INDEX_INSERT_MAX chains.
-        */
-       capacity = (*handle)->chain_index_sz * CHAIN_INDEX_BUCKET_LEN;
-       exceeded = ((((*handle)->num_chains)-capacity));
-       if (exceeded > CHAIN_INDEX_INSERT_MAX) {
-               debug("Capacity(%d) exceeded(%d) rebuild (chains:%d)\n",
-                     capacity, exceeded, (*handle)->num_chains);
-               iptcc_chain_index_rebuild(*handle);
-       }
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-/* Get the number of references to this chain. */
-int
-TC_GET_REFERENCES(unsigned int *ref, const IPT_CHAINLABEL chain,
-                 TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-
-       iptc_fn = TC_GET_REFERENCES;
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       *ref = c->references;
-
-       return 1;
-}
-
-/* Deletes a chain. */
-int
-TC_DELETE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle)
-{
-       unsigned int references;
-       struct chain_head *c;
-
-       iptc_fn = TC_DELETE_CHAIN;
-
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               DEBUGP("cannot find chain `%s'\n", chain);
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (TC_BUILTIN(chain, *handle)) {
-               DEBUGP("cannot remove builtin chain `%s'\n", chain);
-               errno = EINVAL;
-               return 0;
-       }
-
-       if (!TC_GET_REFERENCES(&references, chain, handle)) {
-               DEBUGP("cannot get references on chain `%s'\n", chain);
-               return 0;
-       }
-
-       if (references > 0) {
-               DEBUGP("chain `%s' still has references\n", chain);
-               errno = EMLINK;
-               return 0;
-       }
-
-       if (c->num_rules) {
-               DEBUGP("chain `%s' is not empty\n", chain);
-               errno = ENOTEMPTY;
-               return 0;
-       }
-
-       /* If we are about to delete the chain that is the current
-        * iterator, move chain iterator forward. */
-       if (c == (*handle)->chain_iterator_cur)
-               iptcc_chain_iterator_advance(*handle);
-
-       (*handle)->num_chains--; /* One user defined chain deleted */
-
-       //list_del(&c->list); /* Done in iptcc_chain_index_delete_chain() */
-       iptcc_chain_index_delete_chain(c, *handle);
-       free(c);
-
-       DEBUGP("chain `%s' deleted\n", chain);
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-/* Renames a chain. */
-int TC_RENAME_CHAIN(const IPT_CHAINLABEL oldname,
-                   const IPT_CHAINLABEL newname,
-                   TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-       iptc_fn = TC_RENAME_CHAIN;
-
-       /* find_label doesn't cover built-in targets: DROP, ACCEPT,
-           QUEUE, RETURN. */
-       if (iptcc_find_label(newname, *handle)
-           || strcmp(newname, LABEL_DROP) == 0
-           || strcmp(newname, LABEL_ACCEPT) == 0
-           || strcmp(newname, LABEL_QUEUE) == 0
-           || strcmp(newname, LABEL_RETURN) == 0) {
-               errno = EEXIST;
-               return 0;
-       }
-
-       if (!(c = iptcc_find_label(oldname, *handle))
-           || TC_BUILTIN(oldname, *handle)) {
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (strlen(newname)+1 > sizeof(IPT_CHAINLABEL)) {
-               errno = EINVAL;
-               return 0;
-       }
-
-       strncpy(c->name, newname, sizeof(IPT_CHAINLABEL));
-       
-       set_changed(*handle);
-
-       return 1;
-}
-
-/* Sets the policy on a built-in chain. */
-int
-TC_SET_POLICY(const IPT_CHAINLABEL chain,
-             const IPT_CHAINLABEL policy,
-             STRUCT_COUNTERS *counters,
-             TC_HANDLE_T *handle)
-{
-       struct chain_head *c;
-
-       iptc_fn = TC_SET_POLICY;
-
-       if (!(c = iptcc_find_label(chain, *handle))) {
-               DEBUGP("cannot find chain `%s'\n", chain);
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (!iptcc_is_builtin(c)) {
-               DEBUGP("cannot set policy of userdefinedchain `%s'\n", chain);
-               errno = ENOENT;
-               return 0;
-       }
-
-       if (strcmp(policy, LABEL_ACCEPT) == 0)
-               c->verdict = -NF_ACCEPT - 1;
-       else if (strcmp(policy, LABEL_DROP) == 0)
-               c->verdict = -NF_DROP - 1;
-       else {
-               errno = EINVAL;
-               return 0;
-       }
-
-       if (counters) {
-               /* set byte and packet counters */
-               memcpy(&c->counters, counters, sizeof(STRUCT_COUNTERS));
-               c->counter_map.maptype = COUNTER_MAP_SET;
-       } else {
-               c->counter_map.maptype = COUNTER_MAP_NOMAP;
-       }
-
-       set_changed(*handle);
-
-       return 1;
-}
-
-/* Without this, on gcc 2.7.2.3, we get:
-   libiptc.c: In function `TC_COMMIT':
-   libiptc.c:833: fixed or forbidden register was spilled.
-   This may be due to a compiler bug or to impossible asm
-   statements or clauses.
-*/
-static void
-subtract_counters(STRUCT_COUNTERS *answer,
-                 const STRUCT_COUNTERS *a,
-                 const STRUCT_COUNTERS *b)
-{
-       answer->pcnt = a->pcnt - b->pcnt;
-       answer->bcnt = a->bcnt - b->bcnt;
-}
-
-
-static void counters_nomap(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx)
-{
-       newcounters->counters[idx] = ((STRUCT_COUNTERS) { 0, 0});
-       DEBUGP_C("NOMAP => zero\n");
-}
-
-static void counters_normal_map(STRUCT_COUNTERS_INFO *newcounters,
-                               STRUCT_REPLACE *repl, unsigned int idx,
-                               unsigned int mappos)
-{
-       /* Original read: X.
-        * Atomic read on replacement: X + Y.
-        * Currently in kernel: Z.
-        * Want in kernel: X + Y + Z.
-        * => Add in X + Y
-        * => Add in replacement read.
-        */
-       newcounters->counters[idx] = repl->counters[mappos];
-       DEBUGP_C("NORMAL_MAP => mappos %u \n", mappos);
-}
-
-static void counters_map_zeroed(STRUCT_COUNTERS_INFO *newcounters,
-                               STRUCT_REPLACE *repl, unsigned int idx,
-                               unsigned int mappos, STRUCT_COUNTERS *counters)
-{
-       /* Original read: X.
-        * Atomic read on replacement: X + Y.
-        * Currently in kernel: Z.
-        * Want in kernel: Y + Z.
-        * => Add in Y.
-        * => Add in (replacement read - original read).
-        */
-       subtract_counters(&newcounters->counters[idx],
-                         &repl->counters[mappos],
-                         counters);
-       DEBUGP_C("ZEROED => mappos %u\n", mappos);
-}
-
-static void counters_map_set(STRUCT_COUNTERS_INFO *newcounters,
-                             unsigned int idx, STRUCT_COUNTERS *counters)
-{
-       /* Want to set counter (iptables-restore) */
-
-       memcpy(&newcounters->counters[idx], counters,
-               sizeof(STRUCT_COUNTERS));
-
-       DEBUGP_C("SET\n");
-}
-
-
-int
-TC_COMMIT(TC_HANDLE_T *handle)
-{
-       /* Replace, then map back the counters. */
-       STRUCT_REPLACE *repl;
-       STRUCT_COUNTERS_INFO *newcounters;
-       struct chain_head *c;
-       int ret;
-       size_t counterlen;
-       int new_number;
-       unsigned int new_size;
-
-       iptc_fn = TC_COMMIT;
-       CHECK(*handle);
-
-       /* Don't commit if nothing changed. */
-       if (!(*handle)->changed)
-               goto finished;
-
-       new_number = iptcc_compile_table_prep(*handle, &new_size);
-       if (new_number < 0) {
-               errno = ENOMEM;
-               goto out_zero;
-       }
-
-       repl = malloc(sizeof(*repl) + new_size);
-       if (!repl) {
-               errno = ENOMEM;
-               goto out_zero;
-       }
-       memset(repl, 0, sizeof(*repl) + new_size);
-
-#if 0
-       TC_DUMP_ENTRIES(*handle);
-#endif
-
-       counterlen = sizeof(STRUCT_COUNTERS_INFO)
-                       + sizeof(STRUCT_COUNTERS) * new_number;
-
-       /* These are the old counters we will get from kernel */
-       repl->counters = malloc(sizeof(STRUCT_COUNTERS)
-                               * (*handle)->info.num_entries);
-       if (!repl->counters) {
-               errno = ENOMEM;
-               goto out_free_repl;
-       }
-       /* These are the counters we're going to put back, later. */
-       newcounters = malloc(counterlen);
-       if (!newcounters) {
-               errno = ENOMEM;
-               goto out_free_repl_counters;
-       }
-       memset(newcounters, 0, counterlen);
-
-       strcpy(repl->name, (*handle)->info.name);
-       repl->num_entries = new_number;
-       repl->size = new_size;
-
-       repl->num_counters = (*handle)->info.num_entries;
-       repl->valid_hooks = (*handle)->info.valid_hooks;
-
-       DEBUGP("num_entries=%u, size=%u, num_counters=%u\n",
-               repl->num_entries, repl->size, repl->num_counters);
-
-       ret = iptcc_compile_table(*handle, repl);
-       if (ret < 0) {
-               errno = ret;
-               goto out_free_newcounters;
-       }
-
-
-#ifdef IPTC_DEBUG2
-       {
-               int fd = open("/tmp/libiptc-so_set_replace.blob", 
-                               O_CREAT|O_WRONLY);
-               if (fd >= 0) {
-                       write(fd, repl, sizeof(*repl) + repl->size);
-                       close(fd);
-               }
-       }
-#endif
-
-       ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_REPLACE, repl,
-                        sizeof(*repl) + repl->size);
-       if (ret < 0)
-               goto out_free_newcounters;
-
-       /* Put counters back. */
-       strcpy(newcounters->name, (*handle)->info.name);
-       newcounters->num_counters = new_number;
-
-       list_for_each_entry(c, &(*handle)->chains, list) {
-               struct rule_head *r;
-
-               /* Builtin chains have their own counters */
-               if (iptcc_is_builtin(c)) {
-                       DEBUGP("counter for chain-index %u: ", c->foot_index);
-                       switch(c->counter_map.maptype) {
-                       case COUNTER_MAP_NOMAP:
-                               counters_nomap(newcounters, c->foot_index);
-                               break;
-                       case COUNTER_MAP_NORMAL_MAP:
-                               counters_normal_map(newcounters, repl,
-                                                   c->foot_index, 
-                                                   c->counter_map.mappos);
-                               break;
-                       case COUNTER_MAP_ZEROED:
-                               counters_map_zeroed(newcounters, repl,
-                                                   c->foot_index, 
-                                                   c->counter_map.mappos,
-                                                   &c->counters);
-                               break;
-                       case COUNTER_MAP_SET:
-                               counters_map_set(newcounters, c->foot_index,
-                                                &c->counters);
-                               break;
-                       }
-               }
-
-               list_for_each_entry(r, &c->rules, list) {
-                       DEBUGP("counter for index %u: ", r->index);
-                       switch (r->counter_map.maptype) {
-                       case COUNTER_MAP_NOMAP:
-                               counters_nomap(newcounters, r->index);
-                               break;
-
-                       case COUNTER_MAP_NORMAL_MAP:
-                               counters_normal_map(newcounters, repl,
-                                                   r->index, 
-                                                   r->counter_map.mappos);
-                               break;
-
-                       case COUNTER_MAP_ZEROED:
-                               counters_map_zeroed(newcounters, repl,
-                                                   r->index,
-                                                   r->counter_map.mappos,
-                                                   &r->entry->counters);
-                               break;
-
-                       case COUNTER_MAP_SET:
-                               counters_map_set(newcounters, r->index,
-                                                &r->entry->counters);
-                               break;
-                       }
-               }
-       }
-
-#ifdef IPTC_DEBUG2
-       {
-               int fd = open("/tmp/libiptc-so_set_add_counters.blob", 
-                               O_CREAT|O_WRONLY);
-               if (fd >= 0) {
-                       write(fd, newcounters, counterlen);
-                       close(fd);
-               }
-       }
-#endif
-
-       ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_ADD_COUNTERS,
-                        newcounters, counterlen);
-       if (ret < 0)
-               goto out_free_newcounters;
-
-       free(repl->counters);
-       free(repl);
-       free(newcounters);
-
-finished:
-       TC_FREE(handle);
-       return 1;
-
-out_free_newcounters:
-       free(newcounters);
-out_free_repl_counters:
-       free(repl->counters);
-out_free_repl:
-       free(repl);
-out_zero:
-       return 0;
-}
-
-/* Get raw socket. */
-int
-TC_GET_RAW_SOCKET(void)
-{
-       return sockfd;
-}
-
-/* Translates errno numbers into more human-readable form than strerror. */
-const char *
-TC_STRERROR(int err)
-{
-       unsigned int i;
-       struct table_struct {
-               void *fn;
-               int err;
-               const char *message;
-       } table [] =
-         { { TC_INIT, EPERM, "Permission denied (you must be root)" },
-           { TC_INIT, EINVAL, "Module is wrong version" },
-           { TC_INIT, ENOENT, 
-                   "Table does not exist (do you need to insmod?)" },
-           { TC_DELETE_CHAIN, ENOTEMPTY, "Chain is not empty" },
-           { TC_DELETE_CHAIN, EINVAL, "Can't delete built-in chain" },
-           { TC_DELETE_CHAIN, EMLINK,
-             "Can't delete chain with references left" },
-           { TC_CREATE_CHAIN, EEXIST, "Chain already exists" },
-           { TC_INSERT_ENTRY, E2BIG, "Index of insertion too big" },
-           { TC_REPLACE_ENTRY, E2BIG, "Index of replacement too big" },
-           { TC_DELETE_NUM_ENTRY, E2BIG, "Index of deletion too big" },
-           { TC_READ_COUNTER, E2BIG, "Index of counter too big" },
-           { TC_ZERO_COUNTER, E2BIG, "Index of counter too big" },
-           { TC_INSERT_ENTRY, ELOOP, "Loop found in table" },
-           { TC_INSERT_ENTRY, EINVAL, "Target problem" },
-           /* EINVAL for CHECK probably means bad interface. */
-           { TC_CHECK_PACKET, EINVAL,
-             "Bad arguments (does that interface exist?)" },
-           { TC_CHECK_PACKET, ENOSYS,
-             "Checking will most likely never get implemented" },
-           /* ENOENT for DELETE probably means no matching rule */
-           { TC_DELETE_ENTRY, ENOENT,
-             "Bad rule (does a matching rule exist in that chain?)" },
-           { TC_SET_POLICY, ENOENT,
-             "Bad built-in chain name" },
-           { TC_SET_POLICY, EINVAL,
-             "Bad policy name" },
-
-           { NULL, 0, "Incompatible with this kernel" },
-           { NULL, ENOPROTOOPT, "iptables who? (do you need to insmod?)" },
-           { NULL, ENOSYS, "Will be implemented real soon.  I promise ;)" },
-           { NULL, ENOMEM, "Memory allocation problem" },
-           { NULL, ENOENT, "No chain/target/match by that name" },
-         };
-
-       for (i = 0; i < sizeof(table)/sizeof(struct table_struct); i++) {
-               if ((!table[i].fn || table[i].fn == iptc_fn)
-                   && table[i].err == err)
-                       return table[i].message;
-       }
-
-       return strerror(err);
-}
diff --git a/src/owniptc/libiptc.h b/src/owniptc/libiptc.h
deleted file mode 100644 (file)
index 3fc25b6..0000000
+++ /dev/null
@@ -1,187 +0,0 @@
-/**
- * This file was imported from the iptables sources.
- * Copyright (C) 1999-2008 Netfilter Core Team
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- */
-
-#ifndef _LIBIPTC_H
-#define _LIBIPTC_H
-/* Library which manipulates filtering rules. */
-
-#include <linux/types.h>
-#include "ipt_kernel_headers.h"
-#include <linux/netfilter_ipv4/ip_tables.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef IPT_MIN_ALIGN
-/* ipt_entry has pointers and u_int64_t's in it, so if you align to
-   it, you'll also align to any crazy matches and targets someone
-   might write */
-#define IPT_MIN_ALIGN (__alignof__(struct ipt_entry))
-#endif
-
-#define IPT_ALIGN(s) (((s) + ((IPT_MIN_ALIGN)-1)) & ~((IPT_MIN_ALIGN)-1))
-
-typedef char ipt_chainlabel[32];
-
-#define IPTC_LABEL_ACCEPT  "ACCEPT"
-#define IPTC_LABEL_DROP    "DROP"
-#define IPTC_LABEL_QUEUE   "QUEUE"
-#define IPTC_LABEL_RETURN  "RETURN"
-
-/* Transparent handle type. */
-typedef struct iptc_handle *iptc_handle_t;
-
-/* Does this chain exist? */
-int iptc_is_chain(const char *chain, const iptc_handle_t handle);
-
-/* Take a snapshot of the rules.  Returns NULL on error. */
-iptc_handle_t iptc_init(const char *tablename);
-
-/* Cleanup after iptc_init(). */
-void iptc_free(iptc_handle_t *h);
-
-/* Iterator functions to run through the chains.  Returns NULL at end. */
-const char *iptc_first_chain(iptc_handle_t *handle);
-const char *iptc_next_chain(iptc_handle_t *handle);
-
-/* Get first rule in the given chain: NULL for empty chain. */
-const struct ipt_entry *iptc_first_rule(const char *chain,
-                                       iptc_handle_t *handle);
-
-/* Returns NULL when rules run out. */
-const struct ipt_entry *iptc_next_rule(const struct ipt_entry *prev,
-                                      iptc_handle_t *handle);
-
-/* Returns a pointer to the target name of this entry. */
-const char *iptc_get_target(const struct ipt_entry *e,
-                           iptc_handle_t *handle);
-
-/* Is this a built-in chain? */
-int iptc_builtin(const char *chain, const iptc_handle_t handle);
-
-/* Get the policy of a given built-in chain */
-const char *iptc_get_policy(const char *chain,
-                           struct ipt_counters *counter,
-                           iptc_handle_t *handle);
-
-/* These functions return TRUE for OK or 0 and set errno.  If errno ==
-   0, it means there was a version error (ie. upgrade libiptc). */
-/* Rule numbers start at 1 for the first rule. */
-
-/* Insert the entry `e' in chain `chain' into position `rulenum'. */
-int iptc_insert_entry(const ipt_chainlabel chain,
-                     const struct ipt_entry *e,
-                     unsigned int rulenum,
-                     iptc_handle_t *handle);
-
-/* Atomically replace rule `rulenum' in `chain' with `e'. */
-int iptc_replace_entry(const ipt_chainlabel chain,
-                      const struct ipt_entry *e,
-                      unsigned int rulenum,
-                      iptc_handle_t *handle);
-
-/* Append entry `e' to chain `chain'.  Equivalent to insert with
-   rulenum = length of chain. */
-int iptc_append_entry(const ipt_chainlabel chain,
-                     const struct ipt_entry *e,
-                     iptc_handle_t *handle);
-
-/* Delete the first rule in `chain' which matches `e', subject to
-   matchmask (array of length == origfw) */
-int iptc_delete_entry(const ipt_chainlabel chain,
-                     const struct ipt_entry *origfw,
-                     unsigned char *matchmask,
-                     iptc_handle_t *handle);
-
-/* Delete the rule in position `rulenum' in `chain'. */
-int iptc_delete_num_entry(const ipt_chainlabel chain,
-                         unsigned int rulenum,
-                         iptc_handle_t *handle);
-
-/* Check the packet `e' on chain `chain'.  Returns the verdict, or
-   NULL and sets errno. */
-const char *iptc_check_packet(const ipt_chainlabel chain,
-                             struct ipt_entry *entry,
-                             iptc_handle_t *handle);
-
-/* Flushes the entries in the given chain (ie. empties chain). */
-int iptc_flush_entries(const ipt_chainlabel chain,
-                      iptc_handle_t *handle);
-
-/* Zeroes the counters in a chain. */
-int iptc_zero_entries(const ipt_chainlabel chain,
-                     iptc_handle_t *handle);
-
-/* Creates a new chain. */
-int iptc_create_chain(const ipt_chainlabel chain,
-                     iptc_handle_t *handle);
-
-/* Deletes a chain. */
-int iptc_delete_chain(const ipt_chainlabel chain,
-                     iptc_handle_t *handle);
-
-/* Renames a chain. */
-int iptc_rename_chain(const ipt_chainlabel oldname,
-                     const ipt_chainlabel newname,
-                     iptc_handle_t *handle);
-
-/* Sets the policy on a built-in chain. */
-int iptc_set_policy(const ipt_chainlabel chain,
-                   const ipt_chainlabel policy,
-                   struct ipt_counters *counters,
-                   iptc_handle_t *handle);
-
-/* Get the number of references to this chain */
-int iptc_get_references(unsigned int *ref,
-                       const ipt_chainlabel chain,
-                       iptc_handle_t *handle);
-
-/* read packet and byte counters for a specific rule */
-struct ipt_counters *iptc_read_counter(const ipt_chainlabel chain,
-                                      unsigned int rulenum,
-                                      iptc_handle_t *handle);
-
-/* zero packet and byte counters for a specific rule */
-int iptc_zero_counter(const ipt_chainlabel chain,
-                     unsigned int rulenum,
-                     iptc_handle_t *handle);
-
-/* set packet and byte counters for a specific rule */
-int iptc_set_counter(const ipt_chainlabel chain,
-                    unsigned int rulenum,
-                    struct ipt_counters *counters,
-                    iptc_handle_t *handle);
-
-/* Makes the actual changes. */
-int iptc_commit(iptc_handle_t *handle);
-
-/* Get raw socket. */
-int iptc_get_raw_socket(void);
-
-/* Translates errno numbers into more human-readable form than strerror. */
-const char *iptc_strerror(int err);
-
-extern void dump_entries(const iptc_handle_t);
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif /* _LIBIPTC_H */
diff --git a/src/owniptc/libxtc.h b/src/owniptc/libxtc.h
deleted file mode 100644 (file)
index 2ed03f4..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * This file was imported from the iptables sources.
- * Copyright (C) 1999-2008 Netfilter Core Team
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- */
-
-#ifndef _LIBXTC_H
-#define _LIBXTC_H
-/* Library which manipulates filtering rules. */
-
-#include "ipt_kernel_headers.h"
-#include <linux/netfilter/x_tables.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef XT_MIN_ALIGN
-/* xt_entry has pointers and u_int64_t's in it, so if you align to
-   it, you'll also align to any crazy matches and targets someone
-   might write */
-#define XT_MIN_ALIGN (__alignof__(struct xt_entry))
-#endif
-
-#ifndef XT_ALIGN
-#define XT_ALIGN(s) (((s) + ((XT_MIN_ALIGN)-1)) & ~((XT_MIN_ALIGN)-1))
-#endif
-
-typedef char xt_chainlabel[32];
-
-#define XTC_LABEL_ACCEPT  "ACCEPT"
-#define XTC_LABEL_DROP    "DROP"
-#define XTC_LABEL_QUEUE   "QUEUE"
-#define XTC_LABEL_RETURN  "RETURN"
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _LIBXTC_H */
diff --git a/src/owniptc/linux_list.h b/src/owniptc/linux_list.h
deleted file mode 100644 (file)
index 56d9a26..0000000
+++ /dev/null
@@ -1,741 +0,0 @@
-/**
- * This file was imported from the iptables sources.
- * Copyright (C) 1999-2008 Netfilter Core Team
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- */
-
-#ifndef _LINUX_LIST_H
-#define _LINUX_LIST_H
-
-#undef offsetof
-#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
-
-/**
- * container_of - cast a member of a structure out to the containing structure
- *
- * @ptr:       the pointer to the member.
- * @type:      the type of the container struct this is embedded in.
- * @member:    the name of the member within the struct.
- *
- */
-#define container_of(ptr, type, member) ({                     \
-        const typeof( ((type *)0)->member ) *__mptr = (ptr);   \
-        (type *)( (char *)__mptr - offsetof(type,member) );})
-
-/*
- * Check at compile time that something is of a particular type.
- * Always evaluates to 1 so you may use it easily in comparisons.
- */
-#define typecheck(type,x) \
-({     type __dummy; \
-       typeof(x) __dummy2; \
-       (void)(&__dummy == &__dummy2); \
-       1; \
-})
-
-#define prefetch(x)            1
-
-/* empty define to make this work in userspace -HW */
-#define smp_wmb()
-
-/*
- * These are non-NULL pointers that will result in page faults
- * under normal circumstances, used to verify that nobody uses
- * non-initialized list entries.
- */
-#define LIST_POISON1  ((void *) 0x00100100)
-#define LIST_POISON2  ((void *) 0x00200200)
-
-/*
- * Simple doubly linked list implementation.
- *
- * Some of the internal functions ("__xxx") are useful when
- * manipulating whole lists rather than single entries, as
- * sometimes we already know the next/prev entries and we can
- * generate better code by using them directly rather than
- * using the generic single-entry routines.
- */
-
-struct list_head {
-       struct list_head *next, *prev;
-};
-
-#define LIST_HEAD_INIT(name) { &(name), &(name) }
-
-#define LIST_HEAD(name) \
-       struct list_head name = LIST_HEAD_INIT(name)
-
-#define INIT_LIST_HEAD(ptr) do { \
-       (ptr)->next = (ptr); (ptr)->prev = (ptr); \
-} while (0)
-
-/*
- * Insert a new entry between two known consecutive entries.
- *
- * This is only for internal list manipulation where we know
- * the prev/next entries already!
- */
-static inline void __list_add(struct list_head *new,
-                             struct list_head *prev,
-                             struct list_head *next)
-{
-       next->prev = new;
-       new->next = next;
-       new->prev = prev;
-       prev->next = new;
-}
-
-/**
- * list_add - add a new entry
- * @new: new entry to be added
- * @head: list head to add it after
- *
- * Insert a new entry after the specified head.
- * This is good for implementing stacks.
- */
-static inline void list_add(struct list_head *new, struct list_head *head)
-{
-       __list_add(new, head, head->next);
-}
-
-/**
- * list_add_tail - add a new entry
- * @new: new entry to be added
- * @head: list head to add it before
- *
- * Insert a new entry before the specified head.
- * This is useful for implementing queues.
- */
-static inline void list_add_tail(struct list_head *new, struct list_head *head)
-{
-       __list_add(new, head->prev, head);
-}
-
-/*
- * Insert a new entry between two known consecutive entries.
- *
- * This is only for internal list manipulation where we know
- * the prev/next entries already!
- */
-static inline void __list_add_rcu(struct list_head * new,
-               struct list_head * prev, struct list_head * next)
-{
-       new->next = next;
-       new->prev = prev;
-       smp_wmb();
-       next->prev = new;
-       prev->next = new;
-}
-
-/**
- * list_add_rcu - add a new entry to rcu-protected list
- * @new: new entry to be added
- * @head: list head to add it after
- *
- * Insert a new entry after the specified head.
- * This is good for implementing stacks.
- *
- * The caller must take whatever precautions are necessary
- * (such as holding appropriate locks) to avoid racing
- * with another list-mutation primitive, such as list_add_rcu()
- * or list_del_rcu(), running on this same list.
- * However, it is perfectly legal to run concurrently with
- * the _rcu list-traversal primitives, such as
- * list_for_each_entry_rcu().
- */
-static inline void list_add_rcu(struct list_head *new, struct list_head *head)
-{
-       __list_add_rcu(new, head, head->next);
-}
-
-/**
- * list_add_tail_rcu - add a new entry to rcu-protected list
- * @new: new entry to be added
- * @head: list head to add it before
- *
- * Insert a new entry before the specified head.
- * This is useful for implementing queues.
- *
- * The caller must take whatever precautions are necessary
- * (such as holding appropriate locks) to avoid racing
- * with another list-mutation primitive, such as list_add_tail_rcu()
- * or list_del_rcu(), running on this same list.
- * However, it is perfectly legal to run concurrently with
- * the _rcu list-traversal primitives, such as
- * list_for_each_entry_rcu().
- */
-static inline void list_add_tail_rcu(struct list_head *new,
-                                       struct list_head *head)
-{
-       __list_add_rcu(new, head->prev, head);
-}
-
-/*
- * Delete a list entry by making the prev/next entries
- * point to each other.
- *
- * This is only for internal list manipulation where we know
- * the prev/next entries already!
- */
-static inline void __list_del(struct list_head * prev, struct list_head * next)
-{
-       next->prev = prev;
-       prev->next = next;
-}
-
-/**
- * list_del - deletes entry from list.
- * @entry: the element to delete from the list.
- * Note: list_empty on entry does not return true after this, the entry is
- * in an undefined state.
- */
-static inline void list_del(struct list_head *entry)
-{
-       __list_del(entry->prev, entry->next);
-       entry->next = LIST_POISON1;
-       entry->prev = LIST_POISON2;
-}
-
-/**
- * list_del_rcu - deletes entry from list without re-initialization
- * @entry: the element to delete from the list.
- *
- * Note: list_empty on entry does not return true after this,
- * the entry is in an undefined state. It is useful for RCU based
- * lockfree traversal.
- *
- * In particular, it means that we can not poison the forward
- * pointers that may still be used for walking the list.
- *
- * The caller must take whatever precautions are necessary
- * (such as holding appropriate locks) to avoid racing
- * with another list-mutation primitive, such as list_del_rcu()
- * or list_add_rcu(), running on this same list.
- * However, it is perfectly legal to run concurrently with
- * the _rcu list-traversal primitives, such as
- * list_for_each_entry_rcu().
- *
- * Note that the caller is not permitted to immediately free
- * the newly deleted entry.  Instead, either synchronize_kernel()
- * or call_rcu() must be used to defer freeing until an RCU
- * grace period has elapsed.
- */
-static inline void list_del_rcu(struct list_head *entry)
-{
-       __list_del(entry->prev, entry->next);
-       entry->prev = LIST_POISON2;
-}
-
-/**
- * list_del_init - deletes entry from list and reinitialize it.
- * @entry: the element to delete from the list.
- */
-static inline void list_del_init(struct list_head *entry)
-{
-       __list_del(entry->prev, entry->next);
-       INIT_LIST_HEAD(entry);
-}
-
-/**
- * list_move - delete from one list and add as another's head
- * @list: the entry to move
- * @head: the head that will precede our entry
- */
-static inline void list_move(struct list_head *list, struct list_head *head)
-{
-        __list_del(list->prev, list->next);
-        list_add(list, head);
-}
-
-/**
- * list_move_tail - delete from one list and add as another's tail
- * @list: the entry to move
- * @head: the head that will follow our entry
- */
-static inline void list_move_tail(struct list_head *list,
-                                 struct list_head *head)
-{
-        __list_del(list->prev, list->next);
-        list_add_tail(list, head);
-}
-
-/**
- * list_empty - tests whether a list is empty
- * @head: the list to test.
- */
-static inline int list_empty(const struct list_head *head)
-{
-       return head->next == head;
-}
-
-/**
- * list_empty_careful - tests whether a list is
- * empty _and_ checks that no other CPU might be
- * in the process of still modifying either member
- *
- * NOTE: using list_empty_careful() without synchronization
- * can only be safe if the only activity that can happen
- * to the list entry is list_del_init(). Eg. it cannot be used
- * if another CPU could re-list_add() it.
- *
- * @head: the list to test.
- */
-static inline int list_empty_careful(const struct list_head *head)
-{
-       struct list_head *next = head->next;
-       return (next == head) && (next == head->prev);
-}
-
-static inline void __list_splice(struct list_head *list,
-                                struct list_head *head)
-{
-       struct list_head *first = list->next;
-       struct list_head *last = list->prev;
-       struct list_head *at = head->next;
-
-       first->prev = head;
-       head->next = first;
-
-       last->next = at;
-       at->prev = last;
-}
-
-/**
- * list_splice - join two lists
- * @list: the new list to add.
- * @head: the place to add it in the first list.
- */
-static inline void list_splice(struct list_head *list, struct list_head *head)
-{
-       if (!list_empty(list))
-               __list_splice(list, head);
-}
-
-/**
- * list_splice_init - join two lists and reinitialise the emptied list.
- * @list: the new list to add.
- * @head: the place to add it in the first list.
- *
- * The list at @list is reinitialised
- */
-static inline void list_splice_init(struct list_head *list,
-                                   struct list_head *head)
-{
-       if (!list_empty(list)) {
-               __list_splice(list, head);
-               INIT_LIST_HEAD(list);
-       }
-}
-
-/**
- * list_entry - get the struct for this entry
- * @ptr:       the &struct list_head pointer.
- * @type:      the type of the struct this is embedded in.
- * @member:    the name of the list_struct within the struct.
- */
-#define list_entry(ptr, type, member) \
-       container_of(ptr, type, member)
-
-/**
- * list_for_each       -       iterate over a list
- * @pos:       the &struct list_head to use as a loop counter.
- * @head:      the head for your list.
- */
-#define list_for_each(pos, head) \
-       for (pos = (head)->next, prefetch(pos->next); pos != (head); \
-               pos = pos->next, prefetch(pos->next))
-
-/**
- * __list_for_each     -       iterate over a list
- * @pos:       the &struct list_head to use as a loop counter.
- * @head:      the head for your list.
- *
- * This variant differs from list_for_each() in that it's the
- * simplest possible list iteration code, no prefetching is done.
- * Use this for code that knows the list to be very short (empty
- * or 1 entry) most of the time.
- */
-#define __list_for_each(pos, head) \
-       for (pos = (head)->next; pos != (head); pos = pos->next)
-
-/**
- * list_for_each_prev  -       iterate over a list backwards
- * @pos:       the &struct list_head to use as a loop counter.
- * @head:      the head for your list.
- */
-#define list_for_each_prev(pos, head) \
-       for (pos = (head)->prev, prefetch(pos->prev); pos != (head); \
-               pos = pos->prev, prefetch(pos->prev))
-
-/**
- * list_for_each_safe  -       iterate over a list safe against removal of list entry
- * @pos:       the &struct list_head to use as a loop counter.
- * @n:         another &struct list_head to use as temporary storage
- * @head:      the head for your list.
- */
-#define list_for_each_safe(pos, n, head) \
-       for (pos = (head)->next, n = pos->next; pos != (head); \
-               pos = n, n = pos->next)
-
-/**
- * list_for_each_entry -       iterate over list of given type
- * @pos:       the type * to use as a loop counter.
- * @head:      the head for your list.
- * @member:    the name of the list_struct within the struct.
- */
-#define list_for_each_entry(pos, head, member)                         \
-       for (pos = list_entry((head)->next, typeof(*pos), member),      \
-                    prefetch(pos->member.next);                        \
-            &pos->member != (head);                                    \
-            pos = list_entry(pos->member.next, typeof(*pos), member),  \
-                    prefetch(pos->member.next))
-
-/**
- * list_for_each_entry_reverse - iterate backwards over list of given type.
- * @pos:       the type * to use as a loop counter.
- * @head:      the head for your list.
- * @member:    the name of the list_struct within the struct.
- */
-#define list_for_each_entry_reverse(pos, head, member)                 \
-       for (pos = list_entry((head)->prev, typeof(*pos), member),      \
-                    prefetch(pos->member.prev);                        \
-            &pos->member != (head);                                    \
-            pos = list_entry(pos->member.prev, typeof(*pos), member),  \
-                    prefetch(pos->member.prev))
-
-/**
- * list_prepare_entry - prepare a pos entry for use as a start point in
- *                     list_for_each_entry_continue
- * @pos:       the type * to use as a start point
- * @head:      the head of the list
- * @member:    the name of the list_struct within the struct.
- */
-#define list_prepare_entry(pos, head, member) \
-       ((pos) ? : list_entry(head, typeof(*pos), member))
-
-/**
- * list_for_each_entry_continue -      iterate over list of given type
- *                     continuing after existing point
- * @pos:       the type * to use as a loop counter.
- * @head:      the head for your list.
- * @member:    the name of the list_struct within the struct.
- */
-#define list_for_each_entry_continue(pos, head, member)                \
-       for (pos = list_entry(pos->member.next, typeof(*pos), member),  \
-                    prefetch(pos->member.next);                        \
-            &pos->member != (head);                                    \
-            pos = list_entry(pos->member.next, typeof(*pos), member),  \
-                    prefetch(pos->member.next))
-
-/**
- * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
- * @pos:       the type * to use as a loop counter.
- * @n:         another type * to use as temporary storage
- * @head:      the head for your list.
- * @member:    the name of the list_struct within the struct.
- */
-#define list_for_each_entry_safe(pos, n, head, member)                 \
-       for (pos = list_entry((head)->next, typeof(*pos), member),      \
-               n = list_entry(pos->member.next, typeof(*pos), member); \
-            &pos->member != (head);                                    \
-            pos = n, n = list_entry(n->member.next, typeof(*n), member))
-
-/**
- * list_for_each_rcu   -       iterate over an rcu-protected list
- * @pos:       the &struct list_head to use as a loop counter.
- * @head:      the head for your list.
- *
- * This list-traversal primitive may safely run concurrently with
- * the _rcu list-mutation primitives such as list_add_rcu()
- * as long as the traversal is guarded by rcu_read_lock().
- */
-#define list_for_each_rcu(pos, head) \
-       for (pos = (head)->next, prefetch(pos->next); pos != (head); \
-               pos = pos->next, ({ smp_read_barrier_depends(); 0;}), prefetch(pos->next))
-
-#define __list_for_each_rcu(pos, head) \
-       for (pos = (head)->next; pos != (head); \
-               pos = pos->next, ({ smp_read_barrier_depends(); 0;}))
-
-/**
- * list_for_each_safe_rcu      -       iterate over an rcu-protected list safe
- *                                     against removal of list entry
- * @pos:       the &struct list_head to use as a loop counter.
- * @n:         another &struct list_head to use as temporary storage
- * @head:      the head for your list.
- *
- * This list-traversal primitive may safely run concurrently with
- * the _rcu list-mutation primitives such as list_add_rcu()
- * as long as the traversal is guarded by rcu_read_lock().
- */
-#define list_for_each_safe_rcu(pos, n, head) \
-       for (pos = (head)->next, n = pos->next; pos != (head); \
-               pos = n, ({ smp_read_barrier_depends(); 0;}), n = pos->next)
-
-/**
- * list_for_each_entry_rcu     -       iterate over rcu list of given type
- * @pos:       the type * to use as a loop counter.
- * @head:      the head for your list.
- * @member:    the name of the list_struct within the struct.
- *
- * This list-traversal primitive may safely run concurrently with
- * the _rcu list-mutation primitives such as list_add_rcu()
- * as long as the traversal is guarded by rcu_read_lock().
- */
-#define list_for_each_entry_rcu(pos, head, member)                     \
-       for (pos = list_entry((head)->next, typeof(*pos), member),      \
-                    prefetch(pos->member.next);                        \
-            &pos->member != (head);                                    \
-            pos = list_entry(pos->member.next, typeof(*pos), member),  \
-                    ({ smp_read_barrier_depends(); 0;}),               \
-                    prefetch(pos->member.next))
-
-
-/**
- * list_for_each_continue_rcu  -       iterate over an rcu-protected list
- *                     continuing after existing point.
- * @pos:       the &struct list_head to use as a loop counter.
- * @head:      the head for your list.
- *
- * This list-traversal primitive may safely run concurrently with
- * the _rcu list-mutation primitives such as list_add_rcu()
- * as long as the traversal is guarded by rcu_read_lock().
- */
-#define list_for_each_continue_rcu(pos, head) \
-       for ((pos) = (pos)->next, prefetch((pos)->next); (pos) != (head); \
-               (pos) = (pos)->next, ({ smp_read_barrier_depends(); 0;}), prefetch((pos)->next))
-
-/*
- * Double linked lists with a single pointer list head.
- * Mostly useful for hash tables where the two pointer list head is
- * too wasteful.
- * You lose the ability to access the tail in O(1).
- */
-
-struct hlist_head {
-       struct hlist_node *first;
-};
-
-struct hlist_node {
-       struct hlist_node *next, **pprev;
-};
-
-#define HLIST_HEAD_INIT { .first = NULL }
-#define HLIST_HEAD(name) struct hlist_head name = {  .first = NULL }
-#define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL)
-#define INIT_HLIST_NODE(ptr) ((ptr)->next = NULL, (ptr)->pprev = NULL)
-
-static inline int hlist_unhashed(const struct hlist_node *h)
-{
-       return !h->pprev;
-}
-
-static inline int hlist_empty(const struct hlist_head *h)
-{
-       return !h->first;
-}
-
-static inline void __hlist_del(struct hlist_node *n)
-{
-       struct hlist_node *next = n->next;
-       struct hlist_node **pprev = n->pprev;
-       *pprev = next;
-       if (next)
-               next->pprev = pprev;
-}
-
-static inline void hlist_del(struct hlist_node *n)
-{
-       __hlist_del(n);
-       n->next = LIST_POISON1;
-       n->pprev = LIST_POISON2;
-}
-
-/**
- * hlist_del_rcu - deletes entry from hash list without re-initialization
- * @n: the element to delete from the hash list.
- *
- * Note: list_unhashed() on entry does not return true after this,
- * the entry is in an undefined state. It is useful for RCU based
- * lockfree traversal.
- *
- * In particular, it means that we can not poison the forward
- * pointers that may still be used for walking the hash list.
- *
- * The caller must take whatever precautions are necessary
- * (such as holding appropriate locks) to avoid racing
- * with another list-mutation primitive, such as hlist_add_head_rcu()
- * or hlist_del_rcu(), running on this same list.
- * However, it is perfectly legal to run concurrently with
- * the _rcu list-traversal primitives, such as
- * hlist_for_each_entry().
- */
-static inline void hlist_del_rcu(struct hlist_node *n)
-{
-       __hlist_del(n);
-       n->pprev = LIST_POISON2;
-}
-
-static inline void hlist_del_init(struct hlist_node *n)
-{
-       if (n->pprev)  {
-               __hlist_del(n);
-               INIT_HLIST_NODE(n);
-       }
-}
-
-#define hlist_del_rcu_init hlist_del_init
-
-static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
-{
-       struct hlist_node *first = h->first;
-       n->next = first;
-       if (first)
-               first->pprev = &n->next;
-       h->first = n;
-       n->pprev = &h->first;
-}
-
-
-/**
- * hlist_add_head_rcu - adds the specified element to the specified hlist,
- * while permitting racing traversals.
- * @n: the element to add to the hash list.
- * @h: the list to add to.
- *
- * The caller must take whatever precautions are necessary
- * (such as holding appropriate locks) to avoid racing
- * with another list-mutation primitive, such as hlist_add_head_rcu()
- * or hlist_del_rcu(), running on this same list.
- * However, it is perfectly legal to run concurrently with
- * the _rcu list-traversal primitives, such as
- * hlist_for_each_entry(), but only if smp_read_barrier_depends()
- * is used to prevent memory-consistency problems on Alpha CPUs.
- * Regardless of the type of CPU, the list-traversal primitive
- * must be guarded by rcu_read_lock().
- *
- * OK, so why don't we have an hlist_for_each_entry_rcu()???
- */
-static inline void hlist_add_head_rcu(struct hlist_node *n,
-                                       struct hlist_head *h)
-{
-       struct hlist_node *first = h->first;
-       n->next = first;
-       n->pprev = &h->first;
-       smp_wmb();
-       if (first)
-               first->pprev = &n->next;
-       h->first = n;
-}
-
-/* next must be != NULL */
-static inline void hlist_add_before(struct hlist_node *n,
-                                       struct hlist_node *next)
-{
-       n->pprev = next->pprev;
-       n->next = next;
-       next->pprev = &n->next;
-       *(n->pprev) = n;
-}
-
-static inline void hlist_add_after(struct hlist_node *n,
-                                       struct hlist_node *next)
-{
-       next->next = n->next;
-       n->next = next;
-       next->pprev = &n->next;
-
-       if(next->next)
-               next->next->pprev  = &next->next;
-}
-
-#define hlist_entry(ptr, type, member) container_of(ptr,type,member)
-
-#define hlist_for_each(pos, head) \
-       for (pos = (head)->first; pos && ({ prefetch(pos->next); 1; }); \
-            pos = pos->next)
-
-#define hlist_for_each_safe(pos, n, head) \
-       for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \
-            pos = n)
-
-/**
- * hlist_for_each_entry        - iterate over list of given type
- * @tpos:      the type * to use as a loop counter.
- * @pos:       the &struct hlist_node to use as a loop counter.
- * @head:      the head for your list.
- * @member:    the name of the hlist_node within the struct.
- */
-#define hlist_for_each_entry(tpos, pos, head, member)                   \
-       for (pos = (head)->first;                                        \
-            pos && ({ prefetch(pos->next); 1;}) &&                      \
-               ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
-            pos = pos->next)
-
-/**
- * hlist_for_each_entry_continue - iterate over a hlist continuing after existing point
- * @tpos:      the type * to use as a loop counter.
- * @pos:       the &struct hlist_node to use as a loop counter.
- * @member:    the name of the hlist_node within the struct.
- */
-#define hlist_for_each_entry_continue(tpos, pos, member)                \
-       for (pos = (pos)->next;                                          \
-            pos && ({ prefetch(pos->next); 1;}) &&                      \
-               ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
-            pos = pos->next)
-
-/**
- * hlist_for_each_entry_from - iterate over a hlist continuing from existing point
- * @tpos:      the type * to use as a loop counter.
- * @pos:       the &struct hlist_node to use as a loop counter.
- * @member:    the name of the hlist_node within the struct.
- */
-#define hlist_for_each_entry_from(tpos, pos, member)                    \
-       for (; pos && ({ prefetch(pos->next); 1;}) &&                    \
-               ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
-            pos = pos->next)
-
-/**
- * hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry
- * @tpos:      the type * to use as a loop counter.
- * @pos:       the &struct hlist_node to use as a loop counter.
- * @n:         another &struct hlist_node to use as temporary storage
- * @head:      the head for your list.
- * @member:    the name of the hlist_node within the struct.
- */
-#define hlist_for_each_entry_safe(tpos, pos, n, head, member)           \
-       for (pos = (head)->first;                                        \
-            pos && ({ n = pos->next; 1; }) &&                           \
-               ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
-            pos = n)
-
-/**
- * hlist_for_each_entry_rcu - iterate over rcu list of given type
- * @pos:       the type * to use as a loop counter.
- * @pos:       the &struct hlist_node to use as a loop counter.
- * @head:      the head for your list.
- * @member:    the name of the hlist_node within the struct.
- *
- * This list-traversal primitive may safely run concurrently with
- * the _rcu list-mutation primitives such as hlist_add_rcu()
- * as long as the traversal is guarded by rcu_read_lock().
- */
-#define hlist_for_each_entry_rcu(tpos, pos, head, member)               \
-       for (pos = (head)->first;                                        \
-            pos && ({ prefetch(pos->next); 1;}) &&                      \
-               ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
-            pos = pos->next, ({ smp_read_barrier_depends(); 0; }) )
-
-#endif
diff --git a/src/owniptc/xtables.h b/src/owniptc/xtables.h
deleted file mode 100644 (file)
index 47e47dc..0000000
+++ /dev/null
@@ -1,239 +0,0 @@
-/**
- * This file was imported from the iptables sources.
- * Copyright (C) 1999-2008 Netfilter Core Team
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- */
-
-#ifndef _XTABLES_H
-#define _XTABLES_H
-
-#include <sys/types.h>
-#include <linux/types.h>
-#include <linux/netfilter/x_tables.h>
-#include "libxtc.h"
-#include <stdbool.h>
-
-#ifndef IPPROTO_SCTP
-#define IPPROTO_SCTP 132
-#endif
-#ifndef IPPROTO_DCCP
-#define IPPROTO_DCCP 33
-#endif
-#ifndef IPPROTO_UDPLITE
-#define IPPROTO_UDPLITE        136
-#endif
-
-#define XTABLES_VERSION "1.4.1.1"
-#define XTABLES_VERSION_CODE (0x10000 * 1 + 0x100 * 4 + 1)
-
-#define XTABLES_API_VERSION(x,y,z)    (0x10000*(x) + 0x100*(y) + z)
-
-/* Include file for additions: new matches and targets. */
-struct xtables_match
-{
-       struct xtables_match *next;
-
-       xt_chainlabel name;
-
-       /* Revision of match (0 by default). */
-       u_int8_t revision;
-
-       u_int16_t family;
-
-       const char *version;
-
-       /* Size of match data. */
-       size_t size;
-
-       /* Size of match data relevent for userspace comparison purposes */
-       size_t userspacesize;
-
-       /* Function which prints out usage message. */
-       void (*help)(void);
-
-       /* Initialize the match. */
-       void (*init)(struct xt_entry_match *m);
-
-       /* Function which parses command options; returns true if it
-           ate an option */
-       /* entry is struct ipt_entry for example */
-       int (*parse)(int c, char **argv, int invert, unsigned int *flags,
-                    const void *entry,
-                    struct xt_entry_match **match);
-
-       /* Final check; exit if not ok. */
-       void (*final_check)(unsigned int flags);
-
-       /* Prints out the match iff non-NULL: put space at end */
-       /* ip is struct ipt_ip * for example */
-       void (*print)(const void *ip,
-                     const struct xt_entry_match *match, int numeric);
-
-       /* Saves the match info in parsable form to stdout. */
-       /* ip is struct ipt_ip * for example */
-       void (*save)(const void *ip, const struct xt_entry_match *match);
-
-       /* Pointer to list of extra command-line options */
-       const struct option *extra_opts;
-
-       /* Ignore these men behind the curtain: */
-       unsigned int option_offset;
-       struct xt_entry_match *m;
-       unsigned int mflags;
-#ifdef NO_SHARED_LIBS
-       unsigned int loaded; /* simulate loading so options are merged properly */
-#endif
-};
-
-struct xtables_target
-{
-       struct xtables_target *next;
-
-       xt_chainlabel name;
-
-       /* Revision of target (0 by default). */
-       u_int8_t revision;
-
-       u_int16_t family;
-
-       const char *version;
-
-       /* Size of target data. */
-       size_t size;
-
-       /* Size of target data relevent for userspace comparison purposes */
-       size_t userspacesize;
-
-       /* Function which prints out usage message. */
-       void (*help)(void);
-
-       /* Initialize the target. */
-       void (*init)(struct xt_entry_target *t);
-
-       /* Function which parses command options; returns true if it
-           ate an option */
-       /* entry is struct ipt_entry for example */
-       int (*parse)(int c, char **argv, int invert, unsigned int *flags,
-                    const void *entry,
-                    struct xt_entry_target **targetinfo);
-
-       /* Final check; exit if not ok. */
-       void (*final_check)(unsigned int flags);
-
-       /* Prints out the target iff non-NULL: put space at end */
-       void (*print)(const void *ip,
-                     const struct xt_entry_target *target, int numeric);
-
-       /* Saves the targinfo in parsable form to stdout. */
-       void (*save)(const void *ip,
-                    const struct xt_entry_target *target);
-
-       /* Pointer to list of extra command-line options */
-       const struct option *extra_opts;
-
-       /* Ignore these men behind the curtain: */
-       unsigned int option_offset;
-       struct xt_entry_target *t;
-       unsigned int tflags;
-       unsigned int used;
-#ifdef NO_SHARED_LIBS
-       unsigned int loaded; /* simulate loading so options are merged properly */
-#endif
-};
-
-/* Your shared library should call one of these. */
-extern void xtables_register_match(struct xtables_match *me);
-extern void xtables_register_target(struct xtables_target *me);
-
-extern int string_to_number_ll(const char *s,
-                              unsigned long long min,
-                              unsigned long long max,
-                              unsigned long long *ret);
-extern int string_to_number_l(const char *s,
-                             unsigned long min,
-                             unsigned long max,
-                             unsigned long *ret);
-extern int string_to_number(const char *s,
-                           unsigned int min,
-                           unsigned int max,
-                           unsigned int *ret);
-extern bool strtonuml(const char *, char **, unsigned long *,
-       unsigned long, unsigned long);
-extern bool strtonum(const char *, char **, unsigned int *,
-       unsigned int, unsigned int);
-extern int service_to_port(const char *name, const char *proto);
-extern u_int16_t parse_port(const char *port, const char *proto);
-extern void
-parse_interface(const char *arg, char *vianame, unsigned char *mask);
-
-enum exittype {
-       OTHER_PROBLEM = 1,
-       PARAMETER_PROBLEM,
-       VERSION_PROBLEM,
-       RESOURCE_PROBLEM,
-       P_ONLY_ONCE,
-       P_NO_INVERT,
-       P_BAD_VALUE,
-       P_ONE_ACTION,
-};
-
-/* this is a special 64bit data type that is 8-byte aligned */
-#define aligned_u64 u_int64_t __attribute__((aligned(8)))
-
-int check_inverse(const char option[], int *invert, int *my_optind, int argc);
-void exit_error(enum exittype, const char *, ...)__attribute__((noreturn,
-                                                         format(printf,2,3)));
-extern void param_act(unsigned int, const char *, ...);
-extern const char *program_name, *program_version;
-
-extern const char *ipaddr_to_numeric(const struct in_addr *);
-extern const char *ipaddr_to_anyname(const struct in_addr *);
-extern const char *ipmask_to_numeric(const struct in_addr *);
-extern struct in_addr *numeric_to_ipaddr(const char *);
-extern struct in_addr *numeric_to_ipmask(const char *);
-extern void ipparse_hostnetworkmask(const char *, struct in_addr **,
-       struct in_addr *, unsigned int *);
-
-extern struct in6_addr *numeric_to_ip6addr(const char *);
-extern const char *ip6addr_to_numeric(const struct in6_addr *);
-extern const char *ip6addr_to_anyname(const struct in6_addr *);
-extern const char *ip6mask_to_numeric(const struct in6_addr *);
-extern void ip6parse_hostnetworkmask(const char *, struct in6_addr **,
-       struct in6_addr *, unsigned int *);
-
-/**
- * Print the specified value to standard output, quoting dangerous
- * characters if required.
- */
-extern void save_string(const char *value);
-
-#ifdef NO_SHARED_LIBS
-#      ifdef _INIT
-#              undef _init
-#              define _init _INIT
-#      endif
-       extern void init_extensions(void);
-#else
-#      define _init __attribute__((constructor)) _INIT
-#endif
-
-/* Present in both iptables.c and ip6tables.c */
-extern u_int16_t parse_protocol(const char *s);
-
-#ifdef XTABLES_INTERNAL
-#      include <xtables/internal.h>
-#endif
-
-#endif /* _XTABLES_H */
index 7260580..78e508a 100644 (file)
@@ -102,6 +102,7 @@ void boot_DynaLoader (PerlInterpreter *, CV *);
 static XS (Collectd_plugin_register_ds);
 static XS (Collectd_plugin_unregister_ds);
 static XS (Collectd_plugin_dispatch_values);
+static XS (Collectd_plugin_get_interval);
 static XS (Collectd__plugin_write);
 static XS (Collectd__plugin_flush);
 static XS (Collectd_plugin_dispatch_notification);
@@ -177,6 +178,7 @@ static struct {
        { "Collectd::plugin_register_data_set",   Collectd_plugin_register_ds },
        { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
        { "Collectd::plugin_dispatch_values",     Collectd_plugin_dispatch_values },
+       { "Collectd::plugin_get_interval",        Collectd_plugin_get_interval },
        { "Collectd::_plugin_write",              Collectd__plugin_write },
        { "Collectd::_plugin_flush",              Collectd__plugin_flush },
        { "Collectd::plugin_dispatch_notification",
@@ -235,15 +237,6 @@ struct {
        { "", NULL }
 };
 
-struct {
-       char  name[64];
-       int  *var;
-} g_integers[] =
-{
-       { "Collectd::interval_g", &interval_g },
-       { "", NULL }
-};
-
 /*
  * Helper functions for data type conversion.
  */
@@ -397,10 +390,16 @@ static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
        }
 
        if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
-               vl->time = (time_t)SvIV (*tmp);
+       {
+               double t = SvNV (*tmp);
+               vl->time = DOUBLE_TO_CDTIME_T (t);
+       }
 
        if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
-               vl->interval = SvIV (*tmp);
+       {
+               double t = SvNV (*tmp);
+               vl->interval = DOUBLE_TO_CDTIME_T (t);
+       }
 
        if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
                sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
@@ -552,9 +551,12 @@ static int hv2notification (pTHX_ HV *hash, notification_t *n)
                n->severity = NOTIF_FAILURE;
 
        if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
-               n->time = (time_t)SvIV (*tmp);
+       {
+               double t = SvNV (*tmp);
+               n->time = DOUBLE_TO_CDTIME_T (t);
+       }
        else
-               n->time = time (NULL);
+               n->time = cdtime ();
 
        if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
                sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
@@ -672,11 +674,17 @@ static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
                return -1;
 
        if (0 != vl->time)
-               if (NULL == hv_store (hash, "time", 4, newSViv (vl->time), 0))
+       {
+               double t = CDTIME_T_TO_DOUBLE (vl->time);
+               if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
                        return -1;
+       }
 
-       if (NULL == hv_store (hash, "interval", 8, newSViv (vl->interval), 0))
-               return -1;
+       {
+               double t = CDTIME_T_TO_DOUBLE (vl->interval);
+               if (NULL == hv_store (hash, "interval", 8, newSVnv (t), 0))
+                       return -1;
+       }
 
        if ('\0' != vl->host[0])
                if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
@@ -754,8 +762,11 @@ static int notification2hv (pTHX_ notification_t *n, HV *hash)
                return -1;
 
        if (0 != n->time)
-               if (NULL == hv_store (hash, "time", 4, newSViv (n->time), 0))
+       {
+               double t = CDTIME_T_TO_DOUBLE (n->time);
+               if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
                        return -1;
+       }
 
        if ('\0' != *n->message)
                if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
@@ -1106,11 +1117,15 @@ static int pplugin_call_all (pTHX_ int type, ...)
                XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
        }
        else if (PLUGIN_FLUSH == type) {
+               cdtime_t timeout;
+
                /*
                 * $_[0] = $timeout;
                 * $_[1] = $identifier;
                 */
-               XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
+               timeout = va_arg (ap, cdtime_t);
+
+               XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
                XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
        }
 
@@ -1646,6 +1661,21 @@ static XS (Collectd_plugin_dispatch_values)
                XSRETURN_EMPTY;
 } /* static XS (Collectd_plugin_dispatch_values) */
 
+/*
+ * Collectd::plugin_get_interval ().
+ */
+static XS (Collectd_plugin_get_interval)
+{
+       dXSARGS;
+
+       /* make sure we don't get any unused variable warnings for 'items';
+        * don't abort, though */
+       if (items)
+               log_err ("Usage: Collectd::plugin_get_interval()");
+
+       XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
+} /* static XS (Collectd_plugin_get_interval) */
+
 /* Collectd::plugin_write (plugin, ds, vl).
  *
  * plugin:
@@ -1916,6 +1946,11 @@ static int perl_read (void)
                aTHX = t->interp;
        }
 
+       /* Assert that we're not running as the base thread. Otherwise, we might
+        * run into concurrency issues with c_ithread_create(). See
+        * https://github.com/collectd/collectd/issues/9 for details. */
+       assert (aTHX != perl_threads->head->interp);
+
        log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
                        aTHX, perl_threads->number_of_threads);
        return pplugin_call_all (aTHX_ PLUGIN_READ);
@@ -1924,6 +1959,7 @@ static int perl_read (void)
 static int perl_write (const data_set_t *ds, const value_list_t *vl,
                user_data_t __attribute__((unused)) *user_data)
 {
+       int status;
        dTHX;
 
        if (NULL == perl_threads)
@@ -1939,9 +1975,20 @@ static int perl_write (const data_set_t *ds, const value_list_t *vl,
                aTHX = t->interp;
        }
 
+       /* Lock the base thread if this is not called from one of the read threads
+        * to avoid race conditions with c_ithread_create(). See
+        * https://github.com/collectd/collectd/issues/9 for details. */
+       if (aTHX == perl_threads->head->interp)
+               pthread_mutex_lock (&perl_threads->mutex);
+
        log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
                        aTHX, perl_threads->number_of_threads);
-       return pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
+       status = pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
+
+       if (aTHX == perl_threads->head->interp)
+               pthread_mutex_unlock (&perl_threads->mutex);
+
+       return status;
 } /* static int perl_write (const data_set_t *, const value_list_t *) */
 
 static void perl_log (int level, const char *msg,
@@ -1962,7 +2009,17 @@ static void perl_log (int level, const char *msg,
                aTHX = t->interp;
        }
 
+       /* Lock the base thread if this is not called from one of the read threads
+        * to avoid race conditions with c_ithread_create(). See
+        * https://github.com/collectd/collectd/issues/9 for details. */
+       if (aTHX == perl_threads->head->interp)
+               pthread_mutex_lock (&perl_threads->mutex);
+
        pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
+
+       if (aTHX == perl_threads->head->interp)
+               pthread_mutex_unlock (&perl_threads->mutex);
+
        return;
 } /* static void perl_log (int, const char *) */
 
@@ -1986,7 +2043,7 @@ static int perl_notify (const notification_t *notif,
        return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
 } /* static int perl_notify (const notification_t *) */
 
-static int perl_flush (int timeout, const char *identifier,
+static int perl_flush (cdtime_t timeout, const char *identifier,
                user_data_t __attribute__((unused)) *user_data)
 {
        dTHX;
@@ -2088,19 +2145,24 @@ static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
        return 0;
 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
 
-static int g_iv_get (pTHX_ SV *var, MAGIC *mg)
+static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
 {
-       int *iv = (int *)mg->mg_ptr;
-       sv_setiv (var, *iv);
+       log_warn ("Accessing $interval_g is deprecated (and might not "
+                       "give the desired results) - plugin_get_interval() should "
+                       "be used instead.");
+       sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
        return 0;
-} /* static int g_iv_get (pTHX_ SV *, MAGIC *) */
+} /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
 
-static int g_iv_set (pTHX_ SV *var, MAGIC *mg)
+static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
 {
-       int *iv = (int *)mg->mg_ptr;
-       *iv = (int)SvIV (var);
+       double nv = (double)SvNV (var);
+       log_warn ("Accessing $interval_g is deprecated (and might not "
+                       "give the desired results) - plugin_get_interval() should "
+                       "be used instead.");
+       interval_g = DOUBLE_TO_CDTIME_T (nv);
        return 0;
-} /* static int g_iv_set (pTHX_ SV *, MAGIC *) */
+} /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
 
 static MGVTBL g_pv_vtbl = {
        g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
@@ -2108,8 +2170,8 @@ static MGVTBL g_pv_vtbl = {
                , NULL
 #endif
 };
-static MGVTBL g_iv_vtbl = {
-       g_iv_get, g_iv_set, NULL, NULL, NULL, NULL, NULL
+static MGVTBL g_interval_vtbl = {
+       g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
                , NULL
 #endif
@@ -2151,12 +2213,11 @@ static void xs_init (pTHX)
                                g_strings[i].var, 0);
        }
 
-       /* global integers */
-       for (i = 0; '\0' != g_integers[i].name[0]; ++i) {
-               tmp = get_sv (g_integers[i].name, 1);
-               sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_iv_vtbl,
-                               (char *)g_integers[i].var, 0);
-       }
+       tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
+       sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
+                       /* vtbl = */ &g_interval_vtbl,
+                       /* name = */ NULL, /* namelen = */ 0);
+
        return;
 } /* static void xs_init (pTHX) */
 
index a6fd06f..6879733 100644 (file)
@@ -617,7 +617,7 @@ static int plugin_config (oconfig_item_t *ci) /* {{{ */
     if (strcasecmp ("Address", child->key) == 0)
       cf_util_get_string (child, &conf_node);
     else if (strcasecmp ("Port", child->key) == 0)
-      cf_util_get_string (child, &conf_service);
+      cf_util_get_service (child, &conf_service);
     else if (strcasecmp ("View", child->key) == 0)
       pinba_config_view (child);
     else
@@ -645,7 +645,7 @@ static int plugin_init (void) /* {{{ */
   if (collector_thread_running)
     return (0);
 
-  status = pthread_create (&collector_thread_id,
+  status = plugin_thread_create (&collector_thread_id,
       /* attrs = */ NULL,
       collector_thread,
       /* args = */ NULL);
index b536f42..8bbb807 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/ping.c
- * Copyright (C) 2005-2009  Florian octo Forster
+ * Copyright (C) 2005-2012  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
 #include "common.h"
 #include "plugin.h"
 #include "configfile.h"
+#include "utils_complain.h"
 
 #include <pthread.h>
 #include <netinet/in.h>
@@ -142,6 +143,97 @@ static void time_calc (struct timespec *ts_dest, /* {{{ */
   time_normalize (ts_dest);
 } /* }}} void time_calc */
 
+static int ping_dispatch_all (pingobj_t *pingobj) /* {{{ */
+{
+  pingobj_iter_t *iter;
+  hostlist_t *hl;
+  int status;
+
+  for (iter = ping_iterator_get (pingobj);
+      iter != NULL;
+      iter = ping_iterator_next (iter))
+  { /* {{{ */
+    char userhost[NI_MAXHOST];
+    double latency;
+    size_t param_size;
+
+    param_size = sizeof (userhost);
+    status = ping_iterator_get_info (iter,
+#ifdef PING_INFO_USERNAME
+        PING_INFO_USERNAME,
+#else
+        PING_INFO_HOSTNAME,
+#endif
+        userhost, &param_size);
+    if (status != 0)
+    {
+      WARNING ("ping plugin: ping_iterator_get_info failed: %s",
+          ping_get_error (pingobj));
+      continue;
+    }
+
+    for (hl = hostlist_head; hl != NULL; hl = hl->next)
+      if (strcmp (userhost, hl->host) == 0)
+        break;
+
+    if (hl == NULL)
+    {
+      WARNING ("ping plugin: Cannot find host %s.", userhost);
+      continue;
+    }
+
+    param_size = sizeof (latency);
+    status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
+        (void *) &latency, &param_size);
+    if (status != 0)
+    {
+      WARNING ("ping plugin: ping_iterator_get_info failed: %s",
+          ping_get_error (pingobj));
+      continue;
+    }
+
+    hl->pkg_sent++;
+    if (latency >= 0.0)
+    {
+      hl->pkg_recv++;
+      hl->latency_total += latency;
+      hl->latency_squared += (latency * latency);
+
+      /* reset missed packages counter */
+      hl->pkg_missed = 0;
+    } else
+      hl->pkg_missed++;
+
+    /* if the host did not answer our last N packages, trigger a resolv. */
+    if (ping_max_missed >= 0 && hl->pkg_missed >= ping_max_missed)
+    { /* {{{ */
+      /* we reset the missed package counter here, since we only want to
+       * trigger a resolv every N packages and not every package _AFTER_ N
+       * missed packages */
+      hl->pkg_missed = 0;
+
+      WARNING ("ping plugin: host %s has not answered %d PING requests,"
+          " triggering resolve", hl->host, ping_max_missed);
+
+      /* we trigger the resolv simply be removeing and adding the host to our
+       * ping object */
+      status = ping_host_remove (pingobj, hl->host);
+      if (status != 0)
+      {
+        WARNING ("ping plugin: ping_host_remove (%s) failed.", hl->host);
+      }
+      else
+      {
+        status = ping_host_add (pingobj, hl->host);
+        if (status != 0)
+          ERROR ("ping plugin: ping_host_add (%s) failed.", hl->host);
+      }
+    } /* }}} ping_max_missed */
+  } /* }}} for (iter) */
+
+  return (0);
+} /* }}} int ping_dispatch_all */
+
 static void *ping_thread (void *arg) /* {{{ */
 {
   static pingobj_t *pingobj = NULL;
@@ -154,6 +246,8 @@ static void *ping_thread (void *arg) /* {{{ */
   hostlist_t *hl;
   int count;
 
+  c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
+
   pthread_mutex_lock (&ping_lock);
 
   pingobj = ping_construct ();
@@ -213,8 +307,8 @@ static void *ping_thread (void *arg) /* {{{ */
 
   while (ping_thread_loop > 0)
   {
-    pingobj_iter_t *iter;
     int status;
+    _Bool send_successful = 0;
 
     if (gettimeofday (&tv_begin, NULL) < 0)
     {
@@ -230,10 +324,13 @@ static void *ping_thread (void *arg) /* {{{ */
     status = ping_send (pingobj);
     if (status < 0)
     {
-      ERROR ("ping plugin: ping_send failed: %s", ping_get_error (pingobj));
-      pthread_mutex_lock (&ping_lock);
-      ping_thread_error = 1;
-      break;
+      c_complain (LOG_ERR, &complaint, "ping plugin: ping_send failed: %s",
+          ping_get_error (pingobj));
+    }
+    else
+    {
+      c_release (LOG_NOTICE, &complaint, "ping plugin: ping_send succeeded.");
+      send_successful = 1;
     }
 
     pthread_mutex_lock (&ping_lock);
@@ -241,87 +338,8 @@ static void *ping_thread (void *arg) /* {{{ */
     if (ping_thread_loop <= 0)
       break;
 
-    for (iter = ping_iterator_get (pingobj);
-        iter != NULL;
-        iter = ping_iterator_next (iter))
-    { /* {{{ */
-      char userhost[NI_MAXHOST];
-      double latency;
-      size_t param_size;
-
-      param_size = sizeof (userhost);
-      status = ping_iterator_get_info (iter,
-#ifdef PING_INFO_USERNAME
-          PING_INFO_USERNAME,
-#else
-          PING_INFO_HOSTNAME,
-#endif
-          userhost, &param_size);
-      if (status != 0)
-      {
-        WARNING ("ping plugin: ping_iterator_get_info failed: %s",
-            ping_get_error (pingobj));
-        continue;
-      }
-
-      for (hl = hostlist_head; hl != NULL; hl = hl->next)
-        if (strcmp (userhost, hl->host) == 0)
-          break;
-
-      if (hl == NULL)
-      {
-        WARNING ("ping plugin: Cannot find host %s.", userhost);
-        continue;
-      }
-
-      param_size = sizeof (latency);
-      status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
-          (void *) &latency, &param_size);
-      if (status != 0)
-      {
-        WARNING ("ping plugin: ping_iterator_get_info failed: %s",
-            ping_get_error (pingobj));
-        continue;
-      }
-
-      hl->pkg_sent++;
-      if (latency >= 0.0)
-      {
-        hl->pkg_recv++;
-        hl->latency_total += latency;
-        hl->latency_squared += (latency * latency);
-
-        /* reset missed packages counter */
-        hl->pkg_missed = 0;
-      } else
-        hl->pkg_missed++;
-
-      /* if the host did not answer our last N packages, trigger a resolv. */
-      if (ping_max_missed >= 0 && hl->pkg_missed >= ping_max_missed)
-      { /* {{{ */
-        /* we reset the missed package counter here, since we only want to
-         * trigger a resolv every N packages and not every package _AFTER_ N
-         * missed packages */
-        hl->pkg_missed = 0;
-
-        WARNING ("ping plugin: host %s has not answered %d PING requests,"
-          " triggering resolve", hl->host, ping_max_missed);
-
-        /* we trigger the resolv simply be removeing and adding the host to our
-         * ping object */
-        status = ping_host_remove (pingobj, hl->host);
-        if (status != 0)
-        {
-          WARNING ("ping plugin: ping_host_remove (%s) failed.", hl->host);
-        }
-        else
-        {
-          status = ping_host_add (pingobj, hl->host);
-          if (status != 0)
-            WARNING ("ping plugin: ping_host_add (%s) failed.", hl->host);
-        }
-      } /* }}} ping_max_missed */
-    } /* }}} for (iter) */
+    if (send_successful)
+      (void) ping_dispatch_all (pingobj);
 
     if (gettimeofday (&tv_end, NULL) < 0)
     {
@@ -361,7 +379,7 @@ static int start_thread (void) /* {{{ */
 
   ping_thread_loop = 1;
   ping_thread_error = 0;
-  status = pthread_create (&ping_thread_id, /* attr = */ NULL,
+  status = plugin_thread_create (&ping_thread_id, /* attr = */ NULL,
       ping_thread, /* arg = */ (void *) 0);
   if (status != 0)
   {
index 65d3875..bbede05 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/plugin.c
- * Copyright (C) 2005-2009  Florian octo Forster
+ * Copyright (C) 2005-2011  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Sebastian Harl <sh at tokkee.org>
  **/
 
@@ -36,7 +36,6 @@
 #include "utils_llist.h"
 #include "utils_heap.h"
 #include "utils_cache.h"
-#include "utils_threshold.h"
 #include "filter_chain.h"
 
 /*
@@ -46,6 +45,7 @@ struct callback_func_s
 {
        void *cf_callback;
        user_data_t cf_udata;
+       plugin_ctx_t cf_ctx;
 };
 typedef struct callback_func_s callback_func_t;
 
@@ -58,6 +58,7 @@ struct read_func_s
         * The `rf_super' member MUST be the first one in this structure! */
 #define rf_callback rf_super.cf_callback
 #define rf_udata rf_super.cf_udata
+#define rf_ctx rf_super.cf_ctx
        callback_func_t rf_super;
        char rf_group[DATA_MAX_NAME_LEN];
        char rf_name[DATA_MAX_NAME_LEN];
@@ -74,6 +75,7 @@ typedef struct read_func_s read_func_t;
 static llist_t *list_init;
 static llist_t *list_write;
 static llist_t *list_flush;
+static llist_t *list_missing;
 static llist_t *list_shutdown;
 static llist_t *list_log;
 static llist_t *list_notification;
@@ -93,6 +95,9 @@ static pthread_cond_t  read_cond = PTHREAD_COND_INITIALIZER;
 static pthread_t      *read_threads = NULL;
 static int             read_threads_num = 0;
 
+static pthread_key_t   plugin_ctx_key;
+static _Bool           plugin_ctx_key_initialized = 0;
+
 /*
  * Static functions
  */
@@ -246,6 +251,8 @@ static int create_register_callback (llist_t **list, /* {{{ */
                cf->cf_udata = *ud;
        }
 
+       cf->cf_ctx = plugin_get_ctx ();
+
        return (register_callback (list, name, cf));
 } /* }}} int create_register_callback */
 
@@ -280,8 +287,6 @@ static int plugin_load_file (char *file, uint32_t flags)
        lt_dlhandle dlh;
        void (*reg_handle) (void);
 
-       DEBUG ("file = %s", file);
-
        lt_dlinit ();
        lt_dlerror (); /* clear errors */
 
@@ -293,27 +298,39 @@ static int plugin_load_file (char *file, uint32_t flags)
                dlh = lt_dlopenadvise(file, advise);
                lt_dladvise_destroy(&advise);
        } else {
-               dlh = lt_dlopen (file);
+               dlh = lt_dlopen (file);
        }
 #else /* if LIBTOOL_VERSION == 1 */
        if (flags & PLUGIN_FLAGS_GLOBAL)
-               ERROR ("plugin_load_file: The global flag is not supported, "
+               WARNING ("plugin_load_file: The global flag is not supported, "
                                "libtool 2 is required for this.");
        dlh = lt_dlopen (file);
 #endif
 
        if (dlh == NULL)
        {
-               const char *error = lt_dlerror ();
+               char errbuf[1024] = "";
+
+               ssnprintf (errbuf, sizeof (errbuf),
+                               "lt_dlopen (\"%s\") failed: %s. "
+                               "The most common cause for this problem are "
+                               "missing dependencies. Use ldd(1) to check "
+                               "the dependencies of the plugin "
+                               "/ shared object.",
+                               file, lt_dlerror ());
+
+               ERROR ("%s", errbuf);
+               /* Make sure this is printed to STDERR in any case, but also
+                * make sure it's printed only once. */
+               if (list_log != NULL)
+                       fprintf (stderr, "ERROR: %s\n", errbuf);
 
-               ERROR ("lt_dlopen (%s) failed: %s", file, error);
-               fprintf (stderr, "lt_dlopen (%s) failed: %s\n", file, error);
                return (1);
        }
 
        if ((reg_handle = (void (*) (void)) lt_dlsym (dlh, "module_register")) == NULL)
        {
-               WARNING ("Couldn't find symbol `module_register' in `%s': %s\n",
+               WARNING ("Couldn't find symbol \"module_register\" in \"%s\": %s\n",
                                file, lt_dlerror ());
                lt_dlclose (dlh);
                return (-1);
@@ -336,40 +353,38 @@ static void *plugin_read_thread (void __attribute__((unused)) *args)
        while (read_loop != 0)
        {
                read_func_t *rf;
-               struct timeval now;
+               plugin_ctx_t old_ctx;
+               cdtime_t now;
                int status;
                int rf_type;
                int rc;
 
-               /* Get the read function that needs to be read next. */
+               /* Get the read function that needs to be read next.
+                * We don't need to hold "read_lock" for the heap, but we need
+                * to call c_heap_get_root() and pthread_cond_wait() in the
+                * same protected block. */
+               pthread_mutex_lock (&read_lock);
                rf = c_heap_get_root (read_heap);
                if (rf == NULL)
                {
-                       struct timespec abstime;
-
-                       gettimeofday (&now, /* timezone = */ NULL);
-
-                       abstime.tv_sec = now.tv_sec + interval_g;
-                       abstime.tv_nsec = 1000 * now.tv_usec;
-
-                       pthread_mutex_lock (&read_lock);
-                       pthread_cond_timedwait (&read_cond, &read_lock,
-                                       &abstime);
-                       pthread_mutex_unlock (&read_lock);
+                       pthread_cond_wait (&read_cond, &read_lock);
+                        pthread_mutex_unlock (&read_lock);
                        continue;
                }
+               pthread_mutex_unlock (&read_lock);
 
                if ((rf->rf_interval.tv_sec == 0) && (rf->rf_interval.tv_nsec == 0))
                {
-                       gettimeofday (&now, /* timezone = */ NULL);
+                       /* this should not happen, because the interval is set
+                        * for each plugin when loading it
+                        * XXX: issue a warning? */
+                       now = cdtime ();
 
-                       rf->rf_interval.tv_sec = interval_g;
-                       rf->rf_interval.tv_nsec = 0;
+                       CDTIME_T_TO_TIMESPEC (plugin_get_interval (), &rf->rf_interval);
 
                        rf->rf_effective_interval = rf->rf_interval;
 
-                       rf->rf_next_read.tv_sec = now.tv_sec;
-                       rf->rf_next_read.tv_nsec = 1000 * now.tv_usec;
+                       CDTIME_T_TO_TIMESPEC (now, &rf->rf_next_read);
                }
 
                /* sleep until this entry is due,
@@ -416,6 +431,8 @@ static void *plugin_read_thread (void __attribute__((unused)) *args)
 
                DEBUG ("plugin_read_thread: Handling `%s'.", rf->rf_name);
 
+               old_ctx = plugin_set_ctx (rf->rf_ctx);
+
                if (rf_type == RF_SIMPLE)
                {
                        int (*callback) (void);
@@ -433,6 +450,8 @@ static void *plugin_read_thread (void __attribute__((unused)) *args)
                        status = (*callback) (&rf->rf_udata);
                }
 
+               plugin_set_ctx (old_ctx);
+
                /* If the function signals failure, we will increase the
                 * intervals in which it will be called. */
                if (status != 0)
@@ -459,7 +478,7 @@ static void *plugin_read_thread (void __attribute__((unused)) *args)
                }
 
                /* update the ``next read due'' field */
-               gettimeofday (&now, /* timezone = */ NULL);
+               now = cdtime ();
 
                DEBUG ("plugin_read_thread: Effective interval of the "
                                "%s plugin is %i.%09i.",
@@ -476,15 +495,12 @@ static void *plugin_read_thread (void __attribute__((unused)) *args)
                NORMALIZE_TIMESPEC (rf->rf_next_read);
 
                /* Check, if `rf_next_read' is in the past. */
-               if ((rf->rf_next_read.tv_sec < now.tv_sec)
-                               || ((rf->rf_next_read.tv_sec == now.tv_sec)
-                                       && (rf->rf_next_read.tv_nsec < (1000 * now.tv_usec))))
+               if (TIMESPEC_TO_CDTIME_T (&rf->rf_next_read) < now)
                {
                        /* `rf_next_read' is in the past. Insert `now'
                         * so this value doesn't trail off into the
                         * past too much. */
-                       rf->rf_next_read.tv_sec = now.tv_sec;
-                       rf->rf_next_read.tv_nsec = 1000 * now.tv_usec;
+                       CDTIME_T_TO_TIMESPEC (now, &rf->rf_next_read);
                }
 
                DEBUG ("plugin_read_thread: Next read of the %s plugin at %i.%09i.",
@@ -734,6 +750,17 @@ static int plugin_insert_read (read_func_t *rf)
                }
        }
 
+       le = llist_search (read_list, rf->rf_name);
+       if (le != NULL)
+       {
+               pthread_mutex_unlock (&read_lock);
+               WARNING ("The read function \"%s\" is already registered. "
+                               "Check for duplicate \"LoadPlugin\" lines "
+                               "in your configuration!",
+                               rf->rf_name);
+               return (EINVAL);
+       }
+
        le = llentry_create (rf->rf_name, rf);
        if (le == NULL)
        {
@@ -754,28 +781,61 @@ static int plugin_insert_read (read_func_t *rf)
        /* This does not fail. */
        llist_append (read_list, le);
 
+       /* Wake up all the read threads. */
+       pthread_cond_broadcast (&read_cond);
        pthread_mutex_unlock (&read_lock);
        return (0);
 } /* int plugin_insert_read */
 
+static int read_cb_wrapper (user_data_t *ud)
+{
+       int (*callback) (void);
+
+       if (ud == NULL)
+               return -1;
+
+       callback = ud->data;
+       return callback();
+} /* int read_cb_wrapper */
+
 int plugin_register_read (const char *name,
                int (*callback) (void))
 {
        read_func_t *rf;
+       plugin_ctx_t ctx = plugin_get_ctx ();
+       int status;
+
+       if (ctx.interval != 0) {
+               /* If ctx.interval is not zero (== use the plugin or global
+                * interval), we need to use the "complex" read callback,
+                * because only that allows to specify a different interval.
+                * Wrap the callback using read_cb_wrapper(). */
+               struct timespec interval;
+               user_data_t user_data;
 
-       rf = (read_func_t *) malloc (sizeof (read_func_t));
+               user_data.data = callback;
+               user_data.free_func = NULL;
+
+               CDTIME_T_TO_TIMESPEC (ctx.interval, &interval);
+               return plugin_register_complex_read (/* group = */ NULL,
+                               name, read_cb_wrapper, &interval, &user_data);
+       }
+
+       DEBUG ("plugin_register_read: default_interval = %.3f",
+                       CDTIME_T_TO_DOUBLE(plugin_get_interval ()));
+
+       rf = malloc (sizeof (*rf));
        if (rf == NULL)
        {
-               char errbuf[1024];
-               ERROR ("plugin_register_read: malloc failed: %s",
-                               sstrerror (errno, errbuf, sizeof (errbuf)));
-               return (-1);
+               ERROR ("plugin_register_read: malloc failed.");
+               return (ENOMEM);
        }
 
        memset (rf, 0, sizeof (read_func_t));
        rf->rf_callback = (void *) callback;
        rf->rf_udata.data = NULL;
        rf->rf_udata.free_func = NULL;
+       rf->rf_ctx = ctx;
        rf->rf_group[0] = '\0';
        sstrncpy (rf->rf_name, name, sizeof (rf->rf_name));
        rf->rf_type = RF_SIMPLE;
@@ -783,7 +843,11 @@ int plugin_register_read (const char *name,
        rf->rf_interval.tv_nsec = 0;
        rf->rf_effective_interval = rf->rf_interval;
 
-       return (plugin_insert_read (rf));
+       status = plugin_insert_read (rf);
+       if (status != 0)
+               sfree (rf);
+
+       return (status);
 } /* int plugin_register_read */
 
 int plugin_register_complex_read (const char *group, const char *name,
@@ -792,12 +856,14 @@ int plugin_register_complex_read (const char *group, const char *name,
                user_data_t *user_data)
 {
        read_func_t *rf;
+       plugin_ctx_t ctx = plugin_get_ctx ();
+       int status;
 
-       rf = (read_func_t *) malloc (sizeof (read_func_t));
+       rf = malloc (sizeof (*rf));
        if (rf == NULL)
        {
                ERROR ("plugin_register_complex_read: malloc failed.");
-               return (-1);
+               return (ENOMEM);
        }
 
        memset (rf, 0, sizeof (read_func_t));
@@ -812,8 +878,16 @@ int plugin_register_complex_read (const char *group, const char *name,
        {
                rf->rf_interval = *interval;
        }
+       else if (ctx.interval != 0)
+       {
+               CDTIME_T_TO_TIMESPEC (ctx.interval, &rf->rf_interval);
+       }
        rf->rf_effective_interval = rf->rf_interval;
 
+       DEBUG ("plugin_register_read: interval = %i.%09i",
+                       (int) rf->rf_interval.tv_sec,
+                       (int) rf->rf_interval.tv_nsec);
+
        /* Set user data */
        if (user_data == NULL)
        {
@@ -825,7 +899,13 @@ int plugin_register_complex_read (const char *group, const char *name,
                rf->rf_udata = *user_data;
        }
 
-       return (plugin_insert_read (rf));
+       rf->rf_ctx = ctx;
+
+       status = plugin_insert_read (rf);
+       if (status != 0)
+               sfree (rf);
+
+       return (status);
 } /* int plugin_register_complex_read */
 
 int plugin_register_write (const char *name,
@@ -842,7 +922,14 @@ int plugin_register_flush (const char *name,
                                (void *) callback, ud));
 } /* int plugin_register_flush */
 
-int plugin_register_shutdown (char *name,
+int plugin_register_missing (const char *name,
+               plugin_missing_cb callback, user_data_t *ud)
+{
+       return (create_register_callback (&list_missing, name,
+                               (void *) callback, ud));
+} /* int plugin_register_missing */
+
+int plugin_register_shutdown (const char *name,
                int (*callback) (void))
 {
        return (create_register_callback (&list_shutdown, name,
@@ -1028,6 +1115,11 @@ int plugin_unregister_flush (const char *name)
        return (plugin_unregister (list_flush, name));
 }
 
+int plugin_unregister_missing (const char *name)
+{
+       return (plugin_unregister (list_missing, name));
+}
+
 int plugin_unregister_shutdown (const char *name)
 {
        return (plugin_unregister (list_shutdown, name));
@@ -1086,10 +1178,13 @@ void plugin_init_all (void)
        {
                callback_func_t *cf;
                plugin_init_cb callback;
+               plugin_ctx_t old_ctx;
 
                cf = le->value;
+               old_ctx = plugin_set_ctx (cf->cf_ctx);
                callback = cf->cf_callback;
                status = (*callback) ();
+               plugin_set_ctx (old_ctx);
 
                if (status != 0)
                {
@@ -1142,11 +1237,14 @@ int plugin_read_all_once (void)
        while (42)
        {
                read_func_t *rf;
+               plugin_ctx_t old_ctx;
 
                rf = c_heap_get_root (read_heap);
                if (rf == NULL)
                        break;
 
+               old_ctx = plugin_set_ctx (rf->rf_ctx);
+
                if (rf->rf_type == RF_SIMPLE)
                {
                        int (*callback) (void);
@@ -1162,6 +1260,8 @@ int plugin_read_all_once (void)
                        status = (*callback) (&rf->rf_udata);
                }
 
+               plugin_set_ctx (old_ctx);
+
                if (status != 0)
                {
                        NOTICE ("read-function of plugin `%s' failed.",
@@ -1208,6 +1308,9 @@ int plugin_write (const char *plugin, /* {{{ */
       callback_func_t *cf = le->value;
       plugin_write_cb callback;
 
+      /* do not switch plugin context; rather keep the context (interval)
+       * information of the calling read plugin */
+
       DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
       callback = cf->cf_callback;
       status = (*callback) (ds, vl, &cf->cf_udata);
@@ -1243,6 +1346,9 @@ int plugin_write (const char *plugin, /* {{{ */
 
     cf = le->value;
 
+    /* do not switch plugin context; rather keep the context (interval)
+     * information of the calling read plugin */
+
     DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
     callback = cf->cf_callback;
     status = (*callback) (ds, vl, &cf->cf_udata);
@@ -1251,7 +1357,7 @@ int plugin_write (const char *plugin, /* {{{ */
   return (status);
 } /* }}} int plugin_write */
 
-int plugin_flush (const char *plugin, int timeout, const char *identifier)
+int plugin_flush (const char *plugin, cdtime_t timeout, const char *identifier)
 {
   llentry_t *le;
 
@@ -1263,6 +1369,7 @@ int plugin_flush (const char *plugin, int timeout, const char *identifier)
   {
     callback_func_t *cf;
     plugin_flush_cb callback;
+    plugin_ctx_t old_ctx;
 
     if ((plugin != NULL)
         && (strcmp (plugin, le->key) != 0))
@@ -1272,10 +1379,13 @@ int plugin_flush (const char *plugin, int timeout, const char *identifier)
     }
 
     cf = le->value;
+    old_ctx = plugin_set_ctx (cf->cf_ctx);
     callback = cf->cf_callback;
 
     (*callback) (timeout, identifier, &cf->cf_udata);
 
+    plugin_set_ctx (old_ctx);
+
     le = le->next;
   }
   return (0);
@@ -1296,7 +1406,8 @@ void plugin_shutdown_all (void)
 
        destroy_read_heap ();
 
-       plugin_flush (/* plugin = */ NULL, /* timeout = */ -1,
+       plugin_flush (/* plugin = */ NULL,
+                       /* timeout = */ 0,
                        /* identifier = */ NULL);
 
        le = NULL;
@@ -1307,8 +1418,10 @@ void plugin_shutdown_all (void)
        {
                callback_func_t *cf;
                plugin_shutdown_cb callback;
+               plugin_ctx_t old_ctx;
 
                cf = le->value;
+               old_ctx = plugin_set_ctx (cf->cf_ctx);
                callback = cf->cf_callback;
 
                /* Advance the pointer before calling the callback allows
@@ -1318,6 +1431,8 @@ void plugin_shutdown_all (void)
                le = le->next;
 
                (*callback) ();
+
+               plugin_set_ctx (old_ctx);
        }
 
        /* Write plugins which use the `user_data' pointer usually need the
@@ -1326,6 +1441,7 @@ void plugin_shutdown_all (void)
         * the real free function when registering the write callback. This way
         * the data isn't freed twice. */
        destroy_all_callbacks (&list_flush);
+       destroy_all_callbacks (&list_missing);
        destroy_all_callbacks (&list_write);
 
        destroy_all_callbacks (&list_notification);
@@ -1333,6 +1449,47 @@ void plugin_shutdown_all (void)
        destroy_all_callbacks (&list_log);
 } /* void plugin_shutdown_all */
 
+int plugin_dispatch_missing (const value_list_t *vl) /* {{{ */
+{
+  llentry_t *le;
+
+  if (list_missing == NULL)
+    return (0);
+
+  le = llist_head (list_missing);
+  while (le != NULL)
+  {
+    callback_func_t *cf;
+    plugin_missing_cb callback;
+    plugin_ctx_t old_ctx;
+    int status;
+
+    cf = le->value;
+    old_ctx = plugin_set_ctx (cf->cf_ctx);
+    callback = cf->cf_callback;
+
+    status = (*callback) (vl, &cf->cf_udata);
+    plugin_set_ctx (old_ctx);
+    if (status != 0)
+    {
+      if (status < 0)
+      {
+        ERROR ("plugin_dispatch_missing: Callback function \"%s\" "
+            "failed with status %i.",
+            le->key, status);
+        return (status);
+      }
+      else
+      {
+        return (0);
+      }
+    }
+
+    le = le->next;
+  }
+  return (0);
+} /* int }}} plugin_dispatch_missing */
+
 int plugin_dispatch_values (value_list_t *vl)
 {
        int status;
@@ -1348,7 +1505,8 @@ int plugin_dispatch_values (value_list_t *vl)
        if ((vl == NULL) || (vl->type[0] == 0)
                        || (vl->values == NULL) || (vl->values_len < 1))
        {
-               ERROR ("plugin_dispatch_values: Invalid value list.");
+               ERROR ("plugin_dispatch_values: Invalid value list "
+                               "from plugin %s.", vl->plugin);
                return (-1);
        }
 
@@ -1384,16 +1542,35 @@ int plugin_dispatch_values (value_list_t *vl)
        }
 
        if (vl->time == 0)
-               vl->time = time (NULL);
+               vl->time = cdtime ();
 
        if (vl->interval <= 0)
-               vl->interval = interval_g;
+       {
+               plugin_ctx_t ctx = plugin_get_ctx ();
+
+               if (ctx.interval != 0)
+                       vl->interval = ctx.interval;
+               else
+               {
+                       char name[6 * DATA_MAX_NAME_LEN];
+                       FORMAT_VL (name, sizeof (name), vl);
+                       ERROR ("plugin_dispatch_values: Unable to determine "
+                                       "interval from context for "
+                                       "value list \"%s\". "
+                                       "This indicates a broken plugin. "
+                                       "Please report this problem to the "
+                                       "collectd mailing list or at "
+                                       "<http://collectd.org/bugs/>.", name);
+                       vl->interval = cf_get_default_interval ();
+               }
+       }
 
-       DEBUG ("plugin_dispatch_values: time = %u; interval = %i; "
+       DEBUG ("plugin_dispatch_values: time = %.3f; interval = %.3f; "
                        "host = %s; "
                        "plugin = %s; plugin_instance = %s; "
                        "type = %s; type_instance = %s;",
-                       (unsigned int) vl->time, vl->interval,
+                       CDTIME_T_TO_DOUBLE (vl->time),
+                       CDTIME_T_TO_DOUBLE (vl->interval),
                        vl->host,
                        vl->plugin, vl->plugin_instance,
                        vl->type, vl->type_instance);
@@ -1477,9 +1654,6 @@ int plugin_dispatch_values (value_list_t *vl)
        /* Update the value cache */
        uc_update (ds, vl);
 
-       /* Initiate threshold checking */
-       ut_check_threshold (ds, vl);
-
        if (post_cache_chain != NULL)
        {
                status = fc_process_chain (ds, vl, post_cache_chain);
@@ -1512,15 +1686,61 @@ int plugin_dispatch_values (value_list_t *vl)
        return (0);
 } /* int plugin_dispatch_values */
 
+int plugin_dispatch_values_secure (const value_list_t *vl)
+{
+  value_list_t vl_copy;
+  int status;
+
+  if (vl == NULL)
+    return EINVAL;
+
+  memcpy (&vl_copy, vl, sizeof (vl_copy));
+
+  /* Write callbacks must not change the values and meta pointers, so we can
+   * savely skip copying those and make this more efficient. */
+  if ((pre_cache_chain == NULL) && (post_cache_chain == NULL))
+    return (plugin_dispatch_values (&vl_copy));
+
+  /* Set pointers to NULL, just to be on the save side. */
+  vl_copy.values = NULL;
+  vl_copy.meta = NULL;
+
+  vl_copy.values = malloc (sizeof (*vl_copy.values) * vl->values_len);
+  if (vl_copy.values == NULL)
+  {
+    ERROR ("plugin_dispatch_values_secure: malloc failed.");
+    return (ENOMEM);
+  }
+  memcpy (vl_copy.values, vl->values, sizeof (*vl_copy.values) * vl->values_len);
+
+  if (vl->meta != NULL)
+  {
+    vl_copy.meta = meta_data_clone (vl->meta);
+    if (vl_copy.meta == NULL)
+    {
+      ERROR ("plugin_dispatch_values_secure: meta_data_clone failed.");
+      free (vl_copy.values);
+      return (ENOMEM);
+    }
+  } /* if (vl->meta) */
+
+  status = plugin_dispatch_values (&vl_copy);
+
+  meta_data_destroy (vl_copy.meta);
+  free (vl_copy.values);
+
+  return (status);
+} /* int plugin_dispatch_values_secure */
+
 int plugin_dispatch_notification (const notification_t *notif)
 {
        llentry_t *le;
        /* Possible TODO: Add flap detection here */
 
        DEBUG ("plugin_dispatch_notification: severity = %i; message = %s; "
-                       "time = %u; host = %s;",
+                       "time = %.3f; host = %s;",
                        notif->severity, notif->message,
-                       (unsigned int) notif->time, notif->host);
+                       CDTIME_T_TO_DOUBLE (notif->time), notif->host);
 
        /* Nobody cares for notifications */
        if (list_notification == NULL)
@@ -1533,6 +1753,9 @@ int plugin_dispatch_notification (const notification_t *notif)
                plugin_notification_cb callback;
                int status;
 
+               /* do not switch plugin context; rather keep the context
+                * (interval) information of the calling plugin */
+
                cf = le->value;
                callback = cf->cf_callback;
                status = (*callback) (notif, &cf->cf_udata);
@@ -1580,12 +1803,53 @@ void plugin_log (int level, const char *format, ...)
                cf = le->value;
                callback = cf->cf_callback;
 
+               /* do not switch plugin context; rather keep the context
+                * (interval) information of the calling plugin */
+
                (*callback) (level, msg, &cf->cf_udata);
 
                le = le->next;
        }
 } /* void plugin_log */
 
+int parse_log_severity (const char *severity)
+{
+       int log_level = -1;
+
+       if ((0 == strcasecmp (severity, "emerg"))
+                       || (0 == strcasecmp (severity, "alert"))
+                       || (0 == strcasecmp (severity, "crit"))
+                       || (0 == strcasecmp (severity, "err")))
+               log_level = LOG_ERR;
+       else if (0 == strcasecmp (severity, "warning"))
+               log_level = LOG_WARNING;
+       else if (0 == strcasecmp (severity, "notice"))
+               log_level = LOG_NOTICE;
+       else if (0 == strcasecmp (severity, "info"))
+               log_level = LOG_INFO;
+#if COLLECT_DEBUG
+       else if (0 == strcasecmp (severity, "debug"))
+               log_level = LOG_DEBUG;
+#endif /* COLLECT_DEBUG */
+
+       return (log_level);
+} /* int parse_log_severity */
+
+int parse_notif_severity (const char *severity)
+{
+       int notif_severity = -1;
+
+       if (strcasecmp (severity, "FAILURE") == 0)
+               notif_severity = NOTIF_FAILURE;
+       else if (strcmp (severity, "OKAY") == 0)
+               notif_severity = NOTIF_OKAY;
+       else if ((strcmp (severity, "WARNING") == 0)
+                       || (strcmp (severity, "WARN") == 0))
+               notif_severity = NOTIF_WARNING;
+
+       return (notif_severity);
+} /* int parse_notif_severity */
+
 const data_set_t *plugin_get_ds (const char *name)
 {
        data_set_t *ds;
@@ -1774,4 +2038,122 @@ int plugin_notification_meta_free (notification_meta_t *n)
   return (0);
 } /* int plugin_notification_meta_free */
 
+static void plugin_ctx_destructor (void *ctx)
+{
+       sfree (ctx);
+} /* void plugin_ctx_destructor */
+
+static plugin_ctx_t ctx_init = { /* interval = */ 0 };
+
+static plugin_ctx_t *plugin_ctx_create (void)
+{
+       plugin_ctx_t *ctx;
+
+       ctx = malloc (sizeof (*ctx));
+       if (ctx == NULL) {
+               char errbuf[1024];
+               ERROR ("Failed to allocate plugin context: %s",
+                               sstrerror (errno, errbuf, sizeof (errbuf)));
+               return NULL;
+       }
+
+       *ctx = ctx_init;
+       assert (plugin_ctx_key_initialized);
+       pthread_setspecific (plugin_ctx_key, ctx);
+       DEBUG("Created new plugin context.");
+       return (ctx);
+} /* int plugin_ctx_create */
+
+void plugin_init_ctx (void)
+{
+       pthread_key_create (&plugin_ctx_key, plugin_ctx_destructor);
+       plugin_ctx_key_initialized = 1;
+} /* void plugin_init_ctx */
+
+plugin_ctx_t plugin_get_ctx (void)
+{
+       plugin_ctx_t *ctx;
+
+       assert (plugin_ctx_key_initialized);
+       ctx = pthread_getspecific (plugin_ctx_key);
+
+       if (ctx == NULL) {
+               ctx = plugin_ctx_create ();
+               /* this must no happen -- exit() instead? */
+               if (ctx == NULL)
+                       return ctx_init;
+       }
+
+       return (*ctx);
+} /* plugin_ctx_t plugin_get_ctx */
+
+plugin_ctx_t plugin_set_ctx (plugin_ctx_t ctx)
+{
+       plugin_ctx_t *c;
+       plugin_ctx_t old;
+
+       assert (plugin_ctx_key_initialized);
+       c = pthread_getspecific (plugin_ctx_key);
+
+       if (c == NULL) {
+               c = plugin_ctx_create ();
+               /* this must no happen -- exit() instead? */
+               if (c == NULL)
+                       return ctx_init;
+       }
+
+       old = *c;
+       *c = ctx;
+
+       return (old);
+} /* void plugin_set_ctx */
+
+cdtime_t plugin_get_interval (void)
+{
+       cdtime_t interval;
+
+       interval = plugin_get_ctx().interval;
+       if (interval > 0)
+               return interval;
+
+       return cf_get_default_interval ();
+} /* cdtime_t plugin_get_interval */
+
+typedef struct {
+       plugin_ctx_t ctx;
+       void *(*start_routine) (void *);
+       void *arg;
+} plugin_thread_t;
+
+static void *plugin_thread_start (void *arg)
+{
+       plugin_thread_t *plugin_thread = arg;
+
+       void *(*start_routine) (void *) = plugin_thread->start_routine;
+       void *plugin_arg = plugin_thread->arg;
+
+       plugin_set_ctx (plugin_thread->ctx);
+
+       free (plugin_thread);
+
+       return start_routine (plugin_arg);
+} /* void *plugin_thread_start */
+
+int plugin_thread_create (pthread_t *thread, const pthread_attr_t *attr,
+               void *(*start_routine) (void *), void *arg)
+{
+       plugin_thread_t *plugin_thread;
+
+       plugin_thread = malloc (sizeof (*plugin_thread));
+       if (plugin_thread == NULL)
+               return -1;
+
+       plugin_thread->ctx           = plugin_get_ctx ();
+       plugin_thread->start_routine = start_routine;
+       plugin_thread->arg           = arg;
+
+       return pthread_create (thread, attr,
+                       plugin_thread_start, plugin_thread);
+} /* int plugin_thread_create */
+
 /* vim: set sw=8 ts=8 noet fdm=marker : */
index d78aa4f..0f35de5 100644 (file)
@@ -2,7 +2,7 @@
 #define PLUGIN_H
 /**
  * collectd - src/plugin.h
- * Copyright (C) 2005-2008  Florian octo Forster
+ * Copyright (C) 2005-2011  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Sebastian Harl <sh at tokkee.org>
  **/
 
 #include "collectd.h"
 #include "configfile.h"
 #include "meta_data.h"
+#include "utils_time.h"
 
 #define PLUGIN_FLAGS_GLOBAL 0x0001
 
@@ -64,6 +65,8 @@
 #define NOTIF_WARNING 2
 #define NOTIF_OKAY    4
 
+#define plugin_interval (plugin_get_ctx().interval)
+
 /*
  * Public data types
  */
@@ -85,8 +88,8 @@ struct value_list_s
 {
        value_t *values;
        int      values_len;
-       time_t   time;
-       int      interval;
+       cdtime_t time;
+       cdtime_t interval;
        char     host[DATA_MAX_NAME_LEN];
        char     plugin[DATA_MAX_NAME_LEN];
        char     plugin_instance[DATA_MAX_NAME_LEN];
@@ -96,7 +99,8 @@ struct value_list_s
 };
 typedef struct value_list_s value_list_t;
 
-#define VALUE_LIST_INIT { NULL, 0, 0, interval_g, "localhost", "", "", "", "", NULL }
+#define VALUE_LIST_INIT { NULL, 0, 0, plugin_get_interval (), \
+       "localhost", "", "", "", "", NULL }
 #define VALUE_LIST_STATIC { NULL, 0, 0, 0, "localhost", "", "", "", "", NULL }
 
 struct data_source_s
@@ -143,7 +147,7 @@ typedef struct notification_meta_s
 typedef struct notification_s
 {
        int    severity;
-       time_t time;
+       cdtime_t time;
        char   message[NOTIF_MAX_MSG_LEN];
        char   host[DATA_MAX_NAME_LEN];
        char   plugin[DATA_MAX_NAME_LEN];
@@ -160,6 +164,12 @@ struct user_data_s
 };
 typedef struct user_data_s user_data_t;
 
+struct plugin_ctx_s
+{
+       cdtime_t interval;
+};
+typedef struct plugin_ctx_s plugin_ctx_t;
+
 /*
  * Callback types
  */
@@ -167,8 +177,12 @@ typedef int (*plugin_init_cb) (void);
 typedef int (*plugin_read_cb) (user_data_t *);
 typedef int (*plugin_write_cb) (const data_set_t *, const value_list_t *,
                user_data_t *);
-typedef int (*plugin_flush_cb) (int timeout, const char *identifier,
+typedef int (*plugin_flush_cb) (cdtime_t timeout, const char *identifier,
                user_data_t *);
+/* "missing" callback. Returns less than zero on failure, zero if other
+ * callbacks should be called, greater than zero if no more callbacks should be
+ * called. */
+typedef int (*plugin_missing_cb) (const value_list_t *, user_data_t *);
 typedef void (*plugin_log_cb) (int severity, const char *message,
                user_data_t *);
 typedef int (*plugin_shutdown_cb) (void);
@@ -248,7 +262,7 @@ void plugin_shutdown_all (void);
 int plugin_write (const char *plugin,
     const data_set_t *ds, const value_list_t *vl);
 
-int plugin_flush (const char *plugin, int timeout, const char *identifier);
+int plugin_flush (const char *plugin, cdtime_t timeout, const char *identifier);
 
 /*
  * The `plugin_register_*' functions are used to make `config', `init',
@@ -264,6 +278,8 @@ int plugin_register_init (const char *name,
                plugin_init_cb callback);
 int plugin_register_read (const char *name,
                int (*callback) (void));
+/* "user_data" will be freed automatically, unless
+ * "plugin_register_complex_read" returns an error (non-zero). */
 int plugin_register_complex_read (const char *group, const char *name,
                plugin_read_cb callback,
                const struct timespec *interval,
@@ -272,7 +288,9 @@ int plugin_register_write (const char *name,
                plugin_write_cb callback, user_data_t *user_data);
 int plugin_register_flush (const char *name,
                plugin_flush_cb callback, user_data_t *user_data);
-int plugin_register_shutdown (char *name,
+int plugin_register_missing (const char *name,
+               plugin_missing_cb callback, user_data_t *user_data);
+int plugin_register_shutdown (const char *name,
                plugin_shutdown_cb callback);
 int plugin_register_data_set (const data_set_t *ds);
 int plugin_register_log (const char *name,
@@ -287,6 +305,7 @@ int plugin_unregister_read (const char *name);
 int plugin_unregister_read_group (const char *group);
 int plugin_unregister_write (const char *name);
 int plugin_unregister_flush (const char *name);
+int plugin_unregister_missing (const char *name);
 int plugin_unregister_shutdown (const char *name);
 int plugin_unregister_data_set (const char *name);
 int plugin_unregister_log (const char *name);
@@ -308,12 +327,18 @@ int plugin_unregister_notification (const char *name);
  *              function.
  */
 int plugin_dispatch_values (value_list_t *vl);
+int plugin_dispatch_values_secure (const value_list_t *vl);
+int plugin_dispatch_missing (const value_list_t *vl);
 
 int plugin_dispatch_notification (const notification_t *notif);
 
 void plugin_log (int level, const char *format, ...)
        __attribute__ ((format(printf,2,3)));
 
+/* These functions return the parsed severity or less than zero on failure. */
+int parse_log_severity (const char *severity);
+int parse_notif_severity (const char *severity);
+
 #define ERROR(...)   plugin_log (LOG_ERR,     __VA_ARGS__)
 #define WARNING(...) plugin_log (LOG_WARNING, __VA_ARGS__)
 #define NOTICE(...)  plugin_log (LOG_NOTICE,  __VA_ARGS__)
@@ -347,4 +372,31 @@ int plugin_notification_meta_copy (notification_t *dst,
 
 int plugin_notification_meta_free (notification_meta_t *n);
 
+/*
+ * Plugin context management.
+ */
+
+void plugin_init_ctx (void);
+
+plugin_ctx_t plugin_get_ctx (void);
+plugin_ctx_t plugin_set_ctx (plugin_ctx_t ctx);
+
+/*
+ * NAME
+ *  plugin_get_interval
+ *
+ * DESCRIPTION
+ *  This function returns the current value of the plugin's interval. The
+ *  return value will be strictly greater than zero in all cases. If
+ *  everything else fails, it will fall back to 10 seconds.
+ */
+cdtime_t plugin_get_interval (void);
+
+/*
+ * Context-aware thread management.
+ */
+
+int plugin_thread_create (pthread_t *thread, const pthread_attr_t *attr,
+               void *(*start_routine) (void *), void *arg);
+
 #endif /* PLUGIN_H */
index 175cc09..a72109a 100644 (file)
@@ -95,6 +95,7 @@ typedef enum {
        C_PSQL_PARAM_DB,
        C_PSQL_PARAM_USER,
        C_PSQL_PARAM_INTERVAL,
+       C_PSQL_PARAM_INSTANCE,
 } c_psql_param_t;
 
 /* Parameter configuration. Stored as `user data' in the query objects. */
@@ -117,7 +118,7 @@ typedef struct {
        udb_query_t    **queries;
        size_t           queries_num;
 
-       int interval;
+       cdtime_t interval;
 
        char *host;
        char *port;
@@ -125,6 +126,8 @@ typedef struct {
        char *user;
        char *password;
 
+       char *instance;
+
        char *sslmode;
 
        char *krbsrvname;
@@ -177,6 +180,8 @@ static c_psql_database_t *c_psql_database_new (const char *name)
        db->user       = NULL;
        db->password   = NULL;
 
+       db->instance   = sstrdup (name);
+
        db->sslmode    = NULL;
 
        db->krbsrvname = NULL;
@@ -208,6 +213,8 @@ static void c_psql_database_delete (void *data)
        sfree (db->user);
        sfree (db->password);
 
+       sfree (db->instance);
+
        sfree (db->sslmode);
 
        sfree (db->krbsrvname);
@@ -271,8 +278,9 @@ static int c_psql_check_connection (c_psql_database_t *db)
 
                if (CONNECTION_OK != PQstatus (db->conn)) {
                        c_complain (LOG_ERR, &db->conn_complaint,
-                                       "Failed to connect to database %s: %s",
-                                       db->database, PQerrorMessage (db->conn));
+                                       "Failed to connect to database %s (%s): %s",
+                                       db->database, db->instance,
+                                       PQerrorMessage (db->conn));
                        return -1;
                }
 
@@ -335,10 +343,15 @@ static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
                                params[i] = db->user;
                                break;
                        case C_PSQL_PARAM_INTERVAL:
-                               ssnprintf (interval, sizeof (interval), "%i",
-                                               db->interval > 0 ? db->interval : interval_g);
+                               ssnprintf (interval, sizeof (interval), "%.3f",
+                                               (db->interval > 0)
+                                               ? CDTIME_T_TO_DOUBLE (db->interval)
+                                               : plugin_get_interval ());
                                params[i] = interval;
                                break;
+                       case C_PSQL_PARAM_INSTANCE:
+                               params[i] = db->instance;
+                               break;
                        default:
                                assert (0);
                }
@@ -376,9 +389,10 @@ static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
        else if ((NULL == data) || (0 == data->params_num))
                res = c_psql_exec_query_noparams (db, q);
        else {
-               log_err ("Connection to database \"%s\" does not support parameters "
-                               "(protocol version %d) - cannot execute query \"%s\".",
-                               db->database, db->proto_version,
+               log_err ("Connection to database \"%s\" (%s) does not support "
+                               "parameters (protocol version %d) - "
+                               "cannot execute query \"%s\".",
+                               db->database, db->instance, db->proto_version,
                                udb_query_get_name (q));
                return -1;
        }
@@ -435,7 +449,7 @@ static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
                host = db->host;
 
        status = udb_query_prepare_result (q, prep_area, host, "postgresql",
-                       db->database, column_names, (size_t) column_num, db->interval);
+                       db->instance, column_names, (size_t) column_num, db->interval);
        if (0 != status) {
                log_err ("udb_query_prepare_result failed with status %i.",
                                status);
@@ -486,6 +500,7 @@ static int c_psql_read (user_data_t *ud)
        db = ud->data;
 
        assert (NULL != db->database);
+       assert (NULL != db->instance);
 
        if (0 != c_psql_check_connection (db))
                return -1;
@@ -522,41 +537,6 @@ static int c_psql_shutdown (void)
        return 0;
 } /* c_psql_shutdown */
 
-static int config_set_s (char *name, char **var, const oconfig_item_t *ci)
-{
-       if ((0 != ci->children_num) || (1 != ci->values_num)
-                       || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
-               log_err ("%s expects a single string argument.", name);
-               return 1;
-       }
-
-       sfree (*var);
-       *var = sstrdup (ci->values[0].value.string);
-       return 0;
-} /* config_set_s */
-
-static int config_set_i (char *name, int *var,
-               const oconfig_item_t *ci, int min)
-{
-       int value;
-
-       if ((0 != ci->children_num) || (1 != ci->values_num)
-                       || (OCONFIG_TYPE_NUMBER != ci->values[0].type)) {
-               log_err ("%s expects a single number argument.", name);
-               return 1;
-       }
-
-       value = (int)ci->values[0].value.number;
-
-       if (value < min) {
-               log_err ("%s expects a number greater or equal to %i.", name, min);
-               return 1;
-       }
-
-       *var = value;
-       return 0;
-} /* config_set_s */
-
 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
 {
        c_psql_user_data_t *data;
@@ -592,6 +572,8 @@ static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
                data->params[data->params_num] = C_PSQL_PARAM_USER;
        else if (0 == strcasecmp (param_str, "interval"))
                data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
+       else if (0 == strcasecmp (param_str, "instance"))
+               data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
        else {
                log_err ("Invalid parameter \"%s\".", param_str);
                return 1;
@@ -618,7 +600,7 @@ static int c_psql_config_database (oconfig_item_t *ci)
        c_psql_database_t *db;
 
        char cb_name[DATA_MAX_NAME_LEN];
-       struct timespec cb_interval;
+       struct timespec cb_interval = { 0, 0 };
        user_data_t ud;
 
        int i;
@@ -639,24 +621,26 @@ static int c_psql_config_database (oconfig_item_t *ci)
                oconfig_item_t *c = ci->children + i;
 
                if (0 == strcasecmp (c->key, "Host"))
-                       config_set_s ("Host", &db->host, c);
+                       cf_util_get_string (c, &db->host);
                else if (0 == strcasecmp (c->key, "Port"))
-                       config_set_s ("Port", &db->port, c);
+                       cf_util_get_service (c, &db->port);
                else if (0 == strcasecmp (c->key, "User"))
-                       config_set_s ("User", &db->user, c);
+                       cf_util_get_string (c, &db->user);
                else if (0 == strcasecmp (c->key, "Password"))
-                       config_set_s ("Password", &db->password, c);
+                       cf_util_get_string (c, &db->password);
+               else if (0 == strcasecmp (c->key, "Instance"))
+                       cf_util_get_string (c, &db->instance);
                else if (0 == strcasecmp (c->key, "SSLMode"))
-                       config_set_s ("SSLMode", &db->sslmode, c);
+                       cf_util_get_string (c, &db->sslmode);
                else if (0 == strcasecmp (c->key, "KRBSrvName"))
-                       config_set_s ("KRBSrvName", &db->krbsrvname, c);
+                       cf_util_get_string (c, &db->krbsrvname);
                else if (0 == strcasecmp (c->key, "Service"))
-                       config_set_s ("Service", &db->service, c);
+                       cf_util_get_string (c, &db->service);
                else if (0 == strcasecmp (c->key, "Query"))
                        udb_query_pick_from_list (c, queries, queries_num,
                                        &db->queries, &db->queries_num);
                else if (0 == strcasecmp (c->key, "Interval"))
-                       config_set_i ("Interval", &db->interval, c, /* min = */ 1);
+                       cf_util_get_cdtime (c, &db->interval);
                else
                        log_warn ("Ignoring unknown config key \"%s\".", c->key);
        }
@@ -699,14 +683,13 @@ static int c_psql_config_database (oconfig_item_t *ci)
        ud.data = db;
        ud.free_func = c_psql_database_delete;
 
-       ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->database);
+       ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->instance);
 
-       memset (&cb_interval, 0, sizeof (cb_interval));
-       if (db->interval > 0)
-               cb_interval.tv_sec = (time_t)db->interval;
+       CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
 
        plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
-                       /* interval = */ &cb_interval, &ud);
+                       /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
+                       &ud);
        return 0;
 } /* c_psql_config_database */
 
index 29f6bca..a140a12 100644 (file)
@@ -321,6 +321,9 @@ static int powerdns_get_data_dgram (list_item_t *item, /* {{{ */
 
   struct sockaddr_un sa_unix;
 
+  struct timeval stv_timeout;
+  cdtime_t cdt_timeout;
+
   sd = socket (PF_UNIX, item->socktype, 0);
   if (sd < 0)
   {
@@ -361,12 +364,13 @@ static int powerdns_get_data_dgram (list_item_t *item, /* {{{ */
       break;
     }
 
-    struct timeval timeout;
-    timeout.tv_sec=2;
-    if (timeout.tv_sec < interval_g * 3 / 4)
-      timeout.tv_sec = interval_g * 3 / 4;
-    timeout.tv_usec=0;
-    status = setsockopt (sd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof (timeout));
+    cdt_timeout = plugin_get_interval () * 3 / 4;
+    if (cdt_timeout < TIME_T_TO_CDTIME_T (2))
+      cdt_timeout = TIME_T_TO_CDTIME_T (2);
+
+    CDTIME_T_TO_TIMEVAL (cdt_timeout, &stv_timeout);
+
+    status = setsockopt (sd, SOL_SOCKET, SO_RCVTIMEO, &stv_timeout, sizeof (stv_timeout));
     if (status != 0)
     {
       FUNC_ERROR ("setsockopt");
index 8a3df64..c77859d 100644 (file)
@@ -1,12 +1,13 @@
 /**
  * collectd - src/processes.c
  * Copyright (C) 2005       Lyonel Vincent
- * Copyright (C) 2006-2008  Florian octo Forster
+ * Copyright (C) 2006-2010  Florian octo Forster
  * Copyright (C) 2008       Oleg King
  * Copyright (C) 2009       Sebastian Harl
  * Copyright (C) 2009       Andrés J. Díaz
  * Copyright (C) 2009       Manuel Sanmartin
  * Copyright (C) 2010       Clément Stenac
+ * Copyright (C) 2012       Cosmin Ioiart
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -30,6 +31,7 @@
  *   Andrés J. Díaz <ajdiaz at connectical.com>
  *   Manuel Sanmartin
  *   Clément Stenac <clement.stenac at diwi.org>
+ *   Cosmin Ioiart <cioiart at gmail.com>
  **/
 
 #include "collectd.h"
 #define MAXARGLN 1024
 /* #endif HAVE_PROCINFO_H */
 
+#elif KERNEL_SOLARIS
+# include <procfs.h>
+# include <dirent.h>
+/* #endif KERNEL_SOLARIS */
+
 #else
 # error "No applicable input method."
 #endif
 # include <regex.h>
 #endif
 
+#if HAVE_KSTAT_H
+# include <kstat.h>
+#endif
+
 #ifndef ARG_MAX
 #  define ARG_MAX 4096
 #endif
 
-static const char *config_keys[] =
-{
-       "Process",
-       "ProcessMatch"
-};
-static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
-
 typedef struct procstat_entry_s
 {
        unsigned long id;
@@ -143,13 +147,13 @@ typedef struct procstat_entry_s
 
        unsigned long vmem_minflt;
        unsigned long vmem_majflt;
-       unsigned long vmem_minflt_counter;
-       unsigned long vmem_majflt_counter;
+       derive_t      vmem_minflt_counter;
+       derive_t      vmem_majflt_counter;
 
        unsigned long cpu_user;
        unsigned long cpu_system;
-       unsigned long cpu_user_counter;
-       unsigned long cpu_system_counter;
+       derive_t      cpu_user_counter;
+       derive_t      cpu_system_counter;
 
        /* io data */
        derive_t io_rchar;
@@ -176,11 +180,11 @@ typedef struct procstat
        unsigned long vmem_code;
        unsigned long stack_size;
 
-       unsigned long vmem_minflt_counter;
-       unsigned long vmem_majflt_counter;
+       derive_t vmem_minflt_counter;
+       derive_t vmem_majflt_counter;
 
-       unsigned long cpu_user_counter;
-       unsigned long cpu_system_counter;
+       derive_t cpu_user_counter;
+       derive_t cpu_system_counter;
 
        /* io data */
        derive_t io_rchar;
@@ -207,7 +211,7 @@ static long pagesize_g;
 /* #endif KERNEL_LINUX */
 
 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
-/* no global variables */
+static int pagesize;
 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
 
 #elif HAVE_PROCINFO_H
@@ -223,8 +227,8 @@ int getargs (struct procentry64 *processBuffer, int bufferLen, char *argsBuffer,
 #endif /* HAVE_PROCINFO_H */
 
 /* put name of process from config to list_head_g tree
  list_head_g is a list of 'procstat_t' structs with
  processes names we want to watch */
* list_head_g is a list of 'procstat_t' structs with
* processes names we want to watch */
 static void ps_list_register (const char *name, const char *regexp)
 {
        procstat_t *new;
@@ -520,42 +524,61 @@ static void ps_list_reset (void)
 }
 
 /* put all pre-defined 'Process' names from config to list_head_g tree */
-static int ps_config (const char *key, const char *value)
+static int ps_config (oconfig_item_t *ci)
 {
-       if (strcasecmp (key, "Process") == 0)
-       {
-               ps_list_register (value, NULL);
-       }
-       else if (strcasecmp (key, "ProcessMatch") == 0)
-       {
-               char *new_val;
-               char *fields[3];
-               int fields_num;
+       int i;
 
-               new_val = strdup (value);
-               if (new_val == NULL) {
-                       ERROR ("processes plugin: strdup failed when processing "
-                                       "`ProcessMatch %s'.", value);
-                       return (1);
+       for (i = 0; i < ci->children_num; ++i) {
+               oconfig_item_t *c = ci->children + i;
+
+               if (strcasecmp (c->key, "Process") == 0)
+               {
+                       if ((c->values_num != 1)
+                                       || (OCONFIG_TYPE_STRING != c->values[0].type)) {
+                               ERROR ("processes plugin: `Process' expects exactly "
+                                               "one string argument (got %i).",
+                                               c->values_num);
+                               continue;
+                       }
+
+                       if (c->children_num != 0) {
+                               WARNING ("processes plugin: the `Process' config option "
+                                               "does not expect any child elements -- ignoring "
+                                               "content (%i elements) of the <Process '%s'> block.",
+                                               c->children_num, c->values[0].value.string);
+                       }
+
+                       ps_list_register (c->values[0].value.string, NULL);
                }
+               else if (strcasecmp (c->key, "ProcessMatch") == 0)
+               {
+                       if ((c->values_num != 2)
+                                       || (OCONFIG_TYPE_STRING != c->values[0].type)
+                                       || (OCONFIG_TYPE_STRING != c->values[1].type))
+                       {
+                               ERROR ("processes plugin: `ProcessMatch' needs exactly "
+                                               "two string arguments (got %i).",
+                                               c->values_num);
+                               continue;
+                       }
 
-               fields_num = strsplit (new_val, fields,
-                               STATIC_ARRAY_SIZE (fields));
-               if (fields_num != 2)
+                       if (c->children_num != 0) {
+                               WARNING ("processes plugin: the `ProcessMatch' config option "
+                                               "does not expect any child elements -- ignoring "
+                                               "content (%i elements) of the <ProcessMatch '%s' '%s'> "
+                                               "block.", c->children_num, c->values[0].value.string,
+                                               c->values[1].value.string);
+                       }
+
+                       ps_list_register (c->values[0].value.string,
+                                       c->values[1].value.string);
+               }
+               else
                {
-                       ERROR ("processes plugin: `ProcessMatch' needs exactly "
-                                       "two string arguments.");
-                       sfree (new_val);
-                       return (1);
+                       ERROR ("processes plugin: The `%s' configuration option is not "
+                                       "understood and will be ignored.", c->key);
+                       continue;
                }
-               ps_list_register (fields[0], fields[1]);
-               sfree (new_val);
-       }
-       else
-       {
-               ERROR ("processes plugin: The `%s' configuration option is not "
-                               "understood and will be ignored.", key);
-               return (-1);
        }
 
        return (0);
@@ -597,7 +620,7 @@ static int ps_init (void)
 /* #endif KERNEL_LINUX */
 
 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
-/* no initialization */
+       pagesize = getpagesize();
 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
 
 #elif HAVE_PROCINFO_H
@@ -664,8 +687,8 @@ static void ps_submit_proc_list (procstat_t *ps)
        plugin_dispatch_values (&vl);
 
        sstrncpy (vl.type, "ps_cputime", sizeof (vl.type));
-       vl.values[0].counter = ps->cpu_user_counter;
-       vl.values[1].counter = ps->cpu_system_counter;
+       vl.values[0].derive = ps->cpu_user_counter;
+       vl.values[1].derive = ps->cpu_system_counter;
        vl.values_len = 2;
        plugin_dispatch_values (&vl);
 
@@ -676,8 +699,8 @@ static void ps_submit_proc_list (procstat_t *ps)
        plugin_dispatch_values (&vl);
 
        sstrncpy (vl.type, "ps_pagefaults", sizeof (vl.type));
-       vl.values[0].counter = ps->vmem_minflt_counter;
-       vl.values[1].counter = ps->vmem_majflt_counter;
+       vl.values[0].derive = ps->vmem_minflt_counter;
+       vl.values[1].derive = ps->vmem_majflt_counter;
        vl.values_len = 2;
        plugin_dispatch_values (&vl);
 
@@ -700,10 +723,10 @@ static void ps_submit_proc_list (procstat_t *ps)
        }
 
        DEBUG ("name = %s; num_proc = %lu; num_lwp = %lu; "
-                        "vmem_size = %lu; vmem_rss = %lu; vmem_data = %lu; "
+                       "vmem_size = %lu; vmem_rss = %lu; vmem_data = %lu; "
                        "vmem_code = %lu; "
-                       "vmem_minflt_counter = %lu; vmem_majflt_counter = %lu; "
-                       "cpu_user_counter = %lu; cpu_system_counter = %lu; "
+                       "vmem_minflt_counter = %"PRIi64"; vmem_majflt_counter = %"PRIi64"; "
+                       "cpu_user_counter = %"PRIi64"; cpu_system_counter = %"PRIi64"; "
                        "io_rchar = %"PRIi64"; io_wchar = %"PRIi64"; "
                        "io_syscr = %"PRIi64"; io_syscw = %"PRIi64";",
                        ps->name, ps->num_proc, ps->num_lwp,
@@ -714,6 +737,26 @@ static void ps_submit_proc_list (procstat_t *ps)
                        ps->io_rchar, ps->io_wchar, ps->io_syscr, ps->io_syscw);
 } /* void ps_submit_proc_list */
 
+#if KERNEL_LINUX || KERNEL_SOLARIS
+static void ps_submit_fork_rate (derive_t value)
+{
+       value_t values[1];
+       value_list_t vl = VALUE_LIST_INIT;
+
+       values[0].derive = value;
+
+       vl.values = values;
+       vl.values_len = 1;
+       sstrncpy(vl.host, hostname_g, sizeof (vl.host));
+       sstrncpy(vl.plugin, "processes", sizeof (vl.plugin));
+       sstrncpy(vl.plugin_instance, "", sizeof (vl.plugin_instance));
+       sstrncpy(vl.type, "fork_rate", sizeof (vl.type));
+       sstrncpy(vl.type_instance, "", sizeof (vl.type_instance));
+
+       plugin_dispatch_values(&vl);
+}
+#endif /* KERNEL_LINUX || KERNEL_SOLARIS*/
+
 /* ------- additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
 #if KERNEL_LINUX
 static int ps_read_tasks (int pid)
@@ -768,7 +811,7 @@ static procstat_t *ps_read_vmem (int pid, procstat_t *ps)
                        continue;
 
                numfields = strsplit (buffer, fields,
-                                      STATIC_ARRAY_SIZE (fields));
+                               STATIC_ARRAY_SIZE (fields));
 
                if (numfields < 2)
                        continue;
@@ -778,7 +821,7 @@ static procstat_t *ps_read_vmem (int pid, procstat_t *ps)
                tmp = strtoll (fields[1], &endptr, /* base = */ 10);
                if ((errno == 0) && (endptr != fields[1]))
                {
-                       if (strncmp (buffer, "VmData", 6) == 0) 
+                       if (strncmp (buffer, "VmData", 6) == 0)
                        {
                                data = tmp;
                        }
@@ -869,13 +912,15 @@ int ps_read_process (int pid, procstat_t *ps, char *state)
        char *fields[64];
        char  fields_len;
 
-       int   i;
+       int   buffer_len;
 
-       int   ppid;
-       int   name_len;
+       char *buffer_ptr;
+       size_t name_start_pos;
+       size_t name_end_pos;
+       size_t name_len;
 
-       long long unsigned cpu_user_counter;
-       long long unsigned cpu_system_counter;
+       derive_t cpu_user_counter;
+       derive_t cpu_system_counter;
        long long unsigned vmem_size;
        long long unsigned vmem_rss;
        long long unsigned stack_size;
@@ -884,34 +929,56 @@ int ps_read_process (int pid, procstat_t *ps, char *state)
 
        ssnprintf (filename, sizeof (filename), "/proc/%i/stat", pid);
 
-       i = read_file_contents (filename, buffer, sizeof(buffer) - 1);
-       if (i <= 0)
+       buffer_len = read_file_contents (filename,
+                       buffer, sizeof(buffer) - 1);
+       if (buffer_len <= 0)
                return (-1);
-       buffer[i] = 0;
-
-       fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
-       if (fields_len < 24)
+       buffer[buffer_len] = 0;
+
+       /* The name of the process is enclosed in parens. Since the name can
+        * contain parens itself, spaces, numbers and pretty much everything
+        * else, use these to determine the process name. We don't use
+        * strchr(3) and strrchr(3) to avoid pointer arithmetic which would
+        * otherwise be required to determine name_len. */
+       name_start_pos = 0;
+       while ((buffer[name_start_pos] != '(')
+                       && (name_start_pos < buffer_len))
+               name_start_pos++;
+
+       name_end_pos = buffer_len;
+       while ((buffer[name_end_pos] != ')')
+                       && (name_end_pos > 0))
+               name_end_pos--;
+
+       /* Either '(' or ')' is not found or they are in the wrong order.
+        * Anyway, something weird that shouldn't happen ever. */
+       if (name_start_pos >= name_end_pos)
        {
-               DEBUG ("processes plugin: ps_read_process (pid = %i):"
-                               " `%s' has only %i fields..",
-                               (int) pid, filename, fields_len);
+               ERROR ("processes plugin: name_start_pos = %zu >= name_end_pos = %zu",
+                               name_start_pos, name_end_pos);
                return (-1);
        }
 
-       /* copy the name, strip brackets in the process */
-       name_len = strlen (fields[1]) - 2;
-       if ((fields[1][0] != '(') || (fields[1][name_len + 1] != ')'))
+       name_len = (name_end_pos - name_start_pos) - 1;
+       if (name_len >= sizeof (ps->name))
+               name_len = sizeof (ps->name) - 1;
+
+       sstrncpy (ps->name, &buffer[name_start_pos + 1], name_len + 1);
+
+       if ((buffer_len - name_end_pos) < 2)
+               return (-1);
+       buffer_ptr = &buffer[name_end_pos + 2];
+
+       fields_len = strsplit (buffer_ptr, fields, STATIC_ARRAY_SIZE (fields));
+       if (fields_len < 22)
        {
-               DEBUG ("No brackets found in process name: `%s'", fields[1]);
+               DEBUG ("processes plugin: ps_read_process (pid = %i):"
+                               " `%s' has only %i fields..",
+                               (int) pid, filename, fields_len);
                return (-1);
        }
-       fields[1] = fields[1] + 1;
-       fields[1][name_len] = '\0';
-       strncpy (ps->name, fields[1], PROCSTAT_NAME_LEN);
-
-       ppid = atoi (fields[3]);
 
-       *state = fields[2][0];
+       *state = fields[0][0];
 
        if (*state == 'Z')
        {
@@ -936,16 +1003,16 @@ int ps_read_process (int pid, procstat_t *ps, char *state)
                return (0);
        }
 
-       cpu_user_counter   = atoll (fields[13]);
-       cpu_system_counter = atoll (fields[14]);
-       vmem_size          = atoll (fields[22]);
-       vmem_rss           = atoll (fields[23]);
-       ps->vmem_minflt_counter = atol (fields[9]);
-       ps->vmem_majflt_counter = atol (fields[11]);
+       cpu_user_counter   = atoll (fields[11]);
+       cpu_system_counter = atoll (fields[12]);
+       vmem_size          = atoll (fields[20]);
+       vmem_rss           = atoll (fields[21]);
+       ps->vmem_minflt_counter = atol (fields[7]);
+       ps->vmem_majflt_counter = atol (fields[9]);
 
        {
-               unsigned long long stack_start = atoll (fields[27]);
-               unsigned long long stack_ptr   = atoll (fields[28]);
+               unsigned long long stack_start = atoll (fields[25]);
+               unsigned long long stack_ptr   = atoll (fields[26]);
 
                stack_size = (stack_start > stack_ptr)
                        ? stack_start - stack_ptr
@@ -965,8 +1032,8 @@ int ps_read_process (int pid, procstat_t *ps, char *state)
                DEBUG("ps_read_process: did not get vmem data for pid %i",pid);
        }
 
-       ps->cpu_user_counter = (unsigned long) cpu_user_counter;
-       ps->cpu_system_counter = (unsigned long) cpu_system_counter;
+       ps->cpu_user_counter = cpu_user_counter;
+       ps->cpu_system_counter = cpu_system_counter;
        ps->vmem_size = (unsigned long) vmem_size;
        ps->vmem_rss = (unsigned long) vmem_rss;
        ps->stack_size = (unsigned long) stack_size;
@@ -999,13 +1066,18 @@ static char *ps_get_cmdline (pid_t pid, char *name, char *buf, size_t buf_len)
        if ((pid < 1) || (NULL == buf) || (buf_len < 2))
                return NULL;
 
-       ssnprintf (file, sizeof (file), "/proc/%u/cmdline", pid);
+       ssnprintf (file, sizeof (file), "/proc/%u/cmdline",
+                       (unsigned int) pid);
 
+       errno = 0;
        fd = open (file, O_RDONLY);
        if (fd < 0) {
                char errbuf[4096];
-               WARNING ("processes plugin: Failed to open `%s': %s.", file,
-                               sstrerror (errno, errbuf, sizeof (errbuf)));
+               /* ENOENT means the process exited while we were handling it.
+                * Don't complain about this, it only fills the logs. */
+               if (errno != ENOENT)
+                       WARNING ("processes plugin: Failed to open `%s': %s.", file,
+                                       sstrerror (errno, errbuf, sizeof (errbuf)));
                return NULL;
        }
 
@@ -1020,7 +1092,7 @@ static char *ps_get_cmdline (pid_t pid, char *name, char *buf, size_t buf_len)
                status = read (fd, (void *)buf_ptr, len);
 
                if (status < 0) {
-                       char errbuf[4096];
+                       char errbuf[1024];
 
                        if ((EAGAIN == errno) || (EINTR == errno))
                                continue;
@@ -1076,70 +1148,226 @@ static char *ps_get_cmdline (pid_t pid, char *name, char *buf, size_t buf_len)
        return buf;
 } /* char *ps_get_cmdline (...) */
 
-static unsigned long read_fork_rate ()
+static int read_fork_rate ()
 {
        FILE *proc_stat;
-       char buf[1024];
-       unsigned long result = 0;
-       int numfields;
-       char *fields[3];
+       char buffer[1024];
+       value_t value;
+       _Bool value_valid = 0;
 
-       proc_stat = fopen("/proc/stat", "r");
-       if (proc_stat == NULL) {
+       proc_stat = fopen ("/proc/stat", "r");
+       if (proc_stat == NULL)
+       {
                char errbuf[1024];
                ERROR ("processes plugin: fopen (/proc/stat) failed: %s",
                                sstrerror (errno, errbuf, sizeof (errbuf)));
-               return ULONG_MAX;
+               return (-1);
        }
 
-       while (fgets (buf, sizeof(buf), proc_stat) != NULL)
+       while (fgets (buffer, sizeof (buffer), proc_stat) != NULL)
        {
-               char *endptr;
+               int status;
+               char *fields[3];
+               int fields_num;
 
-               numfields = strsplit(buf, fields, STATIC_ARRAY_SIZE (fields));
-               if (numfields != 2)
+               fields_num = strsplit (buffer, fields,
+                               STATIC_ARRAY_SIZE (fields));
+               if (fields_num != 2)
                        continue;
 
                if (strcmp ("processes", fields[0]) != 0)
                        continue;
 
-               errno = 0;
-               endptr = NULL;
-               result = strtoul(fields[1], &endptr, /* base = */ 10);
-               if ((endptr == fields[1]) || (errno != 0)) {
-                       ERROR ("processes plugin: Cannot parse fork rate: %s",
-                                       fields[1]);
-                       result = ULONG_MAX;
-                       break;
-               }
+               status = parse_value (fields[1], &value, DS_TYPE_DERIVE);
+               if (status == 0)
+                       value_valid = 1;
 
                break;
        }
-
        fclose(proc_stat);
 
-       return result;
+       if (!value_valid)
+               return (-1);
+
+       ps_submit_fork_rate (value.derive);
+       return (0);
 }
+#endif /*KERNEL_LINUX */
 
-static void ps_submit_fork_rate (unsigned long value)
+#if KERNEL_SOLARIS
+static const char *ps_get_cmdline (pid_t pid, /* {{{ */
+               char *buffer, size_t buffer_size)
 {
-       value_t values[1];
-       value_list_t vl = VALUE_LIST_INIT;
+       char path[PATH_MAX];
+       psinfo_t info;
+       int status;
 
-       values[0].derive = (derive_t) value;
+       snprintf(path, sizeof (path), "/proc/%i/psinfo", pid);
 
-       vl.values = values;
-       vl.values_len = 1;
-       sstrncpy (vl.host, hostname_g, sizeof (vl.host));
-       sstrncpy (vl.plugin, "processes", sizeof (vl.plugin));
-       sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
-       sstrncpy (vl.type, "fork_rate", sizeof (vl.type));
-       sstrncpy (vl.type_instance, "", sizeof (vl.type_instance));
+       status = read_file_contents (path, (void *) &info, sizeof (info));
+       if (status != ((int) buffer_size))
+       {
+               ERROR ("processes plugin: Unexpected return value "
+                               "while reading \"%s\": "
+                               "Returned %i but expected %zu.",
+                               path, status, buffer_size);
+               return (NULL);
+       }
 
-       plugin_dispatch_values (&vl);
+       info.pr_psargs[sizeof (info.pr_psargs) - 1] = 0;
+       sstrncpy (buffer, info.pr_psargs, buffer_size);
+
+       return (buffer);
+} /* }}} int ps_get_cmdline */
+
+/*
+ * Reads process information on the Solaris OS. The information comes mainly from
+ * /proc/PID/status, /proc/PID/psinfo and /proc/PID/usage
+ * The values for input and ouput chars are calculated "by hand"
+ * Added a few "solaris" specific process states as well
+ */
+static int ps_read_process(int pid, procstat_t *ps, char *state)
+{
+       char filename[64];
+       char f_psinfo[64], f_usage[64];
+       char *buffer;
+
+       pstatus_t *myStatus;
+       psinfo_t *myInfo;
+       prusage_t *myUsage;
+
+       snprintf(filename, sizeof (filename), "/proc/%i/status", pid);
+       snprintf(f_psinfo, sizeof (f_psinfo), "/proc/%i/psinfo", pid);
+       snprintf(f_usage, sizeof (f_usage), "/proc/%i/usage", pid);
+
+
+       buffer = malloc(sizeof (pstatus_t));
+       memset(buffer, 0, sizeof (pstatus_t));
+       read_file_contents(filename, buffer, sizeof (pstatus_t));
+       myStatus = (pstatus_t *) buffer;
+
+       buffer = malloc(sizeof (psinfo_t));
+       memset(buffer, 0, sizeof(psinfo_t));
+       read_file_contents(f_psinfo, buffer, sizeof (psinfo_t));
+       myInfo = (psinfo_t *) buffer;
+
+       buffer = malloc(sizeof (prusage_t));
+       memset(buffer, 0, sizeof(prusage_t));
+       read_file_contents(f_usage, buffer, sizeof (prusage_t));
+       myUsage = (prusage_t *) buffer;
+
+       sstrncpy(ps->name, myInfo->pr_fname, sizeof (myInfo->pr_fname));
+       ps->num_lwp = myStatus->pr_nlwp;
+       if (myInfo->pr_wstat != 0) {
+               ps->num_proc = 0;
+               ps->num_lwp = 0;
+               *state = (char) 'Z';
+               return (0);
+       } else {
+               ps->num_proc = 1;
+               ps->num_lwp = myInfo->pr_nlwp;
+       }
+
+       /*
+        * Convert system time and user time from nanoseconds to microseconds
+        * for compatibility with the linux module
+        */
+       ps->cpu_system_counter = myStatus -> pr_stime.tv_nsec / 1000;
+       ps->cpu_user_counter = myStatus -> pr_utime.tv_nsec / 1000;
+
+       /*
+        * Convert rssize from KB to bytes to be consistent w/ the linux module
+        */
+       ps->vmem_rss = myInfo->pr_rssize * 1024;
+       ps->vmem_size = myInfo->pr_size * 1024;
+       ps->vmem_minflt_counter = myUsage->pr_minf;
+       ps->vmem_majflt_counter = myUsage->pr_majf;
+
+       /*
+        * TODO: Data and code segment calculations for Solaris
+        */
+
+       ps->vmem_data = -1;
+       ps->vmem_code = -1;
+       ps->stack_size = myStatus->pr_stksize;
+
+       /*
+        * Calculating input/ouput chars
+        * Formula used is total chars / total blocks => chars/block
+        * then convert input/output blocks to chars
+        */
+       ulong_t tot_chars = myUsage->pr_ioch;
+       ulong_t tot_blocks = myUsage->pr_inblk + myUsage->pr_oublk;
+       ulong_t chars_per_block = 1;
+       if (tot_blocks != 0)
+               chars_per_block = tot_chars / tot_blocks;
+       ps->io_rchar = myUsage->pr_inblk * chars_per_block;
+       ps->io_wchar = myUsage->pr_oublk * chars_per_block;
+       ps->io_syscr = myUsage->pr_sysc;
+       ps->io_syscw = myUsage->pr_sysc;
+
+
+       /*
+        * TODO: Find way of setting BLOCKED and PAGING status
+        */
+
+       *state = (char) 'R';
+       if (myStatus->pr_flags & PR_ASLEEP)
+               *state = (char) 'S';
+       else if (myStatus->pr_flags & PR_STOPPED)
+               *state = (char) 'T';
+       else if (myStatus->pr_flags & PR_DETACH)
+               *state = (char) 'E';
+       else if (myStatus->pr_flags & PR_DAEMON)
+               *state = (char) 'A';
+       else if (myStatus->pr_flags & PR_ISSYS)
+               *state = (char) 'Y';
+       else if (myStatus->pr_flags & PR_ORPHAN)
+               *state = (char) 'O';
+
+       sfree(myStatus);
+       sfree(myInfo);
+       sfree(myUsage);
+
+       return (0);
 }
 
-#endif /* KERNEL_LINUX */
+/*
+ * Reads the number of threads created since the last reboot. On Solaris these
+ * are retrieved from kstat (module cpu, name sys, class misc, stat nthreads).
+ * The result is the sum for all the threads created on each cpu
+ */
+static int read_fork_rate()
+{
+       extern kstat_ctl_t *kc;
+       kstat_t *ksp_chain = NULL;
+       derive_t result = 0;
+
+       if (kc == NULL)
+               return (-1);
+
+       for (ksp_chain = kc->kc_chain;
+                       ksp_chain != NULL;
+                       ksp_chain = ksp_chain->ks_next)
+       {
+               if ((strcmp (ksp_chain->ks_module, "cpu") == 0)
+                               && (strcmp (ksp_chain->ks_name, "sys") == 0)
+                               && (strcmp (ksp_chain->ks_class, "misc") == 0))
+               {
+                       long long tmp;
+
+                       kstat_read (kc, ksp_chain, NULL);
+
+                       tmp = get_kstat_value(ksp_chain, "nthreads");
+                       if (tmp != -1LL)
+                               result += tmp;
+               }
+       }
+
+       ps_submit_fork_rate (result);
+       return (0);
+}
+#endif /* KERNEL_SOLARIS */
 
 #if HAVE_THREAD_INFO
 static int mach_get_task_name (task_t t, int *pid, char *name, size_t name_max_len)
@@ -1465,8 +1693,6 @@ static int ps_read (void)
        procstat_entry_t pse;
        char       state;
 
-       unsigned long fork_rate;
-
        procstat_t *ps_ptr;
 
        running = sleeping = zombies = stopped = paging = blocked = 0;
@@ -1548,9 +1774,7 @@ static int ps_read (void)
        for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
                ps_submit_proc_list (ps_ptr);
 
-       fork_rate = read_fork_rate();
-       if (fork_rate != ULONG_MAX)
-               ps_submit_fork_rate(fork_rate);
+       read_fork_rate();
 /* #endif KERNEL_LINUX */
 
 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
@@ -1564,11 +1788,9 @@ static int ps_read (void)
 
        kvm_t *kd;
        char errbuf[1024];
-       char cmdline[ARG_MAX];
-       char *cmdline_ptr;
-       struct kinfo_proc *procs;          /* array of processes */
-       char **argv;
-       int count;                         /* returns number of processes */
+       struct kinfo_proc *procs;          /* array of processes */
+       struct kinfo_proc *proc_ptr = NULL;
+       int count;                         /* returns number of processes */
        int i;
 
        procstat_t *ps_ptr;
@@ -1589,73 +1811,89 @@ static int ps_read (void)
        procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, &count);
        if (procs == NULL)
        {
-               kvm_close (kd);
                ERROR ("processes plugin: Cannot get kvm processes list: %s",
                                kvm_geterr(kd));
+               kvm_close (kd);
                return (0);
        }
 
        /* Iterate through the processes in kinfo_proc */
        for (i = 0; i < count; i++)
        {
-               /* retrieve the arguments */
-               cmdline[0] = 0;
-               cmdline_ptr = NULL;
-
-               argv = kvm_getargv (kd, (const struct kinfo_proc *) &(procs[i]), 0);
-               if (argv != NULL)
+               /* Create only one process list entry per _process_, i.e.
+                * filter out threads (duplicate PID entries). */
+               if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid))
                {
-                       int status;
-                       int argc;
+                       char cmdline[ARG_MAX] = "";
+                       _Bool have_cmdline = 0;
 
-                       argc = 0;
-                       while (argv[argc] != NULL)
-                               argc++;
-
-                       status = strjoin (cmdline, sizeof (cmdline),
-                                       argv, argc, " ");
-
-                       if (status < 0)
-                       {
-                               WARNING ("processes plugin: Command line did "
-                                               "not fit into buffer.");
-                       }
-                       else
+                       proc_ptr = &(procs[i]);
+                       /* Don't probe system processes and processes without arguments */
+                       if (((procs[i].ki_flag & P_SYSTEM) == 0)
+                                       && (procs[i].ki_args != NULL))
                        {
-                               cmdline_ptr = &cmdline[0];
-                       }
-               }
+                               char **argv;
+                               int argc;
+                               int status;
+
+                               /* retrieve the arguments */
+                               argv = kvm_getargv (kd, proc_ptr, /* nchr = */ 0);
+                               argc = 0;
+                               if ((argv != NULL) && (argv[0] != NULL))
+                               {
+                                       while (argv[argc] != NULL)
+                                               argc++;
+
+                                       status = strjoin (cmdline, sizeof (cmdline), argv, argc, " ");
+                                       if (status < 0)
+                                               WARNING ("processes plugin: Command line did not fit into buffer.");
+                                       else
+                                               have_cmdline = 1;
+                               }
+                       } /* if (process has argument list) */
 
-               pse.id       = procs[i].ki_pid;
-               pse.age      = 0;
+                       pse.id       = procs[i].ki_pid;
+                       pse.age      = 0;
 
-               pse.num_proc = 1;
-               pse.num_lwp  = procs[i].ki_numthreads;
+                       pse.num_proc = 1;
+                       pse.num_lwp  = procs[i].ki_numthreads;
 
-               pse.vmem_size = procs[i].ki_size;
-               pse.vmem_rss = procs[i].ki_rssize * getpagesize();
-               pse.vmem_data = procs[i].ki_dsize * getpagesize();
-               pse.vmem_code = procs[i].ki_tsize * getpagesize();
-               pse.stack_size = procs[i].ki_ssize * getpagesize();
-               pse.vmem_minflt = 0;
-               pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt;
-               pse.vmem_majflt = 0;
-               pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt;
+                       pse.vmem_size = procs[i].ki_size;
+                       pse.vmem_rss = procs[i].ki_rssize * pagesize;
+                       pse.vmem_data = procs[i].ki_dsize * pagesize;
+                       pse.vmem_code = procs[i].ki_tsize * pagesize;
+                       pse.stack_size = procs[i].ki_ssize * pagesize;
+                       pse.vmem_minflt = 0;
+                       pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt;
+                       pse.vmem_majflt = 0;
+                       pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt;
 
-               pse.cpu_user = 0;
-               pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_sec
-                       * 1000
-                       + procs[i].ki_rusage.ru_utime.tv_usec;
-               pse.cpu_system = 0;
-               pse.cpu_system_counter = procs[i].ki_rusage.ru_stime.tv_sec
-                       * 1000
-                       + procs[i].ki_rusage.ru_stime.tv_usec;
+                       pse.cpu_user = 0;
+                       pse.cpu_system = 0;
+                       pse.cpu_user_counter = 0;
+                       pse.cpu_system_counter = 0;
+                       /*
+                        * The u-area might be swapped out, and we can't get
+                        * at it because we have a crashdump and no swap.
+                        * If it's here fill in these fields, otherwise, just
+                        * leave them 0.
+                        */
+                       if (procs[i].ki_flag & P_INMEM)
+                       {
+                               pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_usec
+                                       + (1000000lu * procs[i].ki_rusage.ru_utime.tv_sec);
+                               pse.cpu_system_counter = procs[i].ki_rusage.ru_stime.tv_usec
+                                       + (1000000lu * procs[i].ki_rusage.ru_stime.tv_sec);
+                       }
 
-               /* no io data */
-               pse.io_rchar = -1;
-               pse.io_wchar = -1;
-               pse.io_syscr = -1;
-               pse.io_syscw = -1;
+                       /* no I/O data */
+                       pse.io_rchar = -1;
+                       pse.io_wchar = -1;
+                       pse.io_syscr = -1;
+                       pse.io_syscw = -1;
+
+                       ps_list_add (procs[i].ki_comm, have_cmdline ? cmdline : NULL, &pse);
+               } /* if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) */
 
                switch (procs[i].ki_stat)
                {
@@ -1667,8 +1905,6 @@ static int ps_read (void)
                        case SLOCK:     blocked++;      break;
                        case SZOMB:     zombies++;      break;
                }
-
-               ps_list_add (procs[i].ki_comm, cmdline_ptr, &pse);
        }
 
        kvm_close(kd);
@@ -1725,7 +1961,7 @@ static int ps_read (void)
                                if (procentry[i].pi_pid == 0)
                                        cmdline = "swapper";
                                cargs = cmdline;
-                       }
+                       }
                        else
                        {
                                if (getargs(&procentry[i], sizeof(struct procentry64), arglist, MAXARGLN) >= 0)
@@ -1817,15 +2053,125 @@ static int ps_read (void)
 
        for (ps = list_head_g; ps != NULL; ps = ps->next)
                ps_submit_proc_list (ps);
-#endif /* HAVE_PROCINFO_H */
+/* #endif HAVE_PROCINFO_H */
+
+#elif KERNEL_SOLARIS
+       /*
+        * The Solaris section adds a few more process states and removes some
+        * process states compared to linux. Most notably there is no "PAGING"
+        * and "BLOCKED" state for a process.  The rest is similar to the linux
+        * code.
+        */
+       int running = 0;
+       int sleeping = 0;
+       int zombies = 0;
+       int stopped = 0;
+       int detached = 0;
+       int daemon = 0;
+       int system = 0;
+       int orphan = 0;
+
+       struct dirent *ent;
+       DIR *proc;
+
+       int status;
+       procstat_t *ps_ptr;
+       char state;
+
+       char cmdline[PRARGSZ];
+
+       ps_list_reset ();
+
+       proc = opendir ("/proc");
+       if (proc == NULL)
+               return (-1);
+
+       while ((ent = readdir(proc)) != NULL)
+       {
+               int pid;
+               struct procstat ps;
+               procstat_entry_t pse;
+
+               if (!isdigit ((int) ent->d_name[0]))
+                       continue;
+
+               if ((pid = atoi (ent->d_name)) < 1)
+                       continue;
+
+               status = ps_read_process (pid, &ps, &state);
+               if (status != 0)
+               {
+                       DEBUG("ps_read_process failed: %i", status);
+                       continue;
+               }
+
+               pse.id = pid;
+               pse.age = 0;
+
+               pse.num_proc   = ps.num_proc;
+               pse.num_lwp    = ps.num_lwp;
+               pse.vmem_size  = ps.vmem_size;
+               pse.vmem_rss   = ps.vmem_rss;
+               pse.vmem_data  = ps.vmem_data;
+               pse.vmem_code  = ps.vmem_code;
+               pse.stack_size = ps.stack_size;
+
+               pse.vmem_minflt = 0;
+               pse.vmem_minflt_counter = ps.vmem_minflt_counter;
+               pse.vmem_majflt = 0;
+               pse.vmem_majflt_counter = ps.vmem_majflt_counter;
+
+               pse.cpu_user = 0;
+               pse.cpu_user_counter = ps.cpu_user_counter;
+               pse.cpu_system = 0;
+               pse.cpu_system_counter = ps.cpu_system_counter;
+
+               pse.io_rchar = ps.io_rchar;
+               pse.io_wchar = ps.io_wchar;
+               pse.io_syscr = ps.io_syscr;
+               pse.io_syscw = ps.io_syscw;
+
+               switch (state)
+               {
+                       case 'R': running++;  break;
+                       case 'S': sleeping++; break;
+                       case 'E': detached++; break;
+                       case 'Z': zombies++;  break;
+                       case 'T': stopped++;  break;
+                       case 'A': daemon++;   break;
+                       case 'Y': system++;   break;
+                       case 'O': orphan++;   break;
+               }
+
+
+               ps_list_add (ps.name,
+                               ps_get_cmdline ((pid_t) pid,
+                                       cmdline, sizeof (cmdline)),
+                               &pse);
+       } /* while(readdir) */
+       closedir (proc);
+
+       ps_submit_state ("running",  running);
+       ps_submit_state ("sleeping", sleeping);
+       ps_submit_state ("zombies",  zombies);
+       ps_submit_state ("stopped",  stopped);
+       ps_submit_state ("detached", detached);
+       ps_submit_state ("daemon",   daemon);
+       ps_submit_state ("system",   system);
+       ps_submit_state ("orphan",   orphan);
+
+       for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
+               ps_submit_proc_list (ps_ptr);
+
+       read_fork_rate();
+#endif /* KERNEL_SOLARIS */
 
        return (0);
 } /* int ps_read */
 
 void module_register (void)
 {
-       plugin_register_config ("processes", ps_config,
-                       config_keys, config_keys_num);
+       plugin_register_complex_config ("processes", ps_config);
        plugin_register_init ("processes", ps_init);
        plugin_register_read ("processes", ps_read);
 } /* void module_register */
index e90c1a4..0dfba21 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/protocols.c
- * Copyright (C) 2009  Florian octo Forster
+ * Copyright (C) 2009,2010  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -51,14 +51,10 @@ static void submit (const char *protocol_name,
 {
   value_t values[1];
   value_list_t vl = VALUE_LIST_INIT;
+  int status;
 
-  char *tmp_ptr;
-
-  errno = 0;
-  tmp_ptr = NULL;
-  values[0].counter = (counter_t) strtoll (str_value, &tmp_ptr,
-      /* base = */ 0);
-  if ((errno != 0) || (tmp_ptr == str_value))
+  status = parse_value (str_value, values, DS_TYPE_DERIVE);
+  if (status != 0)
   {
     ERROR ("protocols plugin: Parsing string as integer failed: %s",
         str_value);
index c056b5b..10ac8f0 100644 (file)
@@ -217,7 +217,7 @@ static int do_interactive = 0;
 
 static PyThreadState *state;
 
-static PyObject *cpy_format_exception;
+static PyObject *sys_path, *cpy_format_exception;
 
 static cpy_callback_t *cpy_config_callbacks;
 static cpy_callback_t *cpy_init_callbacks;
@@ -282,17 +282,13 @@ void cpy_log_exception(const char *context) {
        Py_END_ALLOW_THREADS
        Py_XDECREF(tn);
        Py_XDECREF(m);
-       if (!cpy_format_exception) {
+       if (!cpy_format_exception || !traceback) {
                PyErr_Clear();
-               Py_XDECREF(type);
+               Py_DECREF(type);
                Py_XDECREF(value);
                Py_XDECREF(traceback);
                return;
        }
-       if (!traceback) {
-               PyErr_Clear();
-               return;
-       }
        list = PyObject_CallFunction(cpy_format_exception, "NNN", type, value, traceback); /* New reference. */
        if (list)
                l = PyObject_Length(list);
@@ -313,6 +309,9 @@ void cpy_log_exception(const char *context) {
        }
        Py_XDECREF(list);
        PyErr_Clear();
+       Py_DECREF(type);
+       Py_XDECREF(value);
+       Py_XDECREF(traceback);
 }
 
 static int cpy_read_callback(user_data_t *data) {
@@ -335,7 +334,7 @@ static int cpy_read_callback(user_data_t *data) {
 static int cpy_write_callback(const data_set_t *ds, const value_list_t *value_list, user_data_t *data) {
        int i;
        cpy_callback_t *c = data->data;
-       PyObject *ret, *list, *temp, *dict = NULL, *val;
+       PyObject *ret, *list, *temp, *dict = NULL;
        Values *v;
 
        CPY_LOCK_THREADS
@@ -345,26 +344,26 @@ static int cpy_write_callback(const data_set_t *ds, const value_list_t *value_li
                        CPY_RETURN_FROM_THREADS 0;
                }
                for (i = 0; i < value_list->values_len; ++i) {
-                       if (ds->ds->type == DS_TYPE_COUNTER) {
+                       if (ds->ds[i].type == DS_TYPE_COUNTER) {
                                if ((long) value_list->values[i].counter == value_list->values[i].counter)
                                        PyList_SetItem(list, i, PyInt_FromLong(value_list->values[i].counter));
                                else
                                        PyList_SetItem(list, i, PyLong_FromUnsignedLongLong(value_list->values[i].counter));
-                       } else if (ds->ds->type == DS_TYPE_GAUGE) {
+                       } else if (ds->ds[i].type == DS_TYPE_GAUGE) {
                                PyList_SetItem(list, i, PyFloat_FromDouble(value_list->values[i].gauge));
-                       } else if (ds->ds->type == DS_TYPE_DERIVE) {
+                       } else if (ds->ds[i].type == DS_TYPE_DERIVE) {
                                if ((long) value_list->values[i].derive == value_list->values[i].derive)
                                        PyList_SetItem(list, i, PyInt_FromLong(value_list->values[i].derive));
                                else
                                        PyList_SetItem(list, i, PyLong_FromLongLong(value_list->values[i].derive));
-                       } else if (ds->ds->type == DS_TYPE_ABSOLUTE) {
+                       } else if (ds->ds[i].type == DS_TYPE_ABSOLUTE) {
                                if ((long) value_list->values[i].absolute == value_list->values[i].absolute)
                                        PyList_SetItem(list, i, PyInt_FromLong(value_list->values[i].absolute));
                                else
                                        PyList_SetItem(list, i, PyLong_FromUnsignedLongLong(value_list->values[i].absolute));
                        } else {
                                Py_BEGIN_ALLOW_THREADS
-                               ERROR("cpy_write_callback: Unknown value type %d.", ds->ds->type);
+                               ERROR("cpy_write_callback: Unknown value type %d.", ds->ds[i].type);
                                Py_END_ALLOW_THREADS
                                Py_DECREF(list);
                                CPY_RETURN_FROM_THREADS 0;
@@ -375,7 +374,7 @@ static int cpy_write_callback(const data_set_t *ds, const value_list_t *value_li
                                CPY_RETURN_FROM_THREADS 0;
                        }
                }
-               dict = PyDict_New();
+               dict = PyDict_New();  /* New reference. */
                if (value_list->meta) {
                        int i, num;
                        char **table;
@@ -394,26 +393,26 @@ static int cpy_write_callback(const data_set_t *ds, const value_list_t *value_li
                                if (type == MD_TYPE_STRING) {
                                        if (meta_data_get_string(meta, table[i], &string))
                                                continue;
-                                       temp = cpy_string_to_unicode_or_bytes(string);
+                                       temp = cpy_string_to_unicode_or_bytes(string);  /* New reference. */
                                        free(string);
                                        PyDict_SetItemString(dict, table[i], temp);
                                        Py_XDECREF(temp);
                                } else if (type == MD_TYPE_SIGNED_INT) {
                                        if (meta_data_get_signed_int(meta, table[i], &si))
                                                continue;
-                                       temp = PyObject_CallFunctionObjArgs((void *) &SignedType, PyLong_FromLongLong(si), (void *) 0);
+                                       temp = PyObject_CallFunctionObjArgs((void *) &SignedType, PyLong_FromLongLong(si), (void *) 0);  /* New reference. */
                                        PyDict_SetItemString(dict, table[i], temp);
                                        Py_XDECREF(temp);
                                } else if (type == MD_TYPE_UNSIGNED_INT) {
                                        if (meta_data_get_unsigned_int(meta, table[i], &ui))
                                                continue;
-                                       temp = PyObject_CallFunctionObjArgs((void *) &UnsignedType, PyLong_FromUnsignedLongLong(ui), (void *) 0);
+                                       temp = PyObject_CallFunctionObjArgs((void *) &UnsignedType, PyLong_FromUnsignedLongLong(ui), (void *) 0);  /* New reference. */
                                        PyDict_SetItemString(dict, table[i], temp);
                                        Py_XDECREF(temp);
                                } else if (type == MD_TYPE_DOUBLE) {
                                        if (meta_data_get_double(meta, table[i], &d))
                                                continue;
-                                       temp = PyFloat_FromDouble(d);
+                                       temp = PyFloat_FromDouble(d);  /* New reference. */
                                        PyDict_SetItemString(dict, table[i], temp);
                                        Py_XDECREF(temp);
                                } else if (type == MD_TYPE_BOOLEAN) {
@@ -428,21 +427,20 @@ static int cpy_write_callback(const data_set_t *ds, const value_list_t *value_li
                        }
                        free(table);
                }
-               val = Values_New(); /* New reference. */
-               v = (Values *) val; 
+               v = (Values *) Values_New(); /* New reference. */
                sstrncpy(v->data.host, value_list->host, sizeof(v->data.host));
                sstrncpy(v->data.type, value_list->type, sizeof(v->data.type));
                sstrncpy(v->data.type_instance, value_list->type_instance, sizeof(v->data.type_instance));
                sstrncpy(v->data.plugin, value_list->plugin, sizeof(v->data.plugin));
                sstrncpy(v->data.plugin_instance, value_list->plugin_instance, sizeof(v->data.plugin_instance));
-               v->data.time = value_list->time;
-               v->interval = value_list->interval;
+               v->data.time = CDTIME_T_TO_DOUBLE(value_list->time);
+               v->interval = CDTIME_T_TO_DOUBLE(value_list->interval);
                Py_CLEAR(v->values);
                v->values = list;
                Py_CLEAR(v->meta);
-               v->meta = dict;
+               v->meta = dict;  /* Steals a reference. */
                ret = PyObject_CallFunctionObjArgs(c->callback, v, c->data, (void *) 0); /* New reference. */
-               Py_XDECREF(val);
+               Py_XDECREF(v);
                if (ret == NULL) {
                        cpy_log_exception("write callback");
                } else {
@@ -465,7 +463,7 @@ static int cpy_notification_callback(const notification_t *notification, user_da
                sstrncpy(n->data.type_instance, notification->type_instance, sizeof(n->data.type_instance));
                sstrncpy(n->data.plugin, notification->plugin, sizeof(n->data.plugin));
                sstrncpy(n->data.plugin_instance, notification->plugin_instance, sizeof(n->data.plugin_instance));
-               n->data.time = notification->time;
+               n->data.time = CDTIME_T_TO_DOUBLE(notification->time);
                sstrncpy(n->message, notification->message, sizeof(n->message));
                n->severity = notification->severity;
                ret = PyObject_CallFunctionObjArgs(c->callback, n, c->data, (void *) 0); /* New reference. */
@@ -484,11 +482,11 @@ static void cpy_log_callback(int severity, const char *message, user_data_t *dat
        PyObject *ret, *text;
 
        CPY_LOCK_THREADS
-       text = cpy_string_to_unicode_or_bytes(message);
+       text = cpy_string_to_unicode_or_bytes(message);  /* New reference. */
        if (c->data == NULL)
-               ret = PyObject_CallFunction(c->callback, "iN", severity, text); /* New reference. */
+               ret = PyObject_CallFunction(c->callback, "iN", severity, text); /* New reference. Steals a reference from "text". */
        else
-               ret = PyObject_CallFunction(c->callback, "iNO", severity, text, c->data); /* New reference. */
+               ret = PyObject_CallFunction(c->callback, "iNO", severity, text, c->data); /* New reference. Steals a reference from "text". */
 
        if (ret == NULL) {
                /* FIXME */
@@ -525,12 +523,13 @@ static void cpy_flush_callback(int timeout, const char *id, user_data_t *data) {
 static PyObject *cpy_register_generic(cpy_callback_t **list_head, PyObject *args, PyObject *kwds) {
        char buf[512];
        cpy_callback_t *c;
-       const char *name = NULL;
+       char *name = NULL;
        PyObject *callback = NULL, *data = NULL, *mod = NULL;
        static char *kwlist[] = {"callback", "data", "name", NULL};
        
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O|Oet", kwlist, &callback, &data, NULL, &name) == 0) return NULL;
        if (PyCallable_Check(callback) == 0) {
+               PyMem_Free(name);
                PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
                return NULL;
        }
@@ -545,18 +544,21 @@ static PyObject *cpy_register_generic(cpy_callback_t **list_head, PyObject *args
        c->next = *list_head;
        *list_head = c;
        Py_XDECREF(mod);
+       PyMem_Free(name);
        return cpy_string_to_unicode_or_bytes(buf);
 }
 
 static PyObject *cpy_flush(cpy_callback_t **list_head, PyObject *args, PyObject *kwds) {
        int timeout = -1;
-       const char *plugin = NULL, *identifier = NULL;
+       char *plugin = NULL, *identifier = NULL;
        static char *kwlist[] = {"plugin", "timeout", "identifier", NULL};
        
        if (PyArg_ParseTupleAndKeywords(args, kwds, "|etiet", kwlist, NULL, &plugin, &timeout, NULL, &identifier) == 0) return NULL;
        Py_BEGIN_ALLOW_THREADS
        plugin_flush(plugin, timeout, identifier);
        Py_END_ALLOW_THREADS
+       PyMem_Free(plugin);
+       PyMem_Free(identifier);
        Py_RETURN_NONE;
 }
 
@@ -575,16 +577,18 @@ static PyObject *cpy_register_generic_userdata(void *reg, void *handler, PyObjec
        reg_function_t *register_function = (reg_function_t *) reg;
        cpy_callback_t *c = NULL;
        user_data_t *user_data = NULL;
-       const char *name = NULL;
+       char *name = NULL;
        PyObject *callback = NULL, *data = NULL;
        static char *kwlist[] = {"callback", "data", "name", NULL};
        
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O|Oet", kwlist, &callback, &data, NULL, &name) == 0) return NULL;
        if (PyCallable_Check(callback) == 0) {
+               PyMem_Free(name);
                PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
                return NULL;
        }
        cpy_build_name(buf, sizeof(buf), callback, name);
+       PyMem_Free(name);
        
        Py_INCREF(callback);
        Py_XINCREF(data);
@@ -605,17 +609,19 @@ static PyObject *cpy_register_read(PyObject *self, PyObject *args, PyObject *kwd
        cpy_callback_t *c = NULL;
        user_data_t *user_data = NULL;
        double interval = 0;
-       const char *name = NULL;
+       char *name = NULL;
        PyObject *callback = NULL, *data = NULL;
        struct timespec ts;
        static char *kwlist[] = {"callback", "interval", "data", "name", NULL};
        
        if (PyArg_ParseTupleAndKeywords(args, kwds, "O|dOet", kwlist, &callback, &interval, &data, NULL, &name) == 0) return NULL;
        if (PyCallable_Check(callback) == 0) {
+               PyMem_Free(name);
                PyErr_SetString(PyExc_TypeError, "callback needs a be a callable object.");
                return NULL;
        }
        cpy_build_name(buf, sizeof(buf), callback, name);
+       PyMem_Free(name);
        
        Py_INCREF(callback);
        Py_XINCREF(data);
@@ -659,48 +665,53 @@ static PyObject *cpy_register_shutdown(PyObject *self, PyObject *args, PyObject
 }
 
 static PyObject *cpy_error(PyObject *self, PyObject *args) {
-       const char *text;
+       char *text;
        if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
        Py_BEGIN_ALLOW_THREADS
        plugin_log(LOG_ERR, "%s", text);
        Py_END_ALLOW_THREADS
+       PyMem_Free(text);
        Py_RETURN_NONE;
 }
 
 static PyObject *cpy_warning(PyObject *self, PyObject *args) {
-       const char *text;
+       char *text;
        if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
        Py_BEGIN_ALLOW_THREADS
        plugin_log(LOG_WARNING, "%s", text);
        Py_END_ALLOW_THREADS
+       PyMem_Free(text);
        Py_RETURN_NONE;
 }
 
 static PyObject *cpy_notice(PyObject *self, PyObject *args) {
-       const char *text;
+       char *text;
        if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
        Py_BEGIN_ALLOW_THREADS
        plugin_log(LOG_NOTICE, "%s", text);
        Py_END_ALLOW_THREADS
+       PyMem_Free(text);
        Py_RETURN_NONE;
 }
 
 static PyObject *cpy_info(PyObject *self, PyObject *args) {
-       const char *text;
+       char *text;
        if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
        Py_BEGIN_ALLOW_THREADS
        plugin_log(LOG_INFO, "%s", text);
        Py_END_ALLOW_THREADS
+       PyMem_Free(text);
        Py_RETURN_NONE;
 }
 
 static PyObject *cpy_debug(PyObject *self, PyObject *args) {
 #ifdef COLLECT_DEBUG
-       const char *text;
+       char *text;
        if (PyArg_ParseTuple(args, "et", NULL, &text) == 0) return NULL;
        Py_BEGIN_ALLOW_THREADS
        plugin_log(LOG_DEBUG, "%s", text);
        Py_END_ALLOW_THREADS
+       PyMem_Free(text);
 #endif
        Py_RETURN_NONE;
 }
@@ -922,7 +933,7 @@ static int cpy_init(void) {
        pthread_sigmask(SIG_BLOCK, &sigset, NULL);
        state = PyEval_SaveThread();
        if (do_interactive) {
-               if (pthread_create(&thread, NULL, cpy_interactive, NULL)) {
+               if (plugin_thread_create(&thread, NULL, cpy_interactive, NULL)) {
                        ERROR("python: Error creating thread for interactive interpreter.");
                }
        }
@@ -976,19 +987,10 @@ PyMODINIT_FUNC PyInit_collectd(void) {
 }
 #endif
 
-static int cpy_config(oconfig_item_t *ci) {
-       int i;
+static int cpy_init_python() {
        char *argv = "";
-       PyObject *sys, *tb;
-       PyObject *sys_path;
+       PyObject *sys;
        PyObject *module;
-       
-       /* Ok in theory we shouldn't do initialization at this point
-        * but we have to. In order to give python scripts a chance
-        * to register a config callback we need to be able to execute
-        * python code during the config callback so we have to start
-        * the interpreter here. */
-       /* Do *not* use the python "thread" module at this point! */
 
 #ifdef IS_PY3K
        /* Add a builtin module, before Py_Initialize */
@@ -1039,6 +1041,22 @@ static int cpy_config(oconfig_item_t *ci) {
        PyModule_AddIntConstant(module, "NOTIF_FAILURE", NOTIF_FAILURE);
        PyModule_AddIntConstant(module, "NOTIF_WARNING", NOTIF_WARNING);
        PyModule_AddIntConstant(module, "NOTIF_OKAY", NOTIF_OKAY);
+       return 0;
+}
+
+static int cpy_config(oconfig_item_t *ci) {
+       int i;
+       PyObject *tb;
+
+       /* Ok in theory we shouldn't do initialization at this point
+        * but we have to. In order to give python scripts a chance
+        * to register a config callback we need to be able to execute
+        * python code during the config callback so we have to start
+        * the interpreter here. */
+       /* Do *not* use the python "thread" module at this point! */
+
+       if (!Py_IsInitialized() && cpy_init_python()) return 1;
+
        for (i = 0; i < ci->children_num; ++i) {
                oconfig_item_t *item = ci->children + i;
                
@@ -1138,7 +1156,6 @@ static int cpy_config(oconfig_item_t *ci) {
                        WARNING("python plugin: Ignoring unknown config key \"%s\".", item->key);
                }
        }
-       Py_DECREF(sys_path);
        return 0;
 }
 
index cc7e296..307af17 100644 (file)
 
 #include "cpython.h"
 
+#define FreeAll() do {\
+       PyMem_Free(type);\
+       PyMem_Free(plugin_instance);\
+       PyMem_Free(type_instance);\
+       PyMem_Free(plugin);\
+       PyMem_Free(host);\
+} while(0)
+
 static PyObject *cpy_common_repr(PyObject *s) {
        PyObject *ret, *tmp;
        static PyObject *l_type = NULL, *l_type_instance = NULL, *l_plugin = NULL, *l_plugin_instance = NULL;
@@ -91,7 +99,7 @@ static PyObject *cpy_common_repr(PyObject *s) {
 
        if (self->time != 0) {
                CPY_STRCAT(&ret, l_time);
-               tmp = PyInt_FromLong(self->time);
+               tmp = PyFloat_FromDouble(self->time);
                CPY_SUBSTITUTE(PyObject_Repr, tmp, tmp);
                CPY_STRCAT_AND_DEL(&ret, tmp);
        }
@@ -143,7 +151,7 @@ static PyObject *PluginData_new(PyTypeObject *type, PyObject *args, PyObject *kw
 static int PluginData_init(PyObject *s, PyObject *args, PyObject *kwds) {
        PluginData *self = (PluginData *) s;
        double time = 0;
-       const char *type = "", *plugin_instance = "", *type_instance = "", *plugin = "", *host = "";
+       char *type = NULL, *plugin_instance = NULL, *type_instance = NULL, *plugin = NULL, *host = NULL;
        static char *kwlist[] = {"type", "plugin_instance", "type_instance",
                        "plugin", "host", "time", NULL};
        
@@ -151,18 +159,21 @@ static int PluginData_init(PyObject *s, PyObject *args, PyObject *kwds) {
                        NULL, &plugin_instance, NULL, &type_instance, NULL, &plugin, NULL, &host, &time))
                return -1;
        
-       if (type[0] != 0 && plugin_get_ds(type) == NULL) {
+       if (type && plugin_get_ds(type) == NULL) {
                PyErr_Format(PyExc_TypeError, "Dataset %s not found", type);
+               FreeAll();
                return -1;
        }
 
-       sstrncpy(self->host, host, sizeof(self->host));
-       sstrncpy(self->plugin, plugin, sizeof(self->plugin));
-       sstrncpy(self->plugin_instance, plugin_instance, sizeof(self->plugin_instance));
-       sstrncpy(self->type, type, sizeof(self->type));
-       sstrncpy(self->type_instance, type_instance, sizeof(self->type_instance));
-       
+       sstrncpy(self->host, host ? host : "", sizeof(self->host));
+       sstrncpy(self->plugin, plugin ? plugin : "", sizeof(self->plugin));
+       sstrncpy(self->plugin_instance, plugin_instance ? plugin_instance : "", sizeof(self->plugin_instance));
+       sstrncpy(self->type, type ? type : "", sizeof(self->type));
+       sstrncpy(self->type_instance, type_instance ? type_instance : "", sizeof(self->type_instance));
        self->time = time;
+
+       FreeAll();
+
        return 0;
 }
 
@@ -351,30 +362,32 @@ static PyObject *Values_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 
 static int Values_init(PyObject *s, PyObject *args, PyObject *kwds) {
        Values *self = (Values *) s;
-       int interval = 0;
-       double time = 0;
+       double interval = 0, time = 0;
        PyObject *values = NULL, *meta = NULL, *tmp;
-       const char *type = "", *plugin_instance = "", *type_instance = "", *plugin = "", *host = "";
+       char *type = NULL, *plugin_instance = NULL, *type_instance = NULL, *plugin = NULL, *host = NULL;
        static char *kwlist[] = {"type", "values", "plugin_instance", "type_instance",
                        "plugin", "host", "time", "interval", "meta", NULL};
        
-       if (!PyArg_ParseTupleAndKeywords(args, kwds, "|etOetetetetdiO", kwlist,
+       if (!PyArg_ParseTupleAndKeywords(args, kwds, "|etOetetetetddO", kwlist,
                        NULL, &type, &values, NULL, &plugin_instance, NULL, &type_instance,
                        NULL, &plugin, NULL, &host, &time, &interval, &meta))
                return -1;
        
-       if (type[0] != 0 && plugin_get_ds(type) == NULL) {
+       if (type && plugin_get_ds(type) == NULL) {
                PyErr_Format(PyExc_TypeError, "Dataset %s not found", type);
+               FreeAll();
                return -1;
        }
 
-       sstrncpy(self->data.host, host, sizeof(self->data.host));
-       sstrncpy(self->data.plugin, plugin, sizeof(self->data.plugin));
-       sstrncpy(self->data.plugin_instance, plugin_instance, sizeof(self->data.plugin_instance));
-       sstrncpy(self->data.type, type, sizeof(self->data.type));
-       sstrncpy(self->data.type_instance, type_instance, sizeof(self->data.type_instance));
+       sstrncpy(self->data.host, host ? host : "", sizeof(self->data.host));
+       sstrncpy(self->data.plugin, plugin ? plugin : "", sizeof(self->data.plugin));
+       sstrncpy(self->data.plugin_instance, plugin_instance ? plugin_instance : "", sizeof(self->data.plugin_instance));
+       sstrncpy(self->data.type, type ? type : "", sizeof(self->data.type));
+       sstrncpy(self->data.type_instance, type_instance ? type_instance : "", sizeof(self->data.type_instance));
        self->data.time = time;
 
+       FreeAll();
+
        if (values == NULL) {
                values = PyList_New(0);
                PyErr_Clear();
@@ -409,8 +422,12 @@ static meta_data_t *cpy_build_meta(PyObject *meta) {
        if (!meta)
                return NULL;
 
+       l = PyDict_Items(meta); /* New reference. */
+       if (!l) {
+               cpy_log_exception("building meta data");
+               return NULL;
+       }
        m = meta_data_create();
-       l = PyDict_Items(meta);
        s = PyList_Size(l);
        for (i = 0; i < s; ++i) {
                const char *string, *keystring;
@@ -475,6 +492,7 @@ static meta_data_t *cpy_build_meta(PyObject *meta) {
                Py_XDECREF(value);
                Py_DECREF(key);
        }
+       Py_XDECREF(l);
        return m;
 }
 
@@ -485,28 +503,30 @@ static PyObject *Values_dispatch(Values *self, PyObject *args, PyObject *kwds) {
        value_t *value;
        value_list_t value_list = VALUE_LIST_INIT;
        PyObject *values = self->values, *meta = self->meta;
-       double time = self->data.time;
-       int interval = self->interval;
-       const char *host = self->data.host;
-       const char *plugin = self->data.plugin;
-       const char *plugin_instance = self->data.plugin_instance;
-       const char *type = self->data.type;
-       const char *type_instance = self->data.type_instance;
+       double time = self->data.time, interval = self->interval;
+       char *host = NULL, *plugin = NULL, *plugin_instance = NULL, *type = NULL, *type_instance = NULL;
        
        static char *kwlist[] = {"type", "values", "plugin_instance", "type_instance",
                        "plugin", "host", "time", "interval", "meta", NULL};
-       if (!PyArg_ParseTupleAndKeywords(args, kwds, "|etOetetetetdiO", kwlist,
+       if (!PyArg_ParseTupleAndKeywords(args, kwds, "|etOetetetetddO", kwlist,
                        NULL, &type, &values, NULL, &plugin_instance, NULL, &type_instance,
                        NULL, &plugin, NULL, &host, &time, &interval, &meta))
                return NULL;
 
-       if (type[0] == 0) {
+       sstrncpy(value_list.host, host ? host : self->data.host, sizeof(value_list.host));
+       sstrncpy(value_list.plugin, plugin ? plugin : self->data.plugin, sizeof(value_list.plugin));
+       sstrncpy(value_list.plugin_instance, plugin_instance ? plugin_instance : self->data.plugin_instance, sizeof(value_list.plugin_instance));
+       sstrncpy(value_list.type, type ? type : self->data.type, sizeof(value_list.type));
+       sstrncpy(value_list.type_instance, type_instance ? type_instance : self->data.type_instance, sizeof(value_list.type_instance));
+       FreeAll();
+       if (value_list.type[0] == 0) {
                PyErr_SetString(PyExc_RuntimeError, "type not set");
+               FreeAll();
                return NULL;
        }
-       ds = plugin_get_ds(type);
+       ds = plugin_get_ds(value_list.type);
        if (ds == NULL) {
-               PyErr_Format(PyExc_TypeError, "Dataset %s not found", type);
+               PyErr_Format(PyExc_TypeError, "Dataset %s not found", value_list.type);
                return NULL;
        }
        if (values == NULL || (PyTuple_Check(values) == 0 && PyList_Check(values) == 0)) {
@@ -519,36 +539,44 @@ static PyObject *Values_dispatch(Values *self, PyObject *args, PyObject *kwds) {
        }
        size = (int) PySequence_Length(values);
        if (size != ds->ds_num) {
-               PyErr_Format(PyExc_RuntimeError, "type %s needs %d values, got %i", type, ds->ds_num, size);
+               PyErr_Format(PyExc_RuntimeError, "type %s needs %d values, got %i", value_list.type, ds->ds_num, size);
                return NULL;
        }
        value = malloc(size * sizeof(*value));
        for (i = 0; i < size; ++i) {
                PyObject *item, *num;
-               item = PySequence_GetItem(values, i);
+               item = PySequence_Fast_GET_ITEM(values, i); /* Borrowed reference. */
                if (ds->ds->type == DS_TYPE_COUNTER) {
-                       num = PyNumber_Long(item);
-                       if (num != NULL)
+                       num = PyNumber_Long(item); /* New reference. */
+                       if (num != NULL) {
                                value[i].counter = PyLong_AsUnsignedLongLong(num);
+                               Py_XDECREF(num);
+                       }
                } else if (ds->ds->type == DS_TYPE_GAUGE) {
-                       num = PyNumber_Float(item);
-                       if (num != NULL)
+                       num = PyNumber_Float(item); /* New reference. */
+                       if (num != NULL) {
                                value[i].gauge = PyFloat_AsDouble(num);
+                               Py_XDECREF(num);
+                       }
                } else if (ds->ds->type == DS_TYPE_DERIVE) {
                        /* This might overflow without raising an exception.
                         * Not much we can do about it */
-                       num = PyNumber_Long(item);
-                       if (num != NULL)
+                       num = PyNumber_Long(item); /* New reference. */
+                       if (num != NULL) {
                                value[i].derive = PyLong_AsLongLong(num);
+                               Py_XDECREF(num);
+                       }
                } else if (ds->ds->type == DS_TYPE_ABSOLUTE) {
                        /* This might overflow without raising an exception.
                         * Not much we can do about it */
-                       num = PyNumber_Long(item);
-                       if (num != NULL)
+                       num = PyNumber_Long(item); /* New reference. */
+                       if (num != NULL) {
                                value[i].absolute = PyLong_AsUnsignedLongLong(num);
+                               Py_XDECREF(num);
+                       }
                } else {
                        free(value);
-                       PyErr_Format(PyExc_RuntimeError, "unknown data type %d for %s", ds->ds->type, type);
+                       PyErr_Format(PyExc_RuntimeError, "unknown data type %d for %s", ds->ds->type, value_list.type);
                        return NULL;
                }
                if (PyErr_Occurred() != NULL) {
@@ -559,13 +587,8 @@ static PyObject *Values_dispatch(Values *self, PyObject *args, PyObject *kwds) {
        value_list.values = value;
        value_list.meta = cpy_build_meta(meta);
        value_list.values_len = size;
-       value_list.time = time;
-       value_list.interval = interval;
-       sstrncpy(value_list.host, host, sizeof(value_list.host));
-       sstrncpy(value_list.plugin, plugin, sizeof(value_list.plugin));
-       sstrncpy(value_list.plugin_instance, plugin_instance, sizeof(value_list.plugin_instance));
-       sstrncpy(value_list.type, type, sizeof(value_list.type));
-       sstrncpy(value_list.type_instance, type_instance, sizeof(value_list.type_instance));
+       value_list.time = DOUBLE_TO_CDTIME_T(time);
+       value_list.interval = DOUBLE_TO_CDTIME_T(interval);
        if (value_list.host[0] == 0)
                sstrncpy(value_list.host, hostname_g, sizeof(value_list.host));
        if (value_list.plugin[0] == 0)
@@ -573,11 +596,12 @@ static PyObject *Values_dispatch(Values *self, PyObject *args, PyObject *kwds) {
        Py_BEGIN_ALLOW_THREADS;
        ret = plugin_dispatch_values(&value_list);
        Py_END_ALLOW_THREADS;
+       meta_data_destroy(value_list.meta);
+       free(value);
        if (ret != 0) {
                PyErr_SetString(PyExc_RuntimeError, "error dispatching values, read the logs");
                return NULL;
        }
-       free(value);
        Py_RETURN_NONE;
 }
 
@@ -588,29 +612,29 @@ static PyObject *Values_write(Values *self, PyObject *args, PyObject *kwds) {
        value_t *value;
        value_list_t value_list = VALUE_LIST_INIT;
        PyObject *values = self->values, *meta = self->meta;
-       double time = self->data.time;
-       int interval = self->interval;
-       const char *host = self->data.host;
-       const char *plugin = self->data.plugin;
-       const char *plugin_instance = self->data.plugin_instance;
-       const char *type = self->data.type;
-       const char *type_instance = self->data.type_instance;
-       const char *dest = NULL;
+       double time = self->data.time, interval = self->interval;
+       char *host = NULL, *plugin = NULL, *plugin_instance = NULL, *type = NULL, *type_instance = NULL, *dest = NULL;
        
        static char *kwlist[] = {"destination", "type", "values", "plugin_instance", "type_instance",
                        "plugin", "host", "time", "interval", "meta", NULL};
-       if (!PyArg_ParseTupleAndKeywords(args, kwds, "|etOetetetetdiO", kwlist,
+       if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|etOetetetetdiO", kwlist, NULL, &dest,
                        NULL, &type, &values, NULL, &plugin_instance, NULL, &type_instance,
                        NULL, &plugin, NULL, &host, &time, &interval, &meta))
                return NULL;
 
-       if (type[0] == 0) {
+       sstrncpy(value_list.host, host ? host : self->data.host, sizeof(value_list.host));
+       sstrncpy(value_list.plugin, plugin ? plugin : self->data.plugin, sizeof(value_list.plugin));
+       sstrncpy(value_list.plugin_instance, plugin_instance ? plugin_instance : self->data.plugin_instance, sizeof(value_list.plugin_instance));
+       sstrncpy(value_list.type, type ? type : self->data.type, sizeof(value_list.type));
+       sstrncpy(value_list.type_instance, type_instance ? type_instance : self->data.type_instance, sizeof(value_list.type_instance));
+       FreeAll();
+       if (value_list.type[0] == 0) {
                PyErr_SetString(PyExc_RuntimeError, "type not set");
                return NULL;
        }
-       ds = plugin_get_ds(type);
+       ds = plugin_get_ds(value_list.type);
        if (ds == NULL) {
-               PyErr_Format(PyExc_TypeError, "Dataset %s not found", type);
+               PyErr_Format(PyExc_TypeError, "Dataset %s not found", value_list.type);
                return NULL;
        }
        if (values == NULL || (PyTuple_Check(values) == 0 && PyList_Check(values) == 0)) {
@@ -619,36 +643,44 @@ static PyObject *Values_write(Values *self, PyObject *args, PyObject *kwds) {
        }
        size = (int) PySequence_Length(values);
        if (size != ds->ds_num) {
-               PyErr_Format(PyExc_RuntimeError, "type %s needs %d values, got %i", type, ds->ds_num, size);
+               PyErr_Format(PyExc_RuntimeError, "type %s needs %d values, got %i", value_list.type, ds->ds_num, size);
                return NULL;
        }
        value = malloc(size * sizeof(*value));
        for (i = 0; i < size; ++i) {
                PyObject *item, *num;
-               item = PySequence_GetItem(values, i);
+               item = PySequence_Fast_GET_ITEM(values, i); /* Borrowed reference. */
                if (ds->ds->type == DS_TYPE_COUNTER) {
-                       num = PyNumber_Long(item);
-                       if (num != NULL)
+                       num = PyNumber_Long(item); /* New reference. */
+                       if (num != NULL) {
                                value[i].counter = PyLong_AsUnsignedLongLong(num);
+                               Py_XDECREF(num);
+                       }
                } else if (ds->ds->type == DS_TYPE_GAUGE) {
-                       num = PyNumber_Float(item);
-                       if (num != NULL)
+                       num = PyNumber_Float(item); /* New reference. */
+                       if (num != NULL) {
                                value[i].gauge = PyFloat_AsDouble(num);
+                               Py_XDECREF(num);
+                       }
                } else if (ds->ds->type == DS_TYPE_DERIVE) {
                        /* This might overflow without raising an exception.
                         * Not much we can do about it */
-                       num = PyNumber_Long(item);
-                       if (num != NULL)
+                       num = PyNumber_Long(item); /* New reference. */
+                       if (num != NULL) {
                                value[i].derive = PyLong_AsLongLong(num);
+                               Py_XDECREF(num);
+                       }
                } else if (ds->ds->type == DS_TYPE_ABSOLUTE) {
                        /* This might overflow without raising an exception.
                         * Not much we can do about it */
-                       num = PyNumber_Long(item);
-                       if (num != NULL)
+                       num = PyNumber_Long(item); /* New reference. */
+                       if (num != NULL) {
                                value[i].absolute = PyLong_AsUnsignedLongLong(num);
+                               Py_XDECREF(num);
+                       }
                } else {
                        free(value);
-                       PyErr_Format(PyExc_RuntimeError, "unknown data type %d for %s", ds->ds->type, type);
+                       PyErr_Format(PyExc_RuntimeError, "unknown data type %d for %s", ds->ds->type, value_list.type);
                        return NULL;
                }
                if (PyErr_Occurred() != NULL) {
@@ -658,13 +690,8 @@ static PyObject *Values_write(Values *self, PyObject *args, PyObject *kwds) {
        }
        value_list.values = value;
        value_list.values_len = size;
-       value_list.time = time;
-       value_list.interval = interval;
-       sstrncpy(value_list.host, host, sizeof(value_list.host));
-       sstrncpy(value_list.plugin, plugin, sizeof(value_list.plugin));
-       sstrncpy(value_list.plugin_instance, plugin_instance, sizeof(value_list.plugin_instance));
-       sstrncpy(value_list.type, type, sizeof(value_list.type));
-       sstrncpy(value_list.type_instance, type_instance, sizeof(value_list.type_instance));
+       value_list.time = DOUBLE_TO_CDTIME_T(time);
+       value_list.interval = DOUBLE_TO_CDTIME_T(interval);
        value_list.meta = cpy_build_meta(meta);;
        if (value_list.host[0] == 0)
                sstrncpy(value_list.host, hostname_g, sizeof(value_list.host));
@@ -673,11 +700,12 @@ static PyObject *Values_write(Values *self, PyObject *args, PyObject *kwds) {
        Py_BEGIN_ALLOW_THREADS;
        ret = plugin_write(dest, NULL, &value_list);
        Py_END_ALLOW_THREADS;
+       meta_data_destroy(value_list.meta);
+       free(value);
        if (ret != 0) {
                PyErr_SetString(PyExc_RuntimeError, "error dispatching values, read the logs");
                return NULL;
        }
-       free(value);
        Py_RETURN_NONE;
 }
 
@@ -701,7 +729,7 @@ static PyObject *Values_repr(PyObject *s) {
        ret = cpy_common_repr(s);
        if (self->interval != 0) {
                CPY_STRCAT(&ret, l_interval);
-               tmp = PyInt_FromLong(self->interval);
+               tmp = PyFloat_FromDouble(self->interval);
                CPY_SUBSTITUTE(PyObject_Repr, tmp, tmp);
                CPY_STRCAT_AND_DEL(&ret, tmp);
        }
@@ -807,8 +835,8 @@ static int Notification_init(PyObject *s, PyObject *args, PyObject *kwds) {
        Notification *self = (Notification *) s;
        int severity = 0;
        double time = 0;
-       const char *message = "";
-       const char *type = "", *plugin_instance = "", *type_instance = "", *plugin = "", *host = "";
+       char *message = NULL;
+       char *type = NULL, *plugin_instance = NULL, *type_instance = NULL, *plugin = NULL, *host = NULL;
        static char *kwlist[] = {"type", "message", "plugin_instance", "type_instance",
                        "plugin", "host", "time", "severity", NULL};
        
@@ -817,20 +845,24 @@ static int Notification_init(PyObject *s, PyObject *args, PyObject *kwds) {
                        NULL, &plugin, NULL, &host, &time, &severity))
                return -1;
        
-       if (type[0] != 0 && plugin_get_ds(type) == NULL) {
+       if (type && plugin_get_ds(type) == NULL) {
                PyErr_Format(PyExc_TypeError, "Dataset %s not found", type);
+               FreeAll();
+               PyMem_Free(message);
                return -1;
        }
 
-       sstrncpy(self->data.host, host, sizeof(self->data.host));
-       sstrncpy(self->data.plugin, plugin, sizeof(self->data.plugin));
-       sstrncpy(self->data.plugin_instance, plugin_instance, sizeof(self->data.plugin_instance));
-       sstrncpy(self->data.type, type, sizeof(self->data.type));
-       sstrncpy(self->data.type_instance, type_instance, sizeof(self->data.type_instance));
+       sstrncpy(self->data.host, host ? host : "", sizeof(self->data.host));
+       sstrncpy(self->data.plugin, plugin ? plugin : "", sizeof(self->data.plugin));
+       sstrncpy(self->data.plugin_instance, plugin_instance ? plugin_instance : "", sizeof(self->data.plugin_instance));
+       sstrncpy(self->data.type, type ? type : "", sizeof(self->data.type));
+       sstrncpy(self->data.type_instance, type_instance ? type_instance : "", sizeof(self->data.type_instance));
+       sstrncpy(self->message, message ? message : "", sizeof(self->message));
        self->data.time = time;
-
-       sstrncpy(self->message, message, sizeof(self->message));
        self->severity = severity;
+
+       FreeAll();
+       PyMem_Free(message);
        return 0;
 }
 
@@ -840,12 +872,8 @@ static PyObject *Notification_dispatch(Notification *self, PyObject *args, PyObj
        notification_t notification;
        double t = self->data.time;
        int severity = self->severity;
-       const char *host = self->data.host;
-       const char *plugin = self->data.plugin;
-       const char *plugin_instance = self->data.plugin_instance;
-       const char *type = self->data.type;
-       const char *type_instance = self->data.type_instance;
-       const char *message = self->message;
+       char *host = NULL, *plugin = NULL, *plugin_instance = NULL, *type = NULL, *type_instance = NULL;
+       char *message = NULL;
        
        static char *kwlist[] = {"type", "message", "plugin_instance", "type_instance",
                        "plugin", "host", "time", "severity", NULL};
@@ -854,27 +882,30 @@ static PyObject *Notification_dispatch(Notification *self, PyObject *args, PyObj
                        NULL, &plugin, NULL, &host, &t, &severity))
                return NULL;
 
-       if (type[0] == 0) {
+       notification.time = DOUBLE_TO_CDTIME_T(t);
+       notification.severity = severity;
+       sstrncpy(notification.message, message ? message : self->message, sizeof(notification.message));
+       sstrncpy(notification.host, host ? host : self->data.host, sizeof(notification.host));
+       sstrncpy(notification.plugin, plugin ? plugin : self->data.plugin, sizeof(notification.plugin));
+       sstrncpy(notification.plugin_instance, plugin_instance ? plugin_instance : self->data.plugin_instance, sizeof(notification.plugin_instance));
+       sstrncpy(notification.type, type ? type : self->data.type, sizeof(notification.type));
+       sstrncpy(notification.type_instance, type_instance ? type_instance : self->data.type_instance, sizeof(notification.type_instance));
+       notification.meta = NULL;
+       FreeAll();
+       PyMem_Free(message);
+
+       if (notification.type[0] == 0) {
                PyErr_SetString(PyExc_RuntimeError, "type not set");
                return NULL;
        }
-       ds = plugin_get_ds(type);
+       ds = plugin_get_ds(notification.type);
        if (ds == NULL) {
-               PyErr_Format(PyExc_TypeError, "Dataset %s not found", type);
+               PyErr_Format(PyExc_TypeError, "Dataset %s not found", notification.type);
                return NULL;
        }
 
-       notification.time = t;
-       notification.severity = severity;
-       sstrncpy(notification.message, message, sizeof(notification.message));
-       sstrncpy(notification.host, host, sizeof(notification.host));
-       sstrncpy(notification.plugin, plugin, sizeof(notification.plugin));
-       sstrncpy(notification.plugin_instance, plugin_instance, sizeof(notification.plugin_instance));
-       sstrncpy(notification.type, type, sizeof(notification.type));
-       sstrncpy(notification.type_instance, type_instance, sizeof(notification.type_instance));
-       notification.meta = NULL;
-       if (notification.time < 1)
-               notification.time = time(0);
+       if (notification.time == 0)
+               notification.time = cdtime();
        if (notification.host[0] == 0)
                sstrncpy(notification.host, hostname_g, sizeof(notification.host));
        if (notification.plugin[0] == 0)
index 30bd8da..439cf4b 100644 (file)
 #include <pthread.h>
 #include <credis.h>
 
+#ifndef HOST_NAME_MAX
+# define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
+#endif
+
 #define REDIS_DEF_HOST   "localhost"
 #define REDIS_DEF_PORT    6379
 #define REDIS_DEF_TIMEOUT 2000
@@ -50,6 +54,7 @@ struct redis_node_s
 {
   char name[MAX_REDIS_NODE_NAME];
   char host[HOST_NAME_MAX];
+  char passwd[HOST_NAME_MAX];
   int port;
   int timeout;
 
@@ -132,6 +137,8 @@ static int redis_config_node (oconfig_item_t *ci) /* {{{ */
     }
     else if (strcasecmp ("Timeout", option->key) == 0)
       status = cf_util_get_int (option, &rn.timeout);
+    else if (strcasecmp ("Password", option->key) == 0)
+      status = cf_util_get_string_buffer (option, rn.passwd, sizeof (rn.passwd));
     else
       WARNING ("redis plugin: Option `%s' not allowed inside a `Node' "
           "block. I'll ignore this option.", option->key);
@@ -196,14 +203,14 @@ static void redis_submit_g (char *plugin_instance,
 } /* }}} */
 
   __attribute__ ((nonnull(2)))
-static void redis_submit_c (char *plugin_instance,
+static void redis_submit_d (char *plugin_instance,
     const char *type, const char *type_instance,
-    counter_t value) /* {{{ */
+    derive_t value) /* {{{ */
 {
   value_t values[1];
   value_list_t vl = VALUE_LIST_INIT;
 
-  values[0].counter = value;
+  values[0].derive = value;
 
   vl.values = values;
   vl.values_len = 1;
@@ -251,6 +258,18 @@ static int redis_read (void) /* {{{ */
       continue;
     }
 
+    if (strlen (rn->passwd) > 0)
+    {
+      DEBUG ("redis plugin: authenticanting node `%s' passwd(%s).", rn->name, rn->passwd);
+      status = credis_auth(rh, rn->passwd);
+      if (status != 0)
+      {
+        WARNING ("redis plugin: unable to authenticate on node `%s'.", rn->name);
+        credis_close (rh);
+        continue;
+      }
+    }
+
     memset (&info, 0, sizeof (info));
     status = credis_info (rh, &info);
     if (status != 0)
@@ -288,8 +307,8 @@ static int redis_read (void) /* {{{ */
     redis_submit_g (rn->name, "current_connections", "slaves", info.connected_slaves);
     redis_submit_g (rn->name, "memory", "used", info.used_memory);
     redis_submit_g (rn->name, "volatile_changes", NULL, info.changes_since_last_save);
-    redis_submit_c (rn->name, "total_connections", NULL, info.total_connections_received);
-    redis_submit_c (rn->name, "total_operations", NULL, info.total_commands_processed);
+    redis_submit_d (rn->name, "total_connections", NULL, info.total_connections_received);
+    redis_submit_d (rn->name, "total_operations", NULL, info.total_commands_processed);
 
     credis_close (rh);
   }
index ff8789e..2ade3bb 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/routeros.c
- * Copyright (C) 2009  Florian octo Forster
+ * Copyright (C) 2009,2010  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
@@ -44,13 +44,13 @@ struct cr_data_s
 typedef struct cr_data_s cr_data_t;
 
 static void cr_submit_io (cr_data_t *rd, const char *type, /* {{{ */
-    const char *type_instance, counter_t rx, counter_t tx)
+    const char *type_instance, derive_t rx, derive_t tx)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = rx;
-       values[1].counter = tx;
+       values[0].derive = rx;
+       values[1].derive = tx;
 
        vl.values = values;
        vl.values_len = STATIC_ARRAY_SIZE (values);
@@ -75,13 +75,13 @@ static void submit_interface (cr_data_t *rd, /* {{{ */
   }
 
   cr_submit_io (rd, "if_packets", i->name,
-      (counter_t) i->rx_packets, (counter_t) i->tx_packets);
+      (derive_t) i->rx_packets, (derive_t) i->tx_packets);
   cr_submit_io (rd, "if_octets", i->name,
-      (counter_t) i->rx_bytes, (counter_t) i->tx_bytes);
+      (derive_t) i->rx_bytes, (derive_t) i->tx_bytes);
   cr_submit_io (rd, "if_errors", i->name,
-      (counter_t) i->rx_errors, (counter_t) i->tx_errors);
+      (derive_t) i->rx_errors, (derive_t) i->tx_errors);
   cr_submit_io (rd, "if_dropped", i->name,
-      (counter_t) i->rx_drops, (counter_t) i->tx_drops);
+      (derive_t) i->rx_drops, (derive_t) i->tx_drops);
 
   submit_interface (rd, i->next);
 } /* }}} void submit_interface */
@@ -116,12 +116,12 @@ static void cr_submit_gauge (cr_data_t *rd, const char *type, /* {{{ */
 
 #if ROS_VERSION >= ROS_VERSION_ENCODE(1, 1, 0)
 static void cr_submit_counter (cr_data_t *rd, const char *type, /* {{{ */
-    const char *type_instance, counter_t value)
+    const char *type_instance, derive_t value)
 {
        value_t values[1];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = value;
+       values[0].derive = value;
 
        vl.values = values;
        vl.values_len = STATIC_ARRAY_SIZE (values);
@@ -166,7 +166,7 @@ static void submit_regtable (cr_data_t *rd, /* {{{ */
   ssnprintf (type_instance, sizeof (type_instance), "%s-%s",
       r->interface, r->radio_name);
   cr_submit_io (rd, "if_octets", type_instance,
-      (counter_t) r->rx_bytes, (counter_t) r->tx_bytes);
+      (derive_t) r->rx_bytes, (derive_t) r->tx_bytes);
   cr_submit_gauge (rd, "snr", type_instance, (gauge_t) r->signal_to_noise);
 
   submit_regtable (rd, r->next);
@@ -212,7 +212,7 @@ static int handle_system_resource (__attribute__((unused)) ros_connection_t *c,
 
   if (rd->collect_disk)
   {
-    cr_submit_counter (rd, "counter", "secors_written", (counter_t) r->write_sect_total);
+    cr_submit_counter (rd, "counter", "secors_written", (derive_t) r->write_sect_total);
     cr_submit_gauge (rd, "gauge", "bad_blocks", (gauge_t) r->bad_blocks);
   }
 
@@ -341,7 +341,7 @@ static int cr_config_router (oconfig_item_t *ci) /* {{{ */
     if (strcasecmp ("Host", child->key) == 0)
       status = cf_util_get_string (child, &router_data->node);
     else if (strcasecmp ("Port", child->key) == 0)
-      status = cf_util_get_string (child, &router_data->service);
+      status = cf_util_get_service (child, &router_data->service);
     else if (strcasecmp ("User", child->key) == 0)
       status = cf_util_get_string (child, &router_data->username);
     else if (strcasecmp ("Password", child->key) == 0)
index 34e860b..45553b7 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/rrdcached.c
- * Copyright (C) 2008  Florian octo Forster
+ * Copyright (C) 2008-2012  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
 /*
  * Private variables
  */
-static const char *config_keys[] =
-{
-  "DaemonAddress",
-  "DataDir",
-  "CreateFiles",
-  "CollectStatistics"
-};
-static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
-
 static char *datadir = NULL;
 static char *daemon_address = NULL;
-static int config_create_files = 1;
-static int config_collect_stats = 1;
+static _Bool config_create_files = 1;
+static _Bool config_collect_stats = 1;
 static rrdcreate_config_t rrdcreate_config =
 {
        /* stepsize = */ 0,
@@ -58,18 +49,28 @@ static rrdcreate_config_t rrdcreate_config =
        /* consolidation_functions_num = */ 0
 };
 
+/*
+ * Prototypes.
+ */
+static int rc_write (const data_set_t *ds, const value_list_t *vl,
+    user_data_t __attribute__((unused)) *user_data);
+static int rc_flush (__attribute__((unused)) cdtime_t timeout,
+    const char *identifier, __attribute__((unused)) user_data_t *ud);
+
 static int value_list_to_string (char *buffer, int buffer_len,
     const data_set_t *ds, const value_list_t *vl)
 {
   int offset;
   int status;
   int i;
+  time_t t;
 
   assert (0 == strcmp (ds->type, vl->type));
 
   memset (buffer, '\0', buffer_len);
 
-  status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) vl->time);
+  t = CDTIME_T_TO_TIME_T (vl->time);
+  status = ssnprintf (buffer, buffer_len, "%lu", (unsigned long) t);
   if ((status < 1) || (status >= buffer_len))
     return (-1);
   offset = status;
@@ -160,55 +161,132 @@ static int value_list_to_filename (char *buffer, int buffer_len,
   return (0);
 } /* int value_list_to_filename */
 
-static int rc_config (const char *key, const char *value)
+static int rc_config_get_int_positive (oconfig_item_t const *ci, int *ret)
+{
+  int status;
+  int tmp = 0;
+
+  status = cf_util_get_int (ci, &tmp);
+  if (status != 0)
+    return (status);
+  if (tmp < 0)
+    return (EINVAL);
+
+  *ret = tmp;
+  return (0);
+} /* int rc_config_get_int_positive */
+
+static int rc_config_get_xff (oconfig_item_t const *ci, double *ret)
 {
-  if (strcasecmp ("DataDir", key) == 0)
+  double value;
+
+  if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
   {
-    if (datadir != NULL)
-      free (datadir);
-    datadir = strdup (value);
-    if (datadir != NULL)
+    ERROR ("rrdcached plugin: The \"%s\" needs exactly one numeric argument "
+        "in the range [0.0, 1.0)", ci->key);
+    return (EINVAL);
+  }
+
+  value = ci->values[0].value.number;
+  if ((value >= 0.0) && (value < 1.0))
+  {
+    *ret = value;
+    return (0);
+  }
+
+  ERROR ("rrdcached plugin: The \"%s\" needs exactly one numeric argument "
+      "in the range [0.0, 1.0)", ci->key);
+  return (EINVAL);
+} /* int rc_config_get_xff */
+
+static int rc_config_add_timespan (int timespan)
+{
+  int *tmp;
+
+  if (timespan <= 0)
+    return (EINVAL);
+
+  tmp = realloc (rrdcreate_config.timespans,
+      sizeof (*rrdcreate_config.timespans)
+      * (rrdcreate_config.timespans_num + 1));
+  if (tmp == NULL)
+    return (ENOMEM);
+  rrdcreate_config.timespans = tmp;
+
+  rrdcreate_config.timespans[rrdcreate_config.timespans_num] = timespan;
+  rrdcreate_config.timespans_num++;
+
+  return (0);
+} /* int rc_config_add_timespan */
+
+static int rc_config (oconfig_item_t *ci)
+{
+  int i;
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t const *child = ci->children + i;
+    const char *key = child->key;
+    int status = 0;
+
+    if (strcasecmp ("DataDir", key) == 0)
     {
-      int len = strlen (datadir);
-      while ((len > 0) && (datadir[len - 1] == '/'))
-      {
-        len--;
-        datadir[len] = '\0';
-      }
-      if (len <= 0)
+      status = cf_util_get_string (child, &datadir);
+      if (status == 0)
       {
-        free (datadir);
-        datadir = NULL;
+        int len = strlen (datadir);
+
+        while ((len > 0) && (datadir[len - 1] == '/'))
+        {
+          len--;
+          datadir[len] = 0;
+        }
+
+        if (len <= 0)
+          sfree (datadir);
       }
     }
-  }
-  else if (strcasecmp ("DaemonAddress", key) == 0)
-  {
-    sfree (daemon_address);
-    daemon_address = strdup (value);
-    if (daemon_address == NULL)
+    else if (strcasecmp ("DaemonAddress", key) == 0)
+      status = cf_util_get_string (child, &daemon_address);
+    else if (strcasecmp ("CreateFiles", key) == 0)
+      status = cf_util_get_boolean (child, &config_create_files);
+    else if (strcasecmp ("CollectStatistics", key) == 0)
+      status = cf_util_get_boolean (child, &config_collect_stats);
+    else if (strcasecmp ("StepSize", key) == 0)
     {
-      ERROR ("rrdcached plugin: strdup failed.");
-      return (1);
+      int tmp = -1;
+
+      status = rc_config_get_int_positive (child, &tmp);
+      if (status == 0)
+        rrdcreate_config.stepsize = (unsigned long) tmp;
     }
-  }
-  else if (strcasecmp ("CreateFiles", key) == 0)
-  {
-    if (IS_FALSE (value))
-      config_create_files = 0;
-    else
-      config_create_files = 1;
-  }
-  else if (strcasecmp ("CollectStatistics", key) == 0)
-  {
-    if (IS_FALSE (value))
-      config_collect_stats = 0;
+    else if (strcasecmp ("HeartBeat", key) == 0)
+      status = rc_config_get_int_positive (child, &rrdcreate_config.heartbeat);
+    else if (strcasecmp ("RRARows", key) == 0)
+      status = rc_config_get_int_positive (child, &rrdcreate_config.rrarows);
+    else if (strcasecmp ("RRATimespan", key) == 0)
+    {
+      int tmp = -1;
+      status = rc_config_get_int_positive (child, &tmp);
+      if (status == 0)
+        status = rc_config_add_timespan (tmp);
+    }
+    else if (strcasecmp ("XFF", key) == 0)
+      status = rc_config_get_xff (child, &rrdcreate_config.xff);
     else
-      config_collect_stats = 1;
+    {
+      WARNING ("rrdcached plugin: Ignoring invalid option %s.", key);
+      continue;
+    }
+
+    if (status != 0)
+      WARNING ("rrdcached plugin: Handling the \"%s\" option failed.", key);
   }
-  else
+
+  if (daemon_address != NULL)
   {
-    return (-1);
+    plugin_register_write ("rrdcached", rc_write, /* user_data = */ NULL);
+    plugin_register_flush ("rrdcached", rc_flush, /* user_data = */ NULL);
   }
   return (0);
 } /* int rc_config */
@@ -225,7 +303,7 @@ static int rc_read (void)
   if (daemon_address == NULL)
     return (-1);
 
-  if (config_collect_stats == 0)
+  if (!config_collect_stats)
     return (-1);
 
   vl.values = values;
@@ -317,7 +395,7 @@ static int rc_read (void)
 
 static int rc_init (void)
 {
-  if (config_collect_stats != 0)
+  if (config_collect_stats)
     plugin_register_read ("rrdcached", rc_read);
 
   return (0);
@@ -326,7 +404,7 @@ static int rc_init (void)
 static int rc_write (const data_set_t *ds, const value_list_t *vl,
     user_data_t __attribute__((unused)) *user_data)
 {
-  char filename[512];
+  char filename[PATH_MAX];
   char values[512];
   char *values_array[2];
   int status;
@@ -359,7 +437,7 @@ static int rc_write (const data_set_t *ds, const value_list_t *vl,
   values_array[0] = values;
   values_array[1] = NULL;
 
-  if (config_create_files != 0)
+  if (config_create_files)
   {
     struct stat statbuf;
 
@@ -404,6 +482,41 @@ static int rc_write (const data_set_t *ds, const value_list_t *vl,
   return (0);
 } /* int rc_write */
 
+static int rc_flush (__attribute__((unused)) cdtime_t timeout, /* {{{ */
+    const char *identifier,
+    __attribute__((unused)) user_data_t *ud)
+{
+  char filename[PATH_MAX + 1];
+  int status;
+
+  if (identifier == NULL)
+    return (EINVAL);
+
+  if (datadir != NULL)
+    ssnprintf (filename, sizeof (filename), "%s/%s.rrd", datadir, identifier);
+  else
+    ssnprintf (filename, sizeof (filename), "%s.rrd", identifier);
+
+  status = rrdc_connect (daemon_address);
+  if (status != 0)
+  {
+    ERROR ("rrdcached plugin: rrdc_connect (%s) failed with status %i.",
+        daemon_address, status);
+    return (-1);
+  }
+
+  status = rrdc_flush (filename);
+  if (status != 0)
+  {
+    ERROR ("rrdcached plugin: rrdc_flush (%s) failed with status %i.",
+        filename, status);
+    return (-1);
+  }
+  DEBUG ("rrdcached plugin: rrdc_flush (%s): Success.", filename);
+
+  return (0);
+} /* }}} int rc_flush */
+
 static int rc_shutdown (void)
 {
   rrdc_disconnect ();
@@ -412,10 +525,8 @@ static int rc_shutdown (void)
 
 void module_register (void)
 {
-  plugin_register_config ("rrdcached", rc_config,
-      config_keys, config_keys_num);
+  plugin_register_complex_config ("rrdcached", rc_config);
   plugin_register_init ("rrdcached", rc_init);
-  plugin_register_write ("rrdcached", rc_write, /* user_data = */ NULL);
   plugin_register_shutdown ("rrdcached", rc_shutdown);
 } /* void module_register */
 
index cb8ad59..b1d13ee 100644 (file)
  */
 struct rrd_cache_s
 {
-       int    values_num;
-       char **values;
-       time_t first_value;
-       time_t last_value;
-       int random_variation;
+       int      values_num;
+       char   **values;
+       cdtime_t first_value;
+       cdtime_t last_value;
+       int64_t  random_variation;
        enum
        {
                FLAG_NONE   = 0x00,
@@ -107,10 +107,10 @@ static rrdcreate_config_t rrdcreate_config =
 
 /* XXX: If you need to lock both, cache_lock and queue_lock, at the same time,
  * ALWAYS lock `cache_lock' first! */
-static int         cache_timeout = 0;
-static int         cache_flush_timeout = 0;
-static int         random_timeout = 1;
-static time_t      cache_flush_last;
+static cdtime_t    cache_timeout = 0;
+static cdtime_t    cache_flush_timeout = 0;
+static cdtime_t    random_timeout = TIME_T_TO_CDTIME_T (1);
+static cdtime_t    cache_flush_last;
 static c_avl_tree_t *cache = NULL;
 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
 
@@ -185,7 +185,7 @@ static int srrd_update (char *filename, char *template,
        if (status != 0)
        {
                WARNING ("rrdtool plugin: rrd_update_r failed: %s: %s",
-                               argv[1], rrd_get_error ());
+                               filename, rrd_get_error ());
        }
 
        sfree (new_argv);
@@ -199,11 +199,13 @@ static int value_list_to_string (char *buffer, int buffer_len,
 {
        int offset;
        int status;
+       time_t tt;
        int i;
 
        memset (buffer, '\0', buffer_len);
 
-       status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) vl->time);
+       tt = CDTIME_T_TO_TIME_T (vl->time);
+       status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) tt);
        if ((status < 1) || (status >= buffer_len))
                return (-1);
        offset = status;
@@ -510,10 +512,11 @@ static int rrd_queue_dequeue (const char *filename,
   return (0);
 } /* int rrd_queue_dequeue */
 
-static void rrd_cache_flush (int timeout)
+/* XXX: You must hold "cache_lock" when calling this function! */
+static void rrd_cache_flush (cdtime_t timeout)
 {
        rrd_cache_t *rc;
-       time_t       now;
+       cdtime_t     now;
 
        char **keys = NULL;
        int    keys_num = 0;
@@ -522,9 +525,11 @@ static void rrd_cache_flush (int timeout)
        c_avl_iterator_t *iter;
        int i;
 
-       DEBUG ("rrdtool plugin: Flushing cache, timeout = %i", timeout);
+       DEBUG ("rrdtool plugin: Flushing cache, timeout = %.3f",
+                       CDTIME_T_TO_DOUBLE (timeout));
 
-       now = time (NULL);
+       now = cdtime ();
+       timeout = TIME_T_TO_CDTIME_T (timeout);
 
        /* Build a list of entries to be flushed */
        iter = c_avl_get_iterator (cache);
@@ -532,7 +537,9 @@ static void rrd_cache_flush (int timeout)
        {
                if (rc->flags != FLAG_NONE)
                        continue;
-               else if ((now - rc->first_value) < timeout)
+               /* timeout == 0  =>  flush everything */
+               else if ((timeout != 0)
+                               && ((now - rc->first_value) < timeout))
                        continue;
                else if (rc->values_num > 0)
                {
@@ -585,10 +592,11 @@ static void rrd_cache_flush (int timeout)
        cache_flush_last = now;
 } /* void rrd_cache_flush */
 
-static int rrd_cache_flush_identifier (int timeout, const char *identifier)
+static int rrd_cache_flush_identifier (cdtime_t timeout,
+    const char *identifier)
 {
   rrd_cache_t *rc;
-  time_t now;
+  cdtime_t now;
   int status;
   char key[2048];
 
@@ -598,7 +606,7 @@ static int rrd_cache_flush_identifier (int timeout, const char *identifier)
     return (0);
   }
 
-  now = time (NULL);
+  now = cdtime ();
 
   if (datadir == NULL)
     snprintf (key, sizeof (key), "%s.rrd",
@@ -642,8 +650,43 @@ static int rrd_cache_flush_identifier (int timeout, const char *identifier)
   return (status);
 } /* int rrd_cache_flush_identifier */
 
+static int64_t rrd_get_random_variation (void)
+{
+  double dbl_timeout;
+  cdtime_t ctm_timeout;
+  double rand_fact;
+  _Bool negative;
+  int64_t ret;
+
+  if (random_timeout <= 0)
+    return (0);
+
+  /* Assure that "cache_timeout + random_variation" is never negative. */
+  if (random_timeout > cache_timeout)
+  {
+         INFO ("rrdtool plugin: Adjusting \"RandomTimeout\" to %.3f seconds.",
+                         CDTIME_T_TO_DOUBLE (cache_timeout));
+         random_timeout = cache_timeout;
+  }
+
+  /* This seems a bit complicated, but "random_timeout" is likely larger than
+   * RAND_MAX, so we can't simply use modulo here. */
+  dbl_timeout = CDTIME_T_TO_DOUBLE (random_timeout);
+  rand_fact = ((double) random ())
+    / ((double) RAND_MAX);
+  negative = (_Bool) (random () % 2);
+
+  ctm_timeout = DOUBLE_TO_CDTIME_T (dbl_timeout * rand_fact);
+
+  ret = (int64_t) ctm_timeout;
+  if (negative)
+    ret *= -1;
+
+  return (ret);
+} /* int64_t rrd_get_random_variation */
+
 static int rrd_cache_insert (const char *filename,
-               const char *value, time_t value_time)
+               const char *value, cdtime_t value_time)
 {
        rrd_cache_t *rc = NULL;
        int new_rc = 0;
@@ -664,14 +707,14 @@ static int rrd_cache_insert (const char *filename,
 
        if (rc == NULL)
        {
-               rc = (rrd_cache_t *) malloc (sizeof (rrd_cache_t));
+               rc = malloc (sizeof (*rc));
                if (rc == NULL)
                        return (-1);
                rc->values_num = 0;
                rc->values = NULL;
                rc->first_value = 0;
                rc->last_value = 0;
-               rc->random_variation = 0;
+               rc->random_variation = rrd_get_random_variation ();
                rc->flags = FLAG_NONE;
                new_rc = 1;
        }
@@ -679,9 +722,9 @@ static int rrd_cache_insert (const char *filename,
        if (rc->last_value >= value_time)
        {
                pthread_mutex_unlock (&cache_lock);
-               DEBUG ("rrdtool plugin: (rc->last_value = %u) >= (value_time = %u)",
-                               (unsigned int) rc->last_value,
-                               (unsigned int) value_time);
+               DEBUG ("rrdtool plugin: (rc->last_value = %"PRIu64") "
+                               ">= (value_time = %"PRIu64")",
+                               rc->last_value, value_time);
                return (-1);
        }
 
@@ -738,11 +781,11 @@ static int rrd_cache_insert (const char *filename,
        }
 
        DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
-                       "values_num = %i; age = %lu;",
+                       "values_num = %i; age = %.3f;",
                        filename, rc->values_num,
-                       (unsigned long)(rc->last_value - rc->first_value));
+                       CDTIME_T_TO_DOUBLE (rc->last_value - rc->first_value));
 
-       if ((rc->last_value + rc->random_variation - rc->first_value) >= cache_timeout)
+       if ((rc->last_value - rc->first_value) >= (cache_timeout + rc->random_variation))
        {
                /* XXX: If you need to lock both, cache_lock and queue_lock, at
                 * the same time, ALWAYS lock `cache_lock' first! */
@@ -754,17 +797,7 @@ static int rrd_cache_insert (const char *filename,
                        if (status == 0)
                                rc->flags = FLAG_QUEUED;
 
-                       /* Update the jitter value. Negative values are
-                        * slightly preferred. */
-                       if (random_timeout > 0)
-                       {
-                               rc->random_variation = (rand () % (2 * random_timeout))
-                                       - random_timeout;
-                       }
-                       else
-                       {
-                               rc->random_variation = 0;
-                       }
+                        rc->random_variation = rrd_get_random_variation ();
                }
                else
                {
@@ -773,7 +806,7 @@ static int rrd_cache_insert (const char *filename,
        }
 
        if ((cache_timeout > 0) &&
-                       ((time (NULL) - cache_flush_last) > cache_flush_timeout))
+                       ((cdtime () - cache_flush_last) > cache_flush_timeout))
                rrd_cache_flush (cache_flush_timeout);
 
        pthread_mutex_unlock (&cache_lock);
@@ -899,8 +932,8 @@ static int rrd_write (const data_set_t *ds, const value_list_t *vl,
        return (status);
 } /* int rrd_write */
 
-static int rrd_flush (int timeout, const char *identifier,
-               user_data_t __attribute__((unused)) *user_data)
+static int rrd_flush (cdtime_t timeout, const char *identifier,
+               __attribute__((unused)) user_data_t *user_data)
 {
        pthread_mutex_lock (&cache_lock);
 
@@ -919,7 +952,7 @@ static int rrd_config (const char *key, const char *value)
 {
        if (strcasecmp ("CacheTimeout", key) == 0)
        {
-               int tmp = atoi (value);
+               double tmp = atof (value);
                if (tmp < 0)
                {
                        fprintf (stderr, "rrdtool: `CacheTimeout' must "
@@ -928,7 +961,7 @@ static int rrd_config (const char *key, const char *value)
                                        "be greater than 0.\n");
                        return (1);
                }
-               cache_timeout = tmp;
+               cache_timeout = DOUBLE_TO_CDTIME_T (tmp);
        }
        else if (strcasecmp ("CacheFlush", key) == 0)
        {
@@ -965,7 +998,7 @@ static int rrd_config (const char *key, const char *value)
        }
        else if (strcasecmp ("StepSize", key) == 0)
        {
-               int temp = atoi (value);
+               unsigned long temp = strtoul (value, NULL, 0);
                if (temp > 0)
                        rrdcreate_config.stepsize = temp;
        }
@@ -1061,10 +1094,10 @@ static int rrd_config (const char *key, const char *value)
        }
        else if (strcasecmp ("RandomTimeout", key) == 0)
         {
-               int tmp;
+               double tmp;
 
-               tmp = atoi (value);
-               if (tmp < 0)
+               tmp = atof (value);
+               if (tmp < 0.0)
                {
                        fprintf (stderr, "rrdtool: `RandomTimeout' must "
                                        "be greater than or equal to zero.\n");
@@ -1073,7 +1106,7 @@ static int rrd_config (const char *key, const char *value)
                }
                else
                {
-                       random_timeout = tmp;
+                       random_timeout = DOUBLE_TO_CDTIME_T (tmp);
                }
        }
        else
@@ -1086,7 +1119,7 @@ static int rrd_config (const char *key, const char *value)
 static int rrd_shutdown (void)
 {
        pthread_mutex_lock (&cache_lock);
-       rrd_cache_flush (-1);
+       rrd_cache_flush (0);
        pthread_mutex_unlock (&cache_lock);
 
        pthread_mutex_lock (&queue_lock);
@@ -1128,22 +1161,9 @@ static int rrd_init (void)
                return (0);
        init_once = 1;
 
-       if (rrdcreate_config.stepsize < 0)
-               rrdcreate_config.stepsize = 0;
        if (rrdcreate_config.heartbeat <= 0)
                rrdcreate_config.heartbeat = 2 * rrdcreate_config.stepsize;
 
-       if ((rrdcreate_config.heartbeat > 0)
-                       && (rrdcreate_config.heartbeat < interval_g))
-               WARNING ("rrdtool plugin: Your `heartbeat' is "
-                               "smaller than your `interval'. This will "
-                               "likely cause problems.");
-       else if ((rrdcreate_config.stepsize > 0)
-                       && (rrdcreate_config.stepsize < interval_g))
-               WARNING ("rrdtool plugin: Your `stepsize' is "
-                               "smaller than your `interval'. This will "
-                               "create needlessly big RRD-files.");
-
        /* Set the cache up */
        pthread_mutex_lock (&cache_lock);
 
@@ -1154,10 +1174,9 @@ static int rrd_init (void)
                return (-1);
        }
 
-       cache_flush_last = time (NULL);
-       if (cache_timeout < 2)
+       cache_flush_last = cdtime ();
+       if (cache_timeout == 0)
        {
-               cache_timeout = 0;
                cache_flush_timeout = 0;
        }
        else if (cache_flush_timeout < cache_timeout)
@@ -1165,7 +1184,7 @@ static int rrd_init (void)
 
        pthread_mutex_unlock (&cache_lock);
 
-       status = pthread_create (&queue_thread, /* attr = */ NULL,
+       status = plugin_thread_create (&queue_thread, /* attr = */ NULL,
                        rrd_queue_thread, /* args = */ NULL);
        if (status != 0)
        {
@@ -1174,7 +1193,7 @@ static int rrd_init (void)
        }
        queue_thread_running = 1;
 
-       DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %i;"
+       DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %lu;"
                        " heartbeat = %i; rrarows = %i; xff = %lf;",
                        (datadir == NULL) ? "(null)" : datadir,
                        rrdcreate_config.stepsize,
index 8391346..209482e 100644 (file)
  *   - honor sensors.conf's ignored
  *   - config Sensor option
  *   - config IgnoreSelected option
+ *
+ *   Henrique de Moraes Holschuh <hmh at debian.org>
+ *   - use default libsensors config file on API 0x400
+ *   - config SensorConfigFile option
  **/
 
 #include "collectd.h"
@@ -132,7 +136,8 @@ static int known_features_num = STATIC_ARRAY_SIZE (known_features);
 static const char *config_keys[] =
 {
        "Sensor",
-       "IgnoreSelected"
+       "IgnoreSelected",
+       "SensorConfigFile"
 };
 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
 
@@ -148,6 +153,7 @@ typedef struct featurelist
 # ifndef SENSORS_CONF_PATH
 #  define SENSORS_CONF_PATH "/etc/sensors.conf"
 # endif
+static char *conffile = SENSORS_CONF_PATH;
 /* #endif SENSORS_API_VERSION < 0x400 */
 
 #elif (SENSORS_API_VERSION >= 0x400) && (SENSORS_API_VERSION < 0x500)
@@ -159,9 +165,7 @@ typedef struct featurelist
        struct featurelist         *next;
 } featurelist_t;
 
-# ifndef SENSORS_CONF_PATH
-#  define SENSORS_CONF_PATH "/etc/sensors3.conf"
-# endif
+static char *conffile = NULL;
 /* #endif (SENSORS_API_VERSION >= 0x400) && (SENSORS_API_VERSION < 0x500) */
 
 #else /* if SENSORS_API_VERSION >= 0x500 */
@@ -169,10 +173,8 @@ typedef struct featurelist
        "as bug."
 #endif
 
-static const char *conffile = SENSORS_CONF_PATH;
 featurelist_t *first_feature = NULL;
 static ignorelist_t *sensor_list;
-static time_t sensors_config_mtime = 0;
 
 #if SENSORS_API_VERSION < 0x400
 /* full chip name logic borrowed from lm_sensors */
@@ -225,7 +227,19 @@ static int sensors_config (const char *key, const char *value)
        if (sensor_list == NULL)
                sensor_list = ignorelist_create (1);
 
-       if (strcasecmp (key, "Sensor") == 0)
+       /* TODO: This setting exists for compatibility with old versions of
+        * lm-sensors. Remove support for those ancient versions in the next
+        * major release. */
+       if (strcasecmp (key, "SensorConfigFile") == 0)
+       {
+               char *tmp = strdup (value);
+               if (tmp != NULL)
+               {
+                       sfree (conffile);
+                       conffile = tmp;
+               }
+       }
+       else if (strcasecmp (key, "Sensor") == 0)
        {
                if (ignorelist_add (sensor_list, value))
                {
@@ -268,47 +282,37 @@ void sensors_free_features (void)
 
 static int sensors_load_conf (void)
 {
-       FILE *fh;
+       static int call_once = 0;
+
+       FILE *fh = NULL;
        featurelist_t *last_feature = NULL;
        
        const sensors_chip_name *chip;
        int chip_num;
 
-       struct stat statbuf;
        int status;
-       
-       status = stat (conffile, &statbuf);
-       if (status != 0)
-       {
-               char errbuf[1024];
-               ERROR ("sensors plugin: stat (%s) failed: %s", conffile,
-                               sstrerror (errno, errbuf, sizeof (errbuf)));
-               sensors_config_mtime = 0;
-       }
 
-       if ((sensors_config_mtime != 0)
-                       && (sensors_config_mtime == statbuf.st_mtime))
-               return (0);
+       if (call_once)
+               return 0;
 
-       if (sensors_config_mtime != 0)
-       {
-               NOTICE ("sensors plugin: Reloading config from %s",
-                               conffile);
-               sensors_free_features ();
-               sensors_config_mtime = 0;
-       }
+       call_once = 1;
 
-       fh = fopen (conffile, "r");
-       if (fh == NULL)
+       if (conffile != NULL)
        {
-               char errbuf[1024];
-               ERROR ("sensors plugin: fopen(%s) failed: %s", conffile,
-                               sstrerror (errno, errbuf, sizeof (errbuf)));
-               return (-1);
+               fh = fopen (conffile, "r");
+               if (fh == NULL)
+               {
+                       char errbuf[1024];
+                       ERROR ("sensors plugin: fopen(%s) failed: %s", conffile,
+                                       sstrerror (errno, errbuf, sizeof (errbuf)));
+                       return (-1);
+               }
        }
 
        status = sensors_init (fh);
-       fclose (fh);
+       if (fh)
+               fclose (fh);
+
        if (status != 0)
        {
                ERROR ("sensors plugin: Cannot initialize sensors. "
@@ -316,8 +320,6 @@ static int sensors_load_conf (void)
                return (-1);
        }
 
-       sensors_config_mtime = statbuf.st_mtime;
-
 #if SENSORS_API_VERSION < 0x400
        chip_num = 0;
        while ((chip = sensors_get_detected_chips (&chip_num)) != NULL)
index cfa26bb..9bd885d 100644 (file)
 #endif
 
 static void serial_submit (const char *type_instance,
-               counter_t rx, counter_t tx)
+               derive_t rx, derive_t tx)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = rx;
-       values[1].counter = tx;
+       values[0].derive = rx;
+       values[1].derive = tx;
 
        vl.values = values;
        vl.values_len = 2;
@@ -54,8 +54,8 @@ static int serial_read (void)
        FILE *fh;
        char buffer[1024];
 
-       counter_t rx = 0;
-       counter_t tx = 0;
+       derive_t rx = 0;
+       derive_t tx = 0;
        
        char *fields[16];
        int i, numfields;
index 1c2828c..c4d043b 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/snmp.c
- * Copyright (C) 2007  Florian octo Forster
+ * Copyright (C) 2007-2012  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
@@ -69,7 +69,7 @@ struct host_definition_s
   int version;
   void *sess_handle;
   c_complain_t complaint;
-  uint32_t interval;
+  cdtime_t interval;
   data_definition_t **data_list;
   int data_list_len;
 };
@@ -79,7 +79,7 @@ typedef struct host_definition_s host_definition_t;
  * gaps in tables. */
 struct csnmp_list_instances_s
 {
-  oid subid;
+  oid_t suffix;
   char instance[DATA_MAX_NAME_LEN];
   struct csnmp_list_instances_s *next;
 };
@@ -87,7 +87,7 @@ typedef struct csnmp_list_instances_s csnmp_list_instances_t;
 
 struct csnmp_table_values_s
 {
-  oid subid;
+  oid_t suffix;
   value_t value;
   struct csnmp_table_values_s *next;
 };
@@ -106,6 +106,54 @@ static int csnmp_read_host (user_data_t *ud);
 /*
  * Private functions
  */
+static void csnmp_oid_init (oid_t *dst, oid const *src, size_t n)
+{
+  assert (n <= STATIC_ARRAY_LEN (dst->oid));
+  memcpy (dst->oid, src, sizeof (*src) * n);
+  dst->oid_len = n;
+}
+
+static int csnmp_oid_compare (oid_t const *left, oid_t const *right)
+{
+  return (snmp_oid_compare (left->oid, left->oid_len,
+        right->oid, right->oid_len));
+}
+
+static int csnmp_oid_suffix (oid_t *dst, oid_t const *src,
+    oid_t const *root)
+{
+  /* Make sure "src" is in "root"s subtree. */
+  if (src->oid_len <= root->oid_len)
+    return (EINVAL);
+  if (snmp_oid_ncompare (root->oid, root->oid_len,
+        src->oid, src->oid_len,
+        /* n = */ root->oid_len) != 0)
+    return (EINVAL);
+
+  memset (dst, 0, sizeof (*dst));
+  dst->oid_len = src->oid_len - root->oid_len;
+  memcpy (dst->oid, &src->oid[root->oid_len],
+      dst->oid_len * sizeof (dst->oid[0]));
+  return (0);
+}
+
+static int csnmp_oid_to_string (char *buffer, size_t buffer_size,
+    oid_t const *o)
+{
+  char oid_str[MAX_OID_LEN][16];
+  char *oid_str_ptr[MAX_OID_LEN];
+  size_t i;
+
+  for (i = 0; i < o->oid_len; i++)
+  {
+    ssnprintf (oid_str[i], sizeof (oid_str[i]), "%lu", (unsigned long) o->oid[i]);
+    oid_str_ptr[i] = oid_str[i];
+  }
+
+  return (strjoin (buffer, buffer_size,
+        oid_str_ptr, o->oid_len, /* separator = */ "."));
+}
+
 static void csnmp_host_close_session (host_definition_t *host) /* {{{ */
 {
   if (host->sess_handle == NULL)
@@ -127,7 +175,7 @@ static void csnmp_host_definition_destroy (void *arg) /* {{{ */
   if (hd->name != NULL)
   {
     DEBUG ("snmp plugin: Destroying host definition for host `%s'.",
-       hd->name);
+        hd->name);
   }
 
   csnmp_host_close_session (hd);
@@ -159,7 +207,6 @@ static void csnmp_host_definition_destroy (void *arg) /* {{{ */
  *      +-> csnmp_config_add_host_community
  *      +-> csnmp_config_add_host_version
  *      +-> csnmp_config_add_host_collect
- *      +-> csnmp_config_add_host_interval
  */
 static void call_snmp_init_once (void)
 {
@@ -213,10 +260,10 @@ static int csnmp_config_add_data_instance (data_definition_t *dd, oconfig_item_t
     dd->instance.oid.oid_len = MAX_OID_LEN;
 
     if (!read_objid (ci->values[0].value.string,
-         dd->instance.oid.oid, &dd->instance.oid.oid_len))
+          dd->instance.oid.oid, &dd->instance.oid.oid_len))
     {
       ERROR ("snmp plugin: read_objid (%s) failed.",
-         ci->values[0].value.string);
+          ci->values[0].value.string);
       return (-1);
     }
   }
@@ -224,7 +271,7 @@ static int csnmp_config_add_data_instance (data_definition_t *dd, oconfig_item_t
   {
     /* Instance is a simple string */
     sstrncpy (dd->instance.string, ci->values[0].value.string,
-       sizeof (dd->instance.string));
+        sizeof (dd->instance.string));
   }
 
   return (0);
@@ -242,7 +289,7 @@ static int csnmp_config_add_data_instance_prefix (data_definition_t *dd,
   if (!dd->is_table)
   {
     WARNING ("snmp plugin: data %s: InstancePrefix is ignored when `Table' "
-       "is set to `false'.", dd->name);
+        "is set to `false'.", dd->name);
     return (-1);
   }
 
@@ -283,10 +330,10 @@ static int csnmp_config_add_data_values (data_definition_t *dd, oconfig_item_t *
     dd->values[i].oid_len = MAX_OID_LEN;
 
     if (NULL == snmp_parse_oid (ci->values[i].value.string,
-         dd->values[i].oid, &dd->values[i].oid_len))
+          dd->values[i].oid, &dd->values[i].oid_len))
     {
       ERROR ("snmp plugin: snmp_parse_oid (%s) failed.",
-         ci->values[i].value.string);
+          ci->values[i].value.string);
       free (dd->values);
       dd->values = NULL;
       dd->values_len = 0;
@@ -302,7 +349,7 @@ static int csnmp_config_add_data_shift (data_definition_t *dd, oconfig_item_t *c
   if ((ci->values_num != 1)
       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
   {
-    WARNING ("snmp plugin: The `Scale' config option needs exactly one number argument.");
+    WARNING ("snmp plugin: The `Shift' config option needs exactly one number argument.");
     return (-1);
   }
 
@@ -524,17 +571,17 @@ static int csnmp_config_add_host_collect (host_definition_t *host,
   {
     for (data = data_head; data != NULL; data = data->next)
       if (strcasecmp (ci->values[i].value.string, data->name) == 0)
-       break;
+        break;
 
     if (data == NULL)
     {
       WARNING ("snmp plugin: No such data configured: `%s'",
-         ci->values[i].value.string);
+          ci->values[i].value.string);
       continue;
     }
 
     DEBUG ("snmp plugin: Collect: host = %s, data[%i] = %s;",
-       host->name, host->data_list_len, data->name);
+        host->name, host->data_list_len, data->name);
 
     host->data_list[host->data_list_len] = data;
     host->data_list_len++;
@@ -543,22 +590,6 @@ static int csnmp_config_add_host_collect (host_definition_t *host,
   return (0);
 } /* int csnmp_config_add_host_collect */
 
-static int csnmp_config_add_host_interval (host_definition_t *hd, oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
-  {
-    WARNING ("snmp plugin: The `Interval' config option needs exactly one number argument.");
-    return (-1);
-  }
-
-  hd->interval = ci->values[0].value.number >= 0
-    ? (uint32_t) ci->values[0].value.number
-    : 0;
-
-  return (0);
-} /* int csnmp_config_add_host_interval */
-
 static int csnmp_config_add_host (oconfig_item_t *ci)
 {
   host_definition_t *hd;
@@ -607,7 +638,7 @@ static int csnmp_config_add_host (oconfig_item_t *ci)
     else if (strcasecmp ("Collect", option->key) == 0)
       csnmp_config_add_host_collect (hd, option);
     else if (strcasecmp ("Interval", option->key) == 0)
-      csnmp_config_add_host_interval (hd, option);
+      cf_util_get_cdtime (option, &hd->interval);
     else
     {
       WARNING ("snmp plugin: csnmp_config_add_host: Option `%s' not allowed here.", option->key);
@@ -651,9 +682,7 @@ static int csnmp_config_add_host (oconfig_item_t *ci)
   cb_data.data = hd;
   cb_data.free_func = csnmp_host_definition_destroy;
 
-  memset (&cb_interval, 0, sizeof (cb_interval));
-  if (hd->interval != 0)
-    cb_interval.tv_sec = (time_t) hd->interval;
+  CDTIME_T_TO_TIMESPEC (hd->interval, &cb_interval);
 
   status = plugin_register_complex_read (/* group = */ NULL, cb_name,
       csnmp_read_host, /* interval = */ &cb_interval,
@@ -715,19 +744,22 @@ static void csnmp_host_open_session (host_definition_t *host)
     snmp_error (&sess, NULL, NULL, &errstr);
 
     ERROR ("snmp plugin: host %s: snmp_sess_open failed: %s",
-       host->name, (errstr == NULL) ? "Unknown problem" : errstr);
+        host->name, (errstr == NULL) ? "Unknown problem" : errstr);
     sfree (errstr);
   }
 } /* void csnmp_host_open_session */
 
 /* TODO: Check if negative values wrap around. Problem: negative temperatures. */
 static value_t csnmp_value_list_to_value (struct variable_list *vl, int type,
-    double scale, double shift)
+    double scale, double shift,
+    const char *host_name, const char *data_name)
 {
   value_t ret;
   uint64_t tmp_unsigned = 0;
   int64_t tmp_signed = 0;
-  int defined = 1;
+  _Bool defined = 1;
+  /* Set to true when the original SNMP type appears to have been signed. */
+  _Bool prefer_signed = 0;
 
   if ((vl->type == ASN_INTEGER)
       || (vl->type == ASN_UINTEGER)
@@ -739,7 +771,12 @@ static value_t csnmp_value_list_to_value (struct variable_list *vl, int type,
   {
     tmp_unsigned = (uint32_t) *vl->val.integer;
     tmp_signed = (int32_t) *vl->val.integer;
-    DEBUG ("snmp plugin: Parsed int32 value is %"PRIi64".", tmp_signed);
+
+    if ((vl->type == ASN_INTEGER)
+        || (vl->type == ASN_GAUGE))
+      prefer_signed = 1;
+
+    DEBUG ("snmp plugin: Parsed int32 value is %"PRIu64".", tmp_unsigned);
   }
   else if (vl->type == ASN_COUNTER64)
   {
@@ -759,16 +796,19 @@ static value_t csnmp_value_list_to_value (struct variable_list *vl, int type,
 
     memset (oid_buffer, 0, sizeof (oid_buffer));
     snprint_objid (oid_buffer, sizeof (oid_buffer) - 1,
-       vl->name, vl->name_length);
+        vl->name, vl->name_length);
 
 #ifdef ASN_NULL
     if (vl->type == ASN_NULL)
       INFO ("snmp plugin: OID \"%s\" is undefined (type ASN_NULL)",
-         oid_buffer);
+          oid_buffer);
     else
 #endif
-      WARNING ("snmp plugin: I don't know the ASN type \"%i\" (OID: %s)",
-         (int) vl->type, oid_buffer);
+      WARNING ("snmp plugin: I don't know the ASN type #%i "
+               "(OID: \"%s\", data block \"%s\", host block \"%s\")",
+          (int) vl->type, oid_buffer,
+          (data_name != NULL) ? data_name : "UNKNOWN",
+          (host_name != NULL) ? host_name : "UNKNOWN");
 
     defined = 0;
   }
@@ -784,7 +824,7 @@ static value_t csnmp_value_list_to_value (struct variable_list *vl, int type,
 
       string_length = sizeof (string) - 1;
       if (vl->val_len < string_length)
-       string_length = vl->val_len;
+        string_length = vl->val_len;
 
       /* The strings we get from the Net-SNMP library may not be null
        * terminated. That is why we're using `memcpy' here and not `strcpy'.
@@ -796,8 +836,8 @@ static value_t csnmp_value_list_to_value (struct variable_list *vl, int type,
       status = parse_value (string, &ret, type);
       if (status != 0)
       {
-       ERROR ("snmp plugin: csnmp_value_list_to_value: Parsing string as %s failed: %s",
-           DS_TYPE_TO_STRING (type), string);
+        ERROR ("snmp plugin: csnmp_value_list_to_value: Parsing string as %s failed: %s",
+            DS_TYPE_TO_STRING (type), string);
       }
     }
 
@@ -805,20 +845,20 @@ static value_t csnmp_value_list_to_value (struct variable_list *vl, int type,
     {
       switch (type)
       {
-       case DS_TYPE_COUNTER:
-       case DS_TYPE_DERIVE:
-       case DS_TYPE_ABSOLUTE:
-         memset (&ret, 0, sizeof (ret));
-         break;
-
-       case DS_TYPE_GAUGE:
-         ret.gauge = NAN;
-         break;
-
-       default:
-         ERROR ("snmp plugin: csnmp_value_list_to_value: Unknown "
-             "data source type: %i.", type);
-         ret.gauge = NAN;
+        case DS_TYPE_COUNTER:
+        case DS_TYPE_DERIVE:
+        case DS_TYPE_ABSOLUTE:
+          memset (&ret, 0, sizeof (ret));
+          break;
+
+        case DS_TYPE_GAUGE:
+          ret.gauge = NAN;
+          break;
+
+        default:
+          ERROR ("snmp plugin: csnmp_value_list_to_value: Unknown "
+              "data source type: %i.", type);
+          ret.gauge = NAN;
       }
     }
   } /* if (vl->type == ASN_OCTET_STR) */
@@ -828,18 +868,28 @@ static value_t csnmp_value_list_to_value (struct variable_list *vl, int type,
   }
   else if (type == DS_TYPE_GAUGE)
   {
-    ret.gauge = NAN;
-    if (defined != 0)
+    if (!defined)
+      ret.gauge = NAN;
+    else if (prefer_signed)
       ret.gauge = (scale * tmp_signed) + shift;
+    else
+      ret.gauge = (scale * tmp_unsigned) + shift;
   }
   else if (type == DS_TYPE_DERIVE)
-    ret.derive = (derive_t) tmp_signed;
+  {
+    if (prefer_signed)
+      ret.derive = (derive_t) tmp_signed;
+    else
+      ret.derive = (derive_t) tmp_unsigned;
+  }
   else if (type == DS_TYPE_ABSOLUTE)
+  {
     ret.absolute = (absolute_t) tmp_unsigned;
+  }
   else
   {
     ERROR ("snmp plugin: csnmp_value_list_to_value: Unknown data source "
-       "type: %i.", type);
+        "type: %i.", type);
     ret.gauge = NAN;
   }
 
@@ -869,10 +919,12 @@ static int csnmp_check_res_left_subtree (const host_definition_t *host,
       vb = vb->next_variable, i++)
   {
     num_checked++;
-    if (snmp_oid_ncompare (data->values[i].oid,
-         data->values[i].oid_len,
-         vb->name, vb->name_length,
-         data->values[i].oid_len) != 0)
+
+    if ((vb->type == SNMP_ENDOFMIBVIEW)
+        || (snmp_oid_ncompare (data->values[i].oid,
+            data->values[i].oid_len,
+            vb->name, vb->name_length,
+            data->values[i].oid_len) != 0))
       num_left_subtree++;
   }
 
@@ -880,7 +932,7 @@ static int csnmp_check_res_left_subtree (const host_definition_t *host,
   if (i < data->values_len)
   {
     ERROR ("snmp plugin: host %s: Expected %i variables, but got only %i",
-       host->name, data->values_len, i);
+        host->name, data->values_len, i);
     return (-1);
   }
 
@@ -889,15 +941,15 @@ static int csnmp_check_res_left_subtree (const host_definition_t *host,
     if (vb == NULL)
     {
       ERROR ("snmp plugin: host %s: Expected one more variable for "
-         "the instance..", host->name);
+          "the instance..", host->name);
       return (-1);
     }
 
     num_checked++;
     if (snmp_oid_ncompare (data->instance.oid.oid,
-         data->instance.oid.oid_len,
-         vb->name, vb->name_length,
-         data->instance.oid.oid_len) != 0)
+          data->instance.oid.oid_len,
+          vb->name, vb->name_length,
+          data->instance.oid.oid_len) != 0)
       num_left_subtree++;
   }
 
@@ -924,7 +976,7 @@ static int csnmp_strvbcopy_hexstring (char *dst, /* {{{ */
     int status;
 
     status = snprintf (buffer_ptr, buffer_free,
-       (i == 0) ? "%02x" : ":%02x", (unsigned int) vb->val.bitstring[i]);
+        (i == 0) ? "%02x" : ":%02x", (unsigned int) vb->val.bitstring[i]);
 
     if (status >= buffer_free)
     {
@@ -977,10 +1029,13 @@ static int csnmp_strvbcopy (char *dst, /* {{{ */
 
 static int csnmp_instance_list_add (csnmp_list_instances_t **head,
     csnmp_list_instances_t **tail,
-    const struct snmp_pdu *res)
+    const struct snmp_pdu *res,
+    const host_definition_t *hd, const data_definition_t *dd)
 {
   csnmp_list_instances_t *il;
   struct variable_list *vb;
+  oid_t vb_name;
+  int status;
 
   /* Set vb on the last variable */
   for (vb = res->variables;
@@ -990,15 +1045,24 @@ static int csnmp_instance_list_add (csnmp_list_instances_t **head,
   if (vb == NULL)
     return (-1);
 
-  il = (csnmp_list_instances_t *) malloc (sizeof (csnmp_list_instances_t));
+  csnmp_oid_init (&vb_name, vb->name, vb->name_length);
+
+  il = malloc (sizeof (*il));
   if (il == NULL)
   {
     ERROR ("snmp plugin: malloc failed.");
     return (-1);
   }
-  il->subid = vb->name[vb->name_length - 1];
+  memset (il, 0, sizeof (*il));
   il->next = NULL;
 
+  status = csnmp_oid_suffix (&il->suffix, &vb_name, &dd->instance.oid);
+  if (status != 0)
+  {
+    sfree (il);
+    return (status);
+  }
+
   /* Get instance name */
   if ((vb->type == ASN_OCTET_STR) || (vb->type == ASN_BIT_STR))
   {
@@ -1009,17 +1073,18 @@ static int csnmp_instance_list_add (csnmp_list_instances_t **head,
     for (ptr = il->instance; *ptr != '\0'; ptr++)
     {
       if ((*ptr > 0) && (*ptr < 32))
-       *ptr = ' ';
+        *ptr = ' ';
       else if (*ptr == '/')
-       *ptr = '_';
+        *ptr = '_';
     }
     DEBUG ("snmp plugin: il->instance = `%s';", il->instance);
   }
   else
   {
-    value_t val = csnmp_value_list_to_value (vb, DS_TYPE_COUNTER, 1.0, 0.0);
+    value_t val = csnmp_value_list_to_value (vb, DS_TYPE_COUNTER,
+        /* scale = */ 1.0, /* shift = */ 0.0, hd->name, dd->name);
     ssnprintf (il->instance, sizeof (il->instance),
-       "%llu", val.counter);
+        "%llu", val.counter);
   }
 
   /* TODO: Debugging output */
@@ -1044,8 +1109,8 @@ static int csnmp_dispatch_table (host_definition_t *host, data_definition_t *dat
   csnmp_table_values_t **value_table_ptr;
 
   int i;
-  oid subid;
-  int have_more;
+  _Bool have_more;
+  oid_t current_suffix;
 
   ds = plugin_get_ds (data->type);
   if (!ds)
@@ -1057,15 +1122,14 @@ static int csnmp_dispatch_table (host_definition_t *host, data_definition_t *dat
 
   instance_list_ptr = instance_list;
 
-  value_table_ptr = (csnmp_table_values_t **) malloc (sizeof (csnmp_table_values_t *)
-      * data->values_len);
+  value_table_ptr = malloc (sizeof (*value_table_ptr) * data->values_len);
   if (value_table_ptr == NULL)
     return (-1);
   for (i = 0; i < data->values_len; i++)
     value_table_ptr[i] = value_table[i];
 
   vl.values_len = ds->ds_num;
-  vl.values = (value_t *) malloc (sizeof (value_t) * vl.values_len);
+  vl.values = malloc (sizeof (*vl.values) * vl.values_len);
   if (vl.values == NULL)
   {
     ERROR ("snmp plugin: malloc failed.");
@@ -1078,50 +1142,70 @@ static int csnmp_dispatch_table (host_definition_t *host, data_definition_t *dat
 
   vl.interval = host->interval;
 
-  subid = 0;
   have_more = 1;
-
-  while (have_more != 0)
+  memset (&current_suffix, 0, sizeof (current_suffix));
+  while (have_more)
   {
+    _Bool suffix_skipped = 0;
+
+    /* Determine next suffix to handle. */
     if (instance_list != NULL)
     {
-      while ((instance_list_ptr != NULL)
-         && (instance_list_ptr->subid < subid))
-       instance_list_ptr = instance_list_ptr->next;
-
       if (instance_list_ptr == NULL)
       {
-       have_more = 0;
-       continue;
+        have_more = 0;
+        continue;
       }
-      else if (instance_list_ptr->subid > subid)
+
+      memcpy (&current_suffix, &instance_list_ptr->suffix, sizeof (current_suffix));
+    }
+    else /* no instance configured */
+    {
+      csnmp_table_values_t *ptr = value_table_ptr[0];
+      if (ptr == NULL)
       {
-       subid = instance_list_ptr->subid;
-       continue;
+        have_more = 0;
+        continue;
       }
-    } /* if (instance_list != NULL) */
 
+      memcpy (&current_suffix, &ptr->suffix, sizeof (current_suffix));
+    }
+
+    /* Update all the value_table_ptr to point at the entry with the same
+     * trailing partial OID */
     for (i = 0; i < data->values_len; i++)
     {
       while ((value_table_ptr[i] != NULL)
-         && (value_table_ptr[i]->subid < subid))
-       value_table_ptr[i] = value_table_ptr[i]->next;
+          && (csnmp_oid_compare (&value_table_ptr[i]->suffix, &current_suffix) < 0))
+        value_table_ptr[i] = value_table_ptr[i]->next;
 
       if (value_table_ptr[i] == NULL)
       {
-       have_more = 0;
-       break;
+        have_more = 0;
+        break;
       }
-      else if (value_table_ptr[i]->subid > subid)
+      else if (csnmp_oid_compare (&value_table_ptr[i]->suffix, &current_suffix) > 0)
       {
-       subid = value_table_ptr[i]->subid;
-       break;
+        /* This suffix is missing in the subtree. Indicate this with the
+         * "suffix_skipped" flag and try the next instance / suffix. */
+        suffix_skipped = 1;
+        break;
       }
     } /* for (i = 0; i < columns; i++) */
-    /* The subid has been increased - start scanning from the beginning
-     * again.. */
-    if (i < data->values_len)
+
+    if (!have_more)
+      break;
+
+    /* Matching the values failed. Start from the beginning again. */
+    if (suffix_skipped)
+    {
+      if (instance_list != NULL)
+        instance_list_ptr = instance_list_ptr->next;
+      else
+        value_table_ptr[0] = value_table_ptr[0]->next;
+
       continue;
+    }
 
     /* if we reach this line, all value_table_ptr[i] are non-NULL and are set
      * to the same subid. instance_list_ptr is either NULL or points to the
@@ -1130,10 +1214,12 @@ static int csnmp_dispatch_table (host_definition_t *host, data_definition_t *dat
     for (i = 1; i < data->values_len; i++)
     {
       assert (value_table_ptr[i] != NULL);
-      assert (value_table_ptr[i-1]->subid == value_table_ptr[i]->subid);
+      assert (csnmp_oid_compare (&value_table_ptr[i-1]->suffix,
+            &value_table_ptr[i]->suffix) == 0);
     }
     assert ((instance_list_ptr == NULL)
-       || (instance_list_ptr->subid == value_table_ptr[0]->subid));
+        || (csnmp_oid_compare (&instance_list_ptr->suffix,
+            &value_table_ptr[0]->suffix) == 0));
 #endif
 
     sstrncpy (vl.type, data->type, sizeof (vl.type));
@@ -1142,15 +1228,15 @@ static int csnmp_dispatch_table (host_definition_t *host, data_definition_t *dat
       char temp[DATA_MAX_NAME_LEN];
 
       if (instance_list_ptr == NULL)
-       ssnprintf (temp, sizeof (temp), "%"PRIu32, (uint32_t) subid);
+        csnmp_oid_to_string (temp, sizeof (temp), &current_suffix);
       else
-       sstrncpy (temp, instance_list_ptr->instance, sizeof (temp));
+        sstrncpy (temp, instance_list_ptr->instance, sizeof (temp));
 
       if (data->instance_prefix == NULL)
-       sstrncpy (vl.type_instance, temp, sizeof (vl.type_instance));
+        sstrncpy (vl.type_instance, temp, sizeof (vl.type_instance));
       else
-       ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s%s",
-           data->instance_prefix, temp);
+        ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s%s",
+            data->instance_prefix, temp);
     }
 
     for (i = 0; i < data->values_len; i++)
@@ -1159,8 +1245,11 @@ static int csnmp_dispatch_table (host_definition_t *host, data_definition_t *dat
     /* If we get here `vl.type_instance' and all `vl.values' have been set */
     plugin_dispatch_values (&vl);
 
-    subid++;
-  } /* while (have_more != 0) */
+    if (instance_list != NULL)
+      instance_list_ptr = instance_list_ptr->next;
+    else
+      value_table_ptr[0] = value_table_ptr[0]->next;
+  } /* while (have_more) */
 
   sfree (vl.values);
   sfree (value_table_ptr);
@@ -1181,13 +1270,13 @@ static int csnmp_read_table (host_definition_t *host, data_definition_t *data)
   int status;
   int i;
 
-  /* `value_table' and `value_table_ptr' implement a linked list for each
-   * value. `instance_list' and `instance_list_ptr' implement a linked list of
+  /* `value_list_head' and `value_list_tail' implement a linked list for each
+   * value. `instance_list_head' and `instance_list_tail' implement a linked list of
    * instance names. This is used to jump gaps in the table. */
-  csnmp_list_instances_t *instance_list;
-  csnmp_list_instances_t *instance_list_ptr;
-  csnmp_table_values_t **value_table;
-  csnmp_table_values_t **value_table_ptr;
+  csnmp_list_instances_t *instance_list_head;
+  csnmp_list_instances_t *instance_list_tail;
+  csnmp_table_values_t **value_list_head;
+  csnmp_table_values_t **value_list_tail;
 
   DEBUG ("snmp plugin: csnmp_read_table (host = %s, data = %s)",
       host->name, data->name);
@@ -1208,7 +1297,7 @@ static int csnmp_read_table (host_definition_t *host, data_definition_t *data)
   if (ds->ds_num != data->values_len)
   {
     ERROR ("snmp plugin: DataSet `%s' requires %i values, but config talks about %i",
-       data->type, ds->ds_num, data->values_len);
+        data->type, ds->ds_num, data->values_len);
     return (-1);
   }
 
@@ -1226,20 +1315,22 @@ static int csnmp_read_table (host_definition_t *host, data_definition_t *data)
   else
     oid_list_len--;
 
-  /* Allocate the `value_table' */
-  value_table = (csnmp_table_values_t **) malloc (sizeof (csnmp_table_values_t *)
-      * 2 * data->values_len);
-  if (value_table == NULL)
+  /* We're going to construct n linked lists, one for each "value".
+   * value_list_head will contain pointers to the heads of these linked lists,
+   * value_list_tail will contain pointers to the tail of the lists. */
+  value_list_head = calloc (data->values_len, sizeof (*value_list_head));
+  value_list_tail = calloc (data->values_len, sizeof (*value_list_tail));
+  if ((value_list_head == NULL) || (value_list_tail == NULL))
   {
-    ERROR ("snmp plugin: csnmp_read_table: malloc failed.");
+    ERROR ("snmp plugin: csnmp_read_table: calloc failed.");
     sfree (oid_list);
+    sfree (value_list_head);
+    sfree (value_list_tail);
     return (-1);
   }
-  memset (value_table, '\0', sizeof (csnmp_table_values_t *) * 2 * data->values_len);
-  value_table_ptr = value_table + data->values_len;
-  
-  instance_list = NULL;
-  instance_list_ptr = NULL;
+
+  instance_list_head = NULL;
+  instance_list_tail = NULL;
 
   status = 0;
   while (status == 0)
@@ -1265,11 +1356,11 @@ static int csnmp_read_table (host_definition_t *host, data_definition_t *data)
       snmp_sess_error (host->sess_handle, NULL, NULL, &errstr);
 
       c_complain (LOG_ERR, &host->complaint,
-         "snmp plugin: host %s: snmp_sess_synch_response failed: %s",
-         host->name, (errstr == NULL) ? "Unknown problem" : errstr);
+          "snmp plugin: host %s: snmp_sess_synch_response failed: %s",
+          host->name, (errstr == NULL) ? "Unknown problem" : errstr);
 
       if (res != NULL)
-       snmp_free_pdu (res);
+        snmp_free_pdu (res);
       res = NULL;
 
       sfree (errstr);
@@ -1281,8 +1372,8 @@ static int csnmp_read_table (host_definition_t *host, data_definition_t *data)
     status = 0;
     assert (res != NULL);
     c_release (LOG_INFO, &host->complaint,
-       "snmp plugin: host %s: snmp_sess_synch_response successful.",
-       host->name);
+        "snmp plugin: host %s: snmp_sess_synch_response successful.",
+        host->name);
 
     vb = res->variables;
     if (vb == NULL)
@@ -1299,76 +1390,90 @@ static int csnmp_read_table (host_definition_t *host, data_definition_t *data)
       break;
     }
 
-    /* if an instance-OID is configured.. */
+    /* Copy the OID of the value used as instance to oid_list, if an instance
+     * is configured. */
     if (data->instance.oid.oid_len > 0)
     {
       /* Allocate a new `csnmp_list_instances_t', insert the instance name and
        * add it to the list */
-      if (csnmp_instance_list_add (&instance_list, &instance_list_ptr,
-           res) != 0)
+      if (csnmp_instance_list_add (&instance_list_head, &instance_list_tail,
+           res, host, data) != 0)
       {
-       ERROR ("snmp plugin: csnmp_instance_list_add failed.");
-       status = -1;
-       break;
+        ERROR ("snmp plugin: csnmp_instance_list_add failed.");
+        status = -1;
+        break;
       }
 
-      /* Set vb on the last variable */
+      /* The instance OID is added to the list of OIDs to GET from the
+       * snmp agent last, so set vb on the last variable returned and copy
+       * that OID. */
       for (vb = res->variables;
-         (vb != NULL) && (vb->next_variable != NULL);
-         vb = vb->next_variable)
-       /* do nothing */;
+          (vb != NULL) && (vb->next_variable != NULL);
+          vb = vb->next_variable)
+        /* do nothing */;
       assert (vb != NULL);
 
-      /* Copy OID to oid_list[data->values_len] */
+      /* Copy the OID of the instance value to oid_list[data->values_len].
+       * "oid_list" is used for the next GETNEXT request. */
       memcpy (oid_list[data->values_len].oid, vb->name,
-         sizeof (oid) * vb->name_length);
+          sizeof (oid) * vb->name_length);
       oid_list[data->values_len].oid_len = vb->name_length;
     }
 
+    /* Iterate over all the (non-instance) values returned by the agent. The
+     * (i < value_len) check will make sure we're not handling the instance OID
+     * twice. */
     for (vb = res->variables, i = 0;
-       (vb != NULL) && (i < data->values_len);
-       vb = vb->next_variable, i++)
+        (vb != NULL) && (i < data->values_len);
+        vb = vb->next_variable, i++)
     {
       csnmp_table_values_t *vt;
+      oid_t vb_name;
+      oid_t suffix;
+
+      csnmp_oid_init (&vb_name, vb->name, vb->name_length);
 
-      /* Check if we left the subtree */
-      if (snmp_oid_ncompare (data->values[i].oid,
-           data->values[i].oid_len,
-           vb->name, vb->name_length,
-           data->values[i].oid_len) != 0)
+      /* Calculate the current suffix. This is later used to check that the
+       * suffix is increasing. This also checks if we left the subtree */
+      status = csnmp_oid_suffix (&suffix, &vb_name, data->values + i);
+      if (status != 0)
       {
-       DEBUG ("snmp plugin: host = %s; data = %s; Value %i left its subtree.",
-           host->name, data->name, i);
-       continue;
+        DEBUG ("snmp plugin: host = %s; data = %s; Value %i failed. "
+            "It probably left its subtree.",
+            host->name, data->name, i);
+        continue;
       }
 
-      if ((value_table_ptr[i] != NULL)
-         && (vb->name[vb->name_length - 1] <= value_table_ptr[i]->subid))
+      /* Make sure the OIDs returned by the agent are increasing. Otherwise our
+       * table matching algorithm will get confused. */
+      if ((value_list_tail[i] != NULL)
+          && (csnmp_oid_compare (&suffix, &value_list_tail[i]->suffix) <= 0))
       {
-       DEBUG ("snmp plugin: host = %s; data = %s; i = %i; "
-           "SUBID is not increasing.",
-           host->name, data->name, i);
-       continue;
+        DEBUG ("snmp plugin: host = %s; data = %s; i = %i; "
+            "Suffix is not increasing.",
+            host->name, data->name, i);
+        continue;
       }
 
-      vt = (csnmp_table_values_t *) malloc (sizeof (csnmp_table_values_t));
+      vt = malloc (sizeof (*vt));
       if (vt == NULL)
       {
-       ERROR ("snmp plugin: malloc failed.");
-       status = -1;
-       break;
+        ERROR ("snmp plugin: malloc failed.");
+        status = -1;
+        break;
       }
+      memset (vt, 0, sizeof (*vt));
 
-      vt->subid = vb->name[vb->name_length - 1];
       vt->value = csnmp_value_list_to_value (vb, ds->ds[i].type,
-         data->scale, data->shift);
+          data->scale, data->shift, host->name, data->name);
+      memcpy (&vt->suffix, &suffix, sizeof (vt->suffix));
       vt->next = NULL;
 
-      if (value_table_ptr[i] == NULL)
-       value_table[i] = vt;
+      if (value_list_tail[i] == NULL)
+        value_list_head[i] = vt;
       else
-       value_table_ptr[i]->next = vt;
-      value_table_ptr[i] = vt;
+        value_list_tail[i]->next = vt;
+      value_list_tail[i] = vt;
 
       /* Copy OID to oid_list[i + 1] */
       memcpy (oid_list[i].oid, vb->name, sizeof (oid) * vb->name_length);
@@ -1385,28 +1490,28 @@ static int csnmp_read_table (host_definition_t *host, data_definition_t *data)
   res = NULL;
 
   if (status == 0)
-    csnmp_dispatch_table (host, data, instance_list, value_table);
+    csnmp_dispatch_table (host, data, instance_list_head, value_list_head);
 
   /* Free all allocated variables here */
-  while (instance_list != NULL)
+  while (instance_list_head != NULL)
   {
-    instance_list_ptr = instance_list->next;
-    sfree (instance_list);
-    instance_list = instance_list_ptr;
+    csnmp_list_instances_t *next = instance_list_head->next;
+    sfree (instance_list_head);
+    instance_list_head = next;
   }
 
   for (i = 0; i < data->values_len; i++)
   {
-    csnmp_table_values_t *tmp;
-    while (value_table[i] != NULL)
+    while (value_list_head[i] != NULL)
     {
-      tmp = value_table[i]->next;
-      sfree (value_table[i]);
-      value_table[i] = tmp;
+      csnmp_table_values_t *next = value_list_head[i]->next;
+      sfree (value_list_head[i]);
+      value_list_head[i] = next;
     }
   }
 
-  sfree (value_table);
+  sfree (value_list_head);
+  sfree (value_list_tail);
   sfree (oid_list);
 
   return (0);
@@ -1443,7 +1548,7 @@ static int csnmp_read_value (host_definition_t *host, data_definition_t *data)
   if (ds->ds_num != data->values_len)
   {
     ERROR ("snmp plugin: DataSet `%s' requires %i values, but config talks about %i",
-       data->type, ds->ds_num, data->values_len);
+        data->type, ds->ds_num, data->values_len);
     return (-1);
   }
 
@@ -1486,7 +1591,7 @@ static int csnmp_read_value (host_definition_t *host, data_definition_t *data)
 
     snmp_sess_error (host->sess_handle, NULL, NULL, &errstr);
     ERROR ("snmp plugin: host %s: snmp_sess_synch_response failed: %s",
-       host->name, (errstr == NULL) ? "Unknown problem" : errstr);
+        host->name, (errstr == NULL) ? "Unknown problem" : errstr);
 
     if (res != NULL)
       snmp_free_pdu (res);
@@ -1504,15 +1609,15 @@ static int csnmp_read_value (host_definition_t *host, data_definition_t *data)
 #if COLLECT_DEBUG
     char buffer[1024];
     snprint_variable (buffer, sizeof (buffer),
-       vb->name, vb->name_length, vb);
+        vb->name, vb->name_length, vb);
     DEBUG ("snmp plugin: Got this variable: %s", buffer);
 #endif /* COLLECT_DEBUG */
 
     for (i = 0; i < data->values_len; i++)
       if (snmp_oid_compare (data->values[i].oid, data->values[i].oid_len,
-           vb->name, vb->name_length) == 0)
-       vl.values[i] = csnmp_value_list_to_value (vb, ds->ds[i].type,
-           data->scale, data->shift);
+            vb->name, vb->name_length) == 0)
+        vl.values[i] = csnmp_value_list_to_value (vb, ds->ds[i].type,
+            data->scale, data->shift, host->name, data->name);
   } /* for (res->variables) */
 
   if (res != NULL)
@@ -1529,8 +1634,8 @@ static int csnmp_read_value (host_definition_t *host, data_definition_t *data)
 static int csnmp_read_host (user_data_t *ud)
 {
   host_definition_t *host;
-  time_t time_start;
-  time_t time_end;
+  cdtime_t time_start;
+  cdtime_t time_end;
   int status;
   int success;
   int i;
@@ -1538,11 +1643,9 @@ static int csnmp_read_host (user_data_t *ud)
   host = ud->data;
 
   if (host->interval == 0)
-    host->interval = interval_g;
+    host->interval = plugin_get_interval ();
 
-  time_start = time (NULL);
-  DEBUG ("snmp plugin: csnmp_read_host (%s) started at %u;", host->name,
-      (unsigned int) time_start);
+  time_start = cdtime ();
 
   if (host->sess_handle == NULL)
     csnmp_host_open_session (host);
@@ -1564,14 +1667,14 @@ static int csnmp_read_host (user_data_t *ud)
       success++;
   }
 
-  time_end = time (NULL);
-  DEBUG ("snmp plugin: csnmp_read_host (%s) finished at %u;", host->name,
-      (unsigned int) time_end);
-  if ((uint32_t) (time_end - time_start) > host->interval)
+  time_end = cdtime ();
+  if ((time_end - time_start) > host->interval)
   {
-    WARNING ("snmp plugin: Host `%s' should be queried every %"PRIu32
-       " seconds, but reading all values takes %u seconds.",
-       host->name, host->interval, (unsigned int) (time_end - time_start));
+    WARNING ("snmp plugin: Host `%s' should be queried every %.3f "
+       "seconds, but reading all values takes %.3f seconds.",
+       host->name,
+       CDTIME_T_TO_DOUBLE (host->interval),
+       CDTIME_T_TO_DOUBLE (time_end - time_start));
   }
 
   if (success == 0)
index f5a0ea2..46d3534 100644 (file)
@@ -1,8 +1,9 @@
 /**
  * collectd - src/swap.c
- * Copyright (C) 2005-2009  Florian octo Forster
+ * Copyright (C) 2005-2012  Florian octo Forster
  * Copyright (C) 2009       Stefan Völkel
  * Copyright (C) 2009       Manuel Sanmartin
+ * Copyright (C) 2010       Aurélien Reynaud
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -18,8 +19,9 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  *   Manuel Sanmartin
+ *   Aurélien Reynaud <collectd at wattapower.net>
  **/
 
 #if HAVE_CONFIG_H
 #define MAX(x,y) ((x) > (y) ? (x) : (y))
 
 #if KERNEL_LINUX
-/* No global variables */
-/* #endif KERNEL_LINUX */
-
-#elif HAVE_LIBKSTAT
+# define SWAP_HAVE_REPORT_BY_DEVICE 1
 static derive_t pagesize;
-static kstat_t *ksp;
-/* #endif HAVE_LIBKSTAT */
+static _Bool report_bytes = 0;
+static _Bool report_by_device = 0;
+/* #endif KERNEL_LINUX */
 
 #elif HAVE_SWAPCTL && HAVE_SWAPCTL_TWO_ARGS
+# define SWAP_HAVE_REPORT_BY_DEVICE 1
 static derive_t pagesize;
-/* #endif HAVE_SWAPCTL */
+static _Bool report_by_device = 0;
+/* #endif HAVE_SWAPCTL && HAVE_SWAPCTL_TWO_ARGS */
 
 #elif defined(VM_SWAPUSAGE)
 /* No global variables */
@@ -102,18 +104,51 @@ static perfstat_memory_total_t pmemory;
 # error "No applicable input method."
 #endif /* HAVE_LIBSTATGRAB */
 
-static int swap_init (void)
+static const char *config_keys[] =
 {
+       "ReportBytes",
+       "ReportByDevice"
+};
+static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
+
+static int swap_config (const char *key, const char *value) /* {{{ */
+{
+       if (strcasecmp ("ReportBytes", key) == 0)
+       {
 #if KERNEL_LINUX
-       /* No init stuff */
-/* #endif KERNEL_LINUX */
+               report_bytes = IS_TRUE (value) ? 1 : 0;
+#else
+               WARNING ("swap plugin: The \"ReportBytes\" option is only "
+                               "valid under Linux. "
+                               "The option is going to be ignored.");
+#endif
+       }
+       else if (strcasecmp ("ReportByDevice", key) == 0)
+       {
+#if SWAP_HAVE_REPORT_BY_DEVICE
+               if (IS_TRUE (value))
+                       report_by_device = 1;
+               else
+                       report_by_device = 0;
+#else
+               WARNING ("swap plugin: The \"ReportByDevice\" option is not "
+                               "supported on this platform. "
+                               "The option is going to be ignored.");
+#endif /* SWAP_HAVE_REPORT_BY_DEVICE */
+       }
+       else
+       {
+               return (-1);
+       }
 
-#elif HAVE_LIBKSTAT
-       /* getpagesize(3C) tells me this does not fail.. */
-       pagesize = (derive_t) getpagesize ();
-       if (get_kstat (&ksp, "unix", 0, "system_pages"))
-               ksp = NULL;
-/* #endif HAVE_LIBKSTAT */
+       return (0);
+} /* }}} int swap_config */
+
+static int swap_init (void) /* {{{ */
+{
+#if KERNEL_LINUX
+       pagesize = (derive_t) sysconf (_SC_PAGESIZE);
+/* #endif KERNEL_LINUX */
 
 #elif HAVE_SWAPCTL && HAVE_SWAPCTL_TWO_ARGS
        /* getpagesize(3C) tells me this does not fail.. */
@@ -154,93 +189,190 @@ static int swap_init (void)
 #endif /* HAVE_PERFSTAT */
 
        return (0);
-}
+} /* }}} int swap_init */
 
-static void swap_submit (const char *type_instance, derive_t value, unsigned type)
+static void swap_submit (const char *plugin_instance, /* {{{ */
+               const char *type, const char *type_instance,
+               value_t value)
 {
-       value_t values[1];
        value_list_t vl = VALUE_LIST_INIT;
 
-       switch (type)
-       {
-               case DS_TYPE_GAUGE:
-                       values[0].gauge = (gauge_t) value;
-                       sstrncpy (vl.type, "swap", sizeof (vl.type));
-                       break;
-               case DS_TYPE_DERIVE:
-                       values[0].derive = value;
-                       sstrncpy (vl.type, "swap_io", sizeof (vl.type));
-                       break;
-               default:
-                       ERROR ("swap plugin: swap_submit called with wrong"
-                               " type");
-       }
+       assert (type != NULL);
 
-       vl.values = values;
+       vl.values = &value;
        vl.values_len = 1;
        sstrncpy (vl.host, hostname_g, sizeof (vl.host));
        sstrncpy (vl.plugin, "swap", sizeof (vl.plugin));
-       sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
+       if (plugin_instance != NULL)
+               sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
+       sstrncpy (vl.type, type, sizeof (vl.type));
+       if (type_instance != NULL)
+               sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
 
        plugin_dispatch_values (&vl);
-} /* void swap_submit */
+} /* }}} void swap_submit_inst */
 
-static int swap_read (void)
+static void swap_submit_gauge (const char *plugin_instance, /* {{{ */
+               const char *type_instance, gauge_t value)
 {
+       value_t v;
+
+       v.gauge = value;
+       swap_submit (plugin_instance, "swap", type_instance, v);
+} /* }}} void swap_submit_gauge */
+
+#if KERNEL_LINUX || HAVE_PERFSTAT
+static void swap_submit_derive (const char *plugin_instance, /* {{{ */
+               const char *type_instance, derive_t value)
+{
+       value_t v;
+
+       v.derive = value;
+       swap_submit (plugin_instance, "swap_io", type_instance, v);
+} /* }}} void swap_submit_derive */
+#endif
+
 #if KERNEL_LINUX
+static int swap_read_separate (void) /* {{{ */
+{
        FILE *fh;
        char buffer[1024];
 
-       char *fields[8];
-       int numfields;
+       fh = fopen ("/proc/swaps", "r");
+       if (fh == NULL)
+       {
+               char errbuf[1024];
+               WARNING ("swap plugin: fopen (/proc/swaps) failed: %s",
+                               sstrerror (errno, errbuf, sizeof (errbuf)));
+               return (-1);
+       }
+
+       while (fgets (buffer, sizeof (buffer), fh) != NULL)
+       {
+               char *fields[8];
+               int numfields;
+               char *endptr;
+
+               char path[PATH_MAX];
+               gauge_t size;
+               gauge_t used;
+               gauge_t free;
+
+               numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
+               if (numfields != 5)
+                       continue;
 
-       _Bool old_kernel=0;
+               sstrncpy (path, fields[0], sizeof (path));
+               escape_slashes (path, sizeof (path));
+
+               errno = 0;
+               endptr = NULL;
+               size = strtod (fields[2], &endptr);
+               if ((endptr == fields[2]) || (errno != 0))
+                       continue;
+
+               errno = 0;
+               endptr = NULL;
+               used = strtod (fields[3], &endptr);
+               if ((endptr == fields[3]) || (errno != 0))
+                       continue;
+
+               if (size < used)
+                       continue;
+
+               free = size - used;
+
+               swap_submit_gauge (path, "used", used);
+               swap_submit_gauge (path, "free", free);
+       }
 
-       derive_t swap_used   = 0;
-       derive_t swap_cached = 0;
-       derive_t swap_free   = 0;
-       derive_t swap_total  = 0;
-       derive_t swap_in     = 0;
-       derive_t swap_out    = 0;
+       fclose (fh);
 
-       if ((fh = fopen ("/proc/meminfo", "r")) == NULL)
+       return (0);
+} /* }}} int swap_read_separate */
+
+static int swap_read_combined (void) /* {{{ */
+{
+       FILE *fh;
+       char buffer[1024];
+
+       uint8_t have_data = 0;
+       gauge_t swap_used   = 0.0;
+       gauge_t swap_cached = 0.0;
+       gauge_t swap_free   = 0.0;
+       gauge_t swap_total  = 0.0;
+
+       fh = fopen ("/proc/meminfo", "r");
+       if (fh == NULL)
        {
                char errbuf[1024];
-               WARNING ("memory: fopen: %s",
+               WARNING ("swap plugin: fopen (/proc/meminfo) failed: %s",
                                sstrerror (errno, errbuf, sizeof (errbuf)));
                return (-1);
        }
 
        while (fgets (buffer, sizeof (buffer), fh) != NULL)
        {
+               char *fields[8];
+               int numfields;
+
                numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
                if (numfields < 2)
                        continue;
 
                if (strcasecmp (fields[0], "SwapTotal:") == 0)
-                       strtoderive (fields[1], &swap_total);
+               {
+                       swap_total = strtod (fields[1], /* endptr = */ NULL);
+                       have_data |= 0x01;
+               }
                else if (strcasecmp (fields[0], "SwapFree:") == 0)
-                       strtoderive (fields[1], &swap_free);
+               {
+                       swap_free = strtod (fields[1], /* endptr = */ NULL);
+                       have_data |= 0x02;
+               }
                else if (strcasecmp (fields[0], "SwapCached:") == 0)
-                       strtoderive (fields[1], &swap_cached);
+               {
+                       swap_cached = strtod (fields[1], /* endptr = */ NULL);
+                       have_data |= 0x04;
+               }
        }
 
-       if (fclose (fh))
-       {
-               char errbuf[1024];
-               WARNING ("memory: fclose: %s",
-                               sstrerror (errno, errbuf, sizeof (errbuf)));
-       }
+       fclose (fh);
 
-       if ((swap_total == 0LL) || ((swap_free + swap_cached) > swap_total))
-               return (-1);
+       if (have_data != 0x07)
+               return (ENOENT);
+
+       if (isnan (swap_total)
+                       || (swap_total <= 0.0)
+                       || ((swap_free + swap_cached) > swap_total))
+               return (EINVAL);
 
        swap_used = swap_total - (swap_free + swap_cached);
 
-       if ((fh = fopen ("/proc/vmstat", "r")) == NULL)
+       swap_submit_gauge (NULL, "used",   1024.0 * swap_used);
+       swap_submit_gauge (NULL, "free",   1024.0 * swap_free);
+       swap_submit_gauge (NULL, "cached", 1024.0 * swap_cached);
+
+       return (0);
+} /* }}} int swap_read_combined */
+
+static int swap_read_io (void) /* {{{ */
+{
+       FILE *fh;
+       char buffer[1024];
+
+       _Bool old_kernel = 0;
+
+       uint8_t have_data = 0;
+       derive_t swap_in  = 0;
+       derive_t swap_out = 0;
+
+       fh = fopen ("/proc/vmstat", "r");
+       if (fh == NULL)
        {
-               // /proc/vmstat does not exist in kernels <2.6
-               if ((fh = fopen ("/proc/stat", "r")) == NULL )
+               /* /proc/vmstat does not exist in kernels <2.6 */
+               fh = fopen ("/proc/stat", "r");
+               if (fh == NULL)
                {
                        char errbuf[1024];
                        WARNING ("swap: fopen: %s",
@@ -253,6 +385,9 @@ static int swap_read (void)
 
        while (fgets (buffer, sizeof (buffer), fh) != NULL)
        {
+               char *fields[8];
+               int numfields;
+
                numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
 
                if (!old_kernel)
@@ -260,10 +395,16 @@ static int swap_read (void)
                        if (numfields != 2)
                                continue;
 
-                       if (strcasecmp ("pswpin", fields[0]) != 0)
+                       if (strcasecmp ("pswpin", fields[0]) == 0)
+                       {
                                strtoderive (fields[1], &swap_in);
+                               have_data |= 0x01;
+                       }
                        else if (strcasecmp ("pswpout", fields[0]) == 0)
+                       {
                                strtoderive (fields[1], &swap_out);
+                               have_data |= 0x02;
+                       }
                }
                else /* if (old_kernel) */
                {
@@ -278,21 +419,49 @@ static int swap_read (void)
                }
        } /* while (fgets) */
 
-       if (fclose (fh))
+       fclose (fh);
+
+       if (have_data != 0x03)
+               return (ENOENT);
+
+       if (report_bytes)
        {
-               char errbuf[1024];
-               WARNING ("swap: fclose: %s",
-                               sstrerror (errno, errbuf, sizeof (errbuf)));
+               swap_in = swap_in * pagesize;
+               swap_out = swap_out * pagesize;
        }
 
-       swap_submit ("used",   1024 * swap_used,   DS_TYPE_GAUGE);
-       swap_submit ("free",   1024 * swap_free,   DS_TYPE_GAUGE);
-       swap_submit ("cached", 1024 * swap_cached, DS_TYPE_GAUGE);
-       swap_submit ("in",  swap_in,  DS_TYPE_DERIVE);
-       swap_submit ("out", swap_out, DS_TYPE_DERIVE);
+       swap_submit_derive (NULL, "in",  swap_in);
+       swap_submit_derive (NULL, "out", swap_out);
+
+       return (0);
+} /* }}} int swap_read_io */
+
+static int swap_read (void) /* {{{ */
+{
+       if (report_by_device)
+               swap_read_separate ();
+       else
+               swap_read_combined ();
+
+       swap_read_io ();
+
+       return (0);
+} /* }}} int swap_read */
 /* #endif KERNEL_LINUX */
 
-#elif HAVE_LIBKSTAT
+/*
+ * Under Solaris, two mechanisms can be used to read swap statistics, swapctl
+ * and kstat. The former reads physical space used on a device, the latter
+ * reports the view from the virtual memory system. It was decided that the
+ * kstat-based information should be moved to the "vmem" plugin, but nobody
+ * with enough Solaris experience was available at that time to do this. The
+ * code below is still there for your reference but it won't be activated in
+ * *this* plugin again. --octo
+ */
+#elif 0 && HAVE_LIBKSTAT
+/* kstat-based read function */
+static int swap_read_kstat (void) /* {{{ */
+{
        derive_t swap_alloc;
        derive_t swap_resv;
        derive_t swap_avail;
@@ -333,15 +502,20 @@ static int swap_read (void)
                        * pagesize);
        swap_avail  = (derive_t) ((ai.ani_max - ai.ani_resv) * pagesize);
 
-       swap_submit ("used", swap_alloc, DS_TYPE_GAUGE);
-       swap_submit ("free", swap_avail, DS_TYPE_GAUGE);
-       swap_submit ("reserved", swap_resv, DS_TYPE_GAUGE);
-/* #endif HAVE_LIBKSTAT */
+       swap_submit_gauge (NULL, "used", swap_alloc);
+       swap_submit_gauge (NULL, "free", swap_avail);
+       swap_submit_gauge (NULL, "reserved", swap_resv);
 
-#elif HAVE_SWAPCTL
- #if HAVE_SWAPCTL_TWO_ARGS
+       return (0);
+} /* }}} int swap_read_kstat */
+/* #endif 0 && HAVE_LIBKSTAT */
+
+#elif HAVE_SWAPCTL && HAVE_SWAPCTL_TWO_ARGS
+/* swapctl-based read function */
+static int swap_read (void) /* {{{ */
+{
         swaptbl_t *s;
-        char strtab[255];
+       char *s_paths;
         int swap_num;
         int status;
         int i;
@@ -359,54 +533,108 @@ static int swap_read (void)
         else if (swap_num == 0)
                 return (0);
 
+       /* Allocate and initialize the swaptbl_t structure */
         s = (swaptbl_t *) smalloc (swap_num * sizeof (swapent_t) + sizeof (struct swaptable));
         if (s == NULL)
         {
                 ERROR ("swap plugin: smalloc failed.");
                 return (-1);
         }
-        /* Initialize string pointers. We have them share the same buffer as we don't care
-        * about the device's name, only its size. This saves memory and alloc/free ops */
-        for (i = 0; i < (swap_num + 1); i++) {
-                s->swt_ent[i].ste_path = strtab;
-        }
-        s->swt_n = swap_num + 1;
+
+       /* Memory to store the path names. We only use these paths when the
+        * separate option has been configured, but it's easier to just
+        * allocate enough memory in any case. */
+       s_paths = calloc (swap_num, PATH_MAX);
+       if (s_paths == NULL)
+       {
+               ERROR ("swap plugin: malloc failed.");
+               sfree (s);
+               return (-1);
+       }
+        for (i = 0; i < swap_num; i++)
+               s->swt_ent[i].ste_path = s_paths + (i * PATH_MAX);
+        s->swt_n = swap_num;
+
         status = swapctl (SC_LIST, s);
-        if (status != swap_num)
+        if (status < 0)
         {
-                ERROR ("swap plugin: swapctl (SC_LIST) failed with status %i.",
-                                status);
+               char errbuf[1024];
+                ERROR ("swap plugin: swapctl (SC_LIST) failed: %s",
+                               sstrerror (errno, errbuf, sizeof (errbuf)));
+               sfree (s_paths);
                 sfree (s);
                 return (-1);
         }
+       else if (swap_num < status)
+       {
+               /* more elements returned than requested */
+               ERROR ("swap plugin: I allocated memory for %i structure%s, "
+                               "but swapctl(2) claims to have returned %i. "
+                               "I'm confused and will give up.",
+                               swap_num, (swap_num == 1) ? "" : "s",
+                               status);
+               sfree (s_paths);
+                sfree (s);
+                return (-1);
+       }
+       else if (swap_num > status)
+               /* less elements returned than requested */
+               swap_num = status;
 
         for (i = 0; i < swap_num; i++)
         {
+               char path[PATH_MAX];
+               derive_t this_total;
+               derive_t this_avail;
+
                 if ((s->swt_ent[i].ste_flags & ST_INDEL) != 0)
                         continue;
 
-                avail += ((derive_t) s->swt_ent[i].ste_free)
-                         * pagesize;
-                total += ((derive_t) s->swt_ent[i].ste_pages)
-                         * pagesize;
-        }
+               this_total = ((derive_t) s->swt_ent[i].ste_pages) * pagesize;
+               this_avail = ((derive_t) s->swt_ent[i].ste_free)  * pagesize;
+
+               /* Shortcut for the "combined" setting (default) */
+               if (!report_by_device)
+               {
+                       avail += this_avail;
+                       total += this_total;
+                       continue;
+               }
+
+               sstrncpy (path, s->swt_ent[i].ste_path, sizeof (path));
+               escape_slashes (path, sizeof (path));
+
+               swap_submit_gauge (path, "used", (gauge_t) (this_total - this_avail));
+               swap_submit_gauge (path, "free", (gauge_t) this_avail);
+        } /* for (swap_num) */
 
         if (total < avail)
         {
                 ERROR ("swap plugin: Total swap space (%"PRIi64") "
                                 "is less than free swap space (%"PRIi64").",
                                 total, avail);
+               sfree (s_paths);
                 sfree (s);
                 return (-1);
         }
 
-        swap_submit ("used", total - avail, DS_TYPE_GAUGE);
-        swap_submit ("free", avail, DS_TYPE_GAUGE);
+       /* If the "separate" option was specified (report_by_device == 2), all
+        * values have already been dispatched from within the loop. */
+       if (!report_by_device)
+       {
+               swap_submit_gauge (NULL, "used", (gauge_t) (total - avail));
+               swap_submit_gauge (NULL, "free", (gauge_t) avail);
+       }
 
+       sfree (s_paths);
         sfree (s);
- /* #endif HAVE_SWAPCTL_TWO_ARGS */
- #elif HAVE_SWAPCTL_THREE_ARGS
+       return (0);
+} /* }}} int swap_read */
+/* #endif HAVE_SWAPCTL && HAVE_SWAPCTL_TWO_ARGS */
 
+#elif HAVE_SWAPCTL && HAVE_SWAPCTL_THREE_ARGS
+static int swap_read (void) /* {{{ */
+{
        struct swapent *swap_entries;
        int swap_num;
        int status;
@@ -466,14 +694,18 @@ static int swap_read (void)
                return (-1);
        }
 
-       swap_submit ("used", used, DS_TYPE_GAUGE);
-       swap_submit ("free", total - used, DS_TYPE_GAUGE);
+       swap_submit_gauge (NULL, "used", (gauge_t) used);
+       swap_submit_gauge (NULL, "free", (gauge_t) (total - used));
 
        sfree (swap_entries);
- #endif /* HAVE_SWAPCTL_THREE_ARGS */
-/* #endif HAVE_SWAPCTL */
+
+       return (0);
+} /* }}} int swap_read */
+/* #endif HAVE_SWAPCTL && HAVE_SWAPCTL_THREE_ARGS */
 
 #elif defined(VM_SWAPUSAGE)
+static int swap_read (void) /* {{{ */
+{
        int              mib[3];
        size_t           mib_len;
        struct xsw_usage sw_usage;
@@ -489,11 +721,16 @@ static int swap_read (void)
                return (-1);
 
        /* The returned values are bytes. */
-       swap_submit ("used", (derive_t) sw_usage.xsu_used, DS_TYPE_GAUGE);
-       swap_submit ("free", (derive_t) sw_usage.xsu_avail, DS_TYPE_GAUGE);
+       swap_submit_gauge (NULL, "used", (gauge_t) sw_usage.xsu_used);
+       swap_submit_gauge (NULL, "free", (gauge_t) sw_usage.xsu_avail);
+
+       return (0);
+} /* }}} int swap_read */
 /* #endif VM_SWAPUSAGE */
 
 #elif HAVE_LIBKVM_GETSWAPINFO
+static int swap_read (void) /* {{{ */
+{
        struct kvm_swap data_s;
        int             status;
 
@@ -517,11 +754,16 @@ static int swap_read (void)
 
        free = total - used;
 
-       swap_submit ("used", used, DS_TYPE_GAUGE);
-       swap_submit ("free", free, DS_TYPE_GAUGE);
+       swap_submit_gauge (NULL, "used", (gauge_t) used);
+       swap_submit_gauge (NULL, "free", (gauge_t) free);
+
+       return (0);
+} /* }}} int swap_read */
 /* #endif HAVE_LIBKVM_GETSWAPINFO */
 
 #elif HAVE_LIBSTATGRAB
+static int swap_read (void) /* {{{ */
+{
        sg_swap_stats *swap;
 
        swap = sg_get_swap_stats ();
@@ -529,11 +771,16 @@ static int swap_read (void)
        if (swap == NULL)
                return (-1);
 
-       swap_submit ("used", (derive_t) swap->used, DS_TYPE_GAUGE);
-       swap_submit ("free", (derive_t) swap->free, DS_TYPE_GAUGE);
+       swap_submit_gauge (NULL, "used", (gauge_t) swap->used);
+       swap_submit_gauge (NULL, "free", (gauge_t) swap->free);
+
+       return (0);
+} /* }}} int swap_read */
 /* #endif  HAVE_LIBSTATGRAB */
 
 #elif HAVE_PERFSTAT
+static int swap_read (void) /* {{{ */
+{
         if(perfstat_memory_total(NULL, &pmemory, sizeof(perfstat_memory_total_t), 1) < 0)
        {
                 char errbuf[1024];
@@ -541,15 +788,23 @@ static int swap_read (void)
                         sstrerror (errno, errbuf, sizeof (errbuf)));
                 return (-1);
         }
-       swap_submit ("used", (derive_t) (pmemory.pgsp_total - pmemory.pgsp_free) * pagesize, DS_TYPE_GAUGE);
-       swap_submit ("free", (derive_t) pmemory.pgsp_free * pagesize , DS_TYPE_GAUGE);
-#endif /* HAVE_PERFSTAT */
+
+       swap_submit_gauge (NULL, "used", (gauge_t) (pmemory.pgsp_total - pmemory.pgsp_free) * pagesize);
+       swap_submit_gauge (NULL, "free", (gauge_t) pmemory.pgsp_free * pagesize );
+       swap_submit_gauge (NULL, "reserved", (gauge_t) pmemory.pgsp_rsvd * pagesize);
+       swap_submit_derive (NULL, "in",  (derive_t) pmemory.pgspins * pagesize);
+       swap_submit_derive (NULL, "out", (derive_t) pmemory.pgspouts * pagesize);
 
        return (0);
-} /* int swap_read */
+} /* }}} int swap_read */
+#endif /* HAVE_PERFSTAT */
 
 void module_register (void)
 {
+       plugin_register_config ("swap", swap_config,
+                       config_keys, config_keys_num);
        plugin_register_init ("swap", swap_init);
        plugin_register_read ("swap", swap_read);
 } /* void module_register */
+
+/* vim: set fdm=marker : */
index ace9dc6..4f5d0c4 100644 (file)
@@ -33,10 +33,12 @@ static int log_level = LOG_DEBUG;
 #else
 static int log_level = LOG_INFO;
 #endif /* COLLECT_DEBUG */
+static int notif_severity = 0;
 
 static const char *config_keys[] =
 {
-       "LogLevel"
+       "LogLevel",
+       "NotifyLevel",
 };
 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
 
@@ -44,26 +46,16 @@ static int sl_config (const char *key, const char *value)
 {
        if (strcasecmp (key, "LogLevel") == 0)
        {
-               if ((strcasecmp (value, "emerg") == 0)
-                               || (strcasecmp (value, "alert") == 0)
-                               || (strcasecmp (value, "crit") == 0)
-                               || (strcasecmp (value, "err") == 0))
-                       log_level = LOG_ERR;
-               else if (strcasecmp (value, "warning") == 0)
-                       log_level = LOG_WARNING;
-               else if (strcasecmp (value, "notice") == 0)
-                       log_level = LOG_NOTICE;
-               else if (strcasecmp (value, "info") == 0)
-                       log_level = LOG_INFO;
-#if COLLECT_DEBUG
-               else if (strcasecmp (value, "debug") == 0)
-                       log_level = LOG_DEBUG;
-#endif
-               else
+               log_level = parse_log_severity (value);
+               if (log_level < 0)
+                       return (1);
+       }
+       else if (strcasecmp (key, "NotifyLevel") == 0)
+       {
+               notif_severity = parse_notif_severity (value);
+               if (notif_severity < 0)
                        return (1);
        }
-       else
-               return (-1);
 
        return (0);
 } /* int sl_config */
@@ -84,11 +76,77 @@ static int sl_shutdown (void)
        return (0);
 }
 
+static int sl_notification (const notification_t *n,
+               user_data_t __attribute__((unused)) *user_data)
+{
+       char  buf[1024] = "";
+       size_t offset = 0;
+       int log_severity;
+       char *severity_string;
+       int status;
+
+       if (n->severity > notif_severity)
+               return (0);
+
+       switch (n->severity)
+       {
+               case NOTIF_FAILURE:
+                       severity_string = "FAILURE";
+                       log_severity = LOG_ERR;
+                       break;
+               case NOTIF_WARNING:
+                       severity_string = "WARNING";
+                       log_severity = LOG_WARNING;
+                       break;
+               case NOTIF_OKAY:
+                       severity_string = "OKAY";
+                       log_severity = LOG_NOTICE;
+                       break;
+               default:
+                       severity_string = "UNKNOWN";
+                       log_severity = LOG_ERR;
+       }
+
+#define BUFFER_ADD(...) do { \
+       status = ssnprintf (&buf[offset], sizeof (buf) - offset, \
+                       __VA_ARGS__); \
+       if (status < 1) \
+               return (-1); \
+       else if (((size_t) status) >= (sizeof (buf) - offset)) \
+               return (-ENOMEM); \
+       else \
+               offset += ((size_t) status); \
+} while (0)
+
+#define BUFFER_ADD_FIELD(field) do { \
+       if (n->field[0]) \
+               BUFFER_ADD (", " #field " = %s", n->field); \
+} while (0)
+
+       BUFFER_ADD ("Notification: severity = %s", severity_string);
+       BUFFER_ADD_FIELD (host);
+       BUFFER_ADD_FIELD (plugin);
+       BUFFER_ADD_FIELD (plugin_instance);
+       BUFFER_ADD_FIELD (type);
+       BUFFER_ADD_FIELD (type_instance);
+       BUFFER_ADD_FIELD (message);
+
+#undef BUFFER_ADD_FIELD
+#undef BUFFER_ADD
+
+       buf[sizeof (buf) - 1] = '\0';
+
+       sl_log (log_severity, buf, NULL);
+
+       return (0);
+} /* int sl_notification */
+
 void module_register (void)
 {
        openlog ("collectd", LOG_CONS | LOG_PID, LOG_DAEMON);
 
        plugin_register_config ("syslog", sl_config, config_keys, config_keys_num);
        plugin_register_log ("syslog", sl_log, /* user_data = */ NULL);
+       plugin_register_notification ("syslog", sl_notification, NULL);
        plugin_register_shutdown ("syslog", sl_shutdown);
 } /* void module_register(void) */
index 32b4296..a8e7dc4 100644 (file)
@@ -58,13 +58,13 @@ static int tape_init (void)
 
 static void tape_submit (const char *plugin_instance,
                const char *type,
-               counter_t read, counter_t write)
+               derive_t read, derive_t write)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = read;
-       values[1].counter = write;
+       values[0].derive = read;
+       values[1].derive = write;
 
        vl.values = values;
        vl.values_len = 2;
index 96598af..cb68048 100644 (file)
@@ -209,7 +209,7 @@ static int tn_invoke (const data_set_t *ds, value_list_t *vl, /* {{{ */
   /* Initialize the structure. */
   memset (&n, 0, sizeof (n));
   n.severity = data->severity;
-  n.time = time (NULL);
+  n.time = cdtime ();
   sstrncpy (n.message, data->message, sizeof (n.message));
   sstrncpy (n.host, vl->host, sizeof (n.host));
   sstrncpy (n.plugin, vl->plugin, sizeof (n.plugin));
index 29fecdf..bef03e5 100644 (file)
@@ -29,6 +29,9 @@ struct ts_data_s
 {
        double factor;
        double offset;
+
+       char **data_sources;
+       size_t data_sources_num;
 };
 typedef struct ts_data_s ts_data_t;
 
@@ -96,7 +99,7 @@ static int ts_invoke_counter (const data_set_t *ds, value_list_t *vl, /* {{{ */
                {
                        difference = curr_counter - prev_counter;
                }
-               rate = ((double) difference) / ((double) vl->interval);
+               rate = ((double) difference) / CDTIME_T_TO_DOUBLE (vl->interval);
 
                /* Modify the rate. */
                if (!isnan (data->factor))
@@ -105,7 +108,7 @@ static int ts_invoke_counter (const data_set_t *ds, value_list_t *vl, /* {{{ */
                        rate += data->offset;
 
                /* Calculate the internal counter. */
-               int_fraction += (rate * ((double) vl->interval));
+               int_fraction += (rate * CDTIME_T_TO_DOUBLE (vl->interval));
                difference = (uint64_t) int_fraction;
                int_fraction -= ((double) difference);
                int_counter  += difference;
@@ -199,7 +202,7 @@ static int ts_invoke_derive (const data_set_t *ds, value_list_t *vl, /* {{{ */
 
                /* Calcualte the rate */
                difference = curr_derive - prev_derive;
-               rate = ((double) difference) / ((double) vl->interval);
+               rate = ((double) difference) / CDTIME_T_TO_DOUBLE (vl->interval);
 
                /* Modify the rate. */
                if (!isnan (data->factor))
@@ -208,7 +211,7 @@ static int ts_invoke_derive (const data_set_t *ds, value_list_t *vl, /* {{{ */
                        rate += data->offset;
 
                /* Calculate the internal derive. */
-               int_fraction += (rate * ((double) vl->interval));
+               int_fraction += (rate * CDTIME_T_TO_DOUBLE (vl->interval));
                if (int_fraction < 0.0) /* handle negative integer rounding correctly */
                        difference = ((int64_t) int_fraction) - 1;
                else
@@ -263,7 +266,7 @@ static int ts_invoke_absolute (const data_set_t *ds, value_list_t *vl, /* {{{ */
        if (status != 0)
                int_fraction = 0.0;
 
-       rate = ((double) curr_absolute) / ((double) vl->interval);
+       rate = ((double) curr_absolute) / CDTIME_T_TO_DOUBLE (vl->interval);
 
        /* Modify the rate. */
        if (!isnan (data->factor))
@@ -272,7 +275,7 @@ static int ts_invoke_absolute (const data_set_t *ds, value_list_t *vl, /* {{{ */
                rate += data->offset;
 
        /* Calculate the new absolute. */
-       int_fraction += (rate * ((double) vl->interval));
+       int_fraction += (rate * CDTIME_T_TO_DOUBLE (vl->interval));
        curr_absolute = (uint64_t) int_fraction;
        int_fraction -= ((double) curr_absolute);
 
@@ -300,17 +303,86 @@ static int ts_config_set_double (double *ret, oconfig_item_t *ci) /* {{{ */
        return (0);
 } /* }}} int ts_config_set_double */
 
+static int ts_config_add_data_source(ts_data_t *data, /* {{{ */
+               oconfig_item_t *ci)
+{
+       size_t new_data_sources_num;
+       char **temp;
+       int i;
+
+       /* Check number of arbuments. */
+       if (ci->values_num < 1)
+       {
+               ERROR ("`value' match: `%s' needs at least one argument.",
+                               ci->key);
+               return (-1);
+       }
+
+       /* Check type of arguments */
+       for (i = 0; i < ci->values_num; i++)
+       {
+               if (ci->values[i].type == OCONFIG_TYPE_STRING)
+                       continue;
+
+               ERROR ("`value' match: `%s' accepts only string arguments "
+                               "(argument %i is a %s).",
+                               ci->key, i + 1,
+                               (ci->values[i].type == OCONFIG_TYPE_BOOLEAN)
+                               ? "truth value" : "number");
+               return (-1);
+       }
+
+       /* Allocate space for the char pointers */
+       new_data_sources_num = data->data_sources_num + ((size_t) ci->values_num);
+       temp = (char **) realloc (data->data_sources,
+                       new_data_sources_num * sizeof (char *));
+       if (temp == NULL)
+       {
+               ERROR ("`value' match: realloc failed.");
+               return (-1);
+       }
+       data->data_sources = temp;
+
+       /* Copy the strings, allocating memory as needed.  */
+       for (i = 0; i < ci->values_num; i++)
+       {
+               size_t j;
+
+               /* If we get here, there better be memory for us to write to.  */
+               assert (data->data_sources_num < new_data_sources_num);
+
+               j = data->data_sources_num;
+               data->data_sources[j] = sstrdup (ci->values[i].value.string);
+               if (data->data_sources[j] == NULL)
+               {
+                       ERROR ("`value' match: sstrdup failed.");
+                       continue;
+               }
+               data->data_sources_num++;
+       }
+
+       return (0);
+} /* }}} int ts_config_add_data_source */
+
 static int ts_destroy (void **user_data) /* {{{ */
 {
-       ts_data_t **data;
+       ts_data_t *data;
 
        if (user_data == NULL)
                return (-EINVAL);
 
-       data = (ts_data_t **) user_data;
+       data = (ts_data_t *) *user_data;
 
-       free (*data);
-       *data = NULL;
+       if ((data != NULL) && (data->data_sources != NULL))
+       {
+               size_t i;
+               for (i = 0; i < data->data_sources_num; i++)
+                       sfree (data->data_sources[i]);
+               sfree (data->data_sources);
+       }
+
+       sfree (data);
+       *user_data = NULL;
 
        return (0);
 } /* }}} int ts_destroy */
@@ -341,6 +413,8 @@ static int ts_create (const oconfig_item_t *ci, void **user_data) /* {{{ */
                                status = ts_config_set_double (&data->factor, child);
                else if (strcasecmp ("Offset", child->key) == 0)
                                status = ts_config_set_double (&data->offset, child);
+               else if (strcasecmp ("DataSource", child->key) == 0)
+                               status = ts_config_add_data_source(data, child);
                else
                {
                        ERROR ("Target `scale': The `%s' configuration option is not understood "
@@ -393,6 +467,18 @@ static int ts_invoke (const data_set_t *ds, value_list_t *vl, /* {{{ */
 
        for (i = 0; i < ds->ds_num; i++)
        {
+               /* If we've got a list of data sources, is it in the list? */
+               if (data->data_sources) {
+                       size_t j;
+                       for (j = 0; j < data->data_sources_num; j++)
+                               if (strcasecmp(ds->ds[i].name, data->data_sources[j]) == 0)
+                                       break;
+
+                       /* No match, ignore */
+                       if (j >= data->data_sources_num)
+                               continue;
+               }
+
                if (ds->ds[i].type == DS_TYPE_COUNTER)
                        ts_invoke_counter (ds, vl, data, i);
                else if (ds->ds[i].type == DS_TYPE_GAUGE)
index 7fc0d42..25f4637 100644 (file)
@@ -210,6 +210,213 @@ static int v5_mysql_threads (const data_set_t *ds, value_list_t *vl) /* {{{ */
   return (FC_TARGET_STOP);
 } /* }}} int v5_mysql_threads */
 
+/*
+ * ZFS ARC hit and miss counters
+ *
+ * 4.* uses the flawed "arc_counts" type. In 5.* this has been replaced by the
+ * more generic "cache_result" type.
+ */
+static int v5_zfs_arc_counts (const data_set_t *ds, value_list_t *vl) /* {{{ */
+{
+  value_list_t new_vl;
+  value_t new_value;
+  _Bool is_hits;
+
+  if (vl->values_len != 4)
+    return (FC_TARGET_STOP);
+
+  if (strcmp ("hits", vl->type_instance) == 0)
+    is_hits = 1;
+  else if (strcmp ("misses", vl->type_instance) == 0)
+    is_hits = 0;
+  else
+    return (FC_TARGET_STOP);
+
+  /* Copy everything: Time, interval, host, ... */
+  memcpy (&new_vl, vl, sizeof (new_vl));
+
+  /* Reset data we can't simply copy */
+  new_vl.values = &new_value;
+  new_vl.values_len = 1;
+  new_vl.meta = NULL;
+
+  /* Change the type to "cache_result" */
+  sstrncpy (new_vl.type, "cache_result", sizeof (new_vl.type));
+
+  /* Dispatch new value lists instead of this one */
+  new_vl.values[0].derive = (derive_t) vl->values[0].counter;
+  ssnprintf (new_vl.type_instance, sizeof (new_vl.type_instance),
+      "demand_data-%s",
+      is_hits ? "hit" : "miss");
+  plugin_dispatch_values (&new_vl);
+
+  new_vl.values[0].derive = (derive_t) vl->values[1].counter;
+  ssnprintf (new_vl.type_instance, sizeof (new_vl.type_instance),
+      "demand_metadata-%s",
+      is_hits ? "hit" : "miss");
+  plugin_dispatch_values (&new_vl);
+
+  new_vl.values[0].derive = (derive_t) vl->values[2].counter;
+  ssnprintf (new_vl.type_instance, sizeof (new_vl.type_instance),
+      "prefetch_data-%s",
+      is_hits ? "hit" : "miss");
+  plugin_dispatch_values (&new_vl);
+
+  new_vl.values[0].derive = (derive_t) vl->values[3].counter;
+  ssnprintf (new_vl.type_instance, sizeof (new_vl.type_instance),
+      "prefetch_metadata-%s",
+      is_hits ? "hit" : "miss");
+  plugin_dispatch_values (&new_vl);
+
+  /* Abort processing */
+  return (FC_TARGET_STOP);
+} /* }}} int v5_zfs_arc_counts */
+
+/*
+ * ZFS ARC L2 bytes
+ *
+ * "arc_l2_bytes" -> "io_octets-L2".
+ */
+static int v5_zfs_arc_l2_bytes (const data_set_t *ds, value_list_t *vl) /* {{{ */
+{
+  value_list_t new_vl;
+  value_t new_values[2];
+
+  if (vl->values_len != 2)
+    return (FC_TARGET_STOP);
+
+  /* Copy everything: Time, interval, host, ... */
+  memcpy (&new_vl, vl, sizeof (new_vl));
+
+  /* Reset data we can't simply copy */
+  new_vl.values = new_values;
+  new_vl.values_len = 2;
+  new_vl.meta = NULL;
+
+  /* Change the type/-instance to "io_octets-L2" */
+  sstrncpy (new_vl.type, "io_octets", sizeof (new_vl.type));
+  sstrncpy (new_vl.type_instance, "L2", sizeof (new_vl.type_instance));
+
+  /* Copy the actual values. */
+  new_vl.values[0].derive = (derive_t) vl->values[0].counter;
+  new_vl.values[1].derive = (derive_t) vl->values[1].counter;
+
+  /* Dispatch new value lists instead of this one */
+  plugin_dispatch_values (&new_vl);
+
+  /* Abort processing */
+  return (FC_TARGET_STOP);
+} /* }}} int v5_zfs_arc_l2_bytes */
+
+/*
+ * ZFS ARC L2 cache size
+ *
+ * 4.* uses a separate type for this. 5.* uses the generic "cache_size" type
+ * instead.
+ */
+static int v5_zfs_arc_l2_size (const data_set_t *ds, value_list_t *vl) /* {{{ */
+{
+  value_list_t new_vl;
+  value_t new_value;
+
+  if (vl->values_len != 1)
+    return (FC_TARGET_STOP);
+
+  /* Copy everything: Time, interval, host, ... */
+  memcpy (&new_vl, vl, sizeof (new_vl));
+
+  /* Reset data we can't simply copy */
+  new_vl.values = &new_value;
+  new_vl.values_len = 1;
+  new_vl.meta = NULL;
+
+  new_vl.values[0].gauge = (gauge_t) vl->values[0].gauge;
+
+  /* Change the type to "cache_size" */
+  sstrncpy (new_vl.type, "cache_size", sizeof (new_vl.type));
+
+  /* Adapt the type instance */
+  sstrncpy (new_vl.type_instance, "L2", sizeof (new_vl.type_instance));
+
+  /* Dispatch new value lists instead of this one */
+  plugin_dispatch_values (&new_vl);
+
+  /* Abort processing */
+  return (FC_TARGET_STOP);
+} /* }}} int v5_zfs_arc_l2_size */
+
+/*
+ * ZFS ARC ratio
+ *
+ * "arc_ratio-L1" -> "cache_ratio-arc"
+ * "arc_ratio-L2" -> "cache_ratio-L2"
+ */
+static int v5_zfs_arc_ratio (const data_set_t *ds, value_list_t *vl) /* {{{ */
+{
+  value_list_t new_vl;
+  value_t new_value;
+
+  if (vl->values_len != 1)
+    return (FC_TARGET_STOP);
+
+  /* Copy everything: Time, interval, host, ... */
+  memcpy (&new_vl, vl, sizeof (new_vl));
+
+  /* Reset data we can't simply copy */
+  new_vl.values = &new_value;
+  new_vl.values_len = 1;
+  new_vl.meta = NULL;
+
+  new_vl.values[0].gauge = (gauge_t) vl->values[0].gauge;
+
+  /* Change the type to "cache_ratio" */
+  sstrncpy (new_vl.type, "cache_ratio", sizeof (new_vl.type));
+
+  /* Adapt the type instance */
+  if (strcmp ("L1", vl->type_instance) == 0)
+    sstrncpy (new_vl.type_instance, "arc", sizeof (new_vl.type_instance));
+
+  /* Dispatch new value lists instead of this one */
+  plugin_dispatch_values (&new_vl);
+
+  /* Abort processing */
+  return (FC_TARGET_STOP);
+} /* }}} int v5_zfs_arc_ratio */
+
+/*
+ * ZFS ARC size
+ *
+ * 4.* uses the "arc_size" type with four data sources. In 5.* this has been
+ * replaces with the "cache_size" type and static data has been removed.
+ */
+static int v5_zfs_arc_size (const data_set_t *ds, value_list_t *vl) /* {{{ */
+{
+  value_list_t new_vl;
+  value_t new_value;
+
+  if (vl->values_len != 4)
+    return (FC_TARGET_STOP);
+
+  /* Copy everything: Time, interval, host, ... */
+  memcpy (&new_vl, vl, sizeof (new_vl));
+
+  /* Reset data we can't simply copy */
+  new_vl.values = &new_value;
+  new_vl.values_len = 1;
+  new_vl.meta = NULL;
+
+  /* Change the type to "cache_size" */
+  sstrncpy (new_vl.type, "cache_size", sizeof (new_vl.type));
+
+  /* Dispatch new value lists instead of this one */
+  new_vl.values[0].derive = (derive_t) vl->values[0].counter;
+  sstrncpy (new_vl.type_instance, "arc", sizeof (new_vl.type_instance));
+  plugin_dispatch_values (&new_vl);
+
+  /* Abort processing */
+  return (FC_TARGET_STOP);
+} /* }}} int v5_zfs_arc_size */
+
 static int v5_destroy (void **user_data) /* {{{ */
 {
   return (0);
@@ -236,6 +443,16 @@ static int v5_invoke (const data_set_t *ds, value_list_t *vl, /* {{{ */
     return (v5_mysql_qcache (ds, vl));
   else if (strcmp ("mysql_threads", vl->type) == 0)
     return (v5_mysql_threads (ds, vl));
+  else if (strcmp ("arc_counts", vl->type) == 0)
+    return (v5_zfs_arc_counts (ds, vl));
+  else if (strcmp ("arc_l2_bytes", vl->type) == 0)
+    return (v5_zfs_arc_l2_bytes (ds, vl));
+  else if (strcmp ("arc_l2_size", vl->type) == 0)
+    return (v5_zfs_arc_l2_size (ds, vl));
+  else if (strcmp ("arc_ratio", vl->type) == 0)
+    return (v5_zfs_arc_ratio (ds, vl));
+  else if (strcmp ("arc_size", vl->type) == 0)
+    return (v5_zfs_arc_size (ds, vl));
 
   return (FC_TARGET_CONTINUE);
 } /* }}} int v5_invoke */
index d68cd09..765b892 100644 (file)
 #undef HAVE_SYSCTLBYNAME /* force HAVE_LIBKVM_NLIST path */
 #endif
 
-#if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_LIBKVM_NLIST
+#if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_LIBKVM_NLIST && !KERNEL_AIX
 # error "No applicable input method."
 #endif
 
 #if KERNEL_LINUX
+# include <asm/types.h>
+/* sys/socket.h is necessary to compile when using netlink on older systems. */
+# include <sys/socket.h>
+# include <linux/netlink.h>
+# include <linux/inet_diag.h>
+# include <sys/socket.h>
+# include <arpa/inet.h>
 /* #endif KERNEL_LINUX */
 
 #elif HAVE_SYSCTLBYNAME
 # include <netinet/tcp_var.h>
 # include <netdb.h>
 # include <arpa/inet.h>
-# include <nlist.h>
+# if !defined(HAVE_BSD_NLIST_H) || !HAVE_BSD_NLIST_H
+#  include <nlist.h>
+# else /* HAVE_BSD_NLIST_H */
+#  include <bsd/nlist.h>
+# endif
 # include <kvm.h>
-#endif /* HAVE_LIBKVM_NLIST */
+/* #endif HAVE_LIBKVM_NLIST */
+
+#elif KERNEL_AIX
+# include <arpa/inet.h>
+# include <sys/socketvar.h>
+#endif /* KERNEL_AIX */
 
 #if KERNEL_LINUX
+struct nlreq {
+  struct nlmsghdr nlh;
+  struct inet_diag_req r;
+};
+
 static const char *tcp_state[] =
 {
   "", /* 0 */
@@ -186,7 +207,49 @@ struct inpcbtable *inpcbtable_ptr = NULL;
 # define TCP_STATE_LISTEN 1
 # define TCP_STATE_MIN 1
 # define TCP_STATE_MAX 10
-#endif /* HAVE_LIBKVM_NLIST */
+/* #endif HAVE_LIBKVM_NLIST */
+
+#elif KERNEL_AIX
+static const char *tcp_state[] =
+{
+  "CLOSED",
+  "LISTEN",
+  "SYN_SENT",
+  "SYN_RCVD",
+  "ESTABLISHED",
+  "CLOSE_WAIT",
+  "FIN_WAIT_1",
+  "CLOSING",
+  "LAST_ACK",
+  "FIN_WAIT_2",
+  "TIME_WAIT"
+};
+
+# define TCP_STATE_LISTEN 1
+# define TCP_STATE_MIN 0
+# define TCP_STATE_MAX 10
+
+struct netinfo_conn {
+  uint32_t unknow1[2];
+  uint16_t dstport;
+  uint16_t unknow2;
+  struct in6_addr dstaddr;
+  uint16_t srcport;
+  uint16_t unknow3;
+  struct in6_addr srcaddr;
+  uint32_t unknow4[36];
+  uint16_t tcp_state;
+  uint16_t unknow5[7];
+};
+
+struct netinfo_header {
+  unsigned int proto;
+  unsigned int size;
+};
+
+# define NETINFO_TCP 3
+extern int netinfo (int proto, void *data, int *size,  int n);
+#endif /* KERNEL_AIX */
 
 #define PORT_COLLECT_LOCAL  0x01
 #define PORT_COLLECT_REMOTE 0x02
@@ -212,6 +275,17 @@ static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
 static int port_collect_listening = 0;
 static port_entry_t *port_list_head = NULL;
 
+#if KERNEL_LINUX
+static uint32_t sequence_number = 0;
+
+enum
+{
+  SRC_DUNNO,
+  SRC_NETLINK,
+  SRC_PROC
+} linux_source = SRC_DUNNO;
+#endif
+
 static void conn_submit_port_entry (port_entry_t *pe)
 {
   value_t values[1];
@@ -368,6 +442,140 @@ static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t
 } /* int conn_handle_ports */
 
 #if KERNEL_LINUX
+/* Returns zero on success, less than zero on socket error and greater than
+ * zero on other errors. */
+static int conn_read_netlink (void)
+{
+  int fd;
+  struct sockaddr_nl nladdr;
+  struct nlreq req;
+  struct msghdr msg;
+  struct iovec iov;
+  struct inet_diag_msg *r;
+  char buf[8192];
+
+  /* If this fails, it's likely a permission problem. We'll fall back to
+   * reading this information from files below. */
+  fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG);
+  if (fd < 0)
+  {
+    ERROR ("tcpconns plugin: conn_read_netlink: socket(AF_NETLINK, SOCK_RAW, "
+       "NETLINK_INET_DIAG) failed: %s",
+       sstrerror (errno, buf, sizeof (buf)));
+    return (-1);
+  }
+
+  memset(&nladdr, 0, sizeof(nladdr));
+  nladdr.nl_family = AF_NETLINK;
+
+  memset(&req, 0, sizeof(req));
+  req.nlh.nlmsg_len = sizeof(req);
+  req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
+  /* NLM_F_ROOT: return the complete table instead of a single entry.
+   * NLM_F_MATCH: return all entries matching criteria (not implemented)
+   * NLM_F_REQUEST: must be set on all request messages */
+  req.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;
+  req.nlh.nlmsg_pid = 0;
+  /* The sequence_number is used to track our messages. Since netlink is not
+   * reliable, we don't want to end up with a corrupt or incomplete old
+   * message in case the system is/was out of memory. */
+  req.nlh.nlmsg_seq = ++sequence_number;
+  req.r.idiag_family = AF_INET;
+  req.r.idiag_states = 0xfff;
+  req.r.idiag_ext = 0;
+
+  memset(&iov, 0, sizeof(iov));
+  iov.iov_base = &req;
+  iov.iov_len = sizeof(req);
+
+  memset(&msg, 0, sizeof(msg));
+  msg.msg_name = (void*)&nladdr;
+  msg.msg_namelen = sizeof(nladdr);
+  msg.msg_iov = &iov;
+  msg.msg_iovlen = 1;
+
+  if (sendmsg (fd, &msg, 0) < 0)
+  {
+    ERROR ("tcpconns plugin: conn_read_netlink: sendmsg(2) failed: %s",
+       sstrerror (errno, buf, sizeof (buf)));
+    close (fd);
+    return (-1);
+  }
+
+  iov.iov_base = buf;
+  iov.iov_len = sizeof(buf);
+
+  while (1)
+  {
+    int status;
+    struct nlmsghdr *h;
+
+    memset(&msg, 0, sizeof(msg));
+    msg.msg_name = (void*)&nladdr;
+    msg.msg_namelen = sizeof(nladdr);
+    msg.msg_iov = &iov;
+    msg.msg_iovlen = 1;
+
+    status = recvmsg(fd, (void *) &msg, /* flags = */ 0);
+    if (status < 0)
+    {
+      if ((errno == EINTR) || (errno == EAGAIN))
+        continue;
+
+      ERROR ("tcpconns plugin: conn_read_netlink: recvmsg(2) failed: %s",
+         sstrerror (errno, buf, sizeof (buf)));
+      close (fd);
+      return (-1);
+    }
+    else if (status == 0)
+    {
+      close (fd);
+      DEBUG ("tcpconns plugin: conn_read_netlink: Unexpected zero-sized "
+         "reply from netlink socket.");
+      return (0);
+    }
+
+    h = (struct nlmsghdr*)buf;
+    while (NLMSG_OK(h, status))
+    {
+      if (h->nlmsg_seq != sequence_number)
+      {
+       h = NLMSG_NEXT(h, status);
+       continue;
+      }
+
+      if (h->nlmsg_type == NLMSG_DONE)
+      {
+       close (fd);
+       return (0);
+      }
+      else if (h->nlmsg_type == NLMSG_ERROR)
+      {
+       struct nlmsgerr *msg_error;
+
+       msg_error = NLMSG_DATA(h);
+       WARNING ("tcpconns plugin: conn_read_netlink: Received error %i.",
+           msg_error->error);
+
+       close (fd);
+       return (1);
+      }
+
+      r = NLMSG_DATA(h);
+
+      /* This code does not (need to) distinguish between IPv4 and IPv6. */
+      conn_handle_ports (ntohs(r->id.idiag_sport),
+         ntohs(r->id.idiag_dport),
+         r->idiag_state);
+
+      h = NLMSG_NEXT(h, status);
+    } /* while (NLMSG_OK) */
+  } /* while (1) */
+
+  /* Not reached because the while() loop above handles the exit condition. */
+  return (0);
+} /* int conn_read_netlink */
+
 static int conn_handle_line (char *buffer)
 {
   char *fields[32];
@@ -502,26 +710,55 @@ static int conn_init (void)
 
 static int conn_read (void)
 {
-  int errors_num = 0;
+  int status;
 
   conn_reset_port_entry ();
 
-  if (conn_read_file ("/proc/net/tcp") != 0)
-    errors_num++;
-  if (conn_read_file ("/proc/net/tcp6") != 0)
-    errors_num++;
-
-  if (errors_num < 2)
+  if (linux_source == SRC_NETLINK)
   {
-    conn_submit_all ();
+    status = conn_read_netlink ();
   }
-  else
+  else if (linux_source == SRC_PROC)
   {
-    ERROR ("tcpconns plugin: Neither /proc/net/tcp nor /proc/net/tcp6 "
-       "coult be read.");
-    return (-1);
+    int errors_num = 0;
+
+    if (conn_read_file ("/proc/net/tcp") != 0)
+      errors_num++;
+    if (conn_read_file ("/proc/net/tcp6") != 0)
+      errors_num++;
+
+    if (errors_num < 2)
+      status = 0;
+    else
+      status = ENOENT;
+  }
+  else /* if (linux_source == SRC_DUNNO) */
+  {
+    /* Try to use netlink for getting this data, it is _much_ faster on systems
+     * with a large amount of connections. */
+    status = conn_read_netlink ();
+    if (status == 0)
+    {
+      INFO ("tcpconns plugin: Reading from netlink succeeded. "
+         "Will use the netlink method from now on.");
+      linux_source = SRC_NETLINK;
+    }
+    else
+    {
+      INFO ("tcpconns plugin: Reading from netlink failed. "
+         "Will read from /proc from now on.");
+      linux_source = SRC_PROC;
+
+      /* return success here to avoid the "plugin failed" message. */
+      return (0);
+    }
   }
 
+  if (status == 0)
+    conn_submit_all ();
+  else
+    return (status);
+
   return (0);
 } /* int conn_read */
 /* #endif KERNEL_LINUX */
@@ -706,7 +943,67 @@ static int conn_read (void)
 
   return (0);
 }
-#endif /* HAVE_LIBKVM_NLIST */
+/* #endif HAVE_LIBKVM_NLIST */
+
+#elif KERNEL_AIX
+
+static int conn_read (void)
+{
+  int size;
+  int i;
+  int nconn;
+  void *data;
+  struct netinfo_header *header;
+  struct netinfo_conn *conn;
+
+  conn_reset_port_entry ();
+
+  size = netinfo(NETINFO_TCP, 0, 0, 0);
+  if (size < 0)
+  {
+    ERROR ("tcpconns plugin: netinfo failed return: %i", size);
+    return (-1);
+  }
+
+  if (size == 0)
+    return (0);
+
+  if ((size - sizeof (struct netinfo_header)) % sizeof (struct netinfo_conn))
+  {
+    ERROR ("tcpconns plugin: invalid buffer size");
+    return (-1);
+  }
+
+  data = malloc(size);
+  if (data == NULL)
+  {
+    ERROR ("tcpconns plugin: malloc failed");
+    return (-1);
+  }
+
+  if (netinfo(NETINFO_TCP, data, &size, 0) < 0)
+  {
+    ERROR ("tcpconns plugin: netinfo failed");
+    free(data);
+    return (-1);
+  }
+
+  header = (struct netinfo_header *)data;
+  nconn = header->size;
+  conn = (struct netinfo_conn *)(data + sizeof(struct netinfo_header));
+
+  for (i=0; i < nconn; conn++, i++)
+  {
+    conn_handle_ports (conn->srcport, conn->dstport, conn->tcp_state);
+  }
+
+  free(data);
+
+  conn_submit_all ();
+
+  return (0);
+}
+#endif /* KERNEL_AIX */
 
 void module_register (void)
 {
@@ -718,6 +1015,8 @@ void module_register (void)
        /* no initialization */
 #elif HAVE_LIBKVM_NLIST
        plugin_register_init ("tcpconns", conn_init);
+#elif KERNEL_AIX
+       /* no initialization */
 #endif
        plugin_register_read ("tcpconns", conn_read);
 } /* void module_register */
index d4bf2aa..2552ad3 100644 (file)
@@ -25,8 +25,8 @@
 #include "common.h"
 #include "plugin.h"
 
-#include <arpa/inet.h>
 #include <netinet/in.h>
+#include <arpa/inet.h>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netdb.h>
@@ -146,7 +146,7 @@ static void tss2_submit_gauge (const char *plugin_instance,
 } /* void tss2_submit_gauge */
 
 static void tss2_submit_io (const char *plugin_instance, const char *type,
-               counter_t rx, counter_t tx)
+               derive_t rx, derive_t tx)
 {
        /*
         * Submits the io rx/tx tuple to the collectd daemon
@@ -154,8 +154,8 @@ static void tss2_submit_io (const char *plugin_instance, const char *type,
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = rx;
-       values[1].counter = tx;
+       values[0].derive = rx;
+       values[1].derive = tx;
 
        vl.values     = values;
        vl.values_len = 2;
@@ -299,6 +299,13 @@ static int tss2_get_socket (FILE **ret_read_fh, FILE **ret_write_fh)
                char *buffer_ptr;
 
                buffer_ptr = fgets (buffer, sizeof (buffer), global_read_fh);
+               if (buffer_ptr == NULL)
+               {
+                       WARNING ("teamspeak2 plugin: Unexpected EOF received "
+                                       "from remote host %s:%s.",
+                                       config_host ? config_host : DEFAULT_HOST,
+                                       config_port ? config_port : DEFAULT_PORT);
+               }
                buffer[sizeof (buffer) - 1] = 0;
 
                if (memcmp ("[TS]\r\n", buffer, 6) != 0)
@@ -498,10 +505,10 @@ static int tss2_read_vserver (vserver_list_t *vserver)
        gauge_t users = NAN;
        gauge_t channels = NAN;
        gauge_t servers = NAN;
-       counter_t rx_octets = 0;
-       counter_t tx_octets = 0;
-       counter_t rx_packets = 0;
-       counter_t tx_packets = 0;
+       derive_t rx_octets = 0;
+       derive_t tx_octets = 0;
+       derive_t rx_packets = 0;
+       derive_t tx_packets = 0;
        gauge_t packet_loss = NAN;
        int valid = 0;
 
index b9d07bf..0ad0d90 100644 (file)
 # error "This module is for Linux only."
 #endif
 
+static const char *config_keys[] = {
+       "Device",
+       "IgnoreSelected",
+       "ForceUseProcfs"
+};
+
 const char *const dirname_sysfs = "/sys/class/thermal";
 const char *const dirname_procfs = "/proc/acpi/thermal_zone";
 
-static char force_procfs = 0;
+static _Bool force_procfs = 0;
 static ignorelist_t *device_list;
-static value_list_t vl_temp_template = VALUE_LIST_STATIC;
-static value_list_t vl_state_template = VALUE_LIST_STATIC;
 
 enum dev_type {
        TEMP = 0,
@@ -45,16 +49,18 @@ enum dev_type {
 static void thermal_submit (const char *plugin_instance, enum dev_type dt,
                gauge_t value)
 {
-       value_list_t vl = (dt == TEMP) ? vl_temp_template : vl_state_template;
-       value_t vt;
+       value_list_t vl = VALUE_LIST_INIT;
+       value_t v;
 
-       vt.gauge = value;
+       v.gauge = value;
+       vl.values = &v;
 
-       vl.values = &vt;
        sstrncpy (vl.plugin, "thermal", sizeof(vl.plugin));
-       sstrncpy (vl.plugin_instance, plugin_instance,
-                       sizeof(vl.plugin_instance));
-       sstrncpy (vl.type, (dt == TEMP) ? "temperature" : "gauge",
+       if (plugin_instance != NULL)
+               sstrncpy (vl.plugin_instance, plugin_instance,
+                               sizeof (vl.plugin_instance));
+       sstrncpy (vl.type,
+                       (dt == TEMP) ? "temperature" : "gauge",
                        sizeof (vl.type));
 
        plugin_dispatch_values (&vl);
@@ -66,7 +72,7 @@ static int thermal_sysfs_device_read (const char __attribute__((unused)) *dir,
        char filename[256];
        char data[1024];
        int len;
-       int ok = 0;
+       _Bool success = 0;
 
        if (device_list && ignorelist_match (device_list, name))
                return -1;
@@ -87,7 +93,7 @@ static int thermal_sysfs_device_read (const char __attribute__((unused)) *dir,
 
                if (endptr == data + len && errno == 0) {
                        thermal_submit(name, TEMP, temp);
-                       ++ok;
+                       success = 1;
                }
        }
 
@@ -107,11 +113,11 @@ static int thermal_sysfs_device_read (const char __attribute__((unused)) *dir,
 
                if (endptr == data + len && errno == 0) {
                        thermal_submit(name, COOLING_DEV, state);
-                       ++ok;
+                       success = 1;
                }
        }
 
-       return ok ? 0 : -1;
+       return (success ? 0 : -1);
 }
 
 static int thermal_procfs_device_read (const char __attribute__((unused)) *dir,
@@ -141,17 +147,17 @@ static int thermal_procfs_device_read (const char __attribute__((unused)) *dir,
                        && (! strncmp(data, str_temp, sizeof(str_temp)-1))) {
                char *endptr = NULL;
                double temp;
-               double celsius, add;
+               double factor, add;
                
                if (data[--len] == 'C') {
                        add = 0;
-                       celsius = 1;
+                       factor = 1.0;
                } else if (data[len] == 'F') {
                        add = -32;
-                       celsius = 5/9;
+                       factor = 5.0/9.0;
                } else if (data[len] == 'K') {
                        add = -273.15;
-                       celsius = 1;
+                       factor = 1.0;
                } else
                        return -1;
 
@@ -164,7 +170,7 @@ static int thermal_procfs_device_read (const char __attribute__((unused)) *dir,
                ++len;
 
                errno = 0;
-               temp = (strtod (data + len, &endptr) + add) * celsius;
+               temp = (strtod (data + len, &endptr) + add) * factor;
 
                if (endptr != data + len && errno == 0) {
                        thermal_submit(name, TEMP, temp);
@@ -175,12 +181,6 @@ static int thermal_procfs_device_read (const char __attribute__((unused)) *dir,
        return -1;
 }
 
-static const char *config_keys[] = {
-       "Device",
-       "IgnoreSelected",
-       "ForceUseProcfs"
-};
-
 static int thermal_config (const char *key, const char *value)
 {
        if (device_list == NULL)
@@ -237,21 +237,6 @@ static int thermal_init (void)
                ret = plugin_register_read ("thermal", thermal_procfs_read);
        }
 
-       if (!ret) {
-               vl_temp_template.values_len = 1;
-               vl_temp_template.interval = interval_g;
-               sstrncpy (vl_temp_template.host, hostname_g,
-                       sizeof(vl_temp_template.host));
-               sstrncpy (vl_temp_template.plugin, "thermal",
-                       sizeof(vl_temp_template.plugin));
-               sstrncpy (vl_temp_template.type_instance, "temperature",
-                       sizeof(vl_temp_template.type_instance));
-
-               vl_state_template = vl_temp_template;
-               sstrncpy (vl_state_template.type_instance, "cooling_state",
-                       sizeof(vl_state_template.type_instance));
-       }
-
        return ret;
 }
 
diff --git a/src/threshold.c b/src/threshold.c
new file mode 100644 (file)
index 0000000..d4cfd6e
--- /dev/null
@@ -0,0 +1,1030 @@
+/**
+ * collectd - src/threshold.c
+ * Copyright (C) 2007-2010  Florian Forster
+ * Copyright (C) 2008-2009  Sebastian Harl
+ * Copyright (C) 2009       Andrés J. Díaz
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; only version 2 of the License is applicable.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Author:
+ *   Florian octo Forster <octo at collectd.org>
+ *   Sebastian Harl <sh at tokkee.org>
+ *   Andrés J. Díaz <ajdiaz at connectical.com>
+ **/
+
+#include "collectd.h"
+#include "common.h"
+#include "plugin.h"
+#include "utils_avltree.h"
+#include "utils_cache.h"
+
+#include <assert.h>
+#include <pthread.h>
+
+/*
+ * Private data structures
+ * {{{ */
+#define UT_FLAG_INVERT  0x01
+#define UT_FLAG_PERSIST 0x02
+#define UT_FLAG_PERCENTAGE 0x04
+#define UT_FLAG_INTERESTING 0x08
+#define UT_FLAG_PERSIST_OK 0x10
+typedef struct threshold_s
+{
+  char host[DATA_MAX_NAME_LEN];
+  char plugin[DATA_MAX_NAME_LEN];
+  char plugin_instance[DATA_MAX_NAME_LEN];
+  char type[DATA_MAX_NAME_LEN];
+  char type_instance[DATA_MAX_NAME_LEN];
+  char data_source[DATA_MAX_NAME_LEN];
+  gauge_t warning_min;
+  gauge_t warning_max;
+  gauge_t failure_min;
+  gauge_t failure_max;
+  gauge_t hysteresis;
+  unsigned int flags;
+  int hits;
+  struct threshold_s *next;
+} threshold_t;
+/* }}} */
+
+/*
+ * Private (static) variables
+ * {{{ */
+static c_avl_tree_t   *threshold_tree = NULL;
+static pthread_mutex_t threshold_lock = PTHREAD_MUTEX_INITIALIZER;
+/* }}} */
+
+/*
+ * Threshold management
+ * ====================
+ * The following functions add, delete, search, etc. configured thresholds to
+ * the underlying AVL trees.
+ */
+/*
+ * threshold_t *threshold_get
+ *
+ * Retrieve one specific threshold configuration. For looking up a threshold
+ * matching a value_list_t, see "threshold_search" below. Returns NULL if the
+ * specified threshold doesn't exist.
+ */
+static threshold_t *threshold_get (const char *hostname,
+    const char *plugin, const char *plugin_instance,
+    const char *type, const char *type_instance)
+{ /* {{{ */
+  char name[6 * DATA_MAX_NAME_LEN];
+  threshold_t *th = NULL;
+
+  format_name (name, sizeof (name),
+      (hostname == NULL) ? "" : hostname,
+      (plugin == NULL) ? "" : plugin, plugin_instance,
+      (type == NULL) ? "" : type, type_instance);
+  name[sizeof (name) - 1] = '\0';
+
+  if (c_avl_get (threshold_tree, name, (void *) &th) == 0)
+    return (th);
+  else
+    return (NULL);
+} /* }}} threshold_t *threshold_get */
+
+/*
+ * int ut_threshold_add
+ *
+ * Adds a threshold configuration to the list of thresholds. The threshold_t
+ * structure is copied and may be destroyed after this call. Returns zero on
+ * success, non-zero otherwise.
+ */
+static int ut_threshold_add (const threshold_t *th)
+{ /* {{{ */
+  char name[6 * DATA_MAX_NAME_LEN];
+  char *name_copy;
+  threshold_t *th_copy;
+  threshold_t *th_ptr;
+  int status = 0;
+
+  if (format_name (name, sizeof (name), th->host,
+       th->plugin, th->plugin_instance,
+       th->type, th->type_instance) != 0)
+  {
+    ERROR ("ut_threshold_add: format_name failed.");
+    return (-1);
+  }
+
+  name_copy = strdup (name);
+  if (name_copy == NULL)
+  {
+    ERROR ("ut_threshold_add: strdup failed.");
+    return (-1);
+  }
+
+  th_copy = (threshold_t *) malloc (sizeof (threshold_t));
+  if (th_copy == NULL)
+  {
+    sfree (name_copy);
+    ERROR ("ut_threshold_add: malloc failed.");
+    return (-1);
+  }
+  memcpy (th_copy, th, sizeof (threshold_t));
+  th_ptr = NULL;
+
+  DEBUG ("ut_threshold_add: Adding entry `%s'", name);
+
+  pthread_mutex_lock (&threshold_lock);
+
+  th_ptr = threshold_get (th->host, th->plugin, th->plugin_instance,
+      th->type, th->type_instance);
+
+  while ((th_ptr != NULL) && (th_ptr->next != NULL))
+    th_ptr = th_ptr->next;
+
+  if (th_ptr == NULL) /* no such threshold yet */
+  {
+    status = c_avl_insert (threshold_tree, name_copy, th_copy);
+  }
+  else /* th_ptr points to the last threshold in the list */
+  {
+    th_ptr->next = th_copy;
+    /* name_copy isn't needed */
+    sfree (name_copy);
+  }
+
+  pthread_mutex_unlock (&threshold_lock);
+
+  if (status != 0)
+  {
+    ERROR ("ut_threshold_add: c_avl_insert (%s) failed.", name);
+    sfree (name_copy);
+    sfree (th_copy);
+  }
+
+  return (status);
+} /* }}} int ut_threshold_add */
+
+/* 
+ * threshold_t *threshold_search
+ *
+ * Searches for a threshold configuration using all the possible variations of
+ * "Host", "Plugin" and "Type" blocks. Returns NULL if no threshold could be
+ * found.
+ * XXX: This is likely the least efficient function in collectd.
+ */
+static threshold_t *threshold_search (const value_list_t *vl)
+{ /* {{{ */
+  threshold_t *th;
+
+  if ((th = threshold_get (vl->host, vl->plugin, vl->plugin_instance,
+         vl->type, vl->type_instance)) != NULL)
+    return (th);
+  else if ((th = threshold_get (vl->host, vl->plugin, vl->plugin_instance,
+         vl->type, NULL)) != NULL)
+    return (th);
+  else if ((th = threshold_get (vl->host, vl->plugin, NULL,
+         vl->type, vl->type_instance)) != NULL)
+    return (th);
+  else if ((th = threshold_get (vl->host, vl->plugin, NULL,
+         vl->type, NULL)) != NULL)
+    return (th);
+  else if ((th = threshold_get (vl->host, "", NULL,
+         vl->type, vl->type_instance)) != NULL)
+    return (th);
+  else if ((th = threshold_get (vl->host, "", NULL,
+         vl->type, NULL)) != NULL)
+    return (th);
+  else if ((th = threshold_get ("", vl->plugin, vl->plugin_instance,
+         vl->type, vl->type_instance)) != NULL)
+    return (th);
+  else if ((th = threshold_get ("", vl->plugin, vl->plugin_instance,
+         vl->type, NULL)) != NULL)
+    return (th);
+  else if ((th = threshold_get ("", vl->plugin, NULL,
+         vl->type, vl->type_instance)) != NULL)
+    return (th);
+  else if ((th = threshold_get ("", vl->plugin, NULL,
+         vl->type, NULL)) != NULL)
+    return (th);
+  else if ((th = threshold_get ("", "", NULL,
+         vl->type, vl->type_instance)) != NULL)
+    return (th);
+  else if ((th = threshold_get ("", "", NULL,
+         vl->type, NULL)) != NULL)
+    return (th);
+
+  return (NULL);
+} /* }}} threshold_t *threshold_search */
+
+/*
+ * Configuration
+ * =============
+ * The following approximately two hundred functions are used to handle the
+ * configuration and fill the threshold list.
+ * {{{ */
+static int ut_config_type_datasource (threshold_t *th, oconfig_item_t *ci)
+{
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_STRING))
+  {
+    WARNING ("threshold values: The `DataSource' option needs exactly one "
+       "string argument.");
+    return (-1);
+  }
+
+  sstrncpy (th->data_source, ci->values[0].value.string,
+      sizeof (th->data_source));
+
+  return (0);
+} /* int ut_config_type_datasource */
+
+static int ut_config_type_instance (threshold_t *th, oconfig_item_t *ci)
+{
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_STRING))
+  {
+    WARNING ("threshold values: The `Instance' option needs exactly one "
+       "string argument.");
+    return (-1);
+  }
+
+  sstrncpy (th->type_instance, ci->values[0].value.string,
+      sizeof (th->type_instance));
+
+  return (0);
+} /* int ut_config_type_instance */
+
+static int ut_config_type_max (threshold_t *th, oconfig_item_t *ci)
+{
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
+  {
+    WARNING ("threshold values: The `%s' option needs exactly one "
+       "number argument.", ci->key);
+    return (-1);
+  }
+
+  if (strcasecmp (ci->key, "WarningMax") == 0)
+    th->warning_max = ci->values[0].value.number;
+  else
+    th->failure_max = ci->values[0].value.number;
+
+  return (0);
+} /* int ut_config_type_max */
+
+static int ut_config_type_min (threshold_t *th, oconfig_item_t *ci)
+{
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
+  {
+    WARNING ("threshold values: The `%s' option needs exactly one "
+       "number argument.", ci->key);
+    return (-1);
+  }
+
+  if (strcasecmp (ci->key, "WarningMin") == 0)
+    th->warning_min = ci->values[0].value.number;
+  else
+    th->failure_min = ci->values[0].value.number;
+
+  return (0);
+} /* int ut_config_type_min */
+
+static int ut_config_type_hits (threshold_t *th, oconfig_item_t *ci)
+{
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
+  {
+    WARNING ("threshold values: The `%s' option needs exactly one "
+      "number argument.", ci->key);
+    return (-1);
+  }
+
+  th->hits = ci->values[0].value.number;
+
+  return (0);
+} /* int ut_config_type_hits */
+
+static int ut_config_type_hysteresis (threshold_t *th, oconfig_item_t *ci)
+{
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
+  {
+    WARNING ("threshold values: The `%s' option needs exactly one "
+      "number argument.", ci->key);
+    return (-1);
+  }
+
+  th->hysteresis = ci->values[0].value.number;
+
+  return (0);
+} /* int ut_config_type_hysteresis */
+
+static int ut_config_type (const threshold_t *th_orig, oconfig_item_t *ci)
+{
+  int i;
+  threshold_t th;
+  int status = 0;
+
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_STRING))
+  {
+    WARNING ("threshold values: The `Type' block needs exactly one string "
+       "argument.");
+    return (-1);
+  }
+
+  if (ci->children_num < 1)
+  {
+    WARNING ("threshold values: The `Type' block needs at least one option.");
+    return (-1);
+  }
+
+  memcpy (&th, th_orig, sizeof (th));
+  sstrncpy (th.type, ci->values[0].value.string, sizeof (th.type));
+
+  th.warning_min = NAN;
+  th.warning_max = NAN;
+  th.failure_min = NAN;
+  th.failure_max = NAN;
+  th.hits = 0;
+  th.hysteresis = 0;
+  th.flags = UT_FLAG_INTERESTING; /* interesting by default */
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *option = ci->children + i;
+    status = 0;
+
+    if (strcasecmp ("Instance", option->key) == 0)
+      status = ut_config_type_instance (&th, option);
+    else if (strcasecmp ("DataSource", option->key) == 0)
+      status = ut_config_type_datasource (&th, option);
+    else if ((strcasecmp ("WarningMax", option->key) == 0)
+       || (strcasecmp ("FailureMax", option->key) == 0))
+      status = ut_config_type_max (&th, option);
+    else if ((strcasecmp ("WarningMin", option->key) == 0)
+       || (strcasecmp ("FailureMin", option->key) == 0))
+      status = ut_config_type_min (&th, option);
+    else if (strcasecmp ("Interesting", option->key) == 0)
+      status = cf_util_get_flag (option, &th.flags, UT_FLAG_INTERESTING);
+    else if (strcasecmp ("Invert", option->key) == 0)
+      status = cf_util_get_flag (option, &th.flags, UT_FLAG_INVERT);
+    else if (strcasecmp ("Persist", option->key) == 0)
+      status = cf_util_get_flag (option, &th.flags, UT_FLAG_PERSIST);
+    else if (strcasecmp ("PersistOK", option->key) == 0)
+      status = cf_util_get_flag (option, &th.flags, UT_FLAG_PERSIST_OK);
+    else if (strcasecmp ("Percentage", option->key) == 0)
+      status = cf_util_get_flag (option, &th.flags, UT_FLAG_PERCENTAGE);
+    else if (strcasecmp ("Hits", option->key) == 0)
+      status = ut_config_type_hits (&th, option);
+    else if (strcasecmp ("Hysteresis", option->key) == 0)
+      status = ut_config_type_hysteresis (&th, option);
+    else
+    {
+      WARNING ("threshold values: Option `%s' not allowed inside a `Type' "
+         "block.", option->key);
+      status = -1;
+    }
+
+    if (status != 0)
+      break;
+  }
+
+  if (status == 0)
+  {
+    status = ut_threshold_add (&th);
+  }
+
+  return (status);
+} /* int ut_config_type */
+
+static int ut_config_plugin_instance (threshold_t *th, oconfig_item_t *ci)
+{
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_STRING))
+  {
+    WARNING ("threshold values: The `Instance' option needs exactly one "
+       "string argument.");
+    return (-1);
+  }
+
+  sstrncpy (th->plugin_instance, ci->values[0].value.string,
+      sizeof (th->plugin_instance));
+
+  return (0);
+} /* int ut_config_plugin_instance */
+
+static int ut_config_plugin (const threshold_t *th_orig, oconfig_item_t *ci)
+{
+  int i;
+  threshold_t th;
+  int status = 0;
+
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_STRING))
+  {
+    WARNING ("threshold values: The `Plugin' block needs exactly one string "
+       "argument.");
+    return (-1);
+  }
+
+  if (ci->children_num < 1)
+  {
+    WARNING ("threshold values: The `Plugin' block needs at least one nested "
+       "block.");
+    return (-1);
+  }
+
+  memcpy (&th, th_orig, sizeof (th));
+  sstrncpy (th.plugin, ci->values[0].value.string, sizeof (th.plugin));
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *option = ci->children + i;
+    status = 0;
+
+    if (strcasecmp ("Type", option->key) == 0)
+      status = ut_config_type (&th, option);
+    else if (strcasecmp ("Instance", option->key) == 0)
+      status = ut_config_plugin_instance (&th, option);
+    else
+    {
+      WARNING ("threshold values: Option `%s' not allowed inside a `Plugin' "
+         "block.", option->key);
+      status = -1;
+    }
+
+    if (status != 0)
+      break;
+  }
+
+  return (status);
+} /* int ut_config_plugin */
+
+static int ut_config_host (const threshold_t *th_orig, oconfig_item_t *ci)
+{
+  int i;
+  threshold_t th;
+  int status = 0;
+
+  if ((ci->values_num != 1)
+      || (ci->values[0].type != OCONFIG_TYPE_STRING))
+  {
+    WARNING ("threshold values: The `Host' block needs exactly one string "
+       "argument.");
+    return (-1);
+  }
+
+  if (ci->children_num < 1)
+  {
+    WARNING ("threshold values: The `Host' block needs at least one nested "
+       "block.");
+    return (-1);
+  }
+
+  memcpy (&th, th_orig, sizeof (th));
+  sstrncpy (th.host, ci->values[0].value.string, sizeof (th.host));
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *option = ci->children + i;
+    status = 0;
+
+    if (strcasecmp ("Type", option->key) == 0)
+      status = ut_config_type (&th, option);
+    else if (strcasecmp ("Plugin", option->key) == 0)
+      status = ut_config_plugin (&th, option);
+    else
+    {
+      WARNING ("threshold values: Option `%s' not allowed inside a `Host' "
+         "block.", option->key);
+      status = -1;
+    }
+
+    if (status != 0)
+      break;
+  }
+
+  return (status);
+} /* int ut_config_host */
+/*
+ * End of the functions used to configure threshold values.
+ */
+/* }}} */
+
+/*
+ * int ut_report_state
+ *
+ * Checks if the `state' differs from the old state and creates a notification
+ * if appropriate.
+ * Does not fail.
+ */
+static int ut_report_state (const data_set_t *ds,
+    const value_list_t *vl,
+    const threshold_t *th,
+    const gauge_t *values,
+    int ds_index,
+    int state)
+{ /* {{{ */
+  int state_old;
+  notification_t n;
+
+  char *buf;
+  size_t bufsize;
+
+  int status;
+
+  /* Check if hits matched */
+  if ( (th->hits != 0) )
+  {
+    int hits = uc_get_hits(ds,vl);
+    /* STATE_OKAY resets hits unless PERSIST_OK flag is set. Hits resets if
+     * threshold is hit. */
+    if ( ( (state == STATE_OKAY) && ((th->flags & UT_FLAG_PERSIST_OK) == 0) ) || (hits > th->hits) )
+    {
+        DEBUG("ut_report_state: reset uc_get_hits = 0");
+        uc_set_hits(ds,vl,0); /* reset hit counter and notify */
+    } else {
+      DEBUG("ut_report_state: th->hits = %d, uc_get_hits = %d",th->hits,uc_get_hits(ds,vl));
+      (void) uc_inc_hits(ds,vl,1); /* increase hit counter */
+      return (0);
+    }
+  } /* end check hits */
+
+  state_old = uc_get_state (ds, vl);
+
+  /* If the state didn't change, report if `persistent' is specified. If the
+   * state is `okay', then only report if `persist_ok` flag is set. */
+  if (state == state_old)
+  {
+    if ((th->flags & UT_FLAG_PERSIST) == 0)
+      return (0);
+    else if ( (state == STATE_OKAY) && ((th->flags & UT_FLAG_PERSIST_OK) == 0) )
+      return (0);
+  }
+
+  if (state != state_old)
+    uc_set_state (ds, vl, state);
+
+  NOTIFICATION_INIT_VL (&n, vl);
+
+  buf = n.message;
+  bufsize = sizeof (n.message);
+
+  if (state == STATE_OKAY)
+    n.severity = NOTIF_OKAY;
+  else if (state == STATE_WARNING)
+    n.severity = NOTIF_WARNING;
+  else
+    n.severity = NOTIF_FAILURE;
+
+  n.time = vl->time;
+
+  status = ssnprintf (buf, bufsize, "Host %s, plugin %s",
+      vl->host, vl->plugin);
+  buf += status;
+  bufsize -= status;
+
+  if (vl->plugin_instance[0] != '\0')
+  {
+    status = ssnprintf (buf, bufsize, " (instance %s)",
+       vl->plugin_instance);
+    buf += status;
+    bufsize -= status;
+  }
+
+  status = ssnprintf (buf, bufsize, " type %s", vl->type);
+  buf += status;
+  bufsize -= status;
+
+  if (vl->type_instance[0] != '\0')
+  {
+    status = ssnprintf (buf, bufsize, " (instance %s)",
+       vl->type_instance);
+    buf += status;
+    bufsize -= status;
+  }
+
+  plugin_notification_meta_add_string (&n, "DataSource",
+      ds->ds[ds_index].name);
+  plugin_notification_meta_add_double (&n, "CurrentValue", values[ds_index]);
+  plugin_notification_meta_add_double (&n, "WarningMin", th->warning_min);
+  plugin_notification_meta_add_double (&n, "WarningMax", th->warning_max);
+  plugin_notification_meta_add_double (&n, "FailureMin", th->failure_min);
+  plugin_notification_meta_add_double (&n, "FailureMax", th->failure_max);
+
+  /* Send an okay notification */
+  if (state == STATE_OKAY)
+  {
+    if (state_old == STATE_MISSING)
+      status = ssnprintf (buf, bufsize,
+          ": Value is no longer missing.");
+    else
+      status = ssnprintf (buf, bufsize,
+          ": All data sources are within range again.");
+    buf += status;
+    bufsize -= status;
+  }
+  else
+  {
+    double min;
+    double max;
+
+    min = (state == STATE_ERROR) ? th->failure_min : th->warning_min;
+    max = (state == STATE_ERROR) ? th->failure_max : th->warning_max;
+
+    if (th->flags & UT_FLAG_INVERT)
+    {
+      if (!isnan (min) && !isnan (max))
+      {
+        status = ssnprintf (buf, bufsize, ": Data source \"%s\" is currently "
+            "%f. That is within the %s region of %f%s and %f%s.",
+            ds->ds[ds_index].name, values[ds_index],
+            (state == STATE_ERROR) ? "failure" : "warning",
+            min, ((th->flags & UT_FLAG_PERCENTAGE) != 0) ? "%" : "",
+            max, ((th->flags & UT_FLAG_PERCENTAGE) != 0) ? "%" : "");
+      }
+      else
+      {
+       status = ssnprintf (buf, bufsize, ": Data source \"%s\" is currently "
+           "%f. That is %s the %s threshold of %f%s.",
+           ds->ds[ds_index].name, values[ds_index],
+           isnan (min) ? "below" : "above",
+           (state == STATE_ERROR) ? "failure" : "warning",
+           isnan (min) ? max : min,
+           ((th->flags & UT_FLAG_PERCENTAGE) != 0) ? "%" : "");
+      }
+    }
+    else if (th->flags & UT_FLAG_PERCENTAGE)
+    {
+      gauge_t value;
+      gauge_t sum;
+      int i;
+
+      sum = 0.0;
+      for (i = 0; i < vl->values_len; i++)
+      {
+        if (isnan (values[i]))
+          continue;
+
+        sum += values[i];
+      }
+
+      if (sum == 0.0)
+        value = NAN;
+      else
+        value = 100.0 * values[ds_index] / sum;
+
+      status = ssnprintf (buf, bufsize, ": Data source \"%s\" is currently "
+          "%g (%.2f%%). That is %s the %s threshold of %.2f%%.",
+          ds->ds[ds_index].name, values[ds_index], value,
+          (value < min) ? "below" : "above",
+          (state == STATE_ERROR) ? "failure" : "warning",
+          (value < min) ? min : max);
+    }
+    else /* is not inverted */
+    {
+      status = ssnprintf (buf, bufsize, ": Data source \"%s\" is currently "
+         "%f. That is %s the %s threshold of %f.",
+         ds->ds[ds_index].name, values[ds_index],
+         (values[ds_index] < min) ? "below" : "above",
+         (state == STATE_ERROR) ? "failure" : "warning",
+         (values[ds_index] < min) ? min : max);
+    }
+    buf += status;
+    bufsize -= status;
+  }
+
+  plugin_dispatch_notification (&n);
+
+  plugin_notification_meta_free (n.meta);
+  return (0);
+} /* }}} int ut_report_state */
+
+/*
+ * int ut_check_one_data_source
+ *
+ * Checks one data source against the given threshold configuration. If the
+ * `DataSource' option is set in the threshold, and the name does NOT match,
+ * `okay' is returned. If the threshold does match, its failure and warning
+ * min and max values are checked and `failure' or `warning' is returned if
+ * appropriate.
+ * Does not fail.
+ */
+static int ut_check_one_data_source (const data_set_t *ds,
+    const value_list_t __attribute__((unused)) *vl,
+    const threshold_t *th,
+    const gauge_t *values,
+    int ds_index)
+{ /* {{{ */
+  const char *ds_name;
+  int is_warning = 0;
+  int is_failure = 0;
+  int prev_state = STATE_OKAY;
+
+  /* check if this threshold applies to this data source */
+  if (ds != NULL)
+  {
+    ds_name = ds->ds[ds_index].name;
+    if ((th->data_source[0] != 0)
+       && (strcmp (ds_name, th->data_source) != 0))
+      return (STATE_OKAY);
+  }
+
+  if ((th->flags & UT_FLAG_INVERT) != 0)
+  {
+    is_warning--;
+    is_failure--;
+  }
+
+  /* XXX: This is an experimental code, not optimized, not fast, not reliable,
+   * and probably, do not work as you expect. Enjoy! :D */
+  if ( (th->hysteresis > 0) && ((prev_state = uc_get_state(ds,vl)) != STATE_OKAY) )
+  {
+    switch(prev_state)
+    {
+      case STATE_ERROR:
+       if ( (!isnan (th->failure_min) && ((th->failure_min + th->hysteresis) < values[ds_index])) ||
+            (!isnan (th->failure_max) && ((th->failure_max - th->hysteresis) > values[ds_index])) )
+         return (STATE_OKAY);
+       else
+         is_failure++;
+      case STATE_WARNING:
+       if ( (!isnan (th->warning_min) && ((th->warning_min + th->hysteresis) < values[ds_index])) ||
+            (!isnan (th->warning_max) && ((th->warning_max - th->hysteresis) > values[ds_index])) )
+         return (STATE_OKAY);
+       else
+         is_warning++;
+     }
+  }
+  else { /* no hysteresis */
+    if ((!isnan (th->failure_min) && (th->failure_min > values[ds_index]))
+       || (!isnan (th->failure_max) && (th->failure_max < values[ds_index])))
+      is_failure++;
+
+    if ((!isnan (th->warning_min) && (th->warning_min > values[ds_index]))
+       || (!isnan (th->warning_max) && (th->warning_max < values[ds_index])))
+      is_warning++;
+ }
+
+  if (is_failure != 0)
+    return (STATE_ERROR);
+
+  if (is_warning != 0)
+    return (STATE_WARNING);
+
+  return (STATE_OKAY);
+} /* }}} int ut_check_one_data_source */
+
+/*
+ * int ut_check_one_threshold
+ *
+ * Checks all data sources of a value list against the given threshold, using
+ * the ut_check_one_data_source function above. Returns the worst status,
+ * which is `okay' if nothing has failed.
+ * Returns less than zero if the data set doesn't have any data sources.
+ */
+static int ut_check_one_threshold (const data_set_t *ds,
+    const value_list_t *vl,
+    const threshold_t *th,
+    const gauge_t *values,
+    int *ret_ds_index)
+{ /* {{{ */
+  int ret = -1;
+  int ds_index = -1;
+  int i;
+  gauge_t values_copy[ds->ds_num];
+
+  memcpy (values_copy, values, sizeof (values_copy));
+
+  if ((th->flags & UT_FLAG_PERCENTAGE) != 0)
+  {
+    int num = 0;
+    gauge_t sum=0.0;
+
+    if (ds->ds_num == 1)
+    {
+      WARNING ("ut_check_one_threshold: The %s type has only one data "
+          "source, but you have configured to check this as a percentage. "
+          "That doesn't make much sense, because the percentage will always "
+          "be 100%%!", ds->type);
+    }
+
+    /* Prepare `sum' and `num'. */
+    for (i = 0; i < ds->ds_num; i++)
+      if (!isnan (values[i]))
+      {
+        num++;
+       sum += values[i];
+      }
+
+    if ((num == 0) /* All data sources are undefined. */
+        || (sum == 0.0)) /* Sum is zero, cannot calculate percentage. */
+    {
+      for (i = 0; i < ds->ds_num; i++)
+        values_copy[i] = NAN;
+    }
+    else /* We can actually calculate the percentage. */
+    {
+      for (i = 0; i < ds->ds_num; i++)
+        values_copy[i] = 100.0 * values[i] / sum;
+    }
+  } /* if (UT_FLAG_PERCENTAGE) */
+
+  for (i = 0; i < ds->ds_num; i++)
+  {
+    int status;
+
+    status = ut_check_one_data_source (ds, vl, th, values_copy, i);
+    if (ret < status)
+    {
+      ret = status;
+      ds_index = i;
+    }
+  } /* for (ds->ds_num) */
+
+  if (ret_ds_index != NULL)
+    *ret_ds_index = ds_index;
+
+  return (ret);
+} /* }}} int ut_check_one_threshold */
+
+/*
+ * int ut_check_threshold
+ *
+ * Gets a list of matching thresholds and searches for the worst status by one
+ * of the thresholds. Then reports that status using the ut_report_state
+ * function above. 
+ * Returns zero on success and if no threshold has been configured. Returns
+ * less than zero on failure.
+ */
+static int ut_check_threshold (const data_set_t *ds, const value_list_t *vl,
+    __attribute__((unused)) user_data_t *ud)
+{ /* {{{ */
+  threshold_t *th;
+  gauge_t *values;
+  int status;
+
+  int worst_state = -1;
+  threshold_t *worst_th = NULL;
+  int worst_ds_index = -1;
+
+  if (threshold_tree == NULL)
+    return (0);
+
+  /* Is this lock really necessary? So far, thresholds are only inserted at
+   * startup. -octo */
+  pthread_mutex_lock (&threshold_lock);
+  th = threshold_search (vl);
+  pthread_mutex_unlock (&threshold_lock);
+  if (th == NULL)
+    return (0);
+
+  DEBUG ("ut_check_threshold: Found matching threshold(s)");
+
+  values = uc_get_rate (ds, vl);
+  if (values == NULL)
+    return (0);
+
+  while (th != NULL)
+  {
+    int ds_index = -1;
+
+    status = ut_check_one_threshold (ds, vl, th, values, &ds_index);
+    if (status < 0)
+    {
+      ERROR ("ut_check_threshold: ut_check_one_threshold failed.");
+      sfree (values);
+      return (-1);
+    }
+
+    if (worst_state < status)
+    {
+      worst_state = status;
+      worst_th = th;
+      worst_ds_index = ds_index;
+    }
+
+    th = th->next;
+  } /* while (th) */
+
+  status = ut_report_state (ds, vl, worst_th, values,
+      worst_ds_index, worst_state);
+  if (status != 0)
+  {
+    ERROR ("ut_check_threshold: ut_report_state failed.");
+    sfree (values);
+    return (-1);
+  }
+
+  sfree (values);
+
+  return (0);
+} /* }}} int ut_check_threshold */
+
+/*
+ * int ut_missing
+ *
+ * This function is called whenever a value goes "missing".
+ */
+static int ut_missing (const value_list_t *vl,
+    __attribute__((unused)) user_data_t *ud)
+{ /* {{{ */
+  threshold_t *th;
+  cdtime_t missing_time;
+  char identifier[6 * DATA_MAX_NAME_LEN];
+  notification_t n;
+
+  /* dispatch notifications for "interesting" values only */
+  if (threshold_tree == NULL)
+    return (0);
+
+  th = threshold_search (vl);
+  if (th == NULL)
+    return (0);
+
+  missing_time = cdtime () - vl->time;
+  FORMAT_VL (identifier, sizeof (identifier), vl);
+
+  NOTIFICATION_INIT_VL (&n, vl);
+  ssnprintf (n.message, sizeof (n.message),
+      "%s has not been updated for %.3f seconds.",
+      identifier, CDTIME_T_TO_DOUBLE (missing_time));
+
+  plugin_dispatch_notification (&n);
+
+  return (0);
+} /* }}} int ut_missing */
+
+int ut_config (oconfig_item_t *ci)
+{ /* {{{ */
+  int i;
+  int status = 0;
+
+  threshold_t th;
+
+  if (threshold_tree == NULL)
+  {
+    threshold_tree = c_avl_create ((void *) strcmp);
+    if (threshold_tree == NULL)
+    {
+      ERROR ("ut_config: c_avl_create failed.");
+      return (-1);
+    }
+  }
+
+  memset (&th, '\0', sizeof (th));
+  th.warning_min = NAN;
+  th.warning_max = NAN;
+  th.failure_min = NAN;
+  th.failure_max = NAN;
+
+  th.hits = 0;
+  th.hysteresis = 0;
+  th.flags = UT_FLAG_INTERESTING; /* interesting by default */
+    
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *option = ci->children + i;
+    status = 0;
+
+    if (strcasecmp ("Type", option->key) == 0)
+      status = ut_config_type (&th, option);
+    else if (strcasecmp ("Plugin", option->key) == 0)
+      status = ut_config_plugin (&th, option);
+    else if (strcasecmp ("Host", option->key) == 0)
+      status = ut_config_host (&th, option);
+    else
+    {
+      WARNING ("threshold values: Option `%s' not allowed here.", option->key);
+      status = -1;
+    }
+
+    if (status != 0)
+      break;
+  }
+
+  if (c_avl_size (threshold_tree) > 0) {
+    plugin_register_missing ("threshold", ut_missing,
+        /* user data = */ NULL);
+    plugin_register_write ("threshold", ut_check_threshold,
+        /* user data = */ NULL);
+  }
+
+  return (status);
+} /* }}} int um_config */
+
+void module_register (void)
+{
+  plugin_register_complex_config ("threshold", ut_config);
+}
+
+/* vim: set sw=2 ts=8 sts=2 tw=78 et fdm=marker : */
index 0484983..ed27b78 100644 (file)
-absolute               count:ABSOLUTE:0:U
-apache_bytes           count:COUNTER:0:134217728
-apache_connections     count:GAUGE:0:65535
-apache_idle_workers    count:GAUGE:0:65535
-apache_requests                count:COUNTER:0:134217728
-apache_scoreboard      count:GAUGE:0:65535
-arc_counts             demand_data:COUNTER:0:U, demand_metadata:COUNTER:0:U, prefetch_data:COUNTER:0:U, prefetch_metadata:COUNTER:0:U
-arc_l2_bytes           read:COUNTER:0:U, write:COUNTER:0:U
-arc_l2_size            value:GAUGE:0:U
-arc_ratio              value:GAUGE:0:U
-arc_size               current:GAUGE:0:U, target:GAUGE:0:U, minlimit:GAUGE:0:U, maxlimit:GAUGE:0:U
+absolute               value:ABSOLUTE:0:U
+apache_bytes           value:DERIVE:0:U
+apache_connections     value:GAUGE:0:65535
+apache_idle_workers    value:GAUGE:0:65535
+apache_requests                value:DERIVE:0:U
+apache_scoreboard      value:GAUGE:0:65535
 ath_nodes              value:GAUGE:0:65535
-ath_stat               value:COUNTER:0:4294967295
+ath_stat               value:DERIVE:0:U
 bitrate                        value:GAUGE:0:4294967295
 bytes                  value:GAUGE:0:U
+cache_eviction         value:DERIVE:0:U
 cache_operation                value:DERIVE:0:U
 cache_ratio            value:GAUGE:0:100
 cache_result           value:DERIVE:0:U
 cache_size             value:GAUGE:0:4294967295
 charge                 value:GAUGE:0:U
-compression            uncompressed:COUNTER:0:U, compressed:COUNTER:0:U
 compression_ratio      value:GAUGE:0:2
-connections            value:COUNTER:0:U
-conntrack              entropy:GAUGE:0:4294967295
-contextswitch          contextswitches:DERIVE:0:U
+compression            uncompressed:DERIVE:0:U, compressed:DERIVE:0:U
+connections            value:DERIVE:0:U
+conntrack              value:GAUGE:0:4294967295
+contextswitch          value:DERIVE:0:U
 counter                        value:COUNTER:U:U
 cpufreq                        value:GAUGE:0:U
-cpu                    value:COUNTER:0:4294967295
-current                        value:GAUGE:U:U
+cpu                    value:DERIVE:0:U
 current_connections    value:GAUGE:0:U
 current_sessions       value:GAUGE:0:U
-delay                  seconds:GAUGE:-1000000:1000000
+current                        value:GAUGE:U:U
+delay                  value:GAUGE:-1000000:1000000
 derive                 value:DERIVE:0:U
-df                     used:GAUGE:0:1125899906842623, free:GAUGE:0:1125899906842623
 df_complex             value:GAUGE:0:U
 df_inodes              value:GAUGE:0:U
+df                     used:GAUGE:0:1125899906842623, free:GAUGE:0:1125899906842623
 disk_latency           read:GAUGE:0:U, write:GAUGE:0:U
-disk_merged            read:COUNTER:0:4294967295, write:COUNTER:0:4294967295
-disk_octets            read:COUNTER:0:17179869183, write:COUNTER:0:17179869183
-disk_ops               read:COUNTER:0:4294967295, write:COUNTER:0:4294967295
-disk_ops_complex       value:COUNTER:0:4294967296
-disk_time              read:COUNTER:0:1000000, write:COUNTER:0:1000000
-dns_answer             value:COUNTER:0:65535
-dns_notify             value:COUNTER:0:65535
-dns_octets             queries:COUNTER:0:125000000, responses:COUNTER:0:125000000
-dns_opcode             value:COUNTER:0:65535
+disk_merged            read:DERIVE:0:U, write:DERIVE:0:U
+disk_octets            read:DERIVE:0:U, write:DERIVE:0:U
+disk_ops_complex       value:DERIVE:0:U
+disk_ops               read:DERIVE:0:U, write:DERIVE:0:U
+disk_time              read:DERIVE:0:U, write:DERIVE:0:U
+dns_answer             value:DERIVE:0:U
+dns_notify             value:DERIVE:0:U
+dns_octets             queries:DERIVE:0:U, responses:DERIVE:0:U
+dns_opcode             value:DERIVE:0:U
 dns_qtype_cached       value:GAUGE:0:4294967295
-dns_qtype              value:COUNTER:0:65535
-dns_query              value:COUNTER:0:65535
-dns_question           value:COUNTER:0:65535
-dns_rcode              value:COUNTER:0:65535
-dns_reject             value:COUNTER:0:65535
-dns_request            value:COUNTER:0:65535
-dns_resolver           value:COUNTER:0:65535
-dns_response           value:COUNTER:0:65535
-dns_transfer           value:COUNTER:0:65535
-dns_update             value:COUNTER:0:65535
-dns_zops               value:COUNTER:0:65535
+dns_qtype              value:DERIVE:0:U
+dns_query              value:DERIVE:0:U
+dns_question           value:DERIVE:0:U
+dns_rcode              value:DERIVE:0:U
+dns_reject             value:DERIVE:0:U
+dns_request            value:DERIVE:0:U
+dns_resolver           value:DERIVE:0:U
+dns_response           value:DERIVE:0:U
+dns_transfer           value:DERIVE:0:U
+dns_update             value:DERIVE:0:U
+dns_zops               value:DERIVE:0:U
 email_check            value:GAUGE:0:U
 email_count            value:GAUGE:0:U
 email_size             value:GAUGE:0:U
-entropy                        entropy:GAUGE:0:4294967295
+entropy                        value:GAUGE:0:4294967295
 fanspeed               value:GAUGE:0:U
-file_size              bytes:GAUGE:0:U
+file_size              value:GAUGE:0:U
 files                  value:GAUGE:0:U
-frequency              frequency:GAUGE:0:U
-frequency_offset       ppm:GAUGE:-1000000:1000000
-fscache_stat           value:COUNTER:0:4294967295
 fork_rate              value:DERIVE:0:U
+frequency              value:GAUGE:0:U
+frequency_offset       value:GAUGE:-1000000:1000000
+fscache_stat           value:DERIVE:0:U
 gauge                  value:GAUGE:U:U
-http_request_methods   count:COUNTER:0:134217728
-http_requests          count:COUNTER:0:134217728
-http_response_codes    count:COUNTER:0:134217728
+hash_collisions                value:DERIVE:0:U
+http_request_methods   value:DERIVE:0:U
+http_requests          value:DERIVE:0:U
+http_response_codes    value:DERIVE:0:U
 humidity               value:GAUGE:0:100
-if_collisions          value:COUNTER:0:4294967295
-if_dropped             rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
-if_errors              rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
-if_multicast           value:COUNTER:0:4294967295
-if_octets              rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
-if_packets             rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
-if_rx_errors           value:COUNTER:0:4294967295
-if_tx_errors           value:COUNTER:0:4294967295
+if_collisions          value:DERIVE:0:U
+if_dropped             rx:DERIVE:0:U, tx:DERIVE:0:U
+if_errors              rx:DERIVE:0:U, tx:DERIVE:0:U
+if_multicast           value:DERIVE:0:U
+if_octets              rx:DERIVE:0:U, tx:DERIVE:0:U
+if_packets             rx:DERIVE:0:U, tx:DERIVE:0:U
+if_rx_errors           value:DERIVE:0:U
+if_tx_errors           value:DERIVE:0:U
 invocations            value:DERIVE:0:U
-io_octets              rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
-io_packets             rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
-ipt_bytes              value:COUNTER:0:134217728
-ipt_packets            value:COUNTER:0:134217728
-irq                    value:COUNTER:U:65535
+io_octets              rx:DERIVE:0:U, tx:DERIVE:0:U
+io_packets             rx:DERIVE:0:U, tx:DERIVE:0:U
+ipt_bytes              value:DERIVE:0:U
+ipt_packets            value:DERIVE:0:U
+irq                    value:DERIVE:0:U
 latency                        value:GAUGE:0:65535
 links                  value:GAUGE:0:U
 load                   shortterm:GAUGE:0:100, midterm:GAUGE:0:100, longterm:GAUGE:0:100
-memcached_command      value:COUNTER:0:U
+md_disks               value:GAUGE:0:U
+memcached_command      value:DERIVE:0:U
 memcached_connections  value:GAUGE:0:U
 memcached_items                value:GAUGE:0:U
-memcached_octets       rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
-memcached_ops          value:COUNTER:0:134217728
+memcached_octets       rx:DERIVE:0:U, tx:DERIVE:0:U
+memcached_ops          value:DERIVE:0:U
 memory                 value:GAUGE:0:281474976710656
 multimeter             value:GAUGE:U:U
-mysql_commands         value:COUNTER:0:U
-mysql_handler          value:COUNTER:0:U
-mysql_locks            value:COUNTER:0:U
-mysql_log_position     value:COUNTER:0:4294967295
-mysql_octets           rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
-nfs_procedure          value:COUNTER:0:4294967295
+mutex_operations       value:DERIVE:0:U
+mysql_commands         value:DERIVE:0:U
+mysql_handler          value:DERIVE:0:U
+mysql_locks            value:DERIVE:0:U
+mysql_log_position     value:DERIVE:0:U
+mysql_octets           rx:DERIVE:0:U, tx:DERIVE:0:U
+nfs_procedure          value:DERIVE:0:U
 nginx_connections      value:GAUGE:0:U
-nginx_requests         value:COUNTER:0:134217728
-node_octets            rx:COUNTER:0:U, tx:COUNTER:0:U
+nginx_requests         value:DERIVE:0:U
+node_octets            rx:DERIVE:0:U, tx:DERIVE:0:U
 node_rssi              value:GAUGE:0:255
-node_stat              value:COUNTER:0:4294967295
+node_stat              value:DERIVE:0:U
 node_tx_rate           value:GAUGE:0:127
-operations             value:COUNTER:0:4294967295
-percent                        percent:GAUGE:0:100.1
-pg_blks                        value:COUNTER:0:U
+operations             value:DERIVE:0:U
+percent                        value:GAUGE:0:100.1
+pg_blks                        value:DERIVE:0:U
 pg_db_size             value:GAUGE:0:U
-pg_n_tup_c             value:COUNTER:0:U
+pg_n_tup_c             value:DERIVE:0:U
 pg_n_tup_g             value:GAUGE:0:U
 pg_numbackends         value:GAUGE:0:U
-pg_scan                        value:COUNTER:0:U
-pg_xact                        value:COUNTER:0:U
+pg_scan                        value:DERIVE:0:U
+pg_xact                        value:DERIVE:0:U
 ping_droprate          value:GAUGE:0:100
-ping                   ping:GAUGE:0:65535
+ping                   value:GAUGE:0:65535
 ping_stddev            value:GAUGE:0:65535
 players                        value:GAUGE:0:1000000
 power                  value:GAUGE:0:U
-protocol_counter       value:COUNTER:0:U
+protocol_counter       value:DERIVE:0:U
+ps_code                        value:GAUGE:0:9223372036854775807
 ps_count               processes:GAUGE:0:1000000, threads:GAUGE:0:1000000
-ps_cputime             user:COUNTER:0:16000000, syst:COUNTER:0:16000000
-ps_pagefaults          minflt:COUNTER:0:9223372036854775807, majflt:COUNTER:0:9223372036854775807
+ps_cputime             user:DERIVE:0:U, syst:DERIVE:0:U
+ps_data                        value:GAUGE:0:9223372036854775807
 ps_disk_octets         read:DERIVE:0:U, write:DERIVE:0:U
 ps_disk_ops            read:DERIVE:0:U, write:DERIVE:0:U
+ps_pagefaults          minflt:DERIVE:0:U, majflt:DERIVE:0:U
 ps_rss                 value:GAUGE:0:9223372036854775807
-ps_code                        value:GAUGE:0:9223372036854775807
-ps_data                        value:GAUGE:0:9223372036854775807
 ps_stacksize           value:GAUGE:0:9223372036854775807
 ps_state               value:GAUGE:0:65535
 ps_vm                  value:GAUGE:0:9223372036854775807
 queue_length           value:GAUGE:0:U
-records                        count:GAUGE:0:U
+records                        value:GAUGE:0:U
 requests               value:GAUGE:0:U
 response_time          value:GAUGE:0:U
 route_etx              value:GAUGE:0:U
 route_metric           value:GAUGE:0:U
 routes                 value:GAUGE:0:U
-serial_octets          rx:COUNTER:0:4294967295, tx:COUNTER:0:4294967295
+serial_octets          rx:DERIVE:0:U, tx:DERIVE:0:U
 signal_noise           value:GAUGE:U:0
 signal_power           value:GAUGE:U:0
 signal_quality         value:GAUGE:0:U
 snr                    value:GAUGE:0:U
 spam_check             value:GAUGE:0:U
 spam_score             value:GAUGE:U:U
-swap_io                        value:DERIVE:0:1099511627776
+swap_io                        value:DERIVE:0:U
 swap                   value:GAUGE:0:1099511627776
 tcp_connections                value:GAUGE:0:4294967295
 temperature            value:GAUGE:-273.15:U
 threads                        value:GAUGE:0:U
-time_dispersion                seconds:GAUGE:-1000000:1000000
-timeleft               timeleft:GAUGE:0:3600
-time_offset            seconds:GAUGE:-1000000:1000000
+time_dispersion                value:GAUGE:-1000000:1000000
+timeleft               value:GAUGE:0:3600
+time_offset            value:GAUGE:-1000000:1000000
 total_bytes            value:DERIVE:0:U
 total_connections      value:DERIVE:0:U
 total_operations       value:DERIVE:0:U
@@ -165,13 +164,13 @@ total_threads             value:DERIVE:0:U
 total_time_in_ms       value:DERIVE:0:U
 total_values           value:DERIVE:0:U
 uptime                 value:GAUGE:0:4294967295
-users                  users:GAUGE:0:65535
+users                  value:GAUGE:0:65535
 vcpu                   value:GAUGE:0:U
-virt_cpu_total         ns:COUNTER:0:256000000000
-virt_vcpu              ns:COUNTER:0:1000000000
-vmpage_action          value:COUNTER:0:4294967295
-vmpage_faults          minflt:COUNTER:0:9223372036854775807, majflt:COUNTER:0:9223372036854775807
-vmpage_io              in:COUNTER:0:4294967295, out:COUNTER:0:4294967295
+virt_cpu_total         value:DERIVE:0:U
+virt_vcpu              value:DERIVE:0:U
+vmpage_action          value:DERIVE:0:U
+vmpage_faults          minflt:DERIVE:0:U, majflt:DERIVE:0:U
+vmpage_io              in:DERIVE:0:U, out:DERIVE:0:U
 vmpage_number          value:GAUGE:0:4294967295
 volatile_changes       value:GAUGE:0:U
 voltage_threshold      value:GAUGE:U:U, threshold:GAUGE:U:U
@@ -179,3 +178,14 @@ voltage                    value:GAUGE:U:U
 vs_memory              value:GAUGE:0:9223372036854775807
 vs_processes           value:GAUGE:0:65535
 vs_threads             value:GAUGE:0:65535
+#
+# Legacy types
+# (required for the v5 upgrade target)
+#
+arc_counts             demand_data:COUNTER:0:U, demand_metadata:COUNTER:0:U, prefetch_data:COUNTER:0:U, prefetch_metadata:COUNTER:0:U
+arc_l2_bytes           read:COUNTER:0:U, write:COUNTER:0:U
+arc_l2_size            value:GAUGE:0:U
+arc_ratio              value:GAUGE:0:U
+arc_size               current:GAUGE:0:U, target:GAUGE:0:U, minlimit:GAUGE:0:U, maxlimit:GAUGE:0:U
+mysql_qcache           hits:COUNTER:0:U, inserts:COUNTER:0:U, not_cached:COUNTER:0:U, lowmem_prunes:COUNTER:0:U, queries_in_cache:GAUGE:0:U
+mysql_threads          running:GAUGE:0:U, connected:GAUGE:0:U, cached:GAUGE:0:U, created:COUNTER:0:U
index 4971417..10cb4f2 100644 (file)
@@ -102,6 +102,10 @@ static void parse_line (char *buf)
   if (fields_num < 2)
     return;
 
+  /* Ignore lines which begin with a hash sign. */
+  if (fields[0][0] == '#')
+    return;
+
   ds = (data_set_t *) malloc (sizeof (data_set_t));
   if (ds == NULL)
     return;
index 0b89748..2c1665f 100644 (file)
@@ -26,7 +26,6 @@
 
 #include "utils_cmd_flush.h"
 #include "utils_cmd_getval.h"
-#include "utils_cmd_getthreshold.h"
 #include "utils_cmd_listval.h"
 #include "utils_cmd_putval.h"
 #include "utils_cmd_putnotif.h"
@@ -54,7 +53,8 @@ static const char *config_keys[] =
 {
        "SocketFile",
        "SocketGroup",
-       "SocketPerms"
+       "SocketPerms",
+       "DeleteSocket"
 };
 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
 
@@ -65,6 +65,7 @@ static int   sock_fd    = -1;
 static char *sock_file  = NULL;
 static char *sock_group = NULL;
 static int   sock_perms = S_IRWXU | S_IRWXG;
+static _Bool delete_socket = 0;
 
 static pthread_t listen_thread = (pthread_t) 0;
 
@@ -89,10 +90,27 @@ static int us_open_socket (void)
        sa.sun_family = AF_UNIX;
        sstrncpy (sa.sun_path, (sock_file != NULL) ? sock_file : US_DEFAULT_PATH,
                        sizeof (sa.sun_path));
-       /* unlink (sa.sun_path); */
 
        DEBUG ("unixsock plugin: socket path = %s", sa.sun_path);
 
+       if (delete_socket)
+       {
+               errno = 0;
+               status = unlink (sa.sun_path);
+               if ((status != 0) && (errno != ENOENT))
+               {
+                       char errbuf[1024];
+                       WARNING ("unixsock plugin: Deleting socket file \"%s\" failed: %s",
+                                       sa.sun_path,
+                                       sstrerror (errno, errbuf, sizeof (errbuf)));
+               }
+               else if (status == 0)
+               {
+                       INFO ("unixsock plugin: Successfully deleted socket file \"%s\".",
+                                       sa.sun_path);
+               }
+       }
+
        status = bind (sock_fd, (struct sockaddr *) &sa, sizeof (sa));
        if (status != 0)
        {
@@ -187,6 +205,7 @@ static void *us_handle_client (void *arg)
                close (fdin);
                close (fdout);
                pthread_exit ((void *) 1);
+               return ((void *) 1);
        }
 
        fhout = fdopen (fdout, "w");
@@ -198,6 +217,7 @@ static void *us_handle_client (void *arg)
                fclose (fhin); /* this closes fdin as well */
                close (fdout);
                pthread_exit ((void *) 1);
+               return ((void *) 1);
        }
 
        /* change output buffer to line buffered mode */
@@ -209,6 +229,7 @@ static void *us_handle_client (void *arg)
                fclose (fhin);
                fclose (fhout);
                pthread_exit ((void *) 1);
+               return ((void *) 0);
        }
 
        while (42)
@@ -222,6 +243,9 @@ static void *us_handle_client (void *arg)
                errno = 0;
                if (fgets (buffer, sizeof (buffer), fhin) == NULL)
                {
+                       if ((errno == EINTR) || (errno == EAGAIN))
+                               continue;
+
                        if (errno != 0)
                        {
                                char errbuf[1024];
@@ -250,16 +274,13 @@ static void *us_handle_client (void *arg)
                        fclose (fhin);
                        fclose (fhout);
                        pthread_exit ((void *) 1);
+                       return ((void *) 1);
                }
 
                if (strcasecmp (fields[0], "getval") == 0)
                {
                        handle_getval (fhout, buffer);
                }
-               else if (strcasecmp (fields[0], "getthreshold") == 0)
-               {
-                       handle_getthreshold (fhout, buffer);
-               }
                else if (strcasecmp (fields[0], "putval") == 0)
                {
                        handle_putval (fhout, buffer);
@@ -304,6 +325,9 @@ static void *us_server_thread (void __attribute__((unused)) *arg)
        pthread_t th;
        pthread_attr_t th_attr;
 
+       pthread_attr_init (&th_attr);
+       pthread_attr_setdetachstate (&th_attr, PTHREAD_CREATE_DETACHED);
+
        if (us_open_socket () != 0)
                pthread_exit ((void *) 1);
 
@@ -322,6 +346,7 @@ static void *us_server_thread (void __attribute__((unused)) *arg)
                                        sstrerror (errno, errbuf, sizeof (errbuf)));
                        close (sock_fd);
                        sock_fd = -1;
+                       pthread_attr_destroy (&th_attr);
                        pthread_exit ((void *) 1);
                }
 
@@ -338,10 +363,8 @@ static void *us_server_thread (void __attribute__((unused)) *arg)
 
                DEBUG ("Spawning child to handle connection on fd #%i", *remote_fd);
 
-               pthread_attr_init (&th_attr);
-               pthread_attr_setdetachstate (&th_attr, PTHREAD_CREATE_DETACHED);
-
-               status = pthread_create (&th, &th_attr, us_handle_client, (void *) remote_fd);
+               status = plugin_thread_create (&th, &th_attr,
+                               us_handle_client, (void *) remote_fd);
                if (status != 0)
                {
                        char errbuf[1024];
@@ -355,6 +378,7 @@ static void *us_server_thread (void __attribute__((unused)) *arg)
 
        close (sock_fd);
        sock_fd = -1;
+       pthread_attr_destroy (&th_attr);
 
        status = unlink ((sock_file != NULL) ? sock_file : US_DEFAULT_PATH);
        if (status != 0)
@@ -392,6 +416,13 @@ static int us_config (const char *key, const char *val)
        {
                sock_perms = (int) strtol (val, NULL, 8);
        }
+       else if (strcasecmp (key, "DeleteSocket") == 0)
+       {
+               if (IS_TRUE (val))
+                       delete_socket = 1;
+               else
+                       delete_socket = 0;
+       }
        else
        {
                return (-1);
@@ -413,7 +444,8 @@ static int us_init (void)
 
        loop = 1;
 
-       status = pthread_create (&listen_thread, NULL, us_server_thread, NULL);
+       status = plugin_thread_create (&listen_thread, NULL,
+                       us_server_thread, NULL);
        if (status != 0)
        {
                char errbuf[1024];
index d2ba963..064c3ce 100644 (file)
 /* Using sysctl interface to retrieve the boot time on *BSD / Darwin / OS X systems */
 /* #endif HAVE_SYS_SYSCTL_H */
 
+#elif HAVE_PERFSTAT
+# include <sys/protosw.h>
+# include <libperfstat.h>
+/* Using perfstat_cpu_total to retrive the boot time in AIX */
+/* #endif HAVE_PERFSTAT */
+
 #else
 # error "No applicable input method."
 #endif
@@ -203,7 +209,29 @@ static int uptime_init (void) /* {{{ */
                                "but `boottime' is zero!");
                return (-1);
        }
-#endif /* HAVE_SYS_SYSCTL_H */
+/* #endif HAVE_SYS_SYSCTL_H */
+
+#elif HAVE_PERFSTAT
+       int status;
+       perfstat_cpu_total_t cputotal;
+       int hertz;
+
+       status = perfstat_cpu_total(NULL, &cputotal,
+               sizeof(perfstat_cpu_total_t), 1);
+       if (status < 0)
+       {
+               char errbuf[1024];
+               ERROR ("uptime plugin: perfstat_cpu_total: %s",
+                       sstrerror (errno, errbuf, sizeof (errbuf)));
+               return (-1);
+       }
+
+       hertz = sysconf(_SC_CLK_TCK);
+       if (hertz <= 0)
+               hertz = HZ;
+
+       boottime = time(NULL) - cputotal.lbolt / hertz;
+#endif /* HAVE_PERFSTAT */
 
        return (0);
 } /* }}} int uptime_init */
index 3e258e9..f71b1fd 100644 (file)
@@ -51,6 +51,7 @@ struct c_avl_tree_s
 {
        c_avl_node_t *root;
        int (*compare) (const void *, const void *);
+       int size;
 };
 
 struct c_avl_iterator_s
@@ -479,12 +480,15 @@ c_avl_tree_t *c_avl_create (int (*compare) (const void *, const void *))
 
        t->root = NULL;
        t->compare = compare;
+       t->size = 0;
 
        return (t);
 }
 
 void c_avl_destroy (c_avl_tree_t *t)
 {
+       if (t == NULL)
+               return;
        free_node (t->root);
        free (t);
 }
@@ -508,6 +512,7 @@ int c_avl_insert (c_avl_tree_t *t, void *key, void *value)
        {
                new->parent = NULL;
                t->root = new;
+               t->size = 1;
                return (0);
        }
 
@@ -553,6 +558,7 @@ int c_avl_insert (c_avl_tree_t *t, void *key, void *value)
        } /* while (42) */
 
        verify_tree (t->root);
+       ++t->size;
        return (0);
 } /* int c_avl_insert */
 
@@ -574,6 +580,7 @@ int c_avl_remove (c_avl_tree_t *t, const void *key, void **rkey, void **rvalue)
 
        status = _remove (t, n);
        verify_tree (t->root);
+       --t->size;
        return (status);
 } /* void *c_avl_remove */
 
@@ -710,3 +717,10 @@ void c_avl_iterator_destroy (c_avl_iterator_t *iter)
 {
        free (iter);
 }
+
+int c_avl_size (c_avl_tree_t *t)
+{
+       if (t == NULL)
+               return (0);
+       return (t->size);
+}
index 355ced2..10fb5cb 100644 (file)
@@ -148,4 +148,19 @@ int c_avl_iterator_next (c_avl_iterator_t *iter, void **key, void **value);
 int c_avl_iterator_prev (c_avl_iterator_t *iter, void **key, void **value);
 void c_avl_iterator_destroy (c_avl_iterator_t *iter);
 
+/*
+ * NAME
+ *   c_avl_size
+ *
+ * DESCRIPTION
+ *   Return the size (number of nodes) of the specified tree.
+ *
+ * PARAMETERS
+ *   `t'        AVL-tree to get the size of.
+ *
+ * RETURN VALUE
+ *   Number of nodes in the tree, 0 if the tree is empty or NULL.
+ */
+int c_avl_size (c_avl_tree_t *t);
+
 #endif /* UTILS_AVLTREE_H */
index aeb662d..fa6e660 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/utils_cache.c
- * Copyright (C) 2007,2008  Florian octo Forster
+ * Copyright (C) 2007-2010  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Author:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
@@ -24,7 +24,6 @@
 #include "plugin.h"
 #include "utils_avltree.h"
 #include "utils_cache.h"
-#include "utils_threshold.h"
 #include "meta_data.h"
 
 #include <assert.h>
@@ -38,13 +37,13 @@ typedef struct cache_entry_s
        value_t   *values_raw;
        /* Time contained in the package
         * (for calculating rates) */
-       time_t last_time;
+       cdtime_t last_time;
        /* Time according to the local clock
         * (for purging old entries) */
-       time_t last_update;
+       cdtime_t last_update;
        /* Interval in which the data is collected
         * (for purding old entries) */
-       int interval;
+       cdtime_t interval;
        int state;
        int hits;
 
@@ -120,80 +119,6 @@ static void cache_free (cache_entry_t *ce)
   sfree (ce);
 } /* void cache_free */
 
-static int uc_send_notification (const char *name)
-{
-  cache_entry_t *ce = NULL;
-  int status;
-
-  char *name_copy;
-  char *host;
-  char *plugin;
-  char *plugin_instance;
-  char *type;
-  char *type_instance;
-
-  notification_t n;
-
-  name_copy = strdup (name);
-  if (name_copy == NULL)
-  {
-    ERROR ("uc_send_notification: strdup failed.");
-    return (-1);
-  }
-
-  status = parse_identifier (name_copy, &host,
-      &plugin, &plugin_instance,
-      &type, &type_instance);
-  if (status != 0)
-  {
-    ERROR ("uc_send_notification: Cannot parse name `%s'", name);
-    return (-1);
-  }
-
-  /* Copy the associative members */
-  notification_init (&n, NOTIF_FAILURE, /* host = */ NULL,
-      host, plugin, plugin_instance, type, type_instance);
-
-  sfree (name_copy);
-  name_copy = host = plugin = plugin_instance = type = type_instance = NULL;
-
-  pthread_mutex_lock (&cache_lock);
-
-  /*
-   * Set the time _after_ getting the lock because we don't know how long
-   * acquiring the lock takes and we will use this time later to decide
-   * whether or not the state is OKAY.
-   */
-  n.time = time (NULL);
-
-  status = c_avl_get (cache_tree, name, (void *) &ce);
-  if (status != 0)
-  {
-    pthread_mutex_unlock (&cache_lock);
-    sfree (name_copy);
-    return (-1);
-  }
-    
-  /* Check if the entry has been updated in the meantime */
-  if ((n.time - ce->last_update) < (timeout_g * ce->interval))
-  {
-    ce->state = STATE_OKAY;
-    pthread_mutex_unlock (&cache_lock);
-    sfree (name_copy);
-    return (-1);
-  }
-
-  ssnprintf (n.message, sizeof (n.message),
-      "%s has not been updated for %i seconds.", name,
-      (int) (n.time - ce->last_update));
-
-  pthread_mutex_unlock (&cache_lock);
-
-  plugin_dispatch_notification (&n);
-
-  return (0);
-} /* int uc_send_notification */
-
 static void uc_check_range (const data_set_t *ds, cache_entry_t *ce)
 {
   int i;
@@ -258,7 +183,7 @@ static int uc_insert (const data_set_t *ds, const value_list_t *vl,
        ce->values_gauge[i] = NAN;
        if (vl->interval > 0)
          ce->values_gauge[i] = ((double) vl->values[i].absolute)
-           / ((double) vl->interval);
+           / CDTIME_T_TO_DOUBLE (vl->interval);
        ce->values_raw[i].absolute = vl->values[i].absolute;
        break;
        
@@ -274,7 +199,7 @@ static int uc_insert (const data_set_t *ds, const value_list_t *vl,
   uc_check_range (ds, ce);
 
   ce->last_time = vl->time;
-  ce->last_update = time (NULL);
+  ce->last_update = cdtime ();
   ce->interval = vl->interval;
   ce->state = STATE_OKAY;
 
@@ -300,145 +225,133 @@ int uc_init (void)
 
 int uc_check_timeout (void)
 {
-  time_t now;
+  cdtime_t now;
   cache_entry_t *ce;
 
   char **keys = NULL;
+  cdtime_t *keys_time = NULL;
+  cdtime_t *keys_interval = NULL;
   int keys_len = 0;
 
   char *key;
   c_avl_iterator_t *iter;
+
+  int status;
   int i;
   
   pthread_mutex_lock (&cache_lock);
 
-  now = time (NULL);
+  now = cdtime ();
 
   /* Build a list of entries to be flushed */
   iter = c_avl_get_iterator (cache_tree);
   while (c_avl_iterator_next (iter, (void *) &key, (void *) &ce) == 0)
   {
-    /* If entry has not been updated, add to `keys' array */
-    if ((now - ce->last_update) >= (timeout_g * ce->interval))
-    {
-      char **tmp;
+    char **tmp;
+    cdtime_t *tmp_time;
 
-      tmp = (char **) realloc ((void *) keys,
-         (keys_len + 1) * sizeof (char *));
-      if (tmp == NULL)
-      {
-       ERROR ("uc_check_timeout: realloc failed.");
-       c_avl_iterator_destroy (iter);
-       sfree (keys);
-       pthread_mutex_unlock (&cache_lock);
-       return (-1);
-      }
-
-      keys = tmp;
-      keys[keys_len] = strdup (key);
-      if (keys[keys_len] == NULL)
-      {
-       ERROR ("uc_check_timeout: strdup failed.");
-       continue;
-      }
-      keys_len++;
-    }
-  } /* while (c_avl_iterator_next) */
-
-  ce = NULL;
-
-  for (i = 0; i < keys_len; i++)
-  {
-    int status;
-
-    status = ut_check_interesting (keys[i]);
+    /* If the entry is fresh enough, continue. */
+    if ((now - ce->last_update) < (ce->interval * timeout_g))
+      continue;
 
-    if (status < 0)
+    /* If entry has not been updated, add to `keys' array */
+    tmp = (char **) realloc ((void *) keys,
+       (keys_len + 1) * sizeof (char *));
+    if (tmp == NULL)
     {
-      ERROR ("uc_check_timeout: ut_check_interesting failed.");
-      sfree (keys[i]);
+      ERROR ("uc_check_timeout: realloc failed.");
       continue;
     }
-    else if (status == 0) /* ``service'' is uninteresting */
+    keys = tmp;
+
+    tmp_time = realloc (keys_time, (keys_len + 1) * sizeof (*keys_time));
+    if (tmp_time == NULL)
     {
-      DEBUG ("uc_check_timeout: %s is missing but ``uninteresting''",
-         keys[i]);
-      ce = NULL;
-      status = c_avl_remove (cache_tree, keys[i],
-         (void *) &key, (void *) &ce);
-      if (status != 0)
-      {
-       ERROR ("uc_check_timeout: c_avl_remove (%s) failed.", keys[i]);
-      }
-      sfree (keys[i]);
-      sfree (key);
-      if (ce != NULL)
-        cache_free (ce);
+      ERROR ("uc_check_timeout: realloc failed.");
       continue;
     }
+    keys_time = tmp_time;
 
-    /* If we get here, the value is ``interesting''. Query the record from the
-     * cache and update the state field. */
-    if (c_avl_get (cache_tree, keys[i], (void *) &ce) != 0)
+    tmp_time = realloc (keys_interval, (keys_len + 1) * sizeof (*keys_interval));
+    if (tmp_time == NULL)
     {
-      ERROR ("uc_check_timeout: cannot get data for %s from cache", keys[i]);
-      /* Do not free `keys[i]' so a notification is sent further down. */
+      ERROR ("uc_check_timeout: realloc failed.");
       continue;
     }
-    assert (ce != NULL);
+    keys_interval = tmp_time;
 
-    if (status == 2) /* persist */
-    {
-      DEBUG ("uc_check_timeout: %s is missing, sending notification.",
-         keys[i]);
-      ce->state = STATE_MISSING;
-      /* Do not free `keys[i]' so a notification is sent further down. */
-    }
-    else if (status == 1) /* do not persist */
+    keys[keys_len] = strdup (key);
+    if (keys[keys_len] == NULL)
     {
-      if (ce->state == STATE_MISSING)
-      {
-       DEBUG ("uc_check_timeout: %s is missing but "
-           "notification has already been sent.",
-           keys[i]);
-       /* Set `keys[i]' to NULL to no notification is sent. */
-       sfree (keys[i]);
-      }
-      else /* (ce->state != STATE_MISSING) */
-      {
-       DEBUG ("uc_check_timeout: %s is missing, sending one notification.",
-           keys[i]);
-       ce->state = STATE_MISSING;
-       /* Do not free `keys[i]' so a notification is sent further down. */
-      }
-    }
-    else
-    {
-      WARNING ("uc_check_timeout: ut_check_interesting (%s) returned "
-         "invalid status %i.",
-         keys[i], status);
-      sfree (keys[i]);
+      ERROR ("uc_check_timeout: strdup failed.");
+      continue;
     }
+    keys_time[keys_len] = ce->last_time;
+    keys_interval[keys_len] = ce->interval;
 
-    /* Make really sure the next iteration doesn't work with this pointer.
-     * There have been too many bugs in the past.. :/  -- octo */
-    ce = NULL;
-  } /* for (keys[i]) */
+    keys_len++;
+  } /* while (c_avl_iterator_next) */
 
   c_avl_iterator_destroy (iter);
-
   pthread_mutex_unlock (&cache_lock);
 
+  if (keys_len == 0)
+    return (0);
+
+  /* Call the "missing" callback for each value. Do this before removing the
+   * value from the cache, so that callbacks can still access the data stored,
+   * including plugin specific meta data, rates, history, …. This must be done
+   * without holding the lock, otherwise we will run into a deadlock if a
+   * plugin calls the cache interface. */
   for (i = 0; i < keys_len; i++)
   {
-    if (keys[i] == NULL)
+    value_list_t vl = VALUE_LIST_INIT;
+
+    vl.values = NULL;
+    vl.values_len = 0;
+    vl.meta = NULL;
+
+    status = parse_identifier_vl (keys[i], &vl);
+    if (status != 0)
+    {
+      ERROR ("uc_check_timeout: parse_identifier_vl (\"%s\") failed.", keys[i]);
+      cache_free (ce);
       continue;
+    }
+
+    vl.time = keys_time[i];
+    vl.interval = keys_interval[i];
+
+    plugin_dispatch_missing (&vl);
+  } /* for (i = 0; i < keys_len; i++) */
+
+  /* Now actually remove all the values from the cache. We don't re-evaluate
+   * the timestamp again, so in theory it is possible we remove a value after
+   * it is updated here. */
+  pthread_mutex_lock (&cache_lock);
+  for (i = 0; i < keys_len; i++)
+  {
+    key = NULL;
+    ce = NULL;
+
+    status = c_avl_remove (cache_tree, keys[i],
+       (void *) &key, (void *) &ce);
+    if (status != 0)
+    {
+      ERROR ("uc_check_timeout: c_avl_remove (\"%s\") failed.", keys[i]);
+      sfree (keys[i]);
+      continue;
+    }
 
-    uc_send_notification (keys[i]);
     sfree (keys[i]);
-  }
+    sfree (key);
+    cache_free (ce);
+  } /* for (i = 0; i < keys_len; i++) */
+  pthread_mutex_unlock (&cache_lock);
 
   sfree (keys);
+  sfree (keys_time);
+  sfree (keys_interval);
 
   return (0);
 } /* int uc_check_timeout */
@@ -447,9 +360,6 @@ int uc_update (const data_set_t *ds, const value_list_t *vl)
 {
   char name[6 * DATA_MAX_NAME_LEN];
   cache_entry_t *ce = NULL;
-  int send_okay_notification = 0;
-  time_t update_delay = 0;
-  notification_t n;
   int status;
   int i;
 
@@ -475,21 +385,14 @@ int uc_update (const data_set_t *ds, const value_list_t *vl)
   if (ce->last_time >= vl->time)
   {
     pthread_mutex_unlock (&cache_lock);
-    NOTICE ("uc_update: Value too old: name = %s; value time = %u; "
-       "last cache update = %u;",
-       name, (unsigned int) vl->time, (unsigned int) ce->last_time);
+    NOTICE ("uc_update: Value too old: name = %s; value time = %.3f; "
+       "last cache update = %.3f;",
+       name,
+       CDTIME_T_TO_DOUBLE (vl->time),
+       CDTIME_T_TO_DOUBLE (ce->last_time));
     return (-1);
   }
 
-  /* Send a notification (after the lock has been released) if we switch the
-   * state from something else to `okay'. */
-  if (ce->state == STATE_MISSING)
-  {
-    send_okay_notification = 1;
-    ce->state = STATE_OKAY;
-    update_delay = time (NULL) - ce->last_update;
-  }
-
   for (i = 0; i < ds->ds_num; i++)
   {
     switch (ds->ds[i].type)
@@ -514,7 +417,7 @@ int uc_update (const data_set_t *ds, const value_list_t *vl)
          }
 
          ce->values_gauge[i] = ((double) diff)
-           / ((double) (vl->time - ce->last_time));
+           / (CDTIME_T_TO_DOUBLE (vl->time - ce->last_time));
          ce->values_raw[i].counter = vl->values[i].counter;
        }
        break;
@@ -531,14 +434,14 @@ int uc_update (const data_set_t *ds, const value_list_t *vl)
          diff = vl->values[i].derive - ce->values_raw[i].derive;
 
          ce->values_gauge[i] = ((double) diff)
-           / ((double) (vl->time - ce->last_time));
+           / (CDTIME_T_TO_DOUBLE (vl->time - ce->last_time));
          ce->values_raw[i].derive = vl->values[i].derive;
        }
        break;
 
       case DS_TYPE_ABSOLUTE:
        ce->values_gauge[i] = ((double) vl->values[i].absolute)
-         / ((double) (vl->time - ce->last_time));
+         / (CDTIME_T_TO_DOUBLE (vl->time - ce->last_time));
        ce->values_raw[i].absolute = vl->values[i].absolute;
        break;
 
@@ -571,33 +474,11 @@ int uc_update (const data_set_t *ds, const value_list_t *vl)
   uc_check_range (ds, ce);
 
   ce->last_time = vl->time;
-  ce->last_update = time (NULL);
+  ce->last_update = cdtime ();
   ce->interval = vl->interval;
 
   pthread_mutex_unlock (&cache_lock);
 
-  if (send_okay_notification == 0)
-    return (0);
-
-  /* Do not send okay notifications for uninteresting values, i. e. values for
-   * which no threshold is configured. */
-  status = ut_check_interesting (name);
-  if (status <= 0)
-    return (0);
-
-  /* Initialize the notification */
-  memset (&n, '\0', sizeof (n));
-  NOTIFICATION_INIT_VL (&n, vl, ds);
-
-  n.severity = NOTIF_OKAY;
-  n.time = vl->time;
-
-  ssnprintf (n.message, sizeof (n.message),
-      "Received a value for %s. It was missing for %u seconds.",
-      name, (unsigned int) update_delay);
-
-  plugin_dispatch_notification (&n);
-
   return (0);
 } /* int uc_update */
 
@@ -682,15 +563,16 @@ gauge_t *uc_get_rate (const data_set_t *ds, const value_list_t *vl)
   return (ret);
 } /* gauge_t *uc_get_rate */
 
-int uc_get_names (char ***ret_names, time_t **ret_times, size_t *ret_number)
+int uc_get_names (char ***ret_names, cdtime_t **ret_times, size_t *ret_number)
 {
   c_avl_iterator_t *iter;
   char *key;
   cache_entry_t *value;
 
   char **names = NULL;
-  time_t *times = NULL;
+  cdtime_t *times = NULL;
   size_t number = 0;
+  size_t size_arrays = 0;
 
   int status = 0;
 
@@ -699,42 +581,47 @@ int uc_get_names (char ***ret_names, time_t **ret_times, size_t *ret_number)
 
   pthread_mutex_lock (&cache_lock);
 
+  size_arrays = (size_t) c_avl_size (cache_tree);
+  if (size_arrays < 1)
+  {
+    /* Handle the "no values" case here, to avoid the error message when
+     * calloc() returns NULL. */
+    pthread_mutex_unlock (&cache_lock);
+    return (0);
+  }
+
+  names = calloc (size_arrays, sizeof (*names));
+  times = calloc (size_arrays, sizeof (*times));
+  if ((names == NULL) || (times == NULL))
+  {
+    ERROR ("uc_get_names: calloc failed.");
+    sfree (names);
+    sfree (times);
+    pthread_mutex_unlock (&cache_lock);
+    return (ENOMEM);
+  }
+
   iter = c_avl_get_iterator (cache_tree);
   while (c_avl_iterator_next (iter, (void *) &key, (void *) &value) == 0)
   {
-    char **temp;
-
     /* remove missing values when list values */
     if (value->state == STATE_MISSING)
       continue;
 
-    if (ret_times != NULL)
-    {
-      time_t *tmp_times;
+    /* c_avl_size does not return a number smaller than the number of elements
+     * returned by c_avl_iterator_next. */
+    assert (number < size_arrays);
 
-      tmp_times = (time_t *) realloc (times, sizeof (time_t) * (number + 1));
-      if (tmp_times == NULL)
-      {
-       status = -1;
-       break;
-      }
-      times = tmp_times;
+    if (ret_times != NULL)
       times[number] = value->last_time;
-    }
 
-    temp = (char **) realloc (names, sizeof (char *) * (number + 1));
-    if (temp == NULL)
-    {
-      status = -1;
-      break;
-    }
-    names = temp;
     names[number] = strdup (key);
     if (names[number] == NULL)
     {
       status = -1;
       break;
     }
+
     number++;
   } /* while (c_avl_iterator_next) */
 
index f8059ec..87f93c0 100644 (file)
@@ -35,7 +35,7 @@ int uc_update (const data_set_t *ds, const value_list_t *vl);
 int uc_get_rate_by_name (const char *name, gauge_t **ret_values, size_t *ret_values_num);
 gauge_t *uc_get_rate (const data_set_t *ds, const value_list_t *vl);
 
-int uc_get_names (char ***ret_names, time_t **ret_times, size_t *ret_number);
+int uc_get_names (char ***ret_names, cdtime_t **ret_times, size_t *ret_number);
 
 int uc_get_state (const data_set_t *ds, const value_list_t *vl);
 int uc_set_state (const data_set_t *ds, const value_list_t *vl, int state);
index 0e7b350..3584f3b 100644 (file)
@@ -54,7 +54,7 @@ int handle_flush (FILE *fh, char *buffer)
        int success = 0;
        int error   = 0;
 
-       int timeout = -1;
+       double timeout = 0.0;
        char **plugins = NULL;
        int plugins_num = 0;
        char **identifiers = NULL;
@@ -106,9 +106,9 @@ int handle_flush (FILE *fh, char *buffer)
                        
                        errno = 0;
                        endptr = NULL;
-                       timeout = strtol (opt_value, &endptr, 0);
+                       timeout = strtod (opt_value, &endptr);
 
-                       if ((endptr == opt_value) || (errno != 0))
+                       if ((endptr == opt_value) || (errno != 0) || (!isfinite (timeout)))
                        {
                                print_to_socket (fh, "-1 Invalid value for option `timeout': "
                                                "%s\n", opt_value);
@@ -116,8 +116,10 @@ int handle_flush (FILE *fh, char *buffer)
                                sfree (identifiers);
                                return (-1);
                        }
-                       else if (timeout <= 0)
-                               timeout = -1;
+                       else if (timeout < 0.0)
+                       {
+                               timeout = 0.0;
+                       }
                }
                else
                {
@@ -149,7 +151,9 @@ int handle_flush (FILE *fh, char *buffer)
                        int status;
 
                        identifier = identifiers[j];
-                       status = plugin_flush (plugin, timeout, identifier);
+                       status = plugin_flush (plugin,
+                                       DOUBLE_TO_CDTIME_T (timeout),
+                                       identifier);
                        if (status == 0)
                                success++;
                        else
index 4ca9646..ef66af5 100644 (file)
@@ -50,7 +50,7 @@ int handle_listval (FILE *fh, char *buffer)
 {
   char *command;
   char **names = NULL;
-  time_t *times = NULL;
+  cdtime_t *times = NULL;
   size_t number = 0;
   size_t i;
   int status;
@@ -90,7 +90,8 @@ int handle_listval (FILE *fh, char *buffer)
   print_to_socket (fh, "%i Value%s found\n",
       (int) number, (number == 1) ? "" : "s");
   for (i = 0; i < number; i++)
-    print_to_socket (fh, "%u %s\n", (unsigned int) times[i], names[i]);
+    print_to_socket (fh, "%.3f %s\n", CDTIME_T_TO_DOUBLE (times[i]),
+               names[i]);
 
   free_everything_and_return (0);
 } /* int handle_listval */
index 15cd939..4cbc2f1 100644 (file)
@@ -56,16 +56,16 @@ static int set_option (value_list_t *vl, const char *key, const char *value)
 
        if (strcasecmp ("interval", key) == 0)
        {
-               int tmp;
+               double tmp;
                char *endptr;
 
                endptr = NULL;
                errno = 0;
-               tmp = strtol (value, &endptr, 0);
+               tmp = strtod (value, &endptr);
 
                if ((errno == 0) && (endptr != NULL)
-                               && (endptr != value) && (tmp > 0))
-                       vl->interval = tmp;
+                               && (endptr != value) && (tmp > 0.0))
+                       vl->interval = DOUBLE_TO_CDTIME_T (tmp);
        }
        else
                return (1);
@@ -246,9 +246,11 @@ int create_putval (char *ret, size_t ret_len, /* {{{ */
        escape_string (buffer_values, sizeof (buffer_values));
 
        ssnprintf (ret, ret_len,
-                       "PUTVAL %s interval=%i %s",
+                       "PUTVAL %s interval=%.3f %s",
                        buffer_ident,
-                       (vl->interval > 0) ? vl->interval : interval_g,
+                       (vl->interval > 0)
+                       ? CDTIME_T_TO_DOUBLE (vl->interval)
+                       : CDTIME_T_TO_DOUBLE (plugin_get_interval ()),
                        buffer_values);
 
        return (0);
index 9074b18..328a6ab 100644 (file)
@@ -39,8 +39,8 @@ static int vcomplain (int level, c_complain_t *c,
 
        c->last = now;
 
-       if (c->interval < interval_g)
-               c->interval = interval_g;
+       if (c->interval < plugin_get_interval ())
+               c->interval = plugin_get_interval ();
        else
                c->interval *= 2;
 
index 78c8052..aadf9c5 100644 (file)
@@ -73,7 +73,7 @@ struct udb_query_preparation_area_s /* {{{ */
   char *plugin;
   char *db_name;
 
-  int interval;
+  cdtime_t interval;
 
   udb_result_preparation_area_t *result_prep_areas;
 }; /* }}} */
@@ -184,7 +184,7 @@ static int udb_config_set_uint (unsigned int *ret_value, /* {{{ */
  */
 static int udb_result_submit (udb_result_t *r, /* {{{ */
     udb_result_preparation_area_t *r_area,
-    const udb_query_t const *q, udb_query_preparation_area_t *q_area)
+    udb_query_t const *q, udb_query_preparation_area_t *q_area)
 {
   value_list_t vl = VALUE_LIST_INIT;
   size_t i;
@@ -219,7 +219,7 @@ static int udb_result_submit (udb_result_t *r, /* {{{ */
 
   sstrncpy (vl.host, q_area->host, sizeof (vl.host));
   sstrncpy (vl.plugin, q_area->plugin, sizeof (vl.plugin));
-  sstrncpy (vl.plugin_instance, q_area->db_name, sizeof (vl.type_instance));
+  sstrncpy (vl.plugin_instance, q_area->db_name, sizeof (vl.plugin_instance));
   sstrncpy (vl.type, r->type, sizeof (vl.type));
 
   /* Set vl.type_instance {{{ */
@@ -259,7 +259,7 @@ static int udb_result_submit (udb_result_t *r, /* {{{ */
   return (0);
 } /* }}} void udb_result_submit */
 
-static void udb_result_finish_result (const udb_result_t const *r, /* {{{ */
+static void udb_result_finish_result (udb_result_t const *r, /* {{{ */
     udb_result_preparation_area_t *prep_area)
 {
   if ((r == NULL) || (prep_area == NULL))
@@ -275,7 +275,7 @@ static void udb_result_finish_result (const udb_result_t const *r, /* {{{ */
 static int udb_result_handle_result (udb_result_t *r, /* {{{ */
     udb_query_preparation_area_t *q_area,
     udb_result_preparation_area_t *r_area,
-    const udb_query_t const *q, char **column_values)
+    udb_query_t const *q, char **column_values)
 {
   size_t i;
 
@@ -290,7 +290,7 @@ static int udb_result_handle_result (udb_result_t *r, /* {{{ */
   return udb_result_submit (r, r_area, q, q_area);
 } /* }}} int udb_result_handle_result */
 
-static int udb_result_prepare_result (const udb_result_t const *r, /* {{{ */
+static int udb_result_prepare_result (udb_result_t const *r, /* {{{ */
     udb_result_preparation_area_t *prep_area,
     char **column_names, size_t column_num)
 {
@@ -825,7 +825,7 @@ int udb_query_check_version (udb_query_t *q, unsigned int version) /* {{{ */
   return (1);
 } /* }}} int udb_query_check_version */
 
-void udb_query_finish_result (const udb_query_t const *q, /* {{{ */
+void udb_query_finish_result (udb_query_t const *q, /* {{{ */
     udb_query_preparation_area_t *prep_area)
 {
   udb_result_preparation_area_t *r_area;
@@ -839,7 +839,7 @@ void udb_query_finish_result (const udb_query_t const *q, /* {{{ */
   sfree (prep_area->plugin);
   sfree (prep_area->db_name);
 
-  prep_area->interval = -1;
+  prep_area->interval = 0;
 
   for (r = q->results, r_area = prep_area->result_prep_areas;
       r != NULL; r = r->next, r_area = r_area->next)
@@ -851,7 +851,7 @@ void udb_query_finish_result (const udb_query_t const *q, /* {{{ */
   }
 } /* }}} void udb_query_finish_result */
 
-int udb_query_handle_result (const udb_query_t const *q, /* {{{ */
+int udb_query_handle_result (udb_query_t const *q, /* {{{ */
     udb_query_preparation_area_t *prep_area, char **column_values)
 {
   udb_result_preparation_area_t *r_area;
@@ -904,10 +904,10 @@ int udb_query_handle_result (const udb_query_t const *q, /* {{{ */
   return (0);
 } /* }}} int udb_query_handle_result */
 
-int udb_query_prepare_result (const udb_query_t const *q, /* {{{ */
+int udb_query_prepare_result (udb_query_t const *q, /* {{{ */
     udb_query_preparation_area_t *prep_area,
     const char *host, const char *plugin, const char *db_name,
-    char **column_names, size_t column_num, int interval)
+    char **column_names, size_t column_num, cdtime_t interval)
 {
   udb_result_preparation_area_t *r_area;
   udb_result_t *r;
index 846f81c..b6f4cea 100644 (file)
@@ -65,13 +65,13 @@ void *udb_query_get_user_data (udb_query_t *q);
  */
 int udb_query_check_version (udb_query_t *q, unsigned int version);
 
-int udb_query_prepare_result (const udb_query_t const *q,
+int udb_query_prepare_result (udb_query_t const *q,
     udb_query_preparation_area_t *prep_area,
     const char *host, const char *plugin, const char *db_name,
-    char **column_names, size_t column_num, int interval);
-int udb_query_handle_result (const udb_query_t const *q,
+    char **column_names, size_t column_num, cdtime_t interval);
+int udb_query_handle_result (udb_query_t const *q,
     udb_query_preparation_area_t *prep_area, char **column_values);
-void udb_query_finish_result (const udb_query_t const *q,
+void udb_query_finish_result (udb_query_t const *q,
     udb_query_preparation_area_t *prep_area);
 
 udb_query_preparation_area_t *
index 22c9b95..80a2ee5 100644 (file)
 #if HAVE_NETINET_IN_H
 # include <netinet/in.h>
 #endif
+#if HAVE_NETINET_IP6_H
+# include <netinet/ip6.h>
+#endif
+#if HAVE_NETINET_IP_COMPAT_H
+# include <netinet/ip_compat.h>
+#endif
 #if HAVE_ARPA_INET_H
 # include <arpa/inet.h>
 #endif
 
 #if HAVE_STRUCT_UDPHDR_UH_DPORT && HAVE_STRUCT_UDPHDR_UH_SPORT
 # define UDP_DEST uh_dport
-# define UDP_SRC  uh_dport
+# define UDP_SRC  uh_sport
 #elif HAVE_STRUCT_UDPHDR_DEST && HAVE_STRUCT_UDPHDR_SOURCE
 # define UDP_DEST dest
 # define UDP_SRC  source
@@ -441,6 +447,7 @@ handle_udp(const struct udphdr *udp, int len)
     return 1;
 }
 
+#if HAVE_NETINET_IP6_H
 static int
 handle_ipv6 (struct ip6_hdr *ipv6, int len)
 {
@@ -448,8 +455,7 @@ handle_ipv6 (struct ip6_hdr *ipv6, int len)
     unsigned int offset;
     int nexthdr;
 
-    struct in6_addr s_addr;
-    struct in6_addr d_addr;
+    struct in6_addr c_src_addr;
     uint16_t payload_len;
 
     if (0 > len)
@@ -457,11 +463,10 @@ handle_ipv6 (struct ip6_hdr *ipv6, int len)
 
     offset = sizeof (struct ip6_hdr);
     nexthdr = ipv6->ip6_nxt;
-    s_addr = ipv6->ip6_src;
-    d_addr = ipv6->ip6_dst;
+    c_src_addr = ipv6->ip6_src;
     payload_len = ntohs (ipv6->ip6_plen);
 
-    if (ignore_list_match (&s_addr))
+    if (ignore_list_match (&c_src_addr))
            return (0);
 
     /* Parse extension headers. This only handles the standard headers, as
@@ -470,7 +475,6 @@ handle_ipv6 (struct ip6_hdr *ipv6, int len)
            || (IPPROTO_HOPOPTS == nexthdr) /* Hop-by-Hop options. */
            || (IPPROTO_FRAGMENT == nexthdr) /* fragmentation header. */
            || (IPPROTO_DSTOPTS == nexthdr) /* destination options. */
-           || (IPPROTO_DSTOPTS == nexthdr) /* destination options. */
            || (IPPROTO_AH == nexthdr) /* destination options. */
            || (IPPROTO_ESP == nexthdr)) /* encapsulating security payload. */
     {
@@ -512,21 +516,31 @@ handle_ipv6 (struct ip6_hdr *ipv6, int len)
 
     return (1); /* Success */
 } /* int handle_ipv6 */
+/* #endif HAVE_NETINET_IP6_H */
+
+#else /* if !HAVE_NETINET_IP6_H */
+static int
+handle_ipv6 (__attribute__((unused)) void *pkg,
+       __attribute__((unused)) int len)
+{
+    return (0);
+}
+#endif /* !HAVE_NETINET_IP6_H */
 
 static int
 handle_ip(const struct ip *ip, int len)
 {
     char buf[PCAP_SNAPLEN];
     int offset = ip->ip_hl << 2;
-    struct in6_addr s_addr;
-    struct in6_addr d_addr;
+    struct in6_addr c_src_addr;
+    struct in6_addr c_dst_addr;
 
     if (ip->ip_v == 6)
-       return (handle_ipv6 ((struct ip6_hdr *) ip, len));
+       return (handle_ipv6 ((void *) ip, len));
 
-    in6_addr_from_buffer (&s_addr, &ip->ip_src.s_addr, sizeof (ip->ip_src.s_addr), AF_INET);
-    in6_addr_from_buffer (&d_addr, &ip->ip_dst.s_addr, sizeof (ip->ip_dst.s_addr), AF_INET);
-    if (ignore_list_match (&s_addr))
+    in6_addr_from_buffer (&c_src_addr, &ip->ip_src.s_addr, sizeof (ip->ip_src.s_addr), AF_INET);
+    in6_addr_from_buffer (&c_dst_addr, &ip->ip_dst.s_addr, sizeof (ip->ip_dst.s_addr), AF_INET);
+    if (ignore_list_match (&c_src_addr))
            return (0);
     if (IPPROTO_UDP != ip->ip_p)
        return 0;
@@ -620,7 +634,7 @@ handle_ether(const u_char * pkt, int len)
        return 0;
     memcpy(buf, pkt, len);
     if (ETHERTYPE_IPV6 == etype)
-       return (handle_ipv6 ((struct ip6_hdr *) buf, len));
+       return (handle_ipv6 ((void *) buf, len));
     else
        return handle_ip((struct ip *) buf, len);
 }
@@ -653,7 +667,7 @@ handle_linux_sll (const u_char *pkt, int len)
        return 0;
 
     if (ETHERTYPE_IPV6 == etype)
-       return (handle_ipv6 ((struct ip6_hdr *) pkt, len));
+       return (handle_ipv6 ((void *) pkt, len));
     else
        return handle_ip((struct ip *) pkt, len);
 }
index d20b7e3..97f21a1 100644 (file)
@@ -234,6 +234,7 @@ void fbh_destroy (fbhash_t *h) /* {{{ */
   if (h == NULL)
     return;
 
+  pthread_mutex_destroy (&h->lock);
   free (h->filename);
   fbh_free_tree (h->tree);
 } /* }}} void fbh_destroy */
diff --git a/src/utils_format_graphite.c b/src/utils_format_graphite.c
new file mode 100644 (file)
index 0000000..b9b906f
--- /dev/null
@@ -0,0 +1,240 @@
+/**
+ * collectd - src/utils_format_graphite.c
+ * Copyright (C) 2012  Thomas Meson
+ * Copyright (C) 2012  Florian octo Forster
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; only version 2 of the License is applicable.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Authors:
+ *   Thomas Meson <zllak at hycik.org>
+ *   Florian octo Forster <octo at collectd.org>
+ **/
+
+#include "collectd.h"
+#include "plugin.h"
+#include "common.h"
+
+#include "utils_cache.h"
+#include "utils_format_json.h"
+#include "utils_parse_option.h"
+
+/* Utils functions to format data sets in graphite format.
+ * Largely taken from write_graphite.c as it remains the same formatting */
+
+static int gr_format_values (char *ret, size_t ret_len,
+        int ds_num, const data_set_t *ds, const value_list_t *vl,
+        gauge_t const *rates)
+{
+    size_t offset = 0;
+    int status;
+
+    assert (0 == strcmp (ds->type, vl->type));
+
+    memset (ret, 0, ret_len);
+
+#define BUFFER_ADD(...) do { \
+    status = ssnprintf (ret + offset, ret_len - offset, \
+            __VA_ARGS__); \
+    if (status < 1) \
+    { \
+        return (-1); \
+    } \
+    else if (((size_t) status) >= (ret_len - offset)) \
+    { \
+        return (-1); \
+    } \
+    else \
+    offset += ((size_t) status); \
+} while (0)
+
+    if (ds->ds[ds_num].type == DS_TYPE_GAUGE)
+        BUFFER_ADD ("%f", vl->values[ds_num].gauge);
+    else if (rates != NULL)
+        BUFFER_ADD ("%f", rates[ds_num]);
+    else if (ds->ds[ds_num].type == DS_TYPE_COUNTER)
+        BUFFER_ADD ("%llu", vl->values[ds_num].counter);
+    else if (ds->ds[ds_num].type == DS_TYPE_DERIVE)
+        BUFFER_ADD ("%"PRIi64, vl->values[ds_num].derive);
+    else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE)
+        BUFFER_ADD ("%"PRIu64, vl->values[ds_num].absolute);
+    else
+    {
+        ERROR ("gr_format_values plugin: Unknown data source type: %i",
+                ds->ds[ds_num].type);
+        return (-1);
+    }
+
+#undef BUFFER_ADD
+
+    return (0);
+}
+
+static void gr_copy_escape_part (char *dst, const char *src, size_t dst_len,
+    char escape_char)
+{
+    size_t i;
+
+    memset (dst, 0, dst_len);
+
+    if (src == NULL)
+        return;
+
+    for (i = 0; i < dst_len; i++)
+    {
+        if (src[i] == 0)
+        {
+            dst[i] = 0;
+            break;
+        }
+
+        if ((src[i] == '.')
+                || isspace ((int) src[i])
+                || iscntrl ((int) src[i]))
+            dst[i] = escape_char;
+        else
+            dst[i] = src[i];
+    }
+}
+
+static int gr_format_name (char *ret, int ret_len,
+        const value_list_t *vl,
+        const char *ds_name,
+        char *prefix,
+        char *postfix,
+        char escape_char)
+{
+    char n_host[DATA_MAX_NAME_LEN];
+    char n_plugin[DATA_MAX_NAME_LEN];
+    char n_plugin_instance[DATA_MAX_NAME_LEN];
+    char n_type[DATA_MAX_NAME_LEN];
+    char n_type_instance[DATA_MAX_NAME_LEN];
+
+    char tmp_plugin[2 * DATA_MAX_NAME_LEN + 1];
+    char tmp_type[2 * DATA_MAX_NAME_LEN + 1];
+
+    if (prefix == NULL)
+        prefix = "";
+
+    if (postfix == NULL)
+        postfix = "";
+
+    gr_copy_escape_part (n_host, vl->host,
+            sizeof (n_host), escape_char);
+    gr_copy_escape_part (n_plugin, vl->plugin,
+            sizeof (n_plugin), escape_char);
+    gr_copy_escape_part (n_plugin_instance, vl->plugin_instance,
+            sizeof (n_plugin_instance), escape_char);
+    gr_copy_escape_part (n_type, vl->type,
+            sizeof (n_type), escape_char);
+    gr_copy_escape_part (n_type_instance, vl->type_instance,
+            sizeof (n_type_instance), escape_char);
+
+    if (n_plugin_instance[0] != '\0')
+        ssnprintf (tmp_plugin, sizeof (tmp_plugin), "%s%c%s",
+            n_plugin,
+            '-',
+            n_plugin_instance);
+    else
+        sstrncpy (tmp_plugin, n_plugin, sizeof (tmp_plugin));
+
+    if (n_type_instance[0] != '\0')
+        ssnprintf (tmp_type, sizeof (tmp_type), "%s%c%s",
+            n_type,
+            '-',
+            n_type_instance);
+    else
+        sstrncpy (tmp_type, n_type, sizeof (tmp_type));
+
+    if (ds_name != NULL)
+        ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s",
+            prefix, n_host, postfix, tmp_plugin, tmp_type, ds_name);
+    else
+        ssnprintf (ret, ret_len, "%s%s%s.%s.%s",
+            prefix, n_host, postfix, tmp_plugin, tmp_type);
+
+    return (0);
+}
+
+int format_graphite (char *buffer, size_t buffer_size,
+    const data_set_t *ds, const value_list_t *vl, char *prefix,
+    char *postfix, char escape_char,
+    _Bool store_rates)
+{
+    int status = 0;
+    int i;
+    int buffer_pos = 0;
+
+    gauge_t *rates = NULL;
+    if (store_rates)
+      rates = uc_get_rate (ds, vl);
+
+    for (i = 0; i < ds->ds_num; i++)
+    {
+        const char *ds_name = NULL;
+        char        key[10*DATA_MAX_NAME_LEN];
+        char        values[512];
+        size_t      message_len;
+        char        message[1024];
+
+        ds_name = ds->ds[i].name;
+
+        /* Copy the identifier to `key' and escape it. */
+        status = gr_format_name (key, sizeof (key), vl, ds_name,
+                    prefix, postfix, escape_char);
+        if (status != 0)
+        {
+            ERROR ("format_graphite: error with gr_format_name");
+            sfree (rates);
+            return (status);
+        }
+
+        escape_string (key, sizeof (key));
+        /* Convert the values to an ASCII representation and put that into
+         * `values'. */
+        status = gr_format_values (values, sizeof (values), i, ds, vl, rates);
+        if (status != 0)
+        {
+            ERROR ("format_graphite: error with gr_format_values");
+            sfree (rates);
+            return (status);
+        }
+
+        /* Compute the graphite command */
+        message_len = (size_t) ssnprintf (message, sizeof (message),
+                "%s %s %u\r\n",
+                key,
+                values,
+                (unsigned int) CDTIME_T_TO_TIME_T (vl->time));
+        if (message_len >= sizeof (message)) {
+            ERROR ("format_graphite: message buffer too small: "
+                    "Need %zu bytes.", message_len + 1);
+            sfree (rates);
+            return (-ENOMEM);
+        }
+
+        /* Append it in case we got multiple data set */
+        if ((buffer_pos + message_len) >= buffer_size)
+        {
+            ERROR ("format_graphite: target buffer too small");
+            sfree (rates);
+            return (-ENOMEM);
+        }
+        memcpy((void *) (buffer + buffer_pos), message, message_len);
+        buffer_pos += message_len;
+    }
+    sfree (rates);
+    return (status);
+} /* int format_graphite */
+
+/* vim: set sw=2 sts=2 et fdm=marker : */
diff --git a/src/utils_format_graphite.h b/src/utils_format_graphite.h
new file mode 100644 (file)
index 0000000..a7a05bb
--- /dev/null
@@ -0,0 +1,34 @@
+/**
+ * collectd - src/utils_format_graphite.h
+ * Copyright (C) 2012  Thomas Meson
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; only version 2 of the License is applicable.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Author:
+ *   Thomas Meson <zllak at hycik.org>
+ **/
+
+#ifndef UTILS_FORMAT_GRAPHITE_H
+#define UTILS_FORMAT_GRAPHITE_H 1
+
+#include "collectd.h"
+#include "plugin.h"
+
+int format_graphite (char *buffer,
+    size_t buffer_size, const data_set_t *ds,
+    const value_list_t *vl, const char *prefix,
+    const char *postfix, const char escape_char,
+    _Bool store_rates);
+
+#endif /* UTILS_FORMAT_GRAPHITE_H */
index ac88c0f..bbc3dfd 100644 (file)
@@ -70,7 +70,7 @@ static int escape_string (char *buffer, size_t buffer_size, /* {{{ */
 #undef BUFFER_ADD
 
   return (0);
-} /* }}} int buffer_add_string */
+} /* }}} int escape_string */
 
 static int values_to_json (char *buffer, size_t buffer_size, /* {{{ */
                 const data_set_t *ds, const value_list_t *vl, int store_rates)
@@ -152,7 +152,7 @@ static int values_to_json (char *buffer, size_t buffer_size, /* {{{ */
 } /* }}} int values_to_json */
 
 static int dstypes_to_json (char *buffer, size_t buffer_size, /* {{{ */
-                const data_set_t *ds, const value_list_t *vl)
+                const data_set_t *ds)
 {
   size_t offset = 0;
   int i;
@@ -189,7 +189,7 @@ static int dstypes_to_json (char *buffer, size_t buffer_size, /* {{{ */
 } /* }}} int dstypes_to_json */
 
 static int dsnames_to_json (char *buffer, size_t buffer_size, /* {{{ */
-                const data_set_t *ds, const value_list_t *vl)
+                const data_set_t *ds)
 {
   size_t offset = 0;
   int i;
@@ -225,6 +225,86 @@ static int dsnames_to_json (char *buffer, size_t buffer_size, /* {{{ */
   return (0);
 } /* }}} int dsnames_to_json */
 
+static int meta_data_to_json (char *buffer, size_t buffer_size, /* {{{ */
+    meta_data_t *meta)
+{
+  size_t offset = 0;
+  char **keys = NULL;
+  int keys_num;
+  int status;
+  int i;
+
+  memset (buffer, 0, buffer_size);
+
+#define BUFFER_ADD(...) do { \
+  status = ssnprintf (buffer + offset, buffer_size - offset, \
+      __VA_ARGS__); \
+  if (status < 1) \
+    return (-1); \
+  else if (((size_t) status) >= (buffer_size - offset)) \
+    return (-ENOMEM); \
+  else \
+    offset += ((size_t) status); \
+} while (0)
+
+  keys_num = meta_data_toc (meta, &keys);
+  for (i = 0; i < keys_num; ++i)
+  {
+    int type;
+    char *key = keys[i];
+
+    type = meta_data_type (meta, key);
+    if (type == MD_TYPE_STRING)
+    {
+      char *value = NULL;
+      if (meta_data_get_string (meta, key, &value) == 0)
+      {
+        char temp[512] = "";
+        escape_string (temp, sizeof (temp), value);
+        sfree (value);
+        BUFFER_ADD (",\"%s\":%s", key, temp);
+      }
+    }
+    else if (type == MD_TYPE_SIGNED_INT)
+    {
+      int64_t value = 0;
+      if (meta_data_get_signed_int (meta, key, &value) == 0)
+        BUFFER_ADD (",\"%s\":%"PRIi64, key, value);
+    }
+    else if (type == MD_TYPE_UNSIGNED_INT)
+    {
+      uint64_t value = 0;
+      if (meta_data_get_unsigned_int (meta, key, &value) == 0)
+        BUFFER_ADD (",\"%s\":%"PRIu64, key, value);
+    }
+    else if (type == MD_TYPE_DOUBLE)
+    {
+      double value = 0.0;
+      if (meta_data_get_double (meta, key, &value) == 0)
+        BUFFER_ADD (",\"%s\":%f", key, value);
+    }
+    else if (type == MD_TYPE_BOOLEAN)
+    {
+      _Bool value = 0;
+      if (meta_data_get_boolean (meta, key, &value) == 0)
+        BUFFER_ADD (",\"%s\":%s", key, value ? "true" : "false");
+    }
+
+    free (key);
+  } /* for (keys) */
+  free (keys);
+
+  if (offset <= 0)
+    return (ENOENT);
+
+  buffer[0] = '{'; /* replace leading ',' */
+  BUFFER_ADD ("}");
+
+#undef BUFFER_ADD
+
+  return (0);
+} /* int meta_data_to_json */
+
 static int value_list_to_json (char *buffer, size_t buffer_size, /* {{{ */
                 const data_set_t *ds, const value_list_t *vl, int store_rates)
 {
@@ -254,18 +334,18 @@ static int value_list_to_json (char *buffer, size_t buffer_size, /* {{{ */
     return (status);
   BUFFER_ADD ("\"values\":%s", temp);
 
-  status = dstypes_to_json (temp, sizeof (temp), ds, vl);
+  status = dstypes_to_json (temp, sizeof (temp), ds);
   if (status != 0)
     return (status);
   BUFFER_ADD (",\"dstypes\":%s", temp);
 
-  status = dsnames_to_json (temp, sizeof (temp), ds, vl);
+  status = dsnames_to_json (temp, sizeof (temp), ds);
   if (status != 0)
     return (status);
   BUFFER_ADD (",\"dsnames\":%s", temp);
 
-  BUFFER_ADD (",\"time\":%lu", (unsigned long) vl->time);
-  BUFFER_ADD (",\"interval\":%i", vl->interval);
+  BUFFER_ADD (",\"time\":%.3f", CDTIME_T_TO_DOUBLE (vl->time));
+  BUFFER_ADD (",\"interval\":%.3f", CDTIME_T_TO_DOUBLE (vl->interval));
 
 #define BUFFER_ADD_KEYVAL(key, value) do { \
   status = escape_string (temp, sizeof (temp), (value)); \
@@ -280,6 +360,17 @@ static int value_list_to_json (char *buffer, size_t buffer_size, /* {{{ */
   BUFFER_ADD_KEYVAL ("type", vl->type);
   BUFFER_ADD_KEYVAL ("type_instance", vl->type_instance);
 
+  if (vl->meta != NULL)
+  {
+    char meta_buffer[buffer_size];
+    memset (meta_buffer, 0, sizeof (meta_buffer));
+    status = meta_data_to_json (meta_buffer, sizeof (meta_buffer), vl->meta);
+    if (status != 0)
+      return (status);
+
+    BUFFER_ADD (",\"meta\":%s", meta_buffer);
+  } /* if (vl->meta != NULL) */
+
   BUFFER_ADD ("}");
 
 #undef BUFFER_ADD_KEYVAL
index 4ecec59..091b5fa 100644 (file)
@@ -103,7 +103,10 @@ static int rra_get (char ***ret, const value_list_t *vl, /* {{{ */
     return (-1);
   }
 
-  ss = (cfg->stepsize > 0) ? cfg->stepsize : vl->interval;
+  if (cfg->stepsize > 0)
+    ss = cfg->stepsize;
+  else
+    ss = (int) CDTIME_T_TO_TIME_T (vl->interval);
   if (ss <= 0)
   {
     *ret = NULL;
@@ -153,7 +156,7 @@ static int rra_get (char ***ret, const value_list_t *vl, /* {{{ */
       if (rra_num >= rra_max)
         break;
 
-      status = ssnprintf (buffer, sizeof (buffer), "RRA:%s:%3.1f:%u:%u",
+      status = ssnprintf (buffer, sizeof (buffer), "RRA:%s:%.10f:%u:%u",
           rra_types[j], cfg->xff, cdp_len, cdp_num);
 
       if ((status < 0) || ((size_t) status >= sizeof (buffer)))
@@ -241,7 +244,9 @@ static int ds_get (char ***ret, /* {{{ */
     status = ssnprintf (buffer, sizeof (buffer),
         "DS:%s:%s:%i:%s:%s",
         d->name, type,
-        (cfg->heartbeat > 0) ? cfg->heartbeat : (2 * vl->interval),
+        (cfg->heartbeat > 0)
+        ? cfg->heartbeat
+        : (int) CDTIME_T_TO_TIME_T (2 * vl->interval),
         min, max);
     if ((status < 1) || ((size_t) status >= sizeof (buffer)))
       break;
@@ -323,7 +328,7 @@ static int srrd_create (const char *filename, /* {{{ */
     last_up = time (NULL) - 10;
 
   ssnprintf (pdp_step_str, sizeof (pdp_step_str), "%lu", pdp_step);
-  ssnprintf (last_up_str, sizeof (last_up_str), "%u", (unsigned int) last_up);
+  ssnprintf (last_up_str, sizeof (last_up_str), "%lu", (unsigned long) last_up);
 
   new_argv[0] = "create";
   new_argv[1] = (void *) filename;
@@ -368,6 +373,8 @@ int cu_rrd_create_file (const char *filename, /* {{{ */
   char **ds_def;
   int ds_num;
   int status = 0;
+  time_t last_up;
+  unsigned long stepsize;
 
   if (check_create_dir (filename))
     return (-1);
@@ -398,10 +405,17 @@ int cu_rrd_create_file (const char *filename, /* {{{ */
   memcpy (argv + ds_num, rra_def, rra_num * sizeof (char *));
   argv[ds_num + rra_num] = NULL;
 
-  assert (vl->time > 10);
-  status = srrd_create (filename,
-      (cfg->stepsize > 0) ? cfg->stepsize : vl->interval,
-      vl->time - 10,
+  last_up = CDTIME_T_TO_TIME_T (vl->time);
+  if (last_up <= 0)
+    last_up = time (NULL);
+  last_up -= 1;
+
+  if (cfg->stepsize > 0)
+    stepsize = cfg->stepsize;
+  else
+    stepsize = (unsigned long) CDTIME_T_TO_TIME_T (vl->interval);
+
+  status = srrd_create (filename, stepsize, last_up,
       argc, (const char **) argv);
 
   free (argv);
index 935e4e0..103ca57 100644 (file)
@@ -28,7 +28,7 @@
 
 struct rrdcreate_config_s
 {
-  int    stepsize;
+  unsigned long stepsize;
   int    heartbeat;
   int    rrarows;
   double xff;
diff --git a/src/utils_threshold.c b/src/utils_threshold.c
deleted file mode 100644 (file)
index 99309b9..0000000
+++ /dev/null
@@ -1,1009 +0,0 @@
-/**
- * collectd - src/utils_threshold.c
- * Copyright (C) 2007-2009  Florian octo Forster
- * Copyright (C) 2008-2009  Sebastian Harl
- * Copyright (C) 2009       Andrés J. Díaz
- *
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- *
- * Author:
- *   Florian octo Forster <octo at verplant.org>
- *   Sebastian Harl <sh at tokkee.org>
- *   Andrés J. Díaz <ajdiaz at connectical.com>
- **/
-
-#include "collectd.h"
-#include "common.h"
-#include "plugin.h"
-#include "utils_avltree.h"
-#include "utils_cache.h"
-#include "utils_threshold.h"
-
-#include <assert.h>
-#include <pthread.h>
-
-/*
- * Private data structures
- * {{{ */
-#define UT_FLAG_INVERT  0x01
-#define UT_FLAG_PERSIST 0x02
-#define UT_FLAG_PERCENTAGE 0x04
-#define UT_FLAG_INTERESTING 0x08
-/* }}} */
-
-/*
- * Private (static) variables
- * {{{ */
-static c_avl_tree_t   *threshold_tree = NULL;
-static pthread_mutex_t threshold_lock = PTHREAD_MUTEX_INITIALIZER;
-/* }}} */
-
-/*
- * Threshold management
- * ====================
- * The following functions add, delete, search, etc. configured thresholds to
- * the underlying AVL trees.
- * {{{ */
-static threshold_t *threshold_get (const char *hostname,
-    const char *plugin, const char *plugin_instance,
-    const char *type, const char *type_instance)
-{
-  char name[6 * DATA_MAX_NAME_LEN];
-  threshold_t *th = NULL;
-
-  format_name (name, sizeof (name),
-      (hostname == NULL) ? "" : hostname,
-      (plugin == NULL) ? "" : plugin, plugin_instance,
-      (type == NULL) ? "" : type, type_instance);
-  name[sizeof (name) - 1] = '\0';
-
-  if (c_avl_get (threshold_tree, name, (void *) &th) == 0)
-    return (th);
-  else
-    return (NULL);
-} /* threshold_t *threshold_get */
-
-static int ut_threshold_add (const threshold_t *th)
-{
-  char name[6 * DATA_MAX_NAME_LEN];
-  char *name_copy;
-  threshold_t *th_copy;
-  threshold_t *th_ptr;
-  int status = 0;
-
-  if (format_name (name, sizeof (name), th->host,
-       th->plugin, th->plugin_instance,
-       th->type, th->type_instance) != 0)
-  {
-    ERROR ("ut_threshold_add: format_name failed.");
-    return (-1);
-  }
-
-  name_copy = strdup (name);
-  if (name_copy == NULL)
-  {
-    ERROR ("ut_threshold_add: strdup failed.");
-    return (-1);
-  }
-
-  th_copy = (threshold_t *) malloc (sizeof (threshold_t));
-  if (th_copy == NULL)
-  {
-    sfree (name_copy);
-    ERROR ("ut_threshold_add: malloc failed.");
-    return (-1);
-  }
-  memcpy (th_copy, th, sizeof (threshold_t));
-  th_ptr = NULL;
-
-  DEBUG ("ut_threshold_add: Adding entry `%s'", name);
-
-  pthread_mutex_lock (&threshold_lock);
-
-  th_ptr = threshold_get (th->host, th->plugin, th->plugin_instance,
-      th->type, th->type_instance);
-
-  while ((th_ptr != NULL) && (th_ptr->next != NULL))
-    th_ptr = th_ptr->next;
-
-  if (th_ptr == NULL) /* no such threshold yet */
-  {
-    status = c_avl_insert (threshold_tree, name_copy, th_copy);
-  }
-  else /* th_ptr points to the last threshold in the list */
-  {
-    th_ptr->next = th_copy;
-    /* name_copy isn't needed */
-    sfree (name_copy);
-  }
-
-  pthread_mutex_unlock (&threshold_lock);
-
-  if (status != 0)
-  {
-    ERROR ("ut_threshold_add: c_avl_insert (%s) failed.", name);
-    sfree (name_copy);
-    sfree (th_copy);
-  }
-
-  return (status);
-} /* int ut_threshold_add */
-/*
- * End of the threshold management functions
- * }}} */
-
-/*
- * Configuration
- * =============
- * The following approximately two hundred functions are used to handle the
- * configuration and fill the threshold list.
- * {{{ */
-static int ut_config_type_datasource (threshold_t *th, oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_STRING))
-  {
-    WARNING ("threshold values: The `DataSource' option needs exactly one "
-       "string argument.");
-    return (-1);
-  }
-
-  sstrncpy (th->data_source, ci->values[0].value.string,
-      sizeof (th->data_source));
-
-  return (0);
-} /* int ut_config_type_datasource */
-
-static int ut_config_type_instance (threshold_t *th, oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_STRING))
-  {
-    WARNING ("threshold values: The `Instance' option needs exactly one "
-       "string argument.");
-    return (-1);
-  }
-
-  sstrncpy (th->type_instance, ci->values[0].value.string,
-      sizeof (th->type_instance));
-
-  return (0);
-} /* int ut_config_type_instance */
-
-static int ut_config_type_max (threshold_t *th, oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
-  {
-    WARNING ("threshold values: The `%s' option needs exactly one "
-       "number argument.", ci->key);
-    return (-1);
-  }
-
-  if (strcasecmp (ci->key, "WarningMax") == 0)
-    th->warning_max = ci->values[0].value.number;
-  else
-    th->failure_max = ci->values[0].value.number;
-
-  return (0);
-} /* int ut_config_type_max */
-
-static int ut_config_type_min (threshold_t *th, oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
-  {
-    WARNING ("threshold values: The `%s' option needs exactly one "
-       "number argument.", ci->key);
-    return (-1);
-  }
-
-  if (strcasecmp (ci->key, "WarningMin") == 0)
-    th->warning_min = ci->values[0].value.number;
-  else
-    th->failure_min = ci->values[0].value.number;
-
-  return (0);
-} /* int ut_config_type_min */
-
-static int ut_config_type_hits (threshold_t *th, oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
-  {
-    WARNING ("threshold values: The `%s' option needs exactly one "
-      "number argument.", ci->key);
-    return (-1);
-  }
-
-  th->hits = ci->values[0].value.number;
-
-  return (0);
-} /* int ut_config_type_hits */
-
-static int ut_config_type_hysteresis (threshold_t *th, oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
-  {
-    WARNING ("threshold values: The `%s' option needs exactly one "
-      "number argument.", ci->key);
-    return (-1);
-  }
-
-  th->hysteresis = ci->values[0].value.number;
-
-  return (0);
-} /* int ut_config_type_hysteresis */
-
-static int ut_config_type (const threshold_t *th_orig, oconfig_item_t *ci)
-{
-  int i;
-  threshold_t th;
-  int status = 0;
-
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_STRING))
-  {
-    WARNING ("threshold values: The `Type' block needs exactly one string "
-       "argument.");
-    return (-1);
-  }
-
-  if (ci->children_num < 1)
-  {
-    WARNING ("threshold values: The `Type' block needs at least one option.");
-    return (-1);
-  }
-
-  memcpy (&th, th_orig, sizeof (th));
-  sstrncpy (th.type, ci->values[0].value.string, sizeof (th.type));
-
-  th.warning_min = NAN;
-  th.warning_max = NAN;
-  th.failure_min = NAN;
-  th.failure_max = NAN;
-  th.hits = 0;
-  th.hysteresis = 0;
-  th.flags = UT_FLAG_INTERESTING; /* interesting by default */
-
-  for (i = 0; i < ci->children_num; i++)
-  {
-    oconfig_item_t *option = ci->children + i;
-    status = 0;
-
-    if (strcasecmp ("Instance", option->key) == 0)
-      status = ut_config_type_instance (&th, option);
-    else if (strcasecmp ("DataSource", option->key) == 0)
-      status = ut_config_type_datasource (&th, option);
-    else if ((strcasecmp ("WarningMax", option->key) == 0)
-       || (strcasecmp ("FailureMax", option->key) == 0))
-      status = ut_config_type_max (&th, option);
-    else if ((strcasecmp ("WarningMin", option->key) == 0)
-       || (strcasecmp ("FailureMin", option->key) == 0))
-      status = ut_config_type_min (&th, option);
-    else if (strcasecmp ("Interesting", option->key) == 0)
-      status = cf_util_get_flag (option, &th.flags, UT_FLAG_INTERESTING);
-    else if (strcasecmp ("Invert", option->key) == 0)
-      status = cf_util_get_flag (option, &th.flags, UT_FLAG_INVERT);
-    else if (strcasecmp ("Persist", option->key) == 0)
-      status = cf_util_get_flag (option, &th.flags, UT_FLAG_PERSIST);
-    else if (strcasecmp ("Percentage", option->key) == 0)
-      status = cf_util_get_flag (option, &th.flags, UT_FLAG_PERCENTAGE);
-    else if (strcasecmp ("Hits", option->key) == 0)
-      status = ut_config_type_hits (&th, option);
-    else if (strcasecmp ("Hysteresis", option->key) == 0)
-      status = ut_config_type_hysteresis (&th, option);
-    else
-    {
-      WARNING ("threshold values: Option `%s' not allowed inside a `Type' "
-         "block.", option->key);
-      status = -1;
-    }
-
-    if (status != 0)
-      break;
-  }
-
-  if (status == 0)
-  {
-    status = ut_threshold_add (&th);
-  }
-
-  return (status);
-} /* int ut_config_type */
-
-static int ut_config_plugin_instance (threshold_t *th, oconfig_item_t *ci)
-{
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_STRING))
-  {
-    WARNING ("threshold values: The `Instance' option needs exactly one "
-       "string argument.");
-    return (-1);
-  }
-
-  sstrncpy (th->plugin_instance, ci->values[0].value.string,
-      sizeof (th->plugin_instance));
-
-  return (0);
-} /* int ut_config_plugin_instance */
-
-static int ut_config_plugin (const threshold_t *th_orig, oconfig_item_t *ci)
-{
-  int i;
-  threshold_t th;
-  int status = 0;
-
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_STRING))
-  {
-    WARNING ("threshold values: The `Plugin' block needs exactly one string "
-       "argument.");
-    return (-1);
-  }
-
-  if (ci->children_num < 1)
-  {
-    WARNING ("threshold values: The `Plugin' block needs at least one nested "
-       "block.");
-    return (-1);
-  }
-
-  memcpy (&th, th_orig, sizeof (th));
-  sstrncpy (th.plugin, ci->values[0].value.string, sizeof (th.plugin));
-
-  for (i = 0; i < ci->children_num; i++)
-  {
-    oconfig_item_t *option = ci->children + i;
-    status = 0;
-
-    if (strcasecmp ("Type", option->key) == 0)
-      status = ut_config_type (&th, option);
-    else if (strcasecmp ("Instance", option->key) == 0)
-      status = ut_config_plugin_instance (&th, option);
-    else
-    {
-      WARNING ("threshold values: Option `%s' not allowed inside a `Plugin' "
-         "block.", option->key);
-      status = -1;
-    }
-
-    if (status != 0)
-      break;
-  }
-
-  return (status);
-} /* int ut_config_plugin */
-
-static int ut_config_host (const threshold_t *th_orig, oconfig_item_t *ci)
-{
-  int i;
-  threshold_t th;
-  int status = 0;
-
-  if ((ci->values_num != 1)
-      || (ci->values[0].type != OCONFIG_TYPE_STRING))
-  {
-    WARNING ("threshold values: The `Host' block needs exactly one string "
-       "argument.");
-    return (-1);
-  }
-
-  if (ci->children_num < 1)
-  {
-    WARNING ("threshold values: The `Host' block needs at least one nested "
-       "block.");
-    return (-1);
-  }
-
-  memcpy (&th, th_orig, sizeof (th));
-  sstrncpy (th.host, ci->values[0].value.string, sizeof (th.host));
-
-  for (i = 0; i < ci->children_num; i++)
-  {
-    oconfig_item_t *option = ci->children + i;
-    status = 0;
-
-    if (strcasecmp ("Type", option->key) == 0)
-      status = ut_config_type (&th, option);
-    else if (strcasecmp ("Plugin", option->key) == 0)
-      status = ut_config_plugin (&th, option);
-    else
-    {
-      WARNING ("threshold values: Option `%s' not allowed inside a `Host' "
-         "block.", option->key);
-      status = -1;
-    }
-
-    if (status != 0)
-      break;
-  }
-
-  return (status);
-} /* int ut_config_host */
-
-int ut_config (const oconfig_item_t *ci)
-{
-  int i;
-  int status = 0;
-
-  threshold_t th;
-
-  if (ci->values_num != 0)
-  {
-    ERROR ("threshold values: The `Threshold' block may not have any "
-       "arguments.");
-    return (-1);
-  }
-
-  if (threshold_tree == NULL)
-  {
-    threshold_tree = c_avl_create ((void *) strcmp);
-    if (threshold_tree == NULL)
-    {
-      ERROR ("ut_config: c_avl_create failed.");
-      return (-1);
-    }
-  }
-
-  memset (&th, '\0', sizeof (th));
-  th.warning_min = NAN;
-  th.warning_max = NAN;
-  th.failure_min = NAN;
-  th.failure_max = NAN;
-
-  th.hits = 0;
-  th.hysteresis = 0;
-  th.flags = UT_FLAG_INTERESTING; /* interesting by default */
-    
-  for (i = 0; i < ci->children_num; i++)
-  {
-    oconfig_item_t *option = ci->children + i;
-    status = 0;
-
-    if (strcasecmp ("Type", option->key) == 0)
-      status = ut_config_type (&th, option);
-    else if (strcasecmp ("Plugin", option->key) == 0)
-      status = ut_config_plugin (&th, option);
-    else if (strcasecmp ("Host", option->key) == 0)
-      status = ut_config_host (&th, option);
-    else
-    {
-      WARNING ("threshold values: Option `%s' not allowed here.", option->key);
-      status = -1;
-    }
-
-    if (status != 0)
-      break;
-  }
-
-  return (status);
-} /* int um_config */
-/*
- * End of the functions used to configure threshold values.
- */
-/* }}} */
-
-static threshold_t *threshold_search (const value_list_t *vl)
-{
-  threshold_t *th;
-
-  if ((th = threshold_get (vl->host, vl->plugin, vl->plugin_instance,
-         vl->type, vl->type_instance)) != NULL)
-    return (th);
-  else if ((th = threshold_get (vl->host, vl->plugin, vl->plugin_instance,
-         vl->type, NULL)) != NULL)
-    return (th);
-  else if ((th = threshold_get (vl->host, vl->plugin, NULL,
-         vl->type, vl->type_instance)) != NULL)
-    return (th);
-  else if ((th = threshold_get (vl->host, vl->plugin, NULL,
-         vl->type, NULL)) != NULL)
-    return (th);
-  else if ((th = threshold_get (vl->host, "", NULL,
-         vl->type, vl->type_instance)) != NULL)
-    return (th);
-  else if ((th = threshold_get (vl->host, "", NULL,
-         vl->type, NULL)) != NULL)
-    return (th);
-  else if ((th = threshold_get ("", vl->plugin, vl->plugin_instance,
-         vl->type, vl->type_instance)) != NULL)
-    return (th);
-  else if ((th = threshold_get ("", vl->plugin, vl->plugin_instance,
-         vl->type, NULL)) != NULL)
-    return (th);
-  else if ((th = threshold_get ("", vl->plugin, NULL,
-         vl->type, vl->type_instance)) != NULL)
-    return (th);
-  else if ((th = threshold_get ("", vl->plugin, NULL,
-         vl->type, NULL)) != NULL)
-    return (th);
-  else if ((th = threshold_get ("", "", NULL,
-         vl->type, vl->type_instance)) != NULL)
-    return (th);
-  else if ((th = threshold_get ("", "", NULL,
-         vl->type, NULL)) != NULL)
-    return (th);
-
-  return (NULL);
-} /* threshold_t *threshold_search */
-
-/*
- * int ut_report_state
- *
- * Checks if the `state' differs from the old state and creates a notification
- * if appropriate.
- * Does not fail.
- */
-static int ut_report_state (const data_set_t *ds,
-    const value_list_t *vl,
-    const threshold_t *th,
-    const gauge_t *values,
-    int ds_index,
-    int state)
-{ /* {{{ */
-  int state_old;
-  notification_t n;
-
-  char *buf;
-  size_t bufsize;
-
-  int status;
-
-  /* Check if hits matched */
-  if ( (th->hits != 0) )
-  {
-    int hits = uc_get_hits(ds,vl);
-    /* The STATE_OKAY always reset hits, or if hits reaise the limit */
-    if ( (state == STATE_OKAY) || (hits > th->hits) )
-    {
-        DEBUG("ut_report_state: reset uc_get_hits = 0");
-        uc_set_hits(ds,vl,0); /* reset hit counter and notify */
-    } else {
-      DEBUG("ut_report_state: th->hits = %d, uc_get_hits = %d",th->hits,uc_get_hits(ds,vl));
-      (void) uc_inc_hits(ds,vl,1); /* increase hit counter */
-      return (0);
-    }
-  } /* end check hits */
-
-  state_old = uc_get_state (ds, vl);
-
-  /* If the state didn't change, only report if `persistent' is specified and
-   * the state is not `okay'. */
-  if (state == state_old)
-  {
-    if ((th->flags & UT_FLAG_PERSIST) == 0)
-      return (0);
-    else if (state == STATE_OKAY)
-      return (0);
-  }
-
-  if (state != state_old)
-    uc_set_state (ds, vl, state);
-
-  NOTIFICATION_INIT_VL (&n, vl, ds);
-
-  buf = n.message;
-  bufsize = sizeof (n.message);
-
-  if (state == STATE_OKAY)
-    n.severity = NOTIF_OKAY;
-  else if (state == STATE_WARNING)
-    n.severity = NOTIF_WARNING;
-  else
-    n.severity = NOTIF_FAILURE;
-
-  n.time = vl->time;
-
-  status = ssnprintf (buf, bufsize, "Host %s, plugin %s",
-      vl->host, vl->plugin);
-  buf += status;
-  bufsize -= status;
-
-  if (vl->plugin_instance[0] != '\0')
-  {
-    status = ssnprintf (buf, bufsize, " (instance %s)",
-       vl->plugin_instance);
-    buf += status;
-    bufsize -= status;
-  }
-
-  status = ssnprintf (buf, bufsize, " type %s", vl->type);
-  buf += status;
-  bufsize -= status;
-
-  if (vl->type_instance[0] != '\0')
-  {
-    status = ssnprintf (buf, bufsize, " (instance %s)",
-       vl->type_instance);
-    buf += status;
-    bufsize -= status;
-  }
-
-  plugin_notification_meta_add_string (&n, "DataSource",
-      ds->ds[ds_index].name);
-  plugin_notification_meta_add_double (&n, "CurrentValue", values[ds_index]);
-  plugin_notification_meta_add_double (&n, "WarningMin", th->warning_min);
-  plugin_notification_meta_add_double (&n, "WarningMax", th->warning_max);
-  plugin_notification_meta_add_double (&n, "FailureMin", th->failure_min);
-  plugin_notification_meta_add_double (&n, "FailureMax", th->failure_max);
-
-  /* Send an okay notification */
-  if (state == STATE_OKAY)
-  {
-    status = ssnprintf (buf, bufsize, ": All data sources are within range again.");
-    buf += status;
-    bufsize -= status;
-  }
-  else
-  {
-    double min;
-    double max;
-
-    min = (state == STATE_ERROR) ? th->failure_min : th->warning_min;
-    max = (state == STATE_ERROR) ? th->failure_max : th->warning_max;
-
-    if (th->flags & UT_FLAG_INVERT)
-    {
-      if (!isnan (min) && !isnan (max))
-      {
-        status = ssnprintf (buf, bufsize, ": Data source \"%s\" is currently "
-            "%f. That is within the %s region of %f%s and %f%s.",
-            ds->ds[ds_index].name, values[ds_index],
-            (state == STATE_ERROR) ? "failure" : "warning",
-            min, ((th->flags & UT_FLAG_PERCENTAGE) != 0) ? "%" : "",
-            max, ((th->flags & UT_FLAG_PERCENTAGE) != 0) ? "%" : "");
-      }
-      else
-      {
-       status = ssnprintf (buf, bufsize, ": Data source \"%s\" is currently "
-           "%f. That is %s the %s threshold of %f%s.",
-           ds->ds[ds_index].name, values[ds_index],
-           isnan (min) ? "below" : "above",
-           (state == STATE_ERROR) ? "failure" : "warning",
-           isnan (min) ? max : min,
-           ((th->flags & UT_FLAG_PERCENTAGE) != 0) ? "%" : "");
-      }
-    }
-    else /* is not inverted */
-    {
-      status = ssnprintf (buf, bufsize, ": Data source \"%s\" is currently "
-         "%f. That is %s the %s threshold of %f%s.",
-         ds->ds[ds_index].name, values[ds_index],
-         (values[ds_index] < min) ? "below" : "above",
-         (state == STATE_ERROR) ? "failure" : "warning",
-         (values[ds_index] < min) ? min : max,
-         ((th->flags & UT_FLAG_PERCENTAGE) != 0) ? "%" : "");
-    }
-    buf += status;
-    bufsize -= status;
-  }
-
-  plugin_dispatch_notification (&n);
-
-  plugin_notification_meta_free (n.meta);
-  return (0);
-} /* }}} int ut_report_state */
-
-/*
- * int ut_check_one_data_source
- *
- * Checks one data source against the given threshold configuration. If the
- * `DataSource' option is set in the threshold, and the name does NOT match,
- * `okay' is returned. If the threshold does match, its failure and warning
- * min and max values are checked and `failure' or `warning' is returned if
- * appropriate.
- * Does not fail.
- */
-static int ut_check_one_data_source (const data_set_t *ds,
-    const value_list_t __attribute__((unused)) *vl,
-    const threshold_t *th,
-    const gauge_t *values,
-    int ds_index)
-{ /* {{{ */
-  const char *ds_name;
-  int is_warning = 0;
-  int is_failure = 0;
-  int prev_state = STATE_OKAY;
-
-  /* check if this threshold applies to this data source */
-  if (ds != NULL)
-  {
-    ds_name = ds->ds[ds_index].name;
-    if ((th->data_source[0] != 0)
-       && (strcmp (ds_name, th->data_source) != 0))
-      return (STATE_OKAY);
-  }
-
-  if ((th->flags & UT_FLAG_INVERT) != 0)
-  {
-    is_warning--;
-    is_failure--;
-  }
-
-  /* XXX: This is an experimental code, not optimized, not fast, not reliable,
-   * and probably, do not work as you expect. Enjoy! :D */
-  if ( (th->hysteresis > 0) && ((prev_state = uc_get_state(ds,vl)) != STATE_OKAY) )
-  {
-    switch(prev_state)
-    {
-      case STATE_ERROR:
-       if ( (!isnan (th->failure_min) && ((th->failure_min + th->hysteresis) < values[ds_index])) ||
-            (!isnan (th->failure_max) && ((th->failure_max - th->hysteresis) > values[ds_index])) )
-         return (STATE_OKAY);
-       else
-         is_failure++;
-      case STATE_WARNING:
-       if ( (!isnan (th->warning_min) && ((th->warning_min + th->hysteresis) < values[ds_index])) ||
-            (!isnan (th->warning_max) && ((th->warning_max - th->hysteresis) > values[ds_index])) )
-         return (STATE_OKAY);
-       else
-         is_warning++;
-     }
-  }
-  else { /* no hysteresis */
-    if ((!isnan (th->failure_min) && (th->failure_min > values[ds_index]))
-       || (!isnan (th->failure_max) && (th->failure_max < values[ds_index])))
-      is_failure++;
-
-    if ((!isnan (th->warning_min) && (th->warning_min > values[ds_index]))
-       || (!isnan (th->warning_max) && (th->warning_max < values[ds_index])))
-      is_warning++;
- }
-
-  if (is_failure != 0)
-    return (STATE_ERROR);
-
-  if (is_warning != 0)
-    return (STATE_WARNING);
-
-  return (STATE_OKAY);
-} /* }}} int ut_check_one_data_source */
-
-/*
- * int ut_check_one_threshold
- *
- * Checks all data sources of a value list against the given threshold, using
- * the ut_check_one_data_source function above. Returns the worst status,
- * which is `okay' if nothing has failed.
- * Returns less than zero if the data set doesn't have any data sources.
- */
-static int ut_check_one_threshold (const data_set_t *ds,
-    const value_list_t *vl,
-    const threshold_t *th,
-    const gauge_t *values,
-    int *ret_ds_index)
-{ /* {{{ */
-  int ret = -1;
-  int ds_index = -1;
-  int i;
-  gauge_t values_copy[ds->ds_num];
-
-  memcpy (values_copy, values, sizeof (values_copy));
-
-  if ((th->flags & UT_FLAG_PERCENTAGE) != 0)
-  {
-    int num = 0;
-    gauge_t sum=0.0;
-
-    if (ds->ds_num == 1)
-    {
-      WARNING ("ut_check_one_threshold: The %s type has only one data "
-          "source, but you have configured to check this as a percentage. "
-          "That doesn't make much sense, because the percentage will always "
-          "be 100%%!", ds->type);
-    }
-
-    /* Prepare `sum' and `num'. */
-    for (i = 0; i < ds->ds_num; i++)
-      if (!isnan (values[i]))
-      {
-        num++;
-       sum += values[i];
-      }
-
-    if ((num == 0) /* All data sources are undefined. */
-        || (sum == 0.0)) /* Sum is zero, cannot calculate percentage. */
-    {
-      for (i = 0; i < ds->ds_num; i++)
-        values_copy[i] = NAN;
-    }
-    else /* We can actually calculate the percentage. */
-    {
-      for (i = 0; i < ds->ds_num; i++)
-        values_copy[i] = 100.0 * values[i] / sum;
-    }
-  } /* if (UT_FLAG_PERCENTAGE) */
-
-  for (i = 0; i < ds->ds_num; i++)
-  {
-    int status;
-
-    status = ut_check_one_data_source (ds, vl, th, values_copy, i);
-    if (ret < status)
-    {
-      ret = status;
-      ds_index = i;
-    }
-  } /* for (ds->ds_num) */
-
-  if (ret_ds_index != NULL)
-    *ret_ds_index = ds_index;
-
-  return (ret);
-} /* }}} int ut_check_one_threshold */
-
-/*
- * int ut_check_threshold (PUBLIC)
- *
- * Gets a list of matching thresholds and searches for the worst status by one
- * of the thresholds. Then reports that status using the ut_report_state
- * function above. 
- * Returns zero on success and if no threshold has been configured. Returns
- * less than zero on failure.
- */
-int ut_check_threshold (const data_set_t *ds, const value_list_t *vl)
-{ /* {{{ */
-  threshold_t *th;
-  gauge_t *values;
-  int status;
-
-  int worst_state = -1;
-  threshold_t *worst_th = NULL;
-  int worst_ds_index = -1;
-
-  if (threshold_tree == NULL)
-    return (0);
-
-  /* Is this lock really necessary? So far, thresholds are only inserted at
-   * startup. -octo */
-  pthread_mutex_lock (&threshold_lock);
-  th = threshold_search (vl);
-  pthread_mutex_unlock (&threshold_lock);
-  if (th == NULL)
-    return (0);
-
-  DEBUG ("ut_check_threshold: Found matching threshold(s)");
-
-  values = uc_get_rate (ds, vl);
-  if (values == NULL)
-    return (0);
-
-  while (th != NULL)
-  {
-    int ds_index = -1;
-
-    status = ut_check_one_threshold (ds, vl, th, values, &ds_index);
-    if (status < 0)
-    {
-      ERROR ("ut_check_threshold: ut_check_one_threshold failed.");
-      sfree (values);
-      return (-1);
-    }
-
-    if (worst_state < status)
-    {
-      worst_state = status;
-      worst_th = th;
-      worst_ds_index = ds_index;
-    }
-
-    th = th->next;
-  } /* while (th) */
-
-  status = ut_report_state (ds, vl, worst_th, values,
-      worst_ds_index, worst_state);
-  if (status != 0)
-  {
-    ERROR ("ut_check_threshold: ut_report_state failed.");
-    sfree (values);
-    return (-1);
-  }
-
-  sfree (values);
-
-  return (0);
-} /* }}} int ut_check_threshold */
-
-/*
- * int ut_check_interesting (PUBLIC)
- *
- * Given an identification returns
- * 0: No threshold is defined.
- * 1: A threshold has been found. The flag `persist' is off.
- * 2: A threshold has been found. The flag `persist' is on.
- *    (That is, it is expected that many notifications are sent until the
- *    problem disappears.)
- */
-int ut_check_interesting (const char *name)
-{ /* {{{ */
-  char *name_copy = NULL;
-  char *host = NULL;
-  char *plugin = NULL;
-  char *plugin_instance = NULL;
-  char *type = NULL;
-  char *type_instance = NULL;
-  int status;
-  data_set_t ds;
-  value_list_t vl;
-  threshold_t *th;
-
-  /* If there is no tree nothing is interesting. */
-  if (threshold_tree == NULL)
-    return (0);
-
-  name_copy = strdup (name);
-  if (name_copy == NULL)
-  {
-    ERROR ("ut_check_interesting: strdup failed.");
-    return (-1);
-  }
-
-  status = parse_identifier (name_copy, &host,
-      &plugin, &plugin_instance, &type, &type_instance);
-  if (status != 0)
-  {
-    ERROR ("ut_check_interesting: parse_identifier failed.");
-    sfree (name_copy);
-    return (-1);
-  }
-
-  memset (&ds, '\0', sizeof (ds));
-  memset (&vl, '\0', sizeof (vl));
-
-  sstrncpy (vl.host, host, sizeof (vl.host));
-  sstrncpy (vl.plugin, plugin, sizeof (vl.plugin));
-  if (plugin_instance != NULL)
-    sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
-  sstrncpy (ds.type, type, sizeof (ds.type));
-  sstrncpy (vl.type, type, sizeof (vl.type));
-  if (type_instance != NULL)
-    sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
-
-  sfree (name_copy);
-  host = plugin = plugin_instance = type = type_instance = NULL;
-
-  th = threshold_search (&vl);
-  if (th == NULL)
-    return (0);
-
-  if ((th->flags & UT_FLAG_INTERESTING) == 0)
-    return (0);
-
-  if ((th->flags & UT_FLAG_PERSIST) == 0)
-    return (1);
-  return (2);
-} /* }}} int ut_check_interesting */
-
-int ut_search_threshold (const value_list_t *vl, /* {{{ */
-    threshold_t *ret_threshold)
-{
-  threshold_t *t;
-
-  if (vl == NULL)
-    return (EINVAL);
-
-  t = threshold_search (vl);
-  if (t == NULL)
-    return (ENOENT);
-
-  memcpy (ret_threshold, t, sizeof (*ret_threshold));
-  ret_threshold->next = NULL;
-
-  return (0);
-} /* }}} int ut_search_threshold */
-
-/* vim: set sw=2 ts=8 sts=2 tw=78 et fdm=marker : */
diff --git a/src/utils_threshold.h b/src/utils_threshold.h
deleted file mode 100644 (file)
index 5955ca6..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * collectd - src/utils_threshold.h
- * Copyright (C) 2007-2009  Florian octo Forster
- *
- * This program is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation; only version 2 of the License is applicable.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
- *
- * Author:
- *   Florian octo Forster <octo at verplant.org>
- **/
-
-#ifndef UTILS_THRESHOLD_H
-#define UTILS_THRESHOLD_H 1
-
-#include "collectd.h"
-#include "liboconfig/oconfig.h"
-#include "plugin.h"
-
-typedef struct threshold_s
-{
-  char host[DATA_MAX_NAME_LEN];
-  char plugin[DATA_MAX_NAME_LEN];
-  char plugin_instance[DATA_MAX_NAME_LEN];
-  char type[DATA_MAX_NAME_LEN];
-  char type_instance[DATA_MAX_NAME_LEN];
-  char data_source[DATA_MAX_NAME_LEN];
-  gauge_t warning_min;
-  gauge_t warning_max;
-  gauge_t failure_min;
-  gauge_t failure_max;
-  gauge_t hysteresis;
-  unsigned int flags;
-  int hits;
-  struct threshold_s *next;
-} threshold_t;
-
-/*
- * ut_config
- *
- * Parses the configuration and sets up the module. This is called from
- * `src/configfile.c'.
- */
-int ut_config (const oconfig_item_t *ci);
-
-/*
- * ut_check_threshold
- *
- * Checks if a threshold is defined for this value and if such a threshold is
- * configured, check if the value within the acceptable range. If it is not, a
- * notification is dispatched to inform the user that a problem exists. This is
- * called from `plugin_read_all'.
- */
-int ut_check_threshold (const data_set_t *ds, const value_list_t *vl);
-
-/*
- * Given an identification returns
- * 0: No threshold is defined.
- * 1: A threshold has been found. The flag `persist' is off.
- * 2: A threshold has been found. The flag `persist' is on.
- *    (That is, it is expected that many notifications are sent until the
- *    problem disappears.)
- */
-int ut_check_interesting (const char *name);
-
-/* 
- * Given an identifier in form of a `value_list_t', searches for the best
- * matching threshold configuration. `ret_threshold' may be NULL.
- *
- * Returns:
- *        0: Success. Threshold configuration has been copied to
- *           `ret_threshold' (if it is non-NULL).
- *   ENOENT: No configuration for this identifier found.
- *     else: Error.
- */
-int ut_search_threshold (const value_list_t *vl, threshold_t *ret_threshold);
-
-#endif /* UTILS_THRESHOLD_H */
diff --git a/src/utils_time.c b/src/utils_time.c
new file mode 100644 (file)
index 0000000..aac6135
--- /dev/null
@@ -0,0 +1,64 @@
+/**
+ * collectd - src/utils_time.h
+ * Copyright (C) 2010  Florian octo Forster
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; only version 2 of the License is applicable.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Authors:
+ *   Florian octo Forster <ff at octo.it>
+ **/
+
+#include "collectd.h"
+#include "utils_time.h"
+#include "plugin.h"
+#include "common.h"
+
+#if HAVE_CLOCK_GETTIME
+cdtime_t cdtime (void) /* {{{ */
+{
+  int status;
+  struct timespec ts = { 0, 0 };
+
+  status = clock_gettime (CLOCK_REALTIME, &ts);
+  if (status != 0)
+  {
+    char errbuf[1024];
+    ERROR ("cdtime: clock_gettime failed: %s",
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return (0);
+  }
+
+  return (TIMESPEC_TO_CDTIME_T (&ts));
+} /* }}} cdtime_t cdtime */
+#else
+/* Work around for Mac OS X which doesn't have clock_gettime(2). *sigh* */
+cdtime_t cdtime (void) /* {{{ */
+{
+  int status;
+  struct timeval tv = { 0, 0 };
+
+  status = gettimeofday (&tv, /* struct timezone = */ NULL);
+  if (status != 0)
+  {
+    char errbuf[1024];
+    ERROR ("cdtime: gettimeofday failed: %s",
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return (0);
+  }
+
+  return (TIMEVAL_TO_CDTIME_T (&tv));
+} /* }}} cdtime_t cdtime */
+#endif
+
+/* vim: set sw=2 sts=2 et fdm=marker : */
diff --git a/src/utils_time.h b/src/utils_time.h
new file mode 100644 (file)
index 0000000..0fd809a
--- /dev/null
@@ -0,0 +1,70 @@
+/**
+ * collectd - src/utils_time.h
+ * Copyright (C) 2010  Florian octo Forster
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; only version 2 of the License is applicable.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Authors:
+ *   Florian octo Forster <ff at octo.it>
+ **/
+
+#ifndef UTILS_TIME_H
+#define UTILS_TIME_H 1
+
+#include "collectd.h"
+
+/*
+ * "cdtime_t" is a 64bit unsigned integer. The time is stored at a 2^-30 second
+ * resolution, i.e. the most significant 34 bit are used to store the time in
+ * seconds, the least significant bits store the sub-second part in something
+ * very close to nanoseconds. *The* big advantage of storing time in this
+ * manner is that comparing times and calculating differences is as simple as
+ * it is with "time_t", i.e. a simple integer comparison / subtraction works.
+ */
+/* 
+ * cdtime_t is defined in "collectd.h" */
+/* typedef uint64_t cdtime_t; */
+
+/* 2^30 = 1073741824 */
+#define TIME_T_TO_CDTIME_T(t) (((cdtime_t) (t)) * 1073741824)
+#define CDTIME_T_TO_TIME_T(t) ((time_t) ((t) / 1073741824))
+
+#define CDTIME_T_TO_DOUBLE(t) (((double) (t)) / 1073741824.0)
+#define DOUBLE_TO_CDTIME_T(d) ((cdtime_t) ((d) * 1073741824.0))
+
+#define MS_TO_CDTIME_T(ms) ((cdtime_t)    (((double) (ms)) * 1073741.824))
+#define CDTIME_T_TO_MS(t)  ((long)        (((double) (t))  / 1073741.824))
+#define US_TO_CDTIME_T(us) ((cdtime_t)    (((double) (us)) * 1073.741824))
+#define CDTIME_T_TO_US(t)  ((suseconds_t) (((double) (t))  / 1073.741824))
+#define NS_TO_CDTIME_T(ns) ((cdtime_t)    (((double) (ns)) * 1.073741824))
+#define CDTIME_T_TO_NS(t)  ((long)        (((double) (t))  / 1.073741824))
+
+#define CDTIME_T_TO_TIMEVAL(cdt,tvp) do {                                    \
+        (tvp)->tv_sec = CDTIME_T_TO_TIME_T (cdt);                            \
+        (tvp)->tv_usec = CDTIME_T_TO_US ((cdt) % 1073741824);                \
+} while (0)
+#define TIMEVAL_TO_CDTIME_T(tv) (TIME_T_TO_CDTIME_T ((tv)->tv_sec)           \
+    + US_TO_CDTIME_T ((tv)->tv_usec))
+
+#define CDTIME_T_TO_TIMESPEC(cdt,tsp) do {                                   \
+  (tsp)->tv_sec = CDTIME_T_TO_TIME_T (cdt);                                  \
+  (tsp)->tv_nsec = CDTIME_T_TO_NS ((cdt) % 1073741824);                      \
+} while (0)
+#define TIMESPEC_TO_CDTIME_T(ts) (TIME_T_TO_CDTIME_T ((ts)->tv_sec)           \
+    + NS_TO_CDTIME_T ((ts)->tv_nsec))
+
+cdtime_t cdtime (void);
+
+#endif /* UTILS_TIME_H */
+/* vim: set sw=2 sts=2 et : */
diff --git a/src/utils_vl_lookup.c b/src/utils_vl_lookup.c
new file mode 100644 (file)
index 0000000..2dada24
--- /dev/null
@@ -0,0 +1,541 @@
+/**
+ * collectd - src/utils_vl_lookup.c
+ * Copyright (C) 2012  Florian Forster
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *   Florian Forster <octo at collectd.org>
+ **/
+
+#include "collectd.h"
+#include "common.h"
+#include "utils_vl_lookup.h"
+#include "utils_avltree.h"
+
+#if BUILD_TEST
+# define sstrncpy strncpy
+# define plugin_log(s, ...) do { \
+  printf ("[severity %i] ", s); \
+  printf (__VA_ARGS__); \
+  printf ("\n"); \
+} while (0)
+#endif
+
+/*
+ * Types
+ */
+struct lookup_s
+{
+  c_avl_tree_t *by_type_tree;
+
+  lookup_class_callback_t cb_user_class;
+  lookup_obj_callback_t cb_user_obj;
+  lookup_free_class_callback_t cb_free_class;
+  lookup_free_obj_callback_t cb_free_obj;
+};
+
+struct user_obj_s;
+typedef struct user_obj_s user_obj_t;
+struct user_obj_s
+{
+  void *user_obj;
+  identifier_t ident;
+
+  user_obj_t *next;
+};
+
+struct user_class_s
+{
+  void *user_class;
+  identifier_t ident;
+  user_obj_t *user_obj_list; /* list of user_obj */
+};
+typedef struct user_class_s user_class_t;
+
+struct user_class_list_s;
+typedef struct user_class_list_s user_class_list_t;
+struct user_class_list_s
+{
+  user_class_t entry;
+  user_class_list_t *next;
+};
+
+struct by_type_entry_s
+{
+  c_avl_tree_t *by_plugin_tree; /* plugin -> user_class_list_t */
+  user_class_list_t *wildcard_plugin_list;
+};
+typedef struct by_type_entry_s by_type_entry_t;
+
+/*
+ * Private functions
+ */
+static void *lu_create_user_obj (lookup_t *obj, /* {{{ */
+    data_set_t const *ds, value_list_t const *vl,
+    user_class_t *user_class)
+{
+  user_obj_t *user_obj;
+
+  user_obj = malloc (sizeof (*user_obj));
+  if (user_obj == NULL)
+  {
+    ERROR ("utils_vl_lookup: malloc failed.");
+    return (NULL);
+  }
+  memset (user_obj, 0, sizeof (*user_obj));
+  user_obj->next = NULL;
+
+  user_obj->user_obj = obj->cb_user_class (ds, vl, user_class->user_class);
+  if (user_obj->user_obj == NULL)
+  {
+    sfree (user_obj);
+    WARNING("utils_vl_lookup: User-provided constructor failed.");
+    return (NULL);
+  }
+
+  sstrncpy (user_obj->ident.host,
+    LU_IS_ALL (user_class->ident.host) ?  "/all/" : vl->host,
+    sizeof (user_obj->ident.host));
+  sstrncpy (user_obj->ident.plugin,
+    LU_IS_ALL (user_class->ident.plugin) ?  "/all/" : vl->plugin,
+    sizeof (user_obj->ident.plugin));
+  sstrncpy (user_obj->ident.plugin_instance,
+    LU_IS_ALL (user_class->ident.plugin_instance) ?  "/all/" : vl->plugin_instance,
+    sizeof (user_obj->ident.plugin_instance));
+  sstrncpy (user_obj->ident.type,
+    LU_IS_ALL (user_class->ident.type) ?  "/all/" : vl->type,
+    sizeof (user_obj->ident.type));
+  sstrncpy (user_obj->ident.type_instance,
+    LU_IS_ALL (user_class->ident.type_instance) ?  "/all/" : vl->type_instance,
+    sizeof (user_obj->ident.type_instance));
+
+  if (user_class->user_obj_list == NULL)
+  {
+    user_class->user_obj_list = user_obj;
+  }
+  else
+  {
+    user_obj_t *last = user_class->user_obj_list;
+    while (last->next != NULL)
+      last = last->next;
+    last->next = user_obj;
+  }
+
+  return (user_obj);
+} /* }}} void *lu_create_user_obj */
+
+static user_obj_t *lu_find_user_obj (user_class_t *user_class, /* {{{ */
+    value_list_t const *vl)
+{
+  user_obj_t *ptr;
+
+  for (ptr = user_class->user_obj_list;
+      ptr != NULL;
+      ptr = ptr->next)
+  {
+    if (!LU_IS_ALL (ptr->ident.host)
+        && (strcmp (ptr->ident.host, vl->host) != 0))
+      continue;
+    if (!LU_IS_ALL (ptr->ident.plugin_instance)
+        && (strcmp (ptr->ident.plugin_instance, vl->plugin_instance) != 0))
+      continue;
+    if (!LU_IS_ALL (ptr->ident.type_instance)
+        && (strcmp (ptr->ident.type_instance, vl->type_instance) != 0))
+      continue;
+
+    return (ptr);
+  }
+
+  return (NULL);
+} /* }}} user_obj_t *lu_find_user_obj */
+
+static int lu_handle_user_class (lookup_t *obj, /* {{{ */
+    data_set_t const *ds, value_list_t const *vl,
+    user_class_t *user_class)
+{
+  user_obj_t *user_obj;
+  int status;
+
+  assert (strcmp (vl->type, user_class->ident.type) == 0);
+  assert (LU_IS_WILDCARD (user_class->ident.plugin)
+      || (strcmp (vl->plugin, user_class->ident.plugin) == 0));
+
+  /* When we get here, type and plugin already match the user class. Now check
+   * the rest of the fields. */
+  if (!LU_IS_WILDCARD (user_class->ident.type_instance)
+      && (strcmp (vl->type_instance, user_class->ident.type_instance) != 0))
+    return (1);
+  if (!LU_IS_WILDCARD (user_class->ident.plugin_instance)
+      && (strcmp (vl->plugin_instance,
+          user_class->ident.plugin_instance) != 0))
+    return (1);
+  if (!LU_IS_WILDCARD (user_class->ident.host)
+      && (strcmp (vl->host, user_class->ident.host) != 0))
+    return (1);
+
+  user_obj = lu_find_user_obj (user_class, vl);
+  if (user_obj == NULL)
+  {
+    /* call lookup_class_callback_t() and insert into the list of user objects. */
+    user_obj = lu_create_user_obj (obj, ds, vl, user_class);
+    if (user_obj == NULL)
+      return (-1);
+  }
+
+  status = obj->cb_user_obj (ds, vl,
+      user_class->user_class, user_obj->user_obj);
+  if (status != 0)
+  {
+    ERROR ("utils_vl_lookup: The user object callback failed with status %i.",
+        status);
+    /* Returning a negative value means: abort! */
+    if (status < 0)
+      return (status);
+    else
+      return (1);
+  }
+
+  return (0);
+} /* }}} int lu_handle_user_class */
+
+static int lu_handle_user_class_list (lookup_t *obj, /* {{{ */
+    data_set_t const *ds, value_list_t const *vl,
+    user_class_list_t *user_class_list)
+{
+  user_class_list_t *ptr;
+  int retval = 0;
+  
+  for (ptr = user_class_list; ptr != NULL; ptr = ptr->next)
+  {
+    int status;
+
+    status = lu_handle_user_class (obj, ds, vl, &ptr->entry);
+    if (status < 0)
+      return (status);
+    else if (status == 0)
+      retval++;
+  }
+
+  return (retval);
+} /* }}} int lu_handle_user_class_list */
+
+static by_type_entry_t *lu_search_by_type (lookup_t *obj, /* {{{ */
+    char const *type, _Bool allocate_if_missing)
+{
+  by_type_entry_t *by_type;
+  char *type_copy;
+  int status;
+
+  status = c_avl_get (obj->by_type_tree, type, (void *) &by_type);
+  if (status == 0)
+    return (by_type);
+
+  if (!allocate_if_missing)
+    return (NULL);
+
+  type_copy = strdup (type);
+  if (type_copy == NULL)
+  {
+    ERROR ("utils_vl_lookup: strdup failed.");
+    return (NULL);
+  }
+
+  by_type = malloc (sizeof (*by_type));
+  if (by_type == NULL)
+  {
+    ERROR ("utils_vl_lookup: malloc failed.");
+    sfree (type_copy);
+    return (NULL);
+  }
+  memset (by_type, 0, sizeof (*by_type));
+  by_type->wildcard_plugin_list = NULL;
+  
+  by_type->by_plugin_tree = c_avl_create ((void *) strcmp);
+  if (by_type->by_plugin_tree == NULL)
+  {
+    ERROR ("utils_vl_lookup: c_avl_create failed.");
+    sfree (by_type);
+    sfree (type_copy);
+    return (NULL);
+  }
+
+  status = c_avl_insert (obj->by_type_tree,
+      /* key = */ type_copy, /* value = */ by_type);
+  assert (status <= 0); /* >0 => entry exists => race condition. */
+  if (status != 0)
+  {
+    ERROR ("utils_vl_lookup: c_avl_insert failed.");
+    c_avl_destroy (by_type->by_plugin_tree);
+    sfree (by_type);
+    sfree (type_copy);
+    return (NULL);
+  }
+  
+  return (by_type);
+} /* }}} by_type_entry_t *lu_search_by_type */
+
+static int lu_add_by_plugin (by_type_entry_t *by_type, /* {{{ */
+    identifier_t const *ident, user_class_list_t *user_class_list)
+{
+  user_class_list_t *ptr = NULL;
+
+  /* Lookup user_class_list from the per-plugin structure. If this is the first
+   * user_class to be added, the blocks return immediately. Otherwise they will
+   * set "ptr" to non-NULL. */
+  if (LU_IS_WILDCARD (ident->plugin))
+  {
+    if (by_type->wildcard_plugin_list == NULL)
+    {
+      by_type->wildcard_plugin_list = user_class_list;
+      return (0);
+    }
+
+    ptr = by_type->wildcard_plugin_list;
+  } /* if (plugin is wildcard) */
+  else /* (plugin is not wildcard) */
+  {
+    int status;
+
+    status = c_avl_get (by_type->by_plugin_tree,
+        ident->plugin, (void *) &ptr);
+
+    if (status != 0) /* plugin not yet in tree */
+    {
+      char *plugin_copy = strdup (ident->plugin);
+
+      if (plugin_copy == NULL)
+      {
+        ERROR ("utils_vl_lookup: strdup failed.");
+        sfree (user_class_list);
+        return (ENOMEM);
+      }
+
+      status = c_avl_insert (by_type->by_plugin_tree,
+          plugin_copy, user_class_list);
+      if (status != 0)
+      {
+        ERROR ("utils_vl_lookup: c_avl_insert(\"%s\") failed with status %i.",
+            plugin_copy, status);
+        sfree (plugin_copy);
+        sfree (user_class_list);
+        return (status);
+      }
+      else
+      {
+        return (0);
+      }
+    } /* if (plugin not yet in tree) */
+  } /* if (plugin is not wildcard) */
+
+  assert (ptr != NULL);
+
+  while (ptr->next != NULL)
+    ptr = ptr->next;
+  ptr->next = user_class_list;
+
+  return (0);
+} /* }}} int lu_add_by_plugin */
+
+static void lu_destroy_user_obj (lookup_t *obj, /* {{{ */
+    user_obj_t *user_obj)
+{
+  while (user_obj != NULL)
+  {
+    user_obj_t *next = user_obj->next;
+
+    if (obj->cb_free_obj != NULL)
+      obj->cb_free_obj (user_obj->user_obj);
+    user_obj->user_obj = NULL;
+
+    sfree (user_obj);
+    user_obj = next;
+  }
+} /* }}} void lu_destroy_user_obj */
+
+static void lu_destroy_user_class_list (lookup_t *obj, /* {{{ */
+    user_class_list_t *user_class_list)
+{
+  while (user_class_list != NULL)
+  {
+    user_class_list_t *next = user_class_list->next;
+
+    if (obj->cb_free_class != NULL)
+      obj->cb_free_class (user_class_list->entry.user_class);
+    user_class_list->entry.user_class = NULL;
+
+    lu_destroy_user_obj (obj, user_class_list->entry.user_obj_list);
+    user_class_list->entry.user_obj_list = NULL;
+
+    sfree (user_class_list);
+    user_class_list = next;
+  }
+} /* }}} void lu_destroy_user_class_list */
+
+static void lu_destroy_by_type (lookup_t *obj, /* {{{ */
+    by_type_entry_t *by_type)
+{
+  
+  while (42)
+  {
+    char *plugin = NULL;
+    user_class_list_t *user_class_list = NULL;
+    int status;
+
+    status = c_avl_pick (by_type->by_plugin_tree,
+        (void *) &plugin, (void *) &user_class_list);
+    if (status != 0)
+      break;
+
+    DEBUG ("utils_vl_lookup: lu_destroy_by_type: Destroying plugin \"%s\".",
+        plugin);
+    sfree (plugin);
+    lu_destroy_user_class_list (obj, user_class_list);
+  }
+
+  c_avl_destroy (by_type->by_plugin_tree);
+  by_type->by_plugin_tree = NULL;
+
+  lu_destroy_user_class_list (obj, by_type->wildcard_plugin_list);
+  by_type->wildcard_plugin_list = NULL;
+
+  sfree (by_type);
+} /* }}} int lu_destroy_by_type */
+
+/*
+ * Public functions
+ */
+lookup_t *lookup_create (lookup_class_callback_t cb_user_class, /* {{{ */
+    lookup_obj_callback_t cb_user_obj,
+    lookup_free_class_callback_t cb_free_class,
+    lookup_free_obj_callback_t cb_free_obj)
+{
+  lookup_t *obj = malloc (sizeof (*obj));
+  if (obj == NULL)
+  {
+    ERROR ("utils_vl_lookup: malloc failed.");
+    return (NULL);
+  }
+  memset (obj, 0, sizeof (*obj));
+
+  obj->by_type_tree = c_avl_create ((void *) strcmp);
+  if (obj->by_type_tree == NULL)
+  {
+    ERROR ("utils_vl_lookup: c_avl_create failed.");
+    sfree (obj);
+    return (NULL);
+  }
+
+  obj->cb_user_class = cb_user_class;
+  obj->cb_user_obj = cb_user_obj;
+  obj->cb_free_class = cb_free_class;
+  obj->cb_free_obj = cb_free_obj;
+
+  return (obj);
+} /* }}} lookup_t *lookup_create */
+
+void lookup_destroy (lookup_t *obj) /* {{{ */
+{
+  int status;
+
+  if (obj == NULL)
+    return;
+
+  while (42)
+  {
+    char *type = NULL;
+    by_type_entry_t *by_type = NULL;
+
+    status = c_avl_pick (obj->by_type_tree, (void *) &type, (void *) &by_type);
+    if (status != 0)
+      break;
+
+    DEBUG ("utils_vl_lookup: lookup_destroy: Destroying type \"%s\".", type);
+    sfree (type);
+    lu_destroy_by_type (obj, by_type);
+  }
+
+  c_avl_destroy (obj->by_type_tree);
+  obj->by_type_tree = NULL;
+
+  sfree (obj);
+} /* }}} void lookup_destroy */
+
+int lookup_add (lookup_t *obj, /* {{{ */
+    identifier_t const *ident, void *user_class)
+{
+  by_type_entry_t *by_type = NULL;
+  user_class_list_t *user_class_obj;
+
+  by_type = lu_search_by_type (obj, ident->type, /* allocate = */ 1);
+  if (by_type == NULL)
+    return (-1);
+
+  user_class_obj = malloc (sizeof (*user_class_obj));
+  if (user_class_obj == NULL)
+  {
+    ERROR ("utils_vl_lookup: malloc failed.");
+    return (ENOMEM);
+  }
+  memset (user_class_obj, 0, sizeof (*user_class_obj));
+  user_class_obj->entry.user_class = user_class;
+  memmove (&user_class_obj->entry.ident, ident, sizeof (*ident));
+  user_class_obj->entry.user_obj_list = NULL;
+  user_class_obj->next = NULL;
+
+  return (lu_add_by_plugin (by_type, ident, user_class_obj));
+} /* }}} int lookup_add */
+
+/* returns the number of successful calls to the callback function */
+int lookup_search (lookup_t *obj, /* {{{ */
+    data_set_t const *ds, value_list_t const *vl)
+{
+  by_type_entry_t *by_type = NULL;
+  user_class_list_t *user_class_list = NULL;
+  int retval = 0;
+  int status;
+
+  if ((obj == NULL) || (ds == NULL) || (vl == NULL))
+    return (-EINVAL);
+
+  by_type = lu_search_by_type (obj, vl->type, /* allocate = */ 0);
+  if (by_type == NULL)
+    return (0);
+
+  status = c_avl_get (by_type->by_plugin_tree,
+      vl->plugin, (void *) &user_class_list);
+  if (status == 0)
+  {
+    status = lu_handle_user_class_list (obj, ds, vl, user_class_list);
+    if (status < 0)
+      return (status);
+    retval += status;
+  }
+
+  if (by_type->wildcard_plugin_list != NULL)
+  {
+    status = lu_handle_user_class_list (obj, ds, vl,
+        by_type->wildcard_plugin_list);
+    if (status < 0)
+      return (status);
+    retval += status;
+  }
+    
+  return (retval);
+} /* }}} lookup_search */
diff --git a/src/utils_vl_lookup.h b/src/utils_vl_lookup.h
new file mode 100644 (file)
index 0000000..c006fc7
--- /dev/null
@@ -0,0 +1,90 @@
+/**
+ * collectd - src/utils_vl_lookup.h
+ * Copyright (C) 2012  Florian Forster
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *   Florian Forster <octo at collectd.org>
+ **/
+
+#ifndef UTILS_VL_LOOKUP_H
+#define UTILS_VL_LOOKUP_H 1
+
+#include "plugin.h"
+
+/*
+ * Types
+ */
+struct lookup_s;
+typedef struct lookup_s lookup_t;
+
+/* Given a user_class, constructs a new user_obj. */
+typedef void *(*lookup_class_callback_t) (data_set_t const *ds,
+    value_list_t const *vl, void *user_class);
+
+/* Given a user_class and a ds/vl combination, does stuff with the data.
+ * This is the main working horse of the module. */
+typedef int (*lookup_obj_callback_t) (data_set_t const *ds,
+    value_list_t const *vl,
+    void *user_class, void *user_obj);
+
+/* Used to free user_class pointers. May be NULL in which case nothing is
+ * freed. */
+typedef void (*lookup_free_class_callback_t) (void *user_class);
+
+/* Used to free user_obj pointers. May be NULL in which case nothing is
+ * freed. */
+typedef void (*lookup_free_obj_callback_t) (void *user_obj);
+
+struct identifier_s
+{
+  char host[DATA_MAX_NAME_LEN];
+  char plugin[DATA_MAX_NAME_LEN];
+  char plugin_instance[DATA_MAX_NAME_LEN];
+  char type[DATA_MAX_NAME_LEN];
+  char type_instance[DATA_MAX_NAME_LEN];
+};
+typedef struct identifier_s identifier_t;
+
+#define LU_ANY "/any/"
+#define LU_ALL "/all/"
+
+#define LU_IS_ANY(str) (strcmp (str, LU_ANY) == 0)
+#define LU_IS_ALL(str) (strcmp (str, LU_ALL) == 0)
+#define LU_IS_WILDCARD(str) (LU_IS_ANY(str) || LU_IS_ALL(str))
+
+/*
+ * Functions
+ */
+__attribute__((nonnull(1,2)))
+lookup_t *lookup_create (lookup_class_callback_t,
+    lookup_obj_callback_t,
+    lookup_free_class_callback_t,
+    lookup_free_obj_callback_t);
+void lookup_destroy (lookup_t *obj);
+
+int lookup_add (lookup_t *obj,
+    identifier_t const *ident, void *user_class);
+
+/* TODO(octo): Pass lookup_obj_callback_t to lookup_search()? */
+int lookup_search (lookup_t *obj,
+    data_set_t const *ds, value_list_t const *vl);
+
+#endif /* UTILS_VL_LOOKUP_H */
diff --git a/src/utils_vl_lookup_test.c b/src/utils_vl_lookup_test.c
new file mode 100644 (file)
index 0000000..6265b32
--- /dev/null
@@ -0,0 +1,214 @@
+/**
+ * collectd - src/utils_vl_lookup_test.c
+ * Copyright (C) 2012  Florian Forster
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *   Florian Forster <octo at collectd.org>
+ **/
+
+#include "collectd.h"
+#include "utils_vl_lookup.h"
+
+static _Bool expect_new_obj = 0;
+static _Bool have_new_obj = 0;
+
+static identifier_t last_class_ident;
+static identifier_t last_obj_ident;
+
+static data_source_t dsrc_test = { "value", DS_TYPE_DERIVE, 0.0, NAN };
+static data_set_t const ds_test = { "test", 1, &dsrc_test };
+
+static data_source_t dsrc_unknown = { "value", DS_TYPE_DERIVE, 0.0, NAN };
+static data_set_t const ds_unknown = { "unknown", 1, &dsrc_unknown };
+
+static int lookup_obj_callback (data_set_t const *ds,
+    value_list_t const *vl,
+    void *user_class, void *user_obj)
+{
+  identifier_t *class = user_class;
+  identifier_t *obj = user_obj;
+
+  assert (expect_new_obj == have_new_obj);
+
+  memcpy (&last_class_ident, class, sizeof (last_class_ident));
+  memcpy (&last_obj_ident, obj, sizeof (last_obj_ident));
+
+  if (strcmp (obj->plugin_instance, "failure") == 0)
+    return (-1);
+
+  return (0);
+}
+
+static void *lookup_class_callback (data_set_t const *ds,
+    value_list_t const *vl, void *user_class)
+{
+  identifier_t *class = user_class;
+  identifier_t *obj;
+
+  assert (expect_new_obj);
+
+  memcpy (&last_class_ident, class, sizeof (last_class_ident));
+  
+  obj = malloc (sizeof (*obj));
+  strncpy (obj->host, vl->host, sizeof (obj->host));
+  strncpy (obj->plugin, vl->plugin, sizeof (obj->plugin));
+  strncpy (obj->plugin_instance, vl->plugin_instance, sizeof (obj->plugin_instance));
+  strncpy (obj->type, vl->type, sizeof (obj->type));
+  strncpy (obj->type_instance, vl->type_instance, sizeof (obj->type_instance));
+
+  have_new_obj = 1;
+
+  return ((void *) obj);
+}
+
+static void checked_lookup_add (lookup_t *obj, /* {{{ */
+    char const *host,
+    char const *plugin, char const *plugin_instance,
+    char const *type, char const *type_instance)
+{
+  identifier_t ident;
+  void *user_class;
+  int status;
+
+  memset (&ident, 0, sizeof (ident));
+  strncpy (ident.host, host, sizeof (ident.host));
+  strncpy (ident.plugin, plugin, sizeof (ident.plugin));
+  strncpy (ident.plugin_instance, plugin_instance, sizeof (ident.plugin_instance));
+  strncpy (ident.type, type, sizeof (ident.type));
+  strncpy (ident.type_instance, type_instance, sizeof (ident.type_instance));
+
+  user_class = malloc (sizeof (ident));
+  memmove (user_class, &ident, sizeof (ident));
+
+  status = lookup_add (obj, &ident, user_class);
+  assert (status == 0);
+} /* }}} void test_add */
+
+static int checked_lookup_search (lookup_t *obj,
+    char const *host,
+    char const *plugin, char const *plugin_instance,
+    char const *type, char const *type_instance,
+    _Bool expect_new)
+{
+  int status;
+  value_list_t vl = VALUE_LIST_STATIC;
+  data_set_t const *ds = &ds_unknown;
+
+  strncpy (vl.host, host, sizeof (vl.host));
+  strncpy (vl.plugin, plugin, sizeof (vl.plugin));
+  strncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
+  strncpy (vl.type, type, sizeof (vl.type));
+  strncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
+
+  if (strcmp (vl.type, "test") == 0)
+    ds = &ds_test;
+
+  expect_new_obj = expect_new;
+  have_new_obj = 0;
+
+  status = lookup_search (obj, ds, &vl);
+  return (status);
+}
+
+static lookup_t *checked_lookup_create (void)
+{
+  lookup_t *obj = lookup_create (
+      lookup_class_callback,
+      lookup_obj_callback,
+      (void *) free,
+      (void *) free);
+  assert (obj != NULL);
+  return (obj);
+}
+
+static void testcase0 (void)
+{
+  lookup_t *obj = checked_lookup_create ();
+
+  checked_lookup_add (obj, "/any/", "test", "", "test", "/all/");
+  checked_lookup_search (obj, "host0", "test", "", "test", "0",
+      /* expect new = */ 1);
+  checked_lookup_search (obj, "host0", "test", "", "test", "1",
+      /* expect new = */ 0);
+  checked_lookup_search (obj, "host1", "test", "", "test", "0",
+      /* expect new = */ 1);
+  checked_lookup_search (obj, "host1", "test", "", "test", "1",
+      /* expect new = */ 0);
+
+  lookup_destroy (obj);
+}
+
+static void testcase1 (void)
+{
+  lookup_t *obj = checked_lookup_create ();
+
+  checked_lookup_add (obj, "/any/", "/all/", "/all/", "test", "/all/");
+  checked_lookup_search (obj, "host0", "plugin0", "", "test", "0",
+      /* expect new = */ 1);
+  checked_lookup_search (obj, "host0", "plugin0", "", "test", "1",
+      /* expect new = */ 0);
+  checked_lookup_search (obj, "host0", "plugin1", "", "test", "0",
+      /* expect new = */ 0);
+  checked_lookup_search (obj, "host0", "plugin1", "", "test", "1",
+      /* expect new = */ 0);
+  checked_lookup_search (obj, "host1", "plugin0", "", "test", "0",
+      /* expect new = */ 1);
+  checked_lookup_search (obj, "host1", "plugin0", "", "test", "1",
+      /* expect new = */ 0);
+  checked_lookup_search (obj, "host1", "plugin1", "", "test", "0",
+      /* expect new = */ 0);
+  checked_lookup_search (obj, "host1", "plugin1", "", "test", "1",
+      /* expect new = */ 0);
+
+  lookup_destroy (obj);
+}
+
+static void testcase2 (void)
+{
+  lookup_t *obj = checked_lookup_create ();
+  int status;
+
+  checked_lookup_add (obj, "/any/", "plugin0", "", "test", "/all/");
+  checked_lookup_add (obj, "/any/", "/all/", "", "test", "ti0");
+
+  status = checked_lookup_search (obj, "host0", "plugin1", "", "test", "",
+      /* expect new = */ 0);
+  assert (status == 0);
+  status = checked_lookup_search (obj, "host0", "plugin0", "", "test", "",
+      /* expect new = */ 1);
+  assert (status == 1);
+  status = checked_lookup_search (obj, "host0", "plugin1", "", "test", "ti0",
+      /* expect new = */ 1);
+  assert (status == 1);
+  status = checked_lookup_search (obj, "host0", "plugin0", "", "test", "ti0",
+      /* expect new = */ 0);
+  assert (status == 2);
+
+  lookup_destroy (obj);
+}
+
+int main (int argc, char **argv) /* {{{ */
+{
+  testcase0 ();
+  testcase1 ();
+  testcase2 ();
+  return (EXIT_SUCCESS);
+} /* }}} int main */
index 6bf2db7..de60e39 100644 (file)
 
 #include <varnish/varnishapi.h>
 
+#if HAVE_VARNISH_V3
+# include <varnish/vsc.h>
+typedef struct VSC_C_main c_varnish_stats_t;
+#endif
+
+#if HAVE_VARNISH_V2
+typedef struct varnish_stats c_varnish_stats_t;
+#endif
+
 /* {{{ user_config_s */
 struct user_config_s {
        char *instance;
@@ -145,9 +154,11 @@ struct user_config_s {
        _Bool collect_fetch;
        _Bool collect_hcb;
        _Bool collect_shm;
-       _Bool collect_sma;
        _Bool collect_sms;
+#if HAVE_VARNISH_V2
        _Bool collect_sm;
+       _Bool collect_sma;
+#endif
        _Bool collect_totals;
        _Bool collect_workers;
 };
@@ -204,182 +215,194 @@ static int varnish_submit_derive (const char *plugin_instance, /* {{{ */
        return (varnish_submit (plugin_instance, category, type, type_instance, value));
 } /* }}} int varnish_submit_derive */
 
-static void varnish_monitor (const user_config_t *conf, struct varnish_stats *VSL_stats) /* {{{ */
+static void varnish_monitor (const user_config_t *conf, /* {{{ */
+               const c_varnish_stats_t *stats)
 {
        if (conf->collect_cache)
        {
                /* Cache hits */
-               varnish_submit_derive (conf->instance, "cache", "cache_result", "hit",     VSL_stats->cache_hit);
+               varnish_submit_derive (conf->instance, "cache", "cache_result", "hit",     stats->cache_hit);
                /* Cache misses */
-               varnish_submit_derive (conf->instance, "cache", "cache_result", "miss",    VSL_stats->cache_miss);
+               varnish_submit_derive (conf->instance, "cache", "cache_result", "miss",    stats->cache_miss);
                /* Cache hits for pass */
-               varnish_submit_derive (conf->instance, "cache", "cache_result", "hitpass", VSL_stats->cache_hitpass);
+               varnish_submit_derive (conf->instance, "cache", "cache_result", "hitpass", stats->cache_hitpass);
        }
 
        if (conf->collect_connections)
        {
                /* Client connections accepted */
-               varnish_submit_derive (conf->instance, "connections", "connections", "accepted", VSL_stats->client_conn);
+               varnish_submit_derive (conf->instance, "connections", "connections", "accepted", stats->client_conn);
                /* Connection dropped, no sess */
-               varnish_submit_derive (conf->instance, "connections", "connections", "dropped" , VSL_stats->client_drop);
+               varnish_submit_derive (conf->instance, "connections", "connections", "dropped" , stats->client_drop);
                /* Client requests received    */
-               varnish_submit_derive (conf->instance, "connections", "connections", "received", VSL_stats->client_req);
+               varnish_submit_derive (conf->instance, "connections", "connections", "received", stats->client_req);
        }
 
        if (conf->collect_esi)
        {
-               /* Objects ESI parsed (unlock) */
-               varnish_submit_derive (conf->instance, "esi", "total_operations", "parsed", VSL_stats->esi_parse);
                /* ESI parse errors (unlock)   */
-               varnish_submit_derive (conf->instance, "esi", "total_operations", "error",  VSL_stats->esi_errors);
+               varnish_submit_derive (conf->instance, "esi", "total_operations", "error",  stats->esi_errors);
+#if HAVE_VARNISH_V2
+               /* Objects ESI parsed (unlock) */
+               varnish_submit_derive (conf->instance, "esi", "total_operations", "parsed", stats->esi_parse);
+#endif
        }
 
        if (conf->collect_backend)
        {
                /* Backend conn. success       */
-               varnish_submit_derive (conf->instance, "backend", "connections", "success"      , VSL_stats->backend_conn);
+               varnish_submit_derive (conf->instance, "backend", "connections", "success"      , stats->backend_conn);
                /* Backend conn. not attempted */
-               varnish_submit_derive (conf->instance, "backend", "connections", "not-attempted", VSL_stats->backend_unhealthy);
+               varnish_submit_derive (conf->instance, "backend", "connections", "not-attempted", stats->backend_unhealthy);
                /* Backend conn. too many      */
-               varnish_submit_derive (conf->instance, "backend", "connections", "too-many"     , VSL_stats->backend_busy);
+               varnish_submit_derive (conf->instance, "backend", "connections", "too-many"     , stats->backend_busy);
                /* Backend conn. failures      */
-               varnish_submit_derive (conf->instance, "backend", "connections", "failures"     , VSL_stats->backend_fail);
+               varnish_submit_derive (conf->instance, "backend", "connections", "failures"     , stats->backend_fail);
                /* Backend conn. reuses        */
-               varnish_submit_derive (conf->instance, "backend", "connections", "reuses"       , VSL_stats->backend_reuse);
+               varnish_submit_derive (conf->instance, "backend", "connections", "reuses"       , stats->backend_reuse);
                /* Backend conn. was closed    */
-               varnish_submit_derive (conf->instance, "backend", "connections", "was-closed"   , VSL_stats->backend_toolate);
+               varnish_submit_derive (conf->instance, "backend", "connections", "was-closed"   , stats->backend_toolate);
                /* Backend conn. recycles      */
-               varnish_submit_derive (conf->instance, "backend", "connections", "recycled"     , VSL_stats->backend_recycle);
+               varnish_submit_derive (conf->instance, "backend", "connections", "recycled"     , stats->backend_recycle);
+#if HAVE_VARNISH_V2
                /* Backend conn. unused        */
-               varnish_submit_derive (conf->instance, "backend", "connections", "unused"       , VSL_stats->backend_unused);
+               varnish_submit_derive (conf->instance, "backend", "connections", "unused"       , stats->backend_unused);
+#endif
        }
 
        if (conf->collect_fetch)
        {
                /* Fetch head                */
-               varnish_submit_derive (conf->instance, "fetch", "http_requests", "head"       , VSL_stats->fetch_head);
+               varnish_submit_derive (conf->instance, "fetch", "http_requests", "head"       , stats->fetch_head);
                /* Fetch with length         */
-               varnish_submit_derive (conf->instance, "fetch", "http_requests", "length"     , VSL_stats->fetch_length);
+               varnish_submit_derive (conf->instance, "fetch", "http_requests", "length"     , stats->fetch_length);
                /* Fetch chunked             */
-               varnish_submit_derive (conf->instance, "fetch", "http_requests", "chunked"    , VSL_stats->fetch_chunked);
+               varnish_submit_derive (conf->instance, "fetch", "http_requests", "chunked"    , stats->fetch_chunked);
                /* Fetch EOF                 */
-               varnish_submit_derive (conf->instance, "fetch", "http_requests", "eof"        , VSL_stats->fetch_eof);
+               varnish_submit_derive (conf->instance, "fetch", "http_requests", "eof"        , stats->fetch_eof);
                /* Fetch bad headers         */
-               varnish_submit_derive (conf->instance, "fetch", "http_requests", "bad_headers", VSL_stats->fetch_bad);
+               varnish_submit_derive (conf->instance, "fetch", "http_requests", "bad_headers", stats->fetch_bad);
                /* Fetch wanted close        */
-               varnish_submit_derive (conf->instance, "fetch", "http_requests", "close"      , VSL_stats->fetch_close);
+               varnish_submit_derive (conf->instance, "fetch", "http_requests", "close"      , stats->fetch_close);
                /* Fetch pre HTTP/1.1 closed */
-               varnish_submit_derive (conf->instance, "fetch", "http_requests", "oldhttp"    , VSL_stats->fetch_oldhttp);
+               varnish_submit_derive (conf->instance, "fetch", "http_requests", "oldhttp"    , stats->fetch_oldhttp);
                /* Fetch zero len            */
-               varnish_submit_derive (conf->instance, "fetch", "http_requests", "zero"       , VSL_stats->fetch_zero);
+               varnish_submit_derive (conf->instance, "fetch", "http_requests", "zero"       , stats->fetch_zero);
                /* Fetch failed              */
-               varnish_submit_derive (conf->instance, "fetch", "http_requests", "failed"     , VSL_stats->fetch_failed);
+               varnish_submit_derive (conf->instance, "fetch", "http_requests", "failed"     , stats->fetch_failed);
        }
 
        if (conf->collect_hcb)
        {
                /* HCB Lookups without lock */
-               varnish_submit_derive (conf->instance, "hcb", "cache_operation", "lookup_nolock", VSL_stats->hcb_nolock);
+               varnish_submit_derive (conf->instance, "hcb", "cache_operation", "lookup_nolock", stats->hcb_nolock);
                /* HCB Lookups with lock    */
-               varnish_submit_derive (conf->instance, "hcb", "cache_operation", "lookup_lock",   VSL_stats->hcb_lock);
+               varnish_submit_derive (conf->instance, "hcb", "cache_operation", "lookup_lock",   stats->hcb_lock);
                /* HCB Inserts              */
-               varnish_submit_derive (conf->instance, "hcb", "cache_operation", "insert",        VSL_stats->hcb_insert);
+               varnish_submit_derive (conf->instance, "hcb", "cache_operation", "insert",        stats->hcb_insert);
        }
 
        if (conf->collect_shm)
        {
                /* SHM records                 */
-               varnish_submit_derive (conf->instance, "shm", "total_operations", "records"   , VSL_stats->shm_records);
+               varnish_submit_derive (conf->instance, "shm", "total_operations", "records"   , stats->shm_records);
                /* SHM writes                  */
-               varnish_submit_derive (conf->instance, "shm", "total_operations", "writes"    , VSL_stats->shm_writes);
+               varnish_submit_derive (conf->instance, "shm", "total_operations", "writes"    , stats->shm_writes);
                /* SHM flushes due to overflow */
-               varnish_submit_derive (conf->instance, "shm", "total_operations", "flushes"   , VSL_stats->shm_flushes);
+               varnish_submit_derive (conf->instance, "shm", "total_operations", "flushes"   , stats->shm_flushes);
                /* SHM MTX contention          */
-               varnish_submit_derive (conf->instance, "shm", "total_operations", "contention", VSL_stats->shm_cont);
+               varnish_submit_derive (conf->instance, "shm", "total_operations", "contention", stats->shm_cont);
                /* SHM cycles through buffer   */
-               varnish_submit_derive (conf->instance, "shm", "total_operations", "cycles"    , VSL_stats->shm_cycles);
+               varnish_submit_derive (conf->instance, "shm", "total_operations", "cycles"    , stats->shm_cycles);
        }
 
+#if HAVE_VARNISH_V2
        if (conf->collect_sm)
        {
                /* allocator requests */
-               varnish_submit_derive (conf->instance, "sm", "total_requests", "nreq",  VSL_stats->sm_nreq);
+               varnish_submit_derive (conf->instance, "sm", "total_requests", "nreq",         stats->sm_nreq);
                /* outstanding allocations */
-               varnish_submit_gauge (conf->instance,  "sm", "requests", "outstanding", VSL_stats->sm_nobj);
+               varnish_submit_gauge (conf->instance,  "sm", "requests", "outstanding",        stats->sm_nobj);
                /* bytes allocated */
-               varnish_submit_gauge (conf->instance,  "sm", "bytes", "allocated",      VSL_stats->sm_balloc);
+               varnish_submit_derive (conf->instance,  "sm", "total_bytes", "allocated",      stats->sm_balloc);
                /* bytes free */
-               varnish_submit_gauge (conf->instance,  "sm", "bytes", "free",           VSL_stats->sm_bfree);
+               varnish_submit_derive (conf->instance,  "sm", "total_bytes", "free",           stats->sm_bfree);
        }
 
        if (conf->collect_sma)
        {
                /* SMA allocator requests */
-               varnish_submit_derive (conf->instance, "sma", "total_requests", "nreq",  VSL_stats->sma_nreq);
+               varnish_submit_derive (conf->instance, "sma", "total_requests", "nreq",    stats->sma_nreq);
                /* SMA outstanding allocations */
-               varnish_submit_gauge (conf->instance,  "sma", "requests", "outstanding", VSL_stats->sma_nobj);
+               varnish_submit_gauge (conf->instance,  "sma", "requests", "outstanding",   stats->sma_nobj);
                /* SMA outstanding bytes */
-               varnish_submit_gauge (conf->instance,  "sma", "bytes", "outstanding",    VSL_stats->sma_nbytes);
+               varnish_submit_gauge (conf->instance,  "sma", "bytes", "outstanding",      stats->sma_nbytes);
                /* SMA bytes allocated */
-               varnish_submit_gauge (conf->instance,  "sma", "bytes", "allocated",      VSL_stats->sma_balloc);
+               varnish_submit_derive (conf->instance,  "sma", "total_bytes", "allocated", stats->sma_balloc);
                /* SMA bytes free */
-               varnish_submit_gauge (conf->instance,  "sma", "bytes", "free" ,          VSL_stats->sma_bfree);
+               varnish_submit_derive (conf->instance,  "sma", "total_bytes", "free" ,     stats->sma_bfree);
        }
+#endif
 
        if (conf->collect_sms)
        {
                /* SMS allocator requests */
-               varnish_submit_derive (conf->instance, "sms", "total_requests", "allocator", VSL_stats->sms_nreq);
+               varnish_submit_derive (conf->instance, "sms", "total_requests", "allocator", stats->sms_nreq);
                /* SMS outstanding allocations */
-               varnish_submit_gauge (conf->instance,  "sms", "requests", "outstanding",     VSL_stats->sms_nobj);
+               varnish_submit_gauge (conf->instance,  "sms", "requests", "outstanding",     stats->sms_nobj);
                /* SMS outstanding bytes */
-               varnish_submit_gauge (conf->instance,  "sms", "bytes", "outstanding",        VSL_stats->sms_nbytes);
+               varnish_submit_gauge (conf->instance,  "sms", "bytes", "outstanding",        stats->sms_nbytes);
                /* SMS bytes allocated */
-               varnish_submit_gauge (conf->instance,  "sms", "bytes", "allocated",          VSL_stats->sms_balloc);
+               varnish_submit_derive (conf->instance,  "sms", "total_bytes", "allocated",   stats->sms_balloc);
                /* SMS bytes freed */
-               varnish_submit_gauge (conf->instance,  "sms", "bytes", "free",               VSL_stats->sms_bfree);
+               varnish_submit_derive (conf->instance,  "sms", "total_bytes", "free",        stats->sms_bfree);
        }
 
        if (conf->collect_totals)
        {
                /* Total Sessions */
-               varnish_submit_derive (conf->instance, "totals", "total_sessions", "sessions",  VSL_stats->s_sess);
+               varnish_submit_derive (conf->instance, "totals", "total_sessions", "sessions",  stats->s_sess);
                /* Total Requests */
-               varnish_submit_derive (conf->instance, "totals", "total_requests", "requests",  VSL_stats->s_req);
+               varnish_submit_derive (conf->instance, "totals", "total_requests", "requests",  stats->s_req);
                /* Total pipe */
-               varnish_submit_derive (conf->instance, "totals", "total_operations", "pipe",    VSL_stats->s_pipe);
+               varnish_submit_derive (conf->instance, "totals", "total_operations", "pipe",    stats->s_pipe);
                /* Total pass */
-               varnish_submit_derive (conf->instance, "totals", "total_operations", "pass",    VSL_stats->s_pass);
+               varnish_submit_derive (conf->instance, "totals", "total_operations", "pass",    stats->s_pass);
                /* Total fetch */
-               varnish_submit_derive (conf->instance, "totals", "total_operations", "fetches", VSL_stats->s_fetch);
+               varnish_submit_derive (conf->instance, "totals", "total_operations", "fetches", stats->s_fetch);
                /* Total header bytes */
-               varnish_submit_derive (conf->instance, "totals", "total_bytes", "header-bytes", VSL_stats->s_hdrbytes);
+               varnish_submit_derive (conf->instance, "totals", "total_bytes", "header-bytes", stats->s_hdrbytes);
                /* Total body byte */
-               varnish_submit_derive (conf->instance, "totals", "total_bytes", "body-bytes",   VSL_stats->s_bodybytes);
+               varnish_submit_derive (conf->instance, "totals", "total_bytes", "body-bytes",   stats->s_bodybytes);
        }
 
        if (conf->collect_workers)
        {
                /* worker threads */
-               varnish_submit_gauge (conf->instance, "workers", "threads", "worker",            VSL_stats->n_wrk);
+               varnish_submit_gauge (conf->instance, "workers", "threads", "worker",             stats->n_wrk);
                /* worker threads created */
-               varnish_submit_gauge (conf->instance, "workers", "total_threads", "created",     VSL_stats->n_wrk_create);
+               varnish_submit_derive (conf->instance, "workers", "total_threads", "created",     stats->n_wrk_create);
                /* worker threads not created */
-               varnish_submit_gauge (conf->instance, "workers", "total_threads", "failed",      VSL_stats->n_wrk_failed);
+               varnish_submit_derive (conf->instance, "workers", "total_threads", "failed",      stats->n_wrk_failed);
                /* worker threads limited */
-               varnish_submit_gauge (conf->instance, "workers", "total_threads", "limited",     VSL_stats->n_wrk_max);
+               varnish_submit_derive (conf->instance, "workers", "total_threads", "limited",     stats->n_wrk_max);
+               /* dropped work requests */
+               varnish_submit_derive (conf->instance, "workers", "total_requests", "dropped",    stats->n_wrk_drop);
+#ifdef HAVE_VARNISH_V2
                /* queued work requests */
-               varnish_submit_gauge (conf->instance, "workers", "total_requests", "queued",     VSL_stats->n_wrk_queue);
+               varnish_submit_derive (conf->instance, "workers", "total_requests", "queued",     stats->n_wrk_queue);
                /* overflowed work requests */
-               varnish_submit_gauge (conf->instance, "workers", "total_requests", "overflowed", VSL_stats->n_wrk_overflow);
-               /* dropped work requests */
-               varnish_submit_gauge (conf->instance, "workers", "total_requests", "dropped",    VSL_stats->n_wrk_drop);
+               varnish_submit_derive (conf->instance, "workers", "total_requests", "overflowed", stats->n_wrk_overflow);
+#endif
        }
 } /* }}} void varnish_monitor */
 
+#if HAVE_VARNISH_V3
 static int varnish_read (user_data_t *ud) /* {{{ */
 {
-       struct varnish_stats *VSL_stats;
+       struct VSM_data *vd;
+       const c_varnish_stats_t *stats;
+
        user_config_t *conf;
 
        if ((ud == NULL) || (ud->data == NULL))
@@ -387,18 +410,52 @@ static int varnish_read (user_data_t *ud) /* {{{ */
 
        conf = ud->data;
 
-       VSL_stats = VSL_OpenStats (conf->instance);
-       if (VSL_stats == NULL)
+       vd = VSM_New();
+       VSC_Setup(vd);
+       if (VSM_n_Arg(vd, conf->instance) == -1)
+       {
+               ERROR ("Varnish plugin : unable to load statistics from instance");
+               return (-1);
+       }
+       if (VSC_Open (vd, /* diag = */ 1))
+       {
+               ERROR ("varnish plugin: Unable to load statistics.");
+
+               return (-1);
+       }
+
+       stats = VSC_Main(vd);
+
+       varnish_monitor (conf, stats);
+       VSM_Close (vd);
+
+       return (0);
+} /* }}} */
+#else /* if HAVE_VARNISH_V2 */
+static int varnish_read (user_data_t *ud) /* {{{ */
+{
+       const c_varnish_stats_t *stats;
+
+       user_config_t *conf;
+
+       if ((ud == NULL) || (ud->data == NULL))
+               return (EINVAL);
+
+       conf = ud->data;
+
+       stats = VSL_OpenStats (conf->instance);
+       if (stats == NULL)
        {
                ERROR ("Varnish plugin : unable to load statistics");
 
                return (-1);
        }
 
-       varnish_monitor (conf, VSL_stats);
+       varnish_monitor (conf, stats);
 
-    return (0);
+       return (0);
 } /* }}} */
+#endif
 
 static void varnish_config_free (void *ptr) /* {{{ */
 {
@@ -423,11 +480,13 @@ static int varnish_config_apply_default (user_config_t *conf) /* {{{ */
        conf->collect_fetch       = 0;
        conf->collect_hcb         = 0;
        conf->collect_shm         = 1;
+#if HAVE_VARNISH_V2
        conf->collect_sm          = 0;
        conf->collect_sma         = 0;
+#endif
        conf->collect_sms         = 0;
        conf->collect_totals      = 0;
-       
+
        return (0);
 } /* }}} int varnish_config_apply_default */
 
@@ -519,12 +578,14 @@ static int varnish_config_instance (const oconfig_item_t *ci) /* {{{ */
                        cf_util_get_boolean (child, &conf->collect_hcb);
                else if (strcasecmp ("CollectSHM", child->key) == 0)
                        cf_util_get_boolean (child, &conf->collect_shm);
-               else if (strcasecmp ("CollectSMA", child->key) == 0)
-                       cf_util_get_boolean (child, &conf->collect_sma);
                else if (strcasecmp ("CollectSMS", child->key) == 0)
                        cf_util_get_boolean (child, &conf->collect_sms);
+#if HAVE_VARNISH_V2
+               else if (strcasecmp ("CollectSMA", child->key) == 0)
+                       cf_util_get_boolean (child, &conf->collect_sma);
                else if (strcasecmp ("CollectSM", child->key) == 0)
                        cf_util_get_boolean (child, &conf->collect_sm);
+#endif
                else if (strcasecmp ("CollectTotals", child->key) == 0)
                        cf_util_get_boolean (child, &conf->collect_totals);
                else if (strcasecmp ("CollectWorkers", child->key) == 0)
@@ -544,9 +605,11 @@ static int varnish_config_instance (const oconfig_item_t *ci) /* {{{ */
                        && !conf->collect_fetch
                        && !conf->collect_hcb
                        && !conf->collect_shm
-                       && !conf->collect_sma
                        && !conf->collect_sms
+#if HAVE_VARNISH_V2
+                       && !conf->collect_sma
                        && !conf->collect_sm
+#endif
                        && !conf->collect_totals
                        && !conf->collect_workers)
        {
index d32f1db..56997bf 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * collectd - src/vmem.c
- * Copyright (C) 2008  Florian octo Forster
+ * Copyright (C) 2008-2010  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -16,7 +16,7 @@
  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  *
  * Authors:
- *   Florian octo Forster <octo at verplant.org>
+ *   Florian octo Forster <octo at collectd.org>
  **/
 
 #include "collectd.h"
@@ -57,12 +57,12 @@ static void submit (const char *plugin_instance, const char *type,
 } /* void vmem_submit */
 
 static void submit_two (const char *plugin_instance, const char *type,
-    const char *type_instance, counter_t c0, counter_t c1)
+    const char *type_instance, derive_t c0, derive_t c1)
 {
   value_t values[2];
 
-  values[0].counter = c0;
-  values[1].counter = c1;
+  values[0].derive = c0;
+  values[1].derive = c1;
 
   submit (plugin_instance, type, type_instance, values, 2);
 } /* void submit_one */
@@ -93,16 +93,16 @@ static int vmem_config (const char *key, const char *value)
 static int vmem_read (void)
 {
 #if KERNEL_LINUX
-  counter_t pgpgin = 0;
-  counter_t pgpgout = 0;
+  derive_t pgpgin = 0;
+  derive_t pgpgout = 0;
   int pgpgvalid = 0;
 
-  counter_t pswpin = 0;
-  counter_t pswpout = 0;
+  derive_t pswpin = 0;
+  derive_t pswpout = 0;
   int pswpvalid = 0;
 
-  counter_t pgfault = 0;
-  counter_t pgmajfault = 0;
+  derive_t pgfault = 0;
+  derive_t pgmajfault = 0;
   int pgfaultvalid = 0;
 
   FILE *fh;
@@ -123,7 +123,7 @@ static int vmem_read (void)
     int fields_num;
     char *key;
     char *endptr;
-    counter_t counter;
+    derive_t counter;
     gauge_t gauge;
 
     fields_num = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
@@ -205,31 +205,31 @@ static int vmem_read (void)
     else if (strncmp ("pgalloc_", key, strlen ("pgalloc_")) == 0)
     {
       char *inst = key + strlen ("pgalloc_");
-      value_t value  = { .counter = counter };
+      value_t value  = { .derive = counter };
       submit_one (inst, "vmpage_action", "alloc", value);
     }
     else if (strncmp ("pgrefill_", key, strlen ("pgrefill_")) == 0)
     {
       char *inst = key + strlen ("pgrefill_");
-      value_t value  = { .counter = counter };
+      value_t value  = { .derive = counter };
       submit_one (inst, "vmpage_action", "refill", value);
     }
     else if (strncmp ("pgsteal_", key, strlen ("pgsteal_")) == 0)
     {
       char *inst = key + strlen ("pgsteal_");
-      value_t value  = { .counter = counter };
+      value_t value  = { .derive = counter };
       submit_one (inst, "vmpage_action", "steal", value);
     }
     else if (strncmp ("pgscan_kswapd_", key, strlen ("pgscan_kswapd_")) == 0)
     {
       char *inst = key + strlen ("pgscan_kswapd_");
-      value_t value  = { .counter = counter };
+      value_t value  = { .derive = counter };
       submit_one (inst, "vmpage_action", "scan_kswapd", value);
     }
     else if (strncmp ("pgscan_direct_", key, strlen ("pgscan_direct_")) == 0)
     {
       char *inst = key + strlen ("pgscan_direct_");
-      value_t value  = { .counter = counter };
+      value_t value  = { .derive = counter };
       submit_one (inst, "vmpage_action", "scan_direct", value);
     }
 
@@ -241,17 +241,17 @@ static int vmem_read (void)
      */
     else if (strcmp ("pgfree", key) == 0)
     {
-      value_t value  = { .counter = counter };
+      value_t value  = { .derive = counter };
       submit_one (NULL, "vmpage_action", "free", value);
     }
     else if (strcmp ("pgactivate", key) == 0)
     {
-      value_t value  = { .counter = counter };
+      value_t value  = { .derive = counter };
       submit_one (NULL, "vmpage_action", "activate", value);
     }
     else if (strcmp ("pgdeactivate", key) == 0)
     {
-      value_t value  = { .counter = counter };
+      value_t value  = { .derive = counter };
       submit_one (NULL, "vmpage_action", "deactivate", value);
     }
   } /* while (fgets) */
index 1615ca0..d80717c 100644 (file)
@@ -1,7 +1,7 @@
 /**
  * collectd - src/vserver.c
  * Copyright (C) 2006,2007  Sebastian Harl
- * Copyright (C) 2007,2008  Florian octo Forster
+ * Copyright (C) 2007-2010  Florian octo Forster
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -48,13 +48,13 @@ static int vserver_init (void)
 } /* static void vserver_init(void) */
 
 static void traffic_submit (const char *plugin_instance,
-               const char *type_instance, counter_t rx, counter_t tx)
+               const char *type_instance, derive_t rx, derive_t tx)
 {
        value_t values[2];
        value_list_t vl = VALUE_LIST_INIT;
 
-       values[0].counter = rx;
-       values[1].counter = tx;
+       values[0].derive = rx;
+       values[1].derive = tx;
 
        vl.values = values;
        vl.values_len = STATIC_ARRAY_SIZE (values);
@@ -107,14 +107,21 @@ static void submit_gauge (const char *plugin_instance, const char *type,
        plugin_dispatch_values (&vl);
 } /* void submit_gauge */
 
-static inline long long __get_sock_bytes(const char *s)
+static derive_t vserver_get_sock_bytes(const char *s)
 {
+       value_t v;
+       int status;
+
        while (s[0] != '/')
                ++s;
 
        /* Remove '/' */
        ++s;
-       return atoll(s);
+
+       status = parse_value (s, &v, DS_TYPE_DERIVE);
+       if (status != 0)
+               return (-1);
+       return (v.derive);
 }
 
 static int vserver_read (void)
@@ -201,8 +208,8 @@ static int vserver_read (void)
 
                while ((fh != NULL) && (NULL != fgets (buffer, BUFSIZE, fh)))
                {
-                       counter_t rx;
-                       counter_t tx;
+                       derive_t rx;
+                       derive_t tx;
                        char *type_instance;
 
                        if (strsplit (buffer, cols, 4) < 4)
@@ -221,8 +228,8 @@ static int vserver_read (void)
                        else
                                continue;
 
-                       rx = __get_sock_bytes (cols[1]);
-                       tx = __get_sock_bytes (cols[2]);
+                       rx = vserver_get_sock_bytes (cols[1]);
+                       tx = vserver_get_sock_bytes (cols[2]);
                        /* cols[3] == errors */
 
                        traffic_submit (dent->d_name, type_instance, rx, tx);
diff --git a/src/write_graphite.c b/src/write_graphite.c
new file mode 100644 (file)
index 0000000..2ae30ef
--- /dev/null
@@ -0,0 +1,508 @@
+/**
+ * collectd - src/write_graphite.c
+ * Copyright (C) 2012       Pierre-Yves Ritschard
+ * Copyright (C) 2011       Scott Sanders
+ * Copyright (C) 2009       Paul Sadauskas
+ * Copyright (C) 2009       Doug MacEachern
+ * Copyright (C) 2007-2012  Florian octo Forster
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; only version 2 of the License is applicable.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ *
+ * Authors:
+ *   Florian octo Forster <octo at collectd.org>
+ *   Doug MacEachern <dougm at hyperic.com>
+ *   Paul Sadauskas <psadauskas at gmail.com>
+ *   Scott Sanders <scott at jssjr.com>
+ *   Pierre-Yves Ritschard <pyr at spootnik.org>
+ *
+ * Based on the write_http plugin.
+ **/
+
+ /* write_graphite plugin configuation example
+  *
+  * <Plugin write_graphite>
+  *   <Carbon>
+  *     Host "localhost"
+  *     Port "2003"
+  *     Prefix "collectd"
+  *   </Carbon>
+  * </Plugin>
+  */
+
+#include "collectd.h"
+#include "common.h"
+#include "plugin.h"
+#include "configfile.h"
+
+#include "utils_cache.h"
+#include "utils_parse_option.h"
+#include "utils_format_graphite.h"
+
+/* Folks without pthread will need to disable this plugin. */
+#include <pthread.h>
+
+#include <sys/socket.h>
+#include <netdb.h>
+
+#ifndef WG_DEFAULT_NODE
+# define WG_DEFAULT_NODE "localhost"
+#endif
+
+#ifndef WG_DEFAULT_SERVICE
+# define WG_DEFAULT_SERVICE "2003"
+#endif
+
+#ifndef WG_DEFAULT_ESCAPE
+# define WG_DEFAULT_ESCAPE '_'
+#endif
+
+/* Ethernet - (IPv6 + TCP) = 1500 - (40 + 32) = 1428 */
+#ifndef WG_SEND_BUF_SIZE
+# define WG_SEND_BUF_SIZE 1428
+#endif
+
+/*
+ * Private variables
+ */
+struct wg_callback
+{
+    int      sock_fd;
+
+    char    *node;
+    char    *service;
+    char    *prefix;
+    char    *postfix;
+    char     escape_char;
+
+    _Bool    store_rates;
+    _Bool    separate_instances;
+    _Bool    always_append_ds;
+
+    char     send_buf[WG_SEND_BUF_SIZE];
+    size_t   send_buf_free;
+    size_t   send_buf_fill;
+    cdtime_t send_buf_init_time;
+
+    pthread_mutex_t send_lock;
+};
+
+
+/*
+ * Functions
+ */
+static void wg_reset_buffer (struct wg_callback *cb)
+{
+    memset (cb->send_buf, 0, sizeof (cb->send_buf));
+    cb->send_buf_free = sizeof (cb->send_buf);
+    cb->send_buf_fill = 0;
+    cb->send_buf_init_time = cdtime ();
+}
+
+static int wg_send_buffer (struct wg_callback *cb)
+{
+    ssize_t status = 0;
+
+    status = swrite (cb->sock_fd, cb->send_buf, strlen (cb->send_buf));
+    if (status < 0)
+    {
+        char errbuf[1024];
+        ERROR ("write_graphite plugin: send failed with status %zi (%s)",
+                status, sstrerror (errno, errbuf, sizeof (errbuf)));
+
+
+        close (cb->sock_fd);
+        cb->sock_fd = -1;
+
+        return (-1);
+    }
+
+    return (0);
+}
+
+/* NOTE: You must hold cb->send_lock when calling this function! */
+static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb)
+{
+    int status;
+
+    DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; "
+            "send_buf_fill = %zu;",
+            (double)timeout,
+            cb->send_buf_fill);
+
+    /* timeout == 0  => flush unconditionally */
+    if (timeout > 0)
+    {
+        cdtime_t now;
+
+        now = cdtime ();
+        if ((cb->send_buf_init_time + timeout) > now)
+            return (0);
+    }
+
+    if (cb->send_buf_fill <= 0)
+    {
+        cb->send_buf_init_time = cdtime ();
+        return (0);
+    }
+
+    status = wg_send_buffer (cb);
+    wg_reset_buffer (cb);
+
+    return (status);
+}
+
+static int wg_callback_init (struct wg_callback *cb)
+{
+    struct addrinfo ai_hints;
+    struct addrinfo *ai_list;
+    struct addrinfo *ai_ptr;
+    int status;
+
+    const char *node = cb->node ? cb->node : WG_DEFAULT_NODE;
+    const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE;
+
+    if (cb->sock_fd > 0)
+        return (0);
+
+    memset (&ai_hints, 0, sizeof (ai_hints));
+#ifdef AI_ADDRCONFIG
+    ai_hints.ai_flags |= AI_ADDRCONFIG;
+#endif
+    ai_hints.ai_family = AF_UNSPEC;
+    ai_hints.ai_socktype = SOCK_STREAM;
+
+    ai_list = NULL;
+
+    status = getaddrinfo (node, service, &ai_hints, &ai_list);
+    if (status != 0)
+    {
+        ERROR ("write_graphite plugin: getaddrinfo (%s, %s) failed: %s",
+                node, service, gai_strerror (status));
+        return (-1);
+    }
+
+    assert (ai_list != NULL);
+    for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
+    {
+        cb->sock_fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
+                ai_ptr->ai_protocol);
+        if (cb->sock_fd < 0)
+            continue;
+
+        status = connect (cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
+        if (status != 0)
+        {
+            close (cb->sock_fd);
+            cb->sock_fd = -1;
+            continue;
+        }
+
+        break;
+    }
+
+    freeaddrinfo (ai_list);
+
+    if (cb->sock_fd < 0)
+    {
+        char errbuf[1024];
+        ERROR ("write_graphite plugin: Connecting to %s:%s failed. "
+                "The last error was: %s", node, service,
+                sstrerror (errno, errbuf, sizeof (errbuf)));
+        close (cb->sock_fd);
+        return (-1);
+    }
+
+    wg_reset_buffer (cb);
+
+    return (0);
+}
+
+static void wg_callback_free (void *data)
+{
+    struct wg_callback *cb;
+
+    if (data == NULL)
+        return;
+
+    cb = data;
+
+    pthread_mutex_lock (&cb->send_lock);
+
+    wg_flush_nolock (/* timeout = */ 0, cb);
+
+    close(cb->sock_fd);
+    cb->sock_fd = -1;
+
+    sfree(cb->node);
+    sfree(cb->service);
+    sfree(cb->prefix);
+    sfree(cb->postfix);
+
+    pthread_mutex_destroy (&cb->send_lock);
+
+    sfree(cb);
+}
+
+static int wg_flush (cdtime_t timeout,
+        const char *identifier __attribute__((unused)),
+        user_data_t *user_data)
+{
+    struct wg_callback *cb;
+    int status;
+
+    if (user_data == NULL)
+        return (-EINVAL);
+
+    cb = user_data->data;
+
+    pthread_mutex_lock (&cb->send_lock);
+
+    if (cb->sock_fd < 0)
+    {
+        status = wg_callback_init (cb);
+        if (status != 0)
+        {
+            ERROR ("write_graphite plugin: wg_callback_init failed.");
+            pthread_mutex_unlock (&cb->send_lock);
+            return (-1);
+        }
+    }
+
+    status = wg_flush_nolock (timeout, cb);
+    pthread_mutex_unlock (&cb->send_lock);
+
+    return (status);
+}
+
+static int wg_send_message (char const *message, struct wg_callback *cb)
+{
+    int status;
+    size_t message_len;
+
+    message_len = strlen (message);
+
+    pthread_mutex_lock (&cb->send_lock);
+
+    if (cb->sock_fd < 0)
+    {
+        status = wg_callback_init (cb);
+        if (status != 0)
+        {
+            ERROR ("write_graphite plugin: wg_callback_init failed.");
+            pthread_mutex_unlock (&cb->send_lock);
+            return (-1);
+        }
+    }
+
+    if (message_len >= cb->send_buf_free)
+    {
+        status = wg_flush_nolock (/* timeout = */ 0, cb);
+        if (status != 0)
+        {
+            pthread_mutex_unlock (&cb->send_lock);
+            return (status);
+        }
+    }
+
+    /* Assert that we have enough space for this message. */
+    assert (message_len < cb->send_buf_free);
+
+    /* `message_len + 1' because `message_len' does not include the
+     * trailing null byte. Neither does `send_buffer_fill'. */
+    memcpy (cb->send_buf + cb->send_buf_fill,
+            message, message_len + 1);
+    cb->send_buf_fill += message_len;
+    cb->send_buf_free -= message_len;
+
+    DEBUG ("write_graphite plugin: [%s]:%s buf %zu/%zu (%.1f %%) \"%s\"",
+            cb->node,
+            cb->service,
+            cb->send_buf_fill, sizeof (cb->send_buf),
+            100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)),
+            message);
+
+    pthread_mutex_unlock (&cb->send_lock);
+
+    return (0);
+}
+
+static int wg_write_messages (const data_set_t *ds, const value_list_t *vl,
+        struct wg_callback *cb)
+{
+    char buffer[4096];
+    int status;
+
+    if (0 != strcmp (ds->type, vl->type))
+    {
+        ERROR ("write_graphite plugin: DS type does not match "
+                "value list type");
+        return -1;
+    }
+
+    memset (buffer, 0, sizeof (buffer));
+    status = format_graphite (buffer, sizeof (buffer), ds, vl,
+            cb->prefix, cb->postfix, cb->escape_char, cb->store_rates);
+    if (status != 0) /* error message has been printed already. */
+        return (status);
+
+    wg_send_message (buffer, cb);
+    if (status != 0)
+    {
+        ERROR ("write_graphite plugin: wg_send_message failed "
+                "with status %i.", status);
+        return (status);
+    }
+
+    return (0);
+} /* int wg_write_messages */
+
+static int wg_write (const data_set_t *ds, const value_list_t *vl,
+        user_data_t *user_data)
+{
+    struct wg_callback *cb;
+    int status;
+
+    if (user_data == NULL)
+        return (EINVAL);
+
+    cb = user_data->data;
+
+    status = wg_write_messages (ds, vl, cb);
+
+    return (status);
+}
+
+static int config_set_char (char *dest,
+        oconfig_item_t *ci)
+{
+    char buffer[4];
+    int status;
+
+    memset (buffer, 0, sizeof (buffer));
+
+    status = cf_util_get_string_buffer (ci, buffer, sizeof (buffer));
+    if (status != 0)
+        return (status);
+
+    if (buffer[0] == 0)
+    {
+        ERROR ("write_graphite plugin: Cannot use an empty string for the "
+                "\"EscapeCharacter\" option.");
+        return (-1);
+    }
+
+    if (buffer[1] != 0)
+    {
+        WARNING ("write_graphite plugin: Only the first character of the "
+                "\"EscapeCharacter\" option ('%c') will be used.",
+                (int) buffer[0]);
+    }
+
+    *dest = buffer[0];
+
+    return (0);
+}
+
+static int wg_config_carbon (oconfig_item_t *ci)
+{
+    struct wg_callback *cb;
+    user_data_t user_data;
+    char callback_name[DATA_MAX_NAME_LEN];
+    int i;
+
+    cb = malloc (sizeof (*cb));
+    if (cb == NULL)
+    {
+        ERROR ("write_graphite plugin: malloc failed.");
+        return (-1);
+    }
+    memset (cb, 0, sizeof (*cb));
+    cb->sock_fd = -1;
+    cb->node = NULL;
+    cb->service = NULL;
+    cb->prefix = NULL;
+    cb->postfix = NULL;
+    cb->escape_char = WG_DEFAULT_ESCAPE;
+    cb->store_rates = 1;
+
+    pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
+
+    for (i = 0; i < ci->children_num; i++)
+    {
+        oconfig_item_t *child = ci->children + i;
+
+        if (strcasecmp ("Host", child->key) == 0)
+            cf_util_get_string (child, &cb->node);
+        else if (strcasecmp ("Port", child->key) == 0)
+            cf_util_get_service (child, &cb->service);
+        else if (strcasecmp ("Prefix", child->key) == 0)
+            cf_util_get_string (child, &cb->prefix);
+        else if (strcasecmp ("Postfix", child->key) == 0)
+            cf_util_get_string (child, &cb->postfix);
+        else if (strcasecmp ("StoreRates", child->key) == 0)
+            cf_util_get_boolean (child, &cb->store_rates);
+        else if (strcasecmp ("SeparateInstances", child->key) == 0)
+            cf_util_get_boolean (child, &cb->separate_instances);
+        else if (strcasecmp ("AlwaysAppendDS", child->key) == 0)
+            cf_util_get_boolean (child, &cb->always_append_ds);
+        else if (strcasecmp ("EscapeCharacter", child->key) == 0)
+            config_set_char (&cb->escape_char, child);
+        else
+        {
+            ERROR ("write_graphite plugin: Invalid configuration "
+                        "option: %s.", child->key);
+        }
+    }
+
+    ssnprintf (callback_name, sizeof (callback_name), "write_graphite/%s/%s",
+            cb->node != NULL ? cb->node : WG_DEFAULT_NODE,
+            cb->service != NULL ? cb->service : WG_DEFAULT_SERVICE);
+
+    memset (&user_data, 0, sizeof (user_data));
+    user_data.data = cb;
+    user_data.free_func = wg_callback_free;
+    plugin_register_write (callback_name, wg_write, &user_data);
+
+    user_data.free_func = NULL;
+    plugin_register_flush (callback_name, wg_flush, &user_data);
+
+    return (0);
+}
+
+static int wg_config (oconfig_item_t *ci)
+{
+    int i;
+
+    for (i = 0; i < ci->children_num; i++)
+    {
+        oconfig_item_t *child = ci->children + i;
+
+        if (strcasecmp ("Carbon", child->key) == 0)
+            wg_config_carbon (child);
+        else
+        {
+            ERROR ("write_graphite plugin: Invalid configuration "
+                    "option: %s.", child->key);
+        }
+    }
+
+    return (0);
+}
+
+void module_register (void)
+{
+    plugin_register_complex_config ("write_graphite", wg_config);
+}
+
+/* vim: set sw=4 ts=4 sts=4 tw=78 et : */
index bac8e98..3035e43 100644 (file)
@@ -61,7 +61,7 @@ struct wh_callback_s
         char   send_buffer[4096];
         size_t send_buffer_free;
         size_t send_buffer_fill;
-        time_t send_buffer_init_time;
+        cdtime_t send_buffer_init_time;
 
         pthread_mutex_t send_lock;
 };
@@ -72,7 +72,7 @@ static void wh_reset_buffer (wh_callback_t *cb)  /* {{{ */
         memset (cb->send_buffer, 0, sizeof (cb->send_buffer));
         cb->send_buffer_free = sizeof (cb->send_buffer);
         cb->send_buffer_fill = 0;
-        cb->send_buffer_init_time = time (NULL);
+        cb->send_buffer_init_time = cdtime ();
 
         if (cb->format == WH_FORMAT_JSON)
         {
@@ -111,6 +111,7 @@ static int wh_callback_init (wh_callback_t *cb) /* {{{ */
                 return (-1);
         }
 
+        curl_easy_setopt (cb->curl, CURLOPT_NOSIGNAL, 1);
         curl_easy_setopt (cb->curl, CURLOPT_USERAGENT, PACKAGE_NAME"/"PACKAGE_VERSION);
 
         headers = NULL;
@@ -157,19 +158,21 @@ static int wh_callback_init (wh_callback_t *cb) /* {{{ */
         return (0);
 } /* }}} int wh_callback_init */
 
-static int wh_flush_nolock (int timeout, wh_callback_t *cb) /* {{{ */
+static int wh_flush_nolock (cdtime_t timeout, wh_callback_t *cb) /* {{{ */
 {
         int status;
 
-        DEBUG ("write_http plugin: wh_flush_nolock: timeout = %i; "
+        DEBUG ("write_http plugin: wh_flush_nolock: timeout = %.3f; "
                         "send_buffer_fill = %zu;",
-                        timeout, cb->send_buffer_fill);
+                        CDTIME_T_TO_DOUBLE (timeout),
+                        cb->send_buffer_fill);
 
+        /* timeout == 0  => flush unconditionally */
         if (timeout > 0)
         {
-                time_t now;
+                cdtime_t now;
 
-                now = time (NULL);
+                now = cdtime ();
                 if ((cb->send_buffer_init_time + timeout) > now)
                         return (0);
         }
@@ -178,7 +181,7 @@ static int wh_flush_nolock (int timeout, wh_callback_t *cb) /* {{{ */
         {
                 if (cb->send_buffer_fill <= 0)
                 {
-                        cb->send_buffer_init_time = time (NULL);
+                        cb->send_buffer_init_time = cdtime ();
                         return (0);
                 }
 
@@ -189,7 +192,7 @@ static int wh_flush_nolock (int timeout, wh_callback_t *cb) /* {{{ */
         {
                 if (cb->send_buffer_fill <= 2)
                 {
-                        cb->send_buffer_init_time = time (NULL);
+                        cb->send_buffer_init_time = cdtime ();
                         return (0);
                 }
 
@@ -218,7 +221,7 @@ static int wh_flush_nolock (int timeout, wh_callback_t *cb) /* {{{ */
         return (status);
 } /* }}} wh_flush_nolock */
 
-static int wh_flush (int timeout, /* {{{ */
+static int wh_flush (cdtime_t timeout, /* {{{ */
                 const char *identifier __attribute__((unused)),
                 user_data_t *user_data)
 {
@@ -258,7 +261,7 @@ static void wh_callback_free (void *data) /* {{{ */
 
         cb = data;
 
-        wh_flush_nolock (/* timeout = */ -1, cb);
+        wh_flush_nolock (/* timeout = */ 0, cb);
 
         curl_easy_cleanup (cb->curl);
         sfree (cb->location);
@@ -304,8 +307,10 @@ static int wh_write_command (const data_set_t *ds, const value_list_t *vl, /* {{
         }
 
         command_len = (size_t) ssnprintf (command, sizeof (command),
-                        "PUTVAL %s interval=%i %s\r\n",
-                        key, vl->interval, values);
+                        "PUTVAL %s interval=%.3f %s\r\n",
+                        key,
+                        CDTIME_T_TO_DOUBLE (vl->interval),
+                        values);
         if (command_len >= sizeof (command)) {
                 ERROR ("write_http plugin: Command buffer too small: "
                                 "Need %zu bytes.", command_len + 1);
@@ -327,7 +332,7 @@ static int wh_write_command (const data_set_t *ds, const value_list_t *vl, /* {{
 
         if (command_len >= cb->send_buffer_free)
         {
-                status = wh_flush_nolock (/* timeout = */ -1, cb);
+                status = wh_flush_nolock (/* timeout = */ 0, cb);
                 if (status != 0)
                 {
                         pthread_mutex_unlock (&cb->send_lock);
@@ -379,7 +384,7 @@ static int wh_write_json (const data_set_t *ds, const value_list_t *vl, /* {{{ *
                         ds, vl, cb->store_rates);
         if (status == (-ENOMEM))
         {
-                status = wh_flush_nolock (/* timeout = */ -1, cb);
+                status = wh_flush_nolock (/* timeout = */ 0, cb);
                 if (status != 0)
                 {
                         wh_reset_buffer (cb);
diff --git a/src/write_mongodb.c b/src/write_mongodb.c
new file mode 100644 (file)
index 0000000..c7b7682
--- /dev/null
@@ -0,0 +1,335 @@
+/**
+ * collectd - src/write_mongodb.c
+ * Copyright (C) 2010-2012  Florian Forster
+ * Copyright (C) 2010       Akkarit Sangpetch
+ * Copyright (C) 2012       Chris Lundquist
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *   Florian Forster <ff at octo.it>
+ *   Akkarit Sangpetch <asangpet at andrew.cmu.edu>
+ *   Chris Lundquist <clundquist at bluebox.net>
+ **/
+
+#include "collectd.h"
+#include "plugin.h"
+#include "common.h"
+#include "configfile.h"
+#include "utils_cache.h"
+
+#include <pthread.h>
+
+#if HAVE_STDINT_H
+# define MONGO_HAVE_STDINT 1
+#else
+# define MONGO_USE_LONG_LONG_INT 1
+#endif
+#include <mongo.h>
+
+struct wm_node_s
+{
+  char name[DATA_MAX_NAME_LEN];
+
+  char *host;
+  int port;
+  int timeout;
+
+  _Bool store_rates;
+
+  mongo conn[1];
+  pthread_mutex_t lock;
+};
+typedef struct wm_node_s wm_node_t;
+
+/*
+ * Functions
+ */
+static bson *wm_create_bson (const data_set_t *ds, /* {{{ */
+    const value_list_t *vl,
+    _Bool store_rates)
+{
+  bson *ret;
+  gauge_t *rates;
+  int i;
+
+  ret = bson_create ();
+  if (ret == NULL)
+  {
+    ERROR ("write_mongodb plugin: bson_create failed.");
+    return (NULL);
+  }
+
+  if (store_rates)
+  {
+    rates = uc_get_rate (ds, vl);
+    if (rates == NULL)
+    {
+      ERROR ("write_mongodb plugin: uc_get_rate() failed.");
+      return (NULL);
+    }
+  }
+  else
+  {
+    rates = NULL;
+  }
+
+  bson_init (ret);
+  bson_append_date (ret, "time", (bson_date_t) CDTIME_T_TO_MS (vl->time));
+  bson_append_string (ret, "host", vl->host);
+  bson_append_string (ret, "plugin", vl->plugin);
+  bson_append_string (ret, "plugin_instance", vl->plugin_instance);
+  bson_append_string (ret, "type", vl->type);
+  bson_append_string (ret, "type_instance", vl->type_instance);
+
+  bson_append_start_array (ret, "values"); /* {{{ */
+  for (i = 0; i < ds->ds_num; i++)
+  {
+    char key[16];
+
+    ssnprintf (key, sizeof (key), "%i", i);
+
+    if (ds->ds[i].type == DS_TYPE_GAUGE)
+      bson_append_double(ret, key, vl->values[i].gauge);
+    else if (store_rates)
+      bson_append_double(ret, key, (double) rates[i]);
+    else if (ds->ds[i].type == DS_TYPE_COUNTER)
+      bson_append_long(ret, key, vl->values[i].counter);
+    else if (ds->ds[i].type == DS_TYPE_DERIVE)
+      bson_append_long(ret, key, vl->values[i].derive);
+    else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
+      bson_append_long(ret, key, vl->values[i].absolute);
+    else
+      assert (23 == 42);
+  }
+  bson_append_finish_array (ret); /* }}} values */
+
+  bson_append_start_array (ret, "dstypes"); /* {{{ */
+  for (i = 0; i < ds->ds_num; i++)
+  {
+    char key[16];
+
+    ssnprintf (key, sizeof (key), "%i", i);
+
+    if (store_rates)
+      bson_append_string (ret, key, "gauge");
+    else
+      bson_append_string (ret, key, DS_TYPE_TO_STRING (ds->ds[i].type));
+  }
+  bson_append_finish_array (ret); /* }}} dstypes */
+
+  bson_append_start_array (ret, "dsnames"); /* {{{ */
+  for (i = 0; i < ds->ds_num; i++)
+  {
+    char key[16];
+
+    ssnprintf (key, sizeof (key), "%i", i);
+    bson_append_string (ret, key, ds->ds[i].name);
+  }
+  bson_append_finish_array (ret); /* }}} dsnames */
+
+  bson_finish (ret);
+
+  sfree (rates);
+  return (ret);
+} /* }}} bson *wm_create_bson */
+
+static int wm_write (const data_set_t *ds, /* {{{ */
+    const value_list_t *vl,
+    user_data_t *ud)
+{
+  wm_node_t *node = ud->data;
+  char collection_name[512];
+  bson *bson_record;
+  int status;
+
+  ssnprintf (collection_name, sizeof (collection_name), "collectd.%s",
+      vl->plugin);
+
+  bson_record = wm_create_bson (ds, vl, node->store_rates);
+  if (bson_record == NULL)
+    return (ENOMEM);
+
+  pthread_mutex_lock (&node->lock);
+
+  if (!mongo_is_connected (node->conn))
+  {
+    INFO ("write_mongodb plugin: Connecting to [%s]:%i",
+        (node->host != NULL) ? node->host : "localhost",
+        (node->port != 0) ? node->port : MONGO_DEFAULT_PORT);
+    status = mongo_connect (node->conn, node->host, node->port);
+    if (status != MONGO_OK) {
+      ERROR ("write_mongodb plugin: Connecting to [%s]:%i failed.",
+          (node->host != NULL) ? node->host : "localhost",
+          (node->port != 0) ? node->port : MONGO_DEFAULT_PORT);
+      mongo_destroy (node->conn);
+      pthread_mutex_unlock (&node->lock);
+      return (-1);
+    }
+
+    if (node->timeout > 0) {
+      status = mongo_set_op_timeout (node->conn, node->timeout);
+      if (status != MONGO_OK) {
+        WARNING ("write_mongodb plugin: mongo_set_op_timeout(%i) failed: %s",
+            node->timeout, node->conn->errstr);
+      }
+    }
+  }
+
+  /* Assert if the connection has been established */
+  assert (mongo_is_connected (node->conn));
+
+  #if MONGO_MINOR >= 6
+    /* There was an API change in 0.6.0 as linked below */
+    /* https://github.com/mongodb/mongo-c-driver/blob/master/HISTORY.md */
+    status = mongo_insert (node->conn, collection_name, bson_record, NULL);
+  #else
+    status = mongo_insert (node->conn, collection_name, bson_record);
+  #endif
+
+  if(status != MONGO_OK)
+  {
+    ERROR ( "write_mongodb plugin: error inserting record: %d", node->conn->err);
+    if (node->conn->err != MONGO_BSON_INVALID)
+      ERROR ("write_mongodb plugin: %s", node->conn->errstr);
+    else if (bson_record->err)
+      ERROR ("write_mongodb plugin: %s", bson_record->errstr);
+
+    /* Disconnect except on data errors. */
+    if ((node->conn->err != MONGO_BSON_INVALID)
+        && (node->conn->err != MONGO_BSON_NOT_FINISHED))
+      mongo_destroy (node->conn);
+  }
+
+  pthread_mutex_unlock (&node->lock);
+
+  /* free our resource as not to leak memory */
+  bson_dispose (bson_record);
+
+  return (0);
+} /* }}} int wm_write */
+
+static void wm_config_free (void *ptr) /* {{{ */
+{
+  wm_node_t *node = ptr;
+
+  if (node == NULL)
+    return;
+
+  if (mongo_is_connected (node->conn))
+    mongo_destroy (node->conn);
+
+  sfree (node->host);
+  sfree (node);
+} /* }}} void wm_config_free */
+
+static int wm_config_node (oconfig_item_t *ci) /* {{{ */
+{
+  wm_node_t *node;
+  int status;
+  int i;
+
+  node = malloc (sizeof (*node));
+  if (node == NULL)
+    return (ENOMEM);
+  memset (node, 0, sizeof (*node));
+  mongo_init (node->conn);
+  node->host = NULL;
+  node->store_rates = 1;
+  pthread_mutex_init (&node->lock, /* attr = */ NULL);
+
+  status = cf_util_get_string_buffer (ci, node->name, sizeof (node->name));
+
+  if (status != 0)
+  {
+    sfree (node);
+    return (status);
+  }
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *child = ci->children + i;
+
+    if (strcasecmp ("Host", child->key) == 0)
+      status = cf_util_get_string (child, &node->host);
+    else if (strcasecmp ("Port", child->key) == 0)
+    {
+      status = cf_util_get_port_number (child);
+      if (status > 0)
+      {
+        node->port = status;
+        status = 0;
+      }
+    }
+    else if (strcasecmp ("Timeout", child->key) == 0)
+      status = cf_util_get_int (child, &node->timeout);
+    else if (strcasecmp ("StoreRates", child->key) == 0)
+      status = cf_util_get_boolean (child, &node->store_rates);
+    else
+      WARNING ("write_mongodb plugin: Ignoring unknown config option \"%s\".",
+          child->key);
+
+    if (status != 0)
+      break;
+  } /* for (i = 0; i < ci->children_num; i++) */
+
+  if (status == 0)
+  {
+    char cb_name[DATA_MAX_NAME_LEN];
+    user_data_t ud;
+
+    ssnprintf (cb_name, sizeof (cb_name), "write_mongodb/%s", node->name);
+
+    ud.data = node;
+    ud.free_func = wm_config_free;
+
+    status = plugin_register_write (cb_name, wm_write, &ud);
+    INFO ("write_mongodb plugin: registered write plugin %s %d",cb_name,status);
+  }
+
+  if (status != 0)
+    wm_config_free (node);
+
+  return (status);
+} /* }}} int wm_config_node */
+
+static int wm_config (oconfig_item_t *ci) /* {{{ */
+{
+  int i;
+
+  for (i = 0; i < ci->children_num; i++)
+  {
+    oconfig_item_t *child = ci->children + i;
+
+    if (strcasecmp ("Node", child->key) == 0)
+      wm_config_node (child);
+    else
+      WARNING ("write_mongodb plugin: Ignoring unknown "
+          "configuration option \"%s\" at top level.", child->key);
+  }
+
+  return (0);
+} /* }}} int wm_config */
+
+void module_register (void)
+{
+  plugin_register_complex_config ("write_mongodb", wm_config);
+}
+
+/* vim: set sw=2 sts=2 tw=78 et fdm=marker : */
index 5f14e90..046b7b0 100644 (file)
@@ -1,6 +1,7 @@
 /**
  * collectd - src/zfs_arc.c
  * Copyright (C) 2009  Anthony Dewhurst
+ * Copyright (C) 2012  Aurelien Rougemont
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -17,6 +18,7 @@
  *
  * Authors:
  *   Anthony Dewhurst <dewhurst at gmail>
+ *   Aurelien Rougemont <beorn at gandi.net>
  **/
 
 #include "collectd.h"
@@ -26,7 +28,7 @@
 /*
  * Global variables
  */
-static kstat_t *ksp;
+
 extern kstat_ctl_t *kc;
 
 static void za_submit (const char* type, const char* type_instance, value_t* values, int values_len)
@@ -46,54 +48,68 @@ static void za_submit (const char* type, const char* type_instance, value_t* val
 
 static void za_submit_gauge (const char* type, const char* type_instance, gauge_t value)
 {
-       value_t values[1];
-
-       values[0].gauge = value;
+       value_t vv;
 
-       za_submit (type, type_instance, values, STATIC_ARRAY_SIZE(values));
+       vv.gauge = value;
+       za_submit (type, type_instance, &vv, 1);
 }
 
-static void za_submit_size (gauge_t size, gauge_t size_target, gauge_t limit_min, gauge_t limit_max)
+static int za_read_derive (kstat_t *ksp, const char *kstat_value,
+    const char *type, const char *type_instance)
 {
-       value_t values[4];
-
-       values[0].gauge = size;
-       values[1].gauge = size_target;
-       values[2].gauge = limit_min;
-       values[3].gauge = limit_max;
-
-       za_submit ("arc_size", "", values, STATIC_ARRAY_SIZE(values));
+  long long tmp;
+  value_t v;
+
+  tmp = get_kstat_value (ksp, (char *)kstat_value);
+  if (tmp == -1LL)
+  {
+    ERROR ("zfs_arc plugin: Reading kstat value \"%s\" failed.", kstat_value);
+    return (-1);
+  }
+
+  v.derive = (derive_t) tmp;
+  za_submit (type, type_instance, /* values = */ &v, /* values_num = */ 1);
+  return (0);
 }
 
-static void za_submit_bytes (counter_t read, counter_t write)
+static int za_read_gauge (kstat_t *ksp, const char *kstat_value,
+    const char *type, const char *type_instance)
 {
-       value_t values[2];
-
-       values[0].counter = read;
-       values[1].counter = write;
-
-       za_submit ("arc_l2_bytes", "", values, STATIC_ARRAY_SIZE(values));
+  long long tmp;
+  value_t v;
+
+  tmp = get_kstat_value (ksp, (char *)kstat_value);
+  if (tmp == -1LL)
+  {
+    ERROR ("zfs_arc plugin: Reading kstat value \"%s\" failed.", kstat_value);
+    return (-1);
+  }
+
+  v.gauge = (gauge_t) tmp;
+  za_submit (type, type_instance, /* values = */ &v, /* values_num = */ 1);
+  return (0);
 }
 
-static void za_submit_counts (char *type_instance, counter_t demand_data, counter_t demand_metadata,
-       counter_t prefetch_data, counter_t prefetch_metadata)
+static void za_submit_ratio (const char* type_instance, gauge_t hits, gauge_t misses)
 {
-       value_t values[4];
+       gauge_t ratio = NAN;
+
+       if (!isfinite (hits) || (hits < 0.0))
+               hits = 0.0;
+       if (!isfinite (misses) || (misses < 0.0))
+               misses = 0.0;
 
-       values[0].counter = demand_data;
-       values[1].counter = demand_metadata;
-       values[2].counter = prefetch_data;
-       values[3].counter = prefetch_metadata;
+       if ((hits != 0.0) || (misses != 0.0))
+               ratio = hits / (hits + misses);
 
-       za_submit ("arc_counts", type_instance, values, STATIC_ARRAY_SIZE(values));
+       za_submit_gauge ("cache_ratio", type_instance, ratio);
 }
 
 static int za_read (void)
 {
-       gauge_t   arcsize, targetsize, minlimit, maxlimit, hits, misses, l2_size, l2_hits, l2_misses;
-       counter_t demand_data_hits, demand_metadata_hits, prefetch_data_hits, prefetch_metadata_hits;
-       counter_t demand_data_misses, demand_metadata_misses, prefetch_data_misses, prefetch_metadata_misses;
-       counter_t l2_read_bytes, l2_write_bytes;
+       gauge_t  arc_hits, arc_misses, l2_hits, l2_misses;
+       value_t  l2_io[2];
+       kstat_t  *ksp   = NULL;
 
        get_kstat (&ksp, "zfs", 0, "arcstats");
        if (ksp == NULL)
@@ -102,51 +118,54 @@ static int za_read (void)
                return (-1);
        }
 
-       arcsize    = get_kstat_value(ksp, "size");
-       targetsize = get_kstat_value(ksp, "c");
-       minlimit   = get_kstat_value(ksp, "c_min");
-       maxlimit   = get_kstat_value(ksp, "c_max");
-
-       demand_data_hits       = get_kstat_value(ksp, "demand_data_hits");
-       demand_metadata_hits   = get_kstat_value(ksp, "demand_metadata_hits");
-       prefetch_data_hits     = get_kstat_value(ksp, "prefetch_data_hits");
-       prefetch_metadata_hits = get_kstat_value(ksp, "prefetch_metadata_hits");
-
-       demand_data_misses       = get_kstat_value(ksp, "demand_data_misses");
-       demand_metadata_misses   = get_kstat_value(ksp, "demand_metadata_misses");
-       prefetch_data_misses     = get_kstat_value(ksp, "prefetch_data_misses");
-       prefetch_metadata_misses = get_kstat_value(ksp, "prefetch_metadata_misses");
-
-       hits   = get_kstat_value(ksp, "hits");
-       misses = get_kstat_value(ksp, "misses");
-
-       l2_size        = get_kstat_value(ksp, "l2_size");
-       l2_read_bytes  = get_kstat_value(ksp, "l2_read_bytes");
-       l2_write_bytes = get_kstat_value(ksp, "l2_write_bytes");
-       l2_hits        = get_kstat_value(ksp, "l2_hits");
-       l2_misses      = get_kstat_value(ksp, "l2_misses");
-
-
-       za_submit_size (arcsize, targetsize, minlimit, maxlimit);
-       za_submit_gauge ("arc_l2_size", "", l2_size);
-
-       za_submit_counts ("hits",   demand_data_hits,     demand_metadata_hits,
-                                   prefetch_data_hits,   prefetch_metadata_hits);
-       za_submit_counts ("misses", demand_data_misses,   demand_metadata_misses,
-                                   prefetch_data_misses, prefetch_metadata_misses);
-
-       za_submit_gauge ("arc_ratio", "L1", hits / (hits + misses));
-       za_submit_gauge ("arc_ratio", "L2", l2_hits / (l2_hits + l2_misses));
-
-       za_submit_bytes (l2_read_bytes, l2_write_bytes);
+       /* Sizes */
+       za_read_gauge (ksp, "size",    "cache_size", "arc");
+       za_read_gauge (ksp, "l2_size", "cache_size", "L2");
+
+        /* Operations */
+       za_read_derive (ksp, "allocated","cache_operation", "allocated");
+       za_read_derive (ksp, "deleted",  "cache_operation", "deleted");
+       za_read_derive (ksp, "stolen",   "cache_operation", "stolen");
+
+        /* Issue indicators */
+        za_read_derive (ksp, "mutex_miss", "mutex_operation", "miss");
+       za_read_derive (ksp, "hash_collisions", "hash_collisions", "");
+       
+        /* Evictions */
+       za_read_derive (ksp, "evict_l2_cached",     "cache_eviction", "cached");
+       za_read_derive (ksp, "evict_l2_eligible",   "cache_eviction", "eligible");
+       za_read_derive (ksp, "evict_l2_ineligible", "cache_eviction", "ineligible");
+
+       /* Hits / misses */
+       za_read_derive (ksp, "demand_data_hits",         "cache_result", "demand_data-hit");
+       za_read_derive (ksp, "demand_metadata_hits",     "cache_result", "demand_metadata-hit");
+       za_read_derive (ksp, "prefetch_data_hits",       "cache_result", "prefetch_data-hit");
+       za_read_derive (ksp, "prefetch_metadata_hits",   "cache_result", "prefetch_metadata-hit");
+       za_read_derive (ksp, "demand_data_misses",       "cache_result", "demand_data-miss");
+       za_read_derive (ksp, "demand_metadata_misses",   "cache_result", "demand_metadata-miss");
+       za_read_derive (ksp, "prefetch_data_misses",     "cache_result", "prefetch_data-miss");
+       za_read_derive (ksp, "prefetch_metadata_misses", "cache_result", "prefetch_metadata-miss");
+
+       /* Ratios */
+       arc_hits   = (gauge_t) get_kstat_value(ksp, "hits");
+       arc_misses = (gauge_t) get_kstat_value(ksp, "misses");
+       l2_hits    = (gauge_t) get_kstat_value(ksp, "l2_hits");
+       l2_misses  = (gauge_t) get_kstat_value(ksp, "l2_misses");
+
+       za_submit_ratio ("arc", arc_hits, arc_misses);
+       za_submit_ratio ("L2", l2_hits, l2_misses);
+
+       /* I/O */
+       l2_io[0].derive = get_kstat_value(ksp, "l2_read_bytes");
+       l2_io[1].derive = get_kstat_value(ksp, "l2_write_bytes");
+
+       za_submit ("io_octets", "L2", l2_io, /* num values = */ 2);
 
        return (0);
-}
+} /* int za_read */
 
 static int za_init (void) /* {{{ */
 {
-       ksp = NULL;
-
        /* kstats chain already opened by update_kstat (using *kc), verify everything went fine. */
        if (kc == NULL)
        {
index 6b3751d..762d547 100755 (executable)
@@ -1,6 +1,6 @@
-#!/bin/sh
+#!/usr/bin/env bash
 
-DEFAULT_VERSION="4.10.1.git"
+DEFAULT_VERSION="5.1.1.git"
 
 VERSION="`git describe 2> /dev/null | sed -e 's/^collectd-//'`"
 
@@ -10,8 +10,4 @@ fi
 
 VERSION="`echo \"$VERSION\" | sed -e 's/-/./g'`"
 
-if test "x`uname -s`" = "xAIX" || test "x`uname -s`" = "xSunOS" ; then
-       echo "$VERSION\c"
-else 
-       echo -n "$VERSION"
-fi
+echo -n "$VERSION"