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