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