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