2 # collectd - bindings/buildperl/Collectd/Unixsock.pm
3 # Copyright (C) 2007,2008 Florian octo Forster
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:
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
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.
24 # Florian Forster <octo at collectd.org>
27 package Collectd::Unixsock;
31 Collectd::Unixsock - Abstraction layer for accessing the functionality by
32 collectd's unixsock plugin.
36 use Collectd::Unixsock ();
38 my $sock = Collectd::Unixsock->new ($path);
40 my $value = $sock->getval (%identifier);
41 $sock->putval (%identifier,
43 values => [123, 234, 345]);
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.
59 #use constant { NOTIF_FAILURE => 1, NOTIF_WARNING => 2, NOTIF_OKAY => 4 };
61 use Carp (qw(cluck confess));
63 use Scalar::Util qw( looks_like_number );
81 my $sock = IO::Socket::UNIX->new (Type => SOCK_STREAM, Peer => $path);
84 cluck ("Cannot open UNIX-socket $path: $!");
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);
104 sub _create_identifier
111 if (!$args->{'host'} || !$args->{'plugin'} || !$args->{'type'})
113 cluck ("Need `host', `plugin' and `type'");
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
136 ($host, $plugin, $type) = split ('/', $string);
138 ($plugin, $plugin_instance) = split ('-', $plugin, 2);
139 ($type, $type_instance) = split ('-', $type, 2);
147 $ident->{'plugin_instance'} = $plugin_instance if (defined ($plugin_instance));
148 $ident->{'type_instance'} = $type_instance if (defined ($type_instance));
151 } # _parse_identifier
157 if ($string =~ m/^\w+$/)
162 $string =~ s#\\#\\\\#g;
163 $string =~ s#"#\\"#g;
164 $string = "\"$string\"";
169 =head1 PUBLIC METHODS
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
185 my $path = @_ ? shift : '/var/run/collectd-unixsock';
186 my $sock = _create_socket ($path) or return;
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.
210 my $fh = $obj->{'sock'} or confess ('object has no filehandle');
216 $identifier = _create_identifier (\%args) or return;
218 $msg = 'GETVAL ' . _escape_argument ($identifier) . "\n";
226 ($status, $msg) = split (' ', $msg, 2);
229 $obj->{'error'} = $msg;
233 for (my $i = 0; $i < $status; $i++)
237 _debug "<- $entry\n";
239 if ($entry =~ m/^(\w+)=NaN$/)
243 elsif ($entry =~ m/^(\w+)=(.*)$/ and looks_like_number($2))
245 $ret->{$1} = 0.0 + $2;
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.
259 sub getthreshold # {{{
265 my $fh = $obj->{'sock'} or confess ('object has no filehandle');
271 $identifier = _create_identifier (\%args) or return;
273 $msg = 'GETTHRESHOLD ' . _escape_argument ($identifier) . "\n";
281 ($status, $msg) = split (' ', $msg, 2);
284 $obj->{'error'} = $msg;
288 for (my $i = 0; $i < $status; $i++)
292 _debug "<- $entry\n";
294 if ($entry =~ m/^([^:]+):\s*(\S.*)$/)
302 $ret->{$key} = $value;
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
327 my $fh = $obj->{'sock'} or confess;
333 if (defined $args{'interval'})
335 $interval = ' interval='
336 . _escape_argument ($args{'interval'});
339 $identifier = _create_identifier (\%args) or return;
340 if (!$args{'values'})
342 cluck ("Need argument `values'");
346 if (!ref ($args{'values'}))
348 $values = $args{'values'};
354 if ("ARRAY" ne ref ($args{'values'}))
356 cluck ("Invalid `values' argument (expected an array ref)");
360 if (! scalar @{$args{'values'}})
362 cluck ("Empty `values' array");
366 $time = $args{'time'} ? $args{'time'} : time ();
367 $values = join (':', $time, map { defined ($_) ? $_ : 'U' } (@{$args{'values'}}));
371 . _escape_argument ($identifier)
373 . ' ' . _escape_argument ($values) . "\n";
381 ($status, $msg) = split (' ', $msg, 2);
382 return (1) if ($status == 0);
384 $obj->{'error'} = $msg;
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.
402 my $fh = $obj->{'sock'} or confess;
405 print $fh "LISTVAL\n";
410 ($status, $msg) = split (' ', $msg, 2);
413 $obj->{'error'} = $msg;
417 for (my $i = 0; $i < $status; $i++)
426 ($time, $ident) = split (' ', $msg, 2);
428 $ident = _parse_identifier ($ident);
429 $ident->{'time'} = int ($time);
432 } # for (i = 0 .. $status)
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.
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
453 Sets the message of the notification. This option is mandatory.
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)>.
476 my $fh = $obj->{'sock'} or confess;
478 my $msg; # message sent to the socket
480 if (!$args{'message'})
482 cluck ("Need argument `message'");
485 if (!$args{'severity'})
487 cluck ("Need argument `severity'");
490 $args{'severity'} = lc ($args{'severity'});
491 if (($args{'severity'} ne 'failure')
492 && ($args{'severity'} ne 'warning')
493 && ($args{'severity'} ne 'okay'))
495 cluck ("Invalid `severity: " . $args{'severity'});
501 $args{'time'} = time ();
505 . join (' ', map { $_ . '=' . _escape_argument ($args{$_}) } (keys %args))
515 ($status, $msg) = split (' ', $msg, 2);
516 return (1) if ($status == 0);
518 $obj->{'error'} = $msg;
522 =item I<$obj>-E<gt>B<flush> (B<timeout> =E<gt> I<$timeout>, B<plugins> =E<gt> [...], B<identifier> =E<gt> [...]);
532 If this option is specified, only data older than I<$timeout> seconds is
537 If this option is specified, only the selected plugins will be flushed. The
538 argument is a reference to an array of strings.
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>.
555 my $fh = $obj->{'sock'} or confess;
560 if (defined ($args{'timeout'}))
562 $msg .= " timeout=" . $args{'timeout'};
565 if ($args{'plugins'})
567 foreach my $plugin (@{$args{'plugins'}})
569 $msg .= " plugin=" . $plugin;
573 if ($args{'identifier'})
575 for (@{$args{'identifier'}})
580 if (ref ($identifier) ne 'HASH')
582 cluck ("The argument of the `identifier' "
583 . "option must be an array reference "
584 . "of hash references.");
588 $ident_str = _create_identifier ($identifier);
594 $msg .= ' identifier=' . _escape_argument ($ident_str);
607 ($status, $msg) = split (' ', $msg, 2);
608 return (1) if ($status == 0);
610 $obj->{'error'} = $msg;
619 return ($obj->{'error'});
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.
638 close ($obj->{'sock'});
639 delete ($obj->{'sock'});
653 L<collectd-unixsock(5)>
657 Florian octo Forster E<lt>octo@collectd.orgE<gt>
661 # vim: set fdm=marker :