1 # $Id: IRSpy.pm,v 1.90 2008-07-16 11:42:13 mike 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::Stats;
19 use ZOOM::IRSpy::Utils qw(cql_target render_record
20 irspy_xpath_context irspy_make_identifier
21 irspy_record2identifier calc_reliability_stats
25 our $VERSION = '1.02';
26 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
28 our $xslt_max_depth = 250;
31 # Enumeration for callback functions to return
32 package ZOOM::IRSpy::Status;
33 sub OK { 29 } # No problems, task is still progressing
34 sub TASK_DONE { 18 } # Task is complete, next task should begin
35 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
36 sub TEST_BAD { 31 } # Whole test is complete, and failed
37 sub TEST_SKIPPED { 12 } # Test couldn't be run
43 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
48 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
49 $spy->targets(@targets);
50 $spy->initialise("Main");
55 This module exists to implement the IRspy program, which discovers,
56 analyses and monitors IR servers implementing the Z39.50 and SRU/W
57 protocols. It is a successor to the ZSpy program.
62 ZOOM::Log::mask_str("irspy");
63 ZOOM::Log::mask_str("irspy_debug");
64 ZOOM::Log::mask_str("irspy_event");
65 ZOOM::Log::mask_str("irspy_unhandled");
66 ZOOM::Log::mask_str("irspy_test");
67 ZOOM::Log::mask_str("irspy_task");
72 my($dbname, $user, $password, $activeSetSize) = @_;
76 push @options, (user => $user, password => $password)
79 my $conn = new ZOOM::Connection($dbname, 0, @options)
80 or die "$0: can't connection to IRSpy database 'dbname'";
82 my $xslt = new XML::LibXSLT;
84 # raise the maximum number of nested template calls and variables/params (default 250)
85 warn "raise the maximum number of nested template calls: $xslt_max_depth\n" if $debug;
86 $xslt->max_depth($xslt_max_depth);
88 $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
89 \&ZOOM::IRSpy::Utils::xslt_strcmp);
91 my $libxml = new XML::LibXML;
92 warn "use irspy_to_zeerex_xsl xslt sheet: $irspy_to_zeerex_xsl\n" if $debug;
93 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
94 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
98 query => "cql.allRecords=1", # unless overridden
99 modn => undef, # Filled in by restrict_modulo()
100 modi => undef, # Filled in by restrict_modulo()
101 targets => undef, # Filled in later if targets() is
102 # called; used only to keep state from
103 # targets() until initialise() is
105 connections => undef, # Filled in by initialise()
106 queue => undef, # Filled in by initialise()
108 irspy_to_zeerex_style => $irspy_to_zeerex_style,
109 test => undef, # Filled in by initialise()
110 timeout => undef, # Filled in by initialise()
111 tests => undef, # Tree of tests to be executed
112 activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
114 $this->log("irspy", "starting up with database '$dbname'");
119 # wrapper to read the IRSpy database name from environment variable / apache config
120 sub connect_to_registry {
123 # XXX: we could also handle her: user, password, elementSetName
125 my $database = $ENV{IRSpyDbName} || "localhost:8018/IR-Explain---1";
140 $this->{query} = $query;
144 # Explicitly nominate a set of targets to check, overriding the
145 # default which is to re-check everything in the database. Each
146 # target already in the database results in the existing record being
147 # updated; each new target causes a new record to be added.
153 $this->log("irspy", "setting explicit list of targets ",
154 join(", ", map { "'$_'" } @targets));
156 foreach my $target (@targets) {
157 my($protocol, $host, $port, $db, $newtarget) =
158 _parse_target_string($target);
159 if ($newtarget ne $target) {
160 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
161 $target = $newtarget; # This is written through the ref
163 push @qlist, cql_target($protocol, $host, $port, $db);
166 $this->{targets} = \@targets;
167 $this->{query} = join(" or ", @qlist);
171 # Also used by ZOOM::IRSpy::Record
172 sub _parse_target_string {
175 my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
176 if (!defined $host) {
178 ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
179 $target = irspy_make_identifier($protocol, $host, $port, $db);
181 die "$0: invalid target string '$target'"
184 return ($protocol, $host, $port, $db, $target);
188 sub restrict_modulo {
197 # Records must be fetched for all records satisfying $this->{query} If
198 # $this->{targets} is already set (i.e. a specific list of targets to
199 # check was specified by a call to targets()), then new, empty records
200 # will be made for any targets that are not already in the database.
206 $tname = "Main" if !defined $tname;
207 $this->{test} = $tname;
208 $this->{tree} = $this->_gather_tests($tname)
209 or die "No tests defined for '$tname'";
210 $this->{tree}->resolve();
211 #$this->{tree}->print(0);
213 $this->{timeout} = "ZOOM::IRSpy::Test::$tname"->timeout();
216 my $targets = $this->{targets};
217 if (defined $targets) {
218 @targets = @$targets;
219 delete $this->{targets};
221 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
222 $this->log("irspy", "'", $this->{query}, "' found ",
223 $rs->size(), " target records");
224 delete $this->{query};
226 foreach my $i (1 .. $rs->size()) {
227 push @targets, render_record($rs, $i-1, "id");
231 my $n = $this->{activeSetSize};
232 $n = @targets if $n == 0 || $n > @targets;
234 $this->{queue} = \@targets;
235 $this->{connections} = [];
236 while (@{ $this->{connections} } < $n) {
237 my $conn = $this->_next_connection();
238 last if !defined $conn;
239 push @{ $this->{connections} }, $conn;
244 sub _next_connection {
248 my $n = $this->{modn};
249 my $i = $this->{modi};
251 $target = shift @{ $this->{queue} };
252 return undef if !defined $target;
255 $target = shift @{ $this->{queue} };
256 return undef if !defined $target;
257 my $h = _hash($target);
259 last if $hmodn == $i;
260 #$this->log("irspy", "'$target' hash $h % $n = $hmodn != $i");
264 die "oops -- target is undefined" if !defined $target;
265 return create ZOOM::IRSpy::Connection($this, $target, async => 1,
266 timeout => $this->{timeout});
274 foreach my $s (split //, $target) {
282 sub _irspy_to_zeerex {
286 my $save_xml = $ENV{IRSPY_SAVE_XML};
287 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
290 unlink('/tmp/irspy_orig.xml');
291 open FH, '>/tmp/irspy_orig.xml'
292 or die "can't write irspy_orig.xml: $!";
293 print FH $irspy_doc->toString();
297 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
299 unlink('/tmp/irspy_transformed.xml');
300 open FH, '>/tmp/irspy_transformed.xml'
301 or die "can't write irspy_transformed.xml: $!";
302 print FH $result->toString();
306 return $result->documentElement();
310 sub _rewrite_irspy_record {
314 $conn->log("irspy", "rewriting XML record");
315 my $rec = $this->_irspy_to_zeerex($conn);
317 # Since IRSpy can run for a long time between writes back to the
318 # database, it's quite possible for the server to have closed the
319 # connection as idle. So re-establish it if necessary.
320 $this->{conn}->connect($conn->option("host"));
322 _rewrite_zeerex_record($this->{conn}, $rec);
323 $conn->log("irspy", "rewrote XML record");
327 my $_reliabilityField = {
328 reliability => [ reliability => 0,
329 "Calculated reliability of server",
330 "e:serverInfo/e:reliability" ],
333 sub _rewrite_zeerex_record {
334 my($conn, $rec, $oldid) = @_;
336 # Add reliability score
337 my $xc = irspy_xpath_context($rec);
338 my($nok, $nall, $percent) = calc_reliability_stats($xc);
339 modify_xml_document($xc, $_reliabilityField, { reliability => $percent });
341 my $p = $conn->package();
342 $p->option(action => "specialUpdate");
343 my $xml = $rec->toString();
344 $p->option(record => $xml);
348 # This is the expression in the ID-making stylesheet
349 # ../../zebra/zeerex2id.xsl
350 my $id = irspy_record2identifier($xc);
351 if (defined $oldid && $id ne $oldid) {
352 warn "IDs differ (old='$oldid' new='$id')";
353 _delete_record($conn, $oldid);
356 $p = $conn->package();
363 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
371 # We can't delete records using recordIdOpaque, since character
372 # sets are handled differently here in extended services from how
373 # they are used in the Alvis filter's record-parsing, and so
374 # non-ASCII characters come out differently in the two contexts.
375 # Instead, we must send a record whose contents indicate the ID of
376 # that which we wish to delete. There are two ways, both
377 # unsatisfactory: we could either fetch the actual record them
378 # resubmit it in the deletion request (which wastes a search and a
379 # fetch) or we could build a record by hand from the parsed-out
380 # components (which is error-prone and which I am not 100% certain
381 # will work since the other contents of the record will be
382 # different). The former evil seems to be the lesser.
384 warn "$conn deleting record '$id'";
386 my $rs = $conn->search(new ZOOM::Query::CQL(cql_target($id)));
387 die "no such ID '$id'" if $rs->size() == 0;
388 my $rec = $rs->record(0);
389 my $xml = $rec->render();
391 my $p = $conn->package();
392 $p->option(action => "recordDelete");
393 $p->option(record => $xml);
397 $p = $conn->package();
403 # The approach: gather declarative information about test hierarchy,
404 # then go into a loop. In the loop, we ensure that each connection is
405 # running a test, and within that test a task, until its list of tests
406 # is exhausted. No individual test ever calls wait(): tests just queue
407 # up tasks and return immediately. When the tasks are run (one at a
408 # time on each connection) they generate events, and it is these that
409 # are harvested by ZOOM::event(). Since each connection knows what
410 # task it is running, it can invoke the appropriate callbacks.
411 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
412 # loop how to continue.
415 # While a connection is running a task, its current_task()
416 # points at the task structure. When it finishes its task,
417 # next_task() is pointed at the next task to execute (if there
418 # is one), and its current_task() is set to zero. When the next
419 # task is executed, the connection's next_task() is set to zero
420 # and its current_task() pointed to the task structure.
421 # current_task() and next_task() are both zero only when there
422 # are no more queued tasks, which is when a new test is
425 # Each connection's current test is stored in its
426 # "current_test_address" option. The next test to execute is
427 # calculated by walking the declarative tree of tests. This
428 # option begins empty; the "next test" after this is of course
434 my $topname = $this->{tree}->name();
435 my $timeout = $this->{timeout};
436 $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
439 my @conn = @{ $this->{connections} };
442 ROUND_AND_ROUND_WE_GO:
444 my @copy_conn = @conn; # avoid alias problems after splice()
445 my $nconn = scalar(@copy_conn);
446 foreach my $i0 (0 .. $#copy_conn) {
447 my $conn = $copy_conn[$i0];
448 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
449 next if !defined $conn;
450 if (!$conn->current_task()) {
451 if (!$conn->next_task()) {
452 # Out of tasks: we need a new test
454 my $address = $conn->option("current_test_address");
456 if (!defined $address) {
459 $conn->log("irspy_test",
460 "checking for next test after '$address'");
461 $nextaddr = $this->_next_test($address);
463 if (!defined $nextaddr) {
464 $conn->log("irspy", "has no more tests: removing");
465 $this->_rewrite_irspy_record($conn);
466 $conn->option(rewrote_record => 1);
467 my $newconn = $this->_next_connection();
468 if (!defined $newconn) {
469 # Do not destroy: needed for later sanity checks
470 splice @conn, $i0, 1;
473 $conn[$i0] = $newconn;
474 $conn[$i0]->option(current_test_address => "");
475 $conn[$i0]->log("irspy", "entering active pool - ",
476 scalar(@{ $this->{queue} }),
477 " targets remain in queue");
482 my $node = $this->{tree}->select($nextaddr)
483 or die "invalid nextaddr '$nextaddr'";
484 $conn->option(current_test_address => $nextaddr);
485 my $tname = $node->name();
486 $conn->log("irspy_test",
487 "starting test '$nextaddr' = $tname");
488 my $tasks = $conn->tasks();
489 my $oldcount = @$tasks;
490 "ZOOM::IRSpy::Test::$tname"->start($conn);
491 $tasks = $conn->tasks();
492 if (@$tasks > $oldcount) {
493 # Prepare to start the first of the newly added tasks
494 $conn->next_task($tasks->[$oldcount]);
496 $conn->log("irspy_task",
497 "no tasks added by new test $tname");
502 my $task = $conn->next_task();
503 die "no next task queued for $conn" if !defined $task;
504 $conn->log("irspy_task", "preparing task $task");
506 $conn->current_task($task);
512 my $i0 = ZOOM::event(\@conn);
513 $this->log("irspy_event",
514 "ZOOM_event(", scalar(@conn), " connections) = $i0");
517 0 => "no events remain",
518 -1 => "ZOOM::event() argument not a reference",
519 -2 => "ZOOM::event() reference not an array",
520 -3 => "no connections remain",
521 -4 => "too many connections for ZOOM::event()",
523 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
524 $this->log("irspy", $message);
528 my $conn = $conn[$i0-1];
529 my $ev = $conn->last_event();
530 my $evstr = ZOOM::event_str($ev);
531 $conn->log("irspy_event", "event $ev ($evstr)");
532 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
534 my $task = $conn->current_task();
535 die "$conn has no current task for event $ev ($evstr)" if !$task;
538 eval { $conn->check() };
539 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
540 my $sub = $task->{cb}->{exception};
541 die $@ if !defined $sub;
542 $res = &$sub($conn, $task, $task->udata(), $@);
544 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
546 my $sub = $task->{cb}->{$ev};
548 $conn->log("irspy_unhandled", "event $ev ($evstr)");
552 $res = &$sub($conn, $task, $task->udata(), $ev);
555 if ($res == ZOOM::IRSpy::Status::OK) {
556 # Nothing to do -- life continues
558 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
559 my $task = $conn->current_task();
560 die "no task for TASK_DONE on $conn" if !$task;
561 die "next task already defined for $conn" if $conn->next_task();
562 $conn->log("irspy_task", "completed task $task");
563 $conn->next_task($task->{next});
564 $conn->current_task(0);
566 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
567 $res == ZOOM::IRSpy::Status::TEST_BAD) {
568 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
569 $conn->log("irspy_task", "test ended during task $task ($x)");
570 $conn->log("irspy_test", "test completed ($x)");
571 $conn->current_task(0);
573 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
574 my $address = $conn->option('current_test_address');
575 $conn->log("irspy", "top-level test failed!")
577 my $node = $this->{tree}->select($address);
579 while (defined $node->next() &&
580 length($node->next()->address()) >= length($address)) {
581 $conn->log("irspy_debug", "skipping from '",
582 $node->address(), "' to '",
583 $node->next()->address(), "'");
584 $node = $node->next();
588 $conn->option(current_test_address => $node->address());
589 $conn->log("irspy_test", "skipped $skipcount tests");
590 $nskipped += $skipcount;
593 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
594 $conn->log("irspy_test", "test skipped during task $task");
595 $conn->current_task(0);
600 die "unknown callback return-value '$res'";
604 $this->log("irspy", "exiting main loop");
606 # Sanity checks: none of the following should ever happen
608 $this->log("irspy", "performing end-of-run sanity-checks");
609 foreach my $conn (@conn) {
610 my $test = $conn->option("current_test_address");
611 my $next = $this->_next_test($test);
614 "$conn (in test '$test') has queued test '$next'");
617 if (my $task = $conn->current_task()) {
618 $this->log("irspy", "$conn still has an active task $task");
621 if (my $task = $conn->next_task()) {
622 $this->log("irspy", "$conn still has a queued task $task");
625 if (!$conn->is_idle()) {
627 "$conn still has ZOOM-C level tasks queued: see below");
630 my $ev = $conn->peek_event();
631 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
632 my $evstr = ZOOM::event_str($ev);
633 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
636 if (!$conn->option("rewrote_record")) {
637 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
642 # This really shouldn't be necessary, and in practice it rarely
643 # helps, but it's belt and braces. (For now, we don't do this
644 # hence the zero in the $nruns check).
647 $this->log("irspy", "back into main loop, ${nruns}th time");
648 goto ROUND_AND_ROUND_WE_GO;
650 $this->log("irspy", "bailing after $nruns main-loop runs");
654 # This shouldn't happen emit anything either:
655 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
656 my $conn = $conn[$i1-1];
657 my $ev = $conn->last_event();
658 my $evstr = ZOOM::event_str($ev);
660 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
661 if $ev != ZOOM::Event::ZEND;
668 # Exactly equivalent to ZOOM::event() except that it is tolerant to
669 # undefined values in the array being passed in.
671 sub __UNUSED_tolerant_ZOOM_event {
675 foreach my $i (0 .. @$connref-1) {
676 my $conn = $connref->[$i];
683 my $res = ZOOM::event(\@conn);
684 return $res if $res <= 0;
685 my $res2 = $map[$res-1] + 1;
686 print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
693 my($tname, @ancestors) = @_;
695 die("$0: test-hierarchy loop detected: " .
696 join(" -> ", @ancestors, $tname))
697 if grep { $_ eq $tname } @ancestors;
699 my $slashSeperatedTname = $tname;
700 $slashSeperatedTname =~ s/::/\//g;
701 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
706 $this->log("irspy", "couldn't require '$fullName': $@");
707 $this->log("warn", "can't load test '$tname': skipping",
708 $@ =~ /^Can.t locate/ ? () : " ($@)");
712 $this->log("irspy", "adding test '$tname'");
714 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
715 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
716 push @subnodes, $subtest if defined $subtest;
719 return new ZOOM::IRSpy::Node($tname, @subnodes);
723 # These next three should arguably be Node methods
726 my($address, $omit_child) = @_;
730 my $maybe = $address eq "" ? "0" : "$address:0";
731 return $maybe if $this->{tree}->select($maybe);
734 # The top-level node has no successor or parent
735 return undef if $address eq "";
737 # Try next sibling child
738 my @components = split /:/, $address;
739 my $last = pop @components;
740 my $maybe = join(":", @components, $last+1);
741 return $maybe if $this->{tree}->select($maybe);
743 # This node is exhausted: try the parent's successor
744 return $this->_next_test(join(":", @components), 1)
748 sub _last_sibling_test {
753 if !defined $this->_next_sibling_test($address);
757 my $maybe = $this->_next_sibling_test($address);
758 last if !defined $maybe;
761 $this->log("irspy", "skipping $nskipped tests to '$address'");
764 return ($address, $nskipped);
768 sub _next_sibling_test {
772 my @components = split /:/, $address;
773 my $last = pop @components;
774 my $maybe = join(":", @components, $last+1);
775 return $maybe if $this->{tree}->select($maybe);
785 ZOOM::IRSpy::Maintenance.
787 The ZOOM-Perl module,
788 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
791 http://indexdata.com/zebra/
795 Mike Taylor, E<lt>mike@indexdata.comE<gt>
797 =head1 COPYRIGHT AND LICENSE
799 Copyright (C) 2006 by Index Data ApS.
801 This library is free software; you can redistribute it and/or modify
802 it under the same terms as Perl itself, either Perl version 5.8.7 or,
803 at your option, any later version of Perl 5 you may have available.