1 # $Id: IRSpy.pm,v 1.53 2006-12-11 13:58:17 sondberg Exp $
9 use Data::Dumper; # For debugging only
13 use XML::LibXML::XPathContext;
15 use Net::Z3950::ZOOM 1.13; # For the ZOOM version-check only
16 use ZOOM::IRSpy::Node;
17 use ZOOM::IRSpy::Connection;
18 use ZOOM::IRSpy::Record;
19 use ZOOM::IRSpy::Utils qw(cql_target);
22 our $VERSION = '0.02';
23 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
26 # Enumeration for callback functions to return
27 package ZOOM::IRSpy::Status;
28 sub OK { 29 } # No problems, task is still progressing
29 sub TASK_DONE { 18 } # Task is complete, next task should begin
30 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
31 sub TEST_BAD { 31 } # Whole test is complete, and failed
32 sub TEST_SKIPPED { 12 } # Test couldn't be run
38 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
43 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
44 print $spy->report_status();
48 This module exists to implement the IRspy program, which discovers,
49 analyses and monitors IR servers implementing the Z39.50 and SRU/W
50 protocols. It is a successor to the ZSpy program.
55 ZOOM::Log::mask_str("irspy");
56 ZOOM::Log::mask_str("irspy_debug");
57 ZOOM::Log::mask_str("irspy_event");
58 ZOOM::Log::mask_str("irspy_unhandled");
59 ZOOM::Log::mask_str("irspy_test");
60 ZOOM::Log::mask_str("irspy_task");
65 my($dbname, $user, $password) = @_;
68 push @options, (user => $user, password => $password)
71 my $conn = new ZOOM::Connection($dbname, 0, @options)
72 or die "$0: can't connection to IRSpy database 'dbname'";
74 my $xslt = new XML::LibXSLT;
76 $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
77 \&ZOOM::IRSpy::Utils::xslt_strcmp);
79 my $libxml = new XML::LibXML;
80 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
81 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
85 allrecords => 1, # unless overridden by targets()
86 query => undef, # filled in later
87 targets => undef, # filled in later
88 connections => undef, # filled in later
90 irspy_to_zeerex_style => $irspy_to_zeerex_style,
91 tests => [], # stack of tests currently being executed
93 $this->log("irspy", "starting up with database '$dbname'");
105 # Explicitly nominate a set of targets to check, overriding the
106 # default which is to re-check everything in the database. Each
107 # target already in the database results in the existing record being
108 # updated; each new target causes a new record to be added.
114 $this->log("irspy", "setting explicit list of targets ",
115 join(", ", map { "'$_'" } @targets));
116 $this->{allrecords} = 0;
118 foreach my $target (@targets) {
119 my($host, $port, $db, $newtarget) = _parse_target_string($target);
120 if ($newtarget ne $target) {
121 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
122 $target = $newtarget; # This is written through the ref
124 push @qlist, cql_target($host, $port, $db);
127 $this->{targets} = \@targets;
128 $this->{query} = join(" or ", @qlist);
132 # Also used by ZOOM::IRSpy::Record
133 sub _parse_target_string {
136 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
137 if (!defined $host) {
139 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
140 $target = "$host:$port/$db";
142 die "$0: invalid target string '$target'"
145 return ($host, $port, $db, $target);
149 # There are two cases.
151 # 1. A specific set of targets is nominated on the command line.
152 # - Records must be fetched for those targets that are in the DB
153 # - New, empty records must be made for those that are not.
154 # - Updated records written to the DB may or may not be new.
156 # 2. All records in the database are to be checked.
157 # - Records must be fetched for all targets in the DB
158 # - Updated records written to the DB may not be new.
160 # That's all -- what could be simpler?
166 if ($this->{allrecords}) {
167 # We need to check on every target in the database, which
168 # means we need to do a "find all". According to the BIB-1
169 # semantics document at
170 # http://www.loc.gov/z3950/agency/bib1.html
172 # @attr 2=103 @attr 1=1035 x
173 # should find all records, but it seems that Zebra doesn't
174 # support this. Furthermore, when using the "alvis" filter
175 # (as we do for IRSpy) it doesn't support the use of any BIB-1
176 # access point -- not even 1035 "everywhere" -- so instead we
177 # hack together a search that we know will find all records.
178 $this->{query} = "port=?*";
180 # Prepopulate the target map with nulls so that after we fill
181 # in what we can from the database query, we know which target
182 # IDs we need new records for.
183 foreach my $target (@{ $this->{targets} }) {
184 $target2record{lc($target)} = undef;
188 $this->log("irspy_debug", "query '", $this->{query}, "'");
189 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
190 delete $this->{query}; # No longer needed at all
191 $this->log("irspy_debug", "found ", $rs->size(), " target records");
192 foreach my $i (1 .. $rs->size()) {
193 my $target = _render_record($rs, $i-1, "id");
194 my $zeerex = _render_record($rs, $i-1, "zeerex");
195 #print STDERR "making '$target' record with '$zeerex'\n";
196 $target2record{lc($target)} =
197 new ZOOM::IRSpy::Record($this, $target, $zeerex);
198 push @{ $this->{targets} }, $target
199 if $this->{allrecords};
202 # Make records for targets not previously in the database
203 foreach my $target (keys %target2record) {
204 my $record = $target2record{$target};
205 if (!defined $record) {
206 $this->log("irspy_debug", "made new record for '$target'");
207 $target2record{$target} = new ZOOM::IRSpy::Record($this, $target);
209 $this->log("irspy_debug", "using existing record for '$target'");
214 foreach my $target (@{ $this->{targets} }) {
215 my $conn = create ZOOM::IRSpy::Connection($this, async => 1);
216 $conn->option(host => $target);
217 my $record = delete $target2record{lc($target)};
218 $conn->record($record);
219 push @connections, $conn;
221 die("remaining target2record = { " .
222 join(", ", map { "$_ ->'" . $target2record{$_}. "'" }
223 sort keys %target2record) . " }")
226 $this->{connections} = \@connections;
227 delete $this->{targets}; # The information is now in {connections}
232 my($rs, $which, $elementSetName) = @_;
234 # There is a slight race condition here on the element-set name,
235 # but it shouldn't be a problem as this is (currently) only called
236 # from parts of the program that run single-threaded.
237 my $old = $rs->option(elementSetName => $elementSetName);
238 my $rec = $rs->record($which);
239 $rs->option(elementSetName => $old);
241 return $rec->render();
245 sub _irspy_to_zeerex {
246 my ($this, $conn) = @_;
247 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
248 #open FH, '>/tmp/irspy_orig.xml';
249 #print FH $irspy_doc->toString();
252 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
254 #open FH, '>/tmp/irspy_transformed.xml';
255 #print FH $result->toString();
258 return $result->documentElement();
262 sub _rewrite_record {
266 $conn->log("irspy", "rewriting XML record");
267 my $rec = $this->_irspy_to_zeerex($conn);
268 _really_rewrite_record($this->{conn}, $rec);
272 sub _really_rewrite_record {
273 my($conn, $rec) = @_;
275 my $p = $conn->package();
276 $p->option(action => "specialUpdate");
277 my $xml = $rec->toString();
278 $p->option(record => $xml);
282 $p = $conn->package();
289 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
294 # The approach: gather declarative information about test hierarchy,
295 # then go into a loop. In the loop, we ensure that each connection is
296 # running a test, and within that test a task, until its list of tests
297 # is exhausted. No individual test ever calls wait(): tests just queue
298 # up tasks and return immediately. When the tasks are run (one at a
299 # time on each connection) they generate events, and it is these that
300 # are harvested by ZOOM::event(). Since each connection knows what
301 # task it is running, it can invoke the appropriate callbacks.
302 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
303 # loop how to continue.
306 # While a connection is running a task, its current_task()
307 # points at the task structure. When it finishes its task,
308 # next_task() is pointed at the next task to execute (if there
309 # is one), and its current_task() is set to zero. When the next
310 # task is executed, the connection's next_task() is set to zero
311 # and its current_task() pointed to the task structure.
312 # current_task() and next_task() are both zero only when there
313 # are no more queued tasks, which is when a new test is
316 # Each connection's current test is stored in its
317 # "current_test_address" option. The next test to execute is
318 # calculated by walking the declarative tree of tests. This
319 # option begins empty; the "next test" after this is of course
326 $tname = "Main" if !defined $tname;
327 $this->{tree} = $this->_gather_tests($tname)
328 or die "No tests defined for '$tname'";
329 #$this->{tree}->print(0);
332 my @conn = @{ $this->{connections} };
335 my @copy_conn = @conn; # avoid alias problems after splice()
336 my $nconn = scalar(@copy_conn);
337 foreach my $i0 (0 .. $#copy_conn) {
338 my $conn = $copy_conn[$i0];
339 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
340 if (!$conn->current_task()) {
341 if (!$conn->next_task()) {
342 # Out of tasks: we need a new test
344 my $address = $conn->option("current_test_address");
346 if (!defined $address) {
349 $this->log("irspy_test",
350 "checking for next test after '$address'");
351 $nextaddr = $this->_next_test($address);
353 if (!defined $nextaddr) {
354 $conn->log("irspy", "has no more tests: removing");
355 splice @conn, $i0, 1;
356 $this->_rewrite_record($conn);
357 $conn->option(rewrote_record => 1);
361 my $node = $this->{tree}->select($nextaddr)
362 or die "invalid nextaddr '$nextaddr'";
363 $conn->option(current_test_address => $nextaddr);
364 my $tname = $node->name();
365 $conn->log("irspy_test",
366 "starting test '$nextaddr' = $tname");
367 my $tasks = $conn->tasks();
368 my $oldcount = @$tasks;
369 "ZOOM::IRSpy::Test::$tname"->start($conn);
370 $tasks = $conn->tasks();
371 if (@$tasks > $oldcount) {
372 # Prepare to start the first of the newly added tasks
373 $conn->next_task($tasks->[$oldcount]);
375 $conn->log("irspy_task",
376 "no tasks added by new test $tname");
381 my $task = $conn->next_task();
382 die "no next task queued for $conn" if !defined $task;
383 $conn->log("irspy_task", "preparing task $task");
385 $conn->current_task($task);
389 # Do we need to test $conn->is_idle()? I don't think so!
392 my $i0 = ZOOM::event(\@conn);
393 $this->log("irspy_event",
394 "ZOOM_event(", scalar(@conn), " connections) = $i0");
395 last if $i0 == 0 || $i0 == -3; # no events or no connections
396 my $conn = $conn[$i0-1];
397 my $ev = $conn->last_event();
398 my $evstr = ZOOM::event_str($ev);
399 $conn->log("irspy_event", "event $ev ($evstr)");
401 my $task = $conn->current_task();
402 die "$conn has no current task for event $ev ($evstr)" if !$task;
403 eval { $conn->_check() };
405 ($ev == ZOOM::Event::RECV_DATA ||
406 $ev == ZOOM::Event::RECV_APDU ||
407 $ev == ZOOM::Event::ZEND)) {
408 # An error in, say, a search response, becomes visible to
409 # ZOOM before the Receive Data event is sent and persists
410 # until after the End, which means that successive events
411 # each report the same error. So we just ignore errors on
412 # "unimportant" events. ### But this doesn't work for,
413 # say, a Connection Refused, as the only event that shows
414 # us this error is the End.
415 $conn->log("irspy_event", "ignoring error ",
416 "on event $ev ($evstr): $@");
422 my $sub = $task->{cb}->{exception};
423 die $@ if !defined $sub;
424 $res = &$sub($conn, $task, $task->udata(), $@);
426 my $sub = $task->{cb}->{$ev};
428 $conn->log("irspy_unhandled", "event $ev ($evstr)");
432 $res = &$sub($conn, $task, $task->udata(), $ev);
435 if ($res == ZOOM::IRSpy::Status::OK) {
436 # Nothing to do -- life continues
438 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
439 my $task = $conn->current_task();
440 die "no task for TASK_DONE on $conn" if !$task;
441 die "next task already defined for $conn" if $conn->next_task();
442 $conn->log("irspy_task", "completed task $task");
443 $conn->next_task($task->{next});
444 $conn->current_task(0);
446 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
447 $res == ZOOM::IRSpy::Status::TEST_BAD) {
448 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
449 $conn->log("irspy_task", "test ended during task $task ($x)");
450 $conn->log("irspy_test", "test completed ($x)");
451 $conn->current_task(0);
453 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
454 my $address = $conn->option('current_test_address');
455 ($address, my $n) = $this->_last_sibling_test($address);
456 if (defined $address) {
457 $conn->log("irspy_test", "skipped $n tests");
458 $conn->option(current_test_address => $address);
463 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
464 $conn->log("irspy_task", "test skipped during task $task");
465 $conn->current_task(0);
467 # I think that's all we need to do
470 die "unknown callback return-value '$res'";
474 $this->log("irspy", "exiting main loop");
475 # Sanity checks: none of the following should ever happen
476 foreach my $conn (@{ $this->{connections} }) {
477 my $test = $conn->option("current_test_address");
478 my $next = $this->_next_test($test);
480 warn "$conn (in test '$test') has queued test '$next'";
482 if (my $task = $conn->current_task()) {
483 warn "$conn still has an active task $task";
485 if (my $task = $conn->next_task()) {
486 warn "$conn still has a queued task $task";
488 if (!$conn->is_idle()) {
489 warn "$conn still has ZOOM-C level tasks queued: see below";
491 if (!$conn->option("rewrote_record")) {
492 warn "$conn did not rewrite its ZeeRex record";
496 # This shouldn't happen emit anything either:
497 @conn = @{ $this->{connections} };
498 while (my $i1 = ZOOM::event(\@conn)) {
499 my $conn = $conn[$i1-1];
500 my $ev = $conn->last_event();
501 my $evstr = ZOOM::event_str($ev);
502 warn "$conn still has ZOOM-C level task queued: $ev ($evstr)"
503 if $ev != ZOOM::Event::ZEND;
512 my($tname, @ancestors) = @_;
514 die("$0: test-hierarchy loop detected: " .
515 join(" -> ", @ancestors, $tname))
516 if grep { $_ eq $tname } @ancestors;
518 my $slashSeperatedTname = $tname;
519 $slashSeperatedTname =~ s/::/\//g;
520 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
524 $this->log("irspy", "successfully required '$fullName'");
526 $this->log("irspy", "couldn't require '$fullName': $@");
527 $this->log("warn", "can't load test '$tname': skipping",
528 $@ =~ /^Can.t locate/ ? () : " ($@)");
532 $this->log("irspy", "adding test '$tname'");
534 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
535 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
536 push @subnodes, $subtest if defined $subtest;
539 return new ZOOM::IRSpy::Node($tname, @subnodes);
543 # These next three should arguably be Node methods
546 my($address, $omit_child) = @_;
550 my $maybe = $address eq "" ? "0" : "$address:0";
551 return $maybe if $this->{tree}->select($maybe);
554 # The top-level node has no successor or parent
555 return undef if $address eq "";
557 # Try next sibling child
558 my @components = split /:/, $address;
559 my $last = pop @components;
560 my $maybe = join(":", @components, $last+1);
561 return $maybe if $this->{tree}->select($maybe);
563 # This node is exhausted: try the parent's successor
564 return $this->_next_test(join(":", @components), 1)
568 sub _last_sibling_test {
573 if !defined $this->_next_sibling_test($address);
577 my $maybe = $this->_next_sibling_test($address);
578 last if !defined $maybe;
581 $this->log("irspy", "skipping $nskipped tests to '$address'");
584 return ($address, $nskipped);
588 sub _next_sibling_test {
592 my @components = split /:/, $address;
593 my $last = pop @components;
594 my $maybe = join(":", @components, $last+1);
595 return $maybe if $this->{tree}->select($maybe);
605 ZOOM::IRSpy::Maintenance.
607 The ZOOM-Perl module,
608 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
611 http://indexdata.com/zebra/
615 Mike Taylor, E<lt>mike@indexdata.comE<gt>
617 =head1 COPYRIGHT AND LICENSE
619 Copyright (C) 2006 by Index Data ApS.
621 This library is free software; you can redistribute it and/or modify
622 it under the same terms as Perl itself, either Perl version 5.8.7 or,
623 at your option, any later version of Perl 5 you may have available.