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