Add resolve(), address(), parent(), previous(), next().
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy.pm
1 # $Id: IRSpy.pm,v 1.71 2007-02-27 14:51:10 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     $this->log("irspy", "'", $this->{query}, "' found ",
203                $rs->size(), " target records");
204     delete $this->{query};      # No longer needed at all
205     my $gatherTargets = !$this->{targets};
206     foreach my $i (1 .. $rs->size()) {
207         my $target = _render_record($rs, $i-1, "id");
208         my $zeerex = _render_record($rs, $i-1, "zeerex");
209         #print STDERR "making '$target' record with '$zeerex'\n";
210         $target2record{lc($target)} =
211             new ZOOM::IRSpy::Record($this, $target, $zeerex);
212         push @{ $this->{targets} }, $target
213             if $gatherTargets;
214     }
215
216     # Make records for targets not previously in the database
217     foreach my $target (keys %target2record) {
218         my $record = $target2record{$target};
219         if (!defined $record) {
220             $this->log("irspy_debug", "made new record for '$target'");
221             $target2record{$target} = new ZOOM::IRSpy::Record($this, $target);
222         } else {
223             $this->log("irspy_debug", "using existing record for '$target'");
224         }
225     }
226
227     my @connections;
228     foreach my $target (@{ $this->{targets} }) {
229         my $conn = create ZOOM::IRSpy::Connection($this, async => 1);
230         $conn->option(host => $target);
231         my $record = delete $target2record{lc($target)};
232         $conn->record($record);
233         push @connections, $conn;
234     }
235     die("remaining target2record = { " .
236         join(", ", map { "$_ ->'" . $target2record{$_}. "'" }
237              sort keys %target2record) . " }")
238         if %target2record;
239
240     $this->{connections} = \@connections;
241     delete $this->{targets};    # The information is now in {connections}
242 }
243
244
245 sub _render_record {
246     my($rs, $which, $elementSetName) = @_;
247
248     # There is a slight race condition here on the element-set name,
249     # but it shouldn't be a problem as this is (currently) only called
250     # from parts of the program that run single-threaded.
251     my $old = $rs->option(elementSetName => $elementSetName);
252     my $rec = $rs->record($which);
253     $rs->option(elementSetName => $old);
254
255     return $rec->render();
256 }
257
258
259 sub _irspy_to_zeerex {
260     my $this = shift();
261     my($conn, $save_xml) = @_;
262     my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
263
264     if ($save_xml) {
265         unlink('/tmp/irspy_orig.xml');
266         open FH, '>/tmp/irspy_orig.xml'
267             or die "can't write irspy_orig.xml: $!";
268         print FH $irspy_doc->toString();
269         close FH;
270     }
271     my %params = ();
272     my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
273     if ($save_xml) {
274         unlink('/tmp/irspy_transformed.xml');
275         open FH, '>/tmp/irspy_transformed.xml'
276             or die "can't write irspy_transformed.xml: $!";
277         print FH $result->toString();
278         close FH;
279     }
280
281     return $result->documentElement();
282 }
283
284
285 sub _rewrite_record {
286     my $this = shift();
287     my($conn) = @_;
288
289     $conn->log("irspy", "rewriting XML record");
290     my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
291     _really_rewrite_record($this->{conn}, $rec);
292 }
293
294
295 sub _really_rewrite_record {
296     my($conn, $rec) = @_;
297
298     my $p = $conn->package();
299     $p->option(action => "specialUpdate");
300     my $xml = $rec->toString();
301     $p->option(record => $xml);
302     $p->send("update");
303     $p->destroy();
304
305     $p = $conn->package();
306     $p->send("commit");
307     $p->destroy();
308     if (0) {
309         $xml =~ s/&/&amp/g;
310         $xml =~ s/</&lt;/g;
311         $xml =~ s/>/&gt;/g;
312         print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
313     }
314 }
315
316
317 # The approach: gather declarative information about test hierarchy,
318 # then go into a loop.  In the loop, we ensure that each connection is
319 # running a test, and within that test a task, until its list of tests
320 # is exhausted.  No individual test ever calls wait(): tests just queue
321 # up tasks and return immediately.  When the tasks are run (one at a
322 # time on each connection) they generate events, and it is these that
323 # are harvested by ZOOM::event().  Since each connection knows what
324 # task it is running, it can invoke the appropriate callbacks.
325 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
326 # loop how to continue.
327 #
328 # Invariants:
329 #       While a connection is running a task, its current_task()
330 #       points at the task structure.  When it finishes its task, 
331 #       next_task() is pointed at the next task to execute (if there
332 #       is one), and its current_task() is set to zero.  When the next
333 #       task is executed, the connection's next_task() is set to zero
334 #       and its current_task() pointed to the task structure.
335 #       current_task() and next_task() are both zero only when there
336 #       are no more queued tasks, which is when a new test is
337 #       started.
338 #
339 #       Each connection's current test is stored in its
340 #       "current_test_address" option.  The next test to execute is
341 #       calculated by walking the declarative tree of tests.  This
342 #       option begins empty; the "next test" after this is of course
343 #       the root test.
344 #
345 sub check {
346     my $this = shift();
347     my($tname) = @_;
348
349     $tname = "Main" if !defined $tname;
350     $this->{tree} = $this->_gather_tests($tname)
351         or die "No tests defined for '$tname'";
352     #$this->{tree}->print(0);
353     my $nskipped = 0;
354
355     my @conn = @{ $this->{connections} };
356
357     my $nruns = 0;
358   ROUND_AND_ROUND_WE_GO:
359     while (1) {
360         my @copy_conn = @conn;  # avoid alias problems after splice()
361         my $nconn = scalar(@copy_conn);
362         foreach my $i0 (0 .. $#copy_conn) {
363             my $conn = $copy_conn[$i0];
364             #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
365             if (!$conn->current_task()) {
366                 if (!$conn->next_task()) {
367                     # Out of tasks: we need a new test
368                   NEXT_TEST:
369                     my $address = $conn->option("current_test_address");
370                     my $nextaddr;
371                     if (!defined $address) {
372                         $nextaddr = "";
373                     } else {
374                         $this->log("irspy_test",
375                                    "checking for next test after '$address'");
376                         $nextaddr = $this->_next_test($address);
377                     }
378                     if (!defined $nextaddr) {
379                         $conn->log("irspy", "has no more tests: removing");
380                         ### Does this go wrong if two connections are exhausted?
381                         splice @conn, $i0, 1;
382                         $this->_rewrite_record($conn);
383                         $conn->option(rewrote_record => 1);
384                         next;
385                     }
386
387                     my $node = $this->{tree}->select($nextaddr)
388                         or die "invalid nextaddr '$nextaddr'";
389                     $conn->option(current_test_address => $nextaddr);
390                     my $tname = $node->name();
391                     $conn->log("irspy_test",
392                                "starting test '$nextaddr' = $tname");
393                     my $tasks = $conn->tasks();
394                     my $oldcount = @$tasks;
395                     "ZOOM::IRSpy::Test::$tname"->start($conn);
396                     $tasks = $conn->tasks();
397                     if (@$tasks > $oldcount) {
398                         # Prepare to start the first of the newly added tasks
399                         $conn->next_task($tasks->[$oldcount]);
400                     } else {
401                         $conn->log("irspy_task",
402                                    "no tasks added by new test $tname");
403                         goto NEXT_TEST;
404                     }
405                 }
406
407                 my $task = $conn->next_task();
408                 die "no next task queued for $conn" if !defined $task;
409                 $conn->log("irspy_task", "preparing task $task");
410                 $conn->next_task(0);
411                 $conn->current_task($task);
412                 $task->run();
413             }
414         }
415
416       NEXT_EVENT:
417         my $i0 = ZOOM::event(\@conn);
418         $this->log("irspy_event",
419                    "ZOOM_event(", scalar(@conn), " connections) = $i0");
420         if ($i0 < 1) {
421             my %messages = (
422                             0 => "no events remain",
423                             -1 => "ZOOM::event() argument not a reference",
424                             -2 => "ZOOM::event() reference not an array",
425                             -3 => "no connections remain",
426                             -4 => "too many connections for ZOOM::event()",
427                             );
428             my $message = $messages{$i0} || "ZOOM::event() returned $i0";
429             $this->log("irspy", $message);
430             last;
431         }
432
433         my $conn = $conn[$i0-1];
434         my $ev = $conn->last_event();
435         my $evstr = ZOOM::event_str($ev);
436         $conn->log("irspy_event", "event $ev ($evstr)");
437         goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
438
439         my $task = $conn->current_task();
440         die "$conn has no current task for event $ev ($evstr)" if !$task;
441
442         my $res;
443         eval { $conn->check() };
444         if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
445             my $sub = $task->{cb}->{exception};
446             die $@ if !defined $sub;
447             $res = &$sub($conn, $task, $task->udata(), $@);
448         } elsif ($@) {
449             die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
450         } else {
451             my $sub = $task->{cb}->{$ev};
452             if (!defined $sub) {
453                 $conn->log("irspy_unhandled", "event $ev ($evstr)");
454                 next;
455             }
456
457             $res = &$sub($conn, $task, $task->udata(), $ev);
458         }
459
460         if ($res == ZOOM::IRSpy::Status::OK) {
461             # Nothing to do -- life continues
462
463         } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
464             my $task = $conn->current_task();
465             die "no task for TASK_DONE on $conn" if !$task;
466             die "next task already defined for $conn" if $conn->next_task();
467             $conn->log("irspy_task", "completed task $task");
468             $conn->next_task($task->{next});
469             $conn->current_task(0);
470
471         } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
472                  $res == ZOOM::IRSpy::Status::TEST_BAD) {
473             my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
474             $conn->log("irspy_task", "test ended during task $task ($x)");
475             $conn->log("irspy_test", "test completed ($x)");
476             $conn->current_task(0);
477             $conn->next_task(0);
478             if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
479                 my $address = $conn->option('current_test_address');
480                 ($address, my $n) = $this->_last_sibling_test($address);
481                 if (defined $address) {
482                     $conn->log("irspy_test", "skipped $n tests");
483                     $conn->option(current_test_address => $address);
484                     $nskipped += $n;
485                 }
486             }
487
488         } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
489             $conn->log("irspy_test", "test skipped during task $task");
490             $conn->current_task(0);
491             $conn->next_task(0);
492             $nskipped++;
493
494         } else {
495             die "unknown callback return-value '$res'";
496         }
497     }
498
499     $this->log("irspy", "exiting main loop");
500     # Sanity checks: none of the following should ever happen
501     my $finished = 1;
502     @conn = @{ $this->{connections} };
503     foreach my $conn (@conn) {
504         my $test = $conn->option("current_test_address");
505         my $next = $this->_next_test($test);
506         if (defined $next) {
507             $this->log("irspy",
508                        "$conn (in test '$test') has queued test '$next'");
509             $finished = 0;
510         }
511         if (my $task = $conn->current_task()) {
512             $this->log("irspy", "$conn still has an active task $task");
513             $finished = 0;
514         }
515         if (my $task = $conn->next_task()) {
516             $this->log("irspy", "$conn still has a queued task $task");
517             $finished = 0;
518         }
519         if (!$conn->is_idle()) {
520             $this->log("irspy",
521                        "$conn still has ZOOM-C level tasks queued: see below");
522             $finished = 0;
523         }
524         my $ev = $conn->peek_event();
525         if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
526             my $evstr = ZOOM::event_str($ev);
527             $this->log("irspy", "$conn has event $ev ($evstr) waiting");
528             $finished = 0;
529         }
530         if (!$conn->option("rewrote_record")) {
531             $this->log("irspy", "$conn did not rewrite its ZeeRex record");
532             $finished = 0;
533         }
534     }
535
536     # This really shouldn't be necessary, and in practice it rarely
537     # helps, but it's belt and braces.  (For now, we don't do this
538     # hence the zero in the $nruns check).
539     if (!$finished) {
540         if (++$nruns < 0) {
541             $this->log("irspy", "back into main loop, ${nruns}th time");
542             goto ROUND_AND_ROUND_WE_GO;
543         } else {
544             $this->log("irspy", "bailing after $nruns main-loop runs");
545         }
546     }
547
548     # This shouldn't happen emit anything either:
549     while ((my $i1 = ZOOM::event(\@conn)) > 0) {
550         my $conn = $conn[$i1-1];
551         my $ev = $conn->last_event();
552         my $evstr = ZOOM::event_str($ev);
553         $this->log("irspy",
554                    "$conn still has ZOOM-C level task queued: $ev ($evstr)")
555             if $ev != ZOOM::Event::ZEND;
556     }
557
558     return $nskipped;
559 }
560
561
562 sub _gather_tests {
563     my $this = shift();
564     my($tname, @ancestors) = @_;
565
566     die("$0: test-hierarchy loop detected: " .
567         join(" -> ", @ancestors, $tname))
568         if grep { $_ eq $tname } @ancestors;
569
570     my $slashSeperatedTname = $tname;
571     $slashSeperatedTname =~ s/::/\//g;
572     my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
573
574     eval {
575         require $fullName;
576         $this->log("irspy", "successfully required '$fullName'");
577     }; if ($@) {
578         $this->log("irspy", "couldn't require '$fullName': $@");
579         $this->log("warn", "can't load test '$tname': skipping",
580                    $@ =~ /^Can.t locate/ ? () : " ($@)");
581         return undef;
582     }
583
584     $this->log("irspy", "adding test '$tname'");
585     my @subnodes;
586     foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
587         my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
588         push @subnodes, $subtest if defined $subtest;
589     }
590
591     return new ZOOM::IRSpy::Node($tname, @subnodes);
592 }
593
594
595 # These next three should arguably be Node methods
596 sub _next_test {
597     my $this = shift();
598     my($address, $omit_child) = @_;
599
600     # Try first child
601     if (!$omit_child) {
602         my $maybe = $address eq "" ? "0" : "$address:0";
603         return $maybe if $this->{tree}->select($maybe);
604     }
605
606     # The top-level node has no successor or parent
607     return undef if $address eq "";
608
609     # Try next sibling child
610     my @components = split /:/, $address;
611     my $last = pop @components;
612     my $maybe = join(":", @components, $last+1);
613     return $maybe if $this->{tree}->select($maybe);
614
615     # This node is exhausted: try the parent's successor
616     return $this->_next_test(join(":", @components), 1)
617 }
618
619
620 sub _last_sibling_test {
621     my $this = shift();
622     my($address) = @_;
623
624     return undef
625         if !defined $this->_next_sibling_test($address);
626
627     my $nskipped = 0;
628     while (1) {
629         my $maybe = $this->_next_sibling_test($address);
630         last if !defined $maybe;
631         $nskipped++;
632         $address = $maybe;
633         $this->log("irspy", "skipping $nskipped tests to '$address'");
634     }
635
636     return ($address, $nskipped);
637 }
638
639
640 sub _next_sibling_test {
641     my $this = shift();
642     my($address) = @_;
643
644     my @components = split /:/, $address;
645     my $last = pop @components;
646     my $maybe = join(":", @components, $last+1);
647     return $maybe if $this->{tree}->select($maybe);
648     return undef;
649 }
650
651
652 =head1 SEE ALSO
653
654 ZOOM::IRSpy::Record,
655 ZOOM::IRSpy::Web,
656 ZOOM::IRSpy::Test,
657 ZOOM::IRSpy::Maintenance.
658
659 The ZOOM-Perl module,
660 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
661
662 The Zebra Database,
663 http://indexdata.com/zebra/
664
665 =head1 AUTHOR
666
667 Mike Taylor, E<lt>mike@indexdata.comE<gt>
668
669 =head1 COPYRIGHT AND LICENSE
670
671 Copyright (C) 2006 by Index Data ApS.
672
673 This library is free software; you can redistribute it and/or modify
674 it under the same terms as Perl itself, either Perl version 5.8.7 or,
675 at your option, any later version of Perl 5 you may have available.
676
677 =cut
678
679
680 1;