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