blib/lib/Net/SNMP/QueryEngine/AnyEvent.pm

filter: Statementstmt 91.3% 21 / 23 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.5% 29 / 31 CC 1 SCAR 0.4
CC
1
Cov
91%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Net::SNMP::QueryEngine::AnyEvent;
2  
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 our $VERSION = 'v1.2.0';
8  
9 1 ▶use AnyEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use AnyEvent::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Data::MessagePack;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 0 ▶use Data::MessagePack::Stream;
Subroutine BEGIN: called CC=1 SCAR=2.6
14 use Scalar::Util qw(weaken);
15  
16 use constant RT_SETOPT => 1;
17 use constant RT_GETOPT => 2;
18 use constant RT_INFO => 3;
19 use constant RT_GET => 4;
20 use constant RT_GETTABLE => 5;
21 use constant RT_DEST_INFO => 6;
22 use constant RT_REPLY => 0x10;
23 use constant RT_ERROR => 0x20;
24  
25 sub new
26 {
27 my ($class, %args) = @_;
28 my %known = map { $_ => 1 } qw(connect reconnect on_connect on_disconnect);
29 for my $k (keys %args) {
30 Carp::croak("unknown constructor argument \"$k\"")
31 unless $known{$k};
32 }
33 my $self = bless {
34 connect => $args{connect} || ["127.0.0.1", 7667],
35 reconnect => defined $args{reconnect} ? $args{reconnect} : 1,
36 on_connect => $args{on_connect},
37 on_disconnect => $args{on_disconnect},
38 condvar => AnyEvent->condvar,
39 pending => 0,
40 mp => Data::MessagePack->new->prefer_integer,
41 cid => int rand 1000000,
42 cb => {},
43 inflight => {},
44 queue => [],
45 connected => 0,
46 down => 0,
47 dead => 0,
48 }, $class;
49 $self->_connect;
50 return $self;
51 }
52  
53 sub _connect
54 {
55 my $self = shift;
56 $self->{reconnect_timer} = undef;
57 weaken(my $weak = $self);
58 $self->{up} = Data::MessagePack::Stream->new;
59 $self->{handle} = AnyEvent::Handle->new(
60 connect => $self->{connect},
61 on_connect => sub {
62 my $s = $weak or return;
63 $s->{connected} = 1;
64 $s->{down} = 0;
65 $s->{on_connect}->($s) if $s->{on_connect};
66 $s->_flush_queue;
67 },
68 on_connect_error => sub { $weak->_disconnected($_[0], $_[1]) if $weak },
69 on_error => sub { $weak->_disconnected($_[0], $_[2]) if $weak },
70 on_eof => sub { $weak->_disconnected($_[0], "connection closed") if $weak },
71 on_read => sub { $weak->read_handler($_[0]) if $weak },
72 );
73 }
74  
75 sub _disconnected
76 {
77 my ($self, $h, $reason) = @_;
78 return unless $self->{handle} && $h == $self->{handle};
79 $self->{handle}->destroy;
80 $self->{handle} = undef;
81 $self->{connected} = 0;
82  
83 if (!$self->{down}) {
84 $self->{down} = 1;
85 $self->{on_disconnect}->($self, $reason) if $self->{on_disconnect};
86 }
87  
88 $self->_deliver($_, 0, "connection lost: $reason")
89 for sort { $a <=> $b } keys %{$self->{inflight}};
90  
91 if ($self->{reconnect} > 0) {
92 weaken(my $weak = $self);
93 $self->{reconnect_timer} = AnyEvent->timer(
94 after => $self->{reconnect},
95 cb => sub { $weak->_connect if $weak },
96 );
97 } else {
98 $self->{dead} = 1;
99 my $queue = $self->{queue};
100 $self->{queue} = [];
101 $self->_deliver($_->[0], 0, "not connected") for @$queue;
102 }
103 }
104  
105 sub _flush_queue
106 {
107 my $self = shift;
108 while ($self->{connected} && @{$self->{queue}}) {
109 my $q = shift @{$self->{queue}};
110 $self->{inflight}{$q->[0]} = 1;
111 $self->{handle}->push_write($q->[1]);
112 }
113 }
114  
115 sub when_done
116 {
117 my ($self, $host, $port, $cb) = @_;
118 my $hp = "$host:$port";
119 $self->{hpcb}{$hp} = $cb;
120 }
121  
122 sub wait
123 {
124 my $self = shift;
125 return unless $self->{pending};
126 $self->{condvar}->recv;
127 }
128  
129 sub cmd
130 {
131 my ($self, $cb, @cmd) = @_;
132 my $cid = $cmd[1];
133 $self->{cb}{$cid} = $cb;
134 $self->{pending}++;
135 if ($self->{pending} == 1 && $self->{condvar}->ready) {
136 # XXX "reset" a condvar so "wait" can be correctly called again
137 $self->{condvar} = AnyEvent->condvar;
138 }
139 if ($self->{dead}) {
140 weaken(my $weak = $self);
141 $self->{failfast}{$cid} = AnyEvent->timer(after => 0, cb => sub {
142 my $s = $weak or return;
143 delete $s->{failfast}{$cid};
144 $s->_deliver($cid, 0, "not connected");
145 });
146 } elsif ($self->{connected}) {
147 $self->{inflight}{$cid} = 1;
148 $self->{handle}->push_write($self->{mp}->pack(\@cmd));
149 } else {
150 push @{$self->{queue}}, [$cid, $self->{mp}->pack(\@cmd)];
151 }
152 }
153  
154 sub read_handler
155 {
156 my ($self, $h) = @_;
157  
158 $self->{up}->feed($h->{rbuf});
159 $h->{rbuf} = "";
160  
161 while ($self->{up}->next) {
162 my $data = $self->{up}->data;
163  
164 if (ref($data) ne "ARRAY" || @$data < 3 || !$self->{cb}{$data->[1]}) {
165 } else {
166 $self->_deliver($data->[1], $data->[0] & RT_REPLY, $data->[2]);
167 }
168 }
169 }
170  
171 sub _deliver
172 {
173 my ($self, $cid, $ok, $result) = @_;
174 my $cb = delete $self->{cb}{$cid} or return;
175 delete $self->{inflight}{$cid};
176 $cb->($self, $ok, $result);
177  
178 my $hp = delete $self->{cid2hp}{$cid};
179 if ($hp && $self->{hp}{$hp}) {
180 $self->{hp}{$hp}--;
181 if ($self->{hp}{$hp} <= 0) {
182 $self->{hpcb}{$hp}->($self) if $self->{hpcb}{$hp};
183 }
184 }
185  
186 $self->{pending}--;
187 if ($self->{pending} <= 0) {
188 $self->{condvar}->send;
189 }
190 }
191  
192 sub DESTROY
193 {
194 my $self = shift;
195 $self->{reconnect_timer} = undef;
196 $self->{handle}->destroy if $self->{handle};
197 }
198  
199 sub setopt
200 {
201 my ($self, $host, $port, $opts, $cb) = @_;
202 $self->cmd($cb, RT_SETOPT, ++$self->{cid}, $host, $port, $opts);
203 }
204  
205 sub getopt
206 {
207 my ($self, $host, $port, $cb) = @_;
208 $self->cmd($cb, RT_GETOPT, ++$self->{cid}, $host, $port);
209 }
210  
211 sub get
212 {
213 my ($self, $host, $port, $oids, $cb) = @_;
214  
215 my $cid = ++$self->{cid};
216 my $hp = "$host:$port";
217 $self->{hp}{$hp}++;
218 $self->{cid2hp}{$cid} = $hp;
219  
220 $self->cmd($cb, RT_GET, $cid, $host, $port, $oids);
221 }
222  
223 sub gettable
224 {
225 my ($self, $host, $port, $oid, $max_rep, $cb) = @_;
226  
227 my $cid = ++$self->{cid};
228 my $hp = "$host:$port";
229 $self->{hp}{$hp}++;
230 $self->{cid2hp}{$cid} = $hp;
231  
232 if ($cb) {
233 $self->cmd($cb, RT_GETTABLE, $cid, $host, $port, $oid, $max_rep);
234 } else {
235 $self->cmd($max_rep, RT_GETTABLE, $cid, $host, $port, $oid);
236 }
237 }
238  
239 sub info
240 {
241 my ($self, $cb) = @_;
242 $self->cmd($cb, RT_INFO, ++$self->{cid});
243 }
244  
245 sub dest_info
246 {
247 my ($self, $cb, $host, $port) = @_;
248 $self->cmd($cb, RT_DEST_INFO, ++$self->{cid}, $host, $port);
249 }
250  
251 =head1 NAME
252  
253 Net::SNMP::QueryEngine::AnyEvent - multiplexing SNMP query engine client using AnyEvent
254  
255 =head1 VERSION
256  
257 Version v1.2.0
258  
259 =head1 SYNOPSIS
260  
261 This is an AnyEvent-flavored Perl client for snmp-query-engine,
262 a multiplexing SNMP query engine.
263  
264 use Net::SNMP::QueryEngine::AnyEvent;
265  
266 my $sqe = Net::SNMP::QueryEngine::AnyEvent->new;
267  
268 $sqe->setopt("127.0.0.1", 161, { community => "meow" }, sub {});
269 $sqe->when_done("127.0.0.1", 161, sub { print "done with localhost\n" });
270  
271 $sqe->gettable("127.0.0.1", 161, "1.3.6.1.2.1.1", sub {
272 my ($h, $ok, $r) = @_;
273 for my $t (@$r) {
274 print "$t->[0] => $t->[1]\n";
275 }
276 });
277  
278 $sqe->get("127.0.0.1", 161,
279 ["1.3.6.1.2.1.1.5.0", "1.3.6.1.2.1.25.1.1.0"],
280 sub {
281 my ($h, $ok, $r) = @_;
282 print "Hostname: $r->[0][1]\n";
283 print "Uptime : $r->[1][1]\n";
284 });
285  
286 $sqe->wait;
287  
288 =head1 METHODS
289  
290 =head2 new
291  
292 Constructor.
293  
294 Net::SNMP::QueryEngine::AnyEvent->new(
295 connect => ["127.0.0.1", 7667],
296 reconnect => 1,
297 on_connect => sub { my ($sqe) = @_; ... },
298 on_disconnect => sub { my ($sqe, $reason) = @_; ... },
299 );
300  
301 All arguments are optional. By default, connects to
302 snmp-query-engine listening on localhost, port 7667;
303 override this by specifying a "connect" argument.
304  
305 "reconnect" is the number of seconds, possibly fractional,
306 between reconnection attempts after the connection to the
307 daemon is lost or cannot be established; it defaults to 1. Requests issued while the
308 connection is down are queued and sent, in order, once the
309 connection is re-established. Requests that were already sent
310 but not yet answered when the connection was lost fail: their
311 callbacks are called with a false $ok and "connection lost: ..."
312 as the result.
313  
314 When "reconnect" is 0, the client does not reconnect. After
315 the first disconnect every request, queued or new, fails with
316 a false $ok and "not connected" as the result.
317  
318 "on_connect" is called with the client object as its only
319 argument every time a connection to the daemon is established,
320 including the first one. Requests issued from this callback
321 are sent before any queued requests, which makes it the right
322 place to re-establish per-destination options with setopt().
323  
324 "on_disconnect" is called with the client object and the
325 disconnect reason whenever the connection to the daemon is
326 lost. It is called before the callbacks of the requests that
327 fail due to the disconnect.
328  
329 =head2 when_done
330  
331 Execute provided callback when there are no unfinished
332 get or gettable queries towards a specified host:port.
333  
334 =head2 wait
335  
336 Enters event loop until there are no unanswered queries.
337 Can be called multiple times.
338  
339 =head2 setopt
340  
341 Performs setopt request.
342  
343 =head2 getopt
344  
345 Performs getopt request.
346  
347 =head2 get
348  
349 Performs get request for arbitrary number
350 of OIDs.
351  
352 =head2 gettable
353  
354 Performs gettable request.
355  
356 =head2 info
357  
358 Performs info request.
359  
360 =head2 dest_info
361  
362 Performs dest_info request.
363  
364 =head1 USING WITH YOUR OWN EVENT LOOP
365  
366 The wait() method is an optional convenience. All callbacks are
367 driven by the event loop itself, so a program which manages its own
368 events never needs to call it: block on a condvar of your own and
369 send it from a callback:
370  
371 my $cv = AnyEvent->condvar;
372 my $sqe = Net::SNMP::QueryEngine::AnyEvent->new;
373  
374 $sqe->gettable("127.0.0.1", 161, "1.3.6.1.2.1.2.2", sub {
375 my ($h, $ok, $r) = @_;
376 ...
377 });
378 $sqe->when_done("127.0.0.1", 161, sub { $cv->send });
379  
380 $cv->recv;
381  
382 =head1 AUTHOR
383  
384 Anton Berezin, C<< <tobez at tobez.org> >>
385  
386 =head1 BUGS
387  
388 Please report any bugs or feature requests via the GitHub issue tracker
389 at L<https://github.com/tobez/Net-SNMP-QueryEngine-AnyEvent/issues>.
390  
391  
392 =head1 SEE ALSO
393  
394 The snmp-query-engine daemon can be found on github
395 at L<https://github.com/tobez/snmp-query-engine>.
396  
397  
398 =head1 SUPPORT
399  
400 You can find documentation for this module with the perldoc command.
401  
402 perldoc Net::SNMP::QueryEngine::AnyEvent
403  
404  
405 You can also look for information at:
406  
407 =over 4
408  
409 =item * GitHub: source code and issue tracker
410  
411 L<https://github.com/tobez/Net-SNMP-QueryEngine-AnyEvent>
412  
413 =item * MetaCPAN
414  
415 L<https://metacpan.org/dist/Net-SNMP-QueryEngine-AnyEvent>
416  
417 =back
418  
419  
420 =head1 ACKNOWLEDGEMENTS
421  
422 This work is in part sponsored by Telia Denmark.
423  
424 =head1 LICENSE AND COPYRIGHT
425  
426 Copyright (c) 2012-2026, Anton Berezin "<tobez@tobez.org>". All rights
427 reserved.
428  
429 Redistribution and use in source and binary forms, with or without
430 modification, are permitted provided that the following conditions are
431 met:
432  
433 1. Redistributions of source code must retain the above copyright
434 notice, this list of conditions and the following disclaimer.
435  
436 2. Redistributions in binary form must reproduce the above copyright
437 notice, this list of conditions and the following disclaimer in the
438 documentation and/or other materials provided with the distribution.
439  
440 THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
441 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
442 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
443 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE
444 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
445 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
446 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
447 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
448 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
449 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
450 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
451  
452 =cut
453  
454 1;
↑ Summary