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