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