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