d01a9e833a41e2fd7c9e0e3af90e83b0755011e2
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy.pm
1 # $Id: IRSpy.pm,v 1.65 2007-02-23 13:14:13 mike Exp $
2
3 package ZOOM::IRSpy;
4
5 use 5.008;
6 use strict;
7 use warnings;
8
9 use Data::Dumper;               # For debugging only
10 use File::Basename;
11 use XML::LibXSLT;
12 use XML::LibXML;
13 use XML::LibXML::XPathContext;
14 use ZOOM;
15 use Net::Z3950::ZOOM 1.13;      # For the ZOOM version-check only
16 use ZOOM::IRSpy::Node;
17 use ZOOM::IRSpy::Connection;
18 use ZOOM::IRSpy::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 = shift();
250     my($conn, $save_xml) = @_;
251     my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
252
253     if ($save_xml) {
254         unlink('/tmp/irspy_orig.xml');
255         open FH, '>/tmp/irspy_orig.xml';
256         print FH $irspy_doc->toString();
257         close FH;
258     }
259     my %params = ();
260     my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
261     if ($save_xml) {
262         unlink('/tmp/irspy_transformed.xml');
263         open FH, '>/tmp/irspy_transformed.xml';
264         print FH $result->toString();
265         close FH;
266     }
267
268     return $result->documentElement();
269 }
270
271
272 sub _rewrite_record {
273     my $this = shift();
274     my($conn) = @_;
275
276     $conn->log("irspy", "rewriting XML record");
277     my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
278     _really_rewrite_record($this->{conn}, $rec);
279 }
280
281
282 sub _really_rewrite_record {
283     my($conn, $rec) = @_;
284
285     my $p = $conn->package();
286     $p->option(action => "specialUpdate");
287     my $xml = $rec->toString();
288     $p->option(record => $xml);
289     $p->send("update");
290     $p->destroy();
291
292     $p = $conn->package();
293     $p->send("commit");
294     $p->destroy();
295     if (0) {
296         $xml =~ s/&/&amp/g;
297         $xml =~ s/</&lt;/g;
298         $xml =~ s/>/&gt;/g;
299         print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
300     }
301 }
302
303
304 # The approach: gather declarative information about test hierarchy,
305 # then go into a loop.  In the loop, we ensure that each connection is
306 # running a test, and within that test a task, until its list of tests
307 # is exhausted.  No individual test ever calls wait(): tests just queue
308 # up tasks and return immediately.  When the tasks are run (one at a
309 # time on each connection) they generate events, and it is these that
310 # are harvested by ZOOM::event().  Since each connection knows what
311 # task it is running, it can invoke the appropriate callbacks.
312 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
313 # loop how to continue.
314 #
315 # Invariants:
316 #       While a connection is running a task, its current_task()
317 #       points at the task structure.  When it finishes its task, 
318 #       next_task() is pointed at the next task to execute (if there
319 #       is one), and its current_task() is set to zero.  When the next
320 #       task is executed, the connection's next_task() is set to zero
321 #       and its current_task() pointed to the task structure.
322 #       current_task() and next_task() are both zero only when there
323 #       are no more queued tasks, which is when a new test is
324 #       started.
325 #
326 #       Each connection's current test is stored in its
327 #       "current_test_address" option.  The next test to execute is
328 #       calculated by walking the declarative tree of tests.  This
329 #       option begins empty; the "next test" after this is of course
330 #       the root test.
331 #
332 sub check {
333     my $this = shift();
334     my($tname) = @_;
335
336     $tname = "Main" if !defined $tname;
337     $this->{tree} = $this->_gather_tests($tname)
338         or die "No tests defined for '$tname'";
339     #$this->{tree}->print(0);
340     my $nskipped = 0;
341
342     my @conn = @{ $this->{connections} };
343
344     my $nruns = 0;
345   ROUND_AND_ROUND_WE_GO:
346     while (1) {
347         my @copy_conn = @conn;  # avoid alias problems after splice()
348         my $nconn = scalar(@copy_conn);
349         foreach my $i0 (0 .. $#copy_conn) {
350             my $conn = $copy_conn[$i0];
351             #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
352             if (!$conn->current_task()) {
353                 if (!$conn->next_task()) {
354                     # Out of tasks: we need a new test
355                   NEXT_TEST:
356                     my $address = $conn->option("current_test_address");
357                     my $nextaddr;
358                     if (!defined $address) {
359                         $nextaddr = "";
360                     } else {
361                         $this->log("irspy_test",
362                                    "checking for next test after '$address'");
363                         $nextaddr = $this->_next_test($address);
364                     }
365                     if (!defined $nextaddr) {
366                         $conn->log("irspy", "has no more tests: removing");
367                         splice @conn, $i0, 1;
368                         $this->_rewrite_record($conn);
369                         $conn->option(rewrote_record => 1);
370                         next;
371                     }
372
373                     my $node = $this->{tree}->select($nextaddr)
374                         or die "invalid nextaddr '$nextaddr'";
375                     $conn->option(current_test_address => $nextaddr);
376                     my $tname = $node->name();
377                     $conn->log("irspy_test",
378                                "starting test '$nextaddr' = $tname");
379                     my $tasks = $conn->tasks();
380                     my $oldcount = @$tasks;
381                     "ZOOM::IRSpy::Test::$tname"->start($conn);
382                     $tasks = $conn->tasks();
383                     if (@$tasks > $oldcount) {
384                         # Prepare to start the first of the newly added tasks
385                         $conn->next_task($tasks->[$oldcount]);
386                     } else {
387                         $conn->log("irspy_task",
388                                    "no tasks added by new test $tname");
389                         goto NEXT_TEST;
390                     }
391                 }
392
393                 my $task = $conn->next_task();
394                 die "no next task queued for $conn" if !defined $task;
395                 $conn->log("irspy_task", "preparing task $task");
396                 $conn->next_task(0);
397                 $conn->current_task($task);
398                 $task->run();
399             }
400
401             # Do we need to test $conn->is_idle()?  I don't think so!
402         }
403
404         my $i0 = ZOOM::event(\@conn);
405         $this->log("irspy_event",
406                    "ZOOM_event(", scalar(@conn), " connections) = $i0");
407         if ($i0 < 1) {
408             my %messages = (
409                             0 => "no events remain",
410                             -1 => "ZOOM::event() argument not a reference",
411                             -2 => "ZOOM::event() reference not an array",
412                             -3 => "no connections remain",
413                             -4 => "too many connections for ZOOM::event()",
414                             );
415             my $message = $messages{$i0} || "ZOOM::event() returned $i0";
416             $this->log("irspy", $message);
417             last;
418         }
419
420         my $conn = $conn[$i0-1];
421         my $ev = $conn->last_event();
422         my $evstr = ZOOM::event_str($ev);
423         $conn->log("irspy_event", "event $ev ($evstr)");
424
425         my $task = $conn->current_task();
426         die "$conn has no current task for event $ev ($evstr)" if !$task;
427         eval { $conn->_check() };
428         if ($@ &&
429             ($ev == ZOOM::Event::RECV_DATA ||
430              $ev == ZOOM::Event::ZEND ||
431              ($ev == ZOOM::Event::RECV_APDU &&
432               !$task->isa("ZOOM::IRSpy::Task::Connect")))) {
433             # An error in, say, a search response, becomes visible to
434             # ZOOM before the Receive Data event is sent and persists
435             # until after the End, which means that successive events
436             # each report the same error.  So we just ignore errors on
437             # "unimportant" events.  We can also ignore errors on
438             # RECV_APDU in most cases, but since there is no RECV_INIT
439             # event, we need to avoid doing this if the task is
440             # Connect.  Yuck -- special cases.
441             # ### But this doesn't work for, say, a Connection Refused,
442             # as the only event that shows us this error is the ZEND.
443             $conn->log("irspy_event", "ignoring error ",
444                        "on event $ev ($evstr): $@");
445             next;
446         }
447
448         my $res;
449         if ($@) {
450             my $sub = $task->{cb}->{exception};
451             die $@ if !defined $sub;
452             $res = &$sub($conn, $task, $task->udata(), $@);
453         } else {
454             my $sub = $task->{cb}->{$ev};
455             if (!defined $sub) {
456                 $conn->log("irspy_unhandled", "event $ev ($evstr)");
457                 next;
458             }
459
460             $res = &$sub($conn, $task, $task->udata(), $ev);
461         }
462
463         if ($res == ZOOM::IRSpy::Status::OK) {
464             # Nothing to do -- life continues
465
466         } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
467             my $task = $conn->current_task();
468             die "no task for TASK_DONE on $conn" if !$task;
469             die "next task already defined for $conn" if $conn->next_task();
470             $conn->log("irspy_task", "completed task $task");
471             $conn->next_task($task->{next});
472             $conn->current_task(0);
473
474         } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
475                  $res == ZOOM::IRSpy::Status::TEST_BAD) {
476             my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
477             $conn->log("irspy_task", "test ended during task $task ($x)");
478             $conn->log("irspy_test", "test completed ($x)");
479             $conn->current_task(0);
480             $conn->next_task(0);
481             if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
482                 my $address = $conn->option('current_test_address');
483                 ($address, my $n) = $this->_last_sibling_test($address);
484                 if (defined $address) {
485                     $conn->log("irspy_test", "skipped $n tests");
486                     $conn->option(current_test_address => $address);
487                     $nskipped += $n;
488                 }
489             }
490
491         } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
492             $conn->log("irspy_test", "test skipped during task $task");
493             $conn->current_task(0);
494             $conn->next_task(0);
495             # I think that's all we need to do
496
497         } else {
498             die "unknown callback return-value '$res'";
499         }
500     }
501
502     $this->log("irspy", "exiting main loop");
503     # Sanity checks: none of the following should ever happen
504     my $finished = 1;
505     @conn = @{ $this->{connections} };
506     foreach my $conn (@conn) {
507         my $test = $conn->option("current_test_address");
508         my $next = $this->_next_test($test);
509         if (defined $next) {
510             $this->log("irspy",
511                        "$conn (in test '$test') has queued test '$next'");
512             $finished = 0;
513         }
514         if (my $task = $conn->current_task()) {
515             $this->log("irspy", "$conn still has an active task $task");
516             $finished = 0;
517         }
518         if (my $task = $conn->next_task()) {
519             $this->log("irspy", "$conn still has a queued task $task");
520             $finished = 0;
521         }
522         if (!$conn->is_idle()) {
523             $this->log("irspy",
524                        "$conn still has ZOOM-C level tasks queued: see below");
525             $finished = 0;
526         }
527         my $ev = $conn->peek_event();
528         if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
529             my $evstr = ZOOM::event_str($ev);
530             $this->log("irspy", "$conn has event $ev ($evstr) waiting");
531             $finished = 0;
532         }
533         if (!$conn->option("rewrote_record")) {
534             $this->log("irspy", "$conn did not rewrite its ZeeRex record");
535             $finished = 0;
536         }
537     }
538
539     # This really shouldn't be necessary, and in practice it rarely
540     # helps, but it's belt and braces.  (For now, we don't do this
541     # hence the zero in the $nruns check).
542     if (!$finished) {
543         if (++$nruns < 0) {
544             $this->log("irspy", "back into main loop, ${nruns}th time");
545             goto ROUND_AND_ROUND_WE_GO;
546         } else {
547             $this->log("irspy", "bailing after $nruns main-loop runs");
548         }
549     }
550
551     # This shouldn't happen emit anything either:
552     while ((my $i1 = ZOOM::event(\@conn)) > 0) {
553         my $conn = $conn[$i1-1];
554         my $ev = $conn->last_event();
555         my $evstr = ZOOM::event_str($ev);
556         $this->log("irspy",
557                    "$conn still has ZOOM-C level task queued: $ev ($evstr)")
558             if $ev != ZOOM::Event::ZEND;
559     }
560
561     return $nskipped;
562 }
563
564
565 sub _gather_tests {
566     my $this = shift();
567     my($tname, @ancestors) = @_;
568
569     die("$0: test-hierarchy loop detected: " .
570         join(" -> ", @ancestors, $tname))
571         if grep { $_ eq $tname } @ancestors;
572
573     my $slashSeperatedTname = $tname;
574     $slashSeperatedTname =~ s/::/\//g;
575     my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
576
577     eval {
578         require $fullName;
579         $this->log("irspy", "successfully required '$fullName'");
580     }; if ($@) {
581         $this->log("irspy", "couldn't require '$fullName': $@");
582         $this->log("warn", "can't load test '$tname': skipping",
583                    $@ =~ /^Can.t locate/ ? () : " ($@)");
584         return undef;
585     }
586
587     $this->log("irspy", "adding test '$tname'");
588     my @subnodes;
589     foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
590         my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
591         push @subnodes, $subtest if defined $subtest;
592     }
593
594     return new ZOOM::IRSpy::Node($tname, @subnodes);
595 }
596
597
598 # These next three should arguably be Node methods
599 sub _next_test {
600     my $this = shift();
601     my($address, $omit_child) = @_;
602
603     # Try first child
604     if (!$omit_child) {
605         my $maybe = $address eq "" ? "0" : "$address:0";
606         return $maybe if $this->{tree}->select($maybe);
607     }
608
609     # The top-level node has no successor or parent
610     return undef if $address eq "";
611
612     # Try next sibling child
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
618     # This node is exhausted: try the parent's successor
619     return $this->_next_test(join(":", @components), 1)
620 }
621
622
623 sub _last_sibling_test {
624     my $this = shift();
625     my($address) = @_;
626
627     return undef
628         if !defined $this->_next_sibling_test($address);
629
630     my $nskipped = 0;
631     while (1) {
632         my $maybe = $this->_next_sibling_test($address);
633         last if !defined $maybe;
634         $nskipped++;
635         $address = $maybe;
636         $this->log("irspy", "skipping $nskipped tests to '$address'");
637     }
638
639     return ($address, $nskipped);
640 }
641
642
643 sub _next_sibling_test {
644     my $this = shift();
645     my($address) = @_;
646
647     my @components = split /:/, $address;
648     my $last = pop @components;
649     my $maybe = join(":", @components, $last+1);
650     return $maybe if $this->{tree}->select($maybe);
651     return undef;
652 }
653
654
655 =head1 SEE ALSO
656
657 ZOOM::IRSpy::Record,
658 ZOOM::IRSpy::Web,
659 ZOOM::IRSpy::Test,
660 ZOOM::IRSpy::Maintenance.
661
662 The ZOOM-Perl module,
663 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
664
665 The Zebra Database,
666 http://indexdata.com/zebra/
667
668 =head1 AUTHOR
669
670 Mike Taylor, E<lt>mike@indexdata.comE<gt>
671
672 =head1 COPYRIGHT AND LICENSE
673
674 Copyright (C) 2006 by Index Data ApS.
675
676 This library is free software; you can redistribute it and/or modify
677 it under the same terms as Perl itself, either Perl version 5.8.7 or,
678 at your option, any later version of Perl 5 you may have available.
679
680 =cut
681
682
683 1;