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