Stop testing a target if we got to many timeouts (>= 3). See bug #3382
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy.pm
1
2 package ZOOM::IRSpy;
3
4 use 5.008;
5 use strict;
6 use warnings;
7
8 use Data::Dumper;               # For debugging only
9 use File::Basename;
10 use XML::LibXSLT;
11 use XML::LibXML;
12 use XML::LibXML::XPathContext;
13 use ZOOM;
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
21                           modify_xml_document);
22
23 our @ISA = qw();
24 our $VERSION = '1.02';
25 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
26 our $debug = 0;
27 our $xslt_max_depth = 250;
28 our $max_timeout_errors = 3;
29
30
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
38 package ZOOM::IRSpy;
39
40
41 =head1 NAME
42
43 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
44
45 =head1 SYNOPSIS
46
47  use ZOOM::IRSpy;
48  $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
49  $spy->targets(@targets);
50  $spy->initialise("Main");
51  $res = $spy->check();
52
53 =head1 DESCRIPTION
54
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.
58
59 =cut
60
61 BEGIN {
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 }
69
70 sub new {
71     my $class = shift();
72     my($dbname, $user, $password, $activeSetSize) = @_;
73
74
75     my @options;
76     push @options, (user => $user, password => $password)
77         if defined $user;
78
79     my $conn = new ZOOM::Connection($dbname, 0, @options)
80         or die "$0: can't connection to IRSpy database 'dbname'";
81
82     my $xslt = new XML::LibXSLT;
83
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);
87
88     $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
89                              \&ZOOM::IRSpy::Utils::xslt_strcmp);
90
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);
95
96     my $this = bless {
97         conn => $conn,
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
104                                 # called.
105         connections => undef,   # Filled in by initialise()
106         queue => undef,         # Filled in by initialise()
107         libxml => $libxml,
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,
113     }, $class;
114     $this->log("irspy", "starting up with database '$dbname'");
115
116     return $this;
117 }
118
119 # wrapper to read the IRSpy database name from environment variable / apache config
120 sub connect_to_registry {
121     my %args = @_;
122
123     # XXX: we could also handle her: user, password, elementSetName
124
125     my $database = $ENV{IRSpyDbName} || "localhost:8018/IR-Explain---1";
126
127     return $database;
128 }
129
130 sub log {
131     my $this = shift();
132     ZOOM::Log::log(@_);
133 }
134
135
136 sub find_targets {
137     my $this = shift();
138     my($query) = @_;
139
140     $this->{query} = $query;
141 }
142
143
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.
148 #
149 sub targets {
150     my $this = shift();
151     my(@targets) = @_;
152
153     $this->log("irspy", "setting explicit list of targets ",
154                join(", ", map { "'$_'" } @targets));
155     my @qlist;
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
162         }
163         push @qlist, cql_target($protocol, $host, $port, $db);
164     }
165
166     $this->{targets} = \@targets;
167     $this->{query} = join(" or ", @qlist);
168 }
169
170
171 # Also used by ZOOM::IRSpy::Record
172 sub _parse_target_string {
173     my($target) = @_;
174
175     my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
176     if (!defined $host) {
177         $port = 210;
178         ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
179         $target = irspy_make_identifier($protocol, $host, $port, $db);
180     }
181     die "$0: invalid target string '$target'"
182         if !defined $host;
183
184     return ($protocol, $host, $port, $db, $target);
185 }
186
187
188 sub restrict_modulo {
189     my $this = shift();
190     my($n, $i) = @_;
191
192     $this->{modn} = $n;
193     $this->{modi} = $i;
194 }
195
196
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.
201 #
202 sub initialise {
203     my $this = shift();
204     my($tname) = @_;
205
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);
212
213     $this->{timeout} = "ZOOM::IRSpy::Test::$tname"->timeout();
214
215     my @targets;
216     my $targets = $this->{targets};
217     if (defined $targets) {
218         @targets = @$targets;
219         delete $this->{targets};
220     } else {
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};
225
226         foreach my $i (1 .. $rs->size()) {
227             push @targets, render_record($rs, $i-1, "id");
228         }
229     }
230
231     my $n = $this->{activeSetSize};
232     $n = @targets if $n == 0 || $n > @targets;
233
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;
240     }
241 }
242
243
244 sub _next_connection {
245     my $this = shift();
246
247     my $target;
248     my $n = $this->{modn};
249     my $i = $this->{modi};
250     if (!defined $n) {
251         $target = shift @{ $this->{queue} };
252         return undef if !defined $target;
253     } else {
254         while (1) {
255             $target = shift @{ $this->{queue} };
256             return undef if !defined $target;
257             my $h = _hash($target);
258             my $hmodn = $h % $n;
259             last if $hmodn == $i;
260             #$this->log("irspy", "'$target' hash $h % $n = $hmodn != $i");
261         }
262     }
263
264     die "oops -- target is undefined" if !defined $target;
265     return create ZOOM::IRSpy::Connection($this, $target, async => 1,
266                                           timeout => $this->{timeout});
267 }
268
269
270 sub _hash {
271     my($target) = @_;
272
273     my $n = 0;
274     foreach my $s (split //, $target) {
275         $n += ord($s);
276     }
277
278     return $n;
279 }
280
281
282 sub _irspy_to_zeerex {
283     my $this = shift();
284     my($conn) = @_;
285
286     my $save_xml = $ENV{IRSPY_SAVE_XML};
287     my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
288
289     if ($save_xml) {
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();
294         close FH;
295     }
296     my %params = ();
297     my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
298     if ($save_xml) {
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();
303         close FH;
304     }
305
306     return $result->documentElement();
307 }
308
309
310 sub _rewrite_irspy_record {
311     my $this = shift();
312     my($conn) = @_;
313
314     $conn->log("irspy", "rewriting XML record");
315     my $rec = $this->_irspy_to_zeerex($conn);
316
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"));
321
322     _rewrite_zeerex_record($this->{conn}, $rec);
323     $conn->log("irspy", "rewrote XML record");
324 }
325
326
327 my $_reliabilityField = {
328     reliability => [ reliability => 0,
329                       "Calculated reliability of server",
330                       "e:serverInfo/e:reliability" ],
331 };
332
333 sub _rewrite_zeerex_record {
334     my($conn, $rec, $oldid) = @_;
335
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 });
340
341     my $p = $conn->package();
342     $p->option(action => "specialUpdate");
343     my $xml = $rec->toString();
344     $p->option(record => $xml);
345     $p->send("update");
346     $p->destroy();
347
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);
354     }
355
356     $p = $conn->package();
357     $p->send("commit");
358     $p->destroy();
359     if (0) {
360         $xml =~ s/&/&amp/g;
361         $xml =~ s/</&lt;/g;
362         $xml =~ s/>/&gt;/g;
363         print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
364     }
365 }
366
367
368 sub _delete_record {
369     my($conn, $id) = @_;
370
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.
383
384     warn "$conn deleting record '$id'";
385
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();
390
391     my $p = $conn->package();
392     $p->option(action => "recordDelete");
393     $p->option(record => $xml);
394     $p->send("update");
395     $p->destroy();
396
397     $p = $conn->package();
398     $p->send("commit");
399     $p->destroy();
400 }
401
402
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.
413 #
414 # Invariants:
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
423 #       started.
424 #
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
429 #       the root test.
430 #
431 sub check {
432     my $this = shift();
433
434     my $topname = $this->{tree}->name();
435     my $timeout = $this->{timeout};
436     $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
437
438     $timeout = 2;
439
440     my $nskipped = 0;
441     my @conn = @{ $this->{connections} };
442
443     my $nruns = 0;
444   ROUND_AND_ROUND_WE_GO:
445     while (1) {
446         my @copy_conn = @conn;  # avoid alias problems after splice()
447         my $nconn = scalar(@copy_conn);
448
449
450         foreach my $i0 (0 .. $#copy_conn) {
451             my $conn = $copy_conn[$i0];
452                 #warn Dumper($conn);
453
454             #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
455             next if !defined $conn;
456             if (!$conn->current_task()) {
457                 if (!$conn->next_task()) {
458                     # Out of tasks: we need a new test
459                   NEXT_TEST:
460                     my $address = $conn->option("current_test_address");
461                     my $nextaddr;
462                     if (!defined $address) {
463                         $nextaddr = "";
464                     } else {
465                         $conn->log("irspy_test",
466                                    "checking for next test after '$address'");
467                         $nextaddr = $this->_next_test($address);
468                         if ($nextaddr && $conn->record->zoom_error->{TIMEOUT} >= $max_timeout_errors) {
469                             $conn->log("irspy", "Got to many timeouts, stop testing: " . $conn->record->zoom_error->{TIMEOUT});
470                             $nextaddr = "";
471                         }
472                     }
473                     if (!defined $nextaddr) {
474                         $conn->log("irspy", "has no more tests: removing");
475                         $this->_rewrite_irspy_record($conn);
476                         $conn->option(rewrote_record => 1);
477                         my $newconn = $this->_next_connection();
478                         if (!defined $newconn) {
479                             # Do not destroy: needed for later sanity checks
480                             splice @conn, $i0, 1;
481                         } else {
482                             $conn->destroy();
483                             $conn[$i0] = $newconn;
484                             $conn[$i0]->option(current_test_address => "");
485                             $conn[$i0]->log("irspy", "entering active pool - ",
486                                             scalar(@{ $this->{queue} }),
487                                             " targets remain in queue");
488                         }
489                         next;
490                     }
491
492                     my $node = $this->{tree}->select($nextaddr)
493                         or die "invalid nextaddr '$nextaddr'";
494                     $conn->option(current_test_address => $nextaddr);
495                     my $tname = $node->name();
496                     $conn->log("irspy_test",
497                                "starting test '$nextaddr' = $tname");
498                     my $tasks = $conn->tasks();
499                     my $oldcount = @$tasks;
500                     "ZOOM::IRSpy::Test::$tname"->start($conn);
501                     $tasks = $conn->tasks();
502                     if (@$tasks > $oldcount) {
503                         # Prepare to start the first of the newly added tasks
504                         $conn->next_task($tasks->[$oldcount]);
505                     } else {
506                         $conn->log("irspy_task",
507                                    "no tasks added by new test $tname");
508                         goto NEXT_TEST;
509                     }
510                 }
511
512                 my $task = $conn->next_task();
513                 die "no next task queued for $conn" if !defined $task;
514                 $conn->log("irspy_task", "preparing task $task");
515                 $conn->next_task(0);
516                 $conn->current_task($task);
517                 $task->run();
518             }
519         }
520
521       NEXT_EVENT:
522         my $i0 = ZOOM::event(\@conn);
523         $this->log("irspy_event",
524                    "ZOOM_event(", scalar(@conn), " connections) = $i0");
525         if ($i0 < 1) {
526             my %messages = (
527                             0 => "no events remain",
528                             -1 => "ZOOM::event() argument not a reference",
529                             -2 => "ZOOM::event() reference not an array",
530                             -3 => "no connections remain",
531                             -4 => "too many connections for ZOOM::event()",
532                             );
533             my $message = $messages{$i0} || "ZOOM::event() returned $i0";
534             $this->log("irspy", $message);
535             last;
536         }
537
538         my $conn = $conn[$i0-1];
539         my $ev = $conn->last_event();
540         my $evstr = ZOOM::event_str($ev);
541         $conn->log("irspy_event", "event $ev ($evstr)");
542         goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
543
544         my $task = $conn->current_task();
545         die "$conn has no current task for event $ev ($evstr)" if !$task;
546
547         my $res;
548         eval { $conn->check() };
549         if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
550             my $sub = $task->{cb}->{exception};
551             die $@ if !defined $sub;
552             $res = &$sub($conn, $task, $task->udata(), $@);
553         } elsif ($@) {
554             die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
555         } else {
556             my $sub = $task->{cb}->{$ev};
557             if (!defined $sub) {
558                 $conn->log("irspy_unhandled", "event $ev ($evstr)");
559                 next;
560             }
561
562             $res = &$sub($conn, $task, $task->udata(), $ev);
563         }
564
565         if ($res == ZOOM::IRSpy::Status::OK) {
566             # Nothing to do -- life continues
567
568         } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
569             my $task = $conn->current_task();
570             die "no task for TASK_DONE on $conn" if !$task;
571             die "next task already defined for $conn" if $conn->next_task();
572             $conn->log("irspy_task", "completed task $task");
573             $conn->next_task($task->{next});
574             $conn->current_task(0);
575
576         } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
577                  $res == ZOOM::IRSpy::Status::TEST_BAD) {
578             my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
579             $conn->log("irspy_task", "test ended during task $task ($x)");
580             $conn->log("irspy_test", "test completed ($x)");
581             $conn->current_task(0);
582             $conn->next_task(0);
583             if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
584                 my $address = $conn->option('current_test_address');
585                 $conn->log("irspy", "top-level test failed!")
586                     if $address eq "";
587                 my $node = $this->{tree}->select($address);
588                 my $skipcount = 0;
589                 while (defined $node->next() &&
590                        length($node->next()->address()) >= length($address)) {
591                     $conn->log("irspy_debug", "skipping from '",
592                                $node->address(), "' to '",
593                                $node->next()->address(), "'");
594                     $node = $node->next();
595                     $skipcount++;
596                 }
597
598                 $conn->option(current_test_address => $node->address());
599                 $conn->log("irspy_test", "skipped $skipcount tests");
600                 $nskipped += $skipcount;
601             }
602
603         } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
604             $conn->log("irspy_test", "test skipped during task $task");
605             $conn->current_task(0);
606             $conn->next_task(0);
607             $nskipped++;
608
609         } else {
610             die "unknown callback return-value '$res'";
611         }
612     }
613
614     $this->log("irspy", "exiting main loop");
615
616     # Sanity checks: none of the following should ever happen
617     my $finished = 1;
618     $this->log("irspy", "performing end-of-run sanity-checks");
619     foreach my $conn (@conn) {
620         my $test = $conn->option("current_test_address");
621         my $next = $this->_next_test($test);
622         if (defined $next) {
623             $this->log("irspy",
624                        "$conn (in test '$test') has queued test '$next'");
625             $finished = 0;
626         }
627         if (my $task = $conn->current_task()) {
628             $this->log("irspy", "$conn still has an active task $task");
629             $finished = 0;
630         }
631         if (my $task = $conn->next_task()) {
632             $this->log("irspy", "$conn still has a queued task $task");
633             $finished = 0;
634         }
635         if (!$conn->is_idle()) {
636             $this->log("irspy",
637                        "$conn still has ZOOM-C level tasks queued: see below");
638             $finished = 0;
639         }
640         my $ev = $conn->peek_event();
641         if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
642             my $evstr = ZOOM::event_str($ev);
643             $this->log("irspy", "$conn has event $ev ($evstr) waiting");
644             $finished = 0;
645         }
646         if (!$conn->option("rewrote_record")) {
647             $this->log("irspy", "$conn did not rewrite its ZeeRex record");
648             $finished = 0;
649         }
650     }
651
652     # This really shouldn't be necessary, and in practice it rarely
653     # helps, but it's belt and braces.  (For now, we don't do this
654     # hence the zero in the $nruns check).
655     if (!$finished) {
656         if (++$nruns < 0) {
657             $this->log("irspy", "back into main loop, ${nruns}th time");
658             goto ROUND_AND_ROUND_WE_GO;
659         } else {
660             $this->log("irspy", "bailing after $nruns main-loop runs");
661         }
662     }
663
664     # This shouldn't happen emit anything either:
665     while ((my $i1 = ZOOM::event(\@conn)) > 0) {
666         my $conn = $conn[$i1-1];
667         my $ev = $conn->last_event();
668         my $evstr = ZOOM::event_str($ev);
669         $this->log("irspy",
670                    "$conn still has ZOOM-C level task queued: $ev ($evstr)")
671             if $ev != ZOOM::Event::ZEND;
672     }
673
674     return $nskipped;
675 }
676
677
678 # Exactly equivalent to ZOOM::event() except that it is tolerant to
679 # undefined values in the array being passed in.
680 #
681 sub __UNUSED_tolerant_ZOOM_event {
682     my($connref) = @_;
683
684     my(@conn, @map);
685     foreach my $i (0 .. @$connref-1) {
686         my $conn = $connref->[$i];
687         if (defined $conn) {
688             push @conn, $conn;
689             push @map, $i;
690         }
691     }
692
693     my $res = ZOOM::event(\@conn);
694     return $res if $res <= 0;
695     my $res2 = $map[$res-1] + 1;
696     print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
697     return $res2;
698 }
699
700
701 sub _gather_tests {
702     my $this = shift();
703     my($tname, @ancestors) = @_;
704
705     die("$0: test-hierarchy loop detected: " .
706         join(" -> ", @ancestors, $tname))
707         if grep { $_ eq $tname } @ancestors;
708
709     my $slashSeperatedTname = $tname;
710     $slashSeperatedTname =~ s/::/\//g;
711     my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
712
713     eval {
714         require $fullName;
715     }; if ($@) {
716         $this->log("irspy", "couldn't require '$fullName': $@");
717         $this->log("warn", "can't load test '$tname': skipping",
718                    $@ =~ /^Can.t locate/ ? () : " ($@)");
719         return undef;
720     }
721
722     $this->log("irspy", "adding test '$tname'");
723     my @subnodes;
724     foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
725         my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
726         push @subnodes, $subtest if defined $subtest;
727     }
728
729     return new ZOOM::IRSpy::Node($tname, @subnodes);
730 }
731
732
733 # These next three should arguably be Node methods
734 sub _next_test {
735     my $this = shift();
736     my($address, $omit_child) = @_;
737
738     # Try first child
739     if (!$omit_child) {
740         my $maybe = $address eq "" ? "0" : "$address:0";
741         return $maybe if $this->{tree}->select($maybe);
742     }
743
744     # The top-level node has no successor or parent
745     return undef if $address eq "";
746
747     # Try next sibling child
748     my @components = split /:/, $address;
749     my $last = pop @components;
750     my $maybe = join(":", @components, $last+1);
751     return $maybe if $this->{tree}->select($maybe);
752
753     # This node is exhausted: try the parent's successor
754     return $this->_next_test(join(":", @components), 1)
755 }
756
757
758 sub _last_sibling_test {
759     my $this = shift();
760     my($address) = @_;
761
762     return undef
763         if !defined $this->_next_sibling_test($address);
764
765     my $nskipped = 0;
766     while (1) {
767         my $maybe = $this->_next_sibling_test($address);
768         last if !defined $maybe;
769         $nskipped++;
770         $address = $maybe;
771         $this->log("irspy", "skipping $nskipped tests to '$address'");
772     }
773
774     return ($address, $nskipped);
775 }
776
777
778 sub _next_sibling_test {
779     my $this = shift();
780     my($address) = @_;
781
782     my @components = split /:/, $address;
783     my $last = pop @components;
784     my $maybe = join(":", @components, $last+1);
785     return $maybe if $this->{tree}->select($maybe);
786     return undef;
787 }
788
789
790 =head1 SEE ALSO
791
792 ZOOM::IRSpy::Record,
793 ZOOM::IRSpy::Web,
794 ZOOM::IRSpy::Test,
795 ZOOM::IRSpy::Maintenance.
796
797 The ZOOM-Perl module,
798 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
799
800 The Zebra Database,
801 http://indexdata.com/zebra/
802
803 =head1 AUTHOR
804
805 Mike Taylor, E<lt>mike@indexdata.comE<gt>
806
807 =head1 COPYRIGHT AND LICENSE
808
809 Copyright (C) 2006 by Index Data ApS.
810
811 This library is free software; you can redistribute it and/or modify
812 it under the same terms as Perl itself, either Perl version 5.8.7 or,
813 at your option, any later version of Perl 5 you may have available.
814
815 =cut
816
817
818 1;