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