import trimField
[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
29
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
37 package ZOOM::IRSpy;
38
39
40 =head1 NAME
41
42 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
43
44 =head1 SYNOPSIS
45
46  use ZOOM::IRSpy;
47  $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
48  $spy->targets(@targets);
49  $spy->initialise("Main");
50  $res = $spy->check();
51
52 =head1 DESCRIPTION
53
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.
57
58 =cut
59
60 BEGIN {
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");
67 }
68
69 sub new {
70     my $class = shift();
71     my($dbname, $user, $password, $activeSetSize) = @_;
72
73
74     my @options;
75     push @options, (user => $user, password => $password)
76         if defined $user;
77
78     my $conn = new ZOOM::Connection($dbname, 0, @options)
79         or die "$0: can't connection to IRSpy database 'dbname'";
80
81     my $xslt = new XML::LibXSLT;
82
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);
86
87     $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
88                              \&ZOOM::IRSpy::Utils::xslt_strcmp);
89
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);
94
95     my $this = bless {
96         conn => $conn,
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
103                                 # called.
104         connections => undef,   # Filled in by initialise()
105         queue => undef,         # Filled in by initialise()
106         libxml => $libxml,
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,
112     }, $class;
113     $this->log("irspy", "starting up with database '$dbname'");
114
115     return $this;
116 }
117
118 # wrapper to read the IRSpy database name from environment variable / apache config
119 sub connect_to_registry {
120     my %args = @_;
121
122     # XXX: we could also handle her: user, password, elementSetName
123
124     my $database = $ENV{IRSpyDbName} || "localhost:8018/IR-Explain---1";
125
126     return $database;
127 }
128
129 sub log {
130     my $this = shift();
131     ZOOM::Log::log(@_);
132 }
133
134
135 sub find_targets {
136     my $this = shift();
137     my($query) = @_;
138
139     $this->{query} = $query;
140 }
141
142
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.
147 #
148 sub targets {
149     my $this = shift();
150     my(@targets) = @_;
151
152     $this->log("irspy", "setting explicit list of targets ",
153                join(", ", map { "'$_'" } @targets));
154     my @qlist;
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
161         }
162         push @qlist, cql_target($protocol, $host, $port, $db);
163     }
164
165     $this->{targets} = \@targets;
166     $this->{query} = join(" or ", @qlist);
167 }
168
169
170 # Also used by ZOOM::IRSpy::Record
171 sub _parse_target_string {
172     my($target) = @_;
173
174     my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
175     if (!defined $host) {
176         $port = 210;
177         ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
178         $target = irspy_make_identifier($protocol, $host, $port, $db);
179     }
180     die "$0: invalid target string '$target'"
181         if !defined $host;
182
183     return ($protocol, $host, $port, $db, $target);
184 }
185
186
187 sub restrict_modulo {
188     my $this = shift();
189     my($n, $i) = @_;
190
191     $this->{modn} = $n;
192     $this->{modi} = $i;
193 }
194
195
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.
200 #
201 sub initialise {
202     my $this = shift();
203     my($tname) = @_;
204
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);
211
212     $this->{timeout} = "ZOOM::IRSpy::Test::$tname"->timeout();
213
214     my @targets;
215     my $targets = $this->{targets};
216     if (defined $targets) {
217         @targets = @$targets;
218         delete $this->{targets};
219     } else {
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};
224
225         foreach my $i (1 .. $rs->size()) {
226             push @targets, render_record($rs, $i-1, "id");
227         }
228     }
229
230     my $n = $this->{activeSetSize};
231     $n = @targets if $n == 0 || $n > @targets;
232
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;
239     }
240 }
241
242
243 sub _next_connection {
244     my $this = shift();
245
246     my $target;
247     my $n = $this->{modn};
248     my $i = $this->{modi};
249     if (!defined $n) {
250         $target = shift @{ $this->{queue} };
251         return undef if !defined $target;
252     } else {
253         while (1) {
254             $target = shift @{ $this->{queue} };
255             return undef if !defined $target;
256             my $h = _hash($target);
257             my $hmodn = $h % $n;
258             last if $hmodn == $i;
259             #$this->log("irspy", "'$target' hash $h % $n = $hmodn != $i");
260         }
261     }
262
263     die "oops -- target is undefined" if !defined $target;
264     return create ZOOM::IRSpy::Connection($this, $target, async => 1,
265                                           timeout => $this->{timeout});
266 }
267
268
269 sub _hash {
270     my($target) = @_;
271
272     my $n = 0;
273     foreach my $s (split //, $target) {
274         $n += ord($s);
275     }
276
277     return $n;
278 }
279
280
281 sub _irspy_to_zeerex {
282     my $this = shift();
283     my($conn) = @_;
284
285     my $save_xml = $ENV{IRSPY_SAVE_XML};
286     my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
287
288     if ($save_xml) {
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();
293         close FH;
294     }
295     my %params = ();
296     my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
297     if ($save_xml) {
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();
302         close FH;
303     }
304
305     return $result->documentElement();
306 }
307
308
309 sub _rewrite_irspy_record {
310     my $this = shift();
311     my($conn) = @_;
312
313     $conn->log("irspy", "rewriting XML record");
314     my $rec = $this->_irspy_to_zeerex($conn);
315
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"));
320
321     _rewrite_zeerex_record($this->{conn}, $rec);
322     $conn->log("irspy", "rewrote XML record");
323 }
324
325
326 my $_reliabilityField = {
327     reliability => [ reliability => 0,
328                       "Calculated reliability of server",
329                       "e:serverInfo/e:reliability" ],
330 };
331
332 sub _rewrite_zeerex_record {
333     my($conn, $rec, $oldid) = @_;
334
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 });
339
340     my $p = $conn->package();
341     $p->option(action => "specialUpdate");
342     my $xml = $rec->toString();
343     $p->option(record => $xml);
344     $p->send("update");
345     $p->destroy();
346
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);
353     }
354
355     $p = $conn->package();
356     $p->send("commit");
357     $p->destroy();
358     if (0) {
359         $xml =~ s/&/&amp/g;
360         $xml =~ s/</&lt;/g;
361         $xml =~ s/>/&gt;/g;
362         print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
363     }
364 }
365
366
367 sub _delete_record {
368     my($conn, $id) = @_;
369
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.
382
383     warn "$conn deleting record '$id'";
384
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();
389
390     my $p = $conn->package();
391     $p->option(action => "recordDelete");
392     $p->option(record => $xml);
393     $p->send("update");
394     $p->destroy();
395
396     $p = $conn->package();
397     $p->send("commit");
398     $p->destroy();
399 }
400
401
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.
412 #
413 # Invariants:
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
422 #       started.
423 #
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
428 #       the root test.
429 #
430 sub check {
431     my $this = shift();
432
433     my $topname = $this->{tree}->name();
434     my $timeout = $this->{timeout};
435     $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
436
437     my $nskipped = 0;
438     my @conn = @{ $this->{connections} };
439
440     my $nruns = 0;
441   ROUND_AND_ROUND_WE_GO:
442     while (1) {
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
452                   NEXT_TEST:
453                     my $address = $conn->option("current_test_address");
454                     my $nextaddr;
455                     if (!defined $address) {
456                         $nextaddr = "";
457                     } else {
458                         $conn->log("irspy_test",
459                                    "checking for next test after '$address'");
460                         $nextaddr = $this->_next_test($address);
461                     }
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;
470                         } else {
471                             $conn->destroy();
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");
477                         }
478                         next;
479                     }
480
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]);
494                     } else {
495                         $conn->log("irspy_task",
496                                    "no tasks added by new test $tname");
497                         goto NEXT_TEST;
498                     }
499                 }
500
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");
504                 $conn->next_task(0);
505                 $conn->current_task($task);
506                 $task->run();
507             }
508         }
509
510       NEXT_EVENT:
511         my $i0 = ZOOM::event(\@conn);
512         $this->log("irspy_event",
513                    "ZOOM_event(", scalar(@conn), " connections) = $i0");
514         if ($i0 < 1) {
515             my %messages = (
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()",
521                             );
522             my $message = $messages{$i0} || "ZOOM::event() returned $i0";
523             $this->log("irspy", $message);
524             last;
525         }
526
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;
532
533         my $task = $conn->current_task();
534         die "$conn has no current task for event $ev ($evstr)" if !$task;
535
536         my $res;
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(), $@);
542         } elsif ($@) {
543             die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
544         } else {
545             my $sub = $task->{cb}->{$ev};
546             if (!defined $sub) {
547                 $conn->log("irspy_unhandled", "event $ev ($evstr)");
548                 next;
549             }
550
551             $res = &$sub($conn, $task, $task->udata(), $ev);
552         }
553
554         if ($res == ZOOM::IRSpy::Status::OK) {
555             # Nothing to do -- life continues
556
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);
564
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);
571             $conn->next_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!")
575                     if $address eq "";
576                 my $node = $this->{tree}->select($address);
577                 my $skipcount = 0;
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();
584                     $skipcount++;
585                 }
586
587                 $conn->option(current_test_address => $node->address());
588                 $conn->log("irspy_test", "skipped $skipcount tests");
589                 $nskipped += $skipcount;
590             }
591
592         } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
593             $conn->log("irspy_test", "test skipped during task $task");
594             $conn->current_task(0);
595             $conn->next_task(0);
596             $nskipped++;
597
598         } else {
599             die "unknown callback return-value '$res'";
600         }
601     }
602
603     $this->log("irspy", "exiting main loop");
604
605     # Sanity checks: none of the following should ever happen
606     my $finished = 1;
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);
611         if (defined $next) {
612             $this->log("irspy",
613                        "$conn (in test '$test') has queued test '$next'");
614             $finished = 0;
615         }
616         if (my $task = $conn->current_task()) {
617             $this->log("irspy", "$conn still has an active task $task");
618             $finished = 0;
619         }
620         if (my $task = $conn->next_task()) {
621             $this->log("irspy", "$conn still has a queued task $task");
622             $finished = 0;
623         }
624         if (!$conn->is_idle()) {
625             $this->log("irspy",
626                        "$conn still has ZOOM-C level tasks queued: see below");
627             $finished = 0;
628         }
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");
633             $finished = 0;
634         }
635         if (!$conn->option("rewrote_record")) {
636             $this->log("irspy", "$conn did not rewrite its ZeeRex record");
637             $finished = 0;
638         }
639     }
640
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).
644     if (!$finished) {
645         if (++$nruns < 0) {
646             $this->log("irspy", "back into main loop, ${nruns}th time");
647             goto ROUND_AND_ROUND_WE_GO;
648         } else {
649             $this->log("irspy", "bailing after $nruns main-loop runs");
650         }
651     }
652
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);
658         $this->log("irspy",
659                    "$conn still has ZOOM-C level task queued: $ev ($evstr)")
660             if $ev != ZOOM::Event::ZEND;
661     }
662
663     return $nskipped;
664 }
665
666
667 # Exactly equivalent to ZOOM::event() except that it is tolerant to
668 # undefined values in the array being passed in.
669 #
670 sub __UNUSED_tolerant_ZOOM_event {
671     my($connref) = @_;
672
673     my(@conn, @map);
674     foreach my $i (0 .. @$connref-1) {
675         my $conn = $connref->[$i];
676         if (defined $conn) {
677             push @conn, $conn;
678             push @map, $i;
679         }
680     }
681
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";
686     return $res2;
687 }
688
689
690 sub _gather_tests {
691     my $this = shift();
692     my($tname, @ancestors) = @_;
693
694     die("$0: test-hierarchy loop detected: " .
695         join(" -> ", @ancestors, $tname))
696         if grep { $_ eq $tname } @ancestors;
697
698     my $slashSeperatedTname = $tname;
699     $slashSeperatedTname =~ s/::/\//g;
700     my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
701
702     eval {
703         require $fullName;
704     }; if ($@) {
705         $this->log("irspy", "couldn't require '$fullName': $@");
706         $this->log("warn", "can't load test '$tname': skipping",
707                    $@ =~ /^Can.t locate/ ? () : " ($@)");
708         return undef;
709     }
710
711     $this->log("irspy", "adding test '$tname'");
712     my @subnodes;
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;
716     }
717
718     return new ZOOM::IRSpy::Node($tname, @subnodes);
719 }
720
721
722 # These next three should arguably be Node methods
723 sub _next_test {
724     my $this = shift();
725     my($address, $omit_child) = @_;
726
727     # Try first child
728     if (!$omit_child) {
729         my $maybe = $address eq "" ? "0" : "$address:0";
730         return $maybe if $this->{tree}->select($maybe);
731     }
732
733     # The top-level node has no successor or parent
734     return undef if $address eq "";
735
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);
741
742     # This node is exhausted: try the parent's successor
743     return $this->_next_test(join(":", @components), 1)
744 }
745
746
747 sub _last_sibling_test {
748     my $this = shift();
749     my($address) = @_;
750
751     return undef
752         if !defined $this->_next_sibling_test($address);
753
754     my $nskipped = 0;
755     while (1) {
756         my $maybe = $this->_next_sibling_test($address);
757         last if !defined $maybe;
758         $nskipped++;
759         $address = $maybe;
760         $this->log("irspy", "skipping $nskipped tests to '$address'");
761     }
762
763     return ($address, $nskipped);
764 }
765
766
767 sub _next_sibling_test {
768     my $this = shift();
769     my($address) = @_;
770
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);
775     return undef;
776 }
777
778
779 =head1 SEE ALSO
780
781 ZOOM::IRSpy::Record,
782 ZOOM::IRSpy::Web,
783 ZOOM::IRSpy::Test,
784 ZOOM::IRSpy::Maintenance.
785
786 The ZOOM-Perl module,
787 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
788
789 The Zebra Database,
790 http://indexdata.com/zebra/
791
792 =head1 AUTHOR
793
794 Mike Taylor, E<lt>mike@indexdata.comE<gt>
795
796 =head1 COPYRIGHT AND LICENSE
797
798 Copyright (C) 2006 by Index Data ApS.
799
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.
803
804 =cut
805
806
807 1;