1 # $Id: IRSpy.pm,v 1.90 2008-07-16 11:42:13 mike Exp $
9 use Data::Dumper; # For debugging only
13 use XML::LibXML::XPathContext;
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::Stats;
19 use ZOOM::IRSpy::Utils qw(cql_target render_record
20 irspy_xpath_context irspy_make_identifier
21 irspy_record2identifier);
24 our $VERSION = '1.01';
25 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
28 # Enumeration for callback functions to return
29 package ZOOM::IRSpy::Status;
30 sub OK { 29 } # No problems, task is still progressing
31 sub TASK_DONE { 18 } # Task is complete, next task should begin
32 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
33 sub TEST_BAD { 31 } # Whole test is complete, and failed
34 sub TEST_SKIPPED { 12 } # Test couldn't be run
40 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
45 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
46 $spy->targets(@targets);
47 $spy->initialise("Main");
52 This module exists to implement the IRspy program, which discovers,
53 analyses and monitors IR servers implementing the Z39.50 and SRU/W
54 protocols. It is a successor to the ZSpy program.
59 ZOOM::Log::mask_str("irspy");
60 ZOOM::Log::mask_str("irspy_debug");
61 ZOOM::Log::mask_str("irspy_event");
62 ZOOM::Log::mask_str("irspy_unhandled");
63 ZOOM::Log::mask_str("irspy_test");
64 ZOOM::Log::mask_str("irspy_task");
69 my($dbname, $user, $password, $activeSetSize) = @_;
72 push @options, (user => $user, password => $password)
75 my $conn = new ZOOM::Connection($dbname, 0, @options)
76 or die "$0: can't connection to IRSpy database 'dbname'";
78 my $xslt = new XML::LibXSLT;
80 # raise the maximum number of nested template calls and variables/params (default 250)
81 $xslt->max_depth(250);
83 $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
84 \&ZOOM::IRSpy::Utils::xslt_strcmp);
86 my $libxml = new XML::LibXML;
87 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
88 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
92 query => "cql.allRecords=1", # unless overridden
93 modn => undef, # Filled in by restrict_modulo()
94 modi => undef, # Filled in by restrict_modulo()
95 targets => undef, # Filled in later if targets() is
96 # called; used only to keep state from
97 # targets() until initialise() is
99 connections => undef, # Filled in by initialise()
100 queue => undef, # Filled in by initialise()
102 irspy_to_zeerex_style => $irspy_to_zeerex_style,
103 test => undef, # Filled in by initialise()
104 timeout => undef, # Filled in by initialise()
105 tests => undef, # Tree of tests to be executed
106 activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
108 $this->log("irspy", "starting up with database '$dbname'");
124 $this->{query} = $query;
128 # Explicitly nominate a set of targets to check, overriding the
129 # default which is to re-check everything in the database. Each
130 # target already in the database results in the existing record being
131 # updated; each new target causes a new record to be added.
137 $this->log("irspy", "setting explicit list of targets ",
138 join(", ", map { "'$_'" } @targets));
140 foreach my $target (@targets) {
141 my($protocol, $host, $port, $db, $newtarget) =
142 _parse_target_string($target);
143 if ($newtarget ne $target) {
144 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
145 $target = $newtarget; # This is written through the ref
147 push @qlist, cql_target($protocol, $host, $port, $db);
150 $this->{targets} = \@targets;
151 $this->{query} = join(" or ", @qlist);
155 # Also used by ZOOM::IRSpy::Record
156 sub _parse_target_string {
159 my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
160 if (!defined $host) {
162 ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
163 $target = irspy_make_identifier($protocol, $host, $port, $db);
165 die "$0: invalid target string '$target'"
168 return ($protocol, $host, $port, $db, $target);
172 sub restrict_modulo {
181 # Records must be fetched for all records satisfying $this->{query} If
182 # $this->{targets} is already set (i.e. a specific list of targets to
183 # check was specified by a call to targets()), then new, empty records
184 # will be made for any targets that are not already in the database.
190 $tname = "Main" if !defined $tname;
191 $this->{test} = $tname;
192 $this->{tree} = $this->_gather_tests($tname)
193 or die "No tests defined for '$tname'";
194 $this->{tree}->resolve();
195 #$this->{tree}->print(0);
197 $this->{timeout} = "ZOOM::IRSpy::Test::$tname"->timeout();
200 my $targets = $this->{targets};
201 if (defined $targets) {
202 @targets = @$targets;
203 delete $this->{targets};
205 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
206 $this->log("irspy", "'", $this->{query}, "' found ",
207 $rs->size(), " target records");
208 delete $this->{query};
210 foreach my $i (1 .. $rs->size()) {
211 push @targets, render_record($rs, $i-1, "id");
215 my $n = $this->{activeSetSize};
216 $n = @targets if $n == 0 || $n > @targets;
218 $this->{queue} = \@targets;
219 $this->{connections} = [];
220 while (@{ $this->{connections} } < $n) {
221 my $conn = $this->_next_connection();
222 last if !defined $conn;
223 push @{ $this->{connections} }, $conn;
228 sub _next_connection {
232 my $n = $this->{modn};
233 my $i = $this->{modi};
235 $target = shift @{ $this->{queue} };
236 return undef if !defined $target;
239 $target = shift @{ $this->{queue} };
240 return undef if !defined $target;
241 my $h = _hash($target);
243 last if $hmodn == $i;
244 #$this->log("irspy", "'$target' hash $h % $n = $hmodn != $i");
248 die "oops -- target is undefined" if !defined $target;
249 return create ZOOM::IRSpy::Connection($this, $target, async => 1,
250 timeout => $this->{timeout});
258 foreach my $s (split //, $target) {
266 sub _irspy_to_zeerex {
268 my($conn, $save_xml) = @_;
269 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
272 unlink('/tmp/irspy_orig.xml');
273 open FH, '>/tmp/irspy_orig.xml'
274 or die "can't write irspy_orig.xml: $!";
275 print FH $irspy_doc->toString();
279 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
281 unlink('/tmp/irspy_transformed.xml');
282 open FH, '>/tmp/irspy_transformed.xml'
283 or die "can't write irspy_transformed.xml: $!";
284 print FH $result->toString();
288 return $result->documentElement();
292 sub _rewrite_record {
296 $conn->log("irspy", "rewriting XML record");
297 my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
299 # Since IRSpy can run for a long time between writes back to the
300 # database, it's quite possible for the server to have closed the
301 # connection as idle. So re-establish it if necessary.
302 $this->{conn}->connect($conn->option("host"));
304 _really_rewrite_record($this->{conn}, $rec);
305 $conn->log("irspy", "rewrote XML record");
309 sub _really_rewrite_record {
310 my($conn, $rec, $oldid) = @_;
312 my $p = $conn->package();
313 $p->option(action => "specialUpdate");
314 my $xml = $rec->toString();
315 $p->option(record => $xml);
319 # This is the expression in the ID-making stylesheet
320 # ../../zebra/zeerex2id.xsl
321 my $xc = irspy_xpath_context($rec);
322 my $id = irspy_record2identifier($xc);
323 if (defined $oldid && $id ne $oldid) {
324 warn "IDs differ (old='$oldid' new='$id')";
325 _delete_record($conn, $oldid);
328 $p = $conn->package();
335 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
343 # We can't delete records using recordIdOpaque, since character
344 # sets are handled differently here in extended services from how
345 # they are used in the Alvis filter's record-parsing, and so
346 # non-ASCII characters come out differently in the two contexts.
347 # Instead, we must send a record whose contents indicate the ID of
348 # that which we wish to delete. There are two ways, both
349 # unsatisfactory: we could either fetch the actual record them
350 # resubmit it in the deletion request (which wastes a search and a
351 # fetch) or we could build a record by hand from the parsed-out
352 # components (which is error-prone and which I am not 100% certain
353 # will work since the other contents of the record will be
354 # different). The former evil seems to be the lesser.
356 warn "$conn deleting record '$id'";
358 my $rs = $conn->search(new ZOOM::Query::CQL(cql_target($id)));
359 die "no such ID '$id'" if $rs->size() == 0;
360 my $rec = $rs->record(0);
361 my $xml = $rec->render();
363 my $p = $conn->package();
364 $p->option(action => "recordDelete");
365 $p->option(record => $xml);
369 $p = $conn->package();
375 # The approach: gather declarative information about test hierarchy,
376 # then go into a loop. In the loop, we ensure that each connection is
377 # running a test, and within that test a task, until its list of tests
378 # is exhausted. No individual test ever calls wait(): tests just queue
379 # up tasks and return immediately. When the tasks are run (one at a
380 # time on each connection) they generate events, and it is these that
381 # are harvested by ZOOM::event(). Since each connection knows what
382 # task it is running, it can invoke the appropriate callbacks.
383 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
384 # loop how to continue.
387 # While a connection is running a task, its current_task()
388 # points at the task structure. When it finishes its task,
389 # next_task() is pointed at the next task to execute (if there
390 # is one), and its current_task() is set to zero. When the next
391 # task is executed, the connection's next_task() is set to zero
392 # and its current_task() pointed to the task structure.
393 # current_task() and next_task() are both zero only when there
394 # are no more queued tasks, which is when a new test is
397 # Each connection's current test is stored in its
398 # "current_test_address" option. The next test to execute is
399 # calculated by walking the declarative tree of tests. This
400 # option begins empty; the "next test" after this is of course
406 my $topname = $this->{tree}->name();
407 my $timeout = $this->{timeout};
408 $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
411 my @conn = @{ $this->{connections} };
414 ROUND_AND_ROUND_WE_GO:
416 my @copy_conn = @conn; # avoid alias problems after splice()
417 my $nconn = scalar(@copy_conn);
418 foreach my $i0 (0 .. $#copy_conn) {
419 my $conn = $copy_conn[$i0];
420 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
421 next if !defined $conn;
422 if (!$conn->current_task()) {
423 if (!$conn->next_task()) {
424 # Out of tasks: we need a new test
426 my $address = $conn->option("current_test_address");
428 if (!defined $address) {
431 $conn->log("irspy_test",
432 "checking for next test after '$address'");
433 $nextaddr = $this->_next_test($address);
435 if (!defined $nextaddr) {
436 $conn->log("irspy", "has no more tests: removing");
437 $this->_rewrite_record($conn);
438 $conn->option(rewrote_record => 1);
439 my $newconn = $this->_next_connection();
440 if (!defined $newconn) {
441 # Do not destroy: needed for later sanity checks
442 splice @conn, $i0, 1;
445 $conn[$i0] = $newconn;
446 $conn[$i0]->option(current_test_address => "");
447 $conn[$i0]->log("irspy", "entering active pool - ",
448 scalar(@{ $this->{queue} }),
449 " targets remain in queue");
454 my $node = $this->{tree}->select($nextaddr)
455 or die "invalid nextaddr '$nextaddr'";
456 $conn->option(current_test_address => $nextaddr);
457 my $tname = $node->name();
458 $conn->log("irspy_test",
459 "starting test '$nextaddr' = $tname");
460 my $tasks = $conn->tasks();
461 my $oldcount = @$tasks;
462 "ZOOM::IRSpy::Test::$tname"->start($conn);
463 $tasks = $conn->tasks();
464 if (@$tasks > $oldcount) {
465 # Prepare to start the first of the newly added tasks
466 $conn->next_task($tasks->[$oldcount]);
468 $conn->log("irspy_task",
469 "no tasks added by new test $tname");
474 my $task = $conn->next_task();
475 die "no next task queued for $conn" if !defined $task;
476 $conn->log("irspy_task", "preparing task $task");
478 $conn->current_task($task);
484 my $i0 = ZOOM::event(\@conn);
485 $this->log("irspy_event",
486 "ZOOM_event(", scalar(@conn), " connections) = $i0");
489 0 => "no events remain",
490 -1 => "ZOOM::event() argument not a reference",
491 -2 => "ZOOM::event() reference not an array",
492 -3 => "no connections remain",
493 -4 => "too many connections for ZOOM::event()",
495 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
496 $this->log("irspy", $message);
500 my $conn = $conn[$i0-1];
501 my $ev = $conn->last_event();
502 my $evstr = ZOOM::event_str($ev);
503 $conn->log("irspy_event", "event $ev ($evstr)");
504 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
506 my $task = $conn->current_task();
507 die "$conn has no current task for event $ev ($evstr)" if !$task;
510 eval { $conn->check() };
511 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
512 my $sub = $task->{cb}->{exception};
513 die $@ if !defined $sub;
514 $res = &$sub($conn, $task, $task->udata(), $@);
516 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
518 my $sub = $task->{cb}->{$ev};
520 $conn->log("irspy_unhandled", "event $ev ($evstr)");
524 $res = &$sub($conn, $task, $task->udata(), $ev);
527 if ($res == ZOOM::IRSpy::Status::OK) {
528 # Nothing to do -- life continues
530 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
531 my $task = $conn->current_task();
532 die "no task for TASK_DONE on $conn" if !$task;
533 die "next task already defined for $conn" if $conn->next_task();
534 $conn->log("irspy_task", "completed task $task");
535 $conn->next_task($task->{next});
536 $conn->current_task(0);
538 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
539 $res == ZOOM::IRSpy::Status::TEST_BAD) {
540 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
541 $conn->log("irspy_task", "test ended during task $task ($x)");
542 $conn->log("irspy_test", "test completed ($x)");
543 $conn->current_task(0);
545 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
546 my $address = $conn->option('current_test_address');
547 $conn->log("irspy", "top-level test failed!")
549 my $node = $this->{tree}->select($address);
551 while (defined $node->next() &&
552 length($node->next()->address()) >= length($address)) {
553 $conn->log("irspy_debug", "skipping from '",
554 $node->address(), "' to '",
555 $node->next()->address(), "'");
556 $node = $node->next();
560 $conn->option(current_test_address => $node->address());
561 $conn->log("irspy_test", "skipped $skipcount tests");
562 $nskipped += $skipcount;
565 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
566 $conn->log("irspy_test", "test skipped during task $task");
567 $conn->current_task(0);
572 die "unknown callback return-value '$res'";
576 $this->log("irspy", "exiting main loop");
578 # Sanity checks: none of the following should ever happen
580 $this->log("irspy", "performing end-of-run sanity-checks");
581 foreach my $conn (@conn) {
582 my $test = $conn->option("current_test_address");
583 my $next = $this->_next_test($test);
586 "$conn (in test '$test') has queued test '$next'");
589 if (my $task = $conn->current_task()) {
590 $this->log("irspy", "$conn still has an active task $task");
593 if (my $task = $conn->next_task()) {
594 $this->log("irspy", "$conn still has a queued task $task");
597 if (!$conn->is_idle()) {
599 "$conn still has ZOOM-C level tasks queued: see below");
602 my $ev = $conn->peek_event();
603 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
604 my $evstr = ZOOM::event_str($ev);
605 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
608 if (!$conn->option("rewrote_record")) {
609 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
614 # This really shouldn't be necessary, and in practice it rarely
615 # helps, but it's belt and braces. (For now, we don't do this
616 # hence the zero in the $nruns check).
619 $this->log("irspy", "back into main loop, ${nruns}th time");
620 goto ROUND_AND_ROUND_WE_GO;
622 $this->log("irspy", "bailing after $nruns main-loop runs");
626 # This shouldn't happen emit anything either:
627 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
628 my $conn = $conn[$i1-1];
629 my $ev = $conn->last_event();
630 my $evstr = ZOOM::event_str($ev);
632 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
633 if $ev != ZOOM::Event::ZEND;
640 # Exactly equivalent to ZOOM::event() except that it is tolerant to
641 # undefined values in the array being passed in.
643 sub __UNUSED_tolerant_ZOOM_event {
647 foreach my $i (0 .. @$connref-1) {
648 my $conn = $connref->[$i];
655 my $res = ZOOM::event(\@conn);
656 return $res if $res <= 0;
657 my $res2 = $map[$res-1] + 1;
658 print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
665 my($tname, @ancestors) = @_;
667 die("$0: test-hierarchy loop detected: " .
668 join(" -> ", @ancestors, $tname))
669 if grep { $_ eq $tname } @ancestors;
671 my $slashSeperatedTname = $tname;
672 $slashSeperatedTname =~ s/::/\//g;
673 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
678 $this->log("irspy", "couldn't require '$fullName': $@");
679 $this->log("warn", "can't load test '$tname': skipping",
680 $@ =~ /^Can.t locate/ ? () : " ($@)");
684 $this->log("irspy", "adding test '$tname'");
686 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
687 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
688 push @subnodes, $subtest if defined $subtest;
691 return new ZOOM::IRSpy::Node($tname, @subnodes);
695 # These next three should arguably be Node methods
698 my($address, $omit_child) = @_;
702 my $maybe = $address eq "" ? "0" : "$address:0";
703 return $maybe if $this->{tree}->select($maybe);
706 # The top-level node has no successor or parent
707 return undef if $address eq "";
709 # Try next sibling child
710 my @components = split /:/, $address;
711 my $last = pop @components;
712 my $maybe = join(":", @components, $last+1);
713 return $maybe if $this->{tree}->select($maybe);
715 # This node is exhausted: try the parent's successor
716 return $this->_next_test(join(":", @components), 1)
720 sub _last_sibling_test {
725 if !defined $this->_next_sibling_test($address);
729 my $maybe = $this->_next_sibling_test($address);
730 last if !defined $maybe;
733 $this->log("irspy", "skipping $nskipped tests to '$address'");
736 return ($address, $nskipped);
740 sub _next_sibling_test {
744 my @components = split /:/, $address;
745 my $last = pop @components;
746 my $maybe = join(":", @components, $last+1);
747 return $maybe if $this->{tree}->select($maybe);
757 ZOOM::IRSpy::Maintenance.
759 The ZOOM-Perl module,
760 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
763 http://indexdata.com/zebra/
767 Mike Taylor, E<lt>mike@indexdata.comE<gt>
769 =head1 COPYRIGHT AND LICENSE
771 Copyright (C) 2006 by Index Data ApS.
773 This library is free software; you can redistribute it and/or modify
774 it under the same terms as Perl itself, either Perl version 5.8.7 or,
775 at your option, any later version of Perl 5 you may have available.