Code

Merge branch 'collectd-5.4'
[collectd.git] / bindings / perl / lib / Collectd / Unixsock.pm
1 #
2 # collectd - bindings/buildperl/Collectd/Unixsock.pm
3 # Copyright (C) 2007,2008  Florian octo Forster
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the "Software"),
7 # to deal in the Software without restriction, including without limitation
8 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 # and/or sell copies of the Software, and to permit persons to whom the
10 # Software is furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 # DEALINGS IN THE SOFTWARE.
22 #
23 # Authors:
24 #   Florian Forster <octo at collectd.org>
25 #
27 package Collectd::Unixsock;
29 =head1 NAME
31 Collectd::Unixsock - Abstraction layer for accessing the functionality by
32 collectd's unixsock plugin.
34 =head1 SYNOPSIS
36   use Collectd::Unixsock ();
38   my $sock = Collectd::Unixsock->new ($path);
40   my $value = $sock->getval (%identifier);
41   $sock->putval (%identifier,
42                  time => time (),
43                  values => [123, 234, 345]);
45   $sock->destroy ();
47 =head1 DESCRIPTION
49 collectd's unixsock plugin allows external programs to access the values it has
50 collected or received and to submit own values. This Perl-module is simply a
51 little abstraction layer over this interface to make it even easier for
52 programmers to interact with the daemon.
54 =cut
56 use strict;
57 use warnings;
59 #use constant { NOTIF_FAILURE => 1, NOTIF_WARNING => 2, NOTIF_OKAY => 4 };
61 use Carp (qw(cluck confess));
62 use IO::Socket::UNIX;
63 use Regexp::Common (qw(number));
65 our $Debug = 0;
67 return (1);
69 sub _debug
70 {
71         if (!$Debug)
72         {
73                 return;
74         }
75         print @_;
76 }
78 sub _create_socket
79 {
80         my $path = shift;
81         my $sock = IO::Socket::UNIX->new (Type => SOCK_STREAM, Peer => $path);
82         if (!$sock)
83         {
84                 cluck ("Cannot open UNIX-socket $path: $!");
85                 return;
86         }
87         return ($sock);
88 } # _create_socket
90 =head1 VALUE IDENTIFIERS
92 The values in the collectd are identified using an five-tuple (host, plugin,
93 plugin-instance, type, type-instance) where only plugin-instance and
94 type-instance may be NULL (or undefined). Many functions expect an
95 I<%identifier> hash that has at least the members B<host>, B<plugin>, and
96 B<type>, possibly completed by B<plugin_instance> and B<type_instance>.
98 Usually you can pass this hash as follows:
100   $obj->method (host => $host, plugin => $plugin, type => $type, %other_args);
102 =cut
104 sub _create_identifier
106         my $args = shift;
107         my $host;
108         my $plugin;
109         my $type;
111         if (!$args->{'host'} || !$args->{'plugin'} || !$args->{'type'})
112         {
113                 cluck ("Need `host', `plugin' and `type'");
114                 return;
115         }
117         $host = $args->{'host'};
118         $plugin = $args->{'plugin'};
119         $plugin .= '-' . $args->{'plugin_instance'} if (defined ($args->{'plugin_instance'}));
120         $type = $args->{'type'};
121         $type .= '-' . $args->{'type_instance'} if (defined ($args->{'type_instance'}));
123         return ("$host/$plugin/$type");
124 } # _create_identifier
126 sub _parse_identifier
128         my $string = shift;
129         my $host;
130         my $plugin;
131         my $plugin_instance;
132         my $type;
133         my $type_instance;
134         my $ident;
136         ($host, $plugin, $type) = split ('/', $string);
138         ($plugin, $plugin_instance) = split ('-', $plugin, 2);
139         ($type, $type_instance) = split ('-', $type, 2);
141         $ident =
142         {
143                 host => $host,
144                 plugin => $plugin,
145                 type => $type
146         };
147         $ident->{'plugin_instance'} = $plugin_instance if (defined ($plugin_instance));
148         $ident->{'type_instance'} = $type_instance if (defined ($type_instance));
150         return ($ident);
151 } # _parse_identifier
153 sub _escape_argument
155         my $string = shift;
157         if ($string =~ m/^\w+$/)
158         {
159                 return ("$string");
160         }
162         $string =~ s#\\#\\\\#g;
163         $string =~ s#"#\\"#g;
164         $string = "\"$string\"";
166         return ($string);
169 =head1 PUBLIC METHODS
171 =over 4
173 =item I<$obj> = Collectd::Unixsock->B<new> ([I<$path>]);
175 Creates a new connection to the daemon. The optional I<$path> argument gives
176 the path to the UNIX socket of the C<unixsock plugin> and defaults to
177 F</var/run/collectd-unixsock>. Returns the newly created object on success and
178 false on error.
180 =cut
182 sub new
184         my $pkg = shift;
185         my $path = @_ ? shift : '/var/run/collectd-unixsock';
186         my $sock = _create_socket ($path) or return;
187         my $obj = bless (
188                 {
189                         path => $path,
190                         sock => $sock,
191                         error => 'No error'
192                 }, $pkg);
193         return ($obj);
194 } # new
196 =item I<$res> = I<$obj>-E<gt>B<getval> (I<%identifier>);
198 Requests a value-list from the daemon. On success a hash-ref is returned with
199 the name of each data-source as the key and the according value as, well, the
200 value. On error false is returned.
202 =cut
204 sub getval # {{{
206         my $obj = shift;
207         my %args = @_;
209         my $status;
210         my $fh = $obj->{'sock'} or confess ('object has no filehandle');
211         my $msg;
212         my $identifier;
214         my $ret = {};
216         $identifier = _create_identifier (\%args) or return;
218         $msg = 'GETVAL ' . _escape_argument ($identifier) . "\n";
219         _debug "-> $msg";
220         print $fh $msg;
222         $msg = <$fh>;
223         chomp ($msg);
224         _debug "<- $msg\n";
226         ($status, $msg) = split (' ', $msg, 2);
227         if ($status <= 0)
228         {
229                 $obj->{'error'} = $msg;
230                 return;
231         }
233         for (my $i = 0; $i < $status; $i++)
234         {
235                 my $entry = <$fh>;
236                 chomp ($entry);
237                 _debug "<- $entry\n";
239                 if ($entry =~ m/^(\w+)=NaN$/)
240                 {
241                         $ret->{$1} = undef;
242                 }
243                 elsif ($entry =~ m/^(\w+)=($RE{num}{real})$/)
244                 {
245                         $ret->{$1} = 0.0 + $2;
246                 }
247         }
249         return ($ret);
250 } # }}} sub getval
252 =item I<$res> = I<$obj>-E<gt>B<getthreshold> (I<%identifier>);
254 Requests a threshold from the daemon. On success a hash-ref is returned with
255 the threshold data. On error false is returned.
257 =cut
259 sub getthreshold # {{{
261         my $obj = shift;
262         my %args = @_;
264         my $status;
265         my $fh = $obj->{'sock'} or confess ('object has no filehandle');
266         my $msg;
267         my $identifier;
269         my $ret = {};
271         $identifier = _create_identifier (\%args) or return;
273         $msg = 'GETTHRESHOLD ' . _escape_argument ($identifier) . "\n";
274         _debug "-> $msg";
275         print $fh $msg;
277         $msg = <$fh>;
278         chomp ($msg);
279         _debug "<- $msg\n";
281         ($status, $msg) = split (' ', $msg, 2);
282         if ($status <= 0)
283         {
284                 $obj->{'error'} = $msg;
285                 return;
286         }
288         for (my $i = 0; $i < $status; $i++)
289         {
290                 my $entry = <$fh>;
291                 chomp ($entry);
292                 _debug "<- $entry\n";
294                 if ($entry =~ m/^([^:]+):\s*(\S.*)$/)
295                 {
296                         my $key = $1;
297                         my $value = $2;
299                         $key =~ s/^\s+//;
300                         $key =~ s/\s+$//;
302                         $ret->{$key} = $value;
303                 }
304         }
306         return ($ret);
307 } # }}} sub getthreshold
309 =item I<$obj>-E<gt>B<putval> (I<%identifier>, B<time> =E<gt> I<$time>, B<values> =E<gt> [...]);
311 Submits a value-list to the daemon. If the B<time> argument is omitted
312 C<time()> is used. The required argument B<values> is a reference to an array
313 of values that is to be submitted. The number of values must match the number
314 of values expected for the given B<type> (see L<VALUE IDENTIFIERS>), though
315 this is checked by the daemon, not the Perl module. Also, gauge data-sources
316 (e.E<nbsp>g. system-load) may be C<undef>. Returns true upon success and false
317 otherwise.
319 =cut
321 sub putval
323         my $obj = shift;
324         my %args = @_;
326         my $status;
327         my $fh = $obj->{'sock'} or confess;
328         my $msg;
329         my $identifier;
330         my $values;
331         my $interval = "";
333         if (defined $args{'interval'})
334         {
335                 $interval = ' interval='
336                 . _escape_argument ($args{'interval'});
337         }
339         $identifier = _create_identifier (\%args) or return;
340         if (!$args{'values'})
341         {
342                 cluck ("Need argument `values'");
343                 return;
344         }
346         if (!ref ($args{'values'}))
347         {
348                 $values = $args{'values'};
349         }
350         else
351         {
352                 my $time;
354                 if ("ARRAY" ne ref ($args{'values'}))
355                 {
356                         cluck ("Invalid `values' argument (expected an array ref)");
357                         return;
358                 }
360                 if (! scalar @{$args{'values'}})
361                 {
362                         cluck ("Empty `values' array");
363                         return;
364                 }
366                 $time = $args{'time'} ? $args{'time'} : time ();
367                 $values = join (':', $time, map { defined ($_) ? $_ : 'U' } (@{$args{'values'}}));
368         }
370         $msg = 'PUTVAL '
371         . _escape_argument ($identifier)
372         . $interval
373         . ' ' . _escape_argument ($values) . "\n";
374         _debug "-> $msg";
375         print $fh $msg;
377         $msg = <$fh>;
378         chomp ($msg);
379         _debug "<- $msg\n";
381         ($status, $msg) = split (' ', $msg, 2);
382         return (1) if ($status == 0);
384         $obj->{'error'} = $msg;
385         return;
386 } # putval
388 =item I<$res> = I<$obj>-E<gt>B<listval> ()
390 Queries a list of values from the daemon. The list is returned as an array of
391 hash references, where each hash reference is a valid identifier. The C<time>
392 member of each hash holds the epoch value of the last update of that value.
394 =cut
396 sub listval
398         my $obj = shift;
399         my $msg;
400         my @ret = ();
401         my $status;
402         my $fh = $obj->{'sock'} or confess;
404         _debug "LISTVAL\n";
405         print $fh "LISTVAL\n";
407         $msg = <$fh>;
408         chomp ($msg);
409         _debug "<- $msg\n";
410         ($status, $msg) = split (' ', $msg, 2);
411         if ($status < 0)
412         {
413                 $obj->{'error'} = $msg;
414                 return;
415         }
417         for (my $i = 0; $i < $status; $i++)
418         {
419                 my $time;
420                 my $ident;
422                 $msg = <$fh>;
423                 chomp ($msg);
424                 _debug "<- $msg\n";
426                 ($time, $ident) = split (' ', $msg, 2);
428                 $ident = _parse_identifier ($ident);
429                 $ident->{'time'} = int ($time);
431                 push (@ret, $ident);
432         } # for (i = 0 .. $status)
434         return (@ret);
435 } # listval
437 =item I<$res> = I<$obj>-E<gt>B<putnotif> (B<severity> =E<gt> I<$severity>, B<message> =E<gt> I<$message>, ...);
439 Submits a notification to the daemon.
441 Valid options are:
443 =over 4
445 =item B<severity>
447 Sets the severity of the notification. The value must be one of the following
448 strings: C<failure>, C<warning>, or C<okay>. Case does not matter. This option
449 is mandatory.
451 =item B<message>
453 Sets the message of the notification. This option is mandatory.
455 =item B<time>
457 Sets the time. If omitted, C<time()> is used.
459 =item I<Value identifier>
461 All the other fields of the value identifiers, B<host>, B<plugin>,
462 B<plugin_instance>, B<type>, and B<type_instance>, are optional. When given,
463 the notification is associated with the performance data of that identifier.
464 For more details, please see L<collectd-unixsock(5)>.
466 =back
468 =cut
470 sub putnotif
472         my $obj = shift;
473         my %args = @_;
475         my $status;
476         my $fh = $obj->{'sock'} or confess;
478         my $msg; # message sent to the socket
479         
480         if (!$args{'message'})
481         {
482                 cluck ("Need argument `message'");
483                 return;
484         }
485         if (!$args{'severity'})
486         {
487                 cluck ("Need argument `severity'");
488                 return;
489         }
490         $args{'severity'} = lc ($args{'severity'});
491         if (($args{'severity'} ne 'failure')
492                 && ($args{'severity'} ne 'warning')
493                 && ($args{'severity'} ne 'okay'))
494         {
495                 cluck ("Invalid `severity: " . $args{'severity'});
496                 return;
497         }
499         if (!$args{'time'})
500         {
501                 $args{'time'} = time ();
502         }
503         
504         $msg = 'PUTNOTIF '
505         . join (' ', map { $_ . '=' . _escape_argument ($args{$_}) } (keys %args))
506         . "\n";
508         _debug "-> $msg";
509         print $fh $msg;
511         $msg = <$fh>;
512         chomp ($msg);
513         _debug "<- $msg\n";
515         ($status, $msg) = split (' ', $msg, 2);
516         return (1) if ($status == 0);
518         $obj->{'error'} = $msg;
519         return;
520 } # putnotif
522 =item I<$obj>-E<gt>B<flush> (B<timeout> =E<gt> I<$timeout>, B<plugins> =E<gt> [...], B<identifier>  =E<gt> [...]);
524 Flush cached data.
526 Valid options are:
528 =over 4
530 =item B<timeout>
532 If this option is specified, only data older than I<$timeout> seconds is
533 flushed.
535 =item B<plugins>
537 If this option is specified, only the selected plugins will be flushed. The
538 argument is a reference to an array of strings.
540 =item B<identifier>
542 If this option is specified, only the given identifier(s) will be flushed. The
543 argument is a reference to an array of identifiers. Identifiers, in this case,
544 are hash references and have the members as outlined in L<VALUE IDENTIFIERS>.
546 =back
548 =cut
550 sub flush
552         my $obj  = shift;
553         my %args = @_;
555         my $fh = $obj->{'sock'} or confess;
557         my $status = 0;
558         my $msg    = "FLUSH";
560         if (defined ($args{'timeout'}))
561         {
562                 $msg .= " timeout=" . $args{'timeout'};
563         }
565         if ($args{'plugins'})
566         {
567                 foreach my $plugin (@{$args{'plugins'}})
568                 {
569                         $msg .= " plugin=" . $plugin;
570                 }
571         }
573         if ($args{'identifier'})
574         {
575                 for (@{$args{'identifier'}})
576                 {
577                         my $identifier = $_;
578                         my $ident_str;
580                         if (ref ($identifier) ne 'HASH')
581                         {
582                                 cluck ("The argument of the `identifier' "
583                                         . "option must be an array reference "
584                                         . "of hash references.");
585                                 return;
586                         }
588                         $ident_str = _create_identifier ($identifier);
589                         if (!$ident_str)
590                         {
591                                 return;
592                         }
594                         $msg .= ' identifier=' . _escape_argument ($ident_str);
595                 }
596         }
598         $msg .= "\n";
600         _debug "-> $msg";
601         print $fh $msg;
603         $msg = <$fh>;
604         chomp ($msg);
605         _debug "<- $msg\n";
607         ($status, $msg) = split (' ', $msg, 2);
608         return (1) if ($status == 0);
610         $obj->{'error'} = $msg;
611         return;
614 sub error
616         my $obj = shift;
617         if ($obj->{'error'})
618         {
619                 return ($obj->{'error'});
620         }
621         return;
624 =item I<$obj>-E<gt>destroy ();
626 Closes the socket before the object is destroyed. This function is also
627 automatically called then the object goes out of scope.
629 =back
631 =cut
633 sub destroy
635         my $obj = shift;
636         if ($obj->{'sock'})
637         {
638                 close ($obj->{'sock'});
639                 delete ($obj->{'sock'});
640         }
643 sub DESTROY
645         my $obj = shift;
646         $obj->destroy ();
649 =head1 SEE ALSO
651 L<collectd(1)>,
652 L<collectd.conf(5)>,
653 L<collectd-unixsock(5)>
655 =head1 AUTHOR
657 Florian octo Forster E<lt>octo@collectd.orgE<gt>
659 =cut
661 # vim: set fdm=marker :