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