1 =head1 NAME
3 collectd-python - Documentation of collectd's C<python plugin>
5 =head1 SYNOPSIS
7 <LoadPlugin python>
8 Globals true
9 </LoadPlugin>
10 # ...
11 <Plugin python>
12 ModulePath "/path/to/your/python/modules"
13 LogTraces true
14 Interactive true
15 Import "spam"
17 <Module spam>
18 spam "wonderful" "lovely"
19 </Module>
20 </Plugin>
22 =head1 DESCRIPTION
24 The C<python plugin> embeds a Python-interpreter into collectd and provides an
25 interface to collectd's plugin system. This makes it possible to write plugins
26 for collectd in Python. This is a lot more efficient than executing a
27 Python-script every time you want to read a value with the C<exec plugin> (see
28 L<collectd-exec(5)>) and provides a lot more functionality, too.
30 At least python I<version 2.3> is required.
32 =head1 CONFIGURATION
34 =over 4
36 =item B<LoadPlugin> I<Plugin>
38 Loads the Python plugin I<Plugin>. Unlike most other LoadPlugin lines, this one
39 should be a block containing the line "Globals true". This will cause collectd
40 to export the name of all objects in the python interpreter for all plugins to
41 see. If you don't do this or your platform does not support it, the embedded
42 interpreter will start anyway but you won't be able to load certain python
43 modules, e.g. "time".
45 =item B<Encoding> I<Name>
47 The default encoding for Unicode objects you pass to collectd. If you omit this
48 option it will default to B<ascii> on I<Python 2> and B<utf-8> on I<Python 3>.
49 This is hardcoded in Python and will ignore everything else, including your
50 locale.
52 =item B<ModulePath> I<Name>
54 Appends I<Name> to B<sys.path>. You won't be able to import any scripts you
55 wrote unless they are located in one of the directories in this list. Please
56 note that it only has effect on plugins loaded after this option. You can
57 use multiple B<ModulePath> lines to add more than one directory.
59 =item B<LogTraces> I<bool>
61 If a python script throws an exception it will be logged by collectd with the
62 name of the exception and the message. If you set this option to true it will
63 also log the full stacktrace just like the default output of an interactive
64 python interpreter. This should probably be set to false most of the time but
65 is very useful for development and debugging of new modules.
67 =item B<Interactive> I<bool>
69 This option will cause the module to launch an interactive python interpreter
70 that reads from and writes to the terminal. Note that collectd will terminate
71 right after starting up if you try to run it as a daemon while this option is
72 enabled to make sure to start collectd with the B<-f> option.
74 The B<collectd> module is I<not> imported into the interpreter's globals. You
75 have to do it manually. Be sure to read the help text of the module, it can be
76 used as a reference guide during coding.
78 This interactive session will behave slightly differently from a daemonized
79 collectd script as well as from a normal python interpreter:
81 =over 4
83 =item
85 B<1.> collectd will try to import the B<readline> module to give you a decent
86 way of entering your commands. The daemonized collectd won't do that.
88 =item
90 B<2.> collectd will block I<SIGINT>. Pressing I<Ctrl+C> will usually cause
91 collectd to shut down. This would be problematic in an interactive session,
92 therefore this signal will be blocked. You can still use it to interrupt
93 syscalls like sleep and pause but it won't generate a I<KeyboardInterrupt>
94 exception either.
96 To quit collectd send I<EOF> (press I<Ctrl+D> at the beginning of a new line).
98 =item
100 B<3.> collectd handles I<SIGCHLD>. This means that python won't be able to
101 determine the return code of spawned processes with system(), popen() and
102 subprocess. This will result in python not using external programs like less
103 to display help texts. You can override this behavior with the B<PAGER>
104 environment variable, e.g. I<export PAGER=less> before starting collectd.
105 Depending on your version of python this might or might not result in an
106 B<OSError> exception which can be ignored.
108 If you really need to spawn new processes from python you can register an init
109 callback and reset the action for SIGCHLD to the default behavior. Please note
110 that this I<will> break the exec plugin. Do not even load the exec plugin if
111 you intend to do this!
113 There is an example script located in B<contrib/python/getsigchld.py> to do
114 this. If you import this from I<collectd.conf> SIGCHLD will be handled
115 normally and spawning processes from python will work as intended.
117 =back
119 =item E<lt>B<Module> I<Name>E<gt> block
121 This block may be used to pass on configuration settings to a Python module.
122 The configuration is converted into an instance of the B<Config> class which is
123 passed to the registered configuration callback. See below for details about
124 the B<Config> class and how to register callbacks.
126 The I<name> identifies the callback.
128 =back
130 =head1 STRINGS
132 There are a lot of places where strings are send from collectd to python and
133 from python to collectd. How exactly this works depends on wheather byte or
134 unicode strings or python2 or python3 are used.
136 Python2 has I<str>, which is just bytes, and I<unicode>. Python3 has I<str>,
137 which is a unicode object, and I<bytes>.
139 When passing strings from python to collectd all of these object are supported
140 in all places, however I<str> should be used if possible. These strings must
141 not contain a NUL byte. Ignoring this will result in a I<TypeError> exception.
142 If a byte string was used it will be used as is by collectd. If a unicode
143 object was used it will be encoded using the default encoding (see above). If
144 this is not possible python will raise a I<UnicodeEncodeError> exception.
146 Wenn passing strings from collectd to python the behavior depends on the
147 python version used. Python2 will always receive a I<str> object. Python3 will
148 usually receive a I<str> object as well, however the original string will be
149 decoded to unicode using the default encoding. If this fails because the
150 string is not a valid sequence for this encoding a I<bytes> object will be
151 returned instead.
153 =head1 WRITING YOUR OWN PLUGINS
155 Writing your own plugins is quite simple. collectd manages plugins by means of
156 B<dispatch functions> which call the appropriate B<callback functions>
157 registered by the plugins. Any plugin basically consists of the implementation
158 of these callback functions and initializing code which registers the
159 functions with collectd. See the section "EXAMPLES" below for a really basic
160 example. The following types of B<callback functions> are known to collectd
161 (all of them are optional):
163 =over 4
165 =item configuration functions
167 This type of functions is called during configuration if an appropriate
168 B<Module> block has been encountered. It is called once for each B<Module>
169 block which matches the name of the callback as provided with the
170 B<register_config> method - see below.
172 Python thread support has not been initialized at this point so do not use any
173 threading functions here!
175 =item init functions
177 This type of functions is called once after loading the module and before any
178 calls to the read and write functions. It should be used to initialize the
179 internal state of the plugin (e.E<nbsp>g. open sockets, ...). This is the
180 earliest point where you may use threads.
182 =item read functions
184 This type of function is used to collect the actual data. It is called once
185 per interval (see the B<Interval> configuration option of collectd). Usually
186 it will call B<plugin_dispatch_values> to dispatch the values to collectd
187 which will pass them on to all registered B<write functions>. If this function
188 throws any kind of exception the plugin will be skipped for an increasing
189 amount of time until it returns normally again.
191 =item write functions
193 This type of function is used to write the dispatched values. It is called
194 once for every value that was dispatched by any plugin.
196 =item flush functions
198 This type of function is used to flush internal caches of plugins. It is
199 usually triggered by the user only. Any plugin which caches data before
200 writing it to disk should provide this kind of callback function.
202 =item log functions
204 This type of function is used to pass messages of plugins or the daemon itself
205 to the user.
207 =item notification function
209 This type of function is used to act upon notifications. In general, a
210 notification is a status message that may be associated with a data instance.
211 Usually, a notification is generated by the daemon if a configured threshold
212 has been exceeded (see the section "THRESHOLD CONFIGURATION" in
213 L<collectd.conf(5)> for more details), but any plugin may dispatch
214 notifications as well.
216 =item shutdown functions
218 This type of function is called once before the daemon shuts down. It should
219 be used to clean up the plugin (e.g. close sockets, ...).
221 =back
223 Any function (except log functions) may set throw an exception in case of any
224 errors. The exception will be passed on to the user using collectd's logging
225 mechanism. If a log callback throws an exception it will be printed to standard
226 error instead.
228 See the documentation of the various B<register_> methods in the section
229 "FUNCTIONS" below for the number and types of arguments passed to each
230 B<callback function>. This section also explains how to register B<callback
231 functions> with collectd.
233 To enable a module, copy it to a place where Python can find it (i.E<nbsp>e. a
234 directory listed in B<sys.path>) just as any other Python plugin and add
235 an appropriate B<Import> option to the configuration file. After restarting
236 collectd you're done.
238 =head1 CLASSES
240 The following complex types are used to pass values between the Python plugin
241 and collectd:
243 =head2 Signed
245 The Signed class is just a long. It has all its methods and behaves exactly
246 like any other long object. It is used to indicate if an integer was or should
247 be stored as a signed or unsigned integer object.
249 class Signed(long)
251 This is a long by another name. Use it in meta data dicts
252 to choose the way it is stored in the meta data.
254 =head2 Unsigned
256 The Unsigned class is just a long. It has all its methods and behaves exactly
257 like any other long object. It is used to indicate if an integer was or should
258 be stored as a signed or unsigned integer object.
260 class Unsigned(long)
262 This is a long by another name. Use it in meta data dicts
263 to choose the way it is stored in the meta data.
265 =head2 Config
267 The Config class is an object which keeps the information provided in the
268 configuration file. The sequence of children keeps one entry for each
269 configuration option. Each such entry is another Config instance, which
270 may nest further if nested blocks are used.
272 class Config(object)
274 This represents a piece of collectd's config file. It is passed to scripts with
275 config callbacks (see B<register_config>) and is of little use if created
276 somewhere else.
278 It has no methods beyond the bare minimum and only exists for its data members.
280 Data descriptors defined here:
282 =over 4
284 =item parent
286 This represents the parent of this node. On the root node
287 of the config tree it will be None.
289 =item key
291 This is the keyword of this item, i.e. the first word of any given line in the
292 config file. It will always be a string.
294 =item values
296 This is a tuple (which might be empty) of all value, i.e. words following the
297 keyword in any given line in the config file.
299 Every item in this tuple will be either a string or a float or a boolean,
300 depending on the contents of the configuration file.
302 =item children
304 This is a tuple of child nodes. For most nodes this will be empty. If this node
305 represents a block instead of a single line of the config file it will contain
306 all nodes in this block.
308 =back
310 =head2 PluginData
312 This should not be used directly but it is the base class for both Values and
313 Notification. It is used to identify the source of a value or notification.
315 class PluginData(object)
317 This is an internal class that is the base for Values and Notification. It is
318 pretty useless by itself and was therefore not exported to the collectd module.
320 Data descriptors defined here:
322 =over 4
324 =item host
326 The hostname of the host this value was read from. For dispatching this can be
327 set to an empty string which means the local hostname as defined in
328 collectd.conf.
330 =item plugin
332 The name of the plugin that read the data. Setting this member to an empty
333 string will insert "python" upon dispatching.
335 =item plugin_instance
337 Plugin instance string. May be empty.
339 =item time
341 This is the Unix timestamp of the time this value was read. For dispatching
342 values this can be set to zero which means "now". This means the time the value
343 is actually dispatched, not the time it was set to 0.
345 =item type
347 The type of this value. This type has to be defined in your I<types.db>.
348 Attempting to set it to any other value will raise a I<TypeError> exception.
349 Assigning a type is mandatory, calling dispatch without doing so will raise a
350 I<RuntimeError> exception.
352 =item type_instance
354 Type instance string. May be empty.
356 =back
358 =head2 Values
360 A Value is an object which features a sequence of values. It is based on then
361 I<PluginData> type and uses its members to identify the values.
363 class Values(PluginData)
365 A Values object used for dispatching values to collectd and receiving values
366 from write callbacks.
368 Method resolution order:
370 =over 4
372 =item Values
374 =item PluginData
376 =item object
378 =back
380 Methods defined here:
382 =over 4
384 =item B<dispatch>([type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.
386 Dispatch this instance to the collectd process. The object has members for each
387 of the possible arguments for this method. For a detailed explanation of these
388 parameters see the member of the same same.
390 If you do not submit a parameter the value saved in its member will be
391 submitted. If you do provide a parameter it will be used instead, without
392 altering the member.
394 =item B<write>([destination][, type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.
396 Write this instance to a single plugin or all plugins if "destination" is
397 omitted. This will bypass the main collectd process and all filtering and
398 caching. Other than that it works similar to "dispatch". In most cases
399 "dispatch" should be used instead of "write".
401 =back
403 Data descriptors defined here:
405 =over 4
407 =item interval
409 The interval is the timespan in seconds between two submits for the same data
410 source. This value has to be a positive integer, so you can't submit more than
411 one value per second. If this member is set to a non-positive value, the
412 default value as specified in the config file will be used (default: 10).
414 If you submit values more often than the specified interval, the average will
415 be used. If you submit less values, your graphs will have gaps.
417 =item values
419 These are the actual values that get dispatched to collectd. It has to be a
420 sequence (a tuple or list) of numbers. The size of the sequence and the type of
421 its content depend on the type member your I<types.db> file. For more
422 information on this read the L<types.db(5)> manual page.
424 If the sequence does not have the correct size upon dispatch a I<RuntimeError>
425 exception will be raised. If the content of the sequence is not a number, a
426 I<TypeError> exception will be raised.
428 =item meta
430 These are the meta data for this Value object.
431 It has to be a dictionary of numbers, strings or bools. All keys must be
432 strings. I<int> and <long> objects will be dispatched as signed integers unless
433 they are between 2**63 and 2**64-1, which will result in a unsigned integer.
434 You can force one of these storage classes by using the classes
435 B<collectd.Signed> and B<collectd.Unsigned>. A meta object received by a write
436 callback will always contain B<Signed> or B<Unsigned> objects.
438 =back
440 =head2 Notification
442 A notification is an object defining the severity and message of the status
443 message as well as an identification of a data instance by means of the members
444 of I<PluginData> on which it is based.
446 class Notification(PluginData)
447 The Notification class is a wrapper around the collectd notification.
448 It can be used to notify other plugins about bad stuff happening. It works
449 similar to Values but has a severity and a message instead of interval
450 and time.
451 Notifications can be dispatched at any time and can be received with
452 register_notification.
454 Method resolution order:
456 =over 4
458 =item Notification
460 =item PluginData
462 =item object
464 =back
466 Methods defined here:
468 =over 4
470 =item B<dispatch>([type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None. Dispatch a value list.
472 Dispatch this instance to the collectd process. The object has members for each
473 of the possible arguments for this method. For a detailed explanation of these
474 parameters see the member of the same same.
476 If you do not submit a parameter the value saved in its member will be
477 submitted. If you do provide a parameter it will be used instead, without
478 altering the member.
480 =back
482 Data descriptors defined here:
484 =over 4
486 =item message
488 Some kind of description what's going on and why this Notification was
489 generated.
491 =item severity
493 The severity of this notification. Assign or compare to I<NOTIF_FAILURE>,
494 I<NOTIF_WARNING> or I<NOTIF_OKAY>.
496 =back
498 =head1 FUNCTIONS
500 The following functions provide the C-interface to Python-modules.
502 =over 4
504 =item B<register_*>(I<callback>[, I<data>][, I<name>]) -> identifier
506 There are eight different register functions to get callback for eight
507 different events. With one exception all of them are called as shown above.
509 =over 4
511 =item
513 I<callback> is a callable object that will be called every time the event is
514 triggered.
516 =item
518 I<data> is an optional object that will be passed back to the callback function
519 every time it is called. If you omit this parameter no object is passed back to
520 your callback, not even None.
522 =item
524 I<name> is an optional identifier for this callback. The default name is
525 B<python>.I<module>. I<module> is taken from the B<__module__> attribute of
526 your callback function. Every callback needs a unique identifier, so if you
527 want to register the same callback multiple time in the same module you need to
528 specify a name here. Otherwise it's save to ignore this parameter I<identifier>
529 is the full identifier assigned to this callback.
531 =back
533 These functions are called in the various stages of the daemon (see the section
534 L<"WRITING YOUR OWN PLUGINS"> above) and are passed the following arguments:
536 =over 4
538 =item register_config
540 The only argument passed is a I<Config> object. See above for the layout of this
541 data type.
542 Note that you can not receive the whole config files this way, only B<Module>
543 blocks inside the Python configuration block. Additionally you will only
544 receive blocks where your callback identifier matches B<python.>I<blockname>.
546 =item register_init
548 The callback will be called without arguments.
550 =item register_read(callback[, interval][, data][, name]) -> identifier
552 This function takes an additional parameter: I<interval>. It specifies the
553 time between calls to the callback function.
555 The callback will be called without arguments.
557 =item register_shutdown
559 The callback will be called without arguments.
561 =item register_write
563 The callback function will be called with one arguments passed, which will be a
564 I<Values> object. For the layout of I<Values> see above.
565 If this callback function throws an exception the next call will be delayed by
566 an increasing interval.
568 =item register_flush
570 Like B<register_config> is important for this callback because it determines
571 what flush requests the plugin will receive.
573 The arguments passed are I<timeout> and I<identifier>. I<timeout> indicates
574 that only data older than I<timeout> seconds is to be flushed. I<identifier>
575 specifies which values are to be flushed.
577 =item register_log
579 The arguments are I<severity> and I<message>. The severity is an integer and
580 small for important messages and high for less important messages. The least
581 important level is B<LOG_DEBUG>, the most important level is B<LOG_ERR>. In
582 between there are (from least to most important): B<LOG_INFO>, B<LOG_NOTICE>,
583 and B<LOG_WARNING>. I<message> is simply a string B<without> a newline at the
584 end.
586 If this callback throws an exception it will B<not> be logged. It will just be
587 printed to B<sys.stderr> which usually means silently ignored.
589 =item register_notification
591 The only argument passed is a I<Notification> object. See above for the layout of this
592 data type.
594 =back
596 =item B<unregister_*>(I<identifier>) -> None
598 Removes a callback or data-set from collectd's internal list of callback
599 functions. Every I<register_*> function has an I<unregister_*> function.
600 I<identifier> is either the string that was returned by the register function
601 or a callback function. The identifier will be constructed in the same way as
602 for the register functions.
604 =item B<flush>(I<plugin[, I<timeout>][, I<identifier>]) -> None
606 Flush one or all plugins. I<timeout> and the specified I<identifiers> are
607 passed on to the registered flush-callbacks. If omitted, the timeout defaults
608 to C<-1>. The identifier defaults to None. If the B<plugin> argument has been
609 specified, only named plugin will be flushed.
611 =item B<error>, B<warning>, B<notice>, B<info>, B<debug>(I<message>)
613 Log a message with the specified severity.
615 =back
617 =head1 EXAMPLES
619 Any Python module will start similar to:
621 import collectd
623 A very simple read function might look like:
625 def read(data=None):
626 vl = collectd.Values(type='gauge')
627 vl.plugin='python.spam'
628 vl.dispatch(values=[random.random() * 100])
630 A very simple write function might look like:
632 def write(vl, data=None):
633 for i in vl.values:
634 print "%s (%s): %f" % (vl.plugin, vl.type, i)
636 To register those functions with collectd:
638 collectd.register_read(read);
639 collectd.register_write(write);
641 See the section L<"CLASSES"> above for a complete documentation of the data
642 types used by the read, write and match functions.
644 =head1 NOTES
646 =over 4
648 =item
650 Please feel free to send in new plugins to collectd's mailinglist at
651 E<lt>collectdE<nbsp>atE<nbsp>verplant.orgE<gt> for review and, possibly,
652 inclusion in the main distribution. In the latter case, we will take care of
653 keeping the plugin up to date and adapting it to new versions of collectd.
655 Before submitting your plugin, please take a look at
656 L<http://collectd.org/dev-info.shtml>.
658 =back
660 =head1 CAVEATS
662 =over 4
664 =item
666 collectd is heavily multi-threaded. Each collectd thread accessing the python
667 plugin will be mapped to a Python interpreter thread. Any such thread will be
668 created and destroyed transparently and on-the-fly.
670 Hence, any plugin has to be thread-safe if it provides several entry points
671 from collectd (i.E<nbsp>e. if it registers more than one callback or if a
672 registered callback may be called more than once in parallel).
674 =item
676 The Python thread module is initialized just before calling the init callbacks.
677 This means you must not use Python's threading module prior to this point. This
678 includes all config and possibly other callback as well.
680 =item
682 The python plugin exports the internal API of collectd which is considered
683 unstable and subject to change at any time. We try hard to not break backwards
684 compatibility in the Python API during the life cycle of one major release.
685 However, this cannot be guaranteed at all times. Watch out for warnings
686 dispatched by the python plugin after upgrades.
688 =back
690 =head1 KNOWN BUGS
692 =over 4
694 =item
696 This plugin is not compatible with python3. Trying to compile it with python3
697 will fail because of the ways string, unicode and bytearray behavior was
698 changed.
700 =item
702 Not all aspects of the collectd API are accessible from python. This includes
703 but is not limited to meta-data, filters and data sets.
705 =back
707 =head1 SEE ALSO
709 L<collectd(1)>,
710 L<collectd.conf(5)>,
711 L<collectd-perl(5)>,
712 L<collectd-exec(5)>,
713 L<types.db(5)>,
714 L<python(1)>,
716 =head1 AUTHOR
718 The C<python plugin> has been written by
719 Sven Trenkel E<lt>collectdE<nbsp>atE<nbsp>semidefinite.deE<gt>.
721 This manpage has been written by Sven Trenkel
722 E<lt>collectdE<nbsp>atE<nbsp>semidefinite.deE<gt>.
723 It is based on the L<collectd-perl(5)> manual page by
724 Florian Forster E<lt>octoE<nbsp>atE<nbsp>verplant.orgE<gt> and
725 Sebastian Harl E<lt>shE<nbsp>atE<nbsp>tokkee.orgE<gt>.
727 =cut