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