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