collectd-perl

title: collectd-perl(5)

summary: Documentation of collectd's perl plugin

text:
# collectd-perl(5)

## NAME
collectd-perl - Documentation of collectd's "perl plugin"

## SYNOPSIS

```
  LoadPlugin perl
  # ...
  <Plugin perl>
    IncludeDir "/path/to/perl/plugins"
    BaseName "Collectd::Plugins"
    EnableDebugger ""
    LoadPlugin "FooBar"
    <Plugin FooBar>
      Foo "Bar"
    </Plugin>
  </Plugin>
```

## DESCRIPTION
The "perl plugin" embeds a Perl-interpreter into collectd and provides an interface to collectd's plugin system. This makes it possible to write plugins for collectd in Perl. This is a lot more efficient than executing a Perl-script every time you want to read a value with the "exec plugin" (see collectd-exec(5)) and provides a lot more functionality, too.

## CONFIGURATION
LoadPlugin Plugin

Loads the Perl plugin Plugin. This does basically the same as use would do in a Perl program. As a side effect, the first occurrence of this option causes the Perl-interpreter to be initialized.

BaseName Name

Prepends Name:: to all plugin names loaded after this option. This is provided for convenience to keep plugin names short. All Perl-based plugins provided with the collectd distributions reside in the "Collectd::Plugins" namespace.

<Plugin Name> block

This block may be used to pass on configuration settings to a Perl plugin. The configuration is converted into a config-item data type which is passed to the registered configuration callback. See below for details about the config-item data type and how to register callbacks. The name identifies the callback. It is used literally and independent of the BaseName setting.

EnableDebugger Package[=option,...]

Run collectd under the control of the Perl source debugger. If Package is not the empty string, control is passed to the debugging, profiling, or tracing module installed as Devel::Package. A comma-separated list of options may be specified after the "=" character. Please note that you may not leave out the Package option even if you specify "". This is the same as using the -d:Package command line option. See perldebug for detailed documentation about debugging Perl.

This option does not prevent collectd from daemonizing, so you should start collectd with the -f command line option. Else you will not be able to use the command line driven interface of the debugger.

IncludeDir Dir

Adds Dir to the @INC array. This is the same as using the -IDir command line option or use lib Dir in the source code. Please note that it only has effect on plugins loaded after this option.

RegisterLegacyFlush true|false

The "Perl plugin" used to register one flush callback (called "perl") and call all Perl-based flush handlers when this callback was called. Newer versions of the plugin wrap the Perl flush handlers and register them directly with the daemon in addition to the legacy "perl" callback. This allows to call specific Perl flush handlers, but has the downside that flushing all plugins now calls the Perl flush handlers twice (once directly and once via the legacy callback). Unfortunately, removing the "perl" callback would break backwards compatibility. This option allows you to disable the legacy "perl" flush callback if you care about the double call and don't call the "perl" callback in your setup.

## WRITING YOUR OWN PLUGINS
Writing your own plugins is quite simple. collectd manages plugins by means of dispatch functions which call the appropriate callback functions registered by the plugins. Any plugin basically consists of the implementation of these callback functions and initializing code which registers the functions with collectd. See the section "EXAMPLES" below for a really basic example. The following types of callback functions are known to collectd (all of them are optional):

configuration functions

This type of functions is called during configuration if an appropriate Plugin block has been encountered. It is called once for each Plugin block which matches the name of the callback as provided with the plugin_register method - see below.

init functions

This type of functions is 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. g. open sockets, ...). If the return value evaluates to false, the plugin will be disabled.

read functions

This type of function is used to collect the actual data. It is called once per interval (see the Interval configuration option of collectd). Usually it will call plugin_dispatch_values to dispatch the values to collectd which will pass them on to all registered write functions. If the return value evaluates to false the plugin will be skipped for an increasing amount of time until it returns true again.

write functions

This type of function is used to write the dispatched values. It is called once for each call to plugin_dispatch_values.

flush functions

This type of function is 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.

log functions

This type of function is used to pass messages of plugins or the daemon itself to the user.

notification function

This type of function is 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 collectd.conf(5) for more details), but any plugin may dispatch notifications as well.

shutdown functions

This type of function is called once before the daemon shuts down. It should be used to clean up the plugin (e.g. close sockets, ...).

Any function (except log functions) may set the $@ variable to describe errors in more detail. The message will be passed on to the user using collectd's logging mechanism.

See the documentation of the plugin_register method in the section "METHODS" below for the number and types of arguments passed to each callback function. This section also explains how to register callback functions with collectd.

To enable a plugin, copy it to a place where Perl can find it (i. e. a directory listed in the @INC array) just as any other Perl plugin and add an appropriate LoadPlugin option to the configuration file. After restarting collectd you're done.

## DATA TYPES
The following complex types are used to pass values between the Perl plugin and collectd:

Config-Item

A config-item is one structure which keeps the information provided in the configuration file. The array of children keeps one entry for each configuration option. Each such entry is another config-item structure, which may nest further if nested blocks are used.

```
  {
    key      => key,
    values   => [ val1, val2, ... ],
    children => [ { ... }, { ... }, ... ]
  }

```

Data-Set

A data-set is a list of one or more data-sources. Each data-source defines a name, type, min- and max-value and the data-set wraps them up into one structure. The general layout looks like this:

```
  [{
    name => 'data_source_name',
    type => DS_TYPE_COUNTER || DS_TYPE_GAUGE || DS_TYPE_DERIVE || DS_TYPE_ABSOLUTE,
    min  => value || undef,
    max  => value || undef
  }, ...]

```

Value-List

A value-list is one structure which features an array of values and fields to identify the values, i. e. time and host, plugin name and plugin-instance as well as a type and type-instance. Since the "type" is not included in the value-list but is passed as an extra argument, the general layout looks like this:

```
  {
    values => [123, 0.5],
    time   => time (),
    interval => plugin_get_interval (),
    host   => $hostname_g,
    plugin => 'myplugin',
    type   => 'myplugin',
    plugin_instance => '',
    type_instance   => ''
  }

```

Notification

A notification is one structure defining the severity, time and message of the status message as well as an identification of a data instance. Also, it includes an optional list of user-defined meta information represented as (name, value) pairs:

```
  {
    severity => NOTIF_FAILURE || NOTIF_WARNING || NOTIF_OKAY,
    time     => time (),
    message  => 'status message',
    host     => $hostname_g,
    plugin   => 'myplugin',
    type     => 'mytype',
    plugin_instance => '',
    type_instance   => '',
    meta     => [ { name => <name>, value => <value> }, ... ]
  }

```

Match-Proc

A match-proc is one structure storing the callbacks of a "match" of the filter chain infrastructure. The general layout looks like this:

```
  {
    create  => 'my_create',
    destroy => 'my_destroy',
    match   => 'my_match'
  }

```

Target-Proc

A target-proc is one structure storing the callbacks of a "target" of the filter chain infrastructure. The general layout looks like this:

```
  {
    create  => 'my_create',
    destroy => 'my_destroy',
    invoke  => 'my_invoke'
  }

```

## METHODS
The following functions provide the C-interface to Perl-modules. They are exported by the ":plugin" export tag (see the section "EXPORTS" below).

plugin_register (type, name, data)

Registers a callback-function or data-set. type can be one of:

TYPE_CONFIG

TYPE_INIT

TYPE_READ

TYPE_WRITE

TYPE_FLUSH

TYPE_LOG

TYPE_NOTIF

TYPE_SHUTDOWN

TYPE_DATASET

name is the name of the callback-function or the type of the data-set, depending on the value of type. (Please note that the type of the data-set is the value passed as name here and has nothing to do with the type argument which simply tells plugin_register what is being registered.)

The last argument, data, is either a function name or an array-reference. If type is TYPE_DATASET, then the data argument must be an array-reference which points to an array of hashes. Each hash describes one data-set. For the exact layout see Data-Set above. Please note that there is a large number of predefined data-sets available in the types.db file which are automatically registered with collectd - see types.db(5) for a description of the format of this file.

Note: Using plugin_register to register a data-set is deprecated. Add the new type to a custom types.db(5) file instead. This functionality might be removed in a future version of collectd.

If the type argument is any of the other types (TYPE_INIT, TYPE_READ, ...) then data is expected to be a function name. If the name is not prefixed with the plugin's package name collectd will add it automatically. The interface slightly differs from the C interface (which expects a function pointer instead) because Perl does not support to share references to subroutines between threads.

These functions are called in the various stages of the daemon (see the section "WRITING YOUR OWN PLUGINS" above) and are passed the following arguments:

TYPE_CONFIG

The only argument passed is config-item. See above for the layout of this data type.

TYPE_INIT

TYPE_READ

TYPE_SHUTDOWN

No arguments are passed.

TYPE_WRITE

The arguments passed are type, data-set, and value-list. type is a string. For the layout of data-set and value-list see above.

TYPE_FLUSH

The arguments passed are timeout and identifier. timeout indicates that only data older than timeout seconds is to be flushed. identifier specifies which values are to be flushed.

TYPE_LOG

The arguments are log-level and message. The log level is small for important messages and high for less important messages. The least important level is LOG_DEBUG, the most important level is LOG_ERR. In between there are (from least to most important): LOG_INFO, LOG_NOTICE, and LOG_WARNING. message is simply a string without a newline at the end.

TYPE_NOTIF

The only argument passed is notification. See above for the layout of this data type.

plugin_unregister (type, plugin)

Removes a callback or data-set from collectd's internal list of functions / datasets.

plugin_dispatch_values (value-list)

Submits a value-list to the daemon. If the data-set identified by value-list->{type} is found (and the number of values matches the number of data-sources) then the type, data-set and value-list is passed to all write-callbacks that are registered with the daemon.

plugin_write ([plugins => ...][, datasets => ...], valuelists => ...)

Calls the write function of the given plugins with the provided data sets and value lists. In contrast to plugin_dispatch_values, it does not update collectd's internal cache and bypasses the filter mechanism (see collectd.conf(5) for details). If the plugins argument has been omitted, the values will be dispatched to all registered write plugins. If the datasets argument has been omitted, the required data sets are looked up according to the "type" member in the appropriate value list. The value of all three arguments may either be a single scalar or a reference to an array. If the datasets argument has been specified, the number of data sets has to equal the number of specified value lists.

plugin_flush ([timeout => timeout][, plugins => ...][, identifiers => ...])

Flush one or more plugins. timeout and the specified identifiers are passed on to the registered flush-callbacks. If omitted, the timeout defaults to -1. The identifier defaults to the undefined value. If the plugins argument has been specified, only named plugins will be flushed. The value of the plugins and identifiers arguments may either be a string or a reference to an array of strings.

plugin_dispatch_notification (notification)

Submits a notification to the daemon which will then pass it to all notification-callbacks that are registered.

plugin_log (log-level, message)

Submits a message of level log-level to collectd's logging mechanism. The message is passed to all log-callbacks that are registered with collectd.

ERROR, WARNING, NOTICE, INFO, DEBUG (message)

Wrappers around plugin_log, using LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO and LOG_DEBUG respectively as log-level.

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 "LoadPlugin perl" block or the global interval (see collectd.conf(5) for details).

The following function provides the filter chain C-interface to Perl-modules. It is exported by the ":filter_chain" export tag (see the section "EXPORTS" below).

fc_register (type, name, proc)

Registers filter chain callbacks with collectd. type may be any of:

FC_MATCH

FC_TARGET

name is the name of the match or target. By this name, the callbacks are identified in the configuration file when specifying a Match or Target block (see collectd.conf(5) for details).

proc is a hash reference. The hash includes up to three callbacks: an optional constructor (create) and destructor (destroy) and a mandatory match or invoke callback. match is called whenever processing an appropriate match, while invoke is called whenever processing an appropriate target (see the section "FILTER CONFIGURATION" in collectd.conf(5) for details). Just like any other callbacks, filter chain callbacks are identified by the function name rather than a function pointer because Perl does not support to share references to subroutines between threads. The following arguments are passed to the callbacks:

create

The arguments passed are config-item and user-data. See above for the layout of the config-item data-type. user-data is a reference to a scalar value that may be used to store any information specific to this particular instance. The daemon does not care about this information at all. It's for the plugin's use only.

destroy

The only argument passed is user-data which is a reference to the user data initialized in the create callback. This callback may be used to cleanup instance-specific information and settings.

match, invoke

The arguments passed are data-set, value-list, meta and user-data. See above for the layout of the data-set and value-list data-types. meta is a pointer to an array of meta information, just like the meta member of the notification data-type (see above). user-data is a reference to the user data initialized in the create callback.

## GLOBAL VARIABLES
$hostname_g

As the name suggests this variable keeps the hostname of the system collectd is running on. The value might be influenced by the Hostname or FQDNLookup configuration options (see collectd.conf(5) for details).

$interval_g

This variable keeps the interval in seconds in which the read functions are queried (see the Interval configuration option). Note: This variable should no longer be used in favor of plugin_get_interval() (see above). This function takes any plugin-specific interval settings into account (see the "Interval" option of "LoadPlugin" in collectd.conf(5) for details).

Any changes to these variables will be globally visible in collectd.

## EXPORTS
By default no symbols are exported. However, the following export tags are available (:all will export all of them):

:plugin

plugin_register ()

plugin_unregister ()

plugin_dispatch_values ()

plugin_flush ()

plugin_flush_one ()

plugin_flush_all ()

plugin_dispatch_notification ()

plugin_log ()

:types

TYPE_CONFIG

TYPE_INIT

TYPE_READ

TYPE_WRITE

TYPE_FLUSH

TYPE_SHUTDOWN

TYPE_LOG

TYPE_DATASET

:ds_types

DS_TYPE_COUNTER

DS_TYPE_GAUGE

DS_TYPE_DERIVE

DS_TYPE_ABSOLUTE

:log

ERROR ()

WARNING ()

NOTICE ()

INFO ()

DEBUG ()

LOG_ERR

LOG_WARNING

LOG_NOTICE

LOG_INFO

LOG_DEBUG

:filter_chain

fc_register

FC_MATCH_NO_MATCH

FC_MATCH_MATCHES

FC_TARGET_CONTINUE

FC_TARGET_STOP

FC_TARGET_RETURN

:fc_types

FC_MATCH

FC_TARGET

:notif

NOTIF_FAILURE

NOTIF_WARNING

NOTIF_OKAY

:globals

$hostname_g

$interval_g

## EXAMPLES
Any Perl plugin will start similar to:

```
  package Collectd::Plugins::FooBar;
  use strict;
  use warnings;
  use Collectd qw( :all );
```

A very simple read function might look like:

```
  sub foobar_read
  {
    my $vl = { plugin => 'foobar', type => 'gauge' };
    $vl->{'values'} = [ rand(42) ];
    plugin_dispatch_values ($vl);
    return 1;
  }
```

A very simple write function might look like:

```
  sub foobar_write
  {
    my ($type, $ds, $vl) = @_;
    for (my $i = 0; $i < scalar (@$ds); ++$i) {
      print "$vl->{'plugin'} ($vl->{'type'}): $vl->{'values'}->[$i]\n";
    }
    return 1;
  }
```

A very simple match callback might look like:

```
  sub foobar_match
  {
    my ($ds, $vl, $meta, $user_data) = @_;
    if (matches($ds, $vl)) {
      return FC_MATCH_MATCHES;
    } else {
      return FC_MATCH_NO_MATCH;
    }
  }
```

To register those functions with collectd:

```
  plugin_register (TYPE_READ, "foobar", "foobar_read");
  plugin_register (TYPE_WRITE, "foobar", "foobar_write");
  fc_register (FC_MATCH, "foobar", "foobar_match");
```

See the section "DATA TYPES" above for a complete documentation of the data types used by the read, write and match functions.

## NOTES
•

Please feel free to send in new plugins to collectd's mailing list at <collectd at collectd.org> 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. Before submitting your plugin, please take a look at <http://collectd.org/dev-info.shtml>.

## CAVEATS

- collectd is heavily multi-threaded. Each collectd thread accessing the perl plugin will be mapped to a Perl interpreter thread (see threads(3perl)). Any such thread will be created and destroyed transparently and on-the-fly. Hence, any plugin has to be thread-safe if it provides several entry points from collectd (i. e. if it registers more than one callback or if a registered callback may be called more than once in parallel). Please note that no data is shared between threads by default. You have to use the threads::shared module to do so.

- Each function name registered with collectd has to be available before the first thread has been created (i. e. basically at compile time). This basically means that hacks (yes, I really consider this to be a hack) like "*foo = \&bar; plugin_register (TYPE_READ, "plugin", "foo");" most likely will not work. This is due to the fact that the symbol table is not shared across different threads.

- Each plugin is usually only loaded once and kept in memory for performance reasons. Therefore, END blocks are only executed once when collectd shuts down. You should not rely on END blocks anyway - use shutdown functions instead.

- The perl plugin exports the internal API of collectd which is considered unstable and subject to change at any time. We try hard to not break backwards compatibility in the Perl API during the life cycle of one major release. However, this cannot be guaranteed at all times. Watch out for warnings dispatched by the perl plugin after upgrades.

## SEE ALSO
collectd(1), collectd.conf(5), collectd-exec(5), types.db(5), perl(1), threads(3perl), threads::shared(3perl), perldebug(1)

## AUTHOR
The "perl plugin" has been written by Sebastian Harl <sh at tokkee.org>.

This manpage has been written by Florian Forster <octo at collectd.org> and Sebastian Harl <sh at tokkee.org>.


collectd-python

package: collectd

title: collectd-python(5)

summary: Documentation of collectd's python plugin

text:
# collectd-python(5)

## NAME
collectd-python - Documentation of collectd's "python plugin"

## SYNOPSIS

```
  LoadPlugin python
  # ...
  <Plugin python>
    ModulePath "/path/to/your/python/modules"
    LogTraces true
    Interactive false
    Import "spam"
    <Module spam>
      spam "wonderful" "lovely"
    </Module>
  </Plugin>
```

## DESCRIPTION
The "python plugin" embeds a Python-interpreter into collectd and provides an interface to collectd's plugin system. This makes it possible to write plugins 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 "exec plugin" (see collectd-exec(5)) and provides a lot more functionality, too.

The minimum required Python version is 2.6.

## CONFIGURATION
LoadPlugin Plugin

Loads the Python plugin Plugin.

Encoding Name

The default encoding for Unicode objects you pass to collectd. If you omit this option it will default to ascii on Python 2. On Python 3 it will always be utf-8, as this function was removed, so this will be silently ignored. These defaults are hardcoded in Python and will ignore everything else, including your locale.

ModulePath Name

Prepends Name to sys.path. You won't be able to import any scripts you wrote unless they are located in one of the directories in this list. Please note that it only has effect on plugins loaded after this option. You can use multiple ModulePath lines to add more than one directory.

LogTraces bool

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 does not apply to the CollectError exception, which will never log a stacktrace. This should probably be set to false most of the time but is very useful for development and debugging of new modules.

Interactive bool

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 so make sure to start collectd with the -f option. The collectd module is 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:

- 1. collectd will try to import the readline module to give you a decent way of entering your commands. The daemonized collectd won't do that.

- 2. Python will be handling SIGINT. Pressing Ctrl+C will usually cause collectd to shut down. This would be problematic in an interactive session, therefore Python will be handling it in interactive sessions. This allows you to use Ctrl+C to interrupt Python code without killing collectd. This also means you can catch KeyboardInterrupt exceptions which does not work during normal operation. To quit collectd send EOF (press Ctrl+D at the beginning of a new line).

- 3. collectd handles 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 to display help texts. You can override this behavior with the PAGER environment variable, e.g. export PAGER=less before starting collectd. Depending on your version of Python this might or might not result in an OSError exception which can be ignored. 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 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 contrib/python/getsigchld.py to do this. If you import this from collectd.conf SIGCHLD will be handled normally and spawning processes from Python will work as intended.

Import Name

Imports the python script Name and loads it into the collectd python process. If your python script is not found, be sure its directory exists in python's sys.path. You can prepend to the sys.path using the ModulePath configuration option.

<Module Name> block

This block may be used to pass on configuration settings to a Python module. The configuration is converted into an instance of the Config class which is passed to the registered configuration callback. See below for details about the Config class and how to register callbacks. The name identifies the callback.

## STRINGS
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 str, which is just bytes, and unicode. Python3 has str, which is a unicode object, and bytes.

When passing strings from Python to collectd all of these object are supported in all places, however str should be used if possible. These strings must not contain a NUL byte. Ignoring this will result in a 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 UnicodeEncodeError exception.

When passing strings from collectd to Python the behavior depends on the Python version used. Python2 will always receive a str object. Python3 will usually receive a 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 bytes object will be returned instead.

## WRITING YOUR OWN PLUGINS
Writing your own plugins is quite simple. collectd manages plugins by means of dispatch functions which call the appropriate callback functions registered by the plugins. Any plugin basically consists of the implementation of these callback functions and initializing code which registers the functions with collectd. See the section "EXAMPLES" below for a really basic example. The following types of callback functions are known to collectd (all of them are optional):

configuration functions

These are called during configuration if an appropriate Module block has been encountered. It is called once for each Module block which matches the name of the callback as provided with the register_config method - see below. Python thread support has not been initialized at this point so do not use any threading functions here!

init functions

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. g. open sockets, ...). This is the earliest point where you may use threads.

read functions

These are used to collect the actual data. It is called once per interval (see the Interval configuration option of collectd). Usually it will call plugin_dispatch_values to dispatch the values to collectd which will pass them on to all registered write functions. If this function throws any kind of exception the plugin will be skipped for an increasing amount of time until it returns normally again.

write functions

These are used to write the dispatched values. It is called once for every value that was dispatched by any plugin.

flush functions

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.

log functions

These are used to pass messages of plugins or the daemon itself to the user.

notification function

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 collectd.conf(5) for more details), but any plugin may dispatch notifications as well.

shutdown functions

These are called once before the daemon shuts down. It should be used to clean up the plugin (e.g. close sockets, ...).

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.

See the documentation of the various register_ methods in the section "FUNCTIONS" below for the number and types of arguments passed to each callback function. This section also explains how to register callback functions with collectd.

To enable a module, copy it to a place where Python can find it (i. e. a directory listed in sys.path) just as any other Python plugin and add an appropriate Import option to the configuration file. After restarting collectd you're done.

## CLASSES
The following complex types are used to pass values between the Python plugin and collectd:

### CollectdError
This is an exception. If any Python script raises this exception it will still be treated like an error by collectd but it will be logged as a warning instead of an error and it will never generate a stacktrace.

```
 class CollectdError(Exception)
```

Basic exception for collectd Python scripts. Throwing this exception will not cause a stacktrace to be logged, even if LogTraces is enabled in the config.

### Signed
The Signed class is just a long. It has all its methods and behaves exactly like any other long object. It is used to indicate if an integer was or should be stored as a signed or unsigned integer object.

```
 class Signed(long)
```

This is a long by another name. Use it in meta data dicts to choose the way it is stored in the meta data.

### Unsigned
The Unsigned class is just a long. It has all its methods and behaves exactly like any other long object. It is used to indicate if an integer was or should be stored as a signed or unsigned integer object.

```
 class Unsigned(long)
```

This is a long by another name. Use it in meta data dicts to choose the way it is stored in the meta data.

### Config
The Config class is an object which keeps the information provided in the configuration file. The sequence of children keeps one entry for each configuration option. Each such entry is another Config instance, which may nest further if nested blocks are used.

```
 class Config(object)
```

This represents a piece of collectd's config file. It is passed to scripts with config callbacks (see register_config) and is of little use if created somewhere else.

It has no methods beyond the bare minimum and only exists for its data members.

Data descriptors defined here:

parent

This represents the parent of this node. On the root node of the config tree it will be None.

key

This is the keyword of this item, i.e. the first word of any given line in the config file. It will always be a string.

values

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, a float or a boolean, depending on the contents of the configuration file.

children

This is a tuple of child nodes. For most nodes this will be empty. If this node represents a block instead of a single line of the config file it will contain all nodes in this block.

### PluginData
This should not be used directly but it is the base class for both Values and Notification. It is used to identify the source of a value or notification.

```
 class PluginData(object)
```

This is an internal class that is the base for Values and Notification. It is pretty useless by itself and was therefore not exported to the collectd module.

Data descriptors defined here:

host

The hostname of the host this value was read from. For dispatching this can be set to an empty string which means the local hostname as defined in collectd.conf.

plugin

The name of the plugin that read the data. Setting this member to an empty string will insert "python" upon dispatching.

plugin_instance

Plugin instance string. May be empty.

time

This is the Unix timestamp of the time this value was read. For dispatching values this can be set to zero which means "now". This means the time the value is actually dispatched, not the time it was set to 0.

type

The type of this value. This type has to be defined in your types.db. Attempting to set it to any other value will raise a TypeError exception. Assigning a type is mandatory, calling dispatch without doing so will raise a RuntimeError exception.

type_instance

Type instance string. May be empty.

### Values
A Value is an object which features a sequence of values. It is based on the PluginData type and uses its members to identify the values.

```
 class Values(PluginData)
```

A Values object used for dispatching values to collectd and receiving values from write callbacks.

Method resolution order:

Values

PluginData

object

Methods defined here:

dispatch([type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.

Dispatch this instance to the collectd process. The object has members for each of the possible arguments for this method. For a detailed explanation of these parameters see the member of the same same. If you do not submit a parameter the value saved in its member will be submitted. If you do provide a parameter it will be used instead, without altering the member.

write([destination][, type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.

Write this instance to a single plugin or all plugins if "destination" is omitted. This will bypass the main collectd process and all filtering and caching. Other than that it works similar to "dispatch". In most cases "dispatch" should be used instead of "write".

Data descriptors defined here:

interval

The interval is the timespan in seconds between two submits for the same data source. This value has to be a positive integer, so you can't submit more than one value per second. If this member is set to a non-positive value, the default value as specified in the config file will be used (default: 10). If you submit values more often than the specified interval, the average will be used. If you submit less values, your graphs will have gaps.

values

These are the actual values that get dispatched to collectd. It has to be a sequence (a tuple or list) of numbers. The size of the sequence and the type of its content depend on the type member your types.db file. For more information on this read the types.db(5) manual page. If the sequence does not have the correct size upon dispatch a RuntimeError exception will be raised. If the content of the sequence is not a number, a TypeError exception will be raised.

meta

These are the meta data for this Value object. It has to be a dictionary of numbers, strings or bools. All keys must be strings. int and <long> objects will be dispatched as signed integers unless they are between 2**63 and 2**64-1, which will result in a unsigned integer. You can force one of these storage classes by using the classes collectd.Signed and collectd.Unsigned. A meta object received by a write callback will always contain Signed or Unsigned objects.

### Notification
A notification is an object defining the severity and message of the status message as well as an identification of a data instance by means of the members of PluginData on which it is based.

class Notification(PluginData) The Notification class is a wrapper around the collectd notification. It can be used to notify other plugins about bad stuff happening. It works similar to Values but has a severity and a message instead of interval and time. Notifications can be dispatched at any time and can be received with register_notification.

Method resolution order:

Notification

PluginData

object

Methods defined here:

dispatch([type][, message][, plugin_instance][, type_instance][, plugin][, host][, time][, severity][, meta]) -> None. Dispatch a notification.

Dispatch this instance to the collectd process. The object has members for each of the possible arguments for this method. For a detailed explanation of these parameters see the member of the same same. If you do not submit a parameter the value saved in its member will be submitted. If you do provide a parameter it will be used instead, without altering the member.

Data descriptors defined here:

message

Some kind of description of what's going on and why this Notification was generated.

severity

The severity of this notification. Assign or compare to NOTIF_FAILURE, NOTIF_WARNING or NOTIF_OKAY.

meta

These are the meta data for the Notification object. It has to be a dictionary of numbers, strings or bools. All keys must be strings. int and long objects will be dispatched as signed integers unless they are between 2**63 and 2**64-1, which will result in a unsigned integer. One of these storage classes can be forced by using the classes collectd.Signed and collectd.Unsigned. A meta object received by a notification callback will always contain Signed or Unsigned objects.

## FUNCTIONS
The following functions provide the C-interface to Python-modules.

register_*(callback[, data][, name]) -> identifier

There are eight different register functions to get callback for eight different events. With one exception all of them are called as shown above.

- callback is a callable object that will be called every time the event is triggered.

- data is an optional object that will be passed back to the callback function every time it is called. If you omit this parameter no object is passed back to your callback, not even None.

- name is an optional identifier for this callback. The default name is python.module. module is taken from the __module__ attribute of your callback function. Every callback needs a unique identifier, so if you 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.

- identifier is the full identifier assigned to this callback.

These functions are called in the various stages of the daemon (see the section "WRITING YOUR OWN PLUGINS" above) and are passed the following arguments:

register_config

The only argument passed is a Config object. See above for the layout of this data type. Note that you cannot receive the whole config files this way, only Module blocks inside the Python configuration block. Additionally you will only receive blocks where your callback identifier matches python.blockname.

register_init

The callback will be called without arguments.

register_read(callback[, interval][, data][, name]) -> identifier

This function takes an additional parameter: interval. It specifies the time between calls to the callback function. The callback will be called without arguments.

register_shutdown

The callback will be called without arguments.

register_write

The callback function will be called with one argument passed, which will be a Values object. For the layout of Values see above. If this callback function throws an exception the next call will be delayed by an increasing interval.

register_flush

Like register_config is important for this callback because it determines what flush requests the plugin will receive. The arguments passed are timeout and identifier. timeout indicates that only data older than timeout seconds is to be flushed. identifier specifies which values are to be flushed.

register_log

The arguments are severity and message. The severity is an integer and small for important messages and high for less important messages. The least important level is LOG_DEBUG, the most important level is LOG_ERR. In between there are (from least to most important): LOG_INFO, LOG_NOTICE, and LOG_WARNING. message is simply a string without a newline at the end. If this callback throws an exception it will not be logged. It will just be printed to sys.stderr which usually means silently ignored.

register_notification

The only argument passed is a Notification object. See above for the layout of this data type.

unregister_*(identifier) -> None

Removes a callback or data-set from collectd's internal list of callback functions. Every register_* function has an unregister_* function. identifier is either the string that was returned by the register function or a callback function. The identifier will be constructed in the same way as for the register functions.

get_dataset(name) -> definition

Returns the definition of a dataset specified by name. definition is a list of tuples, each representing one data source. Each tuple has 4 values:

name

A string, the name of the data source.

type

A string that is equal to either of the variables DS_TYPE_COUNTER, DS_TYPE_GAUGE, DS_TYPE_DERIVE or DS_TYPE_ABSOLUTE.

min

A float or None, the minimum value.

max

A float or None, the maximum value.

flush(plugin[, timeout][, identifier]) - None

Flush one or all plugins. timeout and the specified identifiers are passed on to the registered flush-callbacks. If omitted, the timeout defaults to -1. The identifier defaults to None. If the plugin argument has been specified, only named plugin will be flushed.

error, warning, notice, info, debug(message)

Log a message with the specified severity.

## EXAMPLES
Any Python module will start similar to:

```
  import collectd
```

A very simple read function might look like:

```
  import random
  def read(data=None):
    vl = collectd.Values(type='gauge')
    vl.plugin='python.spam'
    vl.dispatch(values=[random.random() * 100])
```

A very simple write function might look like:

```
  def write(vl, data=None):
    for i in vl.values:
      print "%s (%s): %f" % (vl.plugin, vl.type, i)
```

To register those functions with collectd:

```
  collectd.register_read(read)
  collectd.register_write(write)
```

See the section "CLASSES" above for a complete documentation of the data types used by the read, write and match functions.

## CAVEATS

- 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. Hence, any plugin has to be thread-safe if it provides several entry points from collectd (i. e. if it registers more than one callback or if a registered callback may be called more than once in parallel).

- The Python thread module is initialized just before calling the init callbacks. This means you must not use Python's threading module prior to this point. This includes all config and possibly other callback as well.

- The python plugin exports the internal API of collectd which is considered unstable and subject to change at any time. We try hard to not break backwards compatibility in the Python API during the life cycle of one major release. However, this cannot be guaranteed at all times. Watch out for warnings dispatched by the python plugin after upgrades.

## KNOWN BUGS
•

Not all aspects of the collectd API are accessible from Python. This includes but is not limited to filters.

## SEE ALSO
collectd(1), collectd.conf(5), collectd-perl(5), collectd-exec(5), types.db(5), python(1),

## AUTHOR
The "python plugin" has been written by Sven Trenkel <collectd at semidefinite.de>.

This manpage has been written by Sven Trenkel <collectd at semidefinite.de>. It is based on the collectd-perl(5) manual page by Florian Forster <octo at collectd.org> and Sebastian Harl <sh at tokkee.org>.


collectd-snmp

title: collectd-snmp(5)

summary: Documentation of collectd's snmp plugin

text:
# collectd-snmp(5)

## NAME
collectd-snmp - Documentation of collectd's "snmp plugin"

## SYNOPSIS

```
  LoadPlugin snmp
  # ...
  <Plugin snmp>
    <Data "powerplus_voltge_input">
      Table false
      Type "voltage"
      TypeInstance "input_line1"
      Scale 0.1
      Values "SNMPv2-SMI::enterprises.6050.5.4.1.1.2.1"
    </Data>
    <Data "hr_users">
      Table false
      Type "users"
      Shift -1
      Values "HOST-RESOURCES-MIB::hrSystemNumUsers.0"
    </Data>
    <Data "std_traffic">
      Table true
      Type "if_octets"
      TypeInstanceOID "IF-MIB::ifDescr"
      #FilterOID "IF-MIB::ifOperStatus"
      #FilterValues "1", "2"
      Values "IF-MIB::ifInOctets" "IF-MIB::ifOutOctets"
    </Data>
    <Data "lancom_stations_total">
        Type "counter"
        PluginInstance "stations_total"
        Table true
        Count true
        Values "SNMPv2-SMI::enterprises.2356.11.1.3.32.1.10" # SNMPv2-SMI::enterprises.lancom-systems.lcos.lcsStatus.lcsStatusWlan.lcsStatusWlanStationTableTable.lcsStatusWlanStationTableEntry.lcsStatusWlanStationTableEntryState
    </Data>
    <Data "lancom_stations_connected">
        Type "counter"
        PluginInstance "stations_connected"
        Table true
        Count true
        Values "SNMPv2-SMI::enterprises.2356.11.1.3.32.1.10" # SNMPv2-SMI::enterprises.lancom-systems.lcos.lcsStatus.lcsStatusWlan.lcsStatusWlanStationTableTable.lcsStatusWlanStationTableEntry.lcsStatusWlanStationTableEntryState
        FilterOID "SNMPv2-SMI::enterprises.2356.11.1.3.32.1.10"
        FilterValues "3" # eConnected
    </Data>
    <Host "some.switch.mydomain.org">
      Address "192.168.0.2"
      Version 1
      Community "community_string"
      Collect "std_traffic"
      Interval 120
      Timeout 10
      Retries 1
    </Host>
    <Host "some.server.mydomain.org">
      Address "192.168.0.42"
      Version 2
      Community "another_string"
      Collect "std_traffic" "hr_users"
    </Host>
    <Host "secure.router.mydomain.org">
      Address "192.168.0.7:165"
      Version 3
      SecurityLevel "authPriv"
      Username "cosmo"
      AuthProtocol "SHA"
      AuthPassphrase "setec_astronomy"
      PrivacyProtocol "AES"
      PrivacyPassphrase "too_many_secrets"
      Collect "std_traffic"
    </Host>
    <Host "some.ups.mydomain.org">
      Address "tcp:192.168.0.3"
      Version 1
      Community "more_communities"
      Collect "powerplus_voltge_input"
      Interval 300
      Timeout 5
      Retries 5
    </Host>
  </Plugin>
```

## DESCRIPTION
The "snmp plugin" queries other hosts using SNMP, the simple network management protocol, and translates the value it receives to collectd's internal format and dispatches them. Depending on the write plugins you have loaded they may be written to disk or submitted to another instance or whatever you configured.

Because querying a host via SNMP may produce a timeout the "complex reads" polling method is used. The ReadThreads parameter in the main configuration influences the number of parallel polling jobs which can be undertaken. If you expect timeouts or some polling to take a long time, you should increase this parameter. Note that other plugins also use the same threads.

## CONFIGURATION
Since the aim of the "snmp plugin" is to provide a generic interface to SNMP, its configuration is not trivial and may take some time.

Since the "Net-SNMP" library is used you can use all the environment variables that are interpreted by that package. See snmpcmd(1) for more details.

There are two types of blocks that can be contained in the "<Plugin snmp>" block: Data and Host:

### The Data block
The Data block defines a list of values or a table of values that are to be queried. The following options can be set:

Type type

collectd's type that is to be used, e. g. "if_octets" for interface traffic or "users" for a user count. The types are read from the TypesDB (see collectd.conf(5)), so you may want to check for which types are defined. See types.db(5) for a description of the format of this file.

Table true|false

Define if this is a single list of values or a table of values. The difference is the following: When Table is set to false, the OIDs given to Values (see below) are queried using the "GET" SNMP command (see snmpget(1)) and transmitted to collectd. One value list is dispatched and, eventually, one file will be written.

When Table is set to true, the OIDs given to Values, TypeInstanceOID, PluginInstanceOID, HostOID and FilterOID (see below) are queried using the "GETNEXT" SNMP command until the subtree is left. After all the lists (think: all columns of the table) have been read, either (Count set to false) several value sets will be dispatched and, eventually, several files will be written, or (Count set to true) one single value will be dispatched. If you configure a Type (see above) which needs more than one data source (for example "if_octets" which needs "rx" and "tx") you will need to specify more than one (two, in the example case) OIDs with the Values option and can't use the Count option. This has nothing to do with the Table setting.

For example, if you want to query the number of users on a system, you can use "HOST-RESOURCES-MIB::hrSystemNumUsers.0". This is one value and belongs to one value list, therefore Table must be set to false. Please note that, in this case, you have to include the sequence number (zero in this case) in the OID.

Counter example: If you want to query the interface table provided by the "IF-MIB", e. g. the bytes transmitted. There are potentially many interfaces, so you will want to set Table to true. Because the "if_octets" type needs two values, received and transmitted bytes, you need to specify two OIDs in the Values setting, in this case likely "IF-MIB::ifHCInOctets" and "IF-MIB::ifHCOutOctets". But, this is because of the Type setting, not the Table setting.

Since the semantic of Instance and Values depends on this setting you need to set it before setting them. Doing vice versa will result in undefined behavior.

Plugin Plugin

Use Plugin as the plugin name of the values that are dispatched. Defaults to "snmp".

PluginInstance Instance

Sets the plugin-instance of the values that are dispatched to Instance value. When Table is set to true and PluginInstanceOID is set then this option has no effect.

Defaults to an empty string.

TypeInstance Instance

Sets the type-instance of the values that are dispatched to Instance value. When Table is set to true and TypeInstanceOID is set then this option has no effect.

Defaults to an empty string.

TypeInstanceOID OID

PluginInstanceOID OID

HostOID OID

If Table is set to true, OID is interpreted as an SNMP-prefix that will return a list of values. Those values are then used as the actual type-instance, plugin-instance or host of dispatched metrics. An example would be the "IF-MIB::ifDescr" subtree. variables(5) from the SNMP distribution describes the format of OIDs. When option is set to empty string, then "SUBID" will be used as the value. Prefix may be set for values with use of appropriate TypeInstancePrefix, PluginInstancePrefix and HostPrefix options.

When Table is set to false or Count is set to true, these options have no effect.

Defaults: When no one of these options is configured explicitly, TypeInstanceOID defaults to an empty string.

TypeInstancePrefix

PluginInstancePrefix

HostPrefix

These options are intented to be used together with TypeInstanceOID, PluginInstanceOID and HostOID respectively. If set, String is preprended to values received by querying the agent.

When Table is set to false or Count is set to true, these options have no effect.

The "UPS-MIB" is an example where you need this setting: It has voltages of the inlets, outlets and the battery of an UPS. However, it doesn't provide a descriptive column for these voltages. In this case having 1, 2, ... as instances is not enough, because the inlet voltages and outlet voltages may both have the subids 1, 2, ... You can use this setting to distinguish between the different voltages.

Instance Instance

Attention: this option exists for backwards compatibility only and will be removed in next major release. Please use TypeInstance / TypeInstanceOID instead. The meaning of this setting depends on whether Table is set to true or false.

If Table is set to true, option behaves as TypeInstanceOID. If Table is set to false, option behaves as TypeInstance.

Note what Table option must be set before setting Instance.

InstancePrefix String

Attention: this option exists for backwards compatibility only and will be removed in next major release. Please use TypeInstancePrefix instead.

Values OID [OID ...]

Configures the values to be queried from the SNMP host. The meaning slightly changes with the Table setting. variables(5) from the SNMP distribution describes the format of OIDs. If Table is set to true, each OID must be the prefix of all the values to query, e. g. "IF-MIB::ifInOctets" for all the counters of incoming traffic. This subtree is walked (using "GETNEXT") until a value from outside the subtree is returned.

If Table is set to false, each OID must be the OID of exactly one value, e. g. "IF-MIB::ifInOctets.3" for the third counter of incoming traffic.

Count true|false

Instead of dispatching one or multiple values per Table entry containing the OID(s) given in the Values option, just dispatch a single count giving the number of entries that would have been dispatched. This is especially useful when combined with the filtering options (see below) to count the number of entries in a Table matching certain criteria. When Table is set to false, this option has no effect.

Scale Value

The gauge-values returned by the SNMP-agent are multiplied by Value. This is useful when values are transferred as a fixed point real number. For example, thermometers may transfer 243 but actually mean 24.3, so you can specify a scale value of 0.1 to correct this. The default value is, of course, 1.0. This value is not applied to counter-values.

Shift Value

Value is added to gauge-values returned by the SNMP-agent after they have been multiplied by any Scale value. If, for example, a thermometer returns degrees Kelvin you could specify a shift of 273.15 here to store values in degrees Celsius. The default value is, of course, 0.0. This value is not applied to counter-values.

Ignore Value [, Value ...]

The ignore values allows one to ignore TypeInstances based on their name and the patterns specified by the various values you've entered. The match is a glob-type shell matching. When Table is set to false then this option has no effect.

InvertMatch true|false(default)

The invertmatch value should be use in combination of the Ignore option. It changes the behaviour of the Ignore option, from a blacklist behaviour when InvertMatch is set to false, to a whitelist when specified to true.

FilterOID OID

FilterValues Value [, Value ...]

FilterIgnoreSelected true|false(default)

When Table is set to true, these options allow to configure filtering based on MIB values. The FilterOID declares OID to fill table column with values. The FilterValues declares values list to do match. Whether table row will be collected or ignored depends on the FilterIgnoreSelected setting. As with other plugins that use the daemon's ignorelist functionality, a string that starts and ends with a slash is interpreted as a regular expression.

If no selection is configured at all, all table rows are selected.

When Table is set to false then these options has no effect.

See Table and /"IGNORELISTS" for details.

### The Host block
The Host block defines which hosts to query, which SNMP community and version to use and which of the defined Data to query.

The argument passed to the Host block is used as the hostname in the data stored by collectd.

Address IP-Address|Hostname

Set the address to connect to. Address may include transport specifier and/or port number.

Version 1|2|3

Set the SNMP version to use. When giving 2 version "2c" is actually used.

Community Community

Pass Community to the host. (Ignored for SNMPv3).

Username Username

Sets the Username to use for SNMPv3 security.

SecurityLevel authPriv|authNoPriv|noAuthNoPriv

Selects the security level for SNMPv3 security.

Context Context

Sets the Context for SNMPv3 security.

AuthProtocol MD5|SHA

Selects the authentication protocol for SNMPv3 security.

AuthPassphrase Passphrase

Sets the authentication passphrase for SNMPv3 security.

PrivacyProtocol AES|DES

Selects the privacy (encryption) protocol for SNMPv3 security.

PrivacyPassphrase Passphrase

Sets the privacy (encryption) passphrase for SNMPv3 security.

Collect Data [Data ...]

Defines which values to collect. Data refers to one of the Data block above. Since the config file is read top-down you need to define the data before using it here.

Interval Seconds

Collect data from this host every Seconds seconds. This option is meant for devices with not much CPU power, e. g. network equipment such as switches, embedded devices, rack monitoring systems and so on. Since the Step of generated RRD files depends on this setting it's wise to select a reasonable value once and never change it.

Timeout Seconds

How long to wait for a response. The "Net-SNMP" library default is 1 second.

Retries Integer

The number of times that a query should be retried after the Timeout expires. The "Net-SNMP" library default is 5.

BulkSize Integer

Configures the size of SNMP bulk transfers. The default is 0, which disables bulk transfers altogether.

## SEE ALSO
collectd(1), collectd.conf(5), snmpget(1), snmpgetnext(1), variables(5), unix(7)

## AUTHORS
Florian Forster <octo@collectd.org> Michael Pilat <mike@mikepilat.com>


collectd-threshold

title: collectd-threshold(5)

text:
# collectd-threshold(5)

## NAME
collectd-threshold - Documentation of collectd's Threshold plugin

## 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>
```

## DESCRIPTION
Starting with version 4.3.0 collectd has support for 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 Threshold plugin takes itself is to generate and dispatch a 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 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 Timeout iterations. The Timeout configuration option is explained in section "GLOBAL OPTIONS" in collectd.conf(5). If, for example, Timeout is set to "2" (the default) and some hosts sends its 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 Interval on the server.

When a value comes within range again or is received after it was missing, an "OKAY-notification" is dispatched.

## 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 "Host", "Plugin", and "Type" blocks select the value for which a threshold should be configured. The "Plugin" and "Type" blocks may be specified further using the "Instance" option. You can combine the block by nesting the blocks, though they must be nested in the above order, i.e. "Host" may contain either "Plugin" and "Type" blocks, "Plugin" may only contain "Type" blocks and "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 must be included in a "Type" block. Currently the following statements are recognized:

FailureMax Value

WarningMax Value

Sets the upper bound of acceptable values. If unset defaults to positive infinity. If a value is greater than FailureMax a FAILURE notification will be created. If the value is greater than WarningMax but less than (or equal to) FailureMax a WARNING notification will be created.

FailureMin Value

WarningMin Value

Sets the lower bound of acceptable values. If unset defaults to negative infinity. If a value is less than FailureMin a FAILURE notification will be created. If the value is less than WarningMin but greater than (or equal to) FailureMin a WARNING notification will be created.

DataSource DSName

Some data sets have more than one "data source". Interesting examples are the "if_octets" data set, which has received ("rx") and sent ("tx") bytes and the "disk_ops" data set, which holds "read" and "write" operations. The system load data set, "load", even has three data sources: "shortterm", "midterm", and "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 DataSource option to have a threshold apply only to one data source.

Invert true|false

If set to true the range of acceptable values is inverted, i.e. values between FailureMin and FailureMax (WarningMin and WarningMax) are not okay. Defaults to false.

Persist true|false

Sets how often notifications are generated. If set to true one notification will be generated for each value that is out of the acceptable range. If set to 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 true a notification about a missing value is generated once every Interval seconds. If set to false only one such notification is generated until the value appears again.

PersistOK true|false

Sets how OKAY notifications act. If set to true one notification will be generated for each value that is in the acceptable range. If set to false (the default) then a notification is only generated if a value is in range but the previous value was not.

Percentage true|false

If set to 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 5 % of the total space is available. Defaults to false.

Hits Value

Sets the number of occurrences which the threshold must be raised before to dispatch any notification or, in other words, the number of Intervals that the threshold must be match before dispatch any notification.

Hysteresis 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 (WarningMax, FailureMin or everything else) minus the hysteresis value, the failure (respectively warning) state will be keep.

Interesting true|false

If set to true (the default), a notification with severity "FAILURE" will be created when a matching value list is no longer updated and purged from the internal cache. When this happens depends on the interval of the value list and the global Timeout setting. See the Interval and Timeout settings in collectd.conf(5) for details. If set to false, this event will be ignored.

## SEE ALSO
collectd(1), collectd.conf(5)

## AUTHOR
Florian Forster <octo at collectd.org>


collectd-unixsock

title: collectd-unixsock(5)

summary: Documentation of collectd's unixsock plugin

text:
# collectd-unixsock(5)

## NAME
collectd-unixsock - Documentation of collectd's "unixsock plugin"

## SYNOPSIS

```
  # See collectd.conf(5)
  LoadPlugin unixsock
  # ...
  <Plugin unixsock>
    SocketFile "/path/to/socket"
    SocketGroup "collectd"
    SocketPerms "0770"
    DeleteSocket false
  </Plugin>
```

## DESCRIPTION
The "unixsock plugin" opens an UNIX-socket over which one can interact with the daemon. This can be used to use the values collected by collectd in other applications, such as monitoring solutions, or submit externally collected values to collectd.

For example, this plugin is used by collectd-nagios(1) to check if some value is in a certain range and exit with a Nagios-compatible exit code.

## COMMANDS
Upon start the "unixsock plugin" opens a UNIX-socket and waits for connections. Once a connection is established the client can send commands to the daemon which it will answer, if it understand them.

In general the plugin answers with a status line of the following form:

Status Message

If Status is greater than or equal to zero the message indicates success, if Status is less than zero the message indicates failure. Message is a human-readable string that further describes the return value.

On success, Status furthermore indicates the number of subsequent lines of output (not including the status line). Each such lines usually contains a single return value. See the description of each command for details.

The following commands are implemented:

GETVAL Identifier

If the value identified by Identifier (see below) is found the complete value-list is returned. The response is a list of name-value-pairs, each pair on its own line (the number of lines is indicated by the status line - see above). Each name-value-pair is of the form name=value. Counter-values are converted to a rate, e. g. bytes per second. Undefined values are returned as NaN. Example:

-> | GETVAL myhost/cpu-0/cpu-user

<- | 1 Value found

<- | value=1.260000e+00

LISTVAL

Returns a list of the values available in the value cache together with the time of the last update, so that querying applications can issue a GETVAL command for the values that have changed. Each return value consists of the update time as an epoch value and the identifier, separated by a space. The update time is the time of the last value, as provided by the collecting instance and may be very different from the time the server considers to be "now". Example:

-> | LISTVAL

<- | 69 Values found

<- | 1182204284 myhost/cpu-0/cpu-idle

<- | 1182204284 myhost/cpu-0/cpu-nice

<- | 1182204284 myhost/cpu-0/cpu-system

<- | 1182204284 myhost/cpu-0/cpu-user

...

PUTVAL Identifier [OptionList] Valuelist

Submits one or more values (identified by Identifier, see below) to the daemon which will dispatch it to all its write-plugins. An Identifier is of the form "host/plugin-instance/type-instance" with both instance-parts being optional. If they're omitted the hyphen must be omitted, too. plugin and each instance-part may be chosen freely as long as the tuple (plugin, plugin instance, type instance) uniquely identifies the plugin within collectd. type identifies the type and number of values (i. e. data-set) passed to collectd. A large list of predefined data-sets is available in the types.db file.

The OptionList is an optional list of Options, where each option is a key-value-pair. A list of currently understood options can be found below, all other options will be ignored. Values that contain spaces must be quoted with double quotes.

Valuelist is a colon-separated list of the time and the values, each either an integer if the data-source is a counter, or a double if the data-source is of type "gauge". You can submit an undefined gauge-value by using U. When submitting U to a counter the behavior is undefined. The time is given as epoch (i. e. standard UNIX time).

You can mix options and values, but the order is important: Options only effect following values, so specifying an option as last field is allowed, but useless. Also, an option applies to all following values, so you don't need to re-set an option over and over again.

The currently defined Options are:

interval=seconds

Gives the interval in which the data identified by Identifier is being collected.

meta:key=value

Add meta data with the key key and the value value.

Please note that this is the same format as used in the exec plugin, see collectd-exec(5).

Example:

-> | PUTVAL testhost/interface/if_octets-test0 interval=10 1179574444:123:456

<- | 0 Success

PUTNOTIF [OptionList] message=Message

Submits a notification to the daemon which will then dispatch it to all plugins which have registered for receiving notifications. The PUTNOTIF command is followed by a list of options which further describe the notification. The message option is special in that it will consume the rest of the line as its value. The message, severity, and time options are mandatory.

Valid options are:

message=Message (REQUIRED)

Sets the message of the notification. This is the message that will be made accessible to the user, so it should contain some useful information. As with all options: If the message includes spaces, it must be quoted with double quotes. This option is mandatory.

severity=failure|warning|okay (REQUIRED)

Sets the severity of the notification. This option is mandatory.

time=Time (REQUIRED)

Sets the time of the notification. The time is given as "epoch", i. e. as seconds since January 1st, 1970, 00:00:00. This option is mandatory.

host=Hostname

plugin=Plugin

plugin_instance=Plugin-Instance

type=Type

type_instance=Type-Instance

These "associative" options establish a relation between this notification and collected performance data. This connection is purely informal, i. e. the daemon itself doesn't do anything with this information. However, websites or GUIs may use this information to place notifications near the affected graph or table. All the options are optional, but plugin_instance without plugin or type_instance without type doesn't make much sense and should be avoided.

type:key=value

Sets user defined meta information. The type key is a single character defining the type of the meta information. The current supported types are:

s A string passed as-is.

Please note that this is the same format as used in the exec plugin, see collectd-exec(5).

Example:

-> | PUTNOTIF type=temperature severity=warning time=1201094702 message=The roof is on fire!

<- | 0 Success

FLUSH [timeout=Timeout] [plugin=Plugin [...]] [identifier=Ident [...]]

Flushes all cached data older than Timeout seconds. If no timeout has been specified, it defaults to -1 which causes all data to be flushed. If the plugin option has been specified, only the Plugin plugin will be flushed. You can have multiple plugin options to flush multiple plugins in one go. If the plugin option is not given all plugins providing a flush callback will be flushed.

If the identifier option is given only the specified values will be flushed. This is meant to be used by graphing or displaying frontends which want to have the latest values for a specific graph. Again, you can specify the identifier option multiple times to flush several values. If this option is not specified at all, all values will be flushed.

Example:

-> | FLUSH plugin=rrdtool identifier=localhost/df/df-root identifier=localhost/df/df-var

<- | 0 Done: 2 successful, 0 errors

### Identifiers
Value or value-lists are identified in a uniform fashion:

Hostname/Plugin/Type

Where Plugin and Type are both either of type "Name" or "Name-Instance". If the identifier includes spaces, it must be quoted using double quotes. This sounds more complicated than it is, so here are some examples:

```
  myhost/cpu-0/cpu-user
  myhost/load/load
  myhost/memory/memory-used
  myhost/disk-sda/disk_octets
  "myups/snmp/temperature-Outlet 1"
```

## ABSTRACTION LAYER
collectd ships the Perl-Module Collectd::Unixsock which provides an abstraction layer over the actual socket connection. It can be found in the directory bindings/perl/ in the source distribution or (usually) somewhere near /usr/share/perl5/ if you're using a package. If you want to use Perl to communicate with the daemon, you're encouraged to use and expand this module.

## SEE ALSO
collectd(1), collectd.conf(5), collectd-nagios(1), unix(7)

## AUTHOR
Florian Forster <octo@collectd.org>