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