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