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