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