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