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