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 calc_reliability_stats
25 our $VERSION = '1.01';
26 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
29 # Enumeration for callback functions to return
30 package ZOOM::IRSpy::Status;
31 sub OK { 29 } # No problems, task is still progressing
32 sub TASK_DONE { 18 } # Task is complete, next task should begin
33 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
34 sub TEST_BAD { 31 } # Whole test is complete, and failed
35 sub TEST_SKIPPED { 12 } # Test couldn't be run
41 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
46 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
47 $spy->targets(@targets);
48 $spy->initialise("Main");
53 This module exists to implement the IRspy program, which discovers,
54 analyses and monitors IR servers implementing the Z39.50 and SRU/W
55 protocols. It is a successor to the ZSpy program.
60 ZOOM::Log::mask_str("irspy");
61 ZOOM::Log::mask_str("irspy_debug");
62 ZOOM::Log::mask_str("irspy_event");
63 ZOOM::Log::mask_str("irspy_unhandled");
64 ZOOM::Log::mask_str("irspy_test");
65 ZOOM::Log::mask_str("irspy_task");
70 my($dbname, $user, $password, $activeSetSize) = @_;
73 push @options, (user => $user, password => $password)
76 my $conn = new ZOOM::Connection($dbname, 0, @options)
77 or die "$0: can't connection to IRSpy database 'dbname'";
79 my $xslt = new XML::LibXSLT;
81 $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
82 \&ZOOM::IRSpy::Utils::xslt_strcmp);
84 my $libxml = new XML::LibXML;
85 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
86 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
90 query => "cql.allRecords=1", # unless overridden
91 modn => undef, # Filled in by restrict_modulo()
92 modi => undef, # Filled in by restrict_modulo()
93 targets => undef, # Filled in later if targets() is
94 # called; used only to keep state from
95 # targets() until initialise() is
97 connections => undef, # Filled in by initialise()
98 queue => undef, # Filled in by initialise()
100 irspy_to_zeerex_style => $irspy_to_zeerex_style,
101 test => undef, # Filled in by initialise()
102 timeout => undef, # Filled in by initialise()
103 tests => undef, # Tree of tests to be executed
104 activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
106 $this->log("irspy", "starting up with database '$dbname'");
122 $this->{query} = $query;
126 # Explicitly nominate a set of targets to check, overriding the
127 # default which is to re-check everything in the database. Each
128 # target already in the database results in the existing record being
129 # updated; each new target causes a new record to be added.
135 $this->log("irspy", "setting explicit list of targets ",
136 join(", ", map { "'$_'" } @targets));
138 foreach my $target (@targets) {
139 my($protocol, $host, $port, $db, $newtarget) =
140 _parse_target_string($target);
141 if ($newtarget ne $target) {
142 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
143 $target = $newtarget; # This is written through the ref
145 push @qlist, cql_target($protocol, $host, $port, $db);
148 $this->{targets} = \@targets;
149 $this->{query} = join(" or ", @qlist);
153 # Also used by ZOOM::IRSpy::Record
154 sub _parse_target_string {
157 my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
158 if (!defined $host) {
160 ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
161 $target = irspy_make_identifier($protocol, $host, $port, $db);
163 die "$0: invalid target string '$target'"
166 return ($protocol, $host, $port, $db, $target);
170 sub restrict_modulo {
179 # Records must be fetched for all records satisfying $this->{query} If
180 # $this->{targets} is already set (i.e. a specific list of targets to
181 # check was specified by a call to targets()), then new, empty records
182 # will be made for any targets that are not already in the database.
188 $tname = "Main" if !defined $tname;
189 $this->{test} = $tname;
190 $this->{tree} = $this->_gather_tests($tname)
191 or die "No tests defined for '$tname'";
192 $this->{tree}->resolve();
193 #$this->{tree}->print(0);
195 $this->{timeout} = "ZOOM::IRSpy::Test::$tname"->timeout();
198 my $targets = $this->{targets};
199 if (defined $targets) {
200 @targets = @$targets;
201 delete $this->{targets};
203 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
204 $this->log("irspy", "'", $this->{query}, "' found ",
205 $rs->size(), " target records");
206 delete $this->{query};
208 foreach my $i (1 .. $rs->size()) {
209 push @targets, render_record($rs, $i-1, "id");
213 my $n = $this->{activeSetSize};
214 $n = @targets if $n == 0 || $n > @targets;
216 $this->{queue} = \@targets;
217 $this->{connections} = [];
218 while (@{ $this->{connections} } < $n) {
219 my $conn = $this->_next_connection();
220 last if !defined $conn;
221 push @{ $this->{connections} }, $conn;
226 sub _next_connection {
230 my $n = $this->{modn};
231 my $i = $this->{modi};
233 $target = shift @{ $this->{queue} };
234 return undef if !defined $target;
237 $target = shift @{ $this->{queue} };
238 return undef if !defined $target;
239 my $h = _hash($target);
241 last if $hmodn == $i;
242 #$this->log("irspy", "'$target' hash $h % $n = $hmodn != $i");
246 die "oops -- target is undefined" if !defined $target;
247 return create ZOOM::IRSpy::Connection($this, $target, async => 1,
248 timeout => $this->{timeout});
256 foreach my $s (split //, $target) {
264 sub _irspy_to_zeerex {
268 my $save_xml = $ENV{IRSPY_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_irspy_record {
296 $conn->log("irspy", "rewriting XML record");
297 my $rec = $this->_irspy_to_zeerex($conn);
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 _rewrite_zeerex_record($this->{conn}, $rec);
305 $conn->log("irspy", "rewrote XML record");
309 my $_reliabilityField = {
310 reliability => [ reliability => 0,
311 "Calculated reliability of server",
312 "e:metaInfo/i:reliability" ],
315 sub _rewrite_zeerex_record {
316 my($conn, $rec, $oldid) = @_;
318 # Add reliability score
319 my $xc = irspy_xpath_context($rec);
320 my($nok, $nall, $percent) = calc_reliability_stats($xc);
321 modify_xml_document($xc, $_reliabilityField, { reliability => $percent });
323 my $p = $conn->package();
324 $p->option(action => "specialUpdate");
325 my $xml = $rec->toString();
326 $p->option(record => $xml);
330 # This is the expression in the ID-making stylesheet
331 # ../../zebra/zeerex2id.xsl
332 my $id = irspy_record2identifier($xc);
333 if (defined $oldid && $id ne $oldid) {
334 warn "IDs differ (old='$oldid' new='$id')";
335 _delete_record($conn, $oldid);
338 $p = $conn->package();
345 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
353 # We can't delete records using recordIdOpaque, since character
354 # sets are handled differently here in extended services from how
355 # they are used in the Alvis filter's record-parsing, and so
356 # non-ASCII characters come out differently in the two contexts.
357 # Instead, we must send a record whose contents indicate the ID of
358 # that which we wish to delete. There are two ways, both
359 # unsatisfactory: we could either fetch the actual record them
360 # resubmit it in the deletion request (which wastes a search and a
361 # fetch) or we could build a record by hand from the parsed-out
362 # components (which is error-prone and which I am not 100% certain
363 # will work since the other contents of the record will be
364 # different). The former evil seems to be the lesser.
366 warn "$conn deleting record '$id'";
368 my $rs = $conn->search(new ZOOM::Query::CQL(cql_target($id)));
369 die "no such ID '$id'" if $rs->size() == 0;
370 my $rec = $rs->record(0);
371 my $xml = $rec->render();
373 my $p = $conn->package();
374 $p->option(action => "recordDelete");
375 $p->option(record => $xml);
379 $p = $conn->package();
385 # The approach: gather declarative information about test hierarchy,
386 # then go into a loop. In the loop, we ensure that each connection is
387 # running a test, and within that test a task, until its list of tests
388 # is exhausted. No individual test ever calls wait(): tests just queue
389 # up tasks and return immediately. When the tasks are run (one at a
390 # time on each connection) they generate events, and it is these that
391 # are harvested by ZOOM::event(). Since each connection knows what
392 # task it is running, it can invoke the appropriate callbacks.
393 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
394 # loop how to continue.
397 # While a connection is running a task, its current_task()
398 # points at the task structure. When it finishes its task,
399 # next_task() is pointed at the next task to execute (if there
400 # is one), and its current_task() is set to zero. When the next
401 # task is executed, the connection's next_task() is set to zero
402 # and its current_task() pointed to the task structure.
403 # current_task() and next_task() are both zero only when there
404 # are no more queued tasks, which is when a new test is
407 # Each connection's current test is stored in its
408 # "current_test_address" option. The next test to execute is
409 # calculated by walking the declarative tree of tests. This
410 # option begins empty; the "next test" after this is of course
416 my $topname = $this->{tree}->name();
417 my $timeout = $this->{timeout};
418 $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
421 my @conn = @{ $this->{connections} };
424 ROUND_AND_ROUND_WE_GO:
426 my @copy_conn = @conn; # avoid alias problems after splice()
427 my $nconn = scalar(@copy_conn);
428 foreach my $i0 (0 .. $#copy_conn) {
429 my $conn = $copy_conn[$i0];
430 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
431 next if !defined $conn;
432 if (!$conn->current_task()) {
433 if (!$conn->next_task()) {
434 # Out of tasks: we need a new test
436 my $address = $conn->option("current_test_address");
438 if (!defined $address) {
441 $conn->log("irspy_test",
442 "checking for next test after '$address'");
443 $nextaddr = $this->_next_test($address);
445 if (!defined $nextaddr) {
446 $conn->log("irspy", "has no more tests: removing");
447 $this->_rewrite_irspy_record($conn);
448 $conn->option(rewrote_record => 1);
449 my $newconn = $this->_next_connection();
450 if (!defined $newconn) {
451 # Do not destroy: needed for later sanity checks
452 splice @conn, $i0, 1;
455 $conn[$i0] = $newconn;
456 $conn[$i0]->option(current_test_address => "");
457 $conn[$i0]->log("irspy", "entering active pool - ",
458 scalar(@{ $this->{queue} }),
459 " targets remain in queue");
464 my $node = $this->{tree}->select($nextaddr)
465 or die "invalid nextaddr '$nextaddr'";
466 $conn->option(current_test_address => $nextaddr);
467 my $tname = $node->name();
468 $conn->log("irspy_test",
469 "starting test '$nextaddr' = $tname");
470 my $tasks = $conn->tasks();
471 my $oldcount = @$tasks;
472 "ZOOM::IRSpy::Test::$tname"->start($conn);
473 $tasks = $conn->tasks();
474 if (@$tasks > $oldcount) {
475 # Prepare to start the first of the newly added tasks
476 $conn->next_task($tasks->[$oldcount]);
478 $conn->log("irspy_task",
479 "no tasks added by new test $tname");
484 my $task = $conn->next_task();
485 die "no next task queued for $conn" if !defined $task;
486 $conn->log("irspy_task", "preparing task $task");
488 $conn->current_task($task);
494 my $i0 = ZOOM::event(\@conn);
495 $this->log("irspy_event",
496 "ZOOM_event(", scalar(@conn), " connections) = $i0");
499 0 => "no events remain",
500 -1 => "ZOOM::event() argument not a reference",
501 -2 => "ZOOM::event() reference not an array",
502 -3 => "no connections remain",
503 -4 => "too many connections for ZOOM::event()",
505 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
506 $this->log("irspy", $message);
510 my $conn = $conn[$i0-1];
511 my $ev = $conn->last_event();
512 my $evstr = ZOOM::event_str($ev);
513 $conn->log("irspy_event", "event $ev ($evstr)");
514 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
516 my $task = $conn->current_task();
517 die "$conn has no current task for event $ev ($evstr)" if !$task;
520 eval { $conn->check() };
521 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
522 my $sub = $task->{cb}->{exception};
523 die $@ if !defined $sub;
524 $res = &$sub($conn, $task, $task->udata(), $@);
526 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
528 my $sub = $task->{cb}->{$ev};
530 $conn->log("irspy_unhandled", "event $ev ($evstr)");
534 $res = &$sub($conn, $task, $task->udata(), $ev);
537 if ($res == ZOOM::IRSpy::Status::OK) {
538 # Nothing to do -- life continues
540 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
541 my $task = $conn->current_task();
542 die "no task for TASK_DONE on $conn" if !$task;
543 die "next task already defined for $conn" if $conn->next_task();
544 $conn->log("irspy_task", "completed task $task");
545 $conn->next_task($task->{next});
546 $conn->current_task(0);
548 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
549 $res == ZOOM::IRSpy::Status::TEST_BAD) {
550 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
551 $conn->log("irspy_task", "test ended during task $task ($x)");
552 $conn->log("irspy_test", "test completed ($x)");
553 $conn->current_task(0);
555 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
556 my $address = $conn->option('current_test_address');
557 $conn->log("irspy", "top-level test failed!")
559 my $node = $this->{tree}->select($address);
561 while (defined $node->next() &&
562 length($node->next()->address()) >= length($address)) {
563 $conn->log("irspy_debug", "skipping from '",
564 $node->address(), "' to '",
565 $node->next()->address(), "'");
566 $node = $node->next();
570 $conn->option(current_test_address => $node->address());
571 $conn->log("irspy_test", "skipped $skipcount tests");
572 $nskipped += $skipcount;
575 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
576 $conn->log("irspy_test", "test skipped during task $task");
577 $conn->current_task(0);
582 die "unknown callback return-value '$res'";
586 $this->log("irspy", "exiting main loop");
588 # Sanity checks: none of the following should ever happen
590 $this->log("irspy", "performing end-of-run sanity-checks");
591 foreach my $conn (@conn) {
592 my $test = $conn->option("current_test_address");
593 my $next = $this->_next_test($test);
596 "$conn (in test '$test') has queued test '$next'");
599 if (my $task = $conn->current_task()) {
600 $this->log("irspy", "$conn still has an active task $task");
603 if (my $task = $conn->next_task()) {
604 $this->log("irspy", "$conn still has a queued task $task");
607 if (!$conn->is_idle()) {
609 "$conn still has ZOOM-C level tasks queued: see below");
612 my $ev = $conn->peek_event();
613 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
614 my $evstr = ZOOM::event_str($ev);
615 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
618 if (!$conn->option("rewrote_record")) {
619 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
624 # This really shouldn't be necessary, and in practice it rarely
625 # helps, but it's belt and braces. (For now, we don't do this
626 # hence the zero in the $nruns check).
629 $this->log("irspy", "back into main loop, ${nruns}th time");
630 goto ROUND_AND_ROUND_WE_GO;
632 $this->log("irspy", "bailing after $nruns main-loop runs");
636 # This shouldn't happen emit anything either:
637 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
638 my $conn = $conn[$i1-1];
639 my $ev = $conn->last_event();
640 my $evstr = ZOOM::event_str($ev);
642 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
643 if $ev != ZOOM::Event::ZEND;
650 # Exactly equivalent to ZOOM::event() except that it is tolerant to
651 # undefined values in the array being passed in.
653 sub __UNUSED_tolerant_ZOOM_event {
657 foreach my $i (0 .. @$connref-1) {
658 my $conn = $connref->[$i];
665 my $res = ZOOM::event(\@conn);
666 return $res if $res <= 0;
667 my $res2 = $map[$res-1] + 1;
668 print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
675 my($tname, @ancestors) = @_;
677 die("$0: test-hierarchy loop detected: " .
678 join(" -> ", @ancestors, $tname))
679 if grep { $_ eq $tname } @ancestors;
681 my $slashSeperatedTname = $tname;
682 $slashSeperatedTname =~ s/::/\//g;
683 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
688 $this->log("irspy", "couldn't require '$fullName': $@");
689 $this->log("warn", "can't load test '$tname': skipping",
690 $@ =~ /^Can.t locate/ ? () : " ($@)");
694 $this->log("irspy", "adding test '$tname'");
696 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
697 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
698 push @subnodes, $subtest if defined $subtest;
701 return new ZOOM::IRSpy::Node($tname, @subnodes);
705 # These next three should arguably be Node methods
708 my($address, $omit_child) = @_;
712 my $maybe = $address eq "" ? "0" : "$address:0";
713 return $maybe if $this->{tree}->select($maybe);
716 # The top-level node has no successor or parent
717 return undef if $address eq "";
719 # Try next sibling child
720 my @components = split /:/, $address;
721 my $last = pop @components;
722 my $maybe = join(":", @components, $last+1);
723 return $maybe if $this->{tree}->select($maybe);
725 # This node is exhausted: try the parent's successor
726 return $this->_next_test(join(":", @components), 1)
730 sub _last_sibling_test {
735 if !defined $this->_next_sibling_test($address);
739 my $maybe = $this->_next_sibling_test($address);
740 last if !defined $maybe;
743 $this->log("irspy", "skipping $nskipped tests to '$address'");
746 return ($address, $nskipped);
750 sub _next_sibling_test {
754 my @components = split /:/, $address;
755 my $last = pop @components;
756 my $maybe = join(":", @components, $last+1);
757 return $maybe if $this->{tree}->select($maybe);
767 ZOOM::IRSpy::Maintenance.
769 The ZOOM-Perl module,
770 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
773 http://indexdata.com/zebra/
777 Mike Taylor, E<lt>mike@indexdata.comE<gt>
779 =head1 COPYRIGHT AND LICENSE
781 Copyright (C) 2006 by Index Data ApS.
783 This library is free software; you can redistribute it and/or modify
784 it under the same terms as Perl itself, either Perl version 5.8.7 or,
785 at your option, any later version of Perl 5 you may have available.