1 # $Id: IRSpy.pm,v 1.85 2007-06-27 11:09:03 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 = '0.02';
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 $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
81 \&ZOOM::IRSpy::Utils::xslt_strcmp);
83 my $libxml = new XML::LibXML;
84 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
85 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
89 query => "cql.allRecords=1", # unless overridden
90 targets => undef, # Filled in later if targets() is
91 # called; used only to keep state from
92 # targets() until initialise() is
94 connections => undef, # Filled in by initialise()
95 queue => undef, # Filled in by initialise()
97 irspy_to_zeerex_style => $irspy_to_zeerex_style,
98 test => undef, # Filled in by initialise()
99 tests => undef, # Tree of tests to be executed
100 activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
102 $this->log("irspy", "starting up with database '$dbname'");
118 $this->{query} = $query;
122 # Explicitly nominate a set of targets to check, overriding the
123 # default which is to re-check everything in the database. Each
124 # target already in the database results in the existing record being
125 # updated; each new target causes a new record to be added.
131 $this->log("irspy", "setting explicit list of targets ",
132 join(", ", map { "'$_'" } @targets));
134 foreach my $target (@targets) {
135 my($protocol, $host, $port, $db, $newtarget) =
136 _parse_target_string($target);
137 if ($newtarget ne $target) {
138 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
139 $target = $newtarget; # This is written through the ref
141 push @qlist, cql_target($protocol, $host, $port, $db);
144 $this->{targets} = \@targets;
145 $this->{query} = join(" or ", @qlist);
149 # Also used by ZOOM::IRSpy::Record
150 sub _parse_target_string {
153 my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
154 if (!defined $host) {
156 ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
157 $target = irspy_make_identifier($protocol, $host, $port, $db);
159 die "$0: invalid target string '$target'"
162 return ($protocol, $host, $port, $db, $target);
166 # Records must be fetched for all records satisfying $this->{query} If
167 # $this->{targets} is already set (i.e. a specific list of targets to
168 # check was specified by a call to targets()), then new, empty records
169 # will be made for any targets that are not already in the database.
175 $tname = "Main" if !defined $tname;
176 $this->{test} = $tname;
177 $this->{tree} = $this->_gather_tests($tname)
178 or die "No tests defined for '$tname'";
179 $this->{tree}->resolve();
180 #$this->{tree}->print(0);
182 my $timeout = "ZOOM::IRSpy::Test::$tname"->timeout();
185 my $targets = $this->{targets};
186 if (defined $targets) {
187 @targets = @$targets;
188 delete $this->{targets};
190 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
191 $this->log("irspy", "'", $this->{query}, "' found ",
192 $rs->size(), " target records");
193 delete $this->{query};
195 foreach my $i (1 .. $rs->size()) {
196 push @targets, render_record($rs, $i-1, "id");
200 my $n = $this->{activeSetSize};
201 $n = @targets if $n == 0 || $n > @targets;
204 foreach my $i (1..$n) {
205 push @connections, create ZOOM::IRSpy::Connection($this,
208 timeout => $timeout);
211 $this->{connections} = \@connections;
212 $this->{queue} = \@targets;
216 sub _irspy_to_zeerex {
218 my($conn, $save_xml) = @_;
219 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
222 unlink('/tmp/irspy_orig.xml');
223 open FH, '>/tmp/irspy_orig.xml'
224 or die "can't write irspy_orig.xml: $!";
225 print FH $irspy_doc->toString();
229 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
231 unlink('/tmp/irspy_transformed.xml');
232 open FH, '>/tmp/irspy_transformed.xml'
233 or die "can't write irspy_transformed.xml: $!";
234 print FH $result->toString();
238 return $result->documentElement();
242 sub _rewrite_record {
246 $conn->log("irspy", "rewriting XML record");
247 my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
249 # Since IRSpy can run for a long time between writes back to the
250 # database, it's quite possible for the server to have closed the
251 # connection as idle. So re-establish it if necessary.
252 $this->{conn}->connect($conn->option("host"));
254 _really_rewrite_record($this->{conn}, $rec);
255 $conn->log("irspy", "rewrote XML record");
259 sub _really_rewrite_record {
260 my($conn, $rec, $oldid) = @_;
262 my $p = $conn->package();
263 $p->option(action => "specialUpdate");
264 my $xml = $rec->toString();
265 $p->option(record => $xml);
269 # This is the expression in the ID-making stylesheet
270 # ../../zebra/zeerex2id.xsl
271 my $xc = irspy_xpath_context($rec);
272 my $id = irspy_record2identifier($xc);
273 if (defined $oldid && $id ne $oldid) {
274 warn "IDs differ (old='$oldid' new='$id')";
275 _delete_record($conn, $oldid);
278 $p = $conn->package();
285 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
293 # We can't delete records using recordIdOpaque, since character
294 # sets are handled differently here in extended services from how
295 # they are used in the Alvis filter's record-parsing, and so
296 # non-ASCII characters come out differently in the two contexts.
297 # Instead, we must send a record whose contents indicate the ID of
298 # that which we wish to delete. There are two ways, both
299 # unsatisfactory: we could either fetch the actual record them
300 # resubmit it in the deletion request (which wastes a search and a
301 # fetch) or we could build a record by hand from the parsed-out
302 # components (which is error-prone and which I am not 100% certain
303 # will work since the other contents of the record will be
304 # different). The former evil seems to be the lesser.
306 warn "$conn deleting record '$id'";
308 my $rs = $conn->search(new ZOOM::Query::CQL(cql_target($id)));
309 die "no such ID '$id'" if $rs->size() == 0;
310 my $rec = $rs->record(0);
311 my $xml = $rec->render();
313 my $p = $conn->package();
314 $p->option(action => "recordDelete");
315 $p->option(record => $xml);
319 $p = $conn->package();
325 # The approach: gather declarative information about test hierarchy,
326 # then go into a loop. In the loop, we ensure that each connection is
327 # running a test, and within that test a task, until its list of tests
328 # is exhausted. No individual test ever calls wait(): tests just queue
329 # up tasks and return immediately. When the tasks are run (one at a
330 # time on each connection) they generate events, and it is these that
331 # are harvested by ZOOM::event(). Since each connection knows what
332 # task it is running, it can invoke the appropriate callbacks.
333 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
334 # loop how to continue.
337 # While a connection is running a task, its current_task()
338 # points at the task structure. When it finishes its task,
339 # next_task() is pointed at the next task to execute (if there
340 # is one), and its current_task() is set to zero. When the next
341 # task is executed, the connection's next_task() is set to zero
342 # and its current_task() pointed to the task structure.
343 # current_task() and next_task() are both zero only when there
344 # are no more queued tasks, which is when a new test is
347 # Each connection's current test is stored in its
348 # "current_test_address" option. The next test to execute is
349 # calculated by walking the declarative tree of tests. This
350 # option begins empty; the "next test" after this is of course
356 my $topname = $this->{tree}->name();
357 my $timeout = "ZOOM::IRSpy::Test::$topname"->timeout();
358 $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
361 my @conn = @{ $this->{connections} };
364 ROUND_AND_ROUND_WE_GO:
366 my @copy_conn = @conn; # avoid alias problems after splice()
367 my $nconn = scalar(@copy_conn);
368 foreach my $i0 (0 .. $#copy_conn) {
369 my $conn = $copy_conn[$i0];
370 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
371 next if !defined $conn;
372 if (!$conn->current_task()) {
373 if (!$conn->next_task()) {
374 # Out of tasks: we need a new test
376 my $address = $conn->option("current_test_address");
378 if (!defined $address) {
381 $conn->log("irspy_test",
382 "checking for next test after '$address'");
383 $nextaddr = $this->_next_test($address);
385 if (!defined $nextaddr) {
386 $conn->log("irspy", "has no more tests: removing");
387 $this->_rewrite_record($conn);
388 $conn->option(rewrote_record => 1);
389 if (@{ $this->{queue} } == 0) {
390 # Do not destroy: we need this for later sanity checks
391 splice @conn, $i0, 1;
395 ZOOM::IRSpy::Connection($this,
396 shift @{ $this->{queue} }, async => 1,
397 timeout => $timeout);
398 $conn[$i0]->option(current_test_address => "");
399 $conn[$i0]->log("irspy", "entering active pool - ",
400 scalar(@{ $this->{queue} }),
401 " targets remain in queue");
406 my $node = $this->{tree}->select($nextaddr)
407 or die "invalid nextaddr '$nextaddr'";
408 $conn->option(current_test_address => $nextaddr);
409 my $tname = $node->name();
410 $conn->log("irspy_test",
411 "starting test '$nextaddr' = $tname");
412 my $tasks = $conn->tasks();
413 my $oldcount = @$tasks;
414 "ZOOM::IRSpy::Test::$tname"->start($conn);
415 $tasks = $conn->tasks();
416 if (@$tasks > $oldcount) {
417 # Prepare to start the first of the newly added tasks
418 $conn->next_task($tasks->[$oldcount]);
420 $conn->log("irspy_task",
421 "no tasks added by new test $tname");
426 my $task = $conn->next_task();
427 die "no next task queued for $conn" if !defined $task;
428 $conn->log("irspy_task", "preparing task $task");
430 $conn->current_task($task);
436 my $i0 = ZOOM::event(\@conn);
437 $this->log("irspy_event",
438 "ZOOM_event(", scalar(@conn), " connections) = $i0");
441 0 => "no events remain",
442 -1 => "ZOOM::event() argument not a reference",
443 -2 => "ZOOM::event() reference not an array",
444 -3 => "no connections remain",
445 -4 => "too many connections for ZOOM::event()",
447 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
448 $this->log("irspy", $message);
452 my $conn = $conn[$i0-1];
453 my $ev = $conn->last_event();
454 my $evstr = ZOOM::event_str($ev);
455 $conn->log("irspy_event", "event $ev ($evstr)");
456 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
458 my $task = $conn->current_task();
459 die "$conn has no current task for event $ev ($evstr)" if !$task;
462 eval { $conn->check() };
463 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
464 my $sub = $task->{cb}->{exception};
465 die $@ if !defined $sub;
466 $res = &$sub($conn, $task, $task->udata(), $@);
468 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
470 my $sub = $task->{cb}->{$ev};
472 $conn->log("irspy_unhandled", "event $ev ($evstr)");
476 $res = &$sub($conn, $task, $task->udata(), $ev);
479 if ($res == ZOOM::IRSpy::Status::OK) {
480 # Nothing to do -- life continues
482 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
483 my $task = $conn->current_task();
484 die "no task for TASK_DONE on $conn" if !$task;
485 die "next task already defined for $conn" if $conn->next_task();
486 $conn->log("irspy_task", "completed task $task");
487 $conn->next_task($task->{next});
488 $conn->current_task(0);
490 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
491 $res == ZOOM::IRSpy::Status::TEST_BAD) {
492 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
493 $conn->log("irspy_task", "test ended during task $task ($x)");
494 $conn->log("irspy_test", "test completed ($x)");
495 $conn->current_task(0);
497 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
498 my $address = $conn->option('current_test_address');
499 $conn->log("irspy", "top-level test failed!")
501 my $node = $this->{tree}->select($address);
503 while (defined $node->next() &&
504 length($node->next()->address()) >= length($address)) {
505 $conn->log("irspy_debug", "skipping from '",
506 $node->address(), "' to '",
507 $node->next()->address(), "'");
508 $node = $node->next();
512 $conn->option(current_test_address => $node->address());
513 $conn->log("irspy_test", "skipped $skipcount tests");
514 $nskipped += $skipcount;
517 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
518 $conn->log("irspy_test", "test skipped during task $task");
519 $conn->current_task(0);
524 die "unknown callback return-value '$res'";
528 $this->log("irspy", "exiting main loop");
530 # Sanity checks: none of the following should ever happen
532 $this->log("irspy", "performing end-of-run sanity-checks");
533 foreach my $conn (@conn) {
534 my $test = $conn->option("current_test_address");
535 my $next = $this->_next_test($test);
538 "$conn (in test '$test') has queued test '$next'");
541 if (my $task = $conn->current_task()) {
542 $this->log("irspy", "$conn still has an active task $task");
545 if (my $task = $conn->next_task()) {
546 $this->log("irspy", "$conn still has a queued task $task");
549 if (!$conn->is_idle()) {
551 "$conn still has ZOOM-C level tasks queued: see below");
554 my $ev = $conn->peek_event();
555 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
556 my $evstr = ZOOM::event_str($ev);
557 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
560 if (!$conn->option("rewrote_record")) {
561 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
566 # This really shouldn't be necessary, and in practice it rarely
567 # helps, but it's belt and braces. (For now, we don't do this
568 # hence the zero in the $nruns check).
571 $this->log("irspy", "back into main loop, ${nruns}th time");
572 goto ROUND_AND_ROUND_WE_GO;
574 $this->log("irspy", "bailing after $nruns main-loop runs");
578 # This shouldn't happen emit anything either:
579 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
580 my $conn = $conn[$i1-1];
581 my $ev = $conn->last_event();
582 my $evstr = ZOOM::event_str($ev);
584 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
585 if $ev != ZOOM::Event::ZEND;
592 # Exactly equivalent to ZOOM::event() except that it is tolerant to
593 # undefined values in the array being passed in.
595 sub __UNUSED_tolerant_ZOOM_event {
599 foreach my $i (0 .. @$connref-1) {
600 my $conn = $connref->[$i];
607 my $res = ZOOM::event(\@conn);
608 return $res if $res <= 0;
609 my $res2 = $map[$res-1] + 1;
610 print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
617 my($tname, @ancestors) = @_;
619 die("$0: test-hierarchy loop detected: " .
620 join(" -> ", @ancestors, $tname))
621 if grep { $_ eq $tname } @ancestors;
623 my $slashSeperatedTname = $tname;
624 $slashSeperatedTname =~ s/::/\//g;
625 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
630 $this->log("irspy", "couldn't require '$fullName': $@");
631 $this->log("warn", "can't load test '$tname': skipping",
632 $@ =~ /^Can.t locate/ ? () : " ($@)");
636 $this->log("irspy", "adding test '$tname'");
638 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
639 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
640 push @subnodes, $subtest if defined $subtest;
643 return new ZOOM::IRSpy::Node($tname, @subnodes);
647 # These next three should arguably be Node methods
650 my($address, $omit_child) = @_;
654 my $maybe = $address eq "" ? "0" : "$address:0";
655 return $maybe if $this->{tree}->select($maybe);
658 # The top-level node has no successor or parent
659 return undef if $address eq "";
661 # Try next sibling child
662 my @components = split /:/, $address;
663 my $last = pop @components;
664 my $maybe = join(":", @components, $last+1);
665 return $maybe if $this->{tree}->select($maybe);
667 # This node is exhausted: try the parent's successor
668 return $this->_next_test(join(":", @components), 1)
672 sub _last_sibling_test {
677 if !defined $this->_next_sibling_test($address);
681 my $maybe = $this->_next_sibling_test($address);
682 last if !defined $maybe;
685 $this->log("irspy", "skipping $nskipped tests to '$address'");
688 return ($address, $nskipped);
692 sub _next_sibling_test {
696 my @components = split /:/, $address;
697 my $last = pop @components;
698 my $maybe = join(":", @components, $last+1);
699 return $maybe if $this->{tree}->select($maybe);
709 ZOOM::IRSpy::Maintenance.
711 The ZOOM-Perl module,
712 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
715 http://indexdata.com/zebra/
719 Mike Taylor, E<lt>mike@indexdata.comE<gt>
721 =head1 COPYRIGHT AND LICENSE
723 Copyright (C) 2006 by Index Data ApS.
725 This library is free software; you can redistribute it and/or modify
726 it under the same terms as Perl itself, either Perl version 5.8.7 or,
727 at your option, any later version of Perl 5 you may have available.