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