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