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 Carp qw(cluck confess carp croak);
61 use Scalar::Util qw( looks_like_number );
73 my $sock = IO::Socket::UNIX->new (Type => SOCK_STREAM, Peer => $path);
76 cluck ("Cannot open UNIX-socket $path: $!");
82 =head1 VALUE IDENTIFIERS
84 The values in the collectd are identified using a five-tuple (host, plugin,
85 plugin-instance, type, type-instance) where only plugin instance and type
86 instance may be undef. Many functions expect an I<%identifier> hash that has at
87 least the members B<host>, B<plugin>, and B<type>, possibly completed by
88 B<plugin_instance> and B<type_instance>.
90 Usually you can pass this hash as follows:
92 $self->method (host => $host, plugin => $plugin, type => $type, %other_args);
96 sub _create_identifier
99 my ($host, $plugin, $type);
101 if (!$args->{host} || !$args->{plugin} || !$args->{type})
103 cluck ("Need `host', `plugin' and `type'");
107 $host = $args->{host};
108 $plugin = $args->{plugin};
109 $plugin .= '-' . $args->{plugin_instance} if defined $args->{plugin_instance};
110 $type = $args->{type};
111 $type .= '-' . $args->{type_instance} if defined $args->{type_instance};
113 return "$host/$plugin/$type";
114 } # _create_identifier
116 sub _parse_identifier
119 my ($plugin_instance, $type_instance);
121 my ($host, $plugin, $type) = split /\//, $string;
123 ($plugin, $plugin_instance) = split /-/, $plugin, 2;
124 ($type, $type_instance) = split /-/, $type, 2;
132 $ident->{plugin_instance} = $plugin_instance if defined $plugin_instance;
133 $ident->{type_instance} = $type_instance if defined $type_instance;
136 } # _parse_identifier
142 return $_ if /^\w+$/;
149 =head1 PUBLIC METHODS
153 =item I<$self> = Collectd::Unixsock->B<new> ([I<$path>]);
155 Creates a new connection to the daemon. The optional I<$path> argument gives
156 the path to the UNIX socket of the C<unixsock plugin> and defaults to
157 F</var/run/collectd-unixsock>. Returns the newly created object on success and
165 my $path = shift || '/var/run/collectd-unixsock';
166 my $sock = _create_socket ($path) or return;
175 =item I<$res> = I<$self>-E<gt>B<getval> (I<%identifier>);
177 Requests a value-list from the daemon. On success a hash-ref is returned with
178 the name of each data-source as the key and the according value as, well, the
179 value. On error false is returned.
188 my ($status, $msg, $identifier, $ret);
189 my $fh = $self->{sock} or confess ('object has no filehandle');
193 $identifier = _create_identifier (\%args) or return;
195 $msg = 'GETVAL ' . _escape_argument ($identifier) . "\n";
203 ($status, $msg) = split / /, $msg, 2;
206 $self->{error} = $msg;
214 _debug "<- $entry\n";
216 if ($entry =~ m/^(\w+)=NaN$/)
220 elsif ($entry =~ m/^(\w+)=(.*)$/ and looks_like_number($2))
222 $ret->{$1} = 0.0 + $2;
229 =item I<$res> = I<$self>-E<gt>B<getthreshold> (I<%identifier>);
231 Requests a threshold from the daemon. On success a hash-ref is returned with
232 the threshold data. On error false is returned.
236 sub getthreshold # {{{
241 my ($status, $msg, $identifier, $ret);
242 my $fh = $self->{sock} or confess ('object has no filehandle');
246 $identifier = _create_identifier (\%args) or return;
248 $msg = 'GETTHRESHOLD ' . _escape_argument ($identifier) . "\n";
256 ($status, $msg) = split (' ', $msg, 2);
259 $self->{error} = $msg;
267 _debug "<- $entry\n";
269 if ($entry =~ m/^([^:]+):\s*(\S.*)$/)
274 $key =~ s/(?:^\s+|\s$)//;
275 $ret->{$key} = $value;
280 } # }}} sub getthreshold
282 =item I<$self>-E<gt>B<putval> (I<%identifier>, B<time> =E<gt> I<$time>, B<values> =E<gt> [...]);
284 Submits a value-list to the daemon. If the B<time> argument is omitted
285 C<time()> is used. The required argument B<values> is a reference to an array
286 of values that is to be submitted. The number of values must match the number
287 of values expected for the given B<type> (see L<VALUE IDENTIFIERS>), though
288 this is checked by the daemon, not the Perl module. Also, gauge data-sources
289 (e.E<nbsp>g. system-load) may be C<undef>. Returns true upon success and false
299 my ($status, $msg, $identifier, $values);
300 my $fh = $self->{sock} or confess;
302 my $interval = defined $args{interval} ?
303 ' interval=' . _escape_argument ($args{interval}) : '';
305 $identifier = _create_identifier (\%args) or return;
308 cluck ("Need argument `values'");
312 if (ref ($args{values}))
316 if ("ARRAY" ne ref ($args{values}))
318 cluck ("Invalid `values' argument (expected an array ref)");
322 if (! scalar @{$args{values}})
324 cluck ("Empty `values' array");
328 $time = $args{time} || time;
329 $values = join (':', $time, map { defined $_ ? $_ : 'U' } @{$args{values}});
333 $values = $args{values};
337 . _escape_argument ($identifier)
339 . ' ' . _escape_argument ($values) . "\n";
347 ($status, $msg) = split / /, $msg, 2;
348 return 1 if $status == 0;
350 $self->{error} = $msg;
354 =item I<$res> = I<$self>-E<gt>B<listval> ()
356 Queries a list of values from the daemon. The list is returned as an array of
357 hash references, where each hash reference is a valid identifier. The C<time>
358 member of each hash holds the epoch value of the last update of that value.
367 my $fh = $self->{sock} or confess;
370 print $fh "LISTVAL\n";
375 ($status, $msg) = split / /, $msg, 2;
378 $self->{error} = $msg;
391 ($time, $ident) = split / /, $msg, 2;
393 $ident = _parse_identifier ($ident);
394 $ident->{time} = int $time;
397 } # for (i = 0 .. $status)
402 =item I<$res> = I<$self>-E<gt>B<putnotif> (B<severity> =E<gt> I<$severity>, B<message> =E<gt> I<$message>, ...);
404 Submits a notification to the daemon.
412 Sets the severity of the notification. The value must be one of the following
413 strings: C<failure>, C<warning>, or C<okay>. Case does not matter. This option
418 Sets the message of the notification. This option is mandatory.
422 Sets the time. If omitted, C<time()> is used.
424 =item I<Value identifier>
426 All the other fields of the value identifiers, B<host>, B<plugin>,
427 B<plugin_instance>, B<type>, and B<type_instance>, are optional. When given,
428 the notification is associated with the performance data of that identifier.
429 For more details, please see L<collectd-unixsock(5)>.
441 my $fh = $self->{sock} or confess;
443 my $msg; # message sent to the socket
445 for my $arg (qw( message severity ))
447 cluck ("Need argument `$arg'"), return unless $args{$arg};
449 $args{severity} = lc $args{severity};
450 if (($args{severity} ne 'failure')
451 && ($args{severity} ne 'warning')
452 && ($args{severity} ne 'okay'))
454 cluck ("Invalid `severity: " . $args{severity});
458 $args{time} ||= time;
461 . join (' ', map { $_ . '=' . _escape_argument ($args{$_}) } keys %args)
471 ($status, $msg) = split / /, $msg, 2;
472 return 1 if $status == 0;
474 $self->{error} = $msg;
478 =item I<$self>-E<gt>B<flush> (B<timeout> =E<gt> I<$timeout>, B<plugins> =E<gt> [...], B<identifier> =E<gt> [...]);
488 If this option is specified, only data older than I<$timeout> seconds is
493 If this option is specified, only the selected plugins will be flushed. The
494 argument is a reference to an array of strings.
498 If this option is specified, only the given identifier(s) will be flushed. The
499 argument is a reference to an array of identifiers. Identifiers, in this case,
500 are hash references and have the members as outlined in L<VALUE IDENTIFIERS>.
511 my $fh = $self->{sock} or confess;
516 $msg .= " timeout=$args{timeout}" if defined $args{timeout};
520 foreach my $plugin (@{$args{plugins}})
522 $msg .= " plugin=" . $plugin;
526 if ($args{identifier})
528 for my $identifier (@{$args{identifier}})
532 if (ref ($identifier) ne 'HASH')
534 cluck ("The argument of the `identifier' "
535 . "option must be an array of hashrefs.");
539 $ident_str = _create_identifier ($identifier) or return;
540 $msg .= ' identifier=' . _escape_argument ($ident_str);
553 ($status, $msg) = split / /, $msg, 2;
554 return 1 if $status == 0;
556 $self->{error} = $msg;
562 return shift->{error};
565 =item I<$self>-E<gt>destroy ();
567 Closes the socket before the object is destroyed. This function is also
568 automatically called then the object goes out of scope.
580 delete $self->{sock};
594 L<collectd-unixsock(5)>
598 Florian octo Forster E<lt>octo@collectd.orgE<gt>
602 # vim: set fdm=marker :