1 # $Id: IRSpy.pm,v 1.82 2007-04-18 15:35:51 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 irspy_xpath_context);
22 our $VERSION = '0.02';
23 our $irspy_to_zeerex_xsl = dirname(__FILE__) . '/../../xsl/irspy2zeerex.xsl';
26 # Enumeration for callback functions to return
27 package ZOOM::IRSpy::Status;
28 sub OK { 29 } # No problems, task is still progressing
29 sub TASK_DONE { 18 } # Task is complete, next task should begin
30 sub TEST_GOOD { 8 } # Whole test is complete, and succeeded
31 sub TEST_BAD { 31 } # Whole test is complete, and failed
32 sub TEST_SKIPPED { 12 } # Test couldn't be run
38 ZOOM::IRSpy - Perl extension for discovering and analysing IR services
43 $spy = new ZOOM::IRSpy("target/string/for/irspy/database");
44 $spy->targets(@targets);
45 $spy->initialise("Main");
50 This module exists to implement the IRspy program, which discovers,
51 analyses and monitors IR servers implementing the Z39.50 and SRU/W
52 protocols. It is a successor to the ZSpy program.
57 ZOOM::Log::mask_str("irspy");
58 ZOOM::Log::mask_str("irspy_debug");
59 ZOOM::Log::mask_str("irspy_event");
60 ZOOM::Log::mask_str("irspy_unhandled");
61 ZOOM::Log::mask_str("irspy_test");
62 ZOOM::Log::mask_str("irspy_task");
67 my($dbname, $user, $password, $activeSetSize) = @_;
70 push @options, (user => $user, password => $password)
73 my $conn = new ZOOM::Connection($dbname, 0, @options)
74 or die "$0: can't connection to IRSpy database 'dbname'";
76 my $xslt = new XML::LibXSLT;
78 $xslt->register_function($ZOOM::IRSpy::Utils::IRSPY_NS, 'strcmp',
79 \&ZOOM::IRSpy::Utils::xslt_strcmp);
81 my $libxml = new XML::LibXML;
82 my $xsl_doc = $libxml->parse_file($irspy_to_zeerex_xsl);
83 my $irspy_to_zeerex_style = $xslt->parse_stylesheet($xsl_doc);
87 query => "cql.allRecords=1", # unless overridden
88 targets => undef, # Filled in later if targets() is
89 # called; used only to keep state from
90 # targets() until initialise() is
92 connections => undef, # Filled in by initialise()
93 queue => undef, # Filled in by initialise()
95 irspy_to_zeerex_style => $irspy_to_zeerex_style,
96 test => undef, # Filled in by initialise()
97 tests => undef, # Tree of tests to be executed
98 activeSetSize => defined $activeSetSize ? $activeSetSize : 10,
100 $this->log("irspy", "starting up with database '$dbname'");
116 $this->{query} = $query;
120 # Explicitly nominate a set of targets to check, overriding the
121 # default which is to re-check everything in the database. Each
122 # target already in the database results in the existing record being
123 # updated; each new target causes a new record to be added.
129 $this->log("irspy", "setting explicit list of targets ",
130 join(", ", map { "'$_'" } @targets));
132 foreach my $target (@targets) {
133 my($host, $port, $db, $newtarget) = _parse_target_string($target);
134 if ($newtarget ne $target) {
135 $this->log("irspy_debug", "rewriting '$target' to '$newtarget'");
136 $target = $newtarget; # This is written through the ref
138 push @qlist, cql_target($host, $port, $db);
141 $this->{targets} = \@targets;
142 $this->{query} = join(" or ", @qlist);
146 # Also used by ZOOM::IRSpy::Record
147 sub _parse_target_string {
150 my($host, $port, $db) = ($target =~ /(.*?):(.*?)\/(.*)/);
151 if (!defined $host) {
153 ($host, $db) = ($target =~ /(.*?)\/(.*)/);
154 $target = "$host:$port/$db";
156 die "$0: invalid target string '$target'"
159 return ($host, $port, $db, $target);
163 # Records must be fetched for all records satisfying $this->{query} If
164 # $this->{targets} is already set (i.e. a specific list of targets to
165 # check was specified by a call to targets()), then new, empty records
166 # will be made for any targets that are not already in the database.
172 $tname = "Main" if !defined $tname;
173 $this->{test} = $tname;
174 $this->{tree} = $this->_gather_tests($tname)
175 or die "No tests defined for '$tname'";
176 $this->{tree}->resolve();
177 $this->{tree}->print(0);
179 my $timeout = "ZOOM::IRSpy::Test::$tname"->timeout();
182 my $targets = $this->{targets};
183 if (defined $targets) {
184 @targets = @$targets;
185 delete $this->{targets};
187 my $rs = $this->{conn}->search(new ZOOM::Query::CQL($this->{query}));
188 $this->log("irspy", "'", $this->{query}, "' found ",
189 $rs->size(), " target records");
190 delete $this->{query};
192 foreach my $i (1 .. $rs->size()) {
193 push @targets, render_record($rs, $i-1, "id");
197 my $n = $this->{activeSetSize};
198 $n = @targets if $n == 0 || $n > @targets;
201 foreach my $i (1..$n) {
202 push @connections, create ZOOM::IRSpy::Connection($this,
205 timeout => $timeout);
208 $this->{connections} = \@connections;
209 $this->{queue} = \@targets;
213 sub _irspy_to_zeerex {
215 my($conn, $save_xml) = @_;
216 my $irspy_doc = $conn->record()->{zeerex}->ownerDocument;
219 unlink('/tmp/irspy_orig.xml');
220 open FH, '>/tmp/irspy_orig.xml'
221 or die "can't write irspy_orig.xml: $!";
222 print FH $irspy_doc->toString();
226 my $result = $this->{irspy_to_zeerex_style}->transform($irspy_doc, %params);
228 unlink('/tmp/irspy_transformed.xml');
229 open FH, '>/tmp/irspy_transformed.xml'
230 or die "can't write irspy_transformed.xml: $!";
231 print FH $result->toString();
235 return $result->documentElement();
239 sub _rewrite_record {
243 $conn->log("irspy", "rewriting XML record");
244 my $rec = $this->_irspy_to_zeerex($conn, $ENV{IRSPY_SAVE_XML});
246 # Since IRSpy can run for a long time between writes back to the
247 # database, it's quite possible for the server to have closed the
248 # connection as idle. So re-establish it if necessary.
249 $this->{conn}->connect($conn->option("host"));
251 _really_rewrite_record($this->{conn}, $rec);
252 $conn->log("irspy", "rewrote XML record");
256 sub _really_rewrite_record {
257 my($conn, $rec, $oldid) = @_;
259 my $p = $conn->package();
260 $p->option(action => "specialUpdate");
261 my $xml = $rec->toString();
262 $p->option(record => $xml);
266 # This is the expression in the ID-making stylesheet
267 # ../../zebra/zeerex2id.xsl
268 my $xc = irspy_xpath_context($rec);
269 my $id = $xc->find("concat(e:serverInfo/e:host, ':',
270 e:serverInfo/e:port, '/',
271 e:serverInfo/e:database)");
272 if (defined $oldid && $id ne $oldid) {
274 warn "IDs differ (old='$oldid' new='$id')";
275 my $p = $conn->package();
276 $p->option(action => "recordDelete");
277 $p->option(recordIdOpaque => $oldid);
278 $p->option(record => "<dummy/>"); # Work around Zebra bug
283 $p = $conn->package();
290 print "Updated $conn with xml=<br/>\n<pre>$xml</pre>\n";
295 # The approach: gather declarative information about test hierarchy,
296 # then go into a loop. In the loop, we ensure that each connection is
297 # running a test, and within that test a task, until its list of tests
298 # is exhausted. No individual test ever calls wait(): tests just queue
299 # up tasks and return immediately. When the tasks are run (one at a
300 # time on each connection) they generate events, and it is these that
301 # are harvested by ZOOM::event(). Since each connection knows what
302 # task it is running, it can invoke the appropriate callbacks.
303 # Callbacks return a ZOOM::IRSpy::Status value which tells the main
304 # loop how to continue.
307 # While a connection is running a task, its current_task()
308 # points at the task structure. When it finishes its task,
309 # next_task() is pointed at the next task to execute (if there
310 # is one), and its current_task() is set to zero. When the next
311 # task is executed, the connection's next_task() is set to zero
312 # and its current_task() pointed to the task structure.
313 # current_task() and next_task() are both zero only when there
314 # are no more queued tasks, which is when a new test is
317 # Each connection's current test is stored in its
318 # "current_test_address" option. The next test to execute is
319 # calculated by walking the declarative tree of tests. This
320 # option begins empty; the "next test" after this is of course
326 my $topname = $this->{tree}->name();
327 my $timeout = "ZOOM::IRSpy::Test::$topname"->timeout();
328 $this->log("irspy", "beginnning with test '$topname' (timeout $timeout)");
331 my @conn = @{ $this->{connections} };
334 ROUND_AND_ROUND_WE_GO:
336 my @copy_conn = @conn; # avoid alias problems after splice()
337 my $nconn = scalar(@copy_conn);
338 foreach my $i0 (0 .. $#copy_conn) {
339 my $conn = $copy_conn[$i0];
340 #print "connection $i0 of $nconn/", scalar(@conn), " is $conn\n";
341 next if !defined $conn;
342 if (!$conn->current_task()) {
343 if (!$conn->next_task()) {
344 # Out of tasks: we need a new test
346 my $address = $conn->option("current_test_address");
348 if (!defined $address) {
351 $conn->log("irspy_test",
352 "checking for next test after '$address'");
353 $nextaddr = $this->_next_test($address);
355 if (!defined $nextaddr) {
356 $conn->log("irspy", "has no more tests: removing");
357 $this->_rewrite_record($conn);
358 $conn->option(rewrote_record => 1);
359 if (@{ $this->{queue} } == 0) {
360 # Do not destroy: we need this for later sanity checks
361 splice @conn, $i0, 1;
365 ZOOM::IRSpy::Connection($this,
366 shift @{ $this->{queue} }, async => 1,
367 timeout => $timeout);
368 $conn[$i0]->option(current_test_address => "");
369 $conn[$i0]->log("irspy", "entering active pool - ",
370 scalar(@{ $this->{queue} }),
371 " targets remain in queue");
376 my $node = $this->{tree}->select($nextaddr)
377 or die "invalid nextaddr '$nextaddr'";
378 $conn->option(current_test_address => $nextaddr);
379 my $tname = $node->name();
380 $conn->log("irspy_test",
381 "starting test '$nextaddr' = $tname");
382 my $tasks = $conn->tasks();
383 my $oldcount = @$tasks;
384 "ZOOM::IRSpy::Test::$tname"->start($conn);
385 $tasks = $conn->tasks();
386 if (@$tasks > $oldcount) {
387 # Prepare to start the first of the newly added tasks
388 $conn->next_task($tasks->[$oldcount]);
390 $conn->log("irspy_task",
391 "no tasks added by new test $tname");
396 my $task = $conn->next_task();
397 die "no next task queued for $conn" if !defined $task;
398 $conn->log("irspy_task", "preparing task $task");
400 $conn->current_task($task);
406 my $i0 = ZOOM::event(\@conn);
407 $this->log("irspy_event",
408 "ZOOM_event(", scalar(@conn), " connections) = $i0");
411 0 => "no events remain",
412 -1 => "ZOOM::event() argument not a reference",
413 -2 => "ZOOM::event() reference not an array",
414 -3 => "no connections remain",
415 -4 => "too many connections for ZOOM::event()",
417 my $message = $messages{$i0} || "ZOOM::event() returned $i0";
418 $this->log("irspy", $message);
422 my $conn = $conn[$i0-1];
423 my $ev = $conn->last_event();
424 my $evstr = ZOOM::event_str($ev);
425 $conn->log("irspy_event", "event $ev ($evstr)");
426 goto NEXT_EVENT if $ev != ZOOM::Event::ZEND;
428 my $task = $conn->current_task();
429 die "$conn has no current task for event $ev ($evstr)" if !$task;
432 eval { $conn->check() };
433 if ($@ && ref $@ && $@->isa("ZOOM::Exception")) {
434 my $sub = $task->{cb}->{exception};
435 die $@ if !defined $sub;
436 $res = &$sub($conn, $task, $task->udata(), $@);
438 die "Unexpected non-ZOOM exception: " . ref($@) . " ($@)";
440 my $sub = $task->{cb}->{$ev};
442 $conn->log("irspy_unhandled", "event $ev ($evstr)");
446 $res = &$sub($conn, $task, $task->udata(), $ev);
449 if ($res == ZOOM::IRSpy::Status::OK) {
450 # Nothing to do -- life continues
452 } elsif ($res == ZOOM::IRSpy::Status::TASK_DONE) {
453 my $task = $conn->current_task();
454 die "no task for TASK_DONE on $conn" if !$task;
455 die "next task already defined for $conn" if $conn->next_task();
456 $conn->log("irspy_task", "completed task $task");
457 $conn->next_task($task->{next});
458 $conn->current_task(0);
460 } elsif ($res == ZOOM::IRSpy::Status::TEST_GOOD ||
461 $res == ZOOM::IRSpy::Status::TEST_BAD) {
462 my $x = ($res == ZOOM::IRSpy::Status::TEST_GOOD) ? "good" : "bad";
463 $conn->log("irspy_task", "test ended during task $task ($x)");
464 $conn->log("irspy_test", "test completed ($x)");
465 $conn->current_task(0);
467 if ($res == ZOOM::IRSpy::Status::TEST_BAD) {
468 my $address = $conn->option('current_test_address');
469 $conn->log("irspy", "top-level test failed!")
471 my $node = $this->{tree}->select($address);
473 while (defined $node->next() &&
474 length($node->next()->address()) >= length($address)) {
475 $conn->log("irspy_debug", "skipping from '",
476 $node->address(), "' to '",
477 $node->next()->address(), "'");
478 $node = $node->next();
482 $conn->option(current_test_address => $node->address());
483 $conn->log("irspy_test", "skipped $skipcount tests");
484 $nskipped += $skipcount;
487 } elsif ($res == ZOOM::IRSpy::Status::TEST_SKIPPED) {
488 $conn->log("irspy_test", "test skipped during task $task");
489 $conn->current_task(0);
494 die "unknown callback return-value '$res'";
498 $this->log("irspy", "exiting main loop");
500 # Sanity checks: none of the following should ever happen
502 $this->log("irspy", "performing end-of-run sanity-checks");
503 foreach my $conn (@conn) {
504 my $test = $conn->option("current_test_address");
505 my $next = $this->_next_test($test);
508 "$conn (in test '$test') has queued test '$next'");
511 if (my $task = $conn->current_task()) {
512 $this->log("irspy", "$conn still has an active task $task");
515 if (my $task = $conn->next_task()) {
516 $this->log("irspy", "$conn still has a queued task $task");
519 if (!$conn->is_idle()) {
521 "$conn still has ZOOM-C level tasks queued: see below");
524 my $ev = $conn->peek_event();
525 if ($ev != 0 && $ev != ZOOM::Event::ZEND) {
526 my $evstr = ZOOM::event_str($ev);
527 $this->log("irspy", "$conn has event $ev ($evstr) waiting");
530 if (!$conn->option("rewrote_record")) {
531 $this->log("irspy", "$conn did not rewrite its ZeeRex record");
536 # This really shouldn't be necessary, and in practice it rarely
537 # helps, but it's belt and braces. (For now, we don't do this
538 # hence the zero in the $nruns check).
541 $this->log("irspy", "back into main loop, ${nruns}th time");
542 goto ROUND_AND_ROUND_WE_GO;
544 $this->log("irspy", "bailing after $nruns main-loop runs");
548 # This shouldn't happen emit anything either:
549 while ((my $i1 = ZOOM::event(\@conn)) > 0) {
550 my $conn = $conn[$i1-1];
551 my $ev = $conn->last_event();
552 my $evstr = ZOOM::event_str($ev);
554 "$conn still has ZOOM-C level task queued: $ev ($evstr)")
555 if $ev != ZOOM::Event::ZEND;
562 # Exactly equivalent to ZOOM::event() except that it is tolerant to
563 # undefined values in the array being passed in.
565 sub __UNUSED_tolerant_ZOOM_event {
569 foreach my $i (0 .. @$connref-1) {
570 my $conn = $connref->[$i];
577 my $res = ZOOM::event(\@conn);
578 return $res if $res <= 0;
579 my $res2 = $map[$res-1] + 1;
580 print STDERR "*** tolerant_ZOOM_event() returns $res->$res2\n";
587 my($tname, @ancestors) = @_;
589 die("$0: test-hierarchy loop detected: " .
590 join(" -> ", @ancestors, $tname))
591 if grep { $_ eq $tname } @ancestors;
593 my $slashSeperatedTname = $tname;
594 $slashSeperatedTname =~ s/::/\//g;
595 my $fullName = "ZOOM/IRSpy/Test/$slashSeperatedTname.pm";
599 $this->log("irspy", "successfully required '$fullName'");
601 $this->log("irspy", "couldn't require '$fullName': $@");
602 $this->log("warn", "can't load test '$tname': skipping",
603 $@ =~ /^Can.t locate/ ? () : " ($@)");
607 $this->log("irspy", "adding test '$tname'");
609 foreach my $subtname ("ZOOM::IRSpy::Test::$tname"->subtests($this)) {
610 my $subtest = $this->_gather_tests($subtname, @ancestors, $tname);
611 push @subnodes, $subtest if defined $subtest;
614 return new ZOOM::IRSpy::Node($tname, @subnodes);
618 # These next three should arguably be Node methods
621 my($address, $omit_child) = @_;
625 my $maybe = $address eq "" ? "0" : "$address:0";
626 return $maybe if $this->{tree}->select($maybe);
629 # The top-level node has no successor or parent
630 return undef if $address eq "";
632 # Try next sibling child
633 my @components = split /:/, $address;
634 my $last = pop @components;
635 my $maybe = join(":", @components, $last+1);
636 return $maybe if $this->{tree}->select($maybe);
638 # This node is exhausted: try the parent's successor
639 return $this->_next_test(join(":", @components), 1)
643 sub _last_sibling_test {
648 if !defined $this->_next_sibling_test($address);
652 my $maybe = $this->_next_sibling_test($address);
653 last if !defined $maybe;
656 $this->log("irspy", "skipping $nskipped tests to '$address'");
659 return ($address, $nskipped);
663 sub _next_sibling_test {
667 my @components = split /:/, $address;
668 my $last = pop @components;
669 my $maybe = join(":", @components, $last+1);
670 return $maybe if $this->{tree}->select($maybe);
680 ZOOM::IRSpy::Maintenance.
682 The ZOOM-Perl module,
683 http://search.cpan.org/~mirk/Net-Z3950-ZOOM/
686 http://indexdata.com/zebra/
690 Mike Taylor, E<lt>mike@indexdata.comE<gt>
692 =head1 COPYRIGHT AND LICENSE
694 Copyright (C) 2006 by Index Data ApS.
696 This library is free software; you can redistribute it and/or modify
697 it under the same terms as Perl itself, either Perl version 5.8.7 or,
698 at your option, any later version of Perl 5 you may have available.