1 # Permission is hereby granted, free of charge, to any person obtaining a
2 # copy of this software and associated documentation files (the "Software"),
3 # to deal in the Software without restriction, including without limitation
4 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
5 # and/or sell copies of the Software, and to permit persons to whom the
6 # Software is furnished to do so, subject to the following conditions:
7 #
8 # The above copyright notice and this permission notice shall be included in
9 # all copies or substantial portions of the Software.
11 =head1 NAME
13 collectd-python - Documentation of collectd's C<python plugin>
15 =head1 SYNOPSIS
17 <LoadPlugin python>
18 Globals true
19 </LoadPlugin>
20 # ...
21 <Plugin python>
22 ModulePath "/path/to/your/python/modules"
23 LogTraces true
24 Interactive true
25 Import "spam"
27 <Module spam>
28 spam "wonderful" "lovely"
29 </Module>
30 </Plugin>
32 =head1 DESCRIPTION
34 The C<python plugin> embeds a Python-interpreter into collectd and provides an
35 interface to collectd's plugin system. This makes it possible to write plugins
36 for collectd in Python. This is a lot more efficient than executing a
37 Python-script every time you want to read a value with the C<exec plugin> (see
38 L<collectd-exec(5)>) and provides a lot more functionality, too.
40 Currently only I<Python 2> is supported and at least I<version 2.3> is
41 required.
43 =head1 CONFIGURATION
45 =over 4
47 =item B<LoadPlugin> I<Plugin>
49 Loads the Python plugin I<Plugin>. Unlike most other LoadPlugin lines, this one
50 should be a block containing the line "Globals true". This will cause collectd
51 to export the name of all objects in the python interpreter for all plugins to
52 see. If you don't do this or your platform does not support it, the embedded
53 interpreter will start anyway but you won't be able to load certain python
54 modules, e.g. "time".
56 =item B<Encoding> I<Name>
58 The default encoding for Unicode objects you pass to collectd. If you omit this
59 option it will default to B<ascii> on I<Python 2> and B<utf-8> on I<Python 3>.
60 This is hardcoded in Python and will ignore everything else, including your
61 locale.
63 =item B<ModulePath> I<Name>
65 Appends I<Name> to B<sys.path>. You won't be able to import any scripts you
66 wrote unless they are located in one of the directories in this list. Please
67 note that it only has effect on plugins loaded after this option. You can
68 use multiple B<ModulePath> lines to add more than one directory.
70 =item B<LogTraces> I<bool>
72 If a python script throws an exception it will be logged by collectd with the
73 name of the exception and the message. If you set this option to true it will
74 also log the full stacktrace just like the default output of an interactive
75 python interpreter. This should probably be set to false most of the time but
76 is very useful for development and debugging of new modules.
78 =item B<Interactive> I<bool>
80 This option will cause the module to launch an interactive python interpreter
81 that reads from and writes to the terminal. Note that collectd will terminate
82 right after starting up if you try to run it as a daemon while this option is
83 enabled to make sure to start collectd with the B<-f> option.
85 The B<collectd> module is I<not> imported into the interpreter's globals. You
86 have to do it manually. Be sure to read the help text of the module, it can be
87 used as a reference guide during coding.
89 This interactive session will behave slightly differently from a daemonized
90 collectd script as well as from a normal python interpreter:
92 =over 4
94 =item
96 B<1.> collectd will try to import the B<readline> module to give you a decent
97 way of entering your commands. The daemonized collectd won't do that.
99 =item
101 B<2.> collectd will block I<SIGINT>. Pressing I<Ctrl+C> will usually cause
102 collectd to shut down. This would be problematic in an interactive session,
103 therefore this signal will be blocked. You can still use it to interrupt
104 syscalls like sleep and pause but it won't generate a I<KeyboardInterrupt>
105 exception either.
107 To quit collectd send I<EOF> (press I<Ctrl+D> at the beginning of a new line).
109 =item
111 B<3.> collectd handles I<SIGCHLD>. This means that python won't be able to
112 determine the return code of spawned processes with system(), popen() and
113 subprocess. This will result in python not using external programs like less
114 to display help texts. You can override this behavior with the B<PAGER>
115 environment variable, e.g. I<export PAGER=less> before starting collectd.
116 Depending on your version of python this might or might not result in an
117 B<OSError> exception which can be ignored.
119 =back
121 =item E<lt>B<Module> I<Name>E<gt> block
123 This block may be used to pass on configuration settings to a Python module.
124 The configuration is converted into an instance of the B<Config> class which is
125 passed to the registered configuration callback. See below for details about
126 the B<Config> class and how to register callbacks.
128 The I<name> identifies the callback.
130 =back
132 =head1 WRITING YOUR OWN PLUGINS
134 Writing your own plugins is quite simple. collectd manages plugins by means of
135 B<dispatch functions> which call the appropriate B<callback functions>
136 registered by the plugins. Any plugin basically consists of the implementation
137 of these callback functions and initializing code which registers the
138 functions with collectd. See the section "EXAMPLES" below for a really basic
139 example. The following types of B<callback functions> are known to collectd
140 (all of them are optional):
142 =over 4
144 =item configuration functions
146 This type of functions is called during configuration if an appropriate
147 B<Module> block has been encountered. It is called once for each B<Module>
148 block which matches the name of the callback as provided with the
149 B<register_config> method - see below.
151 Python thread support has not been initialized at this point so do not use any
152 threading functions here!
154 =item init functions
156 This type of functions is called once after loading the module and before any
157 calls to the read and write functions. It should be used to initialize the
158 internal state of the plugin (e.E<nbsp>g. open sockets, ...). This is the
159 earliest point where you may use threads.
161 =item read functions
163 This type of function is used to collect the actual data. It is called once
164 per interval (see the B<Interval> configuration option of collectd). Usually
165 it will call B<plugin_dispatch_values> to dispatch the values to collectd
166 which will pass them on to all registered B<write functions>. If this function
167 throws any kind of exception the plugin will be skipped for an increasing
168 amount of time until it returns normally again.
170 =item write functions
172 This type of function is used to write the dispatched values. It is called
173 once for every value that was dispatched by any plugin.
175 =item flush functions
177 This type of function is used to flush internal caches of plugins. It is
178 usually triggered by the user only. Any plugin which caches data before
179 writing it to disk should provide this kind of callback function.
181 =item log functions
183 This type of function is used to pass messages of plugins or the daemon itself
184 to the user.
186 =item notification function
188 This type of function is used to act upon notifications. In general, a
189 notification is a status message that may be associated with a data instance.
190 Usually, a notification is generated by the daemon if a configured threshold
191 has been exceeded (see the section "THRESHOLD CONFIGURATION" in
192 L<collectd.conf(5)> for more details), but any plugin may dispatch
193 notifications as well.
195 =item shutdown functions
197 This type of function is called once before the daemon shuts down. It should
198 be used to clean up the plugin (e.g. close sockets, ...).
200 =back
202 Any function (except log functions) may set throw an exception in case of any
203 errors. The exception will be passed on to the user using collectd's logging
204 mechanism. If a log callback throws an exception it will be printed to standard
205 error instead.
207 See the documentation of the various B<register_> methods in the section
208 "FUNCTIONS" below for the number and types of arguments passed to each
209 B<callback function>. This section also explains how to register B<callback
210 functions> with collectd.
212 To enable a module, copy it to a place where Python can find it (i.E<nbsp>e. a
213 directory listed in B<sys.path>) just as any other Python plugin and add
214 an appropriate B<Import> option to the configuration file. After restarting
215 collectd you're done.
217 =head1 CLASSES
219 The following complex types are used to pass values between the Python plugin
220 and collectd:
222 =head2 Config
224 The Config class is an object which keeps the information provided in the
225 configuration file. The sequence of children keeps one entry for each
226 configuration option. Each such entry is another Config instance, which
227 may nest further if nested blocks are used.
229 class Config(object)
231 This represents a piece of collectd's config file. It is passed to scripts with
232 config callbacks (see B<register_config>) and is of little use if created
233 somewhere else.
235 It has no methods beyond the bare minimum and only exists for its data members.
237 Data descriptors defined here:
239 =over 4
241 =item parent
243 This represents the parent of this node. On the root node
244 of the config tree it will be None.
246 =item key
248 This is the keyword of this item, i.e. the first word of any given line in the
249 config file. It will always be a string.
251 =item values
253 This is a tuple (which might be empty) of all value, i.e. words following the
254 keyword in any given line in the config file.
256 Every item in this tuple will be either a string or a float or a boolean,
257 depending on the contents of the configuration file.
259 =item children
261 This is a tuple of child nodes. For most nodes this will be empty. If this node
262 represents a block instead of a single line of the config file it will contain
263 all nodes in this block.
265 =back
267 =head2 PluginData
269 This should not be used directly but it is the base class for both Values and
270 Notification. It is used to identify the source of a value or notification.
272 class PluginData(object)
274 This is an internal class that is the base for Values and Notification. It is
275 pretty useless by itself and was therefore not exported to the collectd module.
277 Data descriptors defined here:
279 =over 4
281 =item host
283 The hostname of the host this value was read from. For dispatching this can be
284 set to an empty string which means the local hostname as defined in
285 collectd.conf.
287 =item plugin
289 The name of the plugin that read the data. Setting this member to an empty
290 string will insert "python" upon dispatching.
292 =item plugin_instance
294 Plugin instance string. May be empty.
296 =item time
298 This is the Unix timestamp of the time this value was read. For dispatching
299 values this can be set to zero which means "now". This means the time the value
300 is actually dispatched, not the time it was set to 0.
302 =item type
304 The type of this value. This type has to be defined in your I<types.db>.
305 Attempting to set it to any other value will raise a I<TypeError> exception.
306 Assigning a type is mandatory, calling dispatch without doing so will raise a
307 I<RuntimeError> exception.
309 =item type_instance
311 Type instance string. May be empty.
313 =back
315 =head2 Values
317 A Value is an object which features a sequence of values. It is based on then
318 I<PluginData> type and uses its members to identify the values.
320 class Values(PluginData)
322 A Values object used for dispatching values to collectd and receiving values
323 from write callbacks.
325 Method resolution order:
327 =over 4
329 =item Values
331 =item PluginData
333 =item object
335 =back
337 Methods defined here:
339 =over 4
341 =item B<dispatch>([type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.
343 Dispatch this instance to the collectd process. The object has members for each
344 of the possible arguments for this method. For a detailed explanation of these
345 parameters see the member of the same same.
347 If you do not submit a parameter the value saved in its member will be
348 submitted. If you do provide a parameter it will be used instead, without
349 altering the member.
351 =item B<write>([destination][, type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.
353 Write this instance to a single plugin or all plugins if "destination" is
354 omitted. This will bypass the main collectd process and all filtering and
355 caching. Other than that it works similar to "dispatch". In most cases
356 "dispatch" should be used instead of "write".
358 =back
360 Data descriptors defined here:
362 =over 4
364 =item interval
366 The interval is the timespan in seconds between two submits for the same data
367 source. This value has to be a positive integer, so you can't submit more than
368 one value per second. If this member is set to a non-positive value, the
369 default value as specified in the config file will be used (default: 10).
371 If you submit values more often than the specified interval, the average will
372 be used. If you submit less values, your graphs will have gaps.
374 =item values
376 These are the actual values that get dispatched to collectd. It has to be a
377 sequence (a tuple or list) of numbers. The size of the sequence and the type of
378 its content depend on the type member your I<types.db> file. For more
379 information on this read the L<types.db(5)> manual page.
381 If the sequence does not have the correct size upon dispatch a I<RuntimeError>
382 exception will be raised. If the content of the sequence is not a number, a
383 I<TypeError> exception will be raised.
385 =back
387 =head2 Notification
389 A notification is an object defining the severity and message of the status
390 message as well as an identification of a data instance by means of the members
391 of I<PluginData> on which it is based.
393 class Notification(PluginData)
394 The Notification class is a wrapper around the collectd notification.
395 It can be used to notify other plugins about bad stuff happening. It works
396 similar to Values but has a severity and a message instead of interval
397 and time.
398 Notifications can be dispatched at any time and can be received with
399 register_notification.
401 Method resolution order:
403 =over 4
405 =item Notification
407 =item PluginData
409 =item object
411 =back
413 Methods defined here:
415 =over 4
417 =item B<dispatch>([type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None. Dispatch a value list.
419 Dispatch this instance to the collectd process. The object has members for each
420 of the possible arguments for this method. For a detailed explanation of these
421 parameters see the member of the same same.
423 If you do not submit a parameter the value saved in its member will be
424 submitted. If you do provide a parameter it will be used instead, without
425 altering the member.
427 =back
429 Data descriptors defined here:
431 =over 4
433 =item message
435 Some kind of description what's going on and why this Notification was
436 generated.
438 =item severity
440 The severity of this notification. Assign or compare to I<NOTIF_FAILURE>,
441 I<NOTIF_WARNING> or I<NOTIF_OKAY>.
443 =back
445 =head1 FUNCTIONS
447 The following functions provide the C-interface to Python-modules.
449 =over 4
451 =item B<register_*>(I<callback>[, I<data>][, I<name>]) -> identifier
453 There are eight different register functions to get callback for eight
454 different events. With one exception all of them are called as shown above.
456 =over 4
458 =item
460 I<callback> is a callable object that will be called every time the event is
461 triggered.
463 =item
465 I<data> is an optional object that will be passed back to the callback function
466 every time it is called. If you omit this parameter no object is passed back to
467 your callback, not even None.
469 =item
471 I<name> is an optional identifier for this callback. The default name is
472 B<python>.I<module>. I<module> is taken from the B<__module__> attribute of
473 your callback function. Every callback needs a unique identifier, so if you
474 want to register the same callback multiple time in the same module you need to
475 specify a name here. Otherwise it's save to ignore this parameter I<identifier>
476 is the full identifier assigned to this callback.
478 =back
480 These functions are called in the various stages of the daemon (see the section
481 L<"WRITING YOUR OWN PLUGINS"> above) and are passed the following arguments:
483 =over 4
485 =item register_config
487 The only argument passed is a I<Config> object. See above for the layout of this
488 data type.
489 Note that you can not receive the whole config files this way, only B<Module>
490 blocks inside the Python configuration block. Additionally you will only
491 receive blocks where your callback identifier matches B<python.>I<blockname>.
493 =item register_init
495 The callback will be called without arguments.
497 =item register_read(callback[, interval][, data][, name]) -> identifier
499 This function takes an additional parameter: I<interval>. It specifies the
500 time between calls to the callback function.
502 The callback will be called without arguments.
504 =item register_shutdown
506 The callback will be called without arguments.
508 =item register_write
510 The callback function will be called with one arguments passed, which will be a
511 I<Values> object. For the layout of I<Values> see above.
512 If this callback function throws an exception the next call will be delayed by
513 an increasing interval.
515 =item register_flush
517 Like B<register_config> is important for this callback because it determines
518 what flush requests the plugin will receive.
520 The arguments passed are I<timeout> and I<identifier>. I<timeout> indicates
521 that only data older than I<timeout> seconds is to be flushed. I<identifier>
522 specifies which values are to be flushed.
524 =item register_log
526 The arguments are I<severity> and I<message>. The severity is an integer and
527 small for important messages and high for less important messages. The least
528 important level is B<LOG_DEBUG>, the most important level is B<LOG_ERR>. In
529 between there are (from least to most important): B<LOG_INFO>, B<LOG_NOTICE>,
530 and B<LOG_WARNING>. I<message> is simply a string B<without> a newline at the
531 end.
533 If this callback throws an exception it will B<not> be logged. It will just be
534 printed to B<sys.stderr> which usually means silently ignored.
536 =item register_notification
538 The only argument passed is a I<Notification> object. See above for the layout of this
539 data type.
541 =back
543 =item B<unregister_*>(I<identifier>) -> None
545 Removes a callback or data-set from collectd's internal list of callback
546 functions. Every I<register_*> function has an I<unregister_*> function.
547 I<identifier> is either the string that was returned by the register function
548 or a callback function. The identifier will be constructed in the same way as
549 for the register functions.
551 =item B<flush>(I<plugin[, I<timeout>][, I<identifier>]) -> None
553 Flush one or all plugins. I<timeout> and the specified I<identifiers> are
554 passed on to the registered flush-callbacks. If omitted, the timeout defaults
555 to C<-1>. The identifier defaults to None. If the B<plugin> argument has been
556 specified, only named plugin will be flushed.
558 =item B<error>, B<warning>, B<notice>, B<info>, B<debug>(I<message>)
560 Log a message with the specified severity.
562 =back
564 =head1 EXAMPLES
566 Any Python module will start similar to:
568 import collectd
570 A very simple read function might look like:
572 def read(data=None):
573 vl = collectd.Values(type='gauge')
574 vl.plugin='python.spam'
575 vl.dispatch(values=[random.random() * 100])
577 A very simple write function might look like:
579 def write(vl, data=None):
580 for i in vl.values:
581 print "%s (%s): %f" % (vl.plugin, vl.type, i)
583 To register those functions with collectd:
585 collectd.register_read(read);
586 collectd.register_write(write);
588 See the section L<"CLASSES"> above for a complete documentation of the data
589 types used by the read, write and match functions.
591 =head1 NOTES
593 =over 4
595 =item
597 Please feel free to send in new plugins to collectd's mailinglist at
598 E<lt>collectdE<nbsp>atE<nbsp>verplant.orgE<gt> for review and, possibly,
599 inclusion in the main distribution. In the latter case, we will take care of
600 keeping the plugin up to date and adapting it to new versions of collectd.
602 Before submitting your plugin, please take a look at
603 L<http://collectd.org/dev-info.shtml>.
605 =back
607 =head1 CAVEATS
609 =over 4
611 =item
613 collectd is heavily multi-threaded. Each collectd thread accessing the python
614 plugin will be mapped to a Python interpreter thread. Any such thread will be
615 created and destroyed transparently and on-the-fly.
617 Hence, any plugin has to be thread-safe if it provides several entry points
618 from collectd (i.E<nbsp>e. if it registers more than one callback or if a
619 registered callback may be called more than once in parallel).
621 =item
623 The Python thread module is initialized just before calling the init callbacks.
624 This means you must not use Python's threading module prior to this point. This
625 includes all config and possibly other callback as well.
627 =item
629 The python plugin exports the internal API of collectd which is considered
630 unstable and subject to change at any time. We try hard to not break backwards
631 compatibility in the Python API during the life cycle of one major release.
632 However, this cannot be guaranteed at all times. Watch out for warnings
633 dispatched by the python plugin after upgrades.
635 =back
637 =head1 KNOWN BUGS
639 =over 4
641 =item
643 This plugin is not compatible with python3. Trying to compile it with python3
644 will fail because of the ways string, unicode and bytearray behavior was
645 changed.
647 =item
649 Not all aspects of the collectd API are accessible from python. This includes
650 but is not limited to meta-data, filters and data sets.
652 =back
654 =head1 SEE ALSO
656 L<collectd(1)>,
657 L<collectd.conf(5)>,
658 L<collectd-perl(5)>,
659 L<collectd-exec(5)>,
660 L<types.db(5)>,
661 L<python(1)>,
663 =head1 AUTHOR
665 The C<python plugin> has been written by
666 Sven Trenkel E<lt>collectdE<nbsp>atE<nbsp>semidefinite.deE<gt>.
668 This manpage has been written by Sven Trenkel
669 E<lt>collectdE<nbsp>atE<nbsp>semidefinite.deE<gt>.
670 It is based on the L<collectd-perl(5)> manual page by
671 Florian Forster E<lt>octoE<nbsp>atE<nbsp>verplant.orgE<gt> and
672 Sebastian Harl E<lt>shE<nbsp>atE<nbsp>tokkee.orgE<gt>.
674 =cut