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;
28 our $max_timeout_errors = 3;
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");
68 ZOOM::Log::mask_str("irspy_data");
73 my($dbname, $user, $password, $activeSetSize) = @_;
77 push @options, (user => $user, password => $password)
80 my $conn = new ZOOM::Connection($dbname, 0, @options)
81 or die "$0: can't connection to IRSpy database 'dbname'";
83 my $xslt = new XML::LibXSLT;
85 # raise the maximum number of nested template calls and variables/params (default 250)
86 warn "raise the maximum number of nested template calls: $xslt_max_depth\n" if $debug;
87 $xslt->max_depth($xslt_max_depth);
89 $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
90 \&ZOOM::IRSpy::Utils::xslt_strcmp);
92 my $libxml = new XML::LibXML;
93 warn "use irspy_to_zeerex_xsl xslt sheet: $irspy_to_zeerex_xsl\n" if $debug;
94 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
95 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
99 query => "cql.allRecords=1", # unless overridden
100 modn => undef, # Filled in by restrict_modulo()
101 modi => undef, # Filled in by restrict_modulo()
102 targets => undef, # Filled in later if targets() is
103 # called; used only to keep state from
104 # targets() until initialise() is
106 connections => undef, # Filled in by initialise()
107 queue => undef, # Filled in by initialise()
109 irspy_to_zeerex_style => $irspy_to_zeerex_style,
110 test => undef, # Filled in by initialise()
111 timeout => undef, # Filled in by initialise()
112 tests => undef, # Tree of tests to be executed
113 activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
114 rules => [], # Can be filled by apply_rules()
115 vars => {}, # Will contain name, id, version, etc.
116 # May be written into by tests (mostly
117 # Ping, which gets the Init response)
118 # and read by tests for rules.
120 $this->log("irspy", "starting up with database '$dbname'");
125 # Read from and write to the set of vars
128 my($key, $newval) = @_;
130 if (defined $newval) {
131 $this->{vars}->{$key} = $newval;
132 #warn "$this: set '$key'='$newval'";
134 my $oldval = $this->{vars}->{$key};
135 $oldval = "" if !defined $oldval;
136 #warn "$this: got '$key'='$oldval'";
141 # wrapper to read the IRSpy database name from environment variable / apache config
142 sub connect_to_registry {
145 # XXX: we could also handle her: user, password, elementSetName
147 my $database = $ENV{IRSpyDbName} || "localhost:8018/IR-Explain---1";
162 $this->{query} = $query;
166 # Explicitly nominate a set of targets to check, overriding the
167 # default which is to re-check everything in the database. Each
168 # target already in the database results in the existing record being
169 # updated; each new target causes a new record to be added.
175 $this->log("irspy", "setting explicit list of targets ",
176 join(", ", map { "'$_'" } @targets));
178 foreach my $target (@targets) {
179 my($protocol, $host, $port, $db, $newtarget) =
180 _parse_target_string($target);
181 if ($newtarget ne $target) {
182 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
183 $target = $newtarget; # This is written through the ref
185 push @qlist, cql_target($protocol, $host, $port, $db);
188 $this->{targets} = \@targets;
189 $this->{query} = join(" or ", @qlist);
193 # Also used by ZOOM::IRSpy::Record
194 sub _parse_target_string {
197 my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
198 if (!defined $host) {
200 ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
201 $target = irspy_make_identifier($protocol, $host, $port, $db);
203 die "$0: invalid target string '$target'"
206 return ($protocol, $host, $port, $db, $target);
210 sub restrict_modulo {
223 my $f = new IO::File("<$fileName")
224 or die "$0: can't open rules file '$fileName': $!";
226 while (my $line = <$f>) {
231 my(@fields) = split /\s+/, $line;
232 my($name, $op, $val, $rule, @params) = @fields;
233 #warn "parsed name='$name', op='$op', val='$val', rule='$rule', params='@params'\n";
234 push @{ $this->{rules} }, [ @fields ];
239 # Records must be fetched for all records satisfying $this->{query} If
240 # $this->{targets} is already set (i.e. a specific list of targets to
241 # check was specified by a call to targets()), then new, empty records
242 # will be made for any targets that are not already in the database.
248 $tname = "Main" if !defined $tname;
249 $this->{test} = $tname;
250 $this->{tree} = $this->_gather_tests($tname)
251 or die "No tests defined for '$tname'";
252 $this->{tree}->resolve();
253 #$this->{tree}->print(0);
255 $this->{timeout} = "ZOOM::IRSpy::Test::$tname"->timeout();
258 my $targets = $this->{targets};
259 if (defined $targets) {
260 @targets = @$targets;
261 delete $this->{targets};
263 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
264 $this->log("irspy", "'", $this->{query}, "' found ",
265 $rs->size(), " target records");
266 delete $this->{query};
268 foreach my $i (1 .. $rs->size()) {
269 push @targets, render_record($rs, $i-1, "id");
273 my $n = $this->{activeSetSize};
274 $n = @targets if $n == 0 || $n > @targets;
276 $this->{queue} = \@targets;
277 $this->{connections} = [];
278 while (@{ $this->{connections} } < $n) {
279 my $conn = $this->_next_connection();
280 last if !defined $conn;
281 push @{ $this->{connections} }, $conn;
286 sub _next_connection {
290 my $n = $this->{modn};
291 my $i = $this->{modi};
293 $target = shift @{ $this->{queue} };
294 return undef if !defined $target;
297 $target = shift @{ $this->{queue} };
298 return undef if !defined $target;
299 my $h = _hash($target);
301 last if $hmodn == $i;
302 #$this->log("irspy", "'$target' hash $h % $n = $hmodn != $i");
306 die "oops -- target is undefined" if !defined $target;
307 return create ZOOM::IRSpy::Connection($this, $target, async => 1,
308 timeout => $this->{timeout});
316 foreach my $s (split //, $target) {
324 sub _irspy_to_zeerex {
328 my $save_xml = $ENV{IRSPY_SAVE_XML};
329 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
332 unlink('/tmp/irspy_orig.xml');
333 open FH, '>/tmp/irspy_orig.xml'
334 or die "can't write irspy_orig.xml: $!";
335 print FH $irspy_doc->toString();
339 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
341 unlink('/tmp/irspy_transformed.xml');
342 open FH, '>/tmp/irspy_transformed.xml'
343 or die "can't write irspy_transformed.xml: $!";
344 print FH $result->toString();
348 return $result->documentElement();
352 sub _rewrite_irspy_record {
356 $conn->log("irspy", "rewriting XML record");
357 my $rec = $this->_irspy_to_zeerex($conn);
359 # Since IRSpy can run for a long time between writes back to the
360 # database, it's quite possible for the server to have closed the
361 # connection as idle. So re-establish it if necessary.
362 $this->{conn}->connect($conn->option("host"));
364 _rewrite_zeerex_record($this->{conn}, $rec);
365 $conn->log("irspy", "rewrote XML record");
369 my $_reliabilityField = {
370 reliability => [ reliability => 0,
371 "Calculated reliability of server",
372 "e:serverInfo/e:reliability" ],
375 sub _rewrite_zeerex_record {
376 my($conn, $rec, $oldid) = @_;
378 # Add reliability score
379 my $xc = irspy_xpath_context($rec);
380 my($nok, $nall, $percent) = calc_reliability_stats($xc);
381 modify_xml_document($xc, $_reliabilityField, { reliability => $percent });
383 my $p = $conn->package();
384 $p->option(action => "specialUpdate");
385 my $xml = $rec->toString();
386 $p->option(record => $xml);
390 # This is the expression in the ID-making stylesheet
391 # ../../zebra/zeerex2id.xsl
392 my $id = irspy_record2identifier($xc);
393 if (defined $oldid && $id ne $oldid) {
394 warn "IDs differ (old='$oldid' new='$id')";
395 _delete_record($conn, $oldid);
398 $p = $conn->package();
405 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
413 # We can't delete records using recordIdOpaque, since character
414 # sets are handled differently here in extended services from how
415 # they are used in the Alvis filter's record-parsing, and so
416 # non-ASCII characters come out differently in the two contexts.
417 # Instead, we must send a record whose contents indicate the ID of
418 # that which we wish to delete. There are two ways, both
419 # unsatisfactory: we could either fetch the actual record them
420 # resubmit it in the deletion request (which wastes a search and a
421 # fetch) or we could build a record by hand from the parsed-out
422 # components (which is error-prone and which I am not 100% certain
423 # will work since the other contents of the record will be
424 # different). The former evil seems to be the lesser.
426 warn "$conn deleting record '$id'";
428 my $rs = $conn->search(new ZOOM::Query::CQL(cql_target($id)));
429 die "no such ID '$id'" if $rs->size() == 0;
430 my $rec = $rs->record(0);
431 my $xml = $rec->render();
433 my $p = $conn->package();
434 $p->option(action => "recordDelete");
435 $p->option(record => $xml);
439 $p = $conn->package();
445 # The approach: gather declarative information about test hierarchy,
446 # then go into a loop. In the loop, we ensure that each connection is
447 # running a test, and within that test a task, until its list of tests
448 # is exhausted. No individual test ever calls wait(): tests just queue
449 # up tasks and return immediately. When the tasks are run (one at a
450 # time on each connection) they generate events, and it is these that
451 # are harvested by ZOOM::event(). Since each connection knows what
452 # task it is running, it can invoke the appropriate callbacks.
453 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
454 # loop how to continue.
457 # While a connection is running a task, its current_task()
458 # points at the task structure. When it finishes its task,
459 # next_task() is pointed at the next task to execute (if there
460 # is one), and its current_task() is set to zero. When the next
461 # task is executed, the connection's next_task() is set to zero
462 # and its current_task() pointed to the task structure.
463 # current_task() and next_task() are both zero only when there
464 # are no more queued tasks, which is when a new test is
467 # Each connection's current test is stored in its
468 # "current_test_address" option. The next test to execute is
469 # calculated by walking the declarative tree of tests. This
470 # option begins empty; the "next test" after this is of course
476 my $topname = $this->{tree}->name();
477 my $timeout = $this->{timeout};
478 $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
481 my @conn = @{ $this->{connections} };
484 ROUND_AND_ROUND_WE_GO:
486 my @copy_conn = @conn; # avoid alias problems after splice()
487 my $nconn = scalar(@copy_conn);
489 foreach my $i0 (0 .. $#copy_conn) {
490 my $conn = $copy_conn[$i0];
491 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
492 next if !defined $conn;
494 if (!$conn->current_task()) {
495 if (!$conn->next_task()) {
496 # Out of tasks: we need a new test
498 my $address = $conn->option("current_test_address");
500 if (!defined $address) {
503 $conn->log("irspy_test",
504 "checking for next test after '$address'");
505 $nextaddr = $this->_next_test($address);
508 if (ZOOM::IRSpy::Test::zoom_error_timeout_check($conn)) {
509 $conn->log("irspy", "Got to many timeouts, stop testing");
513 if (!defined $nextaddr) {
514 $conn->log("irspy", "has no more tests: removing");
515 $this->_rewrite_irspy_record($conn);
516 $conn->option(rewrote_record => 1);
517 my $newconn = $this->_next_connection();
518 if (!defined $newconn) {
519 # Do not destroy: needed for later sanity checks
520 splice @conn, $i0, 1;
523 $conn[$i0] = $newconn;
524 $conn[$i0]->option(current_test_address => "");
525 $conn[$i0]->log("irspy", "entering active pool - ",
526 scalar(@{ $this->{queue} }),
527 " targets remain in queue");
532 my $node = $this->{tree}->select($nextaddr)
533 or die "invalid nextaddr '$nextaddr'";
534 $conn->option(current_test_address => $nextaddr);
535 my $tname = $node->name();
536 if ($this->should_skip_test($tname)) {
537 $conn->log("irspy_test",
538 "skipping test '$nextaddr' = $tname due to rule");
543 $conn->log("irspy_test",
544 "starting test '$nextaddr' = $tname");
545 my $tasks = $conn->tasks();
546 my $oldcount = @$tasks;
547 "ZOOM::IRSpy::Test::$tname"->start($conn);
548 $tasks = $conn->tasks();
549 if (@$tasks > $oldcount) {
550 # Prepare to start the first of the newly added tasks
551 $conn->next_task($tasks->[$oldcount]);
553 $conn->log("irspy_task",
554 "no tasks added by new test $tname");
559 my $task = $conn->next_task();
560 die "no next task queued for $conn" if !defined $task;
562 # do not run the next task if we got too many timeouts
563 if (ZOOM::IRSpy::Test::zoom_error_timeout_check($conn)) {
564 $conn->log("irspy_task", "Got too many timeouts for this target, do not start a new task");
568 $conn->log("irspy_task", "preparing task $task");
570 $conn->current_task($task);
576 my $i0 = ZOOM::event(\@conn);
577 $this->log("irspy_event",
578 "ZOOM_event(", scalar(@conn), " connections) = $i0");
581 0 => "no events remain",
582 -1 => "ZOOM::event() argument not a reference",
583 -2 => "ZOOM::event() reference not an array",
584 -3 => "no connections remain",
585 -4 => "too many connections for ZOOM::event()",
587 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
588 $this->log("irspy", $message);
592 my $conn = $conn[$i0-1];
593 my $ev = $conn->last_event();
594 my $evstr = ZOOM::event_str($ev);
595 $conn->log("irspy_event", "event $ev ($evstr)");
596 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
598 my $task = $conn->current_task();
599 die "$conn has no current task for event $ev ($evstr)" if !$task;
602 eval { $conn->check() };
603 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
604 my $sub = $task->{cb}->{exception};
605 die $@ if !defined $sub;
606 $res = &$sub($conn, $task, $task->udata(), $@);
608 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
610 my $sub = $task->{cb}->{$ev};
612 $conn->log("irspy_unhandled", "event $ev ($evstr)");
616 $res = &$sub($conn, $task, $task->udata(), $ev);
619 if ($res == ZOOM::IRSpy::Status::OK) {
620 # Nothing to do -- life continues
622 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
623 my $task = $conn->current_task();
624 die "no task for TASK_DONE on $conn" if !$task;
625 die "next task already defined for $conn" if $conn->next_task();
626 $conn->log("irspy_task", "completed task $task");
627 $conn->next_task($task->{next});
628 $conn->current_task(0);
630 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
631 $res == ZOOM::IRSpy::Status::TEST_BAD) {
632 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
633 $conn->log("irspy_task", "test ended during task $task ($x)");
634 $conn->log("irspy_test", "test completed ($x)");
635 $conn->current_task(0);
637 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
638 my $address = $conn->option('current_test_address');
639 $conn->log("irspy", "top-level test failed!")
641 my $node = $this->{tree}->select($address);
643 while (defined $node->next() &&
644 length($node->next()->address()) >= length($address)) {
645 $conn->log("irspy_test", "skipping from '",
646 $node->address(), "' to '",
647 $node->next()->address(), "' (", $node->next()->name(), ")");
648 $node = $node->next();
652 $conn->option(current_test_address => $node->address());
653 $conn->log("irspy_test", "skipped $skipcount tests");
654 $nskipped += $skipcount;
657 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
658 $conn->log("irspy_test", "test skipped during task $task");
659 $conn->current_task(0);
664 die "unknown callback return-value '$res'";
668 $this->log("irspy", "exiting main loop");
670 # Sanity checks: none of the following should ever happen
672 $this->log("irspy", "performing end-of-run sanity-checks");
673 foreach my $conn (@conn) {
674 my $test = $conn->option("current_test_address");
675 my $next = $this->_next_test($test);
678 "$conn (in test '$test') has queued test '$next'");
681 if (my $task = $conn->current_task()) {
682 $this->log("irspy", "$conn still has an active task $task");
685 if (my $task = $conn->next_task()) {
686 $this->log("irspy", "$conn still has a queued task $task");
689 if (!$conn->is_idle()) {
691 "$conn still has ZOOM-C level tasks queued: see below");
694 my $ev = $conn->peek_event();
695 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
696 my $evstr = ZOOM::event_str($ev);
697 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
700 if (!$conn->option("rewrote_record")) {
701 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
706 # This really shouldn't be necessary, and in practice it rarely
707 # helps, but it's belt and braces. (For now, we don't do this
708 # hence the zero in the $nruns check).
711 $this->log("irspy", "back into main loop, ${nruns}th time");
712 goto ROUND_AND_ROUND_WE_GO;
714 $this->log("irspy", "bailing after $nruns main-loop runs");
718 # This shouldn't happen emit anything either:
719 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
720 my $conn = $conn[$i1-1];
721 my $ev = $conn->last_event();
722 my $evstr = ZOOM::event_str($ev);
724 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
725 if $ev != ZOOM::Event::ZEND;
732 ### This could of course call a much more general looping evaluator
733 sub should_skip_test {
737 foreach my $rule (@{ $this->{rules} }) {
738 my($name, $op, $val, $rule, @params) = @$rule;
739 #warn "using name='$name', op='$op', val='$val', rule='$rule', params='@params'\n";
742 $params[0] eq $tname) {
744 $re =~ s/^\/(.*)\/$/$1/;
745 if ($this->var($name) =~ $re) {
746 #warn "$name '", $this->var($name), "' matches /$re/ -- skipping '$tname'";
756 # Exactly equivalent to ZOOM::event() except that it is tolerant to
757 # undefined values in the array being passed in.
759 sub __UNUSED_tolerant_ZOOM_event {
763 foreach my $i (0 .. @$connref-1) {
764 my $conn = $connref->[$i];
771 my $res = ZOOM::event(\@conn);
772 return $res if $res <= 0;
773 my $res2 = $map[$res-1] + 1;
774 print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
781 my($tname, @ancestors) = @_;
783 die("$0: test-hierarchy loop detected: " .
784 join(" -> ", @ancestors, $tname))
785 if grep { $_ eq $tname } @ancestors;
787 my $slashSeperatedTname = $tname;
788 $slashSeperatedTname =~ s/::/\//g;
789 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
794 $this->log("irspy", "couldn't require '$fullName': $@");
795 $this->log("warn", "can't load test '$tname': skipping",
796 $@ =~ /^Can.t locate/ ? () : " ($@)");
800 $this->log("irspy", "adding test '$tname'");
802 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
803 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
804 push @subnodes, $subtest if defined $subtest;
807 return new ZOOM::IRSpy::Node($tname, @subnodes);
811 # These next three should arguably be Node methods
814 my($address, $omit_child) = @_;
818 my $maybe = $address eq "" ? "0" : "$address:0";
819 return $maybe if $this->{tree}->select($maybe);
822 # The top-level node has no successor or parent
823 return undef if $address eq "";
825 # Try next sibling child
826 # The use of a regexp in split() is to avoid confusing Emacs's
827 # Perl mode; the third colon is to avoid looking like a POSIX
828 # named character class ... *sigh*
829 my @components = split /[:::]/, $address;
830 my $last = pop @components;
831 my $maybe = join(":", @components, $last+1);
832 return $maybe if $this->{tree}->select($maybe);
834 # This node is exhausted: try the parent's successor
835 return $this->_next_test(join(":", @components), 1)
839 sub _last_sibling_test {
840 die "_last_sibling_test() called -- I thought that never happened?";
845 if !defined $this->_next_sibling_test($address);
849 my $maybe = $this->_next_sibling_test($address);
850 last if !defined $maybe;
853 $this->log("irspy", "skipping $nskipped tests to '$address'");
856 return ($address, $nskipped);
860 sub _next_sibling_test {
861 die "_next_sibling_test() called -- I thought that never happened?";
865 my @components = split /[:::]/, $address;
866 my $last = pop @components;
867 my $maybe = join(":", @components, $last+1);
868 return $maybe if $this->{tree}->select($maybe);
878 ZOOM::IRSpy::Maintenance.
880 The ZOOM-Perl module,
881 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
884 http://indexdata.com/zebra/
888 Mike Taylor, E<lt>mike@indexdata.comE<gt>
890 =head1 COPYRIGHT AND LICENSE
892 Copyright (C) 2006 by Index Data ApS.
894 This library is free software; you can redistribute it and/or modify
895 it under the same terms as Perl itself, either Perl version 5.8.7 or,
896 at your option, any later version of Perl 5 you may have available.