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