Factor IRSpy-independent _really_write_record() out of
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy.pm
1 # $Id: IRSpy.pm,v 1.42 2006-10-27 15:36:04 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     _really_rewrite_record($this->{conn}, $rec);
260 }
261
262
263 sub _really_rewrite_record {
264     my($conn, $rec) = @_;
265
266     my $p = $conn->package();
267     $p->option(action => "specialUpdate");
268     my $xml = $rec->toString();
269     $p->option(record => $xml);
270     $p->send("update");
271     $p->destroy();
272
273     $p = $conn->package();
274     $p->send("commit");
275     $p->destroy();
276     if (0) {
277         $xml =~ s/&/&amp/g;
278         $xml =~ s/</&lt;/g;
279         $xml =~ s/>/&gt;/g;
280         print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
281     }
282 }
283
284
285 # The approach: gather declarative information about test hierarchy,
286 # then go into a loop.  In the loop, we ensure that each connection is
287 # running a test, and within that test a task, until its list of tests
288 # is exhausted.  No individual test ever calls wait(): tests just queue
289 # up tasks and return immediately.  When the tasks are run (one at a
290 # time on each connection) they generate events, and it is these that
291 # are harvested by ZOOM::event().  Since each connection knows what
292 # task it is running, it can invoke the appropriate callbacks.
293 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
294 # loop how to continue.
295 #
296 # Invariants:
297 #       While a connection is running a task, its current_task()
298 #       points at the task structure.  When it finishes its task, 
299 #       next_task() is pointed at the next task to execute (if there
300 #       is one), and its current_task() is set to zero.  When the next
301 #       task is executed, the connection's next_task() is set to zero
302 #       and its current_task() pointed to the task structure.
303 #       current_task() and next_task() are both zero only when there
304 #       are no more queued tasks, which is when a new test is
305 #       started.
306 #
307 #       Each connection's current test is stored in its
308 #       "current_test_address" option.  The next test to execute is
309 #       calculated by walking the declarative tree of tests.  This
310 #       option begins empty; the "next test" after this is of course
311 #       the root test.
312 #
313 sub check {
314     my $this = shift();
315     my($tname) = @_;
316
317     $tname = "Main" if !defined $tname;
318     $this->{tree} = $this->_gather_tests($tname)
319         or die "No tests defined for '$tname'";
320     #$this->{tree}->print(0);
321     my $nskipped = 0;
322
323     my @conn = @{ $this->{connections} };
324
325     while (1) {
326         my @copy_conn = @conn;  # avoid alias problems after splice()
327         my $nconn = scalar(@copy_conn);
328         foreach my $i0 (0 .. $#copy_conn) {
329             my $conn = $copy_conn[$i0];
330             #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
331             if (!$conn->current_task()) {
332                 if (!$conn->next_task()) {
333                     # Out of tasks: we need a new test
334                   NEXT_TEST:
335                     my $address = $conn->option("current_test_address");
336                     my $nextaddr;
337                     if (!defined $address) {
338                         $nextaddr = "";
339                     } else {
340                         $this->log("irspy_test",
341                                    "checking for next test after '$address'");
342                         $nextaddr = $this->_next_test($address);
343                     }
344                     if (!defined $nextaddr) {
345                         $conn->log("irspy", "has no more tests: removing");
346                         splice @conn, $i0, 1;
347                         $this->_rewrite_record($conn);
348                         next;
349                     }
350
351                     my $node = $this->{tree}->select($nextaddr)
352                         or die "invalid nextaddr '$nextaddr'";
353                     $conn->option(current_test_address => $nextaddr);
354                     my $tname = $node->name();
355                     $conn->log("irspy_test",
356                                "starting test '$nextaddr' = $tname");
357                     my $tasks = $conn->tasks();
358                     my $oldcount = @$tasks;
359                     "ZOOM::IRSpy::Test::$tname"->start($conn);
360                     $tasks = $conn->tasks();
361                     if (@$tasks > $oldcount) {
362                         # Prepare to start the first of the newly added tasks
363                         $conn->next_task($tasks->[$oldcount]);
364                     } else {
365                         $conn->log("irspy_task",
366                                    "no tasks added by new test $tname");
367                         goto NEXT_TEST;
368                     }
369                 }
370
371                 my $task = $conn->next_task();
372                 die "no next task queued for $conn" if !defined $task;
373                 $conn->log("irspy_task", "preparing task $task");
374                 $conn->next_task(0);
375                 $conn->current_task($task);
376                 $task->run();
377             }
378
379             # Do we need to test $conn->is_idle()?  I don't think so!
380         }
381
382         my $i0 = ZOOM::event(\@conn);
383         $this->log("irspy_event",
384                    "ZOOM_event(", scalar(@conn), " connections) = $i0");
385         last if $i0 == 0 || $i0 == -3; # no events or no connections
386         my $conn = $conn[$i0-1];
387         my $ev = $conn->last_event();
388         my $evstr = ZOOM::event_str($ev);
389         $conn->log("irspy_event", "event $ev ($evstr)");
390
391         my $task = $conn->current_task();
392         die "$conn has no current task for event $ev ($evstr)" if !$task;
393         eval { $conn->_check() };
394         if ($@ &&
395             ($ev == ZOOM::Event::RECV_DATA ||
396              $ev == ZOOM::Event::RECV_APDU ||
397              $ev == ZOOM::Event::ZEND)) {
398             # An error in, say, a search response, becomes visible to
399             # ZOOM before the Receive Data event is sent and persists
400             # until after the End, which means that successive events
401             # each report the same error.  So we just ignore errors on
402             # "unimportant" events.  ### But this doesn't work for,
403             # say, a Connection Refused, as the only event that shows
404             # us this error is the End.
405             $conn->log("irspy_event", "ignoring error ",
406                        "on event $ev ($evstr): $@");
407             next;
408         }
409
410         my $res;
411         if ($@) {
412             my $sub = $task->{cb}->{exception};
413             die $@ if !defined $sub;
414             $res = &$sub($conn, $task, $task->udata(), $@);
415         } else {
416             my $sub = $task->{cb}->{$ev};
417             if (!defined $sub) {
418                 $conn->log("irspy_unhandled", "event $ev ($evstr)");
419                 next;
420             }
421
422             $res = &$sub($conn, $task, $task->udata(), $ev);
423         }
424
425         if ($res == ZOOM::IRSpy::Status::OK) {
426             # Nothing to do -- life continues
427
428         } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
429             my $task = $conn->current_task();
430             die "no task for TASK_DONE on $conn" if !$task;
431             die "next task already defined for $conn" if $conn->next_task();
432             $conn->log("irspy_task", "completed task $task");
433             $conn->next_task($task->{next});
434             $conn->current_task(0);
435
436         } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
437                  $res == ZOOM::IRSpy::Status::TEST_BAD) {
438             my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
439             $conn->log("irspy_task", "test ended during task $task ($x)");
440             $conn->log("irspy_test", "test completed ($x)");
441             $conn->current_task(0);
442             $conn->next_task(0);
443             if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
444                 my $address = $conn->option('current_test_address');
445                 ($address, my $n) = $this->_last_sibling_test($address);
446                 if (defined $address) {
447                     $conn->log("irspy_test", "skipped $n tests");
448                     $conn->option(current_test_address => $address);
449                     $nskipped += $n;
450                 }
451             }
452         } else {
453             die "unknown callback return-value '$res'";
454         }
455     }
456
457     $this->log("irspy", "exiting main loop");
458     return $nskipped;
459 }
460
461
462 sub _gather_tests {
463     my $this = shift();
464     my($tname, @ancestors) = @_;
465
466     die("$0: test-hierarchy loop detected: " .
467         join(" -> ", @ancestors, $tname))
468         if grep { $_ eq $tname } @ancestors;
469
470     my $slashSeperatedTname = $tname;
471     $slashSeperatedTname =~ s/::/\//g;
472     my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
473
474     eval {
475         ### This next line shouldn't be necessary, as we should
476         #   already be running in an environment where the test
477         #   modules are available -- otherwise, how did _this_ module
478         #   get loaded?  But it seems that for reasons I don't
479         #   understand we do sometimes (not always!) need this when
480         #   running under Apache.
481         use lib '/usr/local/src/cvs/irspy/lib';
482         require $fullName;
483         $this->log("irspy", "successfully required '$fullName'");
484     }; if ($@) {
485         $this->log("irspy", "couldn't require '$fullName': $@");
486         $this->log("warn", "can't load test '$tname': skipping",
487                    $@ =~ /^Can.t locate/ ? () : " ($@)");
488         return undef;
489     }
490
491     $this->log("irspy", "adding test '$tname'");
492     my @subnodes;
493     foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
494         my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
495         push @subnodes, $subtest if defined $subtest;
496     }
497
498     return new ZOOM::IRSpy::Node($tname, @subnodes);
499 }
500
501
502 # These next three should arguably be Node methods
503 sub _next_test {
504     my $this = shift();
505     my($address, $omit_child) = @_;
506
507     # Try first child
508     if (!$omit_child) {
509         my $maybe = $address eq "" ? "0" : "$address:0";
510         return $maybe if $this->{tree}->select($maybe);
511     }
512
513     # The top-level node has no successor or parent
514     return undef if $address eq "";
515
516     # Try next sibling child
517     my @components = split /:/, $address;
518     my $last = pop @components;
519     my $maybe = join(":", @components, $last+1);
520     return $maybe if $this->{tree}->select($maybe);
521
522     # This node is exhausted: try the parent's successor
523     return $this->_next_test(join(":", @components), 1)
524 }
525
526
527 sub _last_sibling_test {
528     my $this = shift();
529     my($address) = @_;
530
531     return undef
532         if !defined $this->_next_sibling_test($address);
533
534     my $nskipped = 0;
535     while (1) {
536         my $maybe = $this->_next_sibling_test($address);
537         last if !defined $maybe;
538         $nskipped++;
539         $this->log("irspy", "skipping $nskipped tests to '$address'");
540         $address = $maybe;
541     }
542
543     return ($address, $nskipped);
544 }
545
546
547 sub _next_sibling_test {
548     my $this = shift();
549     my($address) = @_;
550
551     my @components = split /:/, $address;
552     my $last = pop @components;
553     my $maybe = join(":", @components, $last+1);
554     return $maybe if $this->{tree}->select($maybe);
555     return undef;
556 }
557
558
559 # Utility functions follow, exported for use of web UI
560
561 # I can't -- just can't, can't, can't -- believe that this function
562 # isn't provided by one of the core XML modules.  But the evidence all
563 # says that it's not: among other things, XML::Generator and
564 # Template::Plugin both roll their own.  So I will do likewise.  D'oh!
565 #
566 sub xml_encode {
567     my ($text) = @_;
568     $text =~ s/&/&amp;/g;
569     $text =~ s/</&lt;/g;
570     $text =~ s/>/&gt;/g;
571     $text =~ s/['']/&apos;/g;
572     $text =~ s/[""]/&quot;/g;
573     return $text;
574 }
575
576
577 sub irspy_xpath_context {
578     my($zoom_record) = @_;
579
580     my $xml = $zoom_record->render();
581     my $parser = new XML::LibXML();
582     my $doc = $parser->parse_string($xml);
583     my $root = $doc->getDocumentElement();
584     my $xc = XML::LibXML::XPathContext->new($root);
585     $xc->registerNs(e => 'http://explain.z3950.org/dtd/2.0/');
586     $xc->registerNs(i => $irspy_ns);
587     return $xc;
588 }
589
590
591 =head1 SEE ALSO
592
593 ZOOM::IRSpy::Record,
594 ZOOM::IRSpy::Web,
595 ZOOM::IRSpy::Test,
596 ZOOM::IRSpy::Maintenance.
597
598 The ZOOM-Perl module,
599 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
600
601 The Zebra Database,
602 http://indexdata.com/zebra/
603
604 =head1 AUTHOR
605
606 Mike Taylor, E<lt>mike@indexdata.comE<gt>
607
608 =head1 COPYRIGHT AND LICENSE
609
610 Copyright (C) 2006 by Index Data ApS.
611
612 This library is free software; you can redistribute it and/or modify
613 it under the same terms as Perl itself, either Perl version 5.8.7 or,
614 at your option, any later version of Perl 5 you may have available.
615
616 =cut
617
618
619 1;