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