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