1 # $Id: IRSpy.pm,v 1.88 2007-09-18 16:57:37 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 $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 modn => undef, # Filled in by restrict_modulo()
91 modi => undef, # Filled in by restrict_modulo()
92 targets => undef, # Filled in later if targets() is
93 # called; used only to keep state from
94 # targets() until initialise() is
96 connections => undef, # Filled in by initialise()
97 queue => undef, # Filled in by initialise()
99 irspy_to_zeerex_style => $irspy_to_zeerex_style,
100 test => undef, # Filled in by initialise()
101 timeout => undef, # Filled in by initialise()
102 tests => undef, # Tree of tests to be executed
103 activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
105 $this->log("irspy", "starting up with database '$dbname'");
121 $this->{query} = $query;
125 # Explicitly nominate a set of targets to check, overriding the
126 # default which is to re-check everything in the database. Each
127 # target already in the database results in the existing record being
128 # updated; each new target causes a new record to be added.
134 $this->log("irspy", "setting explicit list of targets ",
135 join(", ", map { "'$_'" } @targets));
137 foreach my $target (@targets) {
138 my($protocol, $host, $port, $db, $newtarget) =
139 _parse_target_string($target);
140 if ($newtarget ne $target) {
141 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
142 $target = $newtarget; # This is written through the ref
144 push @qlist, cql_target($protocol, $host, $port, $db);
147 $this->{targets} = \@targets;
148 $this->{query} = join(" or ", @qlist);
152 # Also used by ZOOM::IRSpy::Record
153 sub _parse_target_string {
156 my($protocol, $host, $port, $db) = ($target =~ /(.*?):(.*?):(.*?)\/(.*)/);
157 if (!defined $host) {
159 ($protocol, $host, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
160 $target = irspy_make_identifier($protocol, $host, $port, $db);
162 die "$0: invalid target string '$target'"
165 return ($protocol, $host, $port, $db, $target);
169 sub restrict_modulo {
178 # Records must be fetched for all records satisfying $this->{query} If
179 # $this->{targets} is already set (i.e. a specific list of targets to
180 # check was specified by a call to targets()), then new, empty records
181 # will be made for any targets that are not already in the database.
187 $tname = "Main" if !defined $tname;
188 $this->{test} = $tname;
189 $this->{tree} = $this->_gather_tests($tname)
190 or die "No tests defined for '$tname'";
191 $this->{tree}->resolve();
192 #$this->{tree}->print(0);
194 $this->{timeout} = "ZOOM::IRSpy::Test::$tname"->timeout();
197 my $targets = $this->{targets};
198 if (defined $targets) {
199 @targets = @$targets;
200 delete $this->{targets};
202 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
203 $this->log("irspy", "'", $this->{query}, "' found ",
204 $rs->size(), " target records");
205 delete $this->{query};
207 foreach my $i (1 .. $rs->size()) {
208 push @targets, render_record($rs, $i-1, "id");
212 my $n = $this->{activeSetSize};
213 $n = @targets if $n == 0 || $n > @targets;
215 $this->{queue} = \@targets;
216 $this->{connections} = [];
217 while (@{ $this->{connections} } < $n) {
218 my $conn = $this->_next_connection();
219 last if !defined $conn;
220 push @{ $this->{connections} }, $conn;
225 sub _next_connection {
229 my $n = $this->{modn};
230 my $i = $this->{modi};
232 $target = shift @{ $this->{queue} };
235 $target = shift @{ $this->{queue} };
236 return undef if !defined $target;
237 my $h = _hash($target);
239 last if $hmodn == $i;
240 $this->log("irspy", "'$target' hash $h % $n = $hmodn != $i");
244 return create ZOOM::IRSpy::Connection($this, $target, async => 1,
245 timeout => $this->{timeout});
253 foreach my $s (split //, $target) {
261 sub _irspy_to_zeerex {
263 my($conn, $save_xml) = @_;
264 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
267 unlink('/tmp/irspy_orig.xml');
268 open FH, '>/tmp/irspy_orig.xml'
269 or die "can't write irspy_orig.xml: $!";
270 print FH $irspy_doc->toString();
274 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
276 unlink('/tmp/irspy_transformed.xml');
277 open FH, '>/tmp/irspy_transformed.xml'
278 or die "can't write irspy_transformed.xml: $!";
279 print FH $result->toString();
283 return $result->documentElement();
287 sub _rewrite_record {
291 $conn->log("irspy", "rewriting XML record");
292 my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
294 # Since IRSpy can run for a long time between writes back to the
295 # database, it's quite possible for the server to have closed the
296 # connection as idle. So re-establish it if necessary.
297 $this->{conn}->connect($conn->option("host"));
299 _really_rewrite_record($this->{conn}, $rec);
300 $conn->log("irspy", "rewrote XML record");
304 sub _really_rewrite_record {
305 my($conn, $rec, $oldid) = @_;
307 my $p = $conn->package();
308 $p->option(action => "specialUpdate");
309 my $xml = $rec->toString();
310 $p->option(record => $xml);
314 # This is the expression in the ID-making stylesheet
315 # ../../zebra/zeerex2id.xsl
316 my $xc = irspy_xpath_context($rec);
317 my $id = irspy_record2identifier($xc);
318 if (defined $oldid && $id ne $oldid) {
319 warn "IDs differ (old='$oldid' new='$id')";
320 _delete_record($conn, $oldid);
323 $p = $conn->package();
330 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
338 # We can't delete records using recordIdOpaque, since character
339 # sets are handled differently here in extended services from how
340 # they are used in the Alvis filter's record-parsing, and so
341 # non-ASCII characters come out differently in the two contexts.
342 # Instead, we must send a record whose contents indicate the ID of
343 # that which we wish to delete. There are two ways, both
344 # unsatisfactory: we could either fetch the actual record them
345 # resubmit it in the deletion request (which wastes a search and a
346 # fetch) or we could build a record by hand from the parsed-out
347 # components (which is error-prone and which I am not 100% certain
348 # will work since the other contents of the record will be
349 # different). The former evil seems to be the lesser.
351 warn "$conn deleting record '$id'";
353 my $rs = $conn->search(new ZOOM::Query::CQL(cql_target($id)));
354 die "no such ID '$id'" if $rs->size() == 0;
355 my $rec = $rs->record(0);
356 my $xml = $rec->render();
358 my $p = $conn->package();
359 $p->option(action => "recordDelete");
360 $p->option(record => $xml);
364 $p = $conn->package();
370 # The approach: gather declarative information about test hierarchy,
371 # then go into a loop. In the loop, we ensure that each connection is
372 # running a test, and within that test a task, until its list of tests
373 # is exhausted. No individual test ever calls wait(): tests just queue
374 # up tasks and return immediately. When the tasks are run (one at a
375 # time on each connection) they generate events, and it is these that
376 # are harvested by ZOOM::event(). Since each connection knows what
377 # task it is running, it can invoke the appropriate callbacks.
378 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
379 # loop how to continue.
382 # While a connection is running a task, its current_task()
383 # points at the task structure. When it finishes its task,
384 # next_task() is pointed at the next task to execute (if there
385 # is one), and its current_task() is set to zero. When the next
386 # task is executed, the connection's next_task() is set to zero
387 # and its current_task() pointed to the task structure.
388 # current_task() and next_task() are both zero only when there
389 # are no more queued tasks, which is when a new test is
392 # Each connection's current test is stored in its
393 # "current_test_address" option. The next test to execute is
394 # calculated by walking the declarative tree of tests. This
395 # option begins empty; the "next test" after this is of course
401 my $topname = $this->{tree}->name();
402 my $timeout = $this->{timeout};
403 $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
406 my @conn = @{ $this->{connections} };
409 ROUND_AND_ROUND_WE_GO:
411 my @copy_conn = @conn; # avoid alias problems after splice()
412 my $nconn = scalar(@copy_conn);
413 foreach my $i0 (0 .. $#copy_conn) {
414 my $conn = $copy_conn[$i0];
415 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
416 next if !defined $conn;
417 if (!$conn->current_task()) {
418 if (!$conn->next_task()) {
419 # Out of tasks: we need a new test
421 my $address = $conn->option("current_test_address");
423 if (!defined $address) {
426 $conn->log("irspy_test",
427 "checking for next test after '$address'");
428 $nextaddr = $this->_next_test($address);
430 if (!defined $nextaddr) {
431 $conn->log("irspy", "has no more tests: removing");
432 $this->_rewrite_record($conn);
433 $conn->option(rewrote_record => 1);
434 my $newconn = $this->_next_connection();
435 if (!defined $newconn) {
436 # Do not destroy: needed for later sanity checks
437 splice @conn, $i0, 1;
440 $conn[$i0] = $newconn;
441 $conn[$i0]->option(current_test_address => "");
442 $conn[$i0]->log("irspy", "entering active pool - ",
443 scalar(@{ $this->{queue} }),
444 " targets remain in queue");
449 my $node = $this->{tree}->select($nextaddr)
450 or die "invalid nextaddr '$nextaddr'";
451 $conn->option(current_test_address => $nextaddr);
452 my $tname = $node->name();
453 $conn->log("irspy_test",
454 "starting test '$nextaddr' = $tname");
455 my $tasks = $conn->tasks();
456 my $oldcount = @$tasks;
457 "ZOOM::IRSpy::Test::$tname"->start($conn);
458 $tasks = $conn->tasks();
459 if (@$tasks > $oldcount) {
460 # Prepare to start the first of the newly added tasks
461 $conn->next_task($tasks->[$oldcount]);
463 $conn->log("irspy_task",
464 "no tasks added by new test $tname");
469 my $task = $conn->next_task();
470 die "no next task queued for $conn" if !defined $task;
471 $conn->log("irspy_task", "preparing task $task");
473 $conn->current_task($task);
479 my $i0 = ZOOM::event(\@conn);
480 $this->log("irspy_event",
481 "ZOOM_event(", scalar(@conn), " connections) = $i0");
484 0 => "no events remain",
485 -1 => "ZOOM::event() argument not a reference",
486 -2 => "ZOOM::event() reference not an array",
487 -3 => "no connections remain",
488 -4 => "too many connections for ZOOM::event()",
490 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
491 $this->log("irspy", $message);
495 my $conn = $conn[$i0-1];
496 my $ev = $conn->last_event();
497 my $evstr = ZOOM::event_str($ev);
498 $conn->log("irspy_event", "event $ev ($evstr)");
499 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
501 my $task = $conn->current_task();
502 die "$conn has no current task for event $ev ($evstr)" if !$task;
505 eval { $conn->check() };
506 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
507 my $sub = $task->{cb}->{exception};
508 die $@ if !defined $sub;
509 $res = &$sub($conn, $task, $task->udata(), $@);
511 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
513 my $sub = $task->{cb}->{$ev};
515 $conn->log("irspy_unhandled", "event $ev ($evstr)");
519 $res = &$sub($conn, $task, $task->udata(), $ev);
522 if ($res == ZOOM::IRSpy::Status::OK) {
523 # Nothing to do -- life continues
525 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
526 my $task = $conn->current_task();
527 die "no task for TASK_DONE on $conn" if !$task;
528 die "next task already defined for $conn" if $conn->next_task();
529 $conn->log("irspy_task", "completed task $task");
530 $conn->next_task($task->{next});
531 $conn->current_task(0);
533 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
534 $res == ZOOM::IRSpy::Status::TEST_BAD) {
535 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
536 $conn->log("irspy_task", "test ended during task $task ($x)");
537 $conn->log("irspy_test", "test completed ($x)");
538 $conn->current_task(0);
540 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
541 my $address = $conn->option('current_test_address');
542 $conn->log("irspy", "top-level test failed!")
544 my $node = $this->{tree}->select($address);
546 while (defined $node->next() &&
547 length($node->next()->address()) >= length($address)) {
548 $conn->log("irspy_debug", "skipping from '",
549 $node->address(), "' to '",
550 $node->next()->address(), "'");
551 $node = $node->next();
555 $conn->option(current_test_address => $node->address());
556 $conn->log("irspy_test", "skipped $skipcount tests");
557 $nskipped += $skipcount;
560 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
561 $conn->log("irspy_test", "test skipped during task $task");
562 $conn->current_task(0);
567 die "unknown callback return-value '$res'";
571 $this->log("irspy", "exiting main loop");
573 # Sanity checks: none of the following should ever happen
575 $this->log("irspy", "performing end-of-run sanity-checks");
576 foreach my $conn (@conn) {
577 my $test = $conn->option("current_test_address");
578 my $next = $this->_next_test($test);
581 "$conn (in test '$test') has queued test '$next'");
584 if (my $task = $conn->current_task()) {
585 $this->log("irspy", "$conn still has an active task $task");
588 if (my $task = $conn->next_task()) {
589 $this->log("irspy", "$conn still has a queued task $task");
592 if (!$conn->is_idle()) {
594 "$conn still has ZOOM-C level tasks queued: see below");
597 my $ev = $conn->peek_event();
598 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
599 my $evstr = ZOOM::event_str($ev);
600 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
603 if (!$conn->option("rewrote_record")) {
604 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
609 # This really shouldn't be necessary, and in practice it rarely
610 # helps, but it's belt and braces. (For now, we don't do this
611 # hence the zero in the $nruns check).
614 $this->log("irspy", "back into main loop, ${nruns}th time");
615 goto ROUND_AND_ROUND_WE_GO;
617 $this->log("irspy", "bailing after $nruns main-loop runs");
621 # This shouldn't happen emit anything either:
622 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
623 my $conn = $conn[$i1-1];
624 my $ev = $conn->last_event();
625 my $evstr = ZOOM::event_str($ev);
627 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
628 if $ev != ZOOM::Event::ZEND;
635 # Exactly equivalent to ZOOM::event() except that it is tolerant to
636 # undefined values in the array being passed in.
638 sub __UNUSED_tolerant_ZOOM_event {
642 foreach my $i (0 .. @$connref-1) {
643 my $conn = $connref->[$i];
650 my $res = ZOOM::event(\@conn);
651 return $res if $res <= 0;
652 my $res2 = $map[$res-1] + 1;
653 print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
660 my($tname, @ancestors) = @_;
662 die("$0: test-hierarchy loop detected: " .
663 join(" -> ", @ancestors, $tname))
664 if grep { $_ eq $tname } @ancestors;
666 my $slashSeperatedTname = $tname;
667 $slashSeperatedTname =~ s/::/\//g;
668 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
673 $this->log("irspy", "couldn't require '$fullName': $@");
674 $this->log("warn", "can't load test '$tname': skipping",
675 $@ =~ /^Can.t locate/ ? () : " ($@)");
679 $this->log("irspy", "adding test '$tname'");
681 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
682 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
683 push @subnodes, $subtest if defined $subtest;
686 return new ZOOM::IRSpy::Node($tname, @subnodes);
690 # These next three should arguably be Node methods
693 my($address, $omit_child) = @_;
697 my $maybe = $address eq "" ? "0" : "$address:0";
698 return $maybe if $this->{tree}->select($maybe);
701 # The top-level node has no successor or parent
702 return undef if $address eq "";
704 # Try next sibling child
705 my @components = split /:/, $address;
706 my $last = pop @components;
707 my $maybe = join(":", @components, $last+1);
708 return $maybe if $this->{tree}->select($maybe);
710 # This node is exhausted: try the parent's successor
711 return $this->_next_test(join(":", @components), 1)
715 sub _last_sibling_test {
720 if !defined $this->_next_sibling_test($address);
724 my $maybe = $this->_next_sibling_test($address);
725 last if !defined $maybe;
728 $this->log("irspy", "skipping $nskipped tests to '$address'");
731 return ($address, $nskipped);
735 sub _next_sibling_test {
739 my @components = split /:/, $address;
740 my $last = pop @components;
741 my $maybe = join(":", @components, $last+1);
742 return $maybe if $this->{tree}->select($maybe);
752 ZOOM::IRSpy::Maintenance.
754 The ZOOM-Perl module,
755 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
758 http://indexdata.com/zebra/
762 Mike Taylor, E<lt>mike@indexdata.comE<gt>
764 =head1 COPYRIGHT AND LICENSE
766 Copyright (C) 2006 by Index Data ApS.
768 This library is free software; you can redistribute it and/or modify
769 it under the same terms as Perl itself, either Perl version 5.8.7 or,
770 at your option, any later version of Perl 5 you may have available.