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