8 use Data::Dumper; # For debugging only
12 use XML::LibXML::XPathContext;
14 use Net::Z3950::ZOOM 1.13; # For the ZOOM version-check only
15 use ZOOM::IRSpy::Node;
16 use ZOOM::IRSpy::Connection;
17 use ZOOM::IRSpy::Stats;
18 use ZOOM::IRSpy::Utils qw(cql_target render_record
19 irspy_xpath_context irspy_make_identifier
20 irspy_record2identifier calc_reliability_stats
24 our $VERSION = '1.02';
25 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
27 our $xslt_max_depth = 250;
30 # Enumeration for callback functions to return
31 package ZOOM::IRSpy::Status;
32 sub OK { 29 } # No problems, task is still progressing
33 sub TASK_DONE { 18 } # Task is complete, next task should begin
34 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
35 sub TEST_BAD { 31 } # Whole test is complete, and failed
36 sub TEST_SKIPPED { 12 } # Test couldn't be run
42 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
47 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
48 $spy->targets(@targets);
49 $spy->initialise("Main");
54 This module exists to implement the IRspy program, which discovers,
55 analyses and monitors IR servers implementing the Z39.50 and SRU/W
56 protocols. It is a successor to the ZSpy program.
61 ZOOM::Log::mask_str("irspy");
62 ZOOM::Log::mask_str("irspy_debug");
63 ZOOM::Log::mask_str("irspy_event");
64 ZOOM::Log::mask_str("irspy_unhandled");
65 ZOOM::Log::mask_str("irspy_test");
66 ZOOM::Log::mask_str("irspy_task");
71 my($dbname, $user, $password, $activeSetSize) = @_;
75 push @options, (user => $user, password => $password)
78 my $conn = new ZOOM::Connection($dbname, 0, @options)
79 or die "$0: can't connection to IRSpy database 'dbname'";
81 my $xslt = new XML::LibXSLT;
83 # raise the maximum number of nested template calls and variables/params (default 250)
84 warn "raise the maximum number of nested template calls: $xslt_max_depth\n" if $debug;
85 $xslt->max_depth($xslt_max_depth);
87 $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
88 \&ZOOM::IRSpy::Utils::xslt_strcmp);
90 my $libxml = new XML::LibXML;
91 warn "use irspy_to_zeerex_xsl xslt sheet: $irspy_to_zeerex_xsl\n" if $debug;
92 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
93 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
97 query => "cql.allRecords=1", # unless overridden
98 modn => undef, # Filled in by restrict_modulo()
99 modi => undef, # Filled in by restrict_modulo()
100 targets => undef, # Filled in later if targets() is
101 # called; used only to keep state from
102 # targets() until initialise() is
104 connections => undef, # Filled in by initialise()
105 queue => undef, # Filled in by initialise()
107 irspy_to_zeerex_style => $irspy_to_zeerex_style,
108 test => undef, # Filled in by initialise()
109 timeout => undef, # Filled in by initialise()
110 tests => undef, # Tree of tests to be executed
111 activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
113 $this->log("irspy", "starting up with database '$dbname'");
118 # wrapper to read the IRSpy database name from environment variable / apache config
119 sub connect_to_registry {
122 # XXX: we could also handle her: user, password, elementSetName
124 my $database = $ENV{IRSpyDbName} || "localhost:8018/IR-Explain---1";
139 $this->{query} = $query;
143 # Explicitly nominate a set of targets to check, overriding the
144 # default which is to re-check everything in the database. Each
145 # target already in the database results in the existing record being
146 # updated; each new target causes a new record to be added.
152 $this->log("irspy", "setting explicit list of targets ",
153 join(", ", map { "'$_'" } @targets));
155 foreach my $target (@targets) {
156 my($protocol, $host, $port, $db, $newtarget) =
157 _parse_target_string($target);
158 if ($newtarget ne $target) {
159 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
160 $target = $newtarget; # This is written through the ref
162 push @qlist, cql_target($protocol, $host, $port, $db);
165 $this->{targets} = \@targets;
166 $this->{query} = join(" or ", @qlist);
170 # Also used by ZOOM::IRSpy::Record
171 sub _parse_target_string {
174 my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
175 if (!defined $host) {
177 ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
178 $target = irspy_make_identifier($protocol, $host, $port, $db);
180 die "$0: invalid target string '$target'"
183 return ($protocol, $host, $port, $db, $target);
187 sub restrict_modulo {
196 # Records must be fetched for all records satisfying $this->{query} If
197 # $this->{targets} is already set (i.e. a specific list of targets to
198 # check was specified by a call to targets()), then new, empty records
199 # will be made for any targets that are not already in the database.
205 $tname = "Main" if !defined $tname;
206 $this->{test} = $tname;
207 $this->{tree} = $this->_gather_tests($tname)
208 or die "No tests defined for '$tname'";
209 $this->{tree}->resolve();
210 #$this->{tree}->print(0);
212 $this->{timeout} = "ZOOM::IRSpy::Test::$tname"->timeout();
215 my $targets = $this->{targets};
216 if (defined $targets) {
217 @targets = @$targets;
218 delete $this->{targets};
220 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
221 $this->log("irspy", "'", $this->{query}, "' found ",
222 $rs->size(), " target records");
223 delete $this->{query};
225 foreach my $i (1 .. $rs->size()) {
226 push @targets, render_record($rs, $i-1, "id");
230 my $n = $this->{activeSetSize};
231 $n = @targets if $n == 0 || $n > @targets;
233 $this->{queue} = \@targets;
234 $this->{connections} = [];
235 while (@{ $this->{connections} } < $n) {
236 my $conn = $this->_next_connection();
237 last if !defined $conn;
238 push @{ $this->{connections} }, $conn;
243 sub _next_connection {
247 my $n = $this->{modn};
248 my $i = $this->{modi};
250 $target = shift @{ $this->{queue} };
251 return undef if !defined $target;
254 $target = shift @{ $this->{queue} };
255 return undef if !defined $target;
256 my $h = _hash($target);
258 last if $hmodn == $i;
259 #$this->log("irspy", "'$target' hash $h % $n = $hmodn != $i");
263 die "oops -- target is undefined" if !defined $target;
264 return create ZOOM::IRSpy::Connection($this, $target, async => 1,
265 timeout => $this->{timeout});
273 foreach my $s (split //, $target) {
281 sub _irspy_to_zeerex {
285 my $save_xml = $ENV{IRSPY_SAVE_XML};
286 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
289 unlink('/tmp/irspy_orig.xml');
290 open FH, '>/tmp/irspy_orig.xml'
291 or die "can't write irspy_orig.xml: $!";
292 print FH $irspy_doc->toString();
296 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
298 unlink('/tmp/irspy_transformed.xml');
299 open FH, '>/tmp/irspy_transformed.xml'
300 or die "can't write irspy_transformed.xml: $!";
301 print FH $result->toString();
305 return $result->documentElement();
309 sub _rewrite_irspy_record {
313 $conn->log("irspy", "rewriting XML record");
314 my $rec = $this->_irspy_to_zeerex($conn);
316 # Since IRSpy can run for a long time between writes back to the
317 # database, it's quite possible for the server to have closed the
318 # connection as idle. So re-establish it if necessary.
319 $this->{conn}->connect($conn->option("host"));
321 _rewrite_zeerex_record($this->{conn}, $rec);
322 $conn->log("irspy", "rewrote XML record");
326 my $_reliabilityField = {
327 reliability => [ reliability => 0,
328 "Calculated reliability of server",
329 "e:serverInfo/e:reliability" ],
332 sub _rewrite_zeerex_record {
333 my($conn, $rec, $oldid) = @_;
335 # Add reliability score
336 my $xc = irspy_xpath_context($rec);
337 my($nok, $nall, $percent) = calc_reliability_stats($xc);
338 modify_xml_document($xc, $_reliabilityField, { reliability => $percent });
340 my $p = $conn->package();
341 $p->option(action => "specialUpdate");
342 my $xml = $rec->toString();
343 $p->option(record => $xml);
347 # This is the expression in the ID-making stylesheet
348 # ../../zebra/zeerex2id.xsl
349 my $id = irspy_record2identifier($xc);
350 if (defined $oldid && $id ne $oldid) {
351 warn "IDs differ (old='$oldid' new='$id')";
352 _delete_record($conn, $oldid);
355 $p = $conn->package();
362 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
370 # We can't delete records using recordIdOpaque, since character
371 # sets are handled differently here in extended services from how
372 # they are used in the Alvis filter's record-parsing, and so
373 # non-ASCII characters come out differently in the two contexts.
374 # Instead, we must send a record whose contents indicate the ID of
375 # that which we wish to delete. There are two ways, both
376 # unsatisfactory: we could either fetch the actual record them
377 # resubmit it in the deletion request (which wastes a search and a
378 # fetch) or we could build a record by hand from the parsed-out
379 # components (which is error-prone and which I am not 100% certain
380 # will work since the other contents of the record will be
381 # different). The former evil seems to be the lesser.
383 warn "$conn deleting record '$id'";
385 my $rs = $conn->search(new ZOOM::Query::CQL(cql_target($id)));
386 die "no such ID '$id'" if $rs->size() == 0;
387 my $rec = $rs->record(0);
388 my $xml = $rec->render();
390 my $p = $conn->package();
391 $p->option(action => "recordDelete");
392 $p->option(record => $xml);
396 $p = $conn->package();
402 # The approach: gather declarative information about test hierarchy,
403 # then go into a loop. In the loop, we ensure that each connection is
404 # running a test, and within that test a task, until its list of tests
405 # is exhausted. No individual test ever calls wait(): tests just queue
406 # up tasks and return immediately. When the tasks are run (one at a
407 # time on each connection) they generate events, and it is these that
408 # are harvested by ZOOM::event(). Since each connection knows what
409 # task it is running, it can invoke the appropriate callbacks.
410 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
411 # loop how to continue.
414 # While a connection is running a task, its current_task()
415 # points at the task structure. When it finishes its task,
416 # next_task() is pointed at the next task to execute (if there
417 # is one), and its current_task() is set to zero. When the next
418 # task is executed, the connection's next_task() is set to zero
419 # and its current_task() pointed to the task structure.
420 # current_task() and next_task() are both zero only when there
421 # are no more queued tasks, which is when a new test is
424 # Each connection's current test is stored in its
425 # "current_test_address" option. The next test to execute is
426 # calculated by walking the declarative tree of tests. This
427 # option begins empty; the "next test" after this is of course
433 my $topname = $this->{tree}->name();
434 my $timeout = $this->{timeout};
435 $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
438 my @conn = @{ $this->{connections} };
441 ROUND_AND_ROUND_WE_GO:
443 my @copy_conn = @conn; # avoid alias problems after splice()
444 my $nconn = scalar(@copy_conn);
445 foreach my $i0 (0 .. $#copy_conn) {
446 my $conn = $copy_conn[$i0];
447 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
448 next if !defined $conn;
449 if (!$conn->current_task()) {
450 if (!$conn->next_task()) {
451 # Out of tasks: we need a new test
453 my $address = $conn->option("current_test_address");
455 if (!defined $address) {
458 $conn->log("irspy_test",
459 "checking for next test after '$address'");
460 $nextaddr = $this->_next_test($address);
462 if (!defined $nextaddr) {
463 $conn->log("irspy", "has no more tests: removing");
464 $this->_rewrite_irspy_record($conn);
465 $conn->option(rewrote_record => 1);
466 my $newconn = $this->_next_connection();
467 if (!defined $newconn) {
468 # Do not destroy: needed for later sanity checks
469 splice @conn, $i0, 1;
472 $conn[$i0] = $newconn;
473 $conn[$i0]->option(current_test_address => "");
474 $conn[$i0]->log("irspy", "entering active pool - ",
475 scalar(@{ $this->{queue} }),
476 " targets remain in queue");
481 my $node = $this->{tree}->select($nextaddr)
482 or die "invalid nextaddr '$nextaddr'";
483 $conn->option(current_test_address => $nextaddr);
484 my $tname = $node->name();
485 $conn->log("irspy_test",
486 "starting test '$nextaddr' = $tname");
487 my $tasks = $conn->tasks();
488 my $oldcount = @$tasks;
489 "ZOOM::IRSpy::Test::$tname"->start($conn);
490 $tasks = $conn->tasks();
491 if (@$tasks > $oldcount) {
492 # Prepare to start the first of the newly added tasks
493 $conn->next_task($tasks->[$oldcount]);
495 $conn->log("irspy_task",
496 "no tasks added by new test $tname");
501 my $task = $conn->next_task();
502 die "no next task queued for $conn" if !defined $task;
503 $conn->log("irspy_task", "preparing task $task");
505 $conn->current_task($task);
511 my $i0 = ZOOM::event(\@conn);
512 $this->log("irspy_event",
513 "ZOOM_event(", scalar(@conn), " connections) = $i0");
516 0 => "no events remain",
517 -1 => "ZOOM::event() argument not a reference",
518 -2 => "ZOOM::event() reference not an array",
519 -3 => "no connections remain",
520 -4 => "too many connections for ZOOM::event()",
522 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
523 $this->log("irspy", $message);
527 my $conn = $conn[$i0-1];
528 my $ev = $conn->last_event();
529 my $evstr = ZOOM::event_str($ev);
530 $conn->log("irspy_event", "event $ev ($evstr)");
531 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
533 my $task = $conn->current_task();
534 die "$conn has no current task for event $ev ($evstr)" if !$task;
537 eval { $conn->check() };
538 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
539 my $sub = $task->{cb}->{exception};
540 die $@ if !defined $sub;
541 $res = &$sub($conn, $task, $task->udata(), $@);
543 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
545 my $sub = $task->{cb}->{$ev};
547 $conn->log("irspy_unhandled", "event $ev ($evstr)");
551 $res = &$sub($conn, $task, $task->udata(), $ev);
554 if ($res == ZOOM::IRSpy::Status::OK) {
555 # Nothing to do -- life continues
557 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
558 my $task = $conn->current_task();
559 die "no task for TASK_DONE on $conn" if !$task;
560 die "next task already defined for $conn" if $conn->next_task();
561 $conn->log("irspy_task", "completed task $task");
562 $conn->next_task($task->{next});
563 $conn->current_task(0);
565 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
566 $res == ZOOM::IRSpy::Status::TEST_BAD) {
567 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
568 $conn->log("irspy_task", "test ended during task $task ($x)");
569 $conn->log("irspy_test", "test completed ($x)");
570 $conn->current_task(0);
572 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
573 my $address = $conn->option('current_test_address');
574 $conn->log("irspy", "top-level test failed!")
576 my $node = $this->{tree}->select($address);
578 while (defined $node->next() &&
579 length($node->next()->address()) >= length($address)) {
580 $conn->log("irspy_debug", "skipping from '",
581 $node->address(), "' to '",
582 $node->next()->address(), "'");
583 $node = $node->next();
587 $conn->option(current_test_address => $node->address());
588 $conn->log("irspy_test", "skipped $skipcount tests");
589 $nskipped += $skipcount;
592 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
593 $conn->log("irspy_test", "test skipped during task $task");
594 $conn->current_task(0);
599 die "unknown callback return-value '$res'";
603 $this->log("irspy", "exiting main loop");
605 # Sanity checks: none of the following should ever happen
607 $this->log("irspy", "performing end-of-run sanity-checks");
608 foreach my $conn (@conn) {
609 my $test = $conn->option("current_test_address");
610 my $next = $this->_next_test($test);
613 "$conn (in test '$test') has queued test '$next'");
616 if (my $task = $conn->current_task()) {
617 $this->log("irspy", "$conn still has an active task $task");
620 if (my $task = $conn->next_task()) {
621 $this->log("irspy", "$conn still has a queued task $task");
624 if (!$conn->is_idle()) {
626 "$conn still has ZOOM-C level tasks queued: see below");
629 my $ev = $conn->peek_event();
630 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
631 my $evstr = ZOOM::event_str($ev);
632 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
635 if (!$conn->option("rewrote_record")) {
636 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
641 # This really shouldn't be necessary, and in practice it rarely
642 # helps, but it's belt and braces. (For now, we don't do this
643 # hence the zero in the $nruns check).
646 $this->log("irspy", "back into main loop, ${nruns}th time");
647 goto ROUND_AND_ROUND_WE_GO;
649 $this->log("irspy", "bailing after $nruns main-loop runs");
653 # This shouldn't happen emit anything either:
654 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
655 my $conn = $conn[$i1-1];
656 my $ev = $conn->last_event();
657 my $evstr = ZOOM::event_str($ev);
659 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
660 if $ev != ZOOM::Event::ZEND;
667 # Exactly equivalent to ZOOM::event() except that it is tolerant to
668 # undefined values in the array being passed in.
670 sub __UNUSED_tolerant_ZOOM_event {
674 foreach my $i (0 .. @$connref-1) {
675 my $conn = $connref->[$i];
682 my $res = ZOOM::event(\@conn);
683 return $res if $res <= 0;
684 my $res2 = $map[$res-1] + 1;
685 print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
692 my($tname, @ancestors) = @_;
694 die("$0: test-hierarchy loop detected: " .
695 join(" -> ", @ancestors, $tname))
696 if grep { $_ eq $tname } @ancestors;
698 my $slashSeperatedTname = $tname;
699 $slashSeperatedTname =~ s/::/\//g;
700 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
705 $this->log("irspy", "couldn't require '$fullName': $@");
706 $this->log("warn", "can't load test '$tname': skipping",
707 $@ =~ /^Can.t locate/ ? () : " ($@)");
711 $this->log("irspy", "adding test '$tname'");
713 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
714 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
715 push @subnodes, $subtest if defined $subtest;
718 return new ZOOM::IRSpy::Node($tname, @subnodes);
722 # These next three should arguably be Node methods
725 my($address, $omit_child) = @_;
729 my $maybe = $address eq "" ? "0" : "$address:0";
730 return $maybe if $this->{tree}->select($maybe);
733 # The top-level node has no successor or parent
734 return undef if $address eq "";
736 # Try next sibling child
737 my @components = split /:/, $address;
738 my $last = pop @components;
739 my $maybe = join(":", @components, $last+1);
740 return $maybe if $this->{tree}->select($maybe);
742 # This node is exhausted: try the parent's successor
743 return $this->_next_test(join(":", @components), 1)
747 sub _last_sibling_test {
752 if !defined $this->_next_sibling_test($address);
756 my $maybe = $this->_next_sibling_test($address);
757 last if !defined $maybe;
760 $this->log("irspy", "skipping $nskipped tests to '$address'");
763 return ($address, $nskipped);
767 sub _next_sibling_test {
771 my @components = split /:/, $address;
772 my $last = pop @components;
773 my $maybe = join(":", @components, $last+1);
774 return $maybe if $this->{tree}->select($maybe);
784 ZOOM::IRSpy::Maintenance.
786 The ZOOM-Perl module,
787 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
790 http://indexdata.com/zebra/
794 Mike Taylor, E<lt>mike@indexdata.comE<gt>
796 =head1 COPYRIGHT AND LICENSE
798 Copyright (C) 2006 by Index Data ApS.
800 This library is free software; you can redistribute it and/or modify
801 it under the same terms as Perl itself, either Perl version 5.8.7 or,
802 at your option, any later version of Perl 5 you may have available.