1 # $Id: IRSpy.pm,v 1.26 2006-10-12 11:06:03 mike Exp $
9 use Data::Dumper; # For debugging only
11 use Net::Z3950::ZOOM 1.13; # For the ZOOM version-check only
12 use ZOOM::IRSpy::Node;
13 use ZOOM::IRSpy::Connection;
14 use ZOOM::IRSpy::Record;
17 our $VERSION = '0.02';
20 # Enumeration for callback functions to return
21 package ZOOM::IRSpy::Status;
22 sub OK { 29 } # No problems, task is still progressing
23 sub TASK_DONE { 18 } # Task is complete, next task should begin
24 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
25 sub TEST_BAD { 31 } # Whole test is complete, and failed
31 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
36 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
37 print $spy->report_status();
41 This module exists to implement the IRspy program, which discovers,
42 analyses and monitors IR servers implementing the Z39.50 and SRU/W
43 protocols. It is a successor to the ZSpy program.
48 ZOOM::Log::mask_str("irspy");
49 ZOOM::Log::mask_str("irspy_test");
50 ZOOM::Log::mask_str("irspy_debug");
51 ZOOM::Log::mask_str("irspy_event");
52 ZOOM::Log::mask_str("irspy_unhandled");
57 my($dbname, $user, $password) = @_;
60 push @options, (user => $user, password => $password)
63 my $conn = new ZOOM::Connection($dbname, 0, @options)
64 or die "$0: can't connection to IRSpy database 'dbname'";
68 allrecords => 1, # unless overridden by targets()
69 query => undef, # filled in later
70 targets => undef, # filled in later
71 connections => undef, # filled in later
72 tests => [], # stack of tests currently being executed
74 $this->log("irspy", "starting up with database '$dbname'");
86 # Explicitly nominate a set of targets to check, overriding the
87 # default which is to re-check everything in the database. Each
88 # target already in the database results in the existing record being
89 # updated; each new target causes a new record to be added.
95 $this->log("irspy", "setting explicit list of targets ",
96 join(", ", map { "'$_'" } @targets));
97 $this->{allrecords} = 0;
99 foreach my $target (@targets) {
100 my($host, $port, $db, $newtarget) = _parse_target_string($target);
101 if ($newtarget ne $target) {
102 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
103 $target = $newtarget; # This is written through the ref
105 push @qlist, (qq[(host="$host" and port="$port" and path="$db")]);
108 $this->{targets} = \@targets;
109 $this->{query} = join(" or ", @qlist);
113 # Also used by ZOOM::IRSpy::Record
114 sub _parse_target_string {
117 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
118 if (!defined $host) {
120 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
121 $target = "$host:$port/$db";
123 die "$0: invalid target string '$target'"
126 return ($host, $port, $db, $target);
130 # There are two cases.
132 # 1. A specific set of targets is nominated on the command line.
133 # - Records must be fetched for those targets that are in the DB
134 # - New, empty records must be made for those that are not.
135 # - Updated records written to the DB may or may not be new.
137 # 2. All records in the database are to be checked.
138 # - Records must be fetched for all targets in the DB
139 # - Updated records written to the DB may not be new.
141 # That's all -- what could be simpler?
147 if ($this->{allrecords}) {
148 # We need to check on every target in the database, which
149 # means we need to do a "find all". According to the BIB-1
150 # semantics document at
151 # http://www.loc.gov/z3950/agency/bib1.html
153 # @attr 2=103 @attr 1=1035 x
154 # should find all records, but it seems that Zebra doesn't
155 # support this. Furthermore, when using the "alvis" filter
156 # (as we do for IRSpy) it doesn't support the use of any BIB-1
157 # access point -- not even 1035 "everywhere" -- so instead we
158 # hack together a search that we know will find all records.
159 $this->{query} = "port=?*";
161 # Prepopulate the target map with nulls so that after we fill
162 # in what we can from the database query, we know which target
163 # IDs we need new records for.
164 foreach my $target (@{ $this->{targets} }) {
165 $target2record{lc($target)} = undef;
169 $this->log("irspy_debug", "query '", $this->{query}, "'");
170 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
171 delete $this->{query}; # No longer needed at all
172 $this->log("irspy_debug", "found ", $rs->size(), " target records");
173 foreach my $i (1 .. $rs->size()) {
174 my $target = _render_record($rs, $i-1, "id");
175 my $zeerex = _render_record($rs, $i-1, "zeerex");
176 #print STDERR "making '$target' record with '$zeerex'\n";
177 $target2record{lc($target)} =
178 new ZOOM::IRSpy::Record($this, $target, $zeerex);
179 push @{ $this->{targets} }, $target
180 if $this->{allrecords};
183 # Make records for targets not previously in the database
184 foreach my $target (keys %target2record) {
185 my $record = $target2record{$target};
186 if (!defined $record) {
187 $this->log("irspy_debug", "made new record for '$target'");
188 $target2record{$target} = new ZOOM::IRSpy::Record($this, $target);
190 $this->log("irspy_debug", "using existing record for '$target'");
195 foreach my $target (@{ $this->{targets} }) {
196 my $conn = create ZOOM::IRSpy::Connection($this, async => 1);
197 $conn->option(host => $target);
198 my $record = delete $target2record{lc($target)};
199 $conn->record($record);
200 push @connections, $conn;
202 die("remaining target2record = { " .
203 join(", ", map { "$_ ->'" . $target2record{$_}. "'" }
204 sort keys %target2record) . " }")
207 $this->{connections} = \@connections;
208 delete $this->{targets}; # The information is now in {connections}
213 my($rs, $which, $elementSetName) = @_;
215 # There is a slight race condition here on the element-set name,
216 # but it shouldn't be a problem as this is (currently) only called
217 # from parts of the program that run single-threaded.
218 my $old = $rs->option(elementSetName => $elementSetName);
219 my $rec = $rs->record($which);
220 $rs->option(elementSetName => $old);
222 return $rec->render();
226 sub _rewrite_records {
229 # Write modified records back to database
230 foreach my $conn (@{ $this->{connections} }) {
231 my $rec = $conn->record();
232 my $p = $this->{conn}->package();
233 $p->option(action => "specialUpdate");
234 my $xml = $rec->{zeerex}->toString();
235 $p->option(record => $xml);
239 $p = $this->{conn}->package();
246 print "Updated with xml=<br/>\n<pre>$xml</pre>\n";
252 # The approach: gather declarative information about test hierarchy,
253 # then go into a loop. In the loop, we ensure that each connection is
254 # running a test, and within that test a task, until its list of tests
255 # is exhausted. No individual test ever calls wait(): tests just queue
256 # up tasks and return immediately. When the tasks are run (one at a
257 # time on each connection) they generate events, and it is these that
258 # are harvested by ZOOM::event(). Since each connection knows what
259 # task it is running, it can invoke the appropriate callbacks.
260 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
261 # loop how to continue.
264 # While a connection is running a task, its current_task()
265 # points at the task structure. When it finishes its task,
266 # next_task() is pointed at the next task to execute (if there
267 # is one), and its current_task() is set to zero. When the next
268 # task is executed, the connection's next_task() is set to zero
269 # and its current_task() pointed to the task structure.
270 # current_task() and next_task() are both zero only when there
271 # are no more queued tasks, which is when a new test is
274 # Each connection's current test is stored in its
275 # "current_test_address" option. The next test to execute is
276 # calculated by walking the declarative tree of tests. This
277 # option begins empty; the "next test" after this is of course
284 $tname = "Main" if !defined $tname;
285 $this->{tree} = $this->_gather_tests($tname)
286 or die "No tests defined";
287 #$this->{tree}->print(0);
290 my @conn = @{ $this->{connections} };
293 my @copy_conn = @conn; # avoid alias problems after splice()
294 foreach my $i0 (0 .. $#copy_conn) {
295 my $conn = $copy_conn[$i0];
296 #print "connection $i0 of ", scalar(@copy_conn), " from ", scalar(@conn), " is $conn\n";
297 if (!$conn->current_task()) {
298 if (!$conn->next_task()) {
299 # Out of tasks: we need a new test
301 my $address = $conn->option("current_test_address");
302 my $nextaddr = defined $address ?
303 $this->_next_test($address) : "";
304 if (!defined $nextaddr) {
305 $conn->log("irspy", "has no more tests: removing");
306 splice @conn, $i0, 1;
310 my $node = $this->{tree}->select($nextaddr)
311 or die "invalid nextaddr '$nextaddr'";
312 $conn->option(current_test_address => $nextaddr);
313 my $tname = $node->name();
314 $conn->log("irspy", "starting test '$nextaddr' = $tname");
315 my $tasks = $conn->tasks();
316 my $oldcount = @$tasks;
317 "ZOOM::IRSpy::Test::$tname"->start($conn);
318 $tasks = $conn->tasks();
319 if (@$tasks > $oldcount) {
320 # Prepare to start the first of the newly added tasks
321 $conn->next_task($tasks->[$oldcount]);
323 $conn->log("irspy", "no tasks added by new test $tname");
328 my $task = $conn->next_task();
329 die "no next task queued for $conn" if !defined $task;
330 $conn->log("irspy", "starting task $task");
332 $conn->current_task($task);
336 ### Test $conn->is_idle() here?
339 my $i0 = ZOOM::event(\@conn);
340 $this->log("irspy_event", "ZOOM_event(", scalar(@conn), " connections) = $i0");
341 last if $i0 == 0 || $i0 == -3; # no events or no connections
342 my $conn = $conn[$i0-1];
343 my $ev = $conn->last_event();
344 my $evstr = ZOOM::event_str($ev);
345 $conn->log("irspy_event", "event $ev ($evstr)");
347 my $task = $conn->current_task();
348 die "$conn has no current task for event $ev ($evstr)" if !$task;
349 eval { $conn->_check() };
351 ($ev == ZOOM::Event::RECV_DATA ||
352 $ev == ZOOM::Event::RECV_APDU ||
353 $ev == ZOOM::Event::ZEND)) {
354 # An error in, say, a search response, becomes visible to
355 # ZOOM before the Receive Data event is sent and persists
356 # until after the End, which means that successive events
357 # each report the same error. So we just ignore errors on
358 # "unimportant" events. ### But this doesn't work for,
359 # say, a Connection Refused, as the only event that shows
360 # us this error is the End.
361 $conn->log("irspy_event", "ignoring error ",
362 "on event $ev ($evstr): $@");
368 my $sub = $task->{cb}->{exception};
369 die $@ if !defined $sub;
370 $res = &$sub($conn, $task, $@);
372 my $sub = $task->{cb}->{$ev};
374 $conn->log("irspy_unhandled", "event $ev ($evstr)");
378 $res = &$sub($conn, $task, $ev);
381 if ($res == ZOOM::IRSpy::Status::OK) {
382 # Nothing to do -- life continues
384 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
385 my $task = $conn->current_task();
386 die "no task for TASK_DONE on $conn" if !$task;
387 die "next task already defined for $conn" if $conn->next_task();
388 $conn->log("irspy", "completed task $task");
389 $conn->next_task($task->{next});
390 $conn->current_task(0);
392 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
393 $res == ZOOM::IRSpy::Status::TEST_BAD) {
394 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
395 $conn->log("irspy", "test completed ($x)");
396 $conn->current_task(0);
398 ### Should also skip over remaining sibling tests if TEST_BAD
399 $nskipped += 1; # should count number of skipped siblings
403 $this->log("irspy_event", "no more events: finishing");
405 #$this->_rewrite_records();
412 my($tname, @ancestors) = @_;
414 die("$0: test-hierarchy loop detected: " .
415 join(" -> ", @ancestors, $tname))
416 if grep { $_ eq $tname } @ancestors;
419 my $slashSeperatedTname = $tname;
420 $slashSeperatedTname =~ s/::/\//g;
421 require "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
423 $this->log("warn", "can't load test '$tname': skipping",
424 $@ =~ /^Can.t locate/ ? () : " ($@)");
428 $this->log("irspy", "adding test '$tname'");
430 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
431 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
432 push @subnodes, $subtest if defined $subtest;
435 return new ZOOM::IRSpy::Node($tname, @subnodes);
441 my($address, $omit_child) = @_;
443 $this->log("irspy", "checking for next test after '$address'");
447 my $maybe = $address eq "" ? "0" : "$address:0";
448 return $maybe if $this->{tree}->select($maybe);
451 # The top-level node has no successor or parent
452 return undef if $address eq "";
454 # Try next sibling child
455 my @components = split /:/, $address;
456 my $last = pop @components;
457 my $maybe = join(":", @components, $last+1);
458 return $maybe if $this->{tree}->select($maybe);
460 # This node is exhausted: try the parent's successor
461 return $this->_next_test(join(":", @components), 1)
470 ZOOM::IRSpy::Maintenance.
472 The ZOOM-Perl module,
473 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
476 http://indexdata.com/zebra/
480 Mike Taylor, E<lt>mike@indexdata.comE<gt>
482 =head1 COPYRIGHT AND LICENSE
484 Copyright (C) 2006 by Index Data ApS.
486 This library is free software; you can redistribute it and/or modify
487 it under the same terms as Perl itself, either Perl version 5.8.7 or,
488 at your option, any later version of Perl 5 you may have available.