Code

src/*.pod: fix minor warnings spotted by podchecker
[collectd.git] / src / collectd-python.pod
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 =encoding UTF-8
13 =head1 NAME
15 collectd-python - Documentation of collectd's C<python plugin>
17 =head1 SYNOPSIS
19   LoadPlugin python
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>.
50 =item B<Encoding> I<Name>
52 The default encoding for Unicode objects you pass to collectd. If you omit this
53 option it will default to B<ascii> on I<Python 2> and B<utf-8> on I<Python 3>.
54 This is hardcoded in Python and will ignore everything else, including your
55 locale.
57 =item B<ModulePath> I<Name>
59 Appends I<Name> to B<sys.path>. You won't be able to import any scripts you
60 wrote unless they are located in one of the directories in this list. Please
61 note that it only has effect on plugins loaded after this option. You can
62 use multiple B<ModulePath> lines to add more than one directory.
64 =item B<LogTraces> I<bool>
66 If a Python script throws an exception it will be logged by collectd with the
67 name of the exception and the message. If you set this option to true it will
68 also log the full stacktrace just like the default output of an interactive
69 Python interpreter. This should probably be set to false most of the time but
70 is very useful for development and debugging of new modules.
72 =item B<Interactive> I<bool>
74 This option will cause the module to launch an interactive Python interpreter
75 that reads from and writes to the terminal. Note that collectd will terminate
76 right after starting up if you try to run it as a daemon while this option is
77 enabled so make sure to start collectd with the B<-f> option.
79 The B<collectd> module is I<not> imported into the interpreter's globals. You
80 have to do it manually. Be sure to read the help text of the module, it can be
81 used as a reference guide during coding.
83 This interactive session will behave slightly differently from a daemonized
84 collectd script as well as from a normal Python interpreter:
86 =over 4
88 =item *
90 B<1.> collectd will try to import the B<readline> module to give you a decent
91 way of entering your commands. The daemonized collectd won't do that.
93 =item *
95 B<2.> collectd will block I<SIGINT>. Pressing I<Ctrl+C> will usually cause
96 collectd to shut down. This would be problematic in an interactive session,
97 therefore this signal will be blocked. You can still use it to interrupt
98 syscalls like sleep and pause but it won't generate a I<KeyboardInterrupt>
99 exception either.
101 To quit collectd send I<EOF> (press I<Ctrl+D> at the beginning of a new line).
103 =item *
105 B<3.> collectd handles I<SIGCHLD>. This means that Python won't be able to
106 determine the return code of spawned processes with system(), popen() and
107 subprocess. This will result in Python not using external programs like less
108 to display help texts. You can override this behavior with the B<PAGER>
109 environment variable, e.g. I<export PAGER=less> before starting collectd.
110 Depending on your version of Python this might or might not result in an
111 B<OSError> exception which can be ignored.
113 If you really need to spawn new processes from Python you can register an init
114 callback and reset the action for SIGCHLD to the default behavior. Please note
115 that this I<will> break the exec plugin. Do not even load the exec plugin if
116 you intend to do this!
118 There is an example script located in B<contrib/python/getsigchld.py>  to do
119 this. If you import this from I<collectd.conf> SIGCHLD will be handled
120 normally and spawning processes from Python will work as intended.
122 =back
124 =item E<lt>B<Module> I<Name>E<gt> block
126 This block may be used to pass on configuration settings to a Python module.
127 The configuration is converted into an instance of the B<Config> class which is
128 passed to the registered configuration callback. See below for details about
129 the B<Config> class and how to register callbacks.
131 The I<name> identifies the callback.
133 =back
135 =head1 STRINGS
137 There are a lot of places where strings are sent from collectd to Python and
138 from Python to collectd. How exactly this works depends on whether byte or
139 unicode strings or Python2 or Python3 are used.
141 Python2 has I<str>, which is just bytes, and I<unicode>. Python3 has I<str>,
142 which is a unicode object, and I<bytes>.
144 When passing strings from Python to collectd all of these object are supported
145 in all places, however I<str> should be used if possible. These strings must
146 not contain a NUL byte. Ignoring this will result in a I<TypeError> exception.
147 If a byte string was used it will be used as is by collectd. If a unicode
148 object was used it will be encoded using the default encoding (see above). If
149 this is not possible Python will raise a I<UnicodeEncodeError> exception.
151 When passing strings from collectd to Python the behavior depends on the
152 Python version used. Python2 will always receive a I<str> object. Python3 will
153 usually receive a I<str> object as well, however the original string will be
154 decoded to unicode using the default encoding. If this fails because the
155 string is not a valid sequence for this encoding a I<bytes> object will be
156 returned instead.
158 =head1 WRITING YOUR OWN PLUGINS
160 Writing your own plugins is quite simple. collectd manages plugins by means of
161 B<dispatch functions> which call the appropriate B<callback functions>
162 registered by the plugins. Any plugin basically consists of the implementation
163 of these callback functions and initializing code which registers the
164 functions with collectd. See the section "EXAMPLES" below for a really basic
165 example. The following types of B<callback functions> are known to collectd
166 (all of them are optional):
168 =over 4
170 =item configuration functions
172 These are called during configuration if an appropriate
173 B<Module> block has been encountered. It is called once for each B<Module>
174 block which matches the name of the callback as provided with the
175 B<register_config> method - see below.
177 Python thread support has not been initialized at this point so do not use any
178 threading functions here!
180 =item init functions
182 These are called once after loading the module and before any
183 calls to the read and write functions. It should be used to initialize the
184 internal state of the plugin (e.E<nbsp>g. open sockets, ...). This is the
185 earliest point where you may use threads.
187 =item read functions
189 These are used to collect the actual data. It is called once
190 per interval (see the B<Interval> configuration option of collectd). Usually
191 it will call B<plugin_dispatch_values> to dispatch the values to collectd
192 which will pass them on to all registered B<write functions>. If this function
193 throws any kind of exception the plugin will be skipped for an increasing
194 amount of time until it returns normally again.
196 =item write functions
198 These are used to write the dispatched values. It is called
199 once for every value that was dispatched by any plugin.
201 =item flush functions
203 These are used to flush internal caches of plugins. It is
204 usually triggered by the user only. Any plugin which caches data before
205 writing it to disk should provide this kind of callback function.
207 =item log functions
209 These are used to pass messages of plugins or the daemon itself
210 to the user.
212 =item notification function
214 These are used to act upon notifications. In general, a
215 notification is a status message that may be associated with a data instance.
216 Usually, a notification is generated by the daemon if a configured threshold
217 has been exceeded (see the section "THRESHOLD CONFIGURATION" in
218 L<collectd.conf(5)> for more details), but any plugin may dispatch
219 notifications as well.
221 =item shutdown functions
223 These are called once before the daemon shuts down. It should
224 be used to clean up the plugin (e.g. close sockets, ...).
226 =back
228 Any function (except log functions) may throw an exception in case of
229 errors. The exception will be passed on to the user using collectd's logging
230 mechanism. If a log callback throws an exception it will be printed to standard
231 error instead.
233 See the documentation of the various B<register_> methods in the section
234 "FUNCTIONS" below for the number and types of arguments passed to each
235 B<callback function>. This section also explains how to register B<callback
236 functions> with collectd.
238 To enable a module, copy it to a place where Python can find it (i.E<nbsp>e. a
239 directory listed in B<sys.path>) just as any other Python plugin and add
240 an appropriate B<Import> option to the configuration file. After restarting
241 collectd you're done.
243 =head1 CLASSES
245 The following complex types are used to pass values between the Python plugin
246 and collectd:
248 =head2 Signed
250 The Signed class is just a long. It has all its methods and behaves exactly
251 like any other long object. It is used to indicate if an integer was or should
252 be stored as a signed or unsigned integer object.
254  class Signed(long)
256 This is a long by another name. Use it in meta data dicts
257 to choose the way it is stored in the meta data.
259 =head2 Unsigned
261 The Unsigned class is just a long. It has all its methods and behaves exactly
262 like any other long object. It is used to indicate if an integer was or should
263 be stored as a signed or unsigned integer object.
265  class Unsigned(long)
267 This is a long by another name. Use it in meta data dicts
268 to choose the way it is stored in the meta data.
270 =head2 Config
272 The Config class is an object which keeps the information provided in the
273 configuration file. The sequence of children keeps one entry for each
274 configuration option. Each such entry is another Config instance, which
275 may nest further if nested blocks are used.
277  class Config(object)
279 This represents a piece of collectd's config file. It is passed to scripts with
280 config callbacks (see B<register_config>) and is of little use if created
281 somewhere else.
283 It has no methods beyond the bare minimum and only exists for its data members.
285 Data descriptors defined here:
287 =over 4
289 =item parent
291 This represents the parent of this node. On the root node
292 of the config tree it will be None.
294 =item key
296 This is the keyword of this item, i.e. the first word of any given line in the
297 config file. It will always be a string.
299 =item values
301 This is a tuple (which might be empty) of all value, i.e. words following the
302 keyword in any given line in the config file.
304 Every item in this tuple will be either a string, a float or a boolean,
305 depending on the contents of the configuration file.
307 =item children
309 This is a tuple of child nodes. For most nodes this will be empty. If this node
310 represents a block instead of a single line of the config file it will contain
311 all nodes in this block.
313 =back
315 =head2 PluginData
317 This should not be used directly but it is the base class for both Values and
318 Notification. It is used to identify the source of a value or notification.
320  class PluginData(object)
322 This is an internal class that is the base for Values and Notification. It is
323 pretty useless by itself and was therefore not exported to the collectd module.
325 Data descriptors defined here:
327 =over 4
329 =item host
331 The hostname of the host this value was read from. For dispatching this can be
332 set to an empty string which means the local hostname as defined in
333 collectd.conf.
335 =item plugin
337 The name of the plugin that read the data. Setting this member to an empty
338 string will insert "python" upon dispatching.
340 =item plugin_instance
342 Plugin instance string. May be empty.
344 =item time
346 This is the Unix timestamp of the time this value was read. For dispatching
347 values this can be set to zero which means "now". This means the time the value
348 is actually dispatched, not the time it was set to 0.
350 =item type
352 The type of this value. This type has to be defined in your I<types.db>.
353 Attempting to set it to any other value will raise a I<TypeError> exception.
354 Assigning a type is mandatory, calling dispatch without doing so will raise a
355 I<RuntimeError> exception.
357 =item type_instance
359 Type instance string. May be empty.
361 =back
363 =head2 Values
365 A Value is an object which features a sequence of values. It is based on the
366 I<PluginData> type and uses its members to identify the values.
368  class Values(PluginData)
370 A Values object used for dispatching values to collectd and receiving values
371 from write callbacks.
373 Method resolution order:
375 =over 4
377 =item Values
379 =item PluginData
381 =item object
383 =back
385 Methods defined here:
387 =over 4
389 =item B<dispatch>([type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.
391 Dispatch this instance to the collectd process. The object has members for each
392 of the possible arguments for this method. For a detailed explanation of these
393 parameters see the member of the same same.
395 If you do not submit a parameter the value saved in its member will be
396 submitted. If you do provide a parameter it will be used instead, without
397 altering the member.
399 =item B<write>([destination][, type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.
401 Write this instance to a single plugin or all plugins if "destination" is
402 omitted. This will bypass the main collectd process and all filtering and
403 caching. Other than that it works similar to "dispatch". In most cases
404 "dispatch" should be used instead of "write".
406 =back
408 Data descriptors defined here:
410 =over 4
412 =item interval
414 The interval is the timespan in seconds between two submits for the same data
415 source. This value has to be a positive integer, so you can't submit more than
416 one value per second. If this member is set to a non-positive value, the
417 default value as specified in the config file will be used (default: 10).
419 If you submit values more often than the specified interval, the average will
420 be used. If you submit less values, your graphs will have gaps.
422 =item values
424 These are the actual values that get dispatched to collectd. It has to be a
425 sequence (a tuple or list) of numbers. The size of the sequence and the type of
426 its content depend on the type member your I<types.db> file. For more
427 information on this read the L<types.db(5)> manual page.
429 If the sequence does not have the correct size upon dispatch a I<RuntimeError>
430 exception will be raised. If the content of the sequence is not a number, a
431 I<TypeError> exception will be raised.
433 =item meta
435 These are the meta data for this Value object.
436 It has to be a dictionary of numbers, strings or bools. All keys must be
437 strings. I<int> and <long> objects will be dispatched as signed integers unless
438 they are between 2**63 and 2**64-1, which will result in a unsigned integer.
439 You can force one of these storage classes by using the classes
440 B<collectd.Signed> and B<collectd.Unsigned>. A meta object received by a write
441 callback will always contain B<Signed> or B<Unsigned> objects.
443 =back
445 =head2 Notification
447 A notification is an object defining the severity and message of the status
448 message as well as an identification of a data instance by means of the members
449 of I<PluginData> on which it is based.
451 class Notification(PluginData)
452 The Notification class is a wrapper around the collectd notification.
453 It can be used to notify other plugins about bad stuff happening. It works
454 similar to Values but has a severity and a message instead of interval
455 and time.
456 Notifications can be dispatched at any time and can be received with
457 register_notification.
459 Method resolution order:
461 =over 4
463 =item Notification
465 =item PluginData
467 =item object
469 =back
471 Methods defined here:
473 =over 4
475 =item B<dispatch>([type][, values][, plugin_instance][, type_instance][, plugin][, host][, time][, interval]) -> None.  Dispatch a value list.
477 Dispatch this instance to the collectd process. The object has members for each
478 of the possible arguments for this method. For a detailed explanation of these
479 parameters see the member of the same same.
481 If you do not submit a parameter the value saved in its member will be
482 submitted. If you do provide a parameter it will be used instead, without
483 altering the member.
485 =back
487 Data descriptors defined here:
489 =over 4
491 =item message
493 Some kind of description of what's going on and why this Notification was
494 generated.
496 =item severity
498 The severity of this notification. Assign or compare to I<NOTIF_FAILURE>,
499 I<NOTIF_WARNING> or I<NOTIF_OKAY>.
501 =back
503 =head1 FUNCTIONS
505 The following functions provide the C-interface to Python-modules.
507 =over 4
509 =item B<register_*>(I<callback>[, I<data>][, I<name>]) -> identifier
511 There are eight different register functions to get callback for eight
512 different events. With one exception all of them are called as shown above.
514 =over 4
516 =item *
518 I<callback> is a callable object that will be called every time the event is
519 triggered.
521 =item *
523 I<data> is an optional object that will be passed back to the callback function
524 every time it is called. If you omit this parameter no object is passed back to
525 your callback, not even None.
527 =item *
529 I<name> is an optional identifier for this callback. The default name is
530 B<python>.I<module>. I<module> is taken from the B<__module__> attribute of
531 your callback function. Every callback needs a unique identifier, so if you
532 want to register the same callback multiple times in the same module you need to
533 specify a name here. Otherwise it's safe to ignore this parameter.
535 =item *
537 I<identifier> is the full identifier assigned to this callback.
539 =back
541 These functions are called in the various stages of the daemon (see the section
542 L<"WRITING YOUR OWN PLUGINS"> above) and are passed the following arguments:
544 =over 4
546 =item register_config
548 The only argument passed is a I<Config> object. See above for the layout of this
549 data type.
550 Note that you cannot receive the whole config files this way, only B<Module>
551 blocks inside the Python configuration block. Additionally you will only
552 receive blocks where your callback identifier matches B<python.>I<blockname>.
554 =item register_init
556 The callback will be called without arguments.
558 =item register_read(callback[, interval][, data][, name]) -> identifier
560 This function takes an additional parameter: I<interval>. It specifies the
561 time between calls to the callback function.
563 The callback will be called without arguments.
565 =item register_shutdown
567 The callback will be called without arguments.
569 =item register_write
571 The callback function will be called with one argument passed, which will be a
572 I<Values> object. For the layout of I<Values> see above.
573 If this callback function throws an exception the next call will be delayed by
574 an increasing interval.
576 =item register_flush
578 Like B<register_config> is important for this callback because it determines
579 what flush requests the plugin will receive.
581 The arguments passed are I<timeout> and I<identifier>. I<timeout> indicates
582 that only data older than I<timeout> seconds is to be flushed. I<identifier>
583 specifies which values are to be flushed.
585 =item register_log
587 The arguments are I<severity> and I<message>. The severity is an integer and
588 small for important messages and high for less important messages. The least
589 important level is B<LOG_DEBUG>, the most important level is B<LOG_ERR>. In
590 between there are (from least to most important): B<LOG_INFO>, B<LOG_NOTICE>,
591 and B<LOG_WARNING>. I<message> is simply a string B<without> a newline at the
592 end.
594 If this callback throws an exception it will B<not> be logged. It will just be
595 printed to B<sys.stderr> which usually means silently ignored.
597 =item register_notification
599 The only argument passed is a I<Notification> object. See above for the layout of this
600 data type.
602 =back
604 =item B<unregister_*>(I<identifier>) -> None
606 Removes a callback or data-set from collectd's internal list of callback
607 functions. Every I<register_*> function has an I<unregister_*> function.
608 I<identifier> is either the string that was returned by the register function
609 or a callback function. The identifier will be constructed in the same way as
610 for the register functions.
612 =item B<flush>(I<plugin[, timeout][, identifier]) -> None
614 Flush one or all plugins. I<timeout> and the specified I<identifiers> are
615 passed on to the registered flush-callbacks. If omitted, the timeout defaults
616 to C<-1>. The identifier defaults to None. If the B<plugin> argument has been
617 specified, only named plugin will be flushed.
619 =item B<error>, B<warning>, B<notice>, B<info>, B<debug>(I<message>)
621 Log a message with the specified severity.
623 =back
625 =head1 EXAMPLES
627 Any Python module will start similar to:
629   import collectd
631 A very simple read function might look like:
633   def read(data=None):
634     vl = collectd.Values(type='gauge')
635     vl.plugin='python.spam'
636     vl.dispatch(values=[random.random() * 100])
638 A very simple write function might look like:
640   def write(vl, data=None):
641     for i in vl.values:
642       print "%s (%s): %f" % (vl.plugin, vl.type, i)
644 To register those functions with collectd:
646   collectd.register_read(read);
647   collectd.register_write(write);
649 See the section L<"CLASSES"> above for a complete documentation of the data
650 types used by the read, write and match functions.
652 =head1 NOTES
654 =over 4
656 =item *
658 Please feel free to send in new plugins to collectd's mailing list at
659 E<lt>collectdE<nbsp>atE<nbsp>verplant.orgE<gt> for review and, possibly,
660 inclusion in the main distribution. In the latter case, we will take care of
661 keeping the plugin up to date and adapting it to new versions of collectd.
663 Before submitting your plugin, please take a look at
664 L<http://collectd.org/dev-info.shtml>.
666 =back
668 =head1 CAVEATS
670 =over 4
672 =item *
674 collectd is heavily multi-threaded. Each collectd thread accessing the Python
675 plugin will be mapped to a Python interpreter thread. Any such thread will be
676 created and destroyed transparently and on-the-fly.
678 Hence, any plugin has to be thread-safe if it provides several entry points
679 from collectd (i.E<nbsp>e. if it registers more than one callback or if a
680 registered callback may be called more than once in parallel).
682 =item *
684 The Python thread module is initialized just before calling the init callbacks.
685 This means you must not use Python's threading module prior to this point. This
686 includes all config and possibly other callback as well.
688 =item *
690 The python plugin exports the internal API of collectd which is considered
691 unstable and subject to change at any time. We try hard to not break backwards
692 compatibility in the Python API during the life cycle of one major release.
693 However, this cannot be guaranteed at all times. Watch out for warnings
694 dispatched by the python plugin after upgrades.
696 =back
698 =head1 KNOWN BUGS
700 =over 4
702 =item *
704 Not all aspects of the collectd API are accessible from Python. This includes
705 but is not limited to filters and data sets.
707 =back
709 =head1 SEE ALSO
711 L<collectd(1)>,
712 L<collectd.conf(5)>,
713 L<collectd-perl(5)>,
714 L<collectd-exec(5)>,
715 L<types.db(5)>,
716 L<python(1)>,
718 =head1 AUTHOR
720 The C<python plugin> has been written by
721 Sven Trenkel E<lt>collectdE<nbsp>atE<nbsp>semidefinite.deE<gt>.
723 This manpage has been written by Sven Trenkel
724 E<lt>collectdE<nbsp>atE<nbsp>semidefinite.deE<gt>.
725 It is based on the L<collectd-perl(5)> manual page by
726 Florian Forster E<lt>octoE<nbsp>atE<nbsp>verplant.orgE<gt> and
727 Sebastian Harl E<lt>shE<nbsp>atE<nbsp>tokkee.orgE<gt>.
729 =cut