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