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