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