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