Import calc_reliability_stats() and modify_xml_document();
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy.pm
1 # $Id: IRSpy.pm,v 1.90 2008-07-16 11:42:13 mike Exp $
2
3 package ZOOM::IRSpy;
4
5 use 5.008;
6 use strict;
7 use warnings;
8
9 use Data::Dumper;               # For debugging only
10 use File::Basename;
11 use XML::LibXSLT;
12 use XML::LibXML;
13 use XML::LibXML::XPathContext;
14 use ZOOM;
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
22                           modify_xml_document);
23
24 our @ISA = qw();
25 our $VERSION = '1.01';
26 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
27
28
29 # Enumeration for callback functions to return
30 package ZOOM::IRSpy::Status;
31 sub OK { 29 }                   # No problems, task is still progressing
32 sub TASK_DONE { 18 }            # Task is complete, next task should begin
33 sub TEST_GOOD { 8 }             # Whole test is complete, and succeeded
34 sub TEST_BAD { 31 }             # Whole test is complete, and failed
35 sub TEST_SKIPPED { 12 }         # Test couldn't be run
36 package ZOOM::IRSpy;
37
38
39 =head1 NAME
40
41 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
42
43 =head1 SYNOPSIS
44
45  use ZOOM::IRSpy;
46  $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
47  $spy->targets(@targets);
48  $spy->initialise("Main");
49  $res = $spy->check();
50
51 =head1 DESCRIPTION
52
53 This module exists to implement the IRspy program, which discovers,
54 analyses and monitors IR servers implementing the Z39.50 and SRU/W
55 protocols.  It is a successor to the ZSpy program.
56
57 =cut
58
59 BEGIN {
60     ZOOM::Log::mask_str("irspy");
61     ZOOM::Log::mask_str("irspy_debug");
62     ZOOM::Log::mask_str("irspy_event");
63     ZOOM::Log::mask_str("irspy_unhandled");
64     ZOOM::Log::mask_str("irspy_test");
65     ZOOM::Log::mask_str("irspy_task");
66 }
67
68 sub new {
69     my $class = shift();
70     my($dbname, $user, $password, $activeSetSize) = @_;
71
72     my @options;
73     push @options, (user => $user, password => $password)
74         if defined $user;
75
76     my $conn = new ZOOM::Connection($dbname, 0, @options)
77         or die "$0: can't connection to IRSpy database 'dbname'";
78
79     my $xslt = new XML::LibXSLT;
80
81     $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
82                              \&ZOOM::IRSpy::Utils::xslt_strcmp);
83
84     my $libxml = new XML::LibXML;
85     my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
86     my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
87
88     my $this = bless {
89         conn => $conn,
90         query => "cql.allRecords=1", # unless overridden
91         modn => undef,          # Filled in by restrict_modulo()
92         modi => undef,          # Filled in by restrict_modulo()
93         targets => undef,       # Filled in later if targets() is
94                                 # called; used only to keep state from
95                                 # targets() until initialise() is
96                                 # called.
97         connections => undef,   # Filled in by initialise()
98         queue => undef,         # Filled in by initialise()
99         libxml => $libxml,
100         irspy_to_zeerex_style => $irspy_to_zeerex_style,
101         test => undef,          # Filled in by initialise()
102         timeout => undef,       # Filled in by initialise()
103         tests => undef,         # Tree of tests to be executed
104         activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
105     }, $class;
106     $this->log("irspy", "starting up with database '$dbname'");
107
108     return $this;
109 }
110
111
112 sub log {
113     my $this = shift();
114     ZOOM::Log::log(@_);
115 }
116
117
118 sub find_targets {
119     my $this = shift();
120     my($query) = @_;
121
122     $this->{query} = $query;
123 }
124
125
126 # Explicitly nominate a set of targets to check, overriding the
127 # default which is to re-check everything in the database.  Each
128 # target already in the database results in the existing record being
129 # updated; each new target causes a new record to be added.
130 #
131 sub targets {
132     my $this = shift();
133     my(@targets) = @_;
134
135     $this->log("irspy", "setting explicit list of targets ",
136                join(", ", map { "'$_'" } @targets));
137     my @qlist;
138     foreach my $target (@targets) {
139         my($protocol, $host, $port, $db, $newtarget) =
140             _parse_target_string($target);
141         if ($newtarget ne $target) {
142             $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
143             $target = $newtarget; # This is written through the ref
144         }
145         push @qlist, cql_target($protocol, $host, $port, $db);
146     }
147
148     $this->{targets} = \@targets;
149     $this->{query} = join(" or ", @qlist);
150 }
151
152
153 # Also used by ZOOM::IRSpy::Record
154 sub _parse_target_string {
155     my($target) = @_;
156
157     my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
158     if (!defined $host) {
159         $port = 210;
160         ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
161         $target = irspy_make_identifier($protocol, $host, $port, $db);
162     }
163     die "$0: invalid target string '$target'"
164         if !defined $host;
165
166     return ($protocol, $host, $port, $db, $target);
167 }
168
169
170 sub restrict_modulo {
171     my $this = shift();
172     my($n, $i) = @_;
173
174     $this->{modn} = $n;
175     $this->{modi} = $i;
176 }
177
178
179 # Records must be fetched for all records satisfying $this->{query} If
180 # $this->{targets} is already set (i.e. a specific list of targets to
181 # check was specified by a call to targets()), then new, empty records
182 # will be made for any targets that are not already in the database.
183 #
184 sub initialise {
185     my $this = shift();
186     my($tname) = @_;
187
188     $tname = "Main" if !defined $tname;
189     $this->{test} = $tname;
190     $this->{tree} = $this->_gather_tests($tname)
191         or die "No tests defined for '$tname'";
192     $this->{tree}->resolve();
193     #$this->{tree}->print(0);
194
195     $this->{timeout} = "ZOOM::IRSpy::Test::$tname"->timeout();
196
197     my @targets;
198     my $targets = $this->{targets};
199     if (defined $targets) {
200         @targets = @$targets;
201         delete $this->{targets};
202     } else {
203         my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
204         $this->log("irspy", "'", $this->{query}, "' found ",
205                    $rs->size(), " target records");
206         delete $this->{query};
207
208         foreach my $i (1 .. $rs->size()) {
209             push @targets, render_record($rs, $i-1, "id");
210         }
211     }
212
213     my $n = $this->{activeSetSize};
214     $n = @targets if $n == 0 || $n > @targets;
215
216     $this->{queue} = \@targets;
217     $this->{connections} = [];
218     while (@{ $this->{connections} } < $n) {
219         my $conn = $this->_next_connection();
220         last if !defined $conn;
221         push @{ $this->{connections} }, $conn;
222     }
223 }
224
225
226 sub _next_connection {
227     my $this = shift();
228
229     my $target;
230     my $n = $this->{modn};
231     my $i = $this->{modi};
232     if (!defined $n) {
233         $target = shift @{ $this->{queue} };
234         return undef if !defined $target;
235     } else {
236         while (1) {
237             $target = shift @{ $this->{queue} };
238             return undef if !defined $target;
239             my $h = _hash($target);
240             my $hmodn = $h % $n;
241             last if $hmodn == $i;
242             #$this->log("irspy", "'$target' hash $h % $n = $hmodn != $i");
243         }
244     }
245
246     die "oops -- target is undefined" if !defined $target;
247     return create ZOOM::IRSpy::Connection($this, $target, async => 1,
248                                           timeout => $this->{timeout});
249 }
250
251
252 sub _hash {
253     my($target) = @_;
254
255     my $n = 0;
256     foreach my $s (split //, $target) {
257         $n += ord($s);
258     }
259
260     return $n;
261 }
262
263
264 sub _irspy_to_zeerex {
265     my $this = shift();
266     my($conn) = @_;
267
268     my $save_xml = $ENV{IRSPY_SAVE_XML};
269     my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
270
271     if ($save_xml) {
272         unlink('/tmp/irspy_orig.xml');
273         open FH, '>/tmp/irspy_orig.xml'
274             or die "can't write irspy_orig.xml: $!";
275         print FH $irspy_doc->toString();
276         close FH;
277     }
278     my %params = ();
279     my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
280     if ($save_xml) {
281         unlink('/tmp/irspy_transformed.xml');
282         open FH, '>/tmp/irspy_transformed.xml'
283             or die "can't write irspy_transformed.xml: $!";
284         print FH $result->toString();
285         close FH;
286     }
287
288     return $result->documentElement();
289 }
290
291
292 sub _rewrite_irspy_record {
293     my $this = shift();
294     my($conn) = @_;
295
296     $conn->log("irspy", "rewriting XML record");
297     my $rec = $this->_irspy_to_zeerex($conn);
298
299     # Since IRSpy can run for a long time between writes back to the
300     # database, it's quite possible for the server to have closed the
301     # connection as idle.  So re-establish it if necessary.
302     $this->{conn}->connect($conn->option("host"));
303
304     _rewrite_zeerex_record($this->{conn}, $rec);
305     $conn->log("irspy", "rewrote XML record");
306 }
307
308
309 my $_reliabilityField = {
310     reliability => [ reliability => 0,
311                       "Calculated reliability of server",
312                       "e:metaInfo/i:reliability" ],
313 };
314
315 sub _rewrite_zeerex_record {
316     my($conn, $rec, $oldid) = @_;
317
318     # Add reliability score
319     my $xc = irspy_xpath_context($rec);
320     my($nok, $nall, $percent) = calc_reliability_stats($xc);
321     modify_xml_document($xc, $_reliabilityField, { reliability => $percent });
322
323     my $p = $conn->package();
324     $p->option(action => "specialUpdate");
325     my $xml = $rec->toString();
326     $p->option(record => $xml);
327     $p->send("update");
328     $p->destroy();
329
330     # This is the expression in the ID-making stylesheet
331     # ../../zebra/zeerex2id.xsl
332     my $id = irspy_record2identifier($xc);
333     if (defined $oldid && $id ne $oldid) {
334         warn "IDs differ (old='$oldid' new='$id')";
335         _delete_record($conn, $oldid);
336     }
337
338     $p = $conn->package();
339     $p->send("commit");
340     $p->destroy();
341     if (0) {
342         $xml =~ s/&/&amp/g;
343         $xml =~ s/</&lt;/g;
344         $xml =~ s/>/&gt;/g;
345         print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
346     }
347 }
348
349
350 sub _delete_record {
351     my($conn, $id) = @_;
352
353     # We can't delete records using recordIdOpaque, since character
354     # sets are handled differently here in extended services from how
355     # they are used in the Alvis filter's record-parsing, and so
356     # non-ASCII characters come out differently in the two contexts.
357     # Instead, we must send a record whose contents indicate the ID of
358     # that which we wish to delete.  There are two ways, both
359     # unsatisfactory: we could either fetch the actual record them
360     # resubmit it in the deletion request (which wastes a search and a
361     # fetch) or we could build a record by hand from the parsed-out
362     # components (which is error-prone and which I am not 100% certain
363     # will work since the other contents of the record will be
364     # different).  The former evil seems to be the lesser.
365
366     warn "$conn deleting record '$id'";
367
368     my $rs = $conn->search(new ZOOM::Query::CQL(cql_target($id)));
369     die "no such ID '$id'" if $rs->size() == 0;
370     my $rec = $rs->record(0);
371     my $xml = $rec->render();
372
373     my $p = $conn->package();
374     $p->option(action => "recordDelete");
375     $p->option(record => $xml);
376     $p->send("update");
377     $p->destroy();
378
379     $p = $conn->package();
380     $p->send("commit");
381     $p->destroy();
382 }
383
384
385 # The approach: gather declarative information about test hierarchy,
386 # then go into a loop.  In the loop, we ensure that each connection is
387 # running a test, and within that test a task, until its list of tests
388 # is exhausted.  No individual test ever calls wait(): tests just queue
389 # up tasks and return immediately.  When the tasks are run (one at a
390 # time on each connection) they generate events, and it is these that
391 # are harvested by ZOOM::event().  Since each connection knows what
392 # task it is running, it can invoke the appropriate callbacks.
393 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
394 # loop how to continue.
395 #
396 # Invariants:
397 #       While a connection is running a task, its current_task()
398 #       points at the task structure.  When it finishes its task, 
399 #       next_task() is pointed at the next task to execute (if there
400 #       is one), and its current_task() is set to zero.  When the next
401 #       task is executed, the connection's next_task() is set to zero
402 #       and its current_task() pointed to the task structure.
403 #       current_task() and next_task() are both zero only when there
404 #       are no more queued tasks, which is when a new test is
405 #       started.
406 #
407 #       Each connection's current test is stored in its
408 #       "current_test_address" option.  The next test to execute is
409 #       calculated by walking the declarative tree of tests.  This
410 #       option begins empty; the "next test" after this is of course
411 #       the root test.
412 #
413 sub check {
414     my $this = shift();
415
416     my $topname = $this->{tree}->name();
417     my $timeout = $this->{timeout};
418     $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
419
420     my $nskipped = 0;
421     my @conn = @{ $this->{connections} };
422
423     my $nruns = 0;
424   ROUND_AND_ROUND_WE_GO:
425     while (1) {
426         my @copy_conn = @conn;  # avoid alias problems after splice()
427         my $nconn = scalar(@copy_conn);
428         foreach my $i0 (0 .. $#copy_conn) {
429             my $conn = $copy_conn[$i0];
430             #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
431             next if !defined $conn;
432             if (!$conn->current_task()) {
433                 if (!$conn->next_task()) {
434                     # Out of tasks: we need a new test
435                   NEXT_TEST:
436                     my $address = $conn->option("current_test_address");
437                     my $nextaddr;
438                     if (!defined $address) {
439                         $nextaddr = "";
440                     } else {
441                         $conn->log("irspy_test",
442                                    "checking for next test after '$address'");
443                         $nextaddr = $this->_next_test($address);
444                     }
445                     if (!defined $nextaddr) {
446                         $conn->log("irspy", "has no more tests: removing");
447                         $this->_rewrite_irspy_record($conn);
448                         $conn->option(rewrote_record => 1);
449                         my $newconn = $this->_next_connection();
450                         if (!defined $newconn) {
451                             # Do not destroy: needed for later sanity checks
452                             splice @conn, $i0, 1;
453                         } else {
454                             $conn->destroy();
455                             $conn[$i0] = $newconn;
456                             $conn[$i0]->option(current_test_address => "");
457                             $conn[$i0]->log("irspy", "entering active pool - ",
458                                             scalar(@{ $this->{queue} }),
459                                             " targets remain in queue");
460                         }
461                         next;
462                     }
463
464                     my $node = $this->{tree}->select($nextaddr)
465                         or die "invalid nextaddr '$nextaddr'";
466                     $conn->option(current_test_address => $nextaddr);
467                     my $tname = $node->name();
468                     $conn->log("irspy_test",
469                                "starting test '$nextaddr' = $tname");
470                     my $tasks = $conn->tasks();
471                     my $oldcount = @$tasks;
472                     "ZOOM::IRSpy::Test::$tname"->start($conn);
473                     $tasks = $conn->tasks();
474                     if (@$tasks > $oldcount) {
475                         # Prepare to start the first of the newly added tasks
476                         $conn->next_task($tasks->[$oldcount]);
477                     } else {
478                         $conn->log("irspy_task",
479                                    "no tasks added by new test $tname");
480                         goto NEXT_TEST;
481                     }
482                 }
483
484                 my $task = $conn->next_task();
485                 die "no next task queued for $conn" if !defined $task;
486                 $conn->log("irspy_task", "preparing task $task");
487                 $conn->next_task(0);
488                 $conn->current_task($task);
489                 $task->run();
490             }
491         }
492
493       NEXT_EVENT:
494         my $i0 = ZOOM::event(\@conn);
495         $this->log("irspy_event",
496                    "ZOOM_event(", scalar(@conn), " connections) = $i0");
497         if ($i0 < 1) {
498             my %messages = (
499                             0 => "no events remain",
500                             -1 => "ZOOM::event() argument not a reference",
501                             -2 => "ZOOM::event() reference not an array",
502                             -3 => "no connections remain",
503                             -4 => "too many connections for ZOOM::event()",
504                             );
505             my $message = $messages{$i0} || "ZOOM::event() returned $i0";
506             $this->log("irspy", $message);
507             last;
508         }
509
510         my $conn = $conn[$i0-1];
511         my $ev = $conn->last_event();
512         my $evstr = ZOOM::event_str($ev);
513         $conn->log("irspy_event", "event $ev ($evstr)");
514         goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
515
516         my $task = $conn->current_task();
517         die "$conn has no current task for event $ev ($evstr)" if !$task;
518
519         my $res;
520         eval { $conn->check() };
521         if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
522             my $sub = $task->{cb}->{exception};
523             die $@ if !defined $sub;
524             $res = &$sub($conn, $task, $task->udata(), $@);
525         } elsif ($@) {
526             die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
527         } else {
528             my $sub = $task->{cb}->{$ev};
529             if (!defined $sub) {
530                 $conn->log("irspy_unhandled", "event $ev ($evstr)");
531                 next;
532             }
533
534             $res = &$sub($conn, $task, $task->udata(), $ev);
535         }
536
537         if ($res == ZOOM::IRSpy::Status::OK) {
538             # Nothing to do -- life continues
539
540         } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
541             my $task = $conn->current_task();
542             die "no task for TASK_DONE on $conn" if !$task;
543             die "next task already defined for $conn" if $conn->next_task();
544             $conn->log("irspy_task", "completed task $task");
545             $conn->next_task($task->{next});
546             $conn->current_task(0);
547
548         } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
549                  $res == ZOOM::IRSpy::Status::TEST_BAD) {
550             my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
551             $conn->log("irspy_task", "test ended during task $task ($x)");
552             $conn->log("irspy_test", "test completed ($x)");
553             $conn->current_task(0);
554             $conn->next_task(0);
555             if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
556                 my $address = $conn->option('current_test_address');
557                 $conn->log("irspy", "top-level test failed!")
558                     if $address eq "";
559                 my $node = $this->{tree}->select($address);
560                 my $skipcount = 0;
561                 while (defined $node->next() &&
562                        length($node->next()->address()) >= length($address)) {
563                     $conn->log("irspy_debug", "skipping from '",
564                                $node->address(), "' to '",
565                                $node->next()->address(), "'");
566                     $node = $node->next();
567                     $skipcount++;
568                 }
569
570                 $conn->option(current_test_address => $node->address());
571                 $conn->log("irspy_test", "skipped $skipcount tests");
572                 $nskipped += $skipcount;
573             }
574
575         } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
576             $conn->log("irspy_test", "test skipped during task $task");
577             $conn->current_task(0);
578             $conn->next_task(0);
579             $nskipped++;
580
581         } else {
582             die "unknown callback return-value '$res'";
583         }
584     }
585
586     $this->log("irspy", "exiting main loop");
587
588     # Sanity checks: none of the following should ever happen
589     my $finished = 1;
590     $this->log("irspy", "performing end-of-run sanity-checks");
591     foreach my $conn (@conn) {
592         my $test = $conn->option("current_test_address");
593         my $next = $this->_next_test($test);
594         if (defined $next) {
595             $this->log("irspy",
596                        "$conn (in test '$test') has queued test '$next'");
597             $finished = 0;
598         }
599         if (my $task = $conn->current_task()) {
600             $this->log("irspy", "$conn still has an active task $task");
601             $finished = 0;
602         }
603         if (my $task = $conn->next_task()) {
604             $this->log("irspy", "$conn still has a queued task $task");
605             $finished = 0;
606         }
607         if (!$conn->is_idle()) {
608             $this->log("irspy",
609                        "$conn still has ZOOM-C level tasks queued: see below");
610             $finished = 0;
611         }
612         my $ev = $conn->peek_event();
613         if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
614             my $evstr = ZOOM::event_str($ev);
615             $this->log("irspy", "$conn has event $ev ($evstr) waiting");
616             $finished = 0;
617         }
618         if (!$conn->option("rewrote_record")) {
619             $this->log("irspy", "$conn did not rewrite its ZeeRex record");
620             $finished = 0;
621         }
622     }
623
624     # This really shouldn't be necessary, and in practice it rarely
625     # helps, but it's belt and braces.  (For now, we don't do this
626     # hence the zero in the $nruns check).
627     if (!$finished) {
628         if (++$nruns < 0) {
629             $this->log("irspy", "back into main loop, ${nruns}th time");
630             goto ROUND_AND_ROUND_WE_GO;
631         } else {
632             $this->log("irspy", "bailing after $nruns main-loop runs");
633         }
634     }
635
636     # This shouldn't happen emit anything either:
637     while ((my $i1 = ZOOM::event(\@conn)) > 0) {
638         my $conn = $conn[$i1-1];
639         my $ev = $conn->last_event();
640         my $evstr = ZOOM::event_str($ev);
641         $this->log("irspy",
642                    "$conn still has ZOOM-C level task queued: $ev ($evstr)")
643             if $ev != ZOOM::Event::ZEND;
644     }
645
646     return $nskipped;
647 }
648
649
650 # Exactly equivalent to ZOOM::event() except that it is tolerant to
651 # undefined values in the array being passed in.
652 #
653 sub __UNUSED_tolerant_ZOOM_event {
654     my($connref) = @_;
655
656     my(@conn, @map);
657     foreach my $i (0 .. @$connref-1) {
658         my $conn = $connref->[$i];
659         if (defined $conn) {
660             push @conn, $conn;
661             push @map, $i;
662         }
663     }
664
665     my $res = ZOOM::event(\@conn);
666     return $res if $res <= 0;
667     my $res2 = $map[$res-1] + 1;
668     print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
669     return $res2;
670 }
671
672
673 sub _gather_tests {
674     my $this = shift();
675     my($tname, @ancestors) = @_;
676
677     die("$0: test-hierarchy loop detected: " .
678         join(" -> ", @ancestors, $tname))
679         if grep { $_ eq $tname } @ancestors;
680
681     my $slashSeperatedTname = $tname;
682     $slashSeperatedTname =~ s/::/\//g;
683     my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
684
685     eval {
686         require $fullName;
687     }; if ($@) {
688         $this->log("irspy", "couldn't require '$fullName': $@");
689         $this->log("warn", "can't load test '$tname': skipping",
690                    $@ =~ /^Can.t locate/ ? () : " ($@)");
691         return undef;
692     }
693
694     $this->log("irspy", "adding test '$tname'");
695     my @subnodes;
696     foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
697         my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
698         push @subnodes, $subtest if defined $subtest;
699     }
700
701     return new ZOOM::IRSpy::Node($tname, @subnodes);
702 }
703
704
705 # These next three should arguably be Node methods
706 sub _next_test {
707     my $this = shift();
708     my($address, $omit_child) = @_;
709
710     # Try first child
711     if (!$omit_child) {
712         my $maybe = $address eq "" ? "0" : "$address:0";
713         return $maybe if $this->{tree}->select($maybe);
714     }
715
716     # The top-level node has no successor or parent
717     return undef if $address eq "";
718
719     # Try next sibling child
720     my @components = split /:/, $address;
721     my $last = pop @components;
722     my $maybe = join(":", @components, $last+1);
723     return $maybe if $this->{tree}->select($maybe);
724
725     # This node is exhausted: try the parent's successor
726     return $this->_next_test(join(":", @components), 1)
727 }
728
729
730 sub _last_sibling_test {
731     my $this = shift();
732     my($address) = @_;
733
734     return undef
735         if !defined $this->_next_sibling_test($address);
736
737     my $nskipped = 0;
738     while (1) {
739         my $maybe = $this->_next_sibling_test($address);
740         last if !defined $maybe;
741         $nskipped++;
742         $address = $maybe;
743         $this->log("irspy", "skipping $nskipped tests to '$address'");
744     }
745
746     return ($address, $nskipped);
747 }
748
749
750 sub _next_sibling_test {
751     my $this = shift();
752     my($address) = @_;
753
754     my @components = split /:/, $address;
755     my $last = pop @components;
756     my $maybe = join(":", @components, $last+1);
757     return $maybe if $this->{tree}->select($maybe);
758     return undef;
759 }
760
761
762 =head1 SEE ALSO
763
764 ZOOM::IRSpy::Record,
765 ZOOM::IRSpy::Web,
766 ZOOM::IRSpy::Test,
767 ZOOM::IRSpy::Maintenance.
768
769 The ZOOM-Perl module,
770 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
771
772 The Zebra Database,
773 http://indexdata.com/zebra/
774
775 =head1 AUTHOR
776
777 Mike Taylor, E<lt>mike@indexdata.comE<gt>
778
779 =head1 COPYRIGHT AND LICENSE
780
781 Copyright (C) 2006 by Index Data ApS.
782
783 This library is free software; you can redistribute it and/or modify
784 it under the same terms as Perl itself, either Perl version 5.8.7 or,
785 at your option, any later version of Perl 5 you may have available.
786
787 =cut
788
789
790 1;