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 false
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 The minimum required Python version is I<2.3>.
42 =head1 CONFIGURATION
44 =over 4
46 =item B<LoadPlugin> I<Plugin>
48 Loads the Python plugin I<Plugin>. Unlike most other LoadPlugin lines, this one
49 should be a block containing the line "Globals true". This will cause collectd
50 to export the name of all objects in the Python interpreter for all plugins to
51 see. If you don't do this or your platform does not support it, the embedded
52 interpreter will start anyway but you won't be able to load certain Python
53 modules, e.g. "time".
55 =item B<Encoding> I<Name>
57 The default encoding for Unicode objects you pass to collectd. If you omit this
58 option it will default to B<ascii> on I<Python 2> and B<utf-8> on I<Python 3>.
59 This is hardcoded in Python and will ignore everything else, including your
60 locale.
62 =item B<ModulePath> I<Name>
64 Appends I<Name> to B<sys.path>. You won't be able to import any scripts you
65 wrote unless they are located in one of the directories in this list. Please
66 note that it only has effect on plugins loaded after this option. You can
67 use multiple B<ModulePath> lines to add more than one directory.
69 =item B<LogTraces> I<bool>
71 If a Python script throws an exception it will be logged by collectd with the
72 name of the exception and the message. If you set this option to true it will
73 also log the full stacktrace just like the default output of an interactive
74 Python interpreter. This should probably be set to false most of the time but
75 is very useful for development and debugging of new modules.
77 =item B<Interactive> I<bool>
79 This option will cause the module to launch an interactive Python interpreter
80 that reads from and writes to the terminal. Note that collectd will terminate
81 right after starting up if you try to run it as a daemon while this option is
82 enabled so make sure to start collectd with the B<-f> option.
84 The B<collectd> module is I<not> imported into the interpreter's globals. You
85 have to do it manually. Be sure to read the help text of the module, it can be
86 used as a reference guide during coding.
88 This interactive session will behave slightly differently from a daemonized
89 collectd script as well as from a normal Python interpreter:
91 =over 4
93 =item
95 B<1.> collectd will try to import the B<readline> module to give you a decent
96 way of entering your commands. The daemonized collectd won't do that.
98 =item
100 B<2.> collectd will block I<SIGINT>. Pressing I<Ctrl+C> will usually cause
101 collectd to shut down. This would be problematic in an interactive session,
102 therefore this signal will be blocked. You can still use it to interrupt
103 syscalls like sleep and pause but it won't generate a I<KeyboardInterrupt>
104 exception either.
106 To quit collectd send I<EOF> (press I<Ctrl+D> at the beginning of a new line).
108 =item
110 B<3.> collectd handles I<SIGCHLD>. This means that Python won't be able to
111 determine the return code of spawned processes with system(), popen() and
112 subprocess. This will result in Python not using external programs like less
113 to display help texts. You can override this behavior with the B<PAGER>
114 environment variable, e.g. I<export PAGER=less> before starting collectd.
115 Depending on your version of Python this might or might not result in an
116 B<OSError> exception which can be ignored.
118 If you really need to spawn new processes from Python you can register an init
119 callback and reset the action for SIGCHLD to the default behavior. Please note
120 that this I<will> break the exec plugin. Do not even load the exec plugin if
121 you intend to do this!
123 There is an example script located in B<contrib/python/getsigchld.py> to do
124 this. If you import this from I<collectd.conf> SIGCHLD will be handled
125 normally and spawning processes from Python will work as intended.
127 =back
129 =item E<lt>B<Module> I<Name>E<gt> block
131 This block may be used to pass on configuration settings to a Python module.
132 The configuration is converted into an instance of the B<Config> class which is
133 passed to the registered configuration callback. See below for details about
134 the B<Config> class and how to register callbacks.
136 The I<name> identifies the callback.
138 =back
140 =head1 STRINGS
142 There are a lot of places where strings are sent from collectd to Python and
143 from Python to collectd. How exactly this works depends on whether byte or
144 unicode strings or Python2 or Python3 are used.
146 Python2 has I<str>, which is just bytes, and I<unicode>. Python3 has I<str>,
147 which is a unicode object, and I<bytes>.
149 When passing strings from Python to collectd all of these object are supported
150 in all places, however I<str> should be used if possible. These strings must
151 not contain a NUL byte. Ignoring this will result in a I<TypeError> exception.
152 If a byte string was used it will be used as is by collectd. If a unicode
153 object was used it will be encoded using the default encoding (see above). If
154 this is not possible Python will raise a I<UnicodeEncodeError> exception.
156 When passing strings from collectd to Python the behavior depends on the
157 Python version used. Python2 will always receive a I<str> object. Python3 will
158 usually receive a I<str> object as well, however the original string will be
159 decoded to unicode using the default encoding. If this fails because the
160 string is not a valid sequence for this encoding a I<bytes> object will be
161 returned instead.
163 =head1 WRITING YOUR OWN PLUGINS
165 Writing your own plugins is quite simple. collectd manages plugins by means of
166 B<dispatch functions> which call the appropriate B<callback functions>
167 registered by the plugins. Any plugin basically consists of the implementation
168 of these callback functions and initializing code which registers the
169 functions with collectd. See the section "EXAMPLES" below for a really basic
170 example. The following types of B<callback functions> are known to collectd
171 (all of them are optional):
173 =over 4
175 =item configuration functions
177 These are called during configuration if an appropriate
178 B<Module> block has been encountered. It is called once for each B<Module>
179 block which matches the name of the callback as provided with the
180 B<register_config> method - see below.
182 Python thread support has not been initialized at this point so do not use any
183 threading functions here!
185 =item init functions
187 These are called once after loading the module and before any
188 calls to the read and write functions. It should be used to initialize the
189 internal state of the plugin (e.E<nbsp>g. open sockets, ...). This is the
190 earliest point where you may use threads.
192 =item read functions
194 These are used to collect the actual data. It is called once
195 per interval (see the B<Interval> configuration option of collectd). Usually
196 it will call B<plugin_dispatch_values> to dispatch the values to collectd
197 which will pass them on to all registered B<write functions>. If this function
198 throws any kind of exception the plugin will be skipped for an increasing
199 amount of time until it returns normally again.
201 =item write functions
203 These are used to write the dispatched values. It is called
204 once for every value that was dispatched by any plugin.
206 =item flush functions
208 These are used to flush internal caches of plugins. It is
209 usually triggered by the user only. Any plugin which caches data before
210 writing it to disk should provide this kind of callback function.
212 =item log functions
214 These are used to pass messages of plugins or the daemon itself
215 to the user.
217 =item notification function
219 These are used to act upon notifications. In general, a
220 notification is a status message that may be associated with a data instance.
221 Usually, a notification is generated by the daemon if a configured threshold
222 has been exceeded (see the section "THRESHOLD CONFIGURATION" in
223 L<collectd.conf(5)> for more details), but any plugin may dispatch
224 notifications as well.
226 =item shutdown functions
228 These are called once before the daemon shuts down. It should
229 be used to clean up the plugin (e.g. close sockets, ...).
231 =back
233 Any function (except log functions) may throw an exception in case of
234 errors. The exception will be passed on to the user using collectd's logging
235 mechanism. If a log callback throws an exception it will be printed to standard
236 error instead.
238 See the documentation of the various B<register_> methods in the section
239 "FUNCTIONS" below for the number and types of arguments passed to each
240 B<callback function>. This section also explains how to register B<callback
241 functions> with collectd.
243 To enable a module, copy it to a place where Python can find it (i.E<nbsp>e. a
244 directory listed in B<sys.path>) just as any other Python plugin and add
245 an appropriate B<Import> option to the configuration file. After restarting
246 collectd you're done.
248 =head1 CLASSES
250 The following complex types are used to pass values between the Python plugin
251 and collectd:
253 =head2 Signed
255 The Signed class is just a long. It has all its methods and behaves exactly
256 like any other long object. It is used to indicate if an integer was or should
257 be stored as a signed or unsigned integer object.
259 class Signed(long)
261 This is a long by another name. Use it in meta data dicts
262 to choose the way it is stored in the meta data.
264 =head2 Unsigned
266 The Unsigned class is just a long. It has all its methods and behaves exactly
267 like any other long object. It is used to indicate if an integer was or should
268 be stored as a signed or unsigned integer object.
270 class Unsigned(long)
272 This is a long by another name. Use it in meta data dicts
273 to choose the way it is stored in the meta data.
275 =head2 Config
277 The Config class is an object which keeps the information provided in the
278 configuration file. The sequence of children keeps one entry for each
279 configuration option. Each such entry is another Config instance, which
280 may nest further if nested blocks are used.
282 class Config(object)
284 This represents a piece of collectd's config file. It is passed to scripts with
285 config callbacks (see B<register_config>) and is of little use if created
286 somewhere else.
288 It has no methods beyond the bare minimum and only exists for its data members.
290 Data descriptors defined here:
292 =over 4
294 =item parent
296 This represents the parent of this node. On the root node
297 of the config tree it will be None.
299 =item key
301 This is the keyword of this item, i.e. the first word of any given line in the
302 config file. It will always be a string.
304 =item values
306 This is a tuple (which might be empty) of all value, i.e. words following the
307 keyword in any given line in the config file.
309 Every item in this tuple will be either a string, a float or a boolean,
310 depending on the contents of the configuration file.
312 =item children
314 This is a tuple of child nodes. For most nodes this will be empty. If this node
315 represents a block instead of a single line of the config file it will contain
316 all nodes in this block.
318 =back
320 =head2 PluginData
322 This should not be used directly but it is the base class for both Values and
323 Notification. It is used to identify the source of a value or notification.
325 class PluginData(object)
327 This is an internal class that is the base for Values and Notification. It is
328 pretty useless by itself and was therefore not exported to the collectd module.
330 Data descriptors defined here:
332 =over 4
334 =item host
336 The hostname of the host this value was read from. For dispatching this can be
337 set to an empty string which means the local hostname as defined in
338 collectd.conf.
340 =item plugin
342 The name of the plugin that read the data. Setting this member to an empty
343 string will insert "python" upon dispatching.
345 =item plugin_instance
347 Plugin instance string. May be empty.
349 =item time
351 This is the Unix timestamp of the time this value was read. For dispatching
352 values this can be set to zero which means "now". This means the time the value
353 is actually dispatched, not the time it was set to 0.
355 =item type
357 The type of this value. This type has to be defined in your I<types.db>.
358 Attempting to set it to any other value will raise a I<TypeError> exception.
359 Assigning a type is mandatory, calling dispatch without doing so will raise a
360 I<RuntimeError> exception.
362 =item type_instance
364 Type instance string. May be empty.
366 =back
368 =head2 Values
370 A Value is an object which features a sequence of values. It is based on the
371 I<PluginData> type and uses its members to identify the values.
373 class Values(PluginData)
375 A Values object used for dispatching values to collectd and receiving values
376 from write callbacks.
378 Method resolution order:
380 =over 4
382 =item Values
384 =item PluginData
386 =item object
388 =back
390 Methods defined here:
392 =over 4
394 =item B<dispatch>([type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.
396 Dispatch this instance to the collectd process. The object has members for each
397 of the possible arguments for this method. For a detailed explanation of these
398 parameters see the member of the same same.
400 If you do not submit a parameter the value saved in its member will be
401 submitted. If you do provide a parameter it will be used instead, without
402 altering the member.
404 =item B<write>([destination][, type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.
406 Write this instance to a single plugin or all plugins if "destination" is
407 omitted. This will bypass the main collectd process and all filtering and
408 caching. Other than that it works similar to "dispatch". In most cases
409 "dispatch" should be used instead of "write".
411 =back
413 Data descriptors defined here:
415 =over 4
417 =item interval
419 The interval is the timespan in seconds between two submits for the same data
420 source. This value has to be a positive integer, so you can't submit more than
421 one value per second. If this member is set to a non-positive value, the
422 default value as specified in the config file will be used (default: 10).
424 If you submit values more often than the specified interval, the average will
425 be used. If you submit less values, your graphs will have gaps.
427 =item values
429 These are the actual values that get dispatched to collectd. It has to be a
430 sequence (a tuple or list) of numbers. The size of the sequence and the type of
431 its content depend on the type member your I<types.db> file. For more
432 information on this read the L<types.db(5)> manual page.
434 If the sequence does not have the correct size upon dispatch a I<RuntimeError>
435 exception will be raised. If the content of the sequence is not a number, a
436 I<TypeError> exception will be raised.
438 =item meta
440 These are the meta data for this Value object.
441 It has to be a dictionary of numbers, strings or bools. All keys must be
442 strings. I<int> and <long> objects will be dispatched as signed integers unless
443 they are between 2**63 and 2**64-1, which will result in a unsigned integer.
444 You can force one of these storage classes by using the classes
445 B<collectd.Signed> and B<collectd.Unsigned>. A meta object received by a write
446 callback will always contain B<Signed> or B<Unsigned> objects.
448 =back
450 =head2 Notification
452 A notification is an object defining the severity and message of the status
453 message as well as an identification of a data instance by means of the members
454 of I<PluginData> on which it is based.
456 class Notification(PluginData)
457 The Notification class is a wrapper around the collectd notification.
458 It can be used to notify other plugins about bad stuff happening. It works
459 similar to Values but has a severity and a message instead of interval
460 and time.
461 Notifications can be dispatched at any time and can be received with
462 register_notification.
464 Method resolution order:
466 =over 4
468 =item Notification
470 =item PluginData
472 =item object
474 =back
476 Methods defined here:
478 =over 4
480 =item B<dispatch>([type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None. Dispatch a value list.
482 Dispatch this instance to the collectd process. The object has members for each
483 of the possible arguments for this method. For a detailed explanation of these
484 parameters see the member of the same same.
486 If you do not submit a parameter the value saved in its member will be
487 submitted. If you do provide a parameter it will be used instead, without
488 altering the member.
490 =back
492 Data descriptors defined here:
494 =over 4
496 =item message
498 Some kind of description of what's going on and why this Notification was
499 generated.
501 =item severity
503 The severity of this notification. Assign or compare to I<NOTIF_FAILURE>,
504 I<NOTIF_WARNING> or I<NOTIF_OKAY>.
506 =back
508 =head1 FUNCTIONS
510 The following functions provide the C-interface to Python-modules.
512 =over 4
514 =item B<register_*>(I<callback>[, I<data>][, I<name>]) -> identifier
516 There are eight different register functions to get callback for eight
517 different events. With one exception all of them are called as shown above.
519 =over 4
521 =item
523 I<callback> is a callable object that will be called every time the event is
524 triggered.
526 =item
528 I<data> is an optional object that will be passed back to the callback function
529 every time it is called. If you omit this parameter no object is passed back to
530 your callback, not even None.
532 =item
534 I<name> is an optional identifier for this callback. The default name is
535 B<python>.I<module>. I<module> is taken from the B<__module__> attribute of
536 your callback function. Every callback needs a unique identifier, so if you
537 want to register the same callback multiple times in the same module you need to
538 specify a name here. Otherwise it's safe to ignore this parameter.
540 =item
542 I<identifier> is the full identifier assigned to this callback.
544 =back
546 These functions are called in the various stages of the daemon (see the section
547 L<"WRITING YOUR OWN PLUGINS"> above) and are passed the following arguments:
549 =over 4
551 =item register_config
553 The only argument passed is a I<Config> object. See above for the layout of this
554 data type.
555 Note that you cannot receive the whole config files this way, only B<Module>
556 blocks inside the Python configuration block. Additionally you will only
557 receive blocks where your callback identifier matches B<python.>I<blockname>.
559 =item register_init
561 The callback will be called without arguments.
563 =item register_read(callback[, interval][, data][, name]) -> identifier
565 This function takes an additional parameter: I<interval>. It specifies the
566 time between calls to the callback function.
568 The callback will be called without arguments.
570 =item register_shutdown
572 The callback will be called without arguments.
574 =item register_write
576 The callback function will be called with one argument passed, which will be a
577 I<Values> object. For the layout of I<Values> see above.
578 If this callback function throws an exception the next call will be delayed by
579 an increasing interval.
581 =item register_flush
583 Like B<register_config> is important for this callback because it determines
584 what flush requests the plugin will receive.
586 The arguments passed are I<timeout> and I<identifier>. I<timeout> indicates
587 that only data older than I<timeout> seconds is to be flushed. I<identifier>
588 specifies which values are to be flushed.
590 =item register_log
592 The arguments are I<severity> and I<message>. The severity is an integer and
593 small for important messages and high for less important messages. The least
594 important level is B<LOG_DEBUG>, the most important level is B<LOG_ERR>. In
595 between there are (from least to most important): B<LOG_INFO>, B<LOG_NOTICE>,
596 and B<LOG_WARNING>. I<message> is simply a string B<without> a newline at the
597 end.
599 If this callback throws an exception it will B<not> be logged. It will just be
600 printed to B<sys.stderr> which usually means silently ignored.
602 =item register_notification
604 The only argument passed is a I<Notification> object. See above for the layout of this
605 data type.
607 =back
609 =item B<unregister_*>(I<identifier>) -> None
611 Removes a callback or data-set from collectd's internal list of callback
612 functions. Every I<register_*> function has an I<unregister_*> function.
613 I<identifier> is either the string that was returned by the register function
614 or a callback function. The identifier will be constructed in the same way as
615 for the register functions.
617 =item B<flush>(I<plugin[, I<timeout>][, I<identifier>]) -> None
619 Flush one or all plugins. I<timeout> and the specified I<identifiers> are
620 passed on to the registered flush-callbacks. If omitted, the timeout defaults
621 to C<-1>. The identifier defaults to None. If the B<plugin> argument has been
622 specified, only named plugin will be flushed.
624 =item B<error>, B<warning>, B<notice>, B<info>, B<debug>(I<message>)
626 Log a message with the specified severity.
628 =back
630 =head1 EXAMPLES
632 Any Python module will start similar to:
634 import collectd
636 A very simple read function might look like:
638 def read(data=None):
639 vl = collectd.Values(type='gauge')
640 vl.plugin='python.spam'
641 vl.dispatch(values=[random.random() * 100])
643 A very simple write function might look like:
645 def write(vl, data=None):
646 for i in vl.values:
647 print "%s (%s): %f" % (vl.plugin, vl.type, i)
649 To register those functions with collectd:
651 collectd.register_read(read);
652 collectd.register_write(write);
654 See the section L<"CLASSES"> above for a complete documentation of the data
655 types used by the read, write and match functions.
657 =head1 NOTES
659 =over 4
661 =item
663 Please feel free to send in new plugins to collectd's mailing list at
664 E<lt>collectdE<nbsp>atE<nbsp>verplant.orgE<gt> for review and, possibly,
665 inclusion in the main distribution. In the latter case, we will take care of
666 keeping the plugin up to date and adapting it to new versions of collectd.
668 Before submitting your plugin, please take a look at
669 L<http://collectd.org/dev-info.shtml>.
671 =back
673 =head1 CAVEATS
675 =over 4
677 =item
679 collectd is heavily multi-threaded. Each collectd thread accessing the Python
680 plugin will be mapped to a Python interpreter thread. Any such thread will be
681 created and destroyed transparently and on-the-fly.
683 Hence, any plugin has to be thread-safe if it provides several entry points
684 from collectd (i.E<nbsp>e. if it registers more than one callback or if a
685 registered callback may be called more than once in parallel).
687 =item
689 The Python thread module is initialized just before calling the init callbacks.
690 This means you must not use Python's threading module prior to this point. This
691 includes all config and possibly other callback as well.
693 =item
695 The python plugin exports the internal API of collectd which is considered
696 unstable and subject to change at any time. We try hard to not break backwards
697 compatibility in the Python API during the life cycle of one major release.
698 However, this cannot be guaranteed at all times. Watch out for warnings
699 dispatched by the python plugin after upgrades.
701 =back
703 =head1 KNOWN BUGS
705 =over 4
707 =item
709 Not all aspects of the collectd API are accessible from Python. This includes
710 but is not limited to filters and data sets.
712 =back
714 =head1 SEE ALSO
716 L<collectd(1)>,
717 L<collectd.conf(5)>,
718 L<collectd-perl(5)>,
719 L<collectd-exec(5)>,
720 L<types.db(5)>,
721 L<python(1)>,
723 =head1 AUTHOR
725 The C<python plugin> has been written by
726 Sven Trenkel E<lt>collectdE<nbsp>atE<nbsp>semidefinite.deE<gt>.
728 This manpage has been written by Sven Trenkel
729 E<lt>collectdE<nbsp>atE<nbsp>semidefinite.deE<gt>.
730 It is based on the L<collectd-perl(5)> manual page by
731 Florian Forster E<lt>octoE<nbsp>atE<nbsp>verplant.orgE<gt> and
732 Sebastian Harl E<lt>shE<nbsp>atE<nbsp>tokkee.orgE<gt>.
734 =cut